Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

SculptForge 0.1.0: open-source digital sculpting

islandmed00b12b7df117
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 00000000..ced1175c
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,8 @@
+BasedOnStyle: LLVM
+IndentWidth: 4
+ColumnLimit: 120
+AllowShortFunctionsOnASingleLine: All
+AllowShortIfStatementsOnASingleLine: WithoutElse
+AccessModifierOffset: -4
+PointerAlignment: Left
+NamespaceIndentation: None
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 00000000..59cf4399
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,46 @@
+name: Bug report
+description: Something doesn't work as expected
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: Thanks for taking the time to report a problem! Please search existing issues first.
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened?
+ description: What you did, what you expected, and what happened instead.
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ placeholder: |
+ 1. Open ...
+ 2. Choose the Clay brush ...
+ 3. ...
+ - type: input
+ id: version
+ attributes:
+ label: SculptForge version
+ description: Help → About, or the release you downloaded.
+ validations:
+ required: true
+ - type: dropdown
+ id: os
+ attributes:
+ label: Operating system
+ options: [Windows, macOS, Ubuntu / Debian, Fedora / RHEL, Arch Linux, Other Linux]
+ validations:
+ required: true
+ - type: textarea
+ id: gpu
+ attributes:
+ label: GPU and driver (for display or performance problems)
+ description: The first lines printed in the terminal show the OpenGL version and renderer.
+ - type: textarea
+ id: files
+ attributes:
+ label: Files or screenshots
+ description: Drag a screenshot or a small model file here if it helps. Don't attach API keys.
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 00000000..59f642c1
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Questions and ideas
+ url: https://github.com/islandmed/SculptForge/discussions
+ about: Ask for help, share sculpts and brushes, discuss ideas.
+ - name: Security vulnerability
+ url: https://github.com/islandmed/SculptForge/security/advisories/new
+ about: Please report security problems privately.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 00000000..45bca0fd
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,20 @@
+name: Feature request
+description: Suggest a brush, tool, workflow or integration
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: What are you trying to do?
+ description: Describe the artistic or pipeline problem, not just the solution.
+ validations:
+ required: true
+ - type: textarea
+ id: idea
+ attributes:
+ label: How would you like it to work?
+ - type: textarea
+ id: other
+ attributes:
+ label: How do other tools handle it?
+ description: ZBrush, Blender, Nomad, Mudbox... Screenshots and links welcome.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..95206e00
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,12 @@
+## What does this change?
+
+## How was it tested?
+
+- [ ] `ctest` passes locally
+- [ ] Tried in the app (for UI or sculpting changes)
+
+## Checklist
+
+- [ ] I wrote this code myself (no code copied from closed-source software; see CONTRIBUTING.md)
+- [ ] I agree to license my contribution under GPL-3.0-or-later
+- [ ] Docs / CHANGELOG updated if users will notice the change
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 00000000..3a626c3a
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,6 @@
+version: 2
+updates:
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: monthly
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..c9182ed7
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,42 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ name: ${{ matrix.name }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { name: Linux x86_64, os: ubuntu-24.04 }
+ - { name: Linux ARM64, os: ubuntu-24.04-arm }
+ - { name: macOS, os: macos-14 }
+ - { name: Windows, os: windows-2022 }
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install Linux dependencies
+ if: runner.os == 'Linux'
+ run: sudo ./packaging/linux/install-build-deps.sh
+
+ - name: Configure
+ run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DSCULPTFORGE_USE_SYSTEM_SDL=OFF
+
+ - name: Build
+ run: cmake --build build --config Release --parallel
+
+ - name: Test
+ run: ctest --test-dir build -C Release --output-on-failure
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
new file mode 100644
index 00000000..5c04d4a1
--- /dev/null
+++ b/.github/workflows/pages.yml
@@ -0,0 +1,31 @@
+name: Website
+
+on:
+ push:
+ branches: [main]
+ paths: ['website/**', '.github/workflows/pages.yml']
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+concurrency:
+ group: pages
+ cancel-in-progress: true
+
+jobs:
+ deploy:
+ runs-on: ubuntu-24.04
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/configure-pages@v5
+ - uses: actions/upload-pages-artifact@v3
+ with:
+ path: website
+ - id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..2b31cf54
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,143 @@
+name: Release
+
+on:
+ push:
+ tags: ['v*']
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: Existing tag to (re)build, e.g. v0.1.0
+ required: true
+
+permissions:
+ contents: write
+
+env:
+ TAG: ${{ github.event.inputs.tag || github.ref_name }}
+
+jobs:
+ linux:
+ name: Linux ${{ matrix.arch }} (.deb, AppImage, .tar.gz)
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { arch: x86_64, os: ubuntu-22.04, ld: x86_64 }
+ - { arch: arm64, os: ubuntu-22.04-arm, ld: aarch64 }
+ steps:
+ - uses: actions/checkout@v4
+ with: { ref: '${{ env.TAG }}' }
+ - run: sudo ./packaging/linux/install-build-deps.sh
+ - name: Build and test
+ run: |
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DSCULPTFORGE_USE_SYSTEM_SDL=OFF
+ cmake --build build --parallel
+ ctest --test-dir build --output-on-failure
+ - name: .deb and .tar.gz
+ run: cd build && cpack -G "DEB;TGZ"
+ - name: AppImage
+ run: |
+ DESTDIR=$PWD/AppDir cmake --install build
+ curl -fsSLo linuxdeploy https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-${{ matrix.ld }}.AppImage
+ chmod +x linuxdeploy
+ VERSION=${TAG#v} ./linuxdeploy --appimage-extract-and-run --appdir AppDir \
+ --desktop-file AppDir/usr/share/applications/org.sculptforge.SculptForge.desktop \
+ --icon-file assets/branding/sculptforge-256.png --icon-filename org.sculptforge.SculptForge \
+ --output appimage
+ mv SculptForge-*.AppImage build/SculptForge-${TAG#v}-linux-${{ matrix.arch }}.AppImage
+ - uses: actions/upload-artifact@v4
+ with:
+ name: linux-${{ matrix.arch }}
+ path: |
+ build/*.deb
+ build/*.tar.gz
+ build/*.AppImage
+
+ rpm:
+ name: RPM ${{ matrix.arch }} (Fedora, RHEL 9+)
+ runs-on: ${{ matrix.os }}
+ container: almalinux:9
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { arch: x86_64, os: ubuntu-24.04 }
+ - { arch: arm64, os: ubuntu-24.04-arm }
+ steps:
+ - run: dnf -y install git
+ - uses: actions/checkout@v4
+ with: { ref: '${{ env.TAG }}' }
+ - run: ./packaging/linux/install-build-deps.sh
+ - name: Build, test and package
+ run: |
+ source /opt/rh/gcc-toolset-13/enable
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DSCULPTFORGE_USE_SYSTEM_SDL=OFF
+ cmake --build build --parallel
+ ctest --test-dir build --output-on-failure
+ cd build && cpack -G RPM
+ - uses: actions/upload-artifact@v4
+ with:
+ name: rpm-${{ matrix.arch }}
+ path: build/*.rpm
+
+ macos:
+ name: macOS (universal .dmg)
+ runs-on: macos-14
+ steps:
+ - uses: actions/checkout@v4
+ with: { ref: '${{ env.TAG }}' }
+ - name: Build and test
+ run: |
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DSCULPTFORGE_USE_SYSTEM_SDL=OFF \
+ -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0
+ cmake --build build --parallel
+ ctest --test-dir build --output-on-failure
+ - name: Package (signed ad-hoc inside CPack, see cmake/MacSign.cmake)
+ run: cd build && cpack -G DragNDrop
+ - uses: actions/upload-artifact@v4
+ with:
+ name: macos
+ path: build/*.dmg
+
+ windows:
+ name: Windows x64 (installer, .zip)
+ runs-on: windows-2022
+ steps:
+ - uses: actions/checkout@v4
+ with: { ref: '${{ env.TAG }}' }
+ - name: Build and test
+ run: |
+ cmake -S . -B build -DSCULPTFORGE_USE_SYSTEM_SDL=OFF
+ cmake --build build --config Release --parallel
+ ctest --test-dir build -C Release --output-on-failure
+ - name: Package
+ run: cd build && cpack -C Release -G "NSIS;ZIP"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: windows
+ path: |
+ build/*.exe
+ build/*.zip
+
+ publish:
+ name: Publish GitHub Release
+ needs: [linux, rpm, macos, windows]
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ with: { ref: '${{ env.TAG }}' }
+ - uses: actions/download-artifact@v4
+ with: { path: dist, merge-multiple: true }
+ - name: Checksums
+ run: cd dist && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
+ - name: Release notes from CHANGELOG
+ run: |
+ awk "/^## \[${TAG#v}\]/{flag=1;next} /^## \[/{flag=0} flag" CHANGELOG.md > notes.md
+ cat packaging/release-notes-footer.md >> notes.md
+ - name: Create or update the release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" --title "SculptForge ${TAG#v}" --notes-file notes.md
+ gh release upload "$TAG" dist/* --clobber
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..adc5f81b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+build/
+build-*/
+out/
+.cache/
+.vscode/
+.idea/
+*.swp
+compile_commands.json
+imgui.ini
+.DS_Store
+*.user
+Testing/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 00000000..173e014d
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,35 @@
+# Changelog
+
+All notable changes to SculptForge are listed here. The format follows
+[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
+[Semantic Versioning](https://semver.org/).
+
+## [0.1.0] - 2026-10-20
+
+First public release.
+
+### Sculpting
+- Brushes: Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch; X/Y/Z symmetry; tablet pressure;
+ ZBrush-style modifiers and navigation.
+- BVH-accelerated picking with incremental refit; memory-budgeted unlimited undo.
+- Loop subdivision, voxel remesh (DynaMesh-style), quadric decimation.
+- Sculpt layers (blend shapes) with live weights and playback.
+
+### AI (optional, bring your own)
+- Brush Lab: describe a brush, get a procedural brush recipe; Anthropic or any OpenAI-compatible endpoint,
+ including local models through Ollama / LM Studio.
+- Generate 3D from an image or from text: free via Hugging Face Spaces (Hunyuan3D, TRELLIS.2, Stable Fast 3D),
+ or paid via fal.ai / Meshy, or your own generator command; results are remeshed for sculpting.
+- Offline image tools: silhouette blockout, relief, stamp-from-view.
+
+### Pipelines and formats
+- FBX export (binary 7.4, LOD groups, blend shapes) and import; glTF/GLB (morph targets); OpenUSD USDA/USDZ
+ (UsdSkel blend shapes, UsdPreviewSurface); OBJ; PLY.
+- Gaussian splats: PLY, .splat, glTF `KHR_gaussian_splatting`, OpenUSD `ParticleField3DGaussianSplat`; splat
+ rendering; splats to mesh; sculpt to splats.
+- Game-ready presets: one-click LOD chains; Unreal Engine preset and **Send to Unreal** over Python remote
+ execution (same machine or local network).
+- `sculptforge-cli` for scripting and pipelines, with an MCP server (`--mcp`) for AI agents.
+- Headless thumbnail/turntable rendering and scripted demo recording.
+
+[0.1.0]: https://github.com/islandmed/SculptForge/releases/tag/v0.1.0
diff --git a/CITATION.cff b/CITATION.cff
new file mode 100644
index 00000000..9a6820ac
--- /dev/null
+++ b/CITATION.cff
@@ -0,0 +1,18 @@
+cff-version: 1.2.0
+message: "If you use SculptForge in your work, please cite it as below."
+title: "SculptForge"
+abstract: "Free and open-source digital sculpting for Linux, macOS and Windows, with game-engine pipelines and bring-your-own AI."
+type: software
+authors:
+ - name: "The SculptForge contributors"
+license: GPL-3.0-or-later
+repository-code: "https://github.com/islandmed/SculptForge"
+url: "https://islandmed.github.io/SculptForge/"
+version: 0.1.0
+date-released: 2026-10-20
+keywords:
+ - sculpting
+ - 3d
+ - game-development
+ - gaussian-splatting
+ - openusd
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 00000000..75d59025
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,234 @@
+cmake_minimum_required(VERSION 3.24)
+project(SculptForge VERSION 0.1.0 LANGUAGES C CXX)
+include(GNUInstallDirs)
+
+set(CMAKE_CXX_STANDARD 20)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
+endif()
+
+option(SCULPTFORGE_BUILD_APP "Build the SculptForge desktop application" ON)
+option(SCULPTFORGE_BUILD_TESTS "Build unit tests" ON)
+option(SCULPTFORGE_USE_SYSTEM_SDL "Use an installed SDL3 if one is found" ON)
+
+include(cmake/Dependencies.cmake)
+
+# --- Core library: geometry, sculpting, undo, commands, file IO (no GPU/UI) ---
+add_library(sculptforge_core STATIC
+ src/core/Mesh.cpp
+ src/core/BVH.cpp
+ src/core/Sculpt.cpp
+ src/core/Undo.cpp
+ src/core/Primitives.cpp
+ src/core/Document.cpp
+ src/core/Commands.cpp
+ src/core/Decimate.cpp
+ src/core/Script.cpp
+ src/core/Json.cpp
+ src/core/BrushRecipe.cpp
+ src/core/Image.cpp
+ src/core/ImageTo3D.cpp
+ src/core/Splats.cpp
+ src/core/Voxel.cpp
+ src/core/EnginePresets.cpp
+ src/io/ObjIO.cpp
+ src/io/FbxIO.cpp
+ third_party/ufbx/ufbx.c
+ src/io/GltfIO.cpp
+ src/io/PlyIO.cpp
+ src/io/UsdIO.cpp
+ src/io/Zip.cpp
+)
+target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx)
+# Third-party C code: compile quietly.
+if(MSVC)
+ set_source_files_properties(third_party/ufbx/ufbx.c PROPERTIES COMPILE_OPTIONS "/w")
+else()
+ set_source_files_properties(third_party/ufbx/ufbx.c PROPERTIES COMPILE_OPTIONS "-w")
+endif()
+target_link_libraries(sculptforge_core PUBLIC glm::glm)
+target_compile_definitions(sculptforge_core PUBLIC GLM_FORCE_XYZW_ONLY)
+if(MSVC)
+ target_compile_options(sculptforge_core PRIVATE /W4 /utf-8 /permissive-)
+ target_compile_definitions(sculptforge_core PUBLIC NOMINMAX _USE_MATH_DEFINES)
+else()
+ target_compile_options(sculptforge_core PRIVATE -Wall -Wextra -Wno-unused-parameter)
+endif()
+
+# --- Bring-your-own-AI (brush assistant). HTTPS via WinHTTP or libcurl. ---
+add_library(sculptforge_ai STATIC src/ai/Http.cpp src/ai/BrushAssistant.cpp src/ai/Generator3D.cpp
+ src/ai/ImageTo3DService.cpp src/ai/GradioClient.cpp src/ai/AiCommands.cpp src/link/Socket.cpp src/link/UnrealLink.cpp)
+target_link_libraries(sculptforge_ai PUBLIC sculptforge_core)
+if(WIN32)
+ target_link_libraries(sculptforge_ai PRIVATE winhttp ws2_32)
+else()
+ find_package(CURL QUIET)
+ if(CURL_FOUND)
+ target_link_libraries(sculptforge_ai PRIVATE CURL::libcurl)
+ target_compile_definitions(sculptforge_ai PRIVATE SF_HAVE_CURL)
+ else()
+ message(WARNING "libcurl not found: AI features will report that HTTP is unavailable")
+ endif()
+endif()
+if(MSVC)
+ target_compile_options(sculptforge_ai PRIVATE /W4 /utf-8 /permissive-)
+else()
+ target_compile_options(sculptforge_ai PRIVATE -Wall -Wextra -Wno-unused-parameter)
+endif()
+
+# --- Headless command-line tool (pipelines, build farms, AI agents) ---
+add_executable(sculptforge-cli src/cli/main.cpp src/cli/McpServer.cpp)
+target_link_libraries(sculptforge-cli PRIVATE sculptforge_core sculptforge_ai)
+
+# --- Desktop application ---
+if(SCULPTFORGE_BUILD_APP)
+ include(cmake/EmbedFile.cmake)
+ embed_files(${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFonts.cpp sf::assets
+ fontRegular ${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts/Inter-Regular.ttf
+ fontSemiBold ${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts/Inter-SemiBold.ttf
+ appIcon ${CMAKE_CURRENT_SOURCE_DIR}/assets/branding/sculptforge-256.png)
+ add_executable(sculptforge
+ ${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFonts.cpp
+ src/app/main.cpp
+ src/app/App.cpp
+ src/app/Demo.cpp
+ src/render/GL.cpp
+ src/render/Camera.cpp
+ src/render/Renderer.cpp
+ )
+ target_link_libraries(sculptforge PRIVATE sculptforge_core sculptforge_ai imgui SDL3::SDL3)
+ target_compile_definitions(sculptforge PRIVATE SCULPTFORGE_VERSION="${PROJECT_VERSION}")
+ if(MSVC)
+ target_compile_options(sculptforge PRIVATE /W4 /utf-8 /permissive-)
+ else()
+ target_compile_options(sculptforge PRIVATE -Wall -Wextra -Wno-unused-parameter)
+ endif()
+ if(WIN32)
+ set_target_properties(sculptforge PROPERTIES WIN32_EXECUTABLE $<CONFIG:Release,MinSizeRel>)
+ set(ICON_PATH "${CMAKE_CURRENT_SOURCE_DIR}/assets/branding/sculptforge.ico")
+ string(REPLACE "/" "\\\\" ICON_PATH "${ICON_PATH}")
+ configure_file(packaging/windows/sculptforge.rc ${CMAKE_CURRENT_BINARY_DIR}/sculptforge.rc @ONLY)
+ target_sources(sculptforge PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/sculptforge.rc)
+ endif()
+ if(APPLE)
+ # App icon: build an .icns from the 1024 px PNG with Apple's own tools.
+ set(ICONSET ${CMAKE_CURRENT_BINARY_DIR}/SculptForge.iconset)
+ set(ICNS ${CMAKE_CURRENT_BINARY_DIR}/SculptForge.icns)
+ set(ICON_SRC ${CMAKE_CURRENT_SOURCE_DIR}/assets/branding/sculptforge-1024.png)
+ set(ICON_COMMANDS COMMAND ${CMAKE_COMMAND} -E make_directory ${ICONSET})
+ foreach(size 16 32 128 256 512)
+ math(EXPR size2 "${size} * 2")
+ list(APPEND ICON_COMMANDS
+ COMMAND sips -z ${size} ${size} ${ICON_SRC} --out ${ICONSET}/icon_${size}x${size}.png
+ COMMAND sips -z ${size2} ${size2} ${ICON_SRC} --out ${ICONSET}/icon_${size}x${size}@2x.png)
+ endforeach()
+ add_custom_command(OUTPUT ${ICNS} ${ICON_COMMANDS}
+ COMMAND iconutil -c icns ${ICONSET} -o ${ICNS}
+ DEPENDS ${ICON_SRC} VERBATIM)
+ target_sources(sculptforge PRIVATE ${ICNS})
+ set_source_files_properties(${ICNS} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
+ set_target_properties(sculptforge PROPERTIES
+ MACOSX_BUNDLE TRUE
+ OUTPUT_NAME "SculptForge"
+ MACOSX_BUNDLE_BUNDLE_NAME "SculptForge"
+ MACOSX_BUNDLE_GUI_IDENTIFIER "org.sculptforge.SculptForge"
+ MACOSX_BUNDLE_ICON_FILE "SculptForge.icns"
+ MACOSX_BUNDLE_COPYRIGHT "Copyright (C) 2026 The SculptForge contributors. GPL-3.0-or-later."
+ MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_VERSION}"
+ MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}")
+ install(TARGETS sculptforge BUNDLE DESTINATION .)
+ # The command-line tool travels inside the app bundle.
+ install(TARGETS sculptforge-cli RUNTIME DESTINATION SculptForge.app/Contents/MacOS)
+ else()
+ install(TARGETS sculptforge RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+ endif()
+endif()
+
+# --- Install layout and packages ---
+if(NOT APPLE)
+ install(TARGETS sculptforge-cli RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+endif()
+if(UNIX AND NOT APPLE)
+ install(FILES packaging/linux/org.sculptforge.SculptForge.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
+ install(FILES packaging/linux/org.sculptforge.SculptForge.metainfo.xml DESTINATION ${CMAKE_INSTALL_DATADIR}/metainfo)
+ install(FILES assets/branding/sculptforge-icon.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps
+ RENAME org.sculptforge.SculptForge.svg)
+ install(FILES assets/branding/sculptforge-256.png DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/256x256/apps
+ RENAME org.sculptforge.SculptForge.png)
+ install(FILES assets/branding/sculptforge-512.png DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/512x512/apps
+ RENAME org.sculptforge.SculptForge.png)
+endif()
+if(APPLE)
+ set(SF_DOC_DIR .)
+elseif(WIN32)
+ set(SF_DOC_DIR doc)
+else()
+ set(SF_DOC_DIR ${CMAKE_INSTALL_DOCDIR})
+endif()
+install(FILES LICENSE THIRD_PARTY_NOTICES.md README.md CHANGELOG.md DESTINATION ${SF_DOC_DIR})
+install(FILES docs/ai-services.md docs/unreal.md docs/generators.md DESTINATION ${SF_DOC_DIR}/docs)
+
+set(CPACK_PACKAGE_NAME "sculptforge")
+set(CPACK_PACKAGE_VENDOR "The SculptForge contributors")
+set(CPACK_PACKAGE_CONTACT "https://github.com/islandmed/SculptForge/issues")
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Free and open-source digital sculpting with game-engine pipelines")
+set(CPACK_PACKAGE_HOMEPAGE_URL "https://islandmed.github.io/SculptForge/")
+set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
+set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_CURRENT_SOURCE_DIR}/LICENSE)
+set(CPACK_PACKAGE_INSTALL_DIRECTORY "SculptForge")
+set(CPACK_PACKAGE_EXECUTABLES "sculptforge" "SculptForge")
+string(TOLOWER "${CMAKE_SYSTEM_NAME}" SF_OS)
+set(SF_ARCH ${CMAKE_SYSTEM_PROCESSOR})
+if(SF_ARCH MATCHES "^(AMD64|amd64|x86_64)$")
+ set(SF_ARCH x86_64)
+elseif(SF_ARCH MATCHES "^(arm64|ARM64|aarch64)$")
+ set(SF_ARCH arm64)
+endif()
+if(APPLE AND CMAKE_OSX_ARCHITECTURES MATCHES ";")
+ set(SF_ARCH universal)
+endif()
+set(CPACK_PACKAGE_FILE_NAME "SculptForge-${PROJECT_VERSION}-${SF_OS}-${SF_ARCH}")
+set(CPACK_STRIP_FILES ON)
+# Debian / Ubuntu
+set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
+set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
+set(CPACK_DEBIAN_PACKAGE_SECTION graphics)
+set(CPACK_DEBIAN_PACKAGE_MAINTAINER "The SculptForge contributors <https://github.com/islandmed/SculptForge>")
+# Fedora / RHEL
+set(CPACK_RPM_FILE_NAME RPM-DEFAULT)
+set(CPACK_RPM_PACKAGE_LICENSE "GPL-3.0-or-later")
+set(CPACK_RPM_PACKAGE_GROUP "Applications/Multimedia")
+set(CPACK_RPM_PACKAGE_URL "https://islandmed.github.io/SculptForge/")
+set(CPACK_RPM_PACKAGE_AUTOREQ ON)
+# Windows installer
+set(CPACK_NSIS_DISPLAY_NAME "SculptForge")
+set(CPACK_NSIS_PACKAGE_NAME "SculptForge")
+set(CPACK_NSIS_MUI_ICON ${CMAKE_CURRENT_SOURCE_DIR}/assets/branding/sculptforge.ico)
+set(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\\\sculptforge.exe")
+set(CPACK_NSIS_URL_INFO_ABOUT "https://islandmed.github.io/SculptForge/")
+set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
+set(CPACK_NSIS_CREATE_ICONS_EXTRA "CreateShortCut '$SMPROGRAMS\\\\$STARTMENU_FOLDER\\\\SculptForge.lnk' '$INSTDIR\\\\bin\\\\sculptforge.exe'")
+# macOS disk image
+set(CPACK_DMG_VOLUME_NAME "SculptForge")
+if(APPLE)
+ set(CPACK_PRE_BUILD_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/cmake/MacSign.cmake)
+endif()
+if(WIN32)
+ set(CPACK_GENERATOR "NSIS;ZIP")
+elseif(APPLE)
+ set(CPACK_GENERATOR "DragNDrop")
+else()
+ set(CPACK_GENERATOR "DEB;RPM;TGZ")
+endif()
+include(CPack)
+
+# --- Tests ---
+if(SCULPTFORGE_BUILD_TESTS)
+ enable_testing()
+ add_executable(sculptforge_tests tests/test_main.cpp src/cli/McpServer.cpp)
+ target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai)
+ add_test(NAME sculptforge_tests COMMAND sculptforge_tests)
+endif()
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 00000000..7e576c36
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,83 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at a private report to the maintainers: use **Report a vulnerability → Private reporting** on the GitHub repository (it reaches only the maintainers), or send a direct message to [@islandmed](https://github.com/islandmed). All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of actions.
+
+**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..34d9d017
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,50 @@
+# Contributing to SculptForge
+
+Thanks for your interest! SculptForge is GPL-3.0-or-later; by contributing you
+agree your work is licensed under the same terms.
+
+## Ground rules
+
+- **Clean-room only.** Do not contribute code, shaders, brushes, alphas, icons or
+ other assets copied or decompiled from ZBrush or any other proprietary
+ product. Re-implementing well-known published techniques is fine.
+- Keep `src/core` free of UI and GPU dependencies so it stays testable and
+ scriptable.
+- New editor operations should be registered as commands in
+ `src/core/Commands.cpp` so they are available to the UI, scripting and the
+ AI assistant alike.
+- Add or update tests in `tests/` for core behaviour changes.
+
+## Workflow
+
+1. Build and run tests (see README).
+2. Keep changes focused; one feature or fix per pull request.
+3. Each source file starts with the SPDX license header.
+4. CI must pass on Linux, macOS and Windows.
+
+## Code style
+
+C++20, 4-space indentation, `camelCase` functions, `PascalCase` types,
+trailing underscore for private members. A `.clang-format` is provided.
+
+## Building, testing and packaging
+
+See [README.md#building](README.md#building). On Linux, `packaging/linux/install-build-deps.sh` installs the
+build dependencies. `ctest` runs the unit tests; `cpack` in the build folder makes the platform's packages.
+Releases are built by `.github/workflows/release.yml` when a `v*` tag is pushed.
+
+## Demo videos
+
+The website's videos are real recordings made by the app itself:
+
+```sh
+./build/sculptforge --demo sculpt --record website/media/sculpt.mp4 --size 1920x1080 --demo-output creature.glb
+./build/sculptforge --demo game-ready --record website/media/game-ready.mp4 --size 1920x1080 --demo-asset creature.glb
+```
+
+Demos live in `src/app/Demo.cpp`; they drive the real UI (buttons are found by their labels).
+
+## Community
+
+Everyone taking part is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md). Report security issues
+privately, as described in [SECURITY.md](SECURITY.md).
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..09f1a748
--- /dev/null
+++ b/README.md
@@ -0,0 +1,224 @@
+<p align="center">
+ <img src="assets/branding/sculptforge-256.png" width="112" alt="SculptForge logo">
+</p>
+
+<h1 align="center">SculptForge</h1>
+
+<p align="center">
+ <strong>Free, open-source digital sculpting for Linux, macOS and Windows,<br>
+ with game-ready pipelines and bring-your-own AI.</strong>
+</p>
+
+<p align="center">
+ <a href="https://github.com/islandmed/SculptForge/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/islandmed/SculptForge/actions/workflows/ci.yml/badge.svg"></a>
+ <a href="https://github.com/islandmed/SculptForge/releases/latest"><img alt="Latest release" src="https://img.shields.io/github/v/release/islandmed/SculptForge?color=f28c3c"></a>
+ <a href="LICENSE"><img alt="License: GPL-3.0-or-later" src="https://img.shields.io/badge/license-GPL--3.0--or--later-blue"></a>
+ <img alt="Platforms" src="https://img.shields.io/badge/platforms-Windows%20%7C%20macOS%20%7C%20Linux-555">
+</p>
+
+<p align="center">
+ <a href="https://islandmed.github.io/SculptForge/"><b>Website & demo videos</b></a> ·
+ <a href="https://github.com/islandmed/SculptForge/releases/latest"><b>Download</b></a> ·
+ <a href="#features">Features</a> ·
+ <a href="#building">Build from source</a> ·
+ <a href="CONTRIBUTING.md">Contribute</a>
+</p>
+
+<p align="center">
+ <a href="https://islandmed.github.io/SculptForge/#demos"><img src="docs/images/sculpt-demo.gif" width="800" alt="Sculpting a creature head with the Move, Clay and Crease brushes and symmetry in SculptForge"></a>
+</p>
+
+SculptForge is a focused sculpting application in the spirit of ZBrush. It starts instantly, works offline,
+and fits into game and animation pipelines: sculpt a character, generate its LODs, sculpt blend shapes, and
+send it straight into Unreal Engine. Optional AI tools design brushes from a description and turn images or
+text into sculptable models, using the model *you* choose. That can be a free one, or one running entirely
+on your own machine.
+
+> **Status: early release (v0.1).** The core sculpting, pipeline and AI features work and are tested on every
+> commit. Multiresolution sculpting, masking, retopology, UVs and texture painting are still on the
+> [roadmap](ROADMAP.md).
+
+## Features
+
+**Sculpting**
+- Standard, Clay, Smooth, Move, Inflate, Crease, Flatten and Pinch brushes; X/Y/Z symmetry; tablet pressure;
+ ZBrush-style modifiers and navigation.
+- Unlimited undo, Loop subdivision, **voxel remesh** (DynaMesh-style) and quadric decimation.
+- **Sculpt layers** that work as blend shapes, with live weights and playback.
+
+**Brush Lab: describe a brush, AI builds it**
+- "Dry cracked mud", "overlapping dragon scales", then "make it sharper". Brushes are recipes (data, never
+ code), with every value exposed as a slider. Share them as `.sfbrush` files.
+- Works with Claude (Anthropic API) or any OpenAI-compatible endpoint, including **local models through
+ Ollama or LM Studio**.
+
+**Generate 3D from an image or text**
+- A sketch, a piece of concept art or a description becomes a full 3D model (limbs, back and all), then gets
+ remeshed so you can sculpt it straight away.
+- **Free** through the official Hugging Face demos of Hunyuan3D 2 / 2.1, TRELLIS.2 and Stable Fast 3D; or
+ paid with your own fal.ai or Meshy key; or plug in any local model.
+ See [AI services & model licences](docs/ai-services.md).
+- Offline tools as well: silhouette blockout, relief, and stamp-from-view.
+
+**Game & animation pipelines**
+- One-click **LOD chains**; blend shapes survive on every level.
+- **Send to Unreal** (Ctrl+U) imports or updates the asset in a running Unreal Editor, on this computer or
+ another one on your network, with no plugin to install. Static meshes come with LODs, skeletal meshes with
+ morph targets. See [docs/unreal.md](docs/unreal.md).
+- **FBX** (binary 7.4, LOD groups, blend shapes), **glTF/GLB** (morph targets), **OpenUSD** USDA/USDZ (UsdSkel
+ blend shapes), OBJ and PLY. Exports are checked with the Khronos glTF validator and OpenUSD's `usdchecker`.
+
+**Gaussian splats**
+- Open phone captures (Polycam, Luma, Postshot, Scaniverse and others) as a sculpting reference, convert them
+ into watertight meshes, or turn a sculpt into splats.
+- Supports PLY (up to SH degree 3), `.splat`, glTF **`KHR_gaussian_splatting`** and OpenUSD
+ **`ParticleField3DGaussianSplat`**.
+
+**Automation**
+- `sculptforge-cli` runs every operation headless, for build farms and pipelines.
+- A built-in **MCP server** (`sculptforge-cli --mcp`) lets Claude Code, Claude Desktop or any MCP client
+ sculpt, convert and export.
+- Headless thumbnail and turntable rendering, plus a scripted demo recorder (`--demo … --record`).
+
+<table>
+ <tr>
+ <td><img src="docs/images/screenshot-brush-lab.jpg" alt="Brush Lab: an AI-designed cracked-mud brush carved into a plane"></td>
+ <td><img src="docs/images/screenshot-game-ready.jpg" alt="LOD chain preview with wireframe and the Game Ready panel"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>Brush Lab: "dry cracked mud", designed by a local model</sub></td>
+ <td align="center"><sub>One-click LODs, blend shapes and Send to Unreal</sub></td>
+ </tr>
+</table>
+
+## Install
+
+Download the latest build for your system from the
+**[releases page](https://github.com/islandmed/SculptForge/releases/latest)**:
+
+| System | Package |
+|---|---|
+| Windows 10/11 | Installer (`.exe`) or portable `.zip` |
+| macOS 11+ (Apple Silicon & Intel) | `.dmg` |
+| Ubuntu / Debian / Mint / Pop!_OS | `.deb` (x86_64, ARM64): `sudo apt install ./sculptforge_*.deb` |
+| Fedora / RHEL 9+ / Rocky / Alma | `.rpm` (x86_64, ARM64): `sudo dnf install ./sculptforge-*.rpm` |
+| Any Linux | `.AppImage` (x86_64, ARM64) |
+| Arch Linux | AUR: `yay -S sculptforge` ([PKGBUILD](packaging/arch/PKGBUILD)) |
+
+The builds aren't code-signed yet. On **macOS**, right-click the app and choose **Open** the first time. On
+**Windows**, if SmartScreen appears, choose **More info → Run anyway**.
+
+## Building
+
+Requirements: CMake 3.24+ and a C++20 compiler (GCC 11+, Clang 14+, Xcode 15+ or Visual Studio 2022).
+Dear ImGui, GLM and (if it isn't installed already) SDL3 are fetched automatically. AI features use libcurl
+on Linux and macOS, and the built-in WinHTTP on Windows.
+
+```sh
+# Linux only: install compilers and X11/Wayland/GL/curl headers (Debian/Ubuntu or Fedora/RHEL)
+sudo ./packaging/linux/install-build-deps.sh
+
+cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
+cmake --build build --parallel
+ctest --test-dir build --output-on-failure
+./build/sculptforge # Windows: build\Release\sculptforge.exe · macOS: open build/SculptForge.app
+```
+
+`cpack` in the build folder makes the platform's packages (`.deb`/`.rpm`/`.tar.gz`, `.dmg`, or installer and
+`.zip`).
+
+## Pipelines & automation
+
+```sh
+# LOD chain for a game asset
+sculptforge-cli -c 'open path=rock.obj; export_lods path=out/rock.glb levels=4 ratio=0.5'
+
+# Concept art or a description -> sculptable 3D model (free, via Hugging Face)
+sculptforge-cli -c 'image_to_3d path=hero.png; export_usd path=hero.usdz'
+sculptforge-cli -c 'text_to_3d prompt="a stylised dragon head"; export_glb path=dragon.glb'
+
+# Sculpt -> Unreal (static mesh with 4 LODs, 2 m tall)
+sculptforge-cli -c 'open path=statue.obj; unreal_send destination=/Game/Props height_cm=200 lods=4'
+
+# Phone capture -> watertight base mesh
+sculptforge-cli -c 'open path=scan.ply; splat_transform rotate_x=180 fit=true; splat_clean; splat_to_mesh resolution=256; export_glb path=base.glb'
+
+# Design a brush with a local model and save it for the team
+sculptforge-cli -c 'brush_ai prompt="weathered stone edges" provider=openai-compatible model=qwen3:4b-instruct; brush_save path=stone.sfbrush'
+
+# Review-sheet turntable (8 frames)
+sculptforge model.glb --render review/model.png --turntable 8 --size 1024x1024
+```
+
+Run `sculptforge-cli --list` for every command.
+
+### Let an AI agent sculpt (MCP)
+
+```sh
+claude mcp add sculptforge -- /path/to/sculptforge-cli --mcp # Claude Code
+```
+
+For Claude Desktop or other MCP clients, add a stdio server whose command is `sculptforge-cli` with the
+argument `--mcp`. The agent gets every command as a tool and works on one live scene per session.
+
+## Controls
+
+| Action | Input |
+|---|---|
+| Sculpt | Left-drag on the model |
+| Subtract / invert | Hold **Alt** |
+| Smooth | Hold **Shift** |
+| Rotate | Left-drag background, or right-drag |
+| Pan | Alt + left-drag background, or middle-drag |
+| Zoom | Mouse wheel, or Ctrl + left-drag background |
+| Brush size | `[` / `]` |
+| Select brush | `1`–`8` |
+| Toggle X symmetry / wireframe | `X` / `W` |
+| Frame model | `F` |
+| Subdivide | Ctrl+D |
+| Undo / Redo | Ctrl+Z / Ctrl+Shift+Z |
+| Open / Save | Ctrl+O / Ctrl+S |
+| Export GLB | Ctrl+E |
+| Send to Unreal | Ctrl+U |
+
+## Project layout
+
+```
+src/core Mesh, BVH, brushes & recipes, layers, undo, subdivision, decimation,
+ voxel remesh, Gaussian splats, image-to-3D, command registry (no GPU/UI)
+src/io File formats: OBJ, FBX, glTF/GLB (+ KHR_gaussian_splatting), PLY, .splat, USDA/USDZ
+src/ai Bring-your-own AI: HTTPS client, brush assistant, image/text-to-3D services, Gradio client
+src/link Live links to game engines (Unreal Python remote execution)
+src/cli sculptforge-cli and its MCP server
+src/render OpenGL 3.3 renderer, splat renderer, offscreen capture
+src/app SDL3 + Dear ImGui application, scripted demo recorder
+packaging Linux desktop/AppStream files, Windows resources, Arch PKGBUILD
+website Project website (GitHub Pages)
+tests Unit tests
+```
+
+## Privacy
+
+SculptForge has no telemetry, no account and no servers of its own. AI features are optional and talk
+directly to the service you choose. See [docs/ai-services.md](docs/ai-services.md) for exactly what is sent
+where, and for the licences of the AI models.
+
+## Contributing
+
+Contributions are welcome: bug reports, brushes, docs and code. Read [CONTRIBUTING.md](CONTRIBUTING.md)
+and the [Code of Conduct](CODE_OF_CONDUCT.md). Please report security issues privately (see
+[SECURITY.md](SECURITY.md)).
+
+## License
+
+Copyright © 2026 The SculptForge contributors.
+
+SculptForge is free software, licensed under the [GNU General Public License v3.0 or later](LICENSE). You own
+everything you make with it; the GPL covers the program, not your models. Third-party components and their
+licences are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+
+<sub>SculptForge is an independent project and is not affiliated with or endorsed by Maxon, Epic Games,
+Autodesk, Pixar, the Khronos Group, Hugging Face, Tencent, Microsoft, Stability AI, Anthropic, fal or Meshy.
+ZBrush is a trademark of Maxon. Unreal and Unreal Engine are trademarks of Epic Games, Inc. FBX is a trademark
+of Autodesk, Inc. glTF is a trademark of the Khronos Group Inc. Other names are trademarks of their respective
+owners.</sub>
diff --git a/ROADMAP.md b/ROADMAP.md
new file mode 100644
index 00000000..ccd2db67
--- /dev/null
+++ b/ROADMAP.md
@@ -0,0 +1,111 @@
+# SculptForge Roadmap
+
+## Why SculptForge? (positioning)
+
+| | ZBrush | Blender (sculpt mode) | Nomad Sculpt | SculptGL | **SculptForge** |
+|---|---|---|---|---|---|
+| Price / license | Paid subscription, closed | Free, GPL | Paid, closed | Free, MIT | **Free, GPL** |
+| Linux | No | Yes | No | Browser | **Yes (native)** |
+| Focus | Sculpting | General 3D suite | Sculpting (mobile-first) | Demo | **Desktop sculpting only** |
+| Very high poly counts | Excellent | Good | Good | Limited | Goal: excellent |
+| ZBrush-style controls | — | Partial (keymap) | Partial | No | **Yes, by default** |
+| Headless / scriptable core | Limited (ZScript) | Python (whole app) | No | No | **Yes (core library + commands)** |
+| AI assistant | Limited | Add-ons only | No | No | **Bring your own AI: brush design today** |
+| Image to 3D | No | Add-ons only | No | No | **Free Hunyuan3D / TRELLIS.2 / SF3D via Hugging Face, paid fal.ai / Meshy, local generators** |
+| Gaussian splats | No | Add-ons only | No | No | **View captures, splat ↔ mesh, PLY / .splat / glTF / USD** |
+| OpenUSD | Export plugin | Yes | No | No | **USDA/USDZ with UsdSkel blend shapes and splat prims** |
+| Unreal Engine | FBX export / GoZ-style bridges | FBX export | No | No | **Send to Unreal (live, no plugin), LODs + morph targets in one FBX** |
+| Agent control (MCP) | No | Add-ons only | No | No | **Built in: `sculptforge-cli --mcp`** |
+| Blend shapes / LODs / GLB | Via export plugins | Yes (general 3D) | Partial | No | **Built in, one click** |
+| Open file formats | Proprietary .ZTL | .blend | Proprietary | OBJ | **OBJ, FBX, glTF, PLY, USD/USDZ** |
+
+Where SculptForge aims to win:
+
+1. **Focus and speed** — a sculpt-only tool that starts instantly and stays responsive at tens of millions of polygons.
+2. **First-class Linux** alongside macOS and Windows.
+3. **Familiar to ZBrush users** — controls work the way they expect.
+4. **Scriptable** — every action is a named command callable from UI, scripts or AI.
+5. **Bring your own AI** — opt-in, provider-agnostic, works fully offline with local models.
+
+Where we deliberately do *not* compete yet: ZRemesher-class automatic
+retopology, a full ZBrush feature list, rendering/animation (use Blender).
+
+## Status key
+
+✅ done · 🚧 in progress · 📋 planned
+
+## Phase 1 — Core sculpting (v0.1)
+
+- ✅ Cross-platform app shell (SDL3, OpenGL 3.3, Dear ImGui)
+- ✅ BVH-accelerated picking and brush queries with incremental refit
+- ✅ Brushes: Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch
+- ✅ Symmetry (X/Y/Z), pen pressure, stroke spacing
+- ✅ Undo/redo (sparse per-stroke + full snapshots for topology changes)
+- ✅ Loop subdivision, sphere/plane primitives
+- ✅ OBJ import/export, native file dialogs, drag & drop
+- ✅ Command registry with LLM tool-schema export
+- 🚧 CI builds and tests on Linux, macOS, Windows (workflow written; verified locally on Linux only)
+
+## Phase 1.5 — Studio pipeline & AI (done)
+
+- ✅ Sculpt layers exported as glTF morph targets (blend shapes), expression preview
+- ✅ Quadric LOD chain with preview; layers preserved on every LOD
+- ✅ glTF/GLB export + import (seam welding, morph targets → layers)
+- ✅ `sculptforge-cli` headless commands, `$variables`, LLM tool-schema export
+- ✅ Headless thumbnail/turntable rendering
+- ✅ Brush Lab: recipe brush engine, procedural patterns, `.sfbrush` files, AI brush design
+ (Anthropic or any OpenAI-compatible/local model)
+- ✅ Image to 3D: sketch inflation, relief, view projection, pluggable generator command
+
+## Phase 1.6 — Open standards & capture (done)
+
+- ✅ AI image-to-3D: free via Hugging Face Spaces (built-in Gradio client: Hunyuan3D 2.1 / 2 / Turbo,
+ TRELLIS.2, Stable Fast 3D), or paid via fal.ai / Meshy; subject framing; auto voxel remesh on import
+- ✅ Voxel remesh (DynaMesh-style): watertight, even surface; merges parts; fixes scans
+- ✅ OpenUSD: USDA/USDZ export (UsdSkel blend shapes, UsdPreviewSurface, splats as
+ `ParticleField3DGaussianSplat`), USDA/USDZ import; validated with OpenUSD 26.08 `usdchecker`
+- ✅ Gaussian splats: PLY (INRIA layout, SH up to degree 3), `.splat`, glTF `KHR_gaussian_splatting`,
+ USD ParticleField; sorted EWA splat rendering; splats → watertight mesh; sculpt → splats
+- ✅ PLY mesh / point cloud import
+- ✅ Unreal Engine: binary FBX 7.4 export (LOD groups, blend shapes), FBX import (ufbx), Unreal preset,
+ Send to Unreal over Python remote execution (same machine or LAN)
+- ✅ MCP server (`sculptforge-cli --mcp`): every command as a tool for Claude Code / Claude Desktop / any MCP client
+
+## Phase 2 — Detail & workflow (v0.2–0.3)
+
+- 📋 Masking (paint, invert, blur, mask-by-cavity) with brushes respecting masks
+- 📋 Multiresolution: subdivision levels you can step up/down while keeping detail
+- 📋 Dynamic topology (local remeshing under the brush)
+- 📋 Alphas / stencils and stroke types (drag-rect, spray, lazy mouse)
+- 📋 More brushes: Clay Buildup, Dam Standard, Snake Hook, Trim, Layer, Nudge
+- 📋 MatCap materials, cavity/AO shading
+- 📋 Quit-with-unsaved-changes prompt, recent files, project file format
+- 📋 Multithreaded brush evaluation, partial GPU uploads per BVH node
+- 📋 Benchmarks: brush latency at 1M / 5M / 20M triangles in CI
+
+## Phase 3 — AI assistant, beyond brushes (v0.4)
+
+- 📋 Chat assistant that drives any SculptForge command (tool calling over the existing registry)
+- 📋 OS keychain storage for API keys
+- 📋 Preview/confirm for destructive AI actions
+- 📋 Viewport screenshot as context (proportion/anatomy feedback)
+- 📋 Text-to-3D through the generator interface
+- 📋 Multi-view image-to-3D (front/side/back) and image-conditioned retopology
+- 📋 Viewport snapshot tool for MCP agents (let the agent see what it sculpted)
+- 📋 Normal/displacement map baking (high → low poly), auto-retopology + UVs
+- 📋 Live link to Unity / Godot / Blender (Unreal done); Unreal: send textures/normal maps, Nanite option
+
+## Phase 4 — Advanced modeling (v0.5+)
+
+- 📋 Boolean merge/subtract on the voxel pipeline; sharper voxel remesh (signed distance instead of occupancy)
+- 📋 Retopology tools and quad remeshing
+- 📋 Multiple subtools/objects, layers
+- 📋 Vertex painting (polypaint), UVs, texture baking (normal/displacement)
+- 📋 STL, binary USD (usdc), SPZ-compressed splats, USD references/payloads
+- 📋 Splat editing: crop box, paint-select, sculpt deforming nearby splats
+
+## Phase 5 — Ecosystem (v1.0)
+
+- 📋 Python scripting & plugin API built on the command registry
+- 📋 Installers: AppImage/Flatpak, signed macOS .dmg, Windows MSI
+- 📋 Documentation site and tutorials
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 00000000..3df227d8
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,27 @@
+# Security policy
+
+## Supported versions
+
+Security fixes go into the latest release and the `main` branch.
+
+## Reporting a vulnerability
+
+Please **don't open a public issue** for security problems.
+
+Report them privately with GitHub's **Security → Report a vulnerability** button on this repository
+(private vulnerability reporting). Only the maintainers can see the report. Please include:
+
+- what an attacker could do and how (steps or a proof-of-concept file)
+- the version or commit, and your operating system
+
+We aim to acknowledge reports within 7 days and to publish a fix and an advisory once a fix is
+available. We're happy to credit you unless you'd rather stay anonymous.
+
+## Scope notes
+
+SculptForge opens files from untrusted sources (OBJ, FBX, glTF, PLY, USD/USDZ, images) and can talk to
+network services you configure (AI providers, Hugging Face Spaces, the Unreal Editor). Crashes or memory
+errors from malformed files, and anything that could leak API keys, are in scope.
+
+API keys you enter are stored in your user settings folder (`ai.json`) with owner-only file permissions.
+They are only ever sent to the service they belong to.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 00000000..720f89d1
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,370 @@
+# Third-party notices
+
+SculptForge is licensed under the GNU General Public License v3.0 or later (see [LICENSE](LICENSE)).
+It includes or links the following third-party software, each under its own license. All of them are
+compatible with the GPL. Their copyright notices and license texts are reproduced below, as their
+licenses require.
+
+| Component | Version | License | Used for |
+|---|---|---|---|
+| [SDL 3](https://libsdl.org) | 3.2.10 (or the system's SDL3) | zlib License | Desktop app: windows, input, OpenGL context. Linked dynamically. |
+| [Dear ImGui](https://github.com/ocornut/imgui) | 1.91.9 | MIT License | Desktop app user interface. |
+| [GLM](https://github.com/g-truc/glm) | 1.0.1 | MIT License (or The Happy Bunny License) | Vector and matrix math. |
+| [stb_image / stb_image_write](https://github.com/nothings/stb) | commit 013ac3be | MIT License or Public Domain (Unlicense), at your choice | Image loading and PNG writing. Vendored in third_party/stb. |
+| [ufbx](https://github.com/ufbx/ufbx) | 0.23.1 (commit 5955c5c) | MIT License or Public Domain (Unlicense), at your choice | FBX import. Vendored in third_party/ufbx. |
+| [Inter typeface](https://github.com/rsms/inter) | 4.1 | SIL Open Font License 1.1 | User interface font, embedded in the desktop app. Vendored in assets/fonts. |
+| [libcurl](https://curl.se) | system library | curl License (MIT/X derivate) | HTTPS for optional AI features on Linux and macOS. Linked dynamically from the operating system; Windows uses the built-in WinHTTP instead. |
+
+SculptForge does not include, bundle or redistribute any AI model. The optional AI features connect
+to services you choose (see [docs/ai-services.md](docs/ai-services.md)), which have their own terms.
+
+The file formats and protocols SculptForge reads and writes (OBJ, PLY, glTF and its Khronos extensions,
+OpenUSD/USDZ, FBX, Gaussian-splat PLY/.splat, the Gradio queue protocol, Unreal Engine Python remote
+execution, the Model Context Protocol) were implemented from their public documentation. No code from
+the Autodesk FBX SDK, the OpenUSD SDK or Unreal Engine is included.
+
+---
+
+## SDL 3
+
+https://libsdl.org — zlib License
+
+```
+Copyright (C) 1997-2025 Sam Lantinga <[email protected]>
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any damages
+arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose,
+including commercial applications, and to alter it and redistribute it
+freely, subject to the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+3. This notice may not be removed or altered from any source distribution.
+```
+
+---
+
+## Dear ImGui
+
+https://github.com/ocornut/imgui — MIT License
+
+```
+The MIT License (MIT)
+
+Copyright (c) 2014-2025 Omar Cornut
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+---
+
+## GLM
+
+https://github.com/g-truc/glm — MIT License (or The Happy Bunny License)
+
+```
+================================================================================
+OpenGL Mathematics (GLM)
+--------------------------------------------------------------------------------
+GLM is licensed under The Happy Bunny License or MIT License
+
+================================================================================
+The Happy Bunny License (Modified MIT License)
+--------------------------------------------------------------------------------
+Copyright (c) 2005 - G-Truc Creation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+Restrictions:
+ By making use of the Software for military purposes, you choose to make a
+ Bunny unhappy.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+================================================================================
+The MIT License
+--------------------------------------------------------------------------------
+Copyright (c) 2005 - G-Truc Creation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+```
+
+---
+
+## stb_image / stb_image_write
+
+https://github.com/nothings/stb — MIT License or Public Domain (Unlicense), at your choice
+
+```
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+```
+
+---
+
+## ufbx
+
+https://github.com/ufbx/ufbx — MIT License or Public Domain (Unlicense), at your choice
+
+```
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2020 Samuli Raivio
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+----------------------------------------
+```
+
+---
+
+## Inter typeface
+
+https://github.com/rsms/inter — SIL Open Font License 1.1
+
+```
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+```
+
+---
+
+## libcurl
+
+https://curl.se — curl License (MIT/X derivate)
+
+```
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (c) 1996 - 2026, Daniel Stenberg, <[email protected]>, and many
+contributors, see the THANKS file.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright
+notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall not
+be used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization of the copyright holder.
+```
diff --git a/assets/branding/sculptforge-1024.png b/assets/branding/sculptforge-1024.png
new file mode 100644
index 00000000..d0b887ea
Binary files /dev/null and b/assets/branding/sculptforge-1024.png differ
diff --git a/assets/branding/sculptforge-256.png b/assets/branding/sculptforge-256.png
new file mode 100644
index 00000000..d0307194
Binary files /dev/null and b/assets/branding/sculptforge-256.png differ
diff --git a/assets/branding/sculptforge-512.png b/assets/branding/sculptforge-512.png
new file mode 100644
index 00000000..f986045b
Binary files /dev/null and b/assets/branding/sculptforge-512.png differ
diff --git a/assets/branding/sculptforge-icon.svg b/assets/branding/sculptforge-icon.svg
new file mode 100644
index 00000000..d22e2aad
--- /dev/null
+++ b/assets/branding/sculptforge-icon.svg
@@ -0,0 +1,39 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="#23232a"/>
+ <stop offset="1" stop-color="#0e0e11"/>
+ </linearGradient>
+ <radialGradient id="clay" cx="0.36" cy="0.32" r="0.78">
+ <stop offset="0" stop-color="#ffd2a6"/>
+ <stop offset="0.38" stop-color="#f6a05a"/>
+ <stop offset="0.8" stop-color="#d5602a"/>
+ <stop offset="1" stop-color="#a3401b"/>
+ </radialGradient>
+ <radialGradient id="glow" cx="0.5" cy="0.5" r="0.5">
+ <stop offset="0" stop-color="#f28c3c" stop-opacity="0.45"/>
+ <stop offset="1" stop-color="#f28c3c" stop-opacity="0"/>
+ </radialGradient>
+ <linearGradient id="groove" x1="0" y1="0" x2="1" y2="0">
+ <stop offset="0" stop-color="#7a2d10" stop-opacity="0"/>
+ <stop offset="0.25" stop-color="#7a2d10" stop-opacity="0.85"/>
+ <stop offset="0.75" stop-color="#7a2d10" stop-opacity="0.85"/>
+ <stop offset="1" stop-color="#7a2d10" stop-opacity="0"/>
+ </linearGradient>
+ </defs>
+ <rect x="16" y="16" width="480" height="480" rx="108" fill="url(#bg)"/>
+ <rect x="16.5" y="16.5" width="479" height="479" rx="107.5" fill="none" stroke="#ffffff" stroke-opacity="0.07" stroke-width="1"/>
+ <circle cx="256" cy="276" r="190" fill="url(#glow)"/>
+ <!-- the clay form -->
+ <path d="M256 104c92 0 150 66 150 160 0 86-62 150-150 150s-150-64-150-150c0-94 58-160 150-160z" fill="url(#clay)"/>
+ <!-- a carved "S" stroke: the brush mark and the initial -->
+ <path d="M318 176c-22-20-46-28-72-26-36 3-60 26-56 56 4 28 30 40 64 50 34 10 62 24 64 56 3 34-26 58-64 60-30 2-54-8-74-28"
+ fill="none" stroke="#6f2a0f" stroke-opacity="0.9" stroke-width="30" stroke-linecap="round"/>
+ <path d="M318 176c-22-20-46-28-72-26-36 3-60 26-56 56 4 28 30 40 64 50 34 10 62 24 64 56 3 34-26 58-64 60-30 2-54-8-74-28"
+ fill="none" stroke="#3f1606" stroke-opacity="0.55" stroke-width="12" stroke-linecap="round" transform="translate(3 4)"/>
+ <path d="M322 168c-22-20-46-29-74-27-38 3-64 28-60 60" fill="none" stroke="#ffe6cc" stroke-opacity="0.6"
+ stroke-width="5" stroke-linecap="round" transform="translate(-6 -8)"/>
+ <!-- forge spark -->
+ <path d="M392 92l9 29 29 9-29 9-9 29-9-29-29-9 29-9z" fill="#ffd9ad"/>
+ <circle cx="392" cy="130" r="22" fill="#ffd9ad" opacity="0.18"/>
+</svg>
diff --git a/assets/branding/sculptforge.ico b/assets/branding/sculptforge.ico
new file mode 100644
index 00000000..3fb52df4
Binary files /dev/null and b/assets/branding/sculptforge.ico differ
diff --git a/assets/demo/teddy-sketch.png b/assets/demo/teddy-sketch.png
new file mode 100644
index 00000000..d1b02320
Binary files /dev/null and b/assets/demo/teddy-sketch.png differ
diff --git a/assets/fonts/Inter-Regular.ttf b/assets/fonts/Inter-Regular.ttf
new file mode 100644
index 00000000..b7aaca8d
Binary files /dev/null and b/assets/fonts/Inter-Regular.ttf differ
diff --git a/assets/fonts/Inter-SemiBold.ttf b/assets/fonts/Inter-SemiBold.ttf
new file mode 100644
index 00000000..47f8ab1d
Binary files /dev/null and b/assets/fonts/Inter-SemiBold.ttf differ
diff --git a/assets/fonts/OFL.txt b/assets/fonts/OFL.txt
new file mode 100644
index 00000000..9b2ca37b
--- /dev/null
+++ b/assets/fonts/OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake
new file mode 100644
index 00000000..f920d8c9
--- /dev/null
+++ b/cmake/Dependencies.cmake
@@ -0,0 +1,53 @@
+# Third-party dependencies. Everything is fetched at configure time so a fresh
+# checkout builds the same way on Linux, macOS and Windows.
+include(FetchContent)
+set(FETCHCONTENT_QUIET ON)
+
+# glm (header-only maths)
+FetchContent_Declare(glm
+ URL https://github.com/g-truc/glm/archive/refs/tags/1.0.1.tar.gz
+ DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
+set(GLM_BUILD_TESTS OFF CACHE BOOL "" FORCE)
+set(GLM_BUILD_INSTALL OFF CACHE BOOL "" FORCE)
+FetchContent_MakeAvailable(glm)
+
+if(NOT SCULPTFORGE_BUILD_APP)
+ return()
+endif()
+
+# SDL3 (windowing, input, pen pressure, native file dialogs)
+if(SCULPTFORGE_USE_SYSTEM_SDL)
+ find_package(SDL3 3.2 CONFIG QUIET)
+endif()
+if(SDL3_FOUND)
+ message(STATUS "Using system SDL3 ${SDL3_VERSION}")
+else()
+ message(STATUS "Fetching SDL3")
+ FetchContent_Declare(SDL3
+ URL https://github.com/libsdl-org/SDL/releases/download/release-3.2.10/SDL3-3.2.10.tar.gz
+ DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
+ # Static: release packages then need no separate SDL library (zlib licence allows this).
+ set(SDL_SHARED OFF CACHE BOOL "" FORCE)
+ set(SDL_STATIC ON CACHE BOOL "" FORCE)
+ set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
+ set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE)
+ FetchContent_MakeAvailable(SDL3)
+endif()
+
+# Dear ImGui (UI) with the SDL3 + OpenGL3 backends
+FetchContent_Declare(imgui
+ URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.9.tar.gz
+ DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
+FetchContent_MakeAvailable(imgui)
+
+add_library(imgui STATIC
+ ${imgui_SOURCE_DIR}/imgui.cpp
+ ${imgui_SOURCE_DIR}/imgui_draw.cpp
+ ${imgui_SOURCE_DIR}/imgui_tables.cpp
+ ${imgui_SOURCE_DIR}/imgui_widgets.cpp
+ ${imgui_SOURCE_DIR}/backends/imgui_impl_sdl3.cpp
+ ${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp)
+target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR} ${imgui_SOURCE_DIR}/backends)
+# Item hooks used by the scripted demo recorder (src/app/Demo.cpp); inert unless enabled at runtime.
+target_compile_definitions(imgui PUBLIC IMGUI_ENABLE_TEST_ENGINE)
+target_link_libraries(imgui PUBLIC SDL3::SDL3 ${CMAKE_DL_LIBS})
diff --git a/cmake/EmbedFile.cmake b/cmake/EmbedFile.cmake
new file mode 100644
index 00000000..8cdc1dcf
--- /dev/null
+++ b/cmake/EmbedFile.cmake
@@ -0,0 +1,23 @@
+# embed_files(<output.cpp> <namespace> <symbol> <file> [<symbol> <file> ...])
+# Generates a C++ source with each file as `const unsigned char <symbol>[]` and
+# `const unsigned long long <symbol>_size`, so assets ship inside the binary.
+function(embed_files output ns)
+ set(content "// Generated by cmake/EmbedFile.cmake - do not edit.\nnamespace ${ns} {\n")
+ set(args ${ARGN})
+ list(LENGTH args count)
+ math(EXPR last "${count} - 1")
+ foreach(i RANGE 0 ${last} 2)
+ math(EXPR j "${i} + 1")
+ list(GET args ${i} symbol)
+ list(GET args ${j} file)
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${file})
+ file(READ ${file} hex HEX)
+ file(SIZE ${file} size)
+ string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," bytes "${hex}")
+ string(REGEX REPLACE "(0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..,)" "\\1\n" bytes "${bytes}")
+ string(APPEND content "extern const unsigned char ${symbol}[] = {\n${bytes}};\nextern const unsigned long long ${symbol}_size = ${size};\n")
+ endforeach()
+ string(APPEND content "} // namespace ${ns}\n")
+ file(WRITE ${output}.tmp "${content}")
+ file(COPY_FILE ${output}.tmp ${output} ONLY_IF_DIFFERENT)
+endfunction()
diff --git a/cmake/MacSign.cmake b/cmake/MacSign.cmake
new file mode 100644
index 00000000..dd7c972d
--- /dev/null
+++ b/cmake/MacSign.cmake
@@ -0,0 +1,18 @@
+# CPack pre-build script (macOS): sign the staged app bundle after everything is installed into it,
+# so the signature covers the final contents. Ad-hoc ("-") unless SCULPTFORGE_CODESIGN_IDENTITY is set
+# in the environment (e.g. "Developer ID Application: ..." from a CI secret).
+set(identity "$ENV{SCULPTFORGE_CODESIGN_IDENTITY}")
+if(identity STREQUAL "")
+ set(identity "-")
+endif()
+file(GLOB_RECURSE plists "${CPACK_TEMPORARY_DIRECTORY}/*SculptForge.app/Contents/Info.plist")
+foreach(plist ${plists})
+ get_filename_component(contents "${plist}" DIRECTORY)
+ get_filename_component(app "${contents}" DIRECTORY)
+ message(STATUS "Signing ${app} (${identity})")
+ execute_process(COMMAND codesign --force --deep --options runtime --timestamp=none --sign "${identity}" "${app}"
+ RESULT_VARIABLE rc)
+ if(NOT rc EQUAL 0)
+ message(FATAL_ERROR "codesign failed for ${app}")
+ endif()
+endforeach()
diff --git a/docs/ai-services.md b/docs/ai-services.md
new file mode 100644
index 00000000..dd5ee75f
--- /dev/null
+++ b/docs/ai-services.md
@@ -0,0 +1,41 @@
+# AI services: privacy and model licences
+
+Every AI feature in SculptForge is **optional and off until you use it**. SculptForge has no
+telemetry, no account and no servers of its own. When you use an AI feature, SculptForge talks
+**directly** to the service you picked; nothing goes anywhere else.
+
+## What is sent where
+
+| Feature | Service (your choice) | What is sent | Key |
+|---|---|---|---|
+| Brush Lab | Anthropic (Claude), or any OpenAI-compatible endpoint such as a local Ollama / LM Studio | Your brush description and the current brush settings (text only) | Your API key; none for local models |
+| Generate 3D (image) | Hugging Face Spaces (free), fal.ai, Meshy, or your own command | The image you chose, cropped and resized to at most 1024 px | Optional HF token; your fal.ai / Meshy key |
+| Generate 3D (text) | Hugging Face Spaces (free), fal.ai, Meshy | Your text description | As above |
+| Send to Unreal | Your own Unreal Editor (local network) | The exported FBX | None |
+
+Keys are stored in your local settings file (`ai.json`, owner-only permissions) or read from
+environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `HF_TOKEN`, `FAL_KEY`, `MESHY_API_KEY`).
+
+## The free image-to-3D and text-to-3D models
+
+The free option runs each model author's **own public demo** on Hugging Face's shared ZeroGPU
+hardware. SculptForge isn't affiliated with Hugging Face or any of the model authors, and doesn't
+host, bundle or redistribute any model. GPU time is rationed per user per day; a free Hugging Face
+token raises the allowance.
+
+**Each model has its own licence, and you're responsible for following it:**
+
+| Model | Author / provider | Licence | Key terms (summary, not legal advice) |
+|---|---|---|---|
+| TRELLIS.2 | Microsoft (Space by Microsoft) | MIT | Permissive. |
+| Hunyuan3D 2.1, Hunyuan3D 2, Hunyuan3D 2 mini Turbo | Tencent (Spaces by Tencent) | [Tencent Hunyuan Community License](https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1/blob/main/LICENSE) | **Not licensed for use in the European Union, the United Kingdom or South Korea.** Products over 1 million monthly active users need a separate licence from Tencent. Tencent claims no rights in your outputs. Outputs may not be used to improve other AI models. |
+| Stable Fast 3D | Stability AI (Space by Stability AI) | [Stability AI Community License](https://huggingface.co/stabilityai/stable-fast-3d/blob/main/LICENSE.md) | Free, including commercial use, for individuals and organisations under US $1M annual revenue; above that, an enterprise licence is required. You own your outputs. "Powered by Stability AI". |
+
+These summaries are for convenience only. Read the licences linked above before using outputs
+commercially, and check where you are. If you're in the EU, UK or South Korea, choose TRELLIS.2,
+Stable Fast 3D or a paid service instead of Hunyuan3D.
+
+## Paid services
+
+fal.ai and Meshy are paid services with their own terms of service and pricing; generations are
+billed to your account with them. Model availability and names can change on their side.
diff --git a/docs/generators.md b/docs/generators.md
new file mode 100644
index 00000000..b6d20293
--- /dev/null
+++ b/docs/generators.md
@@ -0,0 +1,88 @@
+# Image-to-3D generators
+
+**Image to 3D → Full 3D model** offers five sources:
+
+| Service | What it is | Setup |
+|---|---|---|
+| **Hugging Face** (default, free) | The official public demos of Hunyuan3D 2.1 / 2 / 2 mini Turbo (Tencent), TRELLIS.2 (Microsoft) and Stable Fast 3D (Stability AI), on Hugging Face's shared ZeroGPU hardware | Nothing. A free token from huggingface.co/settings/tokens (read access), or `HF_TOKEN`, raises the daily GPU allowance; TRELLIS.2 needs one |
+| **fal.ai** | Hosted reconstruction models, billed per generation: TRELLIS.2 (Microsoft), Hunyuan3D 3.1 Pro/Rapid (Tencent), Meshy 6 - or any other fal model id | Key from fal.ai/dashboard/keys, or `FAL_KEY` |
+| **Meshy** | Meshy's own API (`meshy-7.1` by default) | Key from meshy.ai, or `MESHY_API_KEY` |
+| **My generator command** | Anything you run locally (see below) | A command line |
+| **Offline blockout** | Inflates the outline into a rounded blob. Fine for simple shapes, not characters | Nothing |
+
+**About the free option:** these are the model authors' own demo apps. They're free,
+but GPU time is rationed per user per day, there can be a queue at busy times,
+and an app can be paused or changed by its owner. SculptForge shows queue
+position and progress, and tells you when the allowance runs out. Typical times
+are about 6 s (Turbo, Stable Fast 3D) and 20 s (Hunyuan3D 2.1). For guaranteed
+capacity, use fal.ai or Meshy, or run a model on your own GPU.
+
+For the hosted services, SculptForge crops the subject out of a transparent
+background, centres it on a square and scales it to at most 1024 px, then sends
+it to the service (with your key or token, if any). It polls until the model is ready,
+downloads the GLB, and by default voxel-remeshes it into a watertight surface
+you can sculpt straight away. Nothing leaves your machine unless you pick a
+hosted service and press **Generate**. Keys are stored in your local `ai.json`
+(owner-only permissions) or read from the environment.
+
+Tips for good results: one character or object per image, a plain or
+transparent background, the whole subject in frame, and a front or
+three-quarter view. A clean concept-art turnaround pose works better than a
+busy illustration.
+
+From the command line or an MCP agent:
+
+```sh
+sculptforge-cli -c 'image_to_3d path=hero.png; export_glb path=hero.glb' # free (Hunyuan3D 2.1)
+HF_TOKEN=... sculptforge-cli -c 'image_to_3d path=hero.png model=trellis-2; export_glb path=hero.glb'
+FAL_KEY=... sculptforge-cli -c 'image_to_3d path=hero.png service=fal model=fal-ai/trellis-2; export_glb path=hero.glb'
+MESHY_API_KEY=... sculptforge-cli -c 'image_to_3d path=hero.png service=meshy remesh=false; export_usd path=hero.usdz'
+```
+
+## Your own generator
+
+The **My generator command** option runs a plain command line, so it works
+with local open-source models on your own GPU, a studio's internal service, or
+a script that calls any cloud API.
+
+## The contract
+
+- `{input}` is replaced with the image path, `{output}` with the path the
+ generator must write. Both are shell-quoted for you, so don't add quotes.
+- Write a `.glb` (preferred) or `.obj` to `{output}` and exit with status 0.
+- SculptForge imports the result, welds UV seams so it can be sculpted, and
+ turns any glTF morph targets into sculpt layers.
+
+The pre-filled command runs SculptForge's own silhouette inflation, which is a
+quick way to check the pipeline works:
+
+```
+sculptforge-cli --set input={input} --set output={output} -c 'image_inflate path=$input subdivisions=2; export_glb path=$output'
+```
+
+## Wiring up a model
+
+Open-source image-to-3D models such as TRELLIS.2, Hunyuan3D, TripoSR and
+Stable Fast 3D ship their own inference scripts (they need a CUDA GPU). Wrap whichever you use in a
+small script that takes an input image and an output path, then point
+SculptForge at it:
+
+```
+python3 /path/to/my_generator.py {input} {output}
+```
+
+```python
+# my_generator.py - adapt to the model you use
+import sys
+image_path, output_path = sys.argv[1], sys.argv[2]
+# 1. load your model (cache it between runs if startup is slow)
+# 2. run it on image_path
+# 3. export the mesh to output_path as .glb
+```
+
+Tips:
+
+- Generated meshes are often dense, uneven and full of small holes. **Mesh →
+ Voxel Remesh** turns them into one clean watertight surface.
+- For cloud services, keep API keys in environment variables your script
+ reads. Don't put them in the command line.
diff --git a/docs/images/screenshot-brush-lab.jpg b/docs/images/screenshot-brush-lab.jpg
new file mode 100644
index 00000000..4697d502
Binary files /dev/null and b/docs/images/screenshot-brush-lab.jpg differ
diff --git a/docs/images/screenshot-game-ready.jpg b/docs/images/screenshot-game-ready.jpg
new file mode 100644
index 00000000..8ded71f5
Binary files /dev/null and b/docs/images/screenshot-game-ready.jpg differ
diff --git a/docs/images/screenshot-sculpt.jpg b/docs/images/screenshot-sculpt.jpg
new file mode 100644
index 00000000..02e053fa
Binary files /dev/null and b/docs/images/screenshot-sculpt.jpg differ
diff --git a/docs/images/screenshot-splats.jpg b/docs/images/screenshot-splats.jpg
new file mode 100644
index 00000000..11f70443
Binary files /dev/null and b/docs/images/screenshot-splats.jpg differ
diff --git a/docs/images/sculpt-demo.gif b/docs/images/sculpt-demo.gif
new file mode 100644
index 00000000..734b827a
Binary files /dev/null and b/docs/images/sculpt-demo.gif differ
diff --git a/docs/images/social-preview.png b/docs/images/social-preview.png
new file mode 100644
index 00000000..7a0ffaea
Binary files /dev/null and b/docs/images/social-preview.png differ
diff --git a/docs/unreal.md b/docs/unreal.md
new file mode 100644
index 00000000..92635981
--- /dev/null
+++ b/docs/unreal.md
@@ -0,0 +1,81 @@
+# SculptForge → Unreal Engine
+
+SculptForge can push a sculpt straight into a running Unreal Editor (5.x), or
+write an Unreal-ready FBX for you to import by hand.
+
+## What you get
+
+| Your sculpt | In Unreal |
+|---|---|
+| No sculpt layers | **Static mesh** `SM_<Name>` with LOD0–LODn from **Game Ready → LODs** (one file, imported as LODs automatically) |
+| Sculpt layers | **Skeletal mesh** `SK_<Name>` with one **morph target** per layer (Unreal adds a single root bone) |
+| Any | Material slot `M_Clay`, real-world size from **Height (cm)** |
+
+Sending the same asset again **updates it in place** (same name and folder), so
+references in your levels stay intact.
+
+## One-time setup in Unreal
+
+1. **Edit → Plugins**: enable **Python Editor Script Plugin**, then restart the editor.
+2. **Edit → Project Settings → Plugins → Python**: tick **Enable Remote Execution?**
+
+That's all when Unreal runs on the same computer as SculptForge.
+
+### Unreal on another computer
+
+On the Unreal machine, in the same **Python** settings page, open the
+**Advanced** section and set:
+
+- **Multicast Time-To-Live** = `1`
+- **Multicast Bind Address** = `0.0.0.0`
+
+In SculptForge, tick **Unreal is on another computer** (or pass `network=true`
+on the command line). SculptForge finds the editor on the local network, the
+editor connects back to SculptForge, and downloads the FBX from it through a
+one-time link that only works during that transfer.
+
+Both computers must be on the same network. The SculptForge computer's firewall
+must allow incoming connections from the Unreal machine, because the editor
+connects back to fetch the command and the file.
+
+## Sending
+
+- **Game Ready → Unreal Engine → Send to Unreal** (or **Ctrl+U**). Set the
+ content folder (default `/Game/SculptForge`) and the height in centimetres.
+- Command line / agents:
+
+```sh
+sculptforge-cli -c 'open path=rock.obj; unreal_send destination=/Game/Props height_cm=120 lods=4'
+sculptforge-cli -c 'unreal_editors network=true' # list editors on the network
+```
+
+If several editors are open, `project=<ProjectName>` picks one.
+
+## Manual import
+
+**File → Export FBX for Unreal...** writes the same file. Drag it into the
+Content Browser:
+
+- Static meshes: LODs are detected from the file's LOD group.
+- Skeletal meshes: choose *Skeletal Mesh* and tick *Import Morph Targets*.
+
+## How it works
+
+Send to Unreal uses Unreal's built-in Python remote execution, the same
+channel Epic's own tools use:
+
+1. A UDP multicast discovery on `239.0.0.1:6766`.
+2. A TCP connection that the editor opens back to SculptForge.
+3. A short Python script that runs `AssetImportTask` with the FBX importer.
+
+Nothing is installed into your project.
+
+## Known limits
+
+- Morph targets need a skeletal mesh in Unreal, so layered sculpts are sent
+ without the LOD chain (Unreal can generate skeletal LODs itself).
+- There are no UVs yet, so Unreal generates lightmap UVs on import.
+- Checked against SculptForge's test suite, two independent FBX readers (ufbx
+ and Assimp), and a stand-in editor that speaks the remote-execution
+ protocol. It has not yet been run against a real Unreal Editor. If something
+ fails, the editor's **Output Log** shows the importer's messages.
diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD
new file mode 100644
index 00000000..72ce8d66
--- /dev/null
+++ b/packaging/arch/PKGBUILD
@@ -0,0 +1,39 @@
+# Maintainer: The SculptForge contributors <https://github.com/islandmed/SculptForge>
+pkgname=sculptforge
+pkgver=0.1.0
+pkgrel=1
+pkgdesc="Free and open-source digital sculpting with game-engine pipelines and bring-your-own AI"
+arch=('x86_64' 'aarch64')
+url="https://islandmed.github.io/SculptForge/"
+license=('GPL-3.0-or-later')
+depends=('sdl3' 'curl' 'gcc-libs' 'glibc' 'libglvnd')
+makedepends=('cmake')
+optdepends=('ollama: local AI for the Brush Lab'
+ 'ffmpeg: recording demo videos (sculptforge --record)')
+_imgui=1.91.9
+_glm=1.0.1
+source=("$pkgname-$pkgver.tar.gz::https://github.com/islandmed/SculptForge/archive/refs/tags/v$pkgver.tar.gz"
+ "imgui-$_imgui.tar.gz::https://github.com/ocornut/imgui/archive/refs/tags/v$_imgui.tar.gz"
+ "glm-$_glm.tar.gz::https://github.com/g-truc/glm/archive/refs/tags/$_glm.tar.gz")
+sha256sums=('SKIP'
+ '3872a5f90df78fced023c1945f4466b654fd74573370b77b17742149763a7a7c'
+ '9f3174561fd26904b23f0db5e560971cbf9b3cbda0b280f04d5c379d03bf234c')
+
+build() {
+ cmake -S "SculptForge-$pkgver" -B build \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_INSTALL_PREFIX=/usr \
+ -DSCULPTFORGE_USE_SYSTEM_SDL=ON \
+ -DFETCHCONTENT_FULLY_DISCONNECTED=ON \
+ -DFETCHCONTENT_SOURCE_DIR_IMGUI="$srcdir/imgui-$_imgui" \
+ -DFETCHCONTENT_SOURCE_DIR_GLM="$srcdir/glm-$_glm"
+ cmake --build build
+}
+
+check() {
+ ctest --test-dir build --output-on-failure
+}
+
+package() {
+ DESTDIR="$pkgdir" cmake --install build
+}
diff --git a/packaging/arch/README.md b/packaging/arch/README.md
new file mode 100644
index 00000000..444a40c2
--- /dev/null
+++ b/packaging/arch/README.md
@@ -0,0 +1,15 @@
+# Arch Linux (AUR)
+
+`PKGBUILD` builds SculptForge from a release tag against Arch's own SDL3 and curl, fully offline
+(Dear ImGui and GLM are pinned sources with checksums).
+
+## Publishing to the AUR (maintainer, once per release)
+
+1. Create an AUR account at https://aur.archlinux.org and add your SSH public key to it.
+2. First time only: `git clone ssh://[email protected]/sculptforge.git aur-sculptforge`
+3. Copy this `PKGBUILD` in, set `pkgver` to the release and update the first checksum:
+ `updpkgsums` (from `pacman-contrib`), then `makepkg -si` to test the build.
+4. `makepkg --printsrcinfo > .SRCINFO`
+5. `git add PKGBUILD .SRCINFO && git commit -m "Update to <version>" && git push`
+
+Users then install with `yay -S sculptforge` (or any AUR helper).
diff --git a/packaging/linux/install-build-deps.sh b/packaging/linux/install-build-deps.sh
new file mode 100755
index 00000000..3928a537
--- /dev/null
+++ b/packaging/linux/install-build-deps.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# Installs everything needed to build SculptForge on Debian/Ubuntu or Fedora/RHEL-family systems.
+set -eu
+if command -v apt-get >/dev/null 2>&1; then
+ apt-get update
+ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
+ build-essential cmake pkg-config git file ca-certificates \
+ libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev libxtst-dev \
+ libxkbcommon-dev libwayland-dev wayland-protocols libdecor-0-dev libegl1-mesa-dev libgl1-mesa-dev \
+ libdbus-1-dev libudev-dev libcurl4-openssl-dev
+elif command -v dnf >/dev/null 2>&1; then
+ dnf -y install dnf-plugins-core
+ dnf config-manager --set-enabled crb 2>/dev/null || true
+ dnf -y install gcc-c++ cmake make pkgconf-pkg-config git file rpm-build \
+ libX11-devel libXext-devel libXrandr-devel libXcursor-devel libXfixes-devel libXi-devel libXScrnSaver-devel \
+ libXtst-devel libxkbcommon-devel wayland-devel wayland-protocols-devel mesa-libEGL-devel mesa-libGL-devel \
+ dbus-devel systemd-devel libcurl-devel
+ # RHEL 9 ships GCC 11; use the newer toolset when available.
+ dnf -y install gcc-toolset-13 2>/dev/null || true
+else
+ echo "Unsupported distribution: install a C++20 compiler, CMake 3.24+, X11/Wayland/GL development headers and libcurl." >&2
+ exit 1
+fi
diff --git a/packaging/linux/org.sculptforge.SculptForge.desktop b/packaging/linux/org.sculptforge.SculptForge.desktop
new file mode 100644
index 00000000..c04aee18
--- /dev/null
+++ b/packaging/linux/org.sculptforge.SculptForge.desktop
@@ -0,0 +1,12 @@
+[Desktop Entry]
+Type=Application
+Name=SculptForge
+GenericName=Digital Sculpting
+Comment=Sculpt 3D models and send them to game engines
+Exec=sculptforge %f
+Icon=org.sculptforge.SculptForge
+Terminal=false
+Categories=Graphics;3DGraphics;
+Keywords=sculpt;3d;model;zbrush;mesh;gltf;fbx;usd;unreal;
+MimeType=model/obj;model/gltf-binary;model/gltf+json;model/vnd.usdz+zip;model/vnd.usda;application/x-sculptforge-brush;
+StartupWMClass=sculptforge
diff --git a/packaging/linux/org.sculptforge.SculptForge.metainfo.xml b/packaging/linux/org.sculptforge.SculptForge.metainfo.xml
new file mode 100644
index 00000000..6ad72e52
--- /dev/null
+++ b/packaging/linux/org.sculptforge.SculptForge.metainfo.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<component type="desktop-application">
+ <id>org.sculptforge.SculptForge</id>
+ <metadata_license>CC0-1.0</metadata_license>
+ <project_license>GPL-3.0-or-later</project_license>
+ <name>SculptForge</name>
+ <summary>Digital sculpting for artists and game pipelines</summary>
+ <developer id="org.sculptforge">
+ <name>The SculptForge contributors</name>
+ </developer>
+ <description>
+ <p>SculptForge is a free and open-source digital sculpting application with ZBrush-style brushes,
+ symmetry, sculpt layers, voxel remeshing and one-click LOD chains.</p>
+ <p>It exports game-ready FBX, glTF and OpenUSD files, can send assets straight into the Unreal Editor,
+ works with Gaussian splats, and offers optional bring-your-own AI tools: describe a brush in words,
+ or turn an image or a description into a sculptable 3D model.</p>
+ </description>
+ <launchable type="desktop-id">org.sculptforge.SculptForge.desktop</launchable>
+ <url type="homepage">https://islandmed.github.io/SculptForge/</url>
+ <url type="bugtracker">https://github.com/islandmed/SculptForge/issues</url>
+ <url type="vcs-browser">https://github.com/islandmed/SculptForge</url>
+ <screenshots>
+ <screenshot type="default">
+ <image>https://islandmed.github.io/SculptForge/media/screenshot-sculpt.jpg</image>
+ <caption>Sculpting a creature with symmetry</caption>
+ </screenshot>
+ </screenshots>
+ <content_rating type="oars-1.1"/>
+ <releases>
+ <release version="0.1.0" date="2026-10-20"/>
+ </releases>
+ <provides>
+ <binary>sculptforge</binary>
+ <binary>sculptforge-cli</binary>
+ </provides>
+</component>
diff --git a/packaging/release-notes-footer.md b/packaging/release-notes-footer.md
new file mode 100644
index 00000000..47e55d92
--- /dev/null
+++ b/packaging/release-notes-footer.md
@@ -0,0 +1,16 @@
+
+---
+
+### Downloads
+
+| Platform | File |
+|---|---|
+| Windows 10/11 (x64) | `SculptForge-…-windows-x86_64.exe` (installer) or `.zip` (portable) |
+| macOS 11+ (Apple Silicon and Intel) | `SculptForge-…-darwin-universal.dmg` |
+| Ubuntu / Debian / Mint / Pop!_OS | `sculptforge_…_amd64.deb` or `…_arm64.deb` |
+| Fedora / RHEL 9+ / Rocky / Alma | `sculptforge-…x86_64.rpm` or `…aarch64.rpm` |
+| Any Linux | `SculptForge-…-linux-x86_64.AppImage` or `…-arm64.AppImage` |
+| Arch Linux | `yay -S sculptforge` (AUR) |
+
+The builds are not code-signed yet. **macOS:** right-click the app → **Open** the first time.
+**Windows:** if SmartScreen appears, choose **More info → Run anyway**. Checksums are in `SHA256SUMS.txt`.
diff --git a/packaging/windows/sculptforge.rc b/packaging/windows/sculptforge.rc
new file mode 100644
index 00000000..84f8b91c
--- /dev/null
+++ b/packaging/windows/sculptforge.rc
@@ -0,0 +1,28 @@
+// SculptForge Windows resources: application icon and version information.
+#include <winver.h>
+
+IDI_ICON1 ICON "@ICON_PATH@"
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0
+ PRODUCTVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0
+ FILEOS VOS_NT_WINDOWS32
+ FILETYPE VFT_APP
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904b0"
+ BEGIN
+ VALUE "CompanyName", "The SculptForge contributors"
+ VALUE "FileDescription", "SculptForge - digital sculpting"
+ VALUE "FileVersion", "@PROJECT_VERSION@"
+ VALUE "LegalCopyright", "Copyright (C) 2026 The SculptForge contributors. GPL-3.0-or-later."
+ VALUE "ProductName", "SculptForge"
+ VALUE "ProductVersion", "@PROJECT_VERSION@"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
diff --git a/src/ai/AiCommands.cpp b/src/ai/AiCommands.cpp
new file mode 100644
index 00000000..f252594c
--- /dev/null
+++ b/src/ai/AiCommands.cpp
@@ -0,0 +1,170 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/AiCommands.h"
+
+#include "ai/ImageTo3DService.h"
+#include "core/EnginePresets.h"
+#include "core/Voxel.h"
+#include "link/UnrealLink.h"
+
+#include <algorithm>
+#include <chrono>
+#include <filesystem>
+
+namespace sf::ai {
+
+void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> settings) {
+ using T = ParamSpec::Type;
+ registry.add({"brush_ai",
+ "Design a brush from a description using your configured AI provider "
+ "(ANTHROPIC_API_KEY, or provider=openai-compatible endpoint=... model=... for Ollama etc.).",
+ {{"prompt", T::String, "What the brush should do, in an artist's words.", true},
+ {"provider", T::String, "'anthropic' or 'openai-compatible' (default: your saved settings).", false},
+ {"endpoint", T::String, "Override the API endpoint URL.", false},
+ {"model", T::String, "Override the model name.", false}},
+ [settings](Document& doc, const Args& a) -> CommandResult {
+ AiSettings s = settings();
+ if (a.contains("provider"))
+ s = AiSettings::defaults(argString(a, "provider") == "openai-compatible"
+ ? AiSettings::Provider::OpenAICompatible
+ : AiSettings::Provider::Anthropic);
+ if (a.contains("endpoint")) s.endpoint = argString(a, "endpoint");
+ if (a.contains("model")) s.model = argString(a, "model");
+ std::vector<ChatMessage> history = {composeUserMessage(argString(a, "prompt"), nullptr)};
+ BrushSuggestion r = requestBrush(s, history, nullptr);
+ if (!r.ok) return {false, r.error};
+ doc.activeBrush = doc.addBrush(r.recipe);
+ return {true, "'" + r.recipe.name + "': " + r.reply};
+ }});
+
+ registry.add({"image_to_3d",
+ "Reconstruct a full 3D model from one picture (character, creature, prop) and make it sculptable. "
+ "Free by default via Hugging Face Spaces (Hunyuan3D, TRELLIS.2, Stable Fast 3D; HF_TOKEN raises the "
+ "daily quota), or paid via fal.ai (FAL_KEY) / Meshy (MESHY_API_KEY). Replaces the scene. "
+ "A transparent background works best.",
+ {{"path", T::String, "Image file (png, jpg...).", true},
+ {"service", T::String, "'huggingface' (free, default), 'fal', 'meshy', 'command' (your generator) or 'inflate' (offline blockout).", false},
+ {"model", T::String, "huggingface: hunyuan3d-2.1, trellis-2, hunyuan3d-2-turbo, hunyuan3d-2, stable-fast-3d; fal: a model id such as fal-ai/trellis-2.", false},
+ {"remesh", T::Bool, "Voxel-remesh the result into a clean watertight sculpting surface. Default true.", false},
+ {"resolution", T::Number, "Remesh voxels across the model (64-512). Default 256.", false}},
+ [settings](Document& doc, const Args& a) -> CommandResult {
+ AiSettings s = settings();
+ if (a.contains("service")) s.generatorService = argString(a, "service");
+ if (a.contains("model")) {
+ if (s.generatorService == "meshy") s.meshyModel = argString(a, "model");
+ else if (s.generatorService == "fal") s.falModel = argString(a, "model");
+ else s.hfModel = argString(a, "model");
+ }
+ const auto stem = std::filesystem::temp_directory_path() /
+ ("sculptforge_generated_" +
+ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
+ const auto stemU8 = stem.u8string();
+ GeneratorResult r = generate3D(s, argString(a, "path"), std::string(stemU8.begin(), stemU8.end()));
+ if (!r.ok) return {false, r.error};
+ CommandResult opened = CommandRegistry().execute(doc, "open", {{"path", r.outputPath}});
+ std::error_code ec;
+ std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
+ if (!opened.ok) return opened;
+ doc.path.clear();
+ const size_t raw = doc.mesh.triangleCount();
+ if (argBool(a, "remesh", true)) {
+ std::string err;
+ Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 256)), 64, 512), &err);
+ if (m.triangleCount() == 0) return {false, "Generated, but remeshing failed: " + err};
+ doc.setMesh(std::move(m));
+ }
+ return {true, "Generated a 3D model (" + std::to_string(raw) + " triangles" +
+ (raw != doc.mesh.triangleCount()
+ ? ", remeshed to " + std::to_string(doc.mesh.triangleCount())
+ : std::string()) +
+ ") - ready to sculpt"};
+ }});
+
+ registry.add({"text_to_3d",
+ "Create a 3D model from a description and make it sculptable. Free by default via Hugging Face "
+ "(Hunyuan3D 2 / 2 mini Turbo; HF_TOKEN raises the daily quota), or paid via fal.ai (FAL_KEY) / "
+ "Meshy (MESHY_API_KEY). Replaces the scene.",
+ {{"prompt", T::String, "One object, e.g. 'a stylised dragon head with curled horns'.", true},
+ {"service", T::String, "'huggingface' (free, default), 'fal' or 'meshy'.", false},
+ {"model", T::String, "huggingface: hunyuan3d-2-turbo or hunyuan3d-2.", false},
+ {"remesh", T::Bool, "Voxel-remesh the result into a clean watertight sculpting surface. Default true.", false},
+ {"resolution", T::Number, "Remesh voxels across the model (64-512). Default 256.", false}},
+ [settings](Document& doc, const Args& a) -> CommandResult {
+ AiSettings s = settings();
+ if (a.contains("service")) s.generatorService = argString(a, "service");
+ if (s.generatorService == "command" || s.generatorService == "inflate") s.generatorService = "huggingface";
+ if (a.contains("model")) {
+ if (s.generatorService == "meshy") s.meshyModel = argString(a, "model");
+ else if (s.generatorService != "fal") s.hfModel = argString(a, "model");
+ }
+ const auto stem = std::filesystem::temp_directory_path() /
+ ("sculptforge_text_" +
+ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
+ const auto stemU8 = stem.u8string();
+ GeneratorResult r = generate3DFromText(s, argString(a, "prompt"), std::string(stemU8.begin(), stemU8.end()));
+ if (!r.ok) return {false, r.error};
+ CommandResult opened = CommandRegistry().execute(doc, "open", {{"path", r.outputPath}});
+ std::error_code ec;
+ std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
+ if (!opened.ok) return opened;
+ doc.path.clear();
+ if (argBool(a, "remesh", true)) {
+ std::string err;
+ Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 256)), 64, 512), &err);
+ if (m.triangleCount() == 0) return {false, "Generated, but remeshing failed: " + err};
+ doc.setMesh(std::move(m));
+ }
+ return {true, "Generated a 3D model from text (" + std::to_string(doc.mesh.triangleCount()) +
+ " triangles) - ready to sculpt"};
+ }});
+
+ registry.add({"unreal_editors", "List running Unreal Editors that SculptForge can send assets to (remote execution).",
+ {{"network", T::Bool, "Also look on other computers (Unreal needs Multicast TTL 1 and bind address 0.0.0.0).", false}},
+ [](Document&, const Args& a) -> CommandResult {
+ std::string err;
+ auto editors = link::findUnrealEditors(argBool(a, "network", false) ? link::UnrealEndpoint::network()
+ : link::UnrealEndpoint(),
+ 1500, err);
+ if (editors.empty())
+ return {false, err.empty() ? "No Unreal Editor found. Enable the Python Editor Script Plugin and "
+ "Project Settings > Python > Enable Remote Execution."
+ : err};
+ std::string msg;
+ for (const auto& e : editors)
+ msg += (msg.empty() ? "" : "; ") + e.projectName + " (UE " + e.engineVersion + ", " + e.machine +
+ (e.local() ? "" : " at " + e.address) + ")";
+ return {true, msg};
+ }});
+
+ registry.add({"unreal_send",
+ "Send the sculpt to the running Unreal Editor: exports an Unreal-ready FBX and imports or updates the "
+ "asset in the project (static mesh with LODs, or skeletal mesh with morph targets).",
+ {{"destination", T::String, "Content folder in the project. Default /Game/SculptForge.", false},
+ {"name", T::String, "Asset name (default SM_<document> or SK_<document>).", false},
+ {"height_cm", T::Number, "Model height in Unreal, in cm. Default: 1 unit = 1 m.", false},
+ {"lods", T::Number, "LOD levels for static meshes (1-8). Default 4.", false},
+ {"project", T::String, "Pick the editor with this project name when several are open.", false},
+ {"network", T::Bool, "Unreal runs on another computer (Unreal needs Multicast TTL 1 and bind address 0.0.0.0).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ UnrealExportOptions o;
+ o.folder = (std::filesystem::temp_directory_path() / "sculptforge_unreal").string();
+ o.assetName = argString(a, "name");
+ o.heightCm = float(argNumber(a, "height_cm", 0.0));
+ o.lods = int(argNumber(a, "lods", 4));
+ UnrealExportResult r;
+ std::string err;
+ if (!exportForUnreal(doc, o, r, err)) return {false, err};
+ link::UnrealImport import;
+ import.fbxPath = r.path;
+ import.destination = argString(a, "destination", "/Game/SculptForge");
+ import.assetName = r.assetName;
+ import.skeletal = r.skeletal;
+ import.lods = r.lodCount > 1;
+ std::string message;
+ const auto endpoint = argBool(a, "network", false) ? link::UnrealEndpoint::network() : link::UnrealEndpoint();
+ const bool ok = link::sendToUnreal(endpoint, import, message, argString(a, "project"));
+ return {ok, message};
+ }});
+}
+
+} // namespace sf::ai
diff --git a/src/ai/AiCommands.h b/src/ai/AiCommands.h
new file mode 100644
index 00000000..542e37a2
--- /dev/null
+++ b/src/ai/AiCommands.h
@@ -0,0 +1,19 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Commands that call out to AI services (brush design, image-to-3D). They
+// live in the ai library so the core stays free of networking; the CLI, the
+// MCP server and the app register them on top of the built-in commands.
+#pragma once
+
+#include "ai/BrushAssistant.h"
+#include "core/Commands.h"
+
+#include <functional>
+
+namespace sf::ai {
+
+// `settings` is called on every run so the latest saved settings are used.
+void registerAiCommands(CommandRegistry& registry, std::function<AiSettings()> settings);
+
+} // namespace sf::ai
diff --git a/src/ai/BrushAssistant.cpp b/src/ai/BrushAssistant.cpp
new file mode 100644
index 00000000..81043e07
--- /dev/null
+++ b/src/ai/BrushAssistant.cpp
@@ -0,0 +1,348 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/BrushAssistant.h"
+
+#include "ai/Http.h"
+
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+namespace sf::ai {
+
+namespace {
+
+constexpr const char* kAnthropicUrl = "https://api.anthropic.com/v1/messages";
+constexpr const char* kAnthropicModel = "claude-opus-5-5";
+constexpr const char* kOllamaUrl = "http://localhost:11434/v1/chat/completions";
+constexpr const char* kOllamaModel = "llama3.1";
+
+std::filesystem::path utf8Path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
+
+Json responseSchema() {
+ Json props = Json::object();
+ Json reply = Json::object();
+ reply.set("type", "string");
+ reply.set("description", "1-3 friendly sentences to the artist: what the brush does and one tweak to try.");
+ props.set("reply", reply);
+ props.set("brush", recipeJsonSchema());
+ Json required = Json::array();
+ required.push("reply");
+ required.push("brush");
+ Json schema = Json::object();
+ schema.set("type", "object");
+ schema.set("properties", props);
+ schema.set("required", required);
+ schema.set("additionalProperties", false);
+ return schema;
+}
+
+// Pulls the JSON object out of model text that may be wrapped in prose or code fences.
+bool extractJsonObject(const std::string& text, Json& out, std::string& error) {
+ size_t first = text.find('{');
+ size_t last = text.rfind('}');
+ if (first == std::string::npos || last == std::string::npos || last < first) {
+ error = "The model did not return a brush recipe";
+ return false;
+ }
+ if (!Json::parse(text.substr(first, last - first + 1), out, error)) {
+ error = "The model returned malformed JSON: " + error;
+ return false;
+ }
+ return true;
+}
+
+std::string apiErrorMessage(const Json& j) {
+ const Json& e = j["error"];
+ if (e.isObject() && e["message"].isString()) return e["message"].asString();
+ if (e.isString()) return e.asString();
+ return {};
+}
+
+} // namespace
+
+AiSettings AiSettings::defaults(Provider provider) {
+ AiSettings s;
+ s.provider = provider;
+ if (provider == Provider::Anthropic) {
+ s.endpoint = kAnthropicUrl;
+ s.model = kAnthropicModel;
+ } else {
+ s.endpoint = kOllamaUrl;
+ s.model = kOllamaModel;
+ }
+ return s;
+}
+
+std::string AiSettings::resolvedKey() const {
+ if (!apiKey.empty()) return apiKey;
+ const char* env = std::getenv(provider == Provider::Anthropic ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY");
+ return env ? env : "";
+}
+
+std::string AiSettings::resolvedFalKey() const {
+ if (!falKey.empty()) return falKey;
+ const char* env = std::getenv("FAL_KEY");
+ return env ? env : "";
+}
+
+std::string AiSettings::resolvedHfToken() const {
+ if (!hfToken.empty()) return hfToken;
+ for (const char* name : {"HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"})
+ if (const char* env = std::getenv(name)) return env;
+ return {};
+}
+
+std::string AiSettings::resolvedMeshyKey() const {
+ if (!meshyKey.empty()) return meshyKey;
+ const char* env = std::getenv("MESHY_API_KEY");
+ return env ? env : "";
+}
+
+Json AiSettings::toJson() const {
+ Json j = Json::object();
+ j.set("provider", provider == Provider::Anthropic ? "anthropic" : "openai-compatible");
+ j.set("endpoint", endpoint);
+ j.set("model", model);
+ j.set("apiKey", apiKey);
+ j.set("effort", effort);
+ j.set("generatorService", generatorService);
+ j.set("generatorCommand", generatorCommand);
+ j.set("hfToken", hfToken);
+ j.set("hfModel", hfModel);
+ j.set("falKey", falKey);
+ j.set("falModel", falModel);
+ j.set("falEndpoint", falEndpoint);
+ j.set("meshyKey", meshyKey);
+ j.set("meshyModel", meshyModel);
+ j.set("meshyEndpoint", meshyEndpoint);
+ return j;
+}
+
+AiSettings AiSettings::fromJson(const Json& j) {
+ Provider p = j["provider"].asString() == "openai-compatible" ? Provider::OpenAICompatible : Provider::Anthropic;
+ AiSettings s = defaults(p);
+ if (!j["endpoint"].asString().empty()) s.endpoint = j["endpoint"].asString();
+ if (!j["model"].asString().empty()) s.model = j["model"].asString();
+ s.apiKey = j["apiKey"].asString();
+ if (!j["effort"].asString().empty()) s.effort = j["effort"].asString();
+ s.generatorCommand = j["generatorCommand"].asString();
+ auto text = [&](const char* key, std::string& field) {
+ if (!j[key].asString().empty()) field = j[key].asString();
+ };
+ text("generatorService", s.generatorService);
+ text("hfToken", s.hfToken);
+ text("hfModel", s.hfModel);
+ text("falKey", s.falKey);
+ text("falModel", s.falModel);
+ text("falEndpoint", s.falEndpoint);
+ text("meshyKey", s.meshyKey);
+ text("meshyModel", s.meshyModel);
+ text("meshyEndpoint", s.meshyEndpoint);
+ return s;
+}
+
+bool AiSettings::save(const std::string& path, std::string& error) const {
+ const auto p = utf8Path(path);
+ {
+ std::ofstream f(p, std::ios::binary | std::ios::trunc);
+ if (!f) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ f << toJson().dump(true) << "\n";
+ }
+ std::error_code ec;
+ std::filesystem::permissions(p, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
+ std::filesystem::perm_options::replace, ec);
+ return true;
+}
+
+AiSettings AiSettings::load(const std::string& path) {
+ // Settings from before the rename (OpenSculpt) move over on first use.
+ if (const size_t at = path.find("SculptForge"); at != std::string::npos) {
+ std::string legacy = path;
+ for (size_t p = legacy.find("SculptForge"); p != std::string::npos; p = legacy.find("SculptForge", p + 10))
+ legacy.replace(p, 11, "OpenSculpt");
+ std::error_code ec;
+ if (!std::filesystem::exists(utf8Path(path), ec) && std::filesystem::exists(utf8Path(legacy), ec)) {
+ std::filesystem::create_directories(utf8Path(path).parent_path(), ec);
+ std::filesystem::copy_file(utf8Path(legacy), utf8Path(path), ec);
+ }
+ }
+ std::ifstream f(utf8Path(path), std::ios::binary);
+ if (!f) return defaults(Provider::Anthropic);
+ std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ Json j;
+ std::string err;
+ if (!Json::parse(text, j, err)) return defaults(Provider::Anthropic);
+ return fromJson(j);
+}
+
+std::string defaultAiSettingsPath() {
+ auto env = [](const char* name) -> std::string {
+ const char* v = std::getenv(name);
+ return v ? v : "";
+ };
+#if defined(_WIN32)
+ const std::string base = env("APPDATA");
+ return base.empty() ? "ai.json" : base + "\\SculptForge\\SculptForge\\ai.json";
+#elif defined(__APPLE__)
+ return env("HOME") + "/Library/Application Support/SculptForge/SculptForge/ai.json";
+#else
+ const std::string xdg = env("XDG_DATA_HOME");
+ return (xdg.empty() ? env("HOME") + "/.local/share" : xdg) + "/SculptForge/SculptForge/ai.json";
+#endif
+}
+
+std::string brushSystemPrompt() {
+ std::string p =
+ "You are the brush designer inside SculptForge, a digital sculpting app used by character, creature and "
+ "environment artists. Artists describe the brush they want in their own words - the feel, the material, "
+ "the mark it should leave, sometimes a reference like 'like a palette knife' or 'dry cracked mud'. You "
+ "translate that into a brush recipe: a set of numeric and named parameters the sculpting engine "
+ "understands. You never write code.\n\n"
+ "Think like a sculptor: what does the tool do to the clay? Does it add or carve, cut crisp lines or soft "
+ "forms, leave texture, follow the stroke? Choose parameters that produce that mark, keep everything else "
+ "neutral (0 or 'none'), and prefer subtle values - artists can turn things up.\n\n"
+ "When the artist asks for a change to the current brush ('sharper', 'less buildup', 'grittier'), start "
+ "from the current recipe they send and change only what they asked for. Keep the same name unless they "
+ "want a new brush.\n\n"
+ "Parameters:\n";
+ for (const auto& rp : recipeParams()) {
+ p += "- ";
+ p += rp.key;
+ p += ": ";
+ p += rp.help;
+ p += "\n";
+ }
+ p += "\nExamples of good recipes:\n";
+ auto examples = builtinBrushRecipes();
+ for (size_t i = 0; i < 3 && i < examples.size(); ++i) p += examples[i].toJson().dump() + "\n";
+ p += "\nRespond with only a JSON object of the form {\"reply\": string, \"brush\": recipe}. 'reply' is 1-3 "
+ "friendly sentences to the artist describing the brush and one thing they could tweak. 'brush' contains "
+ "every parameter listed above plus 'name' and 'description'.";
+ return p;
+}
+
+ChatMessage composeUserMessage(const std::string& request, const BrushRecipe* current) {
+ ChatMessage m{ChatMessage::Role::User, {}, request};
+ if (current)
+ m.text = "Current brush recipe (edit it if I'm asking for a change):\n" + current->toJson().dump() +
+ "\n\nMy request: " + request;
+ else
+ m.text = request;
+ return m;
+}
+
+std::string requestUrl(const AiSettings& s) { return s.endpoint; }
+
+std::vector<std::string> requestHeaders(const AiSettings& s) {
+ std::vector<std::string> h = {"Content-Type: application/json"};
+ const std::string key = s.resolvedKey();
+ if (s.provider == AiSettings::Provider::Anthropic) {
+ h.push_back("x-api-key: " + key);
+ h.push_back("anthropic-version: 2023-06-01");
+ h.push_back("anthropic-beta: server-side-fallback-2026-07-01");
+ } else if (!key.empty()) {
+ h.push_back("Authorization: Bearer " + key);
+ }
+ return h;
+}
+
+std::string buildRequestBody(const AiSettings& s, const std::vector<ChatMessage>& history) {
+ Json body = Json::object();
+ body.set("model", s.model);
+ Json messages = Json::array();
+ if (s.provider == AiSettings::Provider::Anthropic) {
+ body.set("max_tokens", 16000);
+ body.set("system", brushSystemPrompt());
+ body.set("fallbacks", "default");
+ Json format = Json::object();
+ format.set("type", "json_schema");
+ format.set("schema", responseSchema());
+ Json outputConfig = Json::object();
+ outputConfig.set("effort", s.effort.empty() ? "low" : s.effort);
+ outputConfig.set("format", format);
+ body.set("output_config", outputConfig);
+ } else {
+ Json sys = Json::object();
+ sys.set("role", "system");
+ sys.set("content", brushSystemPrompt());
+ messages.push(sys);
+ }
+ for (const auto& m : history) {
+ Json msg = Json::object();
+ msg.set("role", m.role == ChatMessage::Role::User ? "user" : "assistant");
+ msg.set("content", m.text);
+ messages.push(msg);
+ }
+ body.set("messages", messages);
+ return body.dump();
+}
+
+BrushSuggestion parseResponse(const AiSettings& s, long httpStatus, const std::string& body,
+ std::string* rawAssistantJson) {
+ BrushSuggestion out;
+ Json j;
+ std::string err;
+ const bool parsed = Json::parse(body, j, err);
+
+ if (httpStatus < 200 || httpStatus >= 300) {
+ std::string msg = parsed ? apiErrorMessage(j) : std::string();
+ if (httpStatus == 401 || httpStatus == 403) msg = "The API key was rejected. " + msg;
+ else if (httpStatus == 429) msg = "Rate limited by the provider - wait a moment and try again. " + msg;
+ else if (httpStatus == 404) msg = "Endpoint or model not found - check the AI settings. " + msg;
+ out.error = "HTTP " + std::to_string(httpStatus) + ": " + (msg.empty() ? body.substr(0, 300) : msg);
+ return out;
+ }
+ if (!parsed) {
+ out.error = "Unreadable response from the provider: " + err;
+ return out;
+ }
+
+ std::string text;
+ if (s.provider == AiSettings::Provider::Anthropic) {
+ if (j["stop_reason"].asString() == "refusal") {
+ out.error = "The model declined this request. Try describing the brush differently.";
+ return out;
+ }
+ for (const auto& block : j["content"].items())
+ if (block["type"].asString() == "text") text += block["text"].asString();
+ if (j["stop_reason"].asString() == "max_tokens" && text.empty()) {
+ out.error = "The response was cut off before a brush was produced.";
+ return out;
+ }
+ } else {
+ text = j["choices"][0]["message"]["content"].asString();
+ }
+
+ Json result;
+ if (!extractJsonObject(text, result, out.error)) return out;
+ // Accept either {"reply", "brush"} or a bare recipe from less obedient local models.
+ const Json& recipeJson = result["brush"].isObject() ? result["brush"] : result;
+ out.recipe = BrushRecipe::fromJson(recipeJson);
+ out.reply = result["reply"].isString() ? result["reply"].asString() : out.recipe.description;
+ out.ok = true;
+ if (rawAssistantJson) *rawAssistantJson = text;
+ return out;
+}
+
+BrushSuggestion requestBrush(const AiSettings& s, const std::vector<ChatMessage>& history,
+ std::string* rawAssistantJson) {
+ if (s.provider == AiSettings::Provider::Anthropic && s.resolvedKey().empty()) {
+ BrushSuggestion out;
+ out.error = "No Anthropic API key - add one in AI settings or set ANTHROPIC_API_KEY.";
+ return out;
+ }
+ HttpResponse r = httpPostJson(requestUrl(s), requestHeaders(s), buildRequestBody(s, history));
+ if (!r.error.empty()) {
+ BrushSuggestion out;
+ out.error = "Could not reach " + s.endpoint + ": " + r.error;
+ return out;
+ }
+ return parseResponse(s, r.status, r.body, rawAssistantJson);
+}
+
+} // namespace sf::ai
diff --git a/src/ai/BrushAssistant.h b/src/ai/BrushAssistant.h
new file mode 100644
index 00000000..ec769074
--- /dev/null
+++ b/src/ai/BrushAssistant.h
@@ -0,0 +1,83 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Bring-your-own-AI brush designer: turns an artist's description ("sharp
+// wrinkles that fade out", "make it grittier") into a BrushRecipe. Works with
+// Anthropic's API or any OpenAI-compatible endpoint (OpenAI, Ollama, LM
+// Studio, OpenRouter, ...). The model only ever returns recipe data.
+#pragma once
+
+#include "core/BrushRecipe.h"
+
+#include <string>
+#include <vector>
+
+namespace sf::ai {
+
+struct AiSettings {
+ enum class Provider { Anthropic, OpenAICompatible };
+ Provider provider = Provider::Anthropic;
+ std::string endpoint;
+ std::string model;
+ std::string apiKey; // empty = use ANTHROPIC_API_KEY / OPENAI_API_KEY from the environment
+ std::string effort = "low";
+ // Image to 3D. service: "huggingface" (free Spaces), "fal", "meshy",
+ // "command" (generatorCommand with {input}/{output}) or "inflate" (offline).
+ std::string generatorService = "huggingface";
+ std::string hfToken; // empty = HF_TOKEN from the environment (optional; raises the free quota)
+ std::string hfModel = "hunyuan3d-2.1";
+ std::string generatorCommand;
+ std::string falKey; // empty = FAL_KEY from the environment
+ std::string falModel = "fal-ai/trellis-2";
+ std::string falEndpoint = "https://queue.fal.run";
+ std::string meshyKey; // empty = MESHY_API_KEY from the environment
+ std::string meshyModel = "latest";
+ std::string meshyEndpoint = "https://api.meshy.ai";
+ std::string resolvedFalKey() const;
+ std::string resolvedHfToken() const;
+ std::string resolvedMeshyKey() const;
+
+ static AiSettings defaults(Provider provider);
+ std::string resolvedKey() const;
+
+ Json toJson() const;
+ static AiSettings fromJson(const Json& j);
+ // Stored in the user's config directory with owner-only permissions.
+ bool save(const std::string& path, std::string& error) const;
+ static AiSettings load(const std::string& path);
+};
+
+struct ChatMessage {
+ enum class Role { User, Assistant } role;
+ std::string text; // exactly what is sent to the model (history is append-only)
+ std::string display; // what the chat panel shows
+};
+
+struct BrushSuggestion {
+ bool ok = false;
+ std::string reply; // short artist-facing explanation
+ BrushRecipe recipe;
+ std::string error;
+};
+
+// Where the app keeps ai.json (same location as SDL_GetPrefPath("SculptForge", "SculptForge")).
+std::string defaultAiSettingsPath();
+
+std::string brushSystemPrompt();
+// The user turn to send: the artist's words plus the brush currently being edited.
+ChatMessage composeUserMessage(const std::string& request, const BrushRecipe* current);
+
+// Request pieces (exposed for tests).
+std::string requestUrl(const AiSettings& s);
+std::vector<std::string> requestHeaders(const AiSettings& s);
+std::string buildRequestBody(const AiSettings& s, const std::vector<ChatMessage>& history);
+// `rawAssistantJson` receives the model's JSON text, to append to the history.
+BrushSuggestion parseResponse(const AiSettings& s, long httpStatus, const std::string& body,
+ std::string* rawAssistantJson = nullptr);
+
+// Blocking (run on a worker thread): sends the conversation, whose last
+// message must be the user's, and returns a recipe.
+BrushSuggestion requestBrush(const AiSettings& s, const std::vector<ChatMessage>& history,
+ std::string* rawAssistantJson);
+
+} // namespace sf::ai
diff --git a/src/ai/Generator3D.cpp b/src/ai/Generator3D.cpp
new file mode 100644
index 00000000..efd1159e
--- /dev/null
+++ b/src/ai/Generator3D.cpp
@@ -0,0 +1,85 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/Generator3D.h"
+
+#include <cstdlib>
+#include <filesystem>
+
+namespace sf::ai {
+
+namespace {
+
+std::string shellQuote(const std::string& s) {
+#if defined(_WIN32)
+ std::string out = "\"";
+ for (char c : s) {
+ if (c == '"') out += "\\\"";
+ else out += c;
+ }
+ return out + "\"";
+#else
+ std::string out = "'";
+ for (char c : s) {
+ if (c == '\'') out += "'\\''";
+ else out += c;
+ }
+ return out + "'";
+#endif
+}
+
+void replaceAll(std::string& s, const std::string& from, const std::string& to) {
+ for (size_t pos = s.find(from); pos != std::string::npos; pos = s.find(from, pos + to.size()))
+ s.replace(pos, from.size(), to);
+}
+
+} // namespace
+
+std::string defaultGeneratorCommand(const std::string& cliPath) {
+#if defined(_WIN32)
+ return shellQuote(cliPath) +
+ " --set input={input} --set output={output} -c \"image_inflate path=$input subdivisions=2; export_glb "
+ "path=$output\"";
+#else
+ return shellQuote(cliPath) +
+ " --set input={input} --set output={output} -c 'image_inflate path=$input subdivisions=2; export_glb "
+ "path=$output'";
+#endif
+}
+
+std::string expandGeneratorCommand(const std::string& commandTemplate, const std::string& input,
+ const std::string& output) {
+ std::string cmd = commandTemplate;
+ replaceAll(cmd, "{input}", shellQuote(input));
+ replaceAll(cmd, "{output}", shellQuote(output));
+ return cmd;
+}
+
+GeneratorResult runGenerator(const std::string& commandTemplate, const std::string& imagePath,
+ const std::string& outputPath) {
+ GeneratorResult r;
+ if (commandTemplate.find("{input}") == std::string::npos || commandTemplate.find("{output}") == std::string::npos) {
+ r.error = "The generator command must contain {input} and {output}";
+ return r;
+ }
+ const std::filesystem::path out(std::u8string(outputPath.begin(), outputPath.end()));
+ std::error_code ec;
+ std::filesystem::remove(out, ec);
+ std::string cmd = expandGeneratorCommand(commandTemplate, imagePath, outputPath);
+#if defined(_WIN32)
+ cmd = "\"" + cmd + "\""; // cmd.exe strips one level of outer quotes
+#endif
+ const int status = std::system(cmd.c_str());
+ if (status != 0) {
+ r.error = "The generator exited with status " + std::to_string(status);
+ return r;
+ }
+ if (!std::filesystem::exists(out, ec) || std::filesystem::file_size(out, ec) == 0) {
+ r.error = "The generator finished but did not write " + outputPath;
+ return r;
+ }
+ r.ok = true;
+ r.outputPath = outputPath;
+ return r;
+}
+
+} // namespace sf::ai
diff --git a/src/ai/Generator3D.h b/src/ai/Generator3D.h
new file mode 100644
index 00000000..edaca2ea
--- /dev/null
+++ b/src/ai/Generator3D.h
@@ -0,0 +1,30 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Bring-your-own image-to-3D generator. SculptForge runs a user-configured
+// command with {input} (the image) and {output} (where to write a .glb/.obj),
+// then imports the result for sculpting. Point it at a local open-source model
+// (TRELLIS, Hunyuan3D-2, TripoSR, Stable Fast 3D...) or a script that calls a
+// cloud service. The built-in default inflates the image's silhouette using
+// sculptforge-cli, so the pipeline works out of the box with no GPU or network.
+#pragma once
+
+#include <string>
+
+namespace sf::ai {
+
+struct GeneratorResult {
+ bool ok = false;
+ std::string outputPath;
+ std::string error;
+};
+
+std::string defaultGeneratorCommand(const std::string& cliPath);
+// Placeholders {input} and {output} are replaced with shell-quoted paths.
+std::string expandGeneratorCommand(const std::string& commandTemplate, const std::string& input,
+ const std::string& output);
+// Blocking; run on a worker thread.
+GeneratorResult runGenerator(const std::string& commandTemplate, const std::string& imagePath,
+ const std::string& outputPath);
+
+} // namespace sf::ai
diff --git a/src/ai/GradioClient.cpp b/src/ai/GradioClient.cpp
new file mode 100644
index 00000000..6c88873a
--- /dev/null
+++ b/src/ai/GradioClient.cpp
@@ -0,0 +1,224 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/GradioClient.h"
+
+#include "ai/Http.h"
+
+#include <chrono>
+#include <random>
+
+namespace sf::ai {
+
+namespace {
+
+std::string randomHash() {
+ std::random_device rd;
+ std::mt19937_64 rng((uint64_t(rd()) << 32) ^ rd() ^ uint64_t(std::chrono::steady_clock::now().time_since_epoch().count()));
+ const char* chars = "abcdefghijklmnopqrstuvwxyz0123456789";
+ std::string h;
+ for (int i = 0; i < 11; ++i) h += chars[rng() % 36];
+ return h;
+}
+
+bool isFileData(const Json& v) { return v.isObject() && (v["path"].isString() || v["url"].isString()); }
+
+// Gradio may wrap returned values as {"__type__": "update", "value": ...}.
+const Json& unwrap(const Json& v) { return v.isObject() && v["value"].isObject() ? v["value"] : v; }
+
+} // namespace
+
+std::string friendlyGradioError(const std::string& raw) {
+ if (raw.find("ZeroGPU") != std::string::npos || raw.find("GPU quota") != std::string::npos)
+ return "Hugging Face's free GPU time is used up for now. Add a free Hugging Face token "
+ "(huggingface.co/settings/tokens) for a bigger daily allowance, wait for it to refill, or pick another model. (" +
+ raw.substr(0, 160) + ")";
+ if (raw.find("503") != std::string::npos || raw.find("Space is") != std::string::npos)
+ return "The Hugging Face Space is asleep or restarting - try again in a minute, or pick another model. (" +
+ raw.substr(0, 160) + ")";
+ return raw;
+}
+
+std::vector<std::string> GradioClient::headers(bool json) const {
+ std::vector<std::string> h;
+ if (json) h.push_back("Content-Type: application/json");
+ if (!token_.empty()) h.push_back("Authorization: Bearer " + token_);
+ return h;
+}
+
+bool GradioClient::connect(const std::string& spaceUrl, const std::string& token, std::string& error) {
+ root_ = spaceUrl;
+ while (!root_.empty() && root_.back() == '/') root_.pop_back();
+ token_ = token;
+ sessionHash_ = randomHash();
+ HttpResponse r = httpRequest("GET", root_ + "/config", headers(false), {}, 60);
+ if (!r.error.empty()) {
+ error = "Cannot reach " + root_ + ": " + r.error;
+ return false;
+ }
+ std::string err;
+ if (r.status != 200 || !Json::parse(r.body, config_, err) || !config_["dependencies"].isArray()) {
+ error = friendlyGradioError("HTTP " + std::to_string(r.status) + " from " + root_ + " (Space is unavailable)");
+ return false;
+ }
+ prefix_ = config_["api_prefix"].isString() ? config_["api_prefix"].asString() : std::string();
+ if (prefix_ == "/") prefix_.clear();
+ return true;
+}
+
+bool GradioClient::upload(const std::string& bytes, const std::string& fileName, Json& fileData, std::string& error) {
+ const std::string boundary = "----sculptforge" + randomHash();
+ std::string body = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"files\"; filename=\"" + fileName +
+ "\"\r\nContent-Type: application/octet-stream\r\n\r\n" + bytes + "\r\n--" + boundary + "--\r\n";
+ auto h = headers(false);
+ h.push_back("Content-Type: multipart/form-data; boundary=" + boundary);
+ HttpResponse r = httpRequest("POST", root_ + prefix_ + "/upload", h, body, 120);
+ Json paths;
+ std::string err;
+ if (!r.error.empty() || r.status != 200 || !Json::parse(r.body, paths, err) || !paths[0].isString()) {
+ error = "Upload to " + root_ + " failed: " + (r.error.empty() ? "HTTP " + std::to_string(r.status) + " " + r.body.substr(0, 200) : r.error);
+ return false;
+ }
+ fileData = Json::object();
+ fileData.set("path", paths[0].asString());
+ Json meta = Json::object();
+ meta.set("_type", "gradio.FileData");
+ fileData.set("meta", meta);
+ fileData.set("orig_name", fileName);
+ return true;
+}
+
+std::string GradioClient::fileUrl(const Json& value) const {
+ const Json& v = unwrap(value);
+ if (v["url"].isString() && !v["url"].asString().empty()) return v["url"].asString();
+ return root_ + prefix_ + "/file=" + v["path"].asString();
+}
+
+bool GradioClient::call(const std::string& apiName, const std::vector<Json>& userArgs, std::vector<Json>& outputs,
+ std::string& error, const std::function<void(const std::string&)>& onStatus) {
+ // Find the endpoint and build the full input list.
+ const Json& deps = config_["dependencies"];
+ const Json* dep = nullptr;
+ int fnIndex = -1;
+ for (size_t i = 0; i < deps.size(); ++i)
+ if (deps[i]["api_name"].asString() == apiName) {
+ dep = &deps[i];
+ fnIndex = deps[i]["id"].isNumber() ? int(deps[i]["id"].asNumber()) : int(i);
+ break;
+ }
+ if (!dep) {
+ error = "This Space has no '" + apiName + "' endpoint (it may have changed)";
+ return false;
+ }
+ auto component = [&](double id) -> const Json* {
+ for (const auto& c : config_["components"].items())
+ if (c["id"].asNumber() == id) return &c;
+ return nullptr;
+ };
+ Json data = Json::array();
+ size_t next = 0;
+ for (const auto& id : (*dep)["inputs"].items()) {
+ const Json* c = component(id.asNumber());
+ const std::string type = c ? (*c)["type"].asString() : std::string();
+ const Json fallback = c ? (*c)["props"]["value"] : Json();
+ if (type == "state") data.push(fallback); // hidden from the public API; the server keeps it per session
+ else if (next < userArgs.size()) data.push(userArgs[next++]);
+ else data.push(fallback);
+ }
+
+ Json join = Json::object();
+ join.set("data", data);
+ join.set("event_data", Json());
+ join.set("fn_index", fnIndex);
+ join.set("trigger_id", Json());
+ join.set("session_hash", sessionHash_);
+ HttpResponse r = httpRequest("POST", root_ + prefix_ + "/queue/join", headers(true), join.dump(), 60);
+ Json joined;
+ std::string err;
+ if (!r.error.empty() || r.status != 200 || !Json::parse(r.body, joined, err)) {
+ error = friendlyGradioError("Could not join the queue: " + (r.error.empty() ? "HTTP " + std::to_string(r.status) + " " + r.body.substr(0, 200) : r.error));
+ return false;
+ }
+ const std::string eventId = joined["event_id"].asString();
+
+ // Read server-sent events until our event completes.
+ std::string buffer;
+ bool done = false, ok = false;
+ auto h = headers(false);
+ h.push_back("Accept: text/event-stream");
+ HttpResponse s = httpRequestStream(
+ "GET", root_ + prefix_ + "/queue/data?session_hash=" + sessionHash_, h, {}, 900, [&](const char* d, size_t n) {
+ buffer.append(d, n);
+ size_t eol;
+ while ((eol = buffer.find('\n')) != std::string::npos) {
+ std::string line = buffer.substr(0, eol);
+ buffer.erase(0, eol + 1);
+ if (line.rfind("data:", 0) != 0) continue;
+ Json m;
+ if (!Json::parse(line.substr(5), m, err)) continue;
+ if (!eventId.empty() && m["event_id"].isString() && m["event_id"].asString() != eventId) continue;
+ const std::string msg = m["msg"].asString();
+ if (msg == "estimation" && onStatus) {
+ const int rank = int(m["rank"].asNumber(0));
+ onStatus(rank > 0 ? "In the free queue: " + std::to_string(rank) + " ahead of you" : "Starting...");
+ } else if (msg == "process_starts" && onStatus) {
+ onStatus("Generating on " + root_.substr(root_.find("//") + 2) + "...");
+ } else if (msg == "progress" && onStatus) {
+ const Json& p = m["progress_data"][0];
+ if (p.isObject()) {
+ std::string text = p["desc"].isString() ? p["desc"].asString() : "Working";
+ if (p["index"].isNumber() && p["length"].isNumber())
+ text += " " + std::to_string(int(p["index"].asNumber())) + "/" + std::to_string(int(p["length"].asNumber()));
+ onStatus(text);
+ }
+ } else if (msg == "process_completed") {
+ done = true;
+ ok = m["success"].asBool(false);
+ if (ok) {
+ outputs = m["output"]["data"].items();
+ } else {
+ const Json& o = m["output"];
+ error = friendlyGradioError(o["error"].isString() ? o["error"].asString()
+ : m["title"].isString() ? m["title"].asString()
+ : std::string("The Space reported an error"));
+ }
+ return false; // stop reading
+ } else if (msg == "close_stream") {
+ return false;
+ }
+ }
+ return true;
+ });
+ if (!done) {
+ error = friendlyGradioError(s.error.empty() ? "The Space closed the connection without a result" : "Connection lost: " + s.error);
+ return false;
+ }
+ if (!ok) return false;
+
+ // Remember the first 3D model (or file) output.
+ lastModelUrl_.clear();
+ const Json& outs = (*dep)["outputs"];
+ for (int pass = 0; pass < 2 && lastModelUrl_.empty(); ++pass)
+ for (size_t i = 0; i < outputs.size() && i < outs.size(); ++i) {
+ const Json* c = component(outs[i].asNumber());
+ const std::string type = c ? (*c)["type"].asString() : std::string();
+ const bool modelType = type == "model3d" || type == "litmodel3d";
+ if ((pass == 0 && modelType) || (pass == 1 && type == "file"))
+ if (isFileData(unwrap(outputs[i]))) {
+ lastModelUrl_ = fileUrl(outputs[i]);
+ break;
+ }
+ }
+ return true;
+}
+
+bool GradioClient::download(const std::string& url, std::string& bytes, std::string& error) {
+ HttpResponse r = httpRequest("GET", url, headers(false), {}, 300);
+ if (!r.error.empty() || r.status != 200 || r.body.empty()) {
+ error = "Download failed: " + (r.error.empty() ? "HTTP " + std::to_string(r.status) : r.error);
+ return false;
+ }
+ bytes = std::move(r.body);
+ return true;
+}
+
+} // namespace sf::ai
diff --git a/src/ai/GradioClient.h b/src/ai/GradioClient.h
new file mode 100644
index 00000000..5f1485fb
--- /dev/null
+++ b/src/ai/GradioClient.h
@@ -0,0 +1,53 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Minimal client for Gradio apps (Hugging Face Spaces), speaking Gradio's
+// queue protocol directly: upload a file, join the queue with a session hash
+// (so multi-step apps keep their state), and read the server-sent events
+// until the result arrives. Works with Gradio 4.x and 5/6.x apps.
+#pragma once
+
+#include "core/Json.h"
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf::ai {
+
+class GradioClient {
+public:
+ // `spaceUrl`, e.g. https://tencent-hunyuan3d-2-1.hf.space. `token` (optional) is a
+ // Hugging Face access token; on ZeroGPU Spaces it raises the free GPU quota.
+ bool connect(const std::string& spaceUrl, const std::string& token, std::string& error);
+
+ // Uploads a file and returns its Gradio FileData object.
+ bool upload(const std::string& bytes, const std::string& fileName, Json& fileData, std::string& error);
+
+ // Runs the endpoint `apiName`. `args` fill the non-state inputs in order (buttons
+ // included: their value is their label); state inputs come from the session and any
+ // missing trailing inputs take the app's own defaults. `outputs` receives every output
+ // value; `onStatus` gets queue/progress text.
+ bool call(const std::string& apiName, const std::vector<Json>& args, std::vector<Json>& outputs, std::string& error,
+ const std::function<void(const std::string&)>& onStatus = {});
+
+ // The first 3D model / file output of the last call, as a downloadable URL.
+ std::string lastModelUrl() const { return lastModelUrl_; }
+ // Downloads `url` (with the token, if any).
+ bool download(const std::string& url, std::string& bytes, std::string& error);
+
+ const std::string& root() const { return root_; }
+
+private:
+ std::vector<std::string> headers(bool json) const;
+ std::string fileUrl(const Json& value) const;
+
+ std::string root_, prefix_, token_, sessionHash_;
+ Json config_;
+ std::string lastModelUrl_;
+};
+
+// Turns Gradio/ZeroGPU failures into advice for artists.
+std::string friendlyGradioError(const std::string& raw);
+
+} // namespace sf::ai
diff --git a/src/ai/Http.cpp b/src/ai/Http.cpp
new file mode 100644
index 00000000..510569a5
--- /dev/null
+++ b/src/ai/Http.cpp
@@ -0,0 +1,182 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/Http.h"
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <winhttp.h>
+#elif defined(SF_HAVE_CURL)
+#include <curl/curl.h>
+#include <mutex>
+#endif
+
+namespace sf::ai {
+
+HttpResponse httpRequest(const std::string& method, const std::string& url, const std::vector<std::string>& headers,
+ const std::string& body, int timeoutSeconds) {
+ std::string received;
+ HttpResponse r = httpRequestStream(method, url, headers, body, timeoutSeconds, [&](const char* d, size_t n) {
+ received.append(d, n);
+ return true;
+ });
+ r.body = std::move(received);
+ return r;
+}
+
+#if defined(_WIN32)
+
+namespace {
+
+std::wstring widen(const std::string& s) {
+ if (s.empty()) return {};
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), int(s.size()), nullptr, 0);
+ std::wstring w(size_t(n), L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.data(), int(s.size()), w.data(), n);
+ return w;
+}
+
+std::string lastError(const char* what) { return std::string(what) + " failed (error " + std::to_string(GetLastError()) + ")"; }
+
+struct Handle {
+ HINTERNET h = nullptr;
+ ~Handle() {
+ if (h) WinHttpCloseHandle(h);
+ }
+};
+
+} // namespace
+
+HttpResponse httpRequestStream(const std::string& method, const std::string& url, const std::vector<std::string>& headers,
+ const std::string& body, int timeoutSeconds,
+ const std::function<bool(const char*, size_t)>& onData) {
+ HttpResponse r;
+ std::wstring wurl = widen(url);
+ URL_COMPONENTS uc{};
+ uc.dwStructSize = sizeof uc;
+ wchar_t host[256] = {}, path[8192] = {};
+ uc.lpszHostName = host;
+ uc.dwHostNameLength = 256;
+ uc.lpszUrlPath = path;
+ uc.dwUrlPathLength = 8192;
+ if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &uc)) {
+ r.error = "Invalid URL: " + url;
+ return r;
+ }
+ // WinHttpCrackUrl splits the query off the path; put it back.
+ std::wstring fullPath = path;
+ if (uc.lpszExtraInfo && uc.dwExtraInfoLength) fullPath.append(uc.lpszExtraInfo, uc.dwExtraInfoLength);
+
+ Handle session{WinHttpOpen(L"SculptForge/0.1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME,
+ WINHTTP_NO_PROXY_BYPASS, 0)};
+ if (!session.h) {
+ r.error = lastError("WinHttpOpen");
+ return r;
+ }
+ const int ms = timeoutSeconds * 1000;
+ WinHttpSetTimeouts(session.h, ms, ms, ms, ms);
+ Handle connection{WinHttpConnect(session.h, host, uc.nPort, 0)};
+ if (!connection.h) {
+ r.error = lastError("WinHttpConnect");
+ return r;
+ }
+ const DWORD flags = uc.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0;
+ Handle request{WinHttpOpenRequest(connection.h, widen(method).c_str(), fullPath.c_str(), nullptr, WINHTTP_NO_REFERER,
+ WINHTTP_DEFAULT_ACCEPT_TYPES, flags)};
+ if (!request.h) {
+ r.error = lastError("WinHttpOpenRequest");
+ return r;
+ }
+ std::wstring allHeaders;
+ for (const auto& h : headers) allHeaders += widen(h) + L"\r\n";
+ if (!WinHttpSendRequest(request.h, allHeaders.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : allHeaders.c_str(), DWORD(-1L),
+ const_cast<char*>(body.data()), DWORD(body.size()), DWORD(body.size()), 0) ||
+ !WinHttpReceiveResponse(request.h, nullptr)) {
+ r.error = lastError("HTTP request");
+ return r;
+ }
+ DWORD status = 0, size = sizeof status;
+ WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
+ &status, &size, WINHTTP_NO_HEADER_INDEX);
+ r.status = long(status);
+ while (true) {
+ DWORD available = 0;
+ if (!WinHttpQueryDataAvailable(request.h, &available) || available == 0) break;
+ std::string chunk(available, '\0');
+ DWORD read = 0;
+ if (!WinHttpReadData(request.h, chunk.data(), available, &read) || read == 0) break;
+ if (!onData(chunk.data(), read)) break;
+ }
+ return r;
+}
+
+#elif defined(SF_HAVE_CURL)
+
+namespace {
+
+struct StreamSink {
+ const std::function<bool(const char*, size_t)>* onData;
+ bool stopped = false;
+};
+
+size_t writeCallback(char* data, size_t size, size_t count, void* user) {
+ auto* sink = static_cast<StreamSink*>(user);
+ if (!(*sink->onData)(data, size * count)) {
+ sink->stopped = true;
+ return 0; // abort the transfer
+ }
+ return size * count;
+}
+
+} // namespace
+
+HttpResponse httpRequestStream(const std::string& method, const std::string& url, const std::vector<std::string>& headers,
+ const std::string& body, int timeoutSeconds,
+ const std::function<bool(const char*, size_t)>& onData) {
+ static std::once_flag once;
+ std::call_once(once, [] { curl_global_init(CURL_GLOBAL_DEFAULT); });
+
+ HttpResponse r;
+ CURL* curl = curl_easy_init();
+ if (!curl) {
+ r.error = "curl_easy_init failed";
+ return r;
+ }
+ StreamSink sink{&onData};
+ curl_slist* list = nullptr;
+ for (const auto& h : headers) list = curl_slist_append(list, h.c_str());
+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
+ if (method == "POST") {
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.data());
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, long(body.size()));
+ } else {
+ curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
+ }
+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
+ curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sink);
+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, long(timeoutSeconds));
+ curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
+ curl_easy_setopt(curl, CURLOPT_USERAGENT, "SculptForge/0.1");
+ CURLcode rc = curl_easy_perform(curl);
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &r.status);
+ if (rc != CURLE_OK && !sink.stopped) r.error = curl_easy_strerror(rc);
+ curl_slist_free_all(list);
+ curl_easy_cleanup(curl);
+ return r;
+}
+
+#else
+
+HttpResponse httpRequestStream(const std::string&, const std::string&, const std::vector<std::string>&, const std::string&, int,
+ const std::function<bool(const char*, size_t)>&) {
+ HttpResponse r;
+ r.error = "This build of SculptForge has no HTTP support (libcurl was not found at build time)";
+ return r;
+}
+
+#endif
+
+} // namespace sf::ai
diff --git a/src/ai/Http.h b/src/ai/Http.h
new file mode 100644
index 00000000..80050417
--- /dev/null
+++ b/src/ai/Http.h
@@ -0,0 +1,36 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Minimal blocking HTTPS client. libcurl on Linux/macOS, WinHTTP on Windows,
+// so no extra dependency needs to be shipped. Call from a worker thread.
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf::ai {
+
+struct HttpResponse {
+ long status = 0; // 0 if the request never reached the server
+ std::string body;
+ std::string error; // transport error description
+};
+
+// `method` is "GET" or "POST"; `headers` are "Name: value" strings. Redirects
+// are followed (result files are usually served from a CDN).
+HttpResponse httpRequest(const std::string& method, const std::string& url, const std::vector<std::string>& headers,
+ const std::string& body = {}, int timeoutSeconds = 120);
+
+// Like httpRequest, but hands the body to `onData` as it arrives (server-sent
+// events, progress). Return false from `onData` to stop reading early.
+HttpResponse httpRequestStream(const std::string& method, const std::string& url, const std::vector<std::string>& headers,
+ const std::string& body, int timeoutSeconds,
+ const std::function<bool(const char* data, size_t size)>& onData);
+
+inline HttpResponse httpPostJson(const std::string& url, const std::vector<std::string>& headers, const std::string& body,
+ int timeoutSeconds = 120) {
+ return httpRequest("POST", url, headers, body, timeoutSeconds);
+}
+
+} // namespace sf::ai
diff --git a/src/ai/ImageTo3DService.cpp b/src/ai/ImageTo3DService.cpp
new file mode 100644
index 00000000..63ed6670
--- /dev/null
+++ b/src/ai/ImageTo3DService.cpp
@@ -0,0 +1,541 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "ai/ImageTo3DService.h"
+
+#include "ai/GradioClient.h"
+#include "ai/Http.h"
+#include "core/Image.h"
+#include "core/ImageTo3D.h"
+#include "io/GltfIO.h"
+
+#include <algorithm>
+#include <cctype>
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <functional>
+#include <thread>
+
+namespace sf::ai {
+
+namespace {
+
+constexpr int kPollSeconds = 3;
+constexpr int kMaxMinutes = 20;
+
+std::string apiError(const HttpResponse& r) {
+ Json j;
+ std::string err;
+ std::string detail;
+ if (Json::parse(r.body, j, err)) {
+ if (j["detail"].isString()) detail = j["detail"].asString();
+ else if (j["detail"].isArray() && j["detail"][0]["msg"].isString()) detail = j["detail"][0]["msg"].asString();
+ else if (j["message"].isString()) detail = j["message"].asString();
+ else if (j["error"].isString()) detail = j["error"].asString();
+ else if (j["error"]["message"].isString()) detail = j["error"]["message"].asString();
+ }
+ if (detail.empty()) detail = r.body.substr(0, 300);
+ switch (r.status) {
+ case 401:
+ case 403: return "The API key was rejected (" + detail + ")";
+ case 402: return "Out of credits on this account (" + detail + ")";
+ case 404: return "Model or endpoint not found - check the model id (" + detail + ")";
+ case 429: return "Rate limited - wait a moment and try again (" + detail + ")";
+ default: return "HTTP " + std::to_string(r.status) + ": " + detail;
+ }
+}
+
+// Sleeps for `seconds`, returning false early if cancelled.
+bool wait(GenerationProgress* p, int seconds) {
+ for (int i = 0; i < seconds * 10; ++i) {
+ if (p && p->cancel) return false;
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ }
+ return !(p && p->cancel);
+}
+
+void status(GenerationProgress* p, const std::string& text, int percent = -1) {
+ if (!p) return;
+ p->setStatus(text);
+ p->percent = percent;
+}
+
+bool download(const std::string& url, const std::string& outputStem, const std::string& extension,
+ GeneratorResult& result, GenerationProgress* p) {
+ status(p, "Downloading model...");
+ HttpResponse r = httpRequest("GET", url, {}, {}, 300);
+ if (!r.error.empty() || r.status < 200 || r.status >= 300 || r.body.empty()) {
+ result.error = "Download failed: " + (r.error.empty() ? "HTTP " + std::to_string(r.status) : r.error);
+ return false;
+ }
+ const std::string path = outputStem + extension;
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f || !f.write(r.body.data(), std::streamsize(r.body.size()))) {
+ result.error = "Cannot write " + path;
+ return false;
+ }
+ result.ok = true;
+ result.outputPath = path;
+ return true;
+}
+
+GeneratorResult runFalRequest(const AiSettings& s, const std::string& model, const std::string& body,
+ const std::string& outputStem, GenerationProgress* p);
+
+GeneratorResult runFal(const AiSettings& s, const std::string& imagePath, const std::string& outputStem,
+ GenerationProgress* p) {
+ GeneratorResult result;
+ if (s.resolvedFalKey().empty()) {
+ result.error = "Add your fal.ai API key (fal.ai/dashboard/keys) or set FAL_KEY";
+ return result;
+ }
+ std::string uri;
+ if (!prepareImageDataUri(imagePath, uri, result.error)) return result;
+ return runFalRequest(s, s.falModel, falSubmitBody(s.falModel, uri), outputStem, p);
+}
+
+GeneratorResult runFalRequest(const AiSettings& s, const std::string& model, const std::string& body,
+ const std::string& outputStem, GenerationProgress* p) {
+ GeneratorResult result;
+ const std::string key = s.resolvedFalKey();
+ if (key.empty()) {
+ result.error = "Add your fal.ai API key (fal.ai/dashboard/keys) or set FAL_KEY";
+ return result;
+ }
+ const std::vector<std::string> headers = {"Authorization: Key " + key, "Content-Type: application/json"};
+ std::string endpoint = s.falEndpoint;
+ while (!endpoint.empty() && endpoint.back() == '/') endpoint.pop_back();
+
+ status(p, "Sending to " + model + "...");
+ HttpResponse r = httpPostJson(endpoint + "/" + model, headers, body, 120);
+ if (!r.error.empty()) {
+ result.error = "Could not reach fal.ai: " + r.error;
+ return result;
+ }
+ if (r.status < 200 || r.status >= 300) {
+ result.error = apiError(r);
+ return result;
+ }
+ Json submitted;
+ std::string err;
+ if (!Json::parse(r.body, submitted, err) || !submitted["request_id"].isString()) {
+ result.error = "Unexpected reply from fal.ai: " + r.body.substr(0, 200);
+ return result;
+ }
+ // Status/result URLs use only the owner/app part of the model id; prefer the ones returned.
+ const std::string requestId = submitted["request_id"].asString();
+ const std::string app = model.substr(0, model.find('/', model.find('/') + 1));
+ const std::string statusUrl = submitted["status_url"].isString() ? submitted["status_url"].asString()
+ : endpoint + "/" + app + "/requests/" + requestId + "/status";
+ const std::string resultUrl = submitted["response_url"].isString() ? submitted["response_url"].asString()
+ : endpoint + "/" + app + "/requests/" + requestId;
+
+ const auto start = std::chrono::steady_clock::now();
+ while (true) {
+ if (!wait(p, kPollSeconds)) {
+ result.error = "Cancelled";
+ return result;
+ }
+ if (std::chrono::steady_clock::now() - start > std::chrono::minutes(kMaxMinutes)) {
+ result.error = "Timed out waiting for fal.ai";
+ return result;
+ }
+ HttpResponse st = httpRequest("GET", statusUrl, headers, {}, 60);
+ if (!st.error.empty()) continue; // transient network trouble: keep polling
+ if (st.status < 200 || st.status >= 300) {
+ result.error = apiError(st);
+ return result;
+ }
+ Json js;
+ if (!Json::parse(st.body, js, err)) continue;
+ const std::string state = js["status"].asString();
+ const int secs = int(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start).count());
+ if (state == "IN_QUEUE")
+ status(p, "Waiting in queue" + (js["queue_position"].isNumber()
+ ? " (position " + std::to_string(int(js["queue_position"].asNumber())) + ")"
+ : std::string()) + "... " + std::to_string(secs) + "s");
+ else if (state == "IN_PROGRESS") status(p, "Reconstructing 3D model... " + std::to_string(secs) + "s");
+ else if (state == "COMPLETED") break;
+ }
+
+ HttpResponse res = httpRequest("GET", resultUrl, headers, {}, 120);
+ if (!res.error.empty() || res.status < 200 || res.status >= 300) {
+ result.error = res.error.empty() ? apiError(res) : "Could not fetch the result: " + res.error;
+ return result;
+ }
+ Json out;
+ if (!Json::parse(res.body, out, err)) {
+ result.error = "Unreadable result from fal.ai";
+ return result;
+ }
+ std::string extension;
+ const std::string url = findModelUrl(out, &extension);
+ if (url.empty()) {
+ result.error = "The result contained no model file: " + res.body.substr(0, 200);
+ return result;
+ }
+ download(url, outputStem, extension, result, p);
+ return result;
+}
+
+GeneratorResult runMeshyRequest(const AiSettings& s, const std::string& taskPath, const std::string& body,
+ const std::string& outputStem, GenerationProgress* p);
+
+GeneratorResult runMeshy(const AiSettings& s, const std::string& imagePath, const std::string& outputStem,
+ GenerationProgress* p) {
+ GeneratorResult result;
+ if (s.resolvedMeshyKey().empty()) {
+ result.error = "Add your Meshy API key (meshy.ai > API) or set MESHY_API_KEY";
+ return result;
+ }
+ std::string uri;
+ if (!prepareImageDataUri(imagePath, uri, result.error)) return result;
+ return runMeshyRequest(s, "/openapi/v1/image-to-3d", meshySubmitBody(s.meshyModel, uri), outputStem, p);
+}
+
+GeneratorResult runMeshyRequest(const AiSettings& s, const std::string& taskPath, const std::string& body,
+ const std::string& outputStem, GenerationProgress* p) {
+ GeneratorResult result;
+ const std::string key = s.resolvedMeshyKey();
+ if (key.empty()) {
+ result.error = "Add your Meshy API key (meshy.ai > API) or set MESHY_API_KEY";
+ return result;
+ }
+ const std::vector<std::string> headers = {"Authorization: Bearer " + key, "Content-Type: application/json"};
+ std::string endpoint = s.meshyEndpoint;
+ while (!endpoint.empty() && endpoint.back() == '/') endpoint.pop_back();
+ const std::string tasks = endpoint + taskPath;
+
+ status(p, "Sending to Meshy...");
+ HttpResponse r = httpPostJson(tasks, headers, body, 120);
+ if (!r.error.empty()) {
+ result.error = "Could not reach Meshy: " + r.error;
+ return result;
+ }
+ if (r.status < 200 || r.status >= 300) {
+ result.error = apiError(r);
+ return result;
+ }
+ Json submitted;
+ std::string err;
+ if (!Json::parse(r.body, submitted, err) || !submitted["result"].isString()) {
+ result.error = "Unexpected reply from Meshy: " + r.body.substr(0, 200);
+ return result;
+ }
+ const std::string taskUrl = tasks + "/" + submitted["result"].asString();
+ const auto start = std::chrono::steady_clock::now();
+ while (true) {
+ if (!wait(p, kPollSeconds)) {
+ result.error = "Cancelled (the Meshy task keeps running on their side)";
+ return result;
+ }
+ if (std::chrono::steady_clock::now() - start > std::chrono::minutes(kMaxMinutes)) {
+ result.error = "Timed out waiting for Meshy";
+ return result;
+ }
+ HttpResponse st = httpRequest("GET", taskUrl, headers, {}, 60);
+ if (!st.error.empty()) continue;
+ if (st.status < 200 || st.status >= 300) {
+ result.error = apiError(st);
+ return result;
+ }
+ Json task;
+ if (!Json::parse(st.body, task, err)) continue;
+ const std::string state = task["status"].asString();
+ const int pct = int(task["progress"].asNumber(-1));
+ if (state == "SUCCEEDED") {
+ std::string extension;
+ const std::string url = findModelUrl(task["model_urls"], &extension);
+ if (url.empty()) {
+ result.error = "Meshy finished but returned no GLB";
+ return result;
+ }
+ download(url, outputStem, extension, result, p);
+ return result;
+ }
+ if (state == "FAILED" || state == "CANCELED") {
+ const std::string msg = task["task_error"]["message"].asString();
+ result.error = "Meshy " + state + (msg.empty() ? std::string() : ": " + msg);
+ return result;
+ }
+ status(p, state == "PENDING" ? "Waiting in queue..." : "Reconstructing 3D model... " + std::to_string(std::max(pct, 0)) + "%",
+ pct);
+ }
+}
+
+// `imagePath` or `prompt` (text to 3D) - exactly one is used.
+GeneratorResult runHuggingFace(const AiSettings& s, const std::string& imagePath, const std::string& prompt,
+ const std::string& outputStem, GenerationProgress* p) {
+ GeneratorResult result;
+ const bool text = !prompt.empty();
+ const auto& presets = text ? hfTextPresets() : hfPresets();
+ const HfPreset* preset = nullptr;
+ for (const auto& h : presets)
+ if (s.hfModel == h.id) preset = &h;
+ if (!preset) preset = &presets[0];
+
+ status(p, "Connecting to " + std::string(preset->label) + "...");
+ GradioClient client;
+ if (!client.connect(preset->space, s.resolvedHfToken(), result.error)) return result;
+ Json image;
+ if (!text) {
+ std::string png;
+ if (!prepareImagePng(imagePath, png, result.error)) return result;
+ if (!client.upload(png, "input.png", image, result.error)) return result;
+ }
+
+ std::vector<Json> firstOutputs;
+ for (const auto& step : preset->steps) {
+ if (p && p->cancel) {
+ result.error = "Cancelled";
+ return result;
+ }
+ std::vector<Json> args;
+ for (const auto& a : step.args) {
+ if (a == "$IMG") {
+ args.push_back(image);
+ } else if (a == "$PROMPT") {
+ args.push_back(Json(prompt));
+ } else if (a.rfind("$OUT", 0) == 0) {
+ const size_t n = size_t(std::stoi(a.substr(4)));
+ args.push_back(n < firstOutputs.size() ? firstOutputs[n] : Json());
+ } else {
+ Json v;
+ std::string err;
+ Json::parse(a, v, err);
+ args.push_back(v);
+ }
+ }
+ std::vector<Json> outputs;
+ if (!client.call(step.api, args, outputs, result.error, [&](const std::string& text) { status(p, text); }))
+ return result;
+ Json first = outputs.empty() ? Json() : outputs[0];
+ if (first.isObject() && first["value"].isObject()) first = first["value"]; // unwrap component updates
+ firstOutputs.push_back(first);
+ }
+ const std::string url = client.lastModelUrl();
+ if (url.empty()) {
+ result.error = "The Space finished but returned no 3D model";
+ return result;
+ }
+ status(p, "Downloading model...");
+ std::string bytes;
+ if (!client.download(url, bytes, result.error)) return result;
+ std::string lower = url.substr(0, url.find('?'));
+ std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ const std::string ext = lower.ends_with(".obj") ? ".obj" : lower.ends_with(".ply") ? ".ply" : ".glb";
+ const std::string path = outputStem + ext;
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f || !f.write(bytes.data(), std::streamsize(bytes.size()))) {
+ result.error = "Cannot write " + path;
+ return result;
+ }
+ result.ok = true;
+ result.outputPath = path;
+ return result;
+}
+
+GeneratorResult runInflate(const std::string& imagePath, const std::string& outputStem, GenerationProgress* p) {
+ GeneratorResult result;
+ status(p, "Inflating silhouette...");
+ Image img;
+ if (!Image::load(imagePath, img, result.error)) return result;
+ InflateOptions o;
+ o.subdivisions = 2;
+ Mesh m = inflateSilhouette(img, o, &result.error);
+ if (m.triangleCount() == 0) return result;
+ const std::string path = outputStem + ".glb";
+ if (!saveGlb(path, m, "Inflated", result.error)) return result;
+ result.ok = true;
+ result.outputPath = path;
+ return result;
+}
+
+} // namespace
+
+const std::vector<ServiceModel>& falModels() {
+ static const std::vector<ServiceModel> models = {
+ {"fal-ai/trellis-2", "TRELLIS.2 (Microsoft) - detailed, open model"},
+ {"fal-ai/hunyuan-3d/v3.1/pro/image-to-3d", "Hunyuan3D 3.1 Pro (Tencent)"},
+ {"fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d", "Hunyuan3D 3.1 Rapid (Tencent) - fast"},
+ {"fal-ai/meshy/v6/image-to-3d", "Meshy 6"},
+ };
+ return models;
+}
+
+std::string base64Encode(const uint8_t* data, size_t size) {
+ static const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ std::string out;
+ out.reserve((size + 2) / 3 * 4);
+ for (size_t i = 0; i < size; i += 3) {
+ const uint32_t n = uint32_t(data[i]) << 16 | (i + 1 < size ? uint32_t(data[i + 1]) << 8 : 0u) |
+ (i + 2 < size ? uint32_t(data[i + 2]) : 0u);
+ out += chars[(n >> 18) & 63];
+ out += chars[(n >> 12) & 63];
+ out += i + 1 < size ? chars[(n >> 6) & 63] : '=';
+ out += i + 2 < size ? chars[n & 63] : '=';
+ }
+ return out;
+}
+
+bool prepareImagePng(const std::string& imagePath, std::string& png, std::string& error) {
+ Image img;
+ if (!Image::load(imagePath, img, error)) return false;
+ if (img.width < 16 || img.height < 16) {
+ error = "The image is too small";
+ return false;
+ }
+ // Reconstruction models work best with the subject centred and filling most of a square frame.
+ Image framed = img.framedSubject(0.08f).downscaled(1024);
+ std::vector<uint8_t> bytes;
+ if (!framed.encodePng(bytes)) {
+ error = "Could not encode the image";
+ return false;
+ }
+ png.assign(bytes.begin(), bytes.end());
+ return true;
+}
+
+bool prepareImageDataUri(const std::string& imagePath, std::string& dataUri, std::string& error) {
+ std::string png;
+ if (!prepareImagePng(imagePath, png, error)) return false;
+ dataUri = "data:image/png;base64," + base64Encode(reinterpret_cast<const uint8_t*>(png.data()), png.size());
+ return true;
+}
+
+const std::vector<HfPreset>& hfTextPresets() {
+ static const std::vector<HfPreset> presets = {
+ {"hunyuan3d-2-turbo", "Hunyuan3D 2 mini Turbo (Tencent) - free, fast", "https://tencent-hunyuan3d-2mini-turbo.hf.space",
+ {{"shape_generation", {"$PROMPT"}}}},
+ {"hunyuan3d-2", "Hunyuan3D 2 (Tencent) - free", "https://tencent-hunyuan3d-2.hf.space", {{"shape_generation", {"$PROMPT"}}}},
+ };
+ return presets;
+}
+
+const std::vector<HfPreset>& hfPresets() {
+ static const std::vector<HfPreset> presets = {
+ {"hunyuan3d-2.1", "Hunyuan3D 2.1 (Tencent) - free, detailed shape", "https://tencent-hunyuan3d-2-1.hf.space",
+ {{"shape_generation", {"$IMG"}}}},
+ {"trellis-2", "TRELLIS.2 (Microsoft) - free, best detail, needs an HF token", "https://microsoft-trellis-2.hf.space",
+ {{"start_session", {}}, {"preprocess_image", {"$IMG"}}, {"image_to_3d", {"$OUT1"}}, {"extract_glb", {}}}},
+ {"hunyuan3d-2-turbo", "Hunyuan3D 2 mini Turbo (Tencent) - free, fastest", "https://tencent-hunyuan3d-2mini-turbo.hf.space",
+ {{"shape_generation", {"\"\"", "$IMG"}}}},
+ {"hunyuan3d-2", "Hunyuan3D 2 (Tencent) - free", "https://tencent-hunyuan3d-2.hf.space",
+ {{"shape_generation", {"\"\"", "$IMG"}}}},
+ {"stable-fast-3d", "Stable Fast 3D (Stability AI) - free, quick and simple", "https://stabilityai-stable-fast-3d.hf.space",
+ // As its UI does: check the background, remove it (fills the session state), then Run.
+ {{"requires_bg_remove", {"$IMG", "0.85"}},
+ {"run_button", {"\"Remove Background\"", "$IMG"}},
+ {"run_button", {"\"Run\"", "$IMG"}}}},
+ };
+ return presets;
+}
+
+std::string falSubmitBody(const std::string& model, const std::string& dataUri) {
+ Json body = Json::object();
+ const bool hunyuan = model.find("hunyuan") != std::string::npos;
+ body.set(hunyuan ? "input_image_url" : "image_url", dataUri);
+ if (model.find("hunyuan-3d/v3.1/rapid") != std::string::npos) body.set("enable_geometry", true); // shape only: we sculpt it
+ return body.dump();
+}
+
+std::string meshySubmitBody(const std::string& model, const std::string& dataUri) {
+ Json body = Json::object();
+ body.set("image_url", dataUri);
+ body.set("ai_model", model.empty() ? "latest" : model);
+ body.set("should_texture", false); // SculptForge sculpts the shape; skip texturing time and credits
+ Json formats = Json::array();
+ formats.push("glb");
+ body.set("target_formats", formats);
+ return body.dump();
+}
+
+std::string findModelUrl(const Json& result, std::string* extension) {
+ auto urlOf = [](const Json& j) -> std::string {
+ if (j.isString()) return j.asString();
+ if (j.isObject() && j["url"].isString()) return j["url"].asString();
+ return {};
+ };
+ auto extOf = [](const std::string& url, const Json& file) {
+ const std::string type = file.isObject() ? file["content_type"].asString() : std::string();
+ std::string path = url.substr(0, url.find('?'));
+ std::transform(path.begin(), path.end(), path.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ if (path.ends_with(".obj") || type.find("obj") != std::string::npos) return std::string(".obj");
+ return std::string(".glb");
+ };
+ // Known field names first (fal TRELLIS/Hunyuan/Meshy, Meshy direct).
+ for (const char* key : {"model_glb", "model_mesh", "glb", "model_file", "mesh", "model_obj", "obj"}) {
+ const std::string url = urlOf(result[key]);
+ if (!url.empty()) {
+ if (extension) *extension = extOf(url, result[key]);
+ return url;
+ }
+ }
+ if (result["model_urls"].isObject()) {
+ if (std::string url = findModelUrl(result["model_urls"], extension); !url.empty()) return url;
+ }
+ // Otherwise any URL ending in .glb anywhere in the result.
+ std::function<std::string(const Json&)> search = [&](const Json& j) -> std::string {
+ if (j.isString()) {
+ std::string path = j.asString().substr(0, j.asString().find('?'));
+ if (path.size() > 4 && (path.ends_with(".glb") || path.ends_with(".GLB"))) return j.asString();
+ return {};
+ }
+ if (j.isArray())
+ for (const auto& item : j.items())
+ if (auto u = search(item); !u.empty()) return u;
+ if (j.isObject())
+ for (const auto& [k, v] : j.members())
+ if (auto u = search(v); !u.empty()) return u;
+ return {};
+ };
+ const std::string url = search(result);
+ if (!url.empty() && extension) *extension = ".glb";
+ return url;
+}
+
+GeneratorResult generate3D(const AiSettings& s, const std::string& imagePath, const std::string& outputStem,
+ GenerationProgress* progress) {
+ if (s.generatorService == "meshy") return runMeshy(s, imagePath, outputStem, progress);
+ if (s.generatorService == "command") {
+ status(progress, "Running your generator...");
+ return runGenerator(s.generatorCommand, imagePath, outputStem + ".glb");
+ }
+ if (s.generatorService == "inflate") return runInflate(imagePath, outputStem, progress);
+ if (s.generatorService == "fal") return runFal(s, imagePath, outputStem, progress);
+ return runHuggingFace(s, imagePath, {}, outputStem, progress);
+}
+
+std::string meshyTextBody(const std::string& model, const std::string& prompt) {
+ Json body = Json::object();
+ body.set("mode", "preview"); // untextured shape: what we sculpt
+ body.set("prompt", prompt.substr(0, 800));
+ body.set("ai_model", model.empty() ? "latest" : model);
+ return body.dump();
+}
+
+std::string falTextBody(const std::string& prompt) {
+ Json body = Json::object();
+ body.set("prompt", prompt.substr(0, 200));
+ body.set("enable_geometry", true); // shape only
+ return body.dump();
+}
+
+GeneratorResult generate3DFromText(const AiSettings& s, const std::string& prompt, const std::string& outputStem,
+ GenerationProgress* progress) {
+ GeneratorResult result;
+ if (prompt.find_first_not_of(" \t\r\n") == std::string::npos) {
+ result.error = "Describe the model you want";
+ return result;
+ }
+ if (s.generatorService == "meshy") return runMeshyRequest(s, "/openapi/v2/text-to-3d", meshyTextBody(s.meshyModel, prompt), outputStem, progress);
+ if (s.generatorService == "fal")
+ return runFalRequest(s, "fal-ai/hunyuan-3d/v3.1/rapid/text-to-3d", falTextBody(prompt), outputStem, progress);
+ if (s.generatorService == "command" || s.generatorService == "inflate") {
+ result.error = "Text to 3D needs Hugging Face (free), fal.ai or Meshy - pick one of those services";
+ return result;
+ }
+ return runHuggingFace(s, {}, prompt, outputStem, progress);
+}
+
+} // namespace sf::ai
diff --git a/src/ai/ImageTo3DService.h b/src/ai/ImageTo3DService.h
new file mode 100644
index 00000000..5ee60429
--- /dev/null
+++ b/src/ai/ImageTo3DService.h
@@ -0,0 +1,91 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Real image-to-3D reconstruction through hosted models, with your own key:
+// - fal.ai: one key for TRELLIS.2 (Microsoft), Hunyuan3D 3.1 (Tencent),
+// Meshy 6 and other models, billed per generation
+// - Hugging Face Spaces: free public demos of TRELLIS.2, Hunyuan3D 2 / 2.1 and
+// Stable Fast 3D on shared GPUs (daily quota; a free HF token raises it)
+// - Meshy: direct API
+// plus the local options (your own generator command, or offline silhouette
+// inflation, which is only a rough blockout).
+//
+// The image is prepared first (subject cropped from a transparent background
+// and centred, scaled to <= 1024 px) and sent inline as a data URI; the
+// resulting GLB is downloaded for import. Nothing is uploaded unless a hosted
+// service is selected.
+#pragma once
+
+#include "ai/BrushAssistant.h"
+#include "ai/Generator3D.h"
+#include "core/Json.h"
+
+#include <atomic>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace sf::ai {
+
+struct GenerationProgress {
+ std::atomic<bool> cancel{false};
+ std::atomic<int> percent{-1}; // -1 = unknown
+
+ void setStatus(std::string text) {
+ std::lock_guard lock(mutex_);
+ status_ = std::move(text);
+ }
+ std::string status() const {
+ std::lock_guard lock(mutex_);
+ return status_;
+ }
+
+private:
+ mutable std::mutex mutex_;
+ std::string status_;
+};
+
+struct ServiceModel {
+ const char* id;
+ const char* label;
+};
+// Curated fal.ai image-to-3D models (any other fal model id also works).
+const std::vector<ServiceModel>& falModels();
+
+// Free models on Hugging Face Spaces (shared GPUs; a free HF token raises the daily quota).
+struct HfStep {
+ const char* api;
+ std::vector<std::string> args; // "$IMG" = the uploaded image, "$OUT<n>" = first output of step n, else JSON
+};
+struct HfPreset {
+ const char* id;
+ const char* label;
+ const char* space; // https://<space>.hf.space
+ std::vector<HfStep> steps;
+};
+const std::vector<HfPreset>& hfPresets();
+// Free text-to-3D models ("$PROMPT" in step args is the description).
+const std::vector<HfPreset>& hfTextPresets();
+
+// Blocking; run on a worker thread. Writes `<outputStem>.glb` (or .obj) and
+// returns its path in `outputPath`.
+GeneratorResult generate3D(const AiSettings& settings, const std::string& imagePath, const std::string& outputStem,
+ GenerationProgress* progress = nullptr);
+
+// Text to 3D: same services (Hugging Face, fal.ai, Meshy); untextured shapes for sculpting.
+GeneratorResult generate3DFromText(const AiSettings& settings, const std::string& prompt, const std::string& outputStem,
+ GenerationProgress* progress = nullptr);
+
+// Pieces exposed for tests.
+std::string meshyTextBody(const std::string& model, const std::string& prompt);
+std::string falTextBody(const std::string& prompt);
+// The image as sent to services: subject framed on a square, <= 1024 px, PNG.
+bool prepareImagePng(const std::string& imagePath, std::string& png, std::string& error);
+bool prepareImageDataUri(const std::string& imagePath, std::string& dataUri, std::string& error);
+std::string falSubmitBody(const std::string& model, const std::string& dataUri);
+std::string meshySubmitBody(const std::string& model, const std::string& dataUri);
+// Finds the model file URL in a service result; `extension` gets ".glb" or ".obj".
+std::string findModelUrl(const Json& result, std::string* extension);
+std::string base64Encode(const uint8_t* data, size_t size);
+
+} // namespace sf::ai
diff --git a/src/app/App.cpp b/src/app/App.cpp
new file mode 100644
index 00000000..2005462d
--- /dev/null
+++ b/src/app/App.cpp
@@ -0,0 +1,1710 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/App.h"
+
+#include "ai/AiCommands.h"
+#include "app/Demo.h"
+
+#include <imgui_internal.h>
+#include "ai/Generator3D.h"
+#include "core/EnginePresets.h"
+#include "link/UnrealLink.h"
+#include "core/Decimate.h"
+#include "core/ImageTo3D.h"
+#include "core/Script.h"
+#include "render/GL.h"
+
+#include <imgui.h>
+#include <imgui_impl_opengl3.h>
+#include <imgui_impl_sdl3.h>
+
+#include <algorithm>
+#include <cfloat>
+#include <cmath>
+#include <filesystem>
+#include <iterator>
+#include <memory>
+#include <thread>
+
+namespace sf {
+
+namespace assets {
+extern const unsigned char fontRegular[];
+extern const unsigned long long fontRegular_size;
+extern const unsigned char fontSemiBold[];
+extern const unsigned long long fontSemiBold_size;
+extern const unsigned char appIcon[];
+extern const unsigned long long appIcon_size;
+} // namespace assets
+
+namespace {
+
+const SDL_DialogFileFilter kObjFilters[] = {{"Wavefront OBJ", "obj"}, {"All files", "*"}};
+const SDL_DialogFileFilter kGlbFilters[] = {{"glTF binary", "glb"}, {"All files", "*"}};
+const SDL_DialogFileFilter kBrushFilters[] = {{"SculptForge brush", "sfbrush"}, {"All files", "*"}};
+const SDL_DialogFileFilter kModelFilters[] = {{"Models and splats", "obj;fbx;glb;gltf;ply;splat;usda;usd;usdz"}, {"All files", "*"}};
+const SDL_DialogFileFilter kFbxFilters[] = {{"FBX", "fbx"}, {"All files", "*"}};
+const SDL_DialogFileFilter kUsdFilters[] = {{"USDZ package", "usdz"}, {"USD text", "usda"}};
+const SDL_DialogFileFilter kSplatFilters[] = {{"Gaussian splats (PLY)", "ply"}, {"glTF splats", "glb"}, {"OpenUSD", "usda;usdz"}};
+const SDL_DialogFileFilter kImageFilters[] = {{"Images", "png;jpg;jpeg;bmp;tga;psd;gif"}, {"All files", "*"}};
+
+const char* kExamplePrompts[] = {
+ "Sharp wrinkles that fade out at the ends",
+ "Overlapping dragon scales",
+ "Weathered, chipped stone edges",
+ "Dry cracked mud",
+ "Soft clay buildup like a thumb smear",
+};
+
+bool ctrlDown(SDL_Keymod mod) { return (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0; }
+
+void applyStyle() {
+ ImGui::StyleColorsDark();
+ ImGuiStyle& s = ImGui::GetStyle();
+ s.WindowRounding = 6.0f;
+ s.FrameRounding = 4.0f;
+ s.GrabRounding = 4.0f;
+ s.WindowBorderSize = 0.0f;
+ s.FramePadding = ImVec2(8, 5);
+ s.ItemSpacing = ImVec2(8, 6);
+ ImVec4* c = s.Colors;
+ c[ImGuiCol_WindowBg] = ImVec4(0.11f, 0.11f, 0.12f, 0.94f);
+ c[ImGuiCol_Button] = ImVec4(0.22f, 0.22f, 0.25f, 1.0f);
+ c[ImGuiCol_ButtonHovered] = ImVec4(0.85f, 0.50f, 0.25f, 0.85f);
+ c[ImGuiCol_ButtonActive] = ImVec4(0.95f, 0.55f, 0.25f, 1.0f);
+ c[ImGuiCol_SliderGrab] = ImVec4(0.90f, 0.55f, 0.25f, 1.0f);
+ c[ImGuiCol_SliderGrabActive] = ImVec4(1.00f, 0.62f, 0.30f, 1.0f);
+ c[ImGuiCol_CheckMark] = ImVec4(1.00f, 0.62f, 0.30f, 1.0f);
+ c[ImGuiCol_Header] = ImVec4(0.85f, 0.50f, 0.25f, 0.45f);
+ c[ImGuiCol_HeaderHovered] = ImVec4(0.85f, 0.50f, 0.25f, 0.70f);
+ c[ImGuiCol_FrameBg] = ImVec4(0.18f, 0.18f, 0.20f, 1.0f);
+}
+
+} // namespace
+
+App::App() = default;
+App::~App() = default;
+
+bool App::init(const AppOptions& options) {
+ options_ = options;
+ const bool recording = !options.recordPath.empty();
+ const bool headless = !options.renderPath.empty() || recording;
+ if (!SDL_Init(SDL_INIT_VIDEO)) {
+ SDL_Log("SDL_Init failed: %s", SDL_GetError());
+ return false;
+ }
+
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
+ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
+ SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
+
+ const SDL_WindowFlags flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY |
+ (headless ? SDL_WINDOW_HIDDEN : 0);
+ const int winW = recording ? options.width : 1600, winH = recording ? options.height : 960;
+ window_ = SDL_CreateWindow("SculptForge", winW, winH, flags);
+ if (!window_) {
+ // Retry without multisampling for drivers that refuse it.
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
+ window_ = SDL_CreateWindow("SculptForge", winW, winH, flags);
+ }
+ if (!window_) {
+ SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());
+ return false;
+ }
+ {
+ Image icon;
+ std::string iconErr;
+ if (Image::decode(assets::appIcon, size_t(assets::appIcon_size), icon, iconErr)) {
+ if (SDL_Surface* surface = SDL_CreateSurfaceFrom(icon.width, icon.height, SDL_PIXELFORMAT_RGBA32, icon.rgba.data(),
+ icon.width * 4)) {
+ SDL_SetWindowIcon(window_, surface);
+ SDL_DestroySurface(surface);
+ }
+ }
+ }
+ glContext_ = SDL_GL_CreateContext(window_);
+ if (!glContext_) {
+ SDL_Log("OpenGL 3.3 context creation failed: %s", SDL_GetError());
+ return false;
+ }
+ SDL_GL_MakeCurrent(window_, glContext_);
+ SDL_GL_SetSwapInterval(1);
+
+ if (const char* missing = gl::load([](const char* n) { return reinterpret_cast<gl::GenericProc>(SDL_GL_GetProcAddress(n)); })) {
+ SDL_Log("Missing OpenGL function: %s", missing);
+ return false;
+ }
+ SDL_Log("OpenGL %s on %s", reinterpret_cast<const char*>(gl::GetString(GL_VERSION)),
+ reinterpret_cast<const char*>(gl::GetString(GL_RENDERER)));
+
+ std::string err;
+ if (!renderer_.init(err)) {
+ SDL_Log("%s", err.c_str());
+ return false;
+ }
+
+ IMGUI_CHECKVERSION();
+ ImGui::CreateContext();
+ ImGuiIO& io = ImGui::GetIO();
+ if (char* pref = SDL_GetPrefPath("SculptForge", "SculptForge")) {
+ iniPath_ = std::string(pref) + "imgui.ini";
+ io.IniFilename = iniPath_.c_str();
+ aiSettingsPath_ = std::string(pref) + "ai.json";
+ aiSettings_ = ai::AiSettings::load(aiSettingsPath_);
+ SDL_free(pref);
+ } else {
+ io.IniFilename = nullptr;
+ }
+ ai::registerAiCommands(commands_, [this] { return aiSettings_; });
+ std::snprintf(falKey_, sizeof falKey_, "%s", aiSettings_.falKey.c_str());
+ std::snprintf(falModel_, sizeof falModel_, "%s", aiSettings_.falModel.c_str());
+ std::snprintf(meshyKey_, sizeof meshyKey_, "%s", aiSettings_.meshyKey.c_str());
+ std::snprintf(hfToken_, sizeof hfToken_, "%s", aiSettings_.hfToken.c_str());
+ // Pixel density (Retina / Wayland scaling) is handled by the backend via the
+ // framebuffer scale; only scale the UI for any additional content scaling.
+ float density = SDL_GetWindowPixelDensity(window_);
+ float scale = SDL_GetWindowDisplayScale(window_) / (density > 0.0f ? density : 1.0f);
+ if (scale <= 0.0f) scale = 1.0f;
+ if (recording) scale = float(options.height) / 900.0f; // UI sized for the video, not this screen
+ uiScale_ = scale;
+ applyStyle();
+ ImGui::GetStyle().ScaleAllSizes(scale);
+ // Inter (SIL OFL), embedded in the binary. Rasterised at the final size for crisp text.
+ ImFontConfig fontConfig;
+ fontConfig.FontDataOwnedByAtlas = false;
+ fontConfig.OversampleH = 2;
+ io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontRegular), int(assets::fontRegular_size),
+ 15.0f * scale, &fontConfig);
+ if (recording) {
+ fontCaption_ = io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontSemiBold),
+ int(assets::fontSemiBold_size), float(options.height) * 0.042f,
+ &fontConfig);
+ fontCaptionSub_ = io.Fonts->AddFontFromMemoryTTF(const_cast<unsigned char*>(assets::fontRegular),
+ int(assets::fontRegular_size), float(options.height) * 0.024f,
+ &fontConfig);
+ ImGui::GetCurrentContext()->TestEngineHookItems = true; // lets the demo find buttons by label
+ io.IniFilename = nullptr; // fixed, reproducible layout
+ }
+ ImGui_ImplSDL3_InitForOpenGL(window_, glContext_);
+ ImGui_ImplOpenGL3_Init("#version 330 core");
+
+ for (int i = 0; i < int(FileAction::Count); ++i) dialogRequests_[i] = {this, FileAction(i)};
+ runCommand("new_sphere");
+ if (!options.openPath.empty()) openPath(options.openPath);
+ if (!options.script.empty()) {
+ std::vector<ScriptStatement> statements;
+ std::string err;
+ if (!parseScript(options.script, statements, err)) {
+ SDL_Log("Script error: %s", err.c_str());
+ return false;
+ }
+ for (const auto& st : statements) {
+ CommandResult r = commands_.execute(doc_, st.command, st.args);
+ SDL_Log("%s: %s", st.command.c_str(), r.message.c_str());
+ if (!r.ok && headless) return false;
+ }
+ camera_.frame(sceneBounds());
+ updateTitle();
+ }
+ if (!aiSettings_.generatorCommand.empty())
+ std::snprintf(generatorCommand_, sizeof generatorCommand_, "%s", aiSettings_.generatorCommand.c_str());
+ else if (const char* base = SDL_GetBasePath()) {
+#if defined(_WIN32)
+ const char* cliName = "sculptforge-cli.exe";
+#else
+ const char* cliName = "sculptforge-cli";
+#endif
+ std::snprintf(generatorCommand_, sizeof generatorCommand_, "%s",
+ ai::defaultGeneratorCommand(std::string(base) + cliName).c_str());
+ }
+ return true;
+}
+
+void App::shutdown() {
+ if (refTexture_) gl::DeleteTextures(1, &refTexture_);
+ ImGui_ImplOpenGL3_Shutdown();
+ ImGui_ImplSDL3_Shutdown();
+ ImGui::DestroyContext();
+ renderer_.shutdown();
+ if (glContext_) SDL_GL_DestroyContext(glContext_);
+ if (window_) SDL_DestroyWindow(window_);
+ SDL_Quit();
+}
+
+int App::renderHeadless() {
+ const int frames = std::max(1, options_.turntable);
+ camera_.frame(options_.hideMesh && !doc_.splats.empty() ? doc_.splats.bounds(0.9f) : sceneBounds());
+ camera_.aspect = float(options_.width) / float(std::max(options_.height, 1));
+ camera_.pitch = glm::radians(options_.pitchDegrees);
+ RenderSettings settings = renderSettings_;
+ settings.wireframe = options_.wireframe;
+ settings.showMesh = !options_.hideMesh;
+ renderer_.sync(doc_.mesh);
+ renderer_.syncSplats(doc_.splats, doc_.splatsVersion);
+ const std::filesystem::path out(std::u8string(options_.renderPath.begin(), options_.renderPath.end()));
+ for (int f = 0; f < frames; ++f) {
+ camera_.yaw = glm::radians(options_.yawDegrees + 360.0f * float(f) / float(frames));
+ Image img;
+ img.width = options_.width;
+ img.height = options_.height;
+ std::string err;
+ if (!renderer_.renderToImage(camera_, img.width, img.height, settings, img.rgba, err)) {
+ SDL_Log("Render failed: %s", err.c_str());
+ return 1;
+ }
+ std::string path = options_.renderPath;
+ if (options_.turntable > 0) {
+ char suffix[16];
+ std::snprintf(suffix, sizeof suffix, "_%03d.png", f);
+ auto stem = (out.parent_path() / out.stem()).u8string();
+ path = std::string(stem.begin(), stem.end()) + suffix;
+ }
+ if (!img.savePng(path, err)) {
+ SDL_Log("%s", err.c_str());
+ return 1;
+ }
+ SDL_Log("Rendered %s", path.c_str());
+ }
+ return 0;
+}
+
+int App::runRecording() {
+ demo_ = std::make_unique<Demo>(*this);
+ std::string err;
+ if (!demo_->load(options_.demo.empty() ? "sculpt" : options_.demo, err)) {
+ SDL_Log("%s", err.c_str());
+ return 1;
+ }
+ const int w = options_.width, h = options_.height, fps = std::max(options_.fps, 1);
+ // Frames go straight to ffmpeg as raw RGBA.
+ std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(w) + "x" + std::to_string(h) +
+ " -r " + std::to_string(fps) +
+ " -i - -c:v libx264 -preset slow -crf 20 -pix_fmt yuv420p -movflags +faststart \"" +
+ options_.recordPath + "\"";
+#if defined(_WIN32)
+ FILE* ff = _popen(cmd.c_str(), "wb");
+#else
+ FILE* ff = popen(cmd.c_str(), "w");
+#endif
+ if (!ff) {
+ SDL_Log("Cannot start ffmpeg");
+ return 1;
+ }
+ std::vector<uint8_t> rgba;
+ const float dt = 1.0f / float(fps);
+ int frames = 0, written = 0;
+ while (!demo_->finished() && frames < fps * 60 * 30) {
+ SDL_Event e;
+ while (SDL_PollEvent(&e)) {
+ } // the demo provides all input
+ demo_->update(dt);
+ processPendingFiles();
+ animateLayers(dt);
+ pollBrushRequest();
+ pollUnreal();
+ camera_.aspect = float(w) / float(h);
+
+ Demo::beginFrame();
+ ImGui_ImplOpenGL3_NewFrame();
+ ImGui_ImplSDL3_NewFrame();
+ ImGuiIO& io = ImGui::GetIO();
+ io.DisplaySize = ImVec2(float(w), float(h));
+ io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
+ io.DeltaTime = dt;
+ ImGui::NewFrame();
+ drawUi();
+ demo_->drawOverlay();
+ ImGui::Render();
+
+ Mesh& shown = displayedMesh();
+ if (&shown != lastDisplayed_) shown.topologyDirty = true;
+ lastDisplayed_ = &shown;
+ renderer_.sync(shown);
+ renderer_.syncSplats(doc_.splats, doc_.splatsVersion);
+ ++frames;
+ // While waiting on a model, keep only every Nth frame (marked on screen as sped up).
+ if ((frames % demo_->frameStride()) != 0) continue;
+ if (!renderer_.beginCapture(w, h, err)) {
+ SDL_Log("%s", err.c_str());
+ break;
+ }
+ renderer_.draw(camera_, w, h, renderSettings_);
+ ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
+ renderer_.endCapture(rgba);
+ fwrite(rgba.data(), 1, rgba.size(), ff);
+ ++written;
+ }
+#if defined(_WIN32)
+ const int status = _pclose(ff);
+#else
+ const int status = pclose(ff);
+#endif
+ if (!status_.empty()) SDL_Log("Last status: %s", status_.c_str());
+ SDL_Log("Recorded %d frames (%.1f s) to %s", written, float(written) / float(fps), options_.recordPath.c_str());
+ return status == 0 ? 0 : 1;
+}
+
+int App::run() {
+ if (!options_.renderPath.empty()) return renderHeadless();
+ if (!options_.recordPath.empty()) return runRecording();
+ Uint64 lastTicks = SDL_GetTicksNS();
+ while (running_) {
+ Uint64 now = SDL_GetTicksNS();
+ float dt = float(double(now - lastTicks) * 1e-9);
+ lastTicks = now;
+ SDL_Event e;
+ while (SDL_PollEvent(&e)) handleEvent(e);
+ processPendingFiles();
+ animateLayers(dt);
+ pollBrushRequest();
+ pollGenerator();
+ pollUnreal();
+
+ int fbW = 0, fbH = 0, winW = 0, winH = 0;
+ SDL_GetWindowSizeInPixels(window_, &fbW, &fbH);
+ SDL_GetWindowSize(window_, &winW, &winH);
+ if (fbW <= 0 || fbH <= 0) {
+ SDL_Delay(16);
+ continue;
+ }
+ camera_.aspect = float(fbW) / float(fbH);
+
+ ImGui_ImplOpenGL3_NewFrame();
+ ImGui_ImplSDL3_NewFrame();
+ ImGui::NewFrame();
+ drawUi();
+ ImGui::Render();
+
+ Mesh& shown = displayedMesh();
+ if (&shown != lastDisplayed_) shown.topologyDirty = true;
+ lastDisplayed_ = &shown;
+ renderer_.sync(shown);
+ renderer_.syncSplats(doc_.splats, doc_.splatsVersion);
+ renderer_.draw(camera_, fbW, fbH, renderSettings_);
+ ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
+ SDL_GL_SwapWindow(window_);
+ }
+ return 0;
+}
+
+// ---------------------------------------------------------------------------
+// Input
+// ---------------------------------------------------------------------------
+
+void App::handleEvent(const SDL_Event& e) {
+ ImGui_ImplSDL3_ProcessEvent(&e);
+ const ImGuiIO& io = ImGui::GetIO();
+
+ switch (e.type) {
+ case SDL_EVENT_QUIT:
+ running_ = false;
+ break;
+ case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
+ if (e.window.windowID == SDL_GetWindowID(window_)) running_ = false;
+ break;
+ case SDL_EVENT_PEN_PROXIMITY_IN:
+ penSeen_ = true;
+ break;
+ case SDL_EVENT_PEN_AXIS:
+ if (e.paxis.axis == SDL_PEN_AXIS_PRESSURE) penPressure_ = e.paxis.value;
+ break;
+ case SDL_EVENT_MOUSE_BUTTON_DOWN:
+ lastInputPen_ = e.button.which == SDL_PEN_MOUSEID;
+ if (!io.WantCaptureMouse) onMouseDown(e.button.x, e.button.y, e.button.button);
+ break;
+ case SDL_EVENT_MOUSE_BUTTON_UP:
+ onMouseUp();
+ break;
+ case SDL_EVENT_MOUSE_MOTION:
+ onMouseMove(e.motion.x, e.motion.y, e.motion.xrel, e.motion.yrel, e.motion.which == SDL_PEN_MOUSEID);
+ break;
+ case SDL_EVENT_MOUSE_WHEEL:
+ if (!io.WantCaptureMouse) camera_.zoom(e.wheel.y);
+ break;
+ case SDL_EVENT_KEY_DOWN:
+ if (!io.WantCaptureKeyboard && !e.key.repeat) onKey(e.key.key, e.key.mod);
+ else if (!io.WantCaptureKeyboard && (e.key.key == SDLK_LEFTBRACKET || e.key.key == SDLK_RIGHTBRACKET))
+ onKey(e.key.key, e.key.mod);
+ break;
+ case SDL_EVENT_DROP_FILE:
+ if (e.drop.data) openPath(e.drop.data);
+ break;
+ default:
+ break;
+ }
+}
+
+bool App::pick(float x, float y, RayHit& hit) const {
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ glm::vec3 origin, dir;
+ camera_.screenRay(x, y, float(w), float(h), origin, dir);
+ return doc_.bvh.raycast(doc_.mesh, origin, dir, hit);
+}
+
+BrushType App::activeBrush() const {
+ // ZBrush convention: holding Shift temporarily switches to Smooth.
+ return (SDL_GetModState() & SDL_KMOD_SHIFT) ? BrushType::Smooth : brush_;
+}
+
+void App::onMouseDown(float x, float y, Uint8 button) {
+ mouseX_ = x;
+ mouseY_ = y;
+ const SDL_Keymod mod = SDL_GetModState();
+ doc_.syncBvh();
+ if (button == SDL_BUTTON_LEFT) {
+ RayHit hit;
+ if (previewLod_ < 0 && pick(x, y, hit)) {
+ beginStroke(x, y, hit);
+ } else {
+ // Dragging on empty space navigates (ZBrush style).
+ drag_ = (mod & SDL_KMOD_ALT) ? Drag::Pan : ctrlDown(mod) ? Drag::Zoom : Drag::Orbit;
+ }
+ } else if (button == SDL_BUTTON_RIGHT) {
+ drag_ = (mod & SDL_KMOD_SHIFT) ? Drag::Pan : Drag::Orbit;
+ } else if (button == SDL_BUTTON_MIDDLE) {
+ drag_ = (mod & SDL_KMOD_CTRL) ? Drag::Zoom : Drag::Pan;
+ }
+}
+
+void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
+ mouseX_ = x;
+ mouseY_ = y;
+ lastInputPen_ = fromPen;
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ switch (drag_) {
+ case Drag::Stroke: strokeTo(x, y); break;
+ case Drag::Orbit: camera_.orbit(dx, dy); break;
+ case Drag::Pan: camera_.pan(dx, dy, float(h)); break;
+ case Drag::Zoom: camera_.zoom(-dy * 0.05f); break;
+ case Drag::None: break;
+ }
+}
+
+void App::onMouseUp() {
+ if (drag_ == Drag::Stroke) endStroke();
+ drag_ = Drag::None;
+}
+
+void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
+ const bool ctrl = ctrlDown(mod);
+ const bool shift = (mod & SDL_KMOD_SHIFT) != 0;
+ if (ctrl) {
+ switch (key) {
+ case SDLK_Z: runCommand(shift ? "redo" : "undo"); break;
+ case SDLK_Y: runCommand("redo"); break;
+ case SDLK_D: runCommand("subdivide"); break;
+ case SDLK_O: openFileDialog(); break;
+ case SDLK_S:
+ if (shift || doc_.path.empty()) saveFileDialog(FileAction::SaveObj);
+ else runCommand("save_obj");
+ break;
+ case SDLK_N: runCommand("new_sphere"); break;
+ case SDLK_E: saveFileDialog(FileAction::ExportGlb); break;
+ case SDLK_U: sendToUnreal(); break;
+ default: break;
+ }
+ return;
+ }
+ switch (key) {
+ case SDLK_LEFTBRACKET: radiusPx_ = std::max(2.0f, radiusPx_ / 1.1f); break;
+ case SDLK_RIGHTBRACKET: radiusPx_ = std::min(800.0f, radiusPx_ * 1.1f); break;
+ case SDLK_X: symmetry_.x = !symmetry_.x; break;
+ case SDLK_W: renderSettings_.wireframe = !renderSettings_.wireframe; break;
+ case SDLK_F: camera_.frame(sceneBounds()); break;
+ case SDLK_F1: showHelp_ = !showHelp_; break;
+ default:
+ if (key >= SDLK_1 && key < SDLK_1 + int(BrushType::Count)) brush_ = BrushType(key - SDLK_1);
+ break;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Strokes
+// ---------------------------------------------------------------------------
+
+void App::beginStroke(float x, float y, const RayHit& hit) {
+ strokeBrush_ = activeBrush();
+ strokeInvert_ = invertToggle_ != ((SDL_GetModState() & SDL_KMOD_ALT) != 0);
+ const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();
+ haveLastDab_ = false;
+ if (!doc_.sculptor.beginStroke(doc_.mesh, recipe ? recipe->name : brushName(strokeBrush_), doc_.activeLayer)) {
+ status_ = "Active layer weight is 0 - raise it to sculpt into the layer";
+ drag_ = Drag::Orbit;
+ return;
+ }
+ drag_ = Drag::Stroke;
+ playingLayer_ = -1;
+ clearLods();
+ lastX_ = x;
+ lastY_ = y;
+ residual_ = 0.0f;
+
+ if (strokeBrush_ == BrushType::Move && !recipe) {
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ float pressure = lastInputPen_ && pressureSize_ ? penPressure_ : 1.0f;
+ DabParams p;
+ p.center = hit.position;
+ p.viewDir = camera_.forward();
+ p.radius = radiusPx_ * pressure * camera_.worldPerPixel(hit.position, float(h));
+ p.strength = strength_;
+ doc_.sculptor.beginGrab(doc_.mesh, doc_.bvh, p, symmetry_);
+ grabPlanePoint_ = grabLast_ = hit.position;
+ return;
+ }
+ dabAt(x, y);
+}
+
+void App::strokeTo(float x, float y) {
+ const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();
+ if (strokeBrush_ == BrushType::Move && !recipe) {
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ glm::vec3 origin, dir;
+ camera_.screenRay(x, y, float(w), float(h), origin, dir);
+ glm::vec3 n = camera_.forward();
+ float denom = glm::dot(dir, n);
+ if (std::abs(denom) < 1e-6f) return;
+ float t = glm::dot(grabPlanePoint_ - origin, n) / denom;
+ glm::vec3 p = origin + dir * t;
+ doc_.sculptor.grab(doc_.mesh, doc_.bvh, p - grabLast_);
+ grabLast_ = p;
+ return;
+ }
+
+ // Place dabs at even screen-space spacing along the cursor path.
+ const float spacing = std::max(1.0f, radiusPx_ * (recipe ? recipe->spacing : 0.15f));
+ glm::vec2 from(lastX_, lastY_), to(x, y);
+ float len = glm::length(to - from);
+ float travelled = spacing - residual_;
+ while (travelled <= len) {
+ glm::vec2 p = from + (to - from) * (travelled / len);
+ dabAt(p.x, p.y);
+ travelled += spacing;
+ }
+ residual_ = len - (travelled - spacing);
+ lastX_ = x;
+ lastY_ = y;
+}
+
+void App::dabAt(float x, float y) {
+ const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();
+ if (recipe && recipe->jitter > 0.0f) {
+ // Deterministic per-stroke scatter (xorshift).
+ auto rnd = [this] {
+ jitterSeed_ ^= jitterSeed_ << 13;
+ jitterSeed_ ^= jitterSeed_ >> 17;
+ jitterSeed_ ^= jitterSeed_ << 5;
+ return float(jitterSeed_ & 0xffff) / 65535.0f * 2.0f - 1.0f;
+ };
+ x += rnd() * recipe->jitter * radiusPx_;
+ y += rnd() * recipe->jitter * radiusPx_;
+ }
+ RayHit hit;
+ if (!pick(x, y, hit)) return;
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+
+ DabParams p;
+ p.center = hit.position;
+ p.viewDir = camera_.forward();
+ p.radius = radiusPx_ * (pressureSize_ ? std::max(pressure, 0.05f) : 1.0f) *
+ camera_.worldPerPixel(hit.position, float(h));
+ p.strength = strength_;
+ p.pressure = pressureStrength_ ? pressure : 1.0f;
+ p.invert = strokeInvert_;
+ p.frontFacesOnly = frontFacesOnly_;
+ if (recipe) {
+ p.strokeDelta = haveLastDab_ ? hit.position - lastDabHit_ : glm::vec3(0.0f);
+ lastDabHit_ = hit.position;
+ haveLastDab_ = true;
+ doc_.sculptor.dabRecipe(doc_.mesh, doc_.bvh, *recipe, p, symmetry_);
+ return;
+ }
+ doc_.sculptor.dab(doc_.mesh, doc_.bvh, strokeBrush_, p, symmetry_);
+}
+
+void App::endStroke() {
+ UndoRecord r = doc_.sculptor.endStroke();
+ if (!r.empty()) {
+ doc_.undo.push(std::move(r));
+ doc_.modified = true;
+ updateTitle();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Commands & files
+// ---------------------------------------------------------------------------
+
+void App::runCommand(const std::string& name, const Args& args) {
+ if (doc_.sculptor.strokeActive()) endStroke();
+ CommandResult r = commands_.execute(doc_, name, args);
+ status_ = r.message;
+ if (r.ok && name != "export_glb" && name != "export_lods" && name != "export_usd" && name != "export_fbx" &&
+ name != "export_unreal" && name.rfind("unreal_", 0) != 0 && name != "save_obj" &&
+ name != "mesh_info" && name.rfind("brush_", 0) != 0 && name.rfind("splat_", 0) != 0 && name != "mesh_to_splats") {
+ clearLods();
+ playingLayer_ = -1;
+ }
+ if (r.ok && name == "save_obj" && !doc_.mesh.layers.empty())
+ status_ += " (OBJ stores the current blend; export GLB to keep layers as blend shapes)";
+ if (!r.ok) SDL_Log("%s failed: %s", name.c_str(), r.message.c_str());
+ if (r.ok && (name == "new_sphere" || name == "new_plane" || name == "open_obj" || name == "open" ||
+ name == "image_relief" || name == "image_inflate" || name == "splat_to_mesh" ||
+ (name == "splat_transform" && args.contains("fit"))))
+ camera_.frame(sceneBounds());
+ updateTitle();
+}
+
+namespace {
+
+void SDLCALL onFileChosen(void* userdata, const char* const* files, int) {
+ if (!files || !files[0]) return;
+ auto* req = static_cast<App::DialogRequest*>(userdata);
+ req->app->queueFile(req->action, files[0]);
+}
+
+} // namespace
+
+void App::queueFile(FileAction action, std::string path) {
+ if (action != FileAction::OpenObj && action != FileAction::LoadBrush && action != FileAction::OpenImage &&
+ std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())
+ path += action == FileAction::SaveObj ? ".obj"
+ : action == FileAction::SaveBrush ? ".sfbrush"
+ : action == FileAction::ExportUsd ? ".usdz"
+ : action == FileAction::SaveSplats ? ".ply"
+ : action == FileAction::ExportUnreal ? ".fbx"
+ : ".glb";
+ std::lock_guard lock(pendingMutex_);
+ pendingFiles_.push_back({action, std::move(path)});
+}
+
+void App::openFileDialog() {
+ SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::OpenObj)], window_, kModelFilters, 2,
+ nullptr, false);
+}
+
+// Opens models, brushes or reference images based on the file type.
+void App::openPath(const std::string& path) {
+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ if (Image::isImagePath(path)) {
+ if (loadReferenceImage(path)) showImageTo3D_ = true;
+ } else if (ext == ".sfbrush") {
+ runCommand("brush_load", {{"path", path}});
+ } else {
+ runCommand("open", {{"path", path}});
+ }
+}
+
+void App::saveFileDialog(FileAction action) {
+ const bool obj = action == FileAction::SaveObj;
+ const SDL_DialogFileFilter* filters = obj ? kObjFilters
+ : action == FileAction::SaveBrush ? kBrushFilters
+ : action == FileAction::ExportUsd ? kUsdFilters
+ : action == FileAction::SaveSplats ? kSplatFilters
+ : action == FileAction::ExportUnreal ? kFbxFilters
+ : kGlbFilters;
+ const int count = action == FileAction::SaveSplats ? 3 : 2;
+ SDL_ShowSaveFileDialog(onFileChosen, &dialogRequests_[int(action)], window_, filters, count,
+ obj && !doc_.path.empty() ? doc_.path.c_str() : nullptr);
+}
+
+AABB App::sceneBounds() const {
+ AABB b = doc_.mesh.bounds();
+ if (!doc_.splats.empty() && renderSettings_.showSplats) b.expand(doc_.splats.bounds(0.9f));
+ return b;
+}
+
+void App::processPendingFiles() {
+ std::vector<PendingFile> files;
+ {
+ std::lock_guard lock(pendingMutex_);
+ files.swap(pendingFiles_);
+ }
+ for (const auto& f : files) {
+ switch (f.action) {
+ case FileAction::OpenObj: openPath(f.path); break;
+ case FileAction::OpenImage: openPath(f.path); break;
+ case FileAction::SaveObj: runCommand("save_obj", {{"path", f.path}}); break;
+ case FileAction::ExportGlb: runCommand("export_glb", {{"path", f.path}}); break;
+ case FileAction::ExportLods:
+ runCommand("export_lods", {{"path", f.path}, {"levels", double(lodLevels_)}, {"ratio", double(lodRatio_)}});
+ break;
+ case FileAction::SaveBrush: runCommand("brush_save", {{"path", f.path}}); break;
+ case FileAction::LoadBrush: runCommand("brush_load", {{"path", f.path}}); break;
+ case FileAction::ExportUsd: runCommand("export_usd", {{"path", f.path}}); break;
+ case FileAction::SaveSplats: runCommand("splat_save", {{"path", f.path}}); break;
+ case FileAction::ExportUnreal: {
+ auto p = std::filesystem::path(std::u8string(f.path.begin(), f.path.end()));
+ auto folder = p.parent_path().u8string();
+ auto stem = p.stem().u8string();
+ runCommand("export_unreal", {{"folder", std::string(folder.begin(), folder.end())},
+ {"name", std::string(stem.begin(), stem.end())},
+ {"height_cm", double(unrealHeightCm_)},
+ {"lods", double(lodLevels_)},
+ {"ratio", double(lodRatio_)}});
+ break;
+ }
+ case FileAction::Count: break;
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Sculpt layers & LODs
+// ---------------------------------------------------------------------------
+
+Mesh& App::displayedMesh() {
+ return previewLod_ >= 0 && previewLod_ < int(lods_.size()) ? lods_[previewLod_] : doc_.mesh;
+}
+
+void App::setLayerWeight(int index, float weight) {
+ doc_.mesh.setLayerWeight(index, weight);
+ doc_.bvhDirty = true;
+ doc_.modified = true;
+ for (auto& lod : lods_) lod.setLayerWeight(index, weight); // LODs share the blend shapes
+}
+
+void App::animateLayers(float dt) {
+ if (playingLayer_ < 0 || playingLayer_ >= int(doc_.mesh.layers.size())) {
+ playingLayer_ = -1;
+ return;
+ }
+ playTime_ += dt;
+ setLayerWeight(playingLayer_, 0.5f - 0.5f * std::cos(playTime_ * 3.0f));
+}
+
+void App::generateLods() {
+ Uint64 start = SDL_GetTicksNS();
+ lods_ = sf::generateLods(doc_.mesh, lodLevels_, lodRatio_);
+ lastDisplayed_ = nullptr;
+ previewLod_ = int(lods_.size()) - 1;
+ status_ = "Generated " + std::to_string(lods_.size()) + " LODs in " +
+ std::to_string(int(double(SDL_GetTicksNS() - start) * 1e-6)) + " ms";
+}
+
+void App::clearLods() {
+ lods_.clear();
+ previewLod_ = -1;
+ lastDisplayed_ = nullptr;
+}
+
+void App::updateTitle() {
+ std::string name = doc_.path.empty()
+ ? std::string("Untitled")
+ : std::filesystem::path(std::u8string(doc_.path.begin(), doc_.path.end())).filename().string();
+ std::string title = (doc_.modified ? "* " : "") + name + " - SculptForge";
+ SDL_SetWindowTitle(window_, title.c_str());
+}
+
+// ---------------------------------------------------------------------------
+// UI
+// ---------------------------------------------------------------------------
+
+void App::drawUi() {
+ drawMenuBar();
+ drawToolPanel();
+ if (showLayersPanel_) drawLayersPanel();
+ if (showGamePanel_) drawGameExportPanel();
+ drawSplatSection();
+ if (showBrushLab_) drawBrushLab();
+ if (showImageTo3D_) drawImageTo3D();
+ if (previewLod_ >= 0) {
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ std::string banner = "Previewing LOD" + std::to_string(previewLod_) + " - " +
+ std::to_string(lods_[previewLod_].triangleCount()) + " tris (sculpting paused)";
+ ImVec2 size = ImGui::CalcTextSize(banner.c_str());
+ ImGui::GetForegroundDrawList()->AddText(
+ ImVec2(vp->Pos.x + (vp->Size.x - size.x) * 0.5f, vp->Pos.y + vp->Size.y - size.y - 16.0f),
+ IM_COL32(255, 190, 120, 255), banner.c_str());
+ }
+ if (!ImGui::GetIO().WantCaptureMouse || drag_ == Drag::Stroke) drawBrushCursor();
+
+ if (showAbout_) {
+ ImGui::SetNextWindowSize(ImVec2(460 * uiScale_, 0), ImGuiCond_Always);
+ ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (ImGui::Begin("About SculptForge", &showAbout_, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse)) {
+ ImGui::Text("SculptForge %s", SCULPTFORGE_VERSION);
+ ImGui::TextWrapped("Free and open-source digital sculpting.");
+ ImGui::Spacing();
+ ImGui::TextWrapped("Copyright (C) 2026 The SculptForge contributors. This program is free software: you can "
+ "redistribute it and/or modify it under the terms of the GNU General Public License, "
+ "version 3 or later. It comes with ABSOLUTELY NO WARRANTY.");
+ ImGui::Spacing();
+ ImGui::TextWrapped("Built with SDL 3 (zlib), Dear ImGui (MIT), GLM (MIT), stb (MIT/public domain), ufbx "
+ "(MIT/public domain) and the Inter typeface (SIL OFL 1.1). Uses libcurl (curl license) "
+ "where available.");
+ ImGui::Spacing();
+ if (ImGui::Button("License")) SDL_OpenURL("https://github.com/islandmed/SculptForge/blob/main/LICENSE");
+ ImGui::SameLine();
+ if (ImGui::Button("Third-party notices"))
+ SDL_OpenURL("https://github.com/islandmed/SculptForge/blob/main/THIRD_PARTY_NOTICES.md");
+ ImGui::SameLine();
+ if (ImGui::Button("AI services & privacy"))
+ SDL_OpenURL("https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md");
+ }
+ ImGui::End();
+ }
+ if (showHelp_) {
+ ImGui::SetNextWindowSize(ImVec2(440, 0), ImGuiCond_FirstUseEver);
+ if (ImGui::Begin("Controls", &showHelp_)) {
+ ImGui::TextUnformatted(
+ "Sculpt Left drag on the model\n"
+ "Invert (subtract) Hold Alt while sculpting\n"
+ "Smooth Hold Shift while sculpting\n"
+ "Rotate Left drag on background / right drag\n"
+ "Pan Alt + left drag background / middle drag\n"
+ "Zoom Mouse wheel / Ctrl + left drag background\n"
+ "Brush size [ and ]\n"
+ "Brushes 1-8\n"
+ "Symmetry X X\n"
+ "Wireframe W\n"
+ "Frame model F\n"
+ "Subdivide Ctrl+D\n"
+ "Undo / Redo Ctrl+Z / Ctrl+Shift+Z\n"
+ "Open / Save Ctrl+O / Ctrl+S\n"
+ "Tablet pressure is used automatically when a pen is detected.\n"
+ "Drop a model (.obj/.glb), brush (.sfbrush) or image onto the window.");
+ }
+ ImGui::End();
+ }
+}
+
+void App::drawMenuBar() {
+ if (!ImGui::BeginMainMenuBar()) return;
+ if (ImGui::BeginMenu("File")) {
+ if (ImGui::MenuItem("New Sphere", "Ctrl+N")) runCommand("new_sphere");
+ if (ImGui::MenuItem("New Plane")) runCommand("new_plane");
+ ImGui::Separator();
+ if (ImGui::MenuItem("Open Model...", "Ctrl+O")) openFileDialog();
+ if (ImGui::MenuItem("Generate 3D..."))
+ SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::OpenImage)], window_, kImageFilters, 2,
+ nullptr, false);
+ if (ImGui::MenuItem("Save", "Ctrl+S", false, !doc_.path.empty())) runCommand("save_obj");
+ if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) saveFileDialog(FileAction::SaveObj);
+ ImGui::Separator();
+ if (ImGui::MenuItem("Export GLB (blend shapes)...", "Ctrl+E")) saveFileDialog(FileAction::ExportGlb);
+ if (ImGui::MenuItem("Export LOD Chain...")) saveFileDialog(FileAction::ExportLods);
+ if (ImGui::MenuItem("Export USD / USDZ...")) saveFileDialog(FileAction::ExportUsd);
+ if (ImGui::MenuItem("Export FBX for Unreal...")) saveFileDialog(FileAction::ExportUnreal);
+ if (ImGui::MenuItem("Send to Unreal", "Ctrl+U", false, !pendingUnreal_.valid())) sendToUnreal();
+ if (ImGui::MenuItem("Save Splats...", nullptr, false, !doc_.splats.empty())) saveFileDialog(FileAction::SaveSplats);
+ ImGui::Separator();
+ if (ImGui::MenuItem("Quit")) running_ = false;
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Edit")) {
+ std::string undoText = doc_.undo.canUndo() ? "Undo " + doc_.undo.undoLabel() : "Undo";
+ std::string redoText = doc_.undo.canRedo() ? "Redo " + doc_.undo.redoLabel() : "Redo";
+ if (ImGui::MenuItem(undoText.c_str(), "Ctrl+Z", false, doc_.undo.canUndo())) runCommand("undo");
+ if (ImGui::MenuItem(redoText.c_str(), "Ctrl+Shift+Z", false, doc_.undo.canRedo())) runCommand("redo");
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Mesh")) {
+ if (ImGui::MenuItem("Subdivide", "Ctrl+D")) runCommand("subdivide");
+ if (ImGui::MenuItem("Voxel Remesh")) runCommand("remesh", {{"resolution", double(voxelResolution_)}});
+ if (ImGui::MenuItem("Sculpt to Splats")) runCommand("mesh_to_splats");
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("View")) {
+ ImGui::MenuItem("Wireframe", "W", &renderSettings_.wireframe);
+ ImGui::MenuItem("Show Mesh", nullptr, &renderSettings_.showMesh);
+ ImGui::Separator();
+ ImGui::MenuItem("Layers Panel", nullptr, &showLayersPanel_);
+ ImGui::MenuItem("Game Ready Panel", nullptr, &showGamePanel_);
+ ImGui::MenuItem("Gaussian Splats", nullptr, &showSplatsPanel_);
+ ImGui::MenuItem("Brush Lab", nullptr, &showBrushLab_);
+ ImGui::MenuItem("Generate 3D", nullptr, &showImageTo3D_);
+ ImGui::MenuItem("Show Splats", nullptr, &renderSettings_.showSplats, !doc_.splats.empty());
+ if (ImGui::MenuItem("Frame Model", "F")) camera_.frame(sceneBounds());
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Help")) {
+ ImGui::MenuItem("Controls", "F1", &showHelp_);
+ ImGui::MenuItem("About SculptForge", nullptr, &showAbout_);
+ if (ImGui::MenuItem("Website & documentation")) SDL_OpenURL("https://islandmed.github.io/SculptForge/");
+ if (ImGui::MenuItem("Report a problem")) SDL_OpenURL("https://github.com/islandmed/SculptForge/issues");
+ ImGui::EndMenu();
+ }
+ ImGui::EndMainMenuBar();
+}
+
+void App::drawLayersPanel() {
+ const float scale = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + vp->Size.x - 290 * scale, vp->Pos.y + 34 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(280 * scale, 0), ImVec2(280 * scale, FLT_MAX));
+ if (!ImGui::Begin("Layers / Blend Shapes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+ ImGui::TextDisabled("Sculpt expressions & correctives;\nexported as glTF morph targets.");
+
+ if (ImGui::RadioButton("Base mesh", doc_.activeLayer < 0)) runCommand("layer_set_active", {{"index", -1.0}});
+
+ int removeIndex = -1;
+ for (int i = 0; i < int(doc_.mesh.layers.size()); ++i) {
+ SculptLayer& layer = doc_.mesh.layers[i];
+ ImGui::PushID(i);
+ ImGui::Separator();
+ if (ImGui::RadioButton(layer.name.c_str(), doc_.activeLayer == i))
+ runCommand("layer_set_active", {{"index", double(i)}});
+ ImGui::SameLine(ImGui::GetContentRegionAvail().x - 52 * scale);
+ const bool playing = playingLayer_ == i;
+ if (ImGui::SmallButton(playing ? "Stop" : "Play")) {
+ playingLayer_ = playing ? -1 : i;
+ playTime_ = 0.0f;
+ if (playing) setLayerWeight(i, 1.0f);
+ }
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Animate this blend shape 0 -> 1 -> 0");
+ ImGui::SameLine();
+ if (ImGui::SmallButton("X")) removeIndex = i;
+ float w = layer.weight;
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::SliderFloat("##weight", &w, 0.0f, 1.0f, "weight %.2f")) {
+ if (playingLayer_ == i) playingLayer_ = -1;
+ setLayerWeight(i, w);
+ }
+ ImGui::PopID();
+ }
+ if (removeIndex >= 0) {
+ if (playingLayer_ == removeIndex) playingLayer_ = -1;
+ runCommand("layer_remove", {{"index", double(removeIndex)}});
+ }
+
+ ImGui::Separator();
+ ImGui::SetNextItemWidth(-ImGui::CalcTextSize("+ Add").x - ImGui::GetStyle().FramePadding.x * 2 -
+ ImGui::GetStyle().ItemSpacing.x);
+ bool enter = ImGui::InputText("##newlayer", newLayerName_, sizeof newLayerName_,
+ ImGuiInputTextFlags_EnterReturnsTrue);
+ ImGui::SameLine();
+ if (ImGui::Button("+ Add") || enter) runCommand("layer_add", {{"name", std::string(newLayerName_)}});
+ ImGui::End();
+}
+
+void App::sendToUnreal() {
+ if (pendingUnreal_.valid()) return;
+ UnrealExportOptions o;
+ o.heightCm = unrealHeightCm_;
+ o.lods = lodLevels_;
+ o.ratio = lodRatio_;
+ o.folder = (std::filesystem::temp_directory_path() / "sculptforge_unreal").string();
+ UnrealExportResult r;
+ std::string err;
+ if (!exportForUnreal(doc_, o, r, err)) {
+ status_ = "Export failed: " + err;
+ return;
+ }
+ link::UnrealImport import;
+ import.fbxPath = r.path;
+ import.destination = unrealDestination_;
+ import.assetName = r.assetName;
+ import.skeletal = r.skeletal;
+ import.lods = r.lodCount > 1;
+ status_ = "Sending " + r.assetName + " to Unreal...";
+ auto promise = std::make_shared<std::promise<std::string>>();
+ pendingUnreal_ = promise->get_future();
+ std::thread([promise, import, network = unrealNetwork_] {
+ std::string message;
+ link::sendToUnreal(network ? link::UnrealEndpoint::network() : link::UnrealEndpoint(), import, message);
+ promise->set_value(message);
+ }).detach();
+}
+
+void App::pollUnreal() {
+ if (!pendingUnreal_.valid() || pendingUnreal_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return;
+ status_ = pendingUnreal_.get();
+}
+
+void App::drawGameExportPanel() {
+ const float scale = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + vp->Size.x - 290 * scale, vp->Pos.y + 330 * scale),
+ ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(280 * scale, 0), ImVec2(280 * scale, FLT_MAX));
+ if (!ImGui::Begin("Game Ready", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+ ImGui::PushItemWidth(-ImGui::CalcTextSize("Reduction").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ if (ImGui::SliderInt("LODs", &lodLevels_, 2, 6)) clearLods();
+ if (ImGui::SliderFloat("Reduction", &lodRatio_, 0.1f, 0.9f, "x%.2f / level")) clearLods();
+ ImGui::PopItemWidth();
+ if (ImGui::Button(lods_.empty() ? "Generate LOD chain" : "Regenerate", ImVec2(-1, 0))) generateLods();
+
+ if (!lods_.empty()) {
+ if (ImGui::BeginTable("lods", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) {
+ ImGui::TableSetupColumn("Level");
+ ImGui::TableSetupColumn("Triangles");
+ ImGui::TableSetupColumn("Budget");
+ ImGui::TableHeadersRow();
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ if (ImGui::Selectable("Sculpt", previewLod_ < 0, ImGuiSelectableFlags_SpanAllColumns)) {
+ previewLod_ = -1;
+ }
+ ImGui::TableNextColumn();
+ ImGui::Text("%zu", doc_.mesh.triangleCount());
+ ImGui::TableNextColumn();
+ ImGui::TextDisabled("editable");
+ for (int i = 0; i < int(lods_.size()); ++i) {
+ ImGui::TableNextRow();
+ ImGui::TableNextColumn();
+ std::string label = "LOD" + std::to_string(i);
+ if (ImGui::Selectable(label.c_str(), previewLod_ == i, ImGuiSelectableFlags_SpanAllColumns)) {
+ previewLod_ = i;
+ renderSettings_.wireframe = true;
+ }
+ ImGui::TableNextColumn();
+ ImGui::Text("%zu", lods_[i].triangleCount());
+ ImGui::TableNextColumn();
+ ImGui::Text("%.1f%%", 100.0 * double(lods_[i].triangleCount()) / double(lods_[0].triangleCount()));
+ }
+ ImGui::EndTable();
+ }
+ ImGui::TextDisabled("Click a level to inspect it in the viewport.");
+ }
+
+ ImGui::SeparatorText("Unreal Engine");
+ ImGui::PushItemWidth(-ImGui::CalcTextSize("Folder").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ ImGui::InputText("Folder", unrealDestination_, sizeof unrealDestination_);
+ if (unrealHeightCm_ <= 0.0f) unrealHeightCm_ = std::max(1.0f, doc_.mesh.bounds().extent().y * 100.0f);
+ ImGui::DragFloat("Height", &unrealHeightCm_, 1.0f, 1.0f, 100000.0f, "%.0f cm");
+ ImGui::PopItemWidth();
+ ImGui::Checkbox("Unreal is on another computer", &unrealNetwork_);
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("In Unreal: Project Settings > Plugins > Python > Advanced:\nMulticast Time-To-Live = 1, "
+ "Multicast Bind Address = 0.0.0.0");
+ if (pendingUnreal_.valid()) {
+ ImGui::ProgressBar(-1.0f * float(ImGui::GetTime()), ImVec2(-1, 0), "Sending to Unreal...");
+ } else if (ImGui::Button("Send to Unreal", ImVec2(-1, 0))) {
+ sendToUnreal();
+ }
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("Imports (or updates) the asset in the open Unreal Editor.\nNeeds the Python Editor Script "
+ "Plugin and Project Settings > Python > Enable Remote Execution.");
+ if (ImGui::Button("Export FBX for Unreal...", ImVec2(-1, 0))) saveFileDialog(FileAction::ExportUnreal);
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ if (doc_.mesh.layers.empty()) ImGui::TextWrapped("Static mesh with %d LODs.", lodLevels_);
+ else ImGui::TextWrapped("Skeletal mesh with %zu morph targets.", doc_.mesh.layers.size());
+ ImGui::PopStyleColor();
+
+ ImGui::SeparatorText("Export");
+ if (ImGui::Button("GLB + blend shapes", ImVec2(-1, 0))) saveFileDialog(FileAction::ExportGlb);
+ if (ImGui::Button("LOD chain (GLB per level)", ImVec2(-1, 0))) saveFileDialog(FileAction::ExportLods);
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Unreal, Unity, Godot, Blender, three.js");
+ ImGui::PopStyleColor();
+ ImGui::End();
+}
+
+// ---------------------------------------------------------------------------
+// Brush Lab: describe a brush in words, get a recipe, tweak it with sliders
+// ---------------------------------------------------------------------------
+
+const BrushRecipe* App::activeRecipe() const {
+ return doc_.activeBrush >= 0 && doc_.activeBrush < int(doc_.brushes.size()) ? &doc_.brushes[doc_.activeBrush]
+ : nullptr;
+}
+
+void App::sendBrushRequest(const std::string& text) {
+ if (text.empty() || pendingBrush_.valid()) return;
+ chat_.push_back(ai::composeUserMessage(text, refineCurrent_ ? activeRecipe() : nullptr));
+ chatLog_.push_back({ChatLine::Kind::User, text});
+ scrollChat_ = true;
+ busyTime_ = 0.0f;
+
+ // Detached worker with its own copies, so quitting never waits on the network.
+ auto promise = std::make_shared<std::promise<BrushReply>>();
+ pendingBrush_ = promise->get_future();
+ std::thread([promise, settings = aiSettings_, history = chat_] {
+ BrushReply reply;
+ reply.suggestion = ai::requestBrush(settings, history, &reply.raw);
+ promise->set_value(std::move(reply));
+ }).detach();
+}
+
+void App::pollBrushRequest() {
+ if (!pendingBrush_.valid() || pendingBrush_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return;
+ BrushReply reply = pendingBrush_.get();
+ scrollChat_ = true;
+ if (!reply.suggestion.ok) {
+ chat_.pop_back(); // keep the model's history to successful turns
+ chatLog_.push_back({ChatLine::Kind::Error, reply.suggestion.error});
+ return;
+ }
+ chat_.push_back({ai::ChatMessage::Role::Assistant, reply.raw, reply.suggestion.reply});
+ doc_.activeBrush = doc_.addBrush(reply.suggestion.recipe);
+ chatLog_.push_back({ChatLine::Kind::Assistant, "[" + reply.suggestion.recipe.name + "] " + reply.suggestion.reply});
+ status_ = "Brush '" + reply.suggestion.recipe.name + "' is ready - try it on the model";
+}
+
+void App::drawRecipeEditor(BrushRecipe& recipe) {
+ char name[64];
+ std::snprintf(name, sizeof name, "%s", recipe.name.c_str());
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::InputText("##name", name, sizeof name, ImGuiInputTextFlags_EnterReturnsTrue) && name[0])
+ recipe.name = name;
+ ImGui::PushItemWidth(-ImGui::CalcTextSize("Pressure curve").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ for (const auto& p : recipeParams()) {
+ switch (p.kind) {
+ case RecipeParam::Kind::Float:
+ ImGui::SliderFloat(p.label, recipe.field(p.key), p.min, p.max, "%.2f");
+ break;
+ case RecipeParam::Kind::Bool: ImGui::Checkbox(p.label, &recipe.frontFacesOnly); break;
+ case RecipeParam::Kind::Enum: {
+ int idx = recipe.enumIndex(p.key);
+ if (ImGui::Combo(p.label, &idx, p.options.data(), int(p.options.size()))) recipe.setEnumIndex(p.key, idx);
+ break;
+ }
+ }
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal)) ImGui::SetTooltip("%s", p.help);
+ }
+ ImGui::PopItemWidth();
+ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ if (ImGui::Button("Save .sfbrush...", ImVec2(half, 0))) saveFileDialog(FileAction::SaveBrush);
+ ImGui::SameLine();
+ if (ImGui::Button("Load .sfbrush...", ImVec2(half, 0)))
+ SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::LoadBrush)], window_, kBrushFilters, 2,
+ nullptr, false);
+}
+
+void App::drawAiSettings() {
+ using P = ai::AiSettings::Provider;
+ const char* providers[] = {"Anthropic (Claude)", "OpenAI-compatible (OpenAI, Ollama, LM Studio...)"};
+ int provider = int(aiSettings_.provider);
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::Combo("##provider", &provider, providers, 2)) {
+ std::string key = aiSettings_.apiKey;
+ aiSettings_ = ai::AiSettings::defaults(P(provider));
+ aiSettings_.apiKey = key;
+ }
+ auto textField = [](const char* label, std::string& value, ImGuiInputTextFlags flags = 0) {
+ char buf[512];
+ std::snprintf(buf, sizeof buf, "%s", value.c_str());
+ ImGui::SetNextItemWidth(-ImGui::CalcTextSize("Endpoint").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ if (ImGui::InputText(label, buf, sizeof buf, flags)) value = buf;
+ };
+ textField("Endpoint", aiSettings_.endpoint);
+ textField("Model", aiSettings_.model);
+ textField("API key", aiSettings_.apiKey, ImGuiInputTextFlags_Password);
+ if (aiSettings_.provider == P::Anthropic) {
+ const char* efforts[] = {"low", "medium", "high"};
+ int e = aiSettings_.effort == "high" ? 2 : aiSettings_.effort == "medium" ? 1 : 0;
+ ImGui::SetNextItemWidth(-ImGui::CalcTextSize("Endpoint").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ if (ImGui::Combo("Effort", &e, efforts, 3)) aiSettings_.effort = efforts[e];
+ }
+ if (ImGui::Button("Save settings", ImVec2(-1, 0))) {
+ std::string err;
+ status_ = aiSettingsPath_.empty() || !aiSettings_.save(aiSettingsPath_, err) ? "Could not save AI settings " + err
+ : "AI settings saved";
+ }
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Opt-in and private: requests go only to the endpoint above. Keys are stored on this "
+ "computer only (owner-readable ai.json); leave empty to use ANTHROPIC_API_KEY / "
+ "OPENAI_API_KEY. For free, offline use, run Ollama and pick OpenAI-compatible.");
+ ImGui::PopStyleColor();
+}
+
+void App::drawBrushLab() {
+ const float scale = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ // First use: bottom of the window, right of the Tools panel.
+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + 270 * scale, std::max(vp->Pos.y + 34 * scale,
+ vp->Pos.y + vp->Size.y - 470 * scale)),
+ ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(420 * scale, 0), ImVec2(420 * scale, FLT_MAX));
+ if (!ImGui::Begin("Brush Lab", &showBrushLab_, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+ ImGui::TextWrapped("Describe a brush the way you'd describe it to another sculptor.");
+
+ // Conversation
+ if (ImGui::BeginChild("chat", ImVec2(-1, 150 * scale), ImGuiChildFlags_Borders)) {
+ if (chatLog_.empty()) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Try one of the ideas below, or ask for changes to the selected brush, e.g. "
+ "\"sharper\", \"less buildup\", \"make it grittier\".");
+ ImGui::PopStyleColor();
+ }
+ for (const auto& line : chatLog_) {
+ ImVec4 col = line.kind == ChatLine::Kind::User ? ImVec4(1.0f, 0.70f, 0.45f, 1.0f)
+ : line.kind == ChatLine::Kind::Error ? ImVec4(1.0f, 0.45f, 0.45f, 1.0f)
+ : ImVec4(0.85f, 0.88f, 0.95f, 1.0f);
+ ImGui::PushStyleColor(ImGuiCol_Text, col);
+ ImGui::TextWrapped("%s %s", line.kind == ChatLine::Kind::User ? ">" : " ", line.text.c_str());
+ ImGui::PopStyleColor();
+ }
+ if (pendingBrush_.valid()) {
+ busyTime_ += ImGui::GetIO().DeltaTime;
+ int dots = int(busyTime_ * 3.0f) % 4;
+ ImGui::TextDisabled(" Designing brush%.*s", dots, "...");
+ }
+ if (scrollChat_) {
+ ImGui::SetScrollHereY(1.0f);
+ scrollChat_ = false;
+ }
+ }
+ ImGui::EndChild();
+
+ // Starter ideas
+ for (int i = 0; i < int(std::size(kExamplePrompts)); ++i) {
+ float w = ImGui::CalcTextSize(kExamplePrompts[i]).x + ImGui::GetStyle().FramePadding.x * 2;
+ if (i > 0 && ImGui::GetItemRectMax().x + ImGui::GetStyle().ItemSpacing.x + w <
+ ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x)
+ ImGui::SameLine();
+ ImGui::BeginDisabled(pendingBrush_.valid());
+ if (ImGui::SmallButton(kExamplePrompts[i])) sendBrushRequest(kExamplePrompts[i]);
+ ImGui::EndDisabled();
+ }
+
+ // Input
+ const char* sendLabel = "Create";
+ ImGui::SetNextItemWidth(-ImGui::CalcTextSize(sendLabel).x - ImGui::GetStyle().FramePadding.x * 2 -
+ ImGui::GetStyle().ItemSpacing.x);
+ bool submit = ImGui::InputTextWithHint("##prompt", "e.g. bark of an old oak tree", chatInput_, sizeof chatInput_,
+ ImGuiInputTextFlags_EnterReturnsTrue);
+ ImGui::SameLine();
+ ImGui::BeginDisabled(pendingBrush_.valid());
+ submit |= ImGui::Button(sendLabel);
+ ImGui::EndDisabled();
+ if (submit && chatInput_[0] && !pendingBrush_.valid()) {
+ sendBrushRequest(chatInput_);
+ chatInput_[0] = '\0';
+ ImGui::SetKeyboardFocusHere(-1);
+ }
+ ImGui::BeginDisabled(!activeRecipe());
+ ImGui::Checkbox("Refine the selected brush", &refineCurrent_);
+ ImGui::EndDisabled();
+ ImGui::SameLine();
+ if (ImGui::SmallButton("Clear chat")) {
+ chat_.clear();
+ chatLog_.clear();
+ }
+
+ if (BrushRecipe* recipe = doc_.activeBrush >= 0 ? &doc_.brushes[doc_.activeBrush] : nullptr) {
+ if (ImGui::CollapsingHeader(("Recipe: " + recipe->name + "###recipe").c_str())) drawRecipeEditor(*recipe);
+ }
+ if (ImGui::CollapsingHeader("AI provider")) drawAiSettings();
+ ImGui::End();
+}
+
+// ---------------------------------------------------------------------------
+// Image to 3D
+// ---------------------------------------------------------------------------
+
+bool App::loadReferenceImage(const std::string& path) {
+ Image img;
+ std::string err;
+ if (!Image::load(path, img, err)) {
+ status_ = err;
+ return false;
+ }
+ refImage_ = std::move(img);
+ refImagePath_ = path;
+ if (!refTexture_) gl::GenTextures(1, &refTexture_);
+ gl::BindTexture(GL_TEXTURE_2D, refTexture_);
+ gl::PixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), refImage_.width, refImage_.height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
+ refImage_.rgba.data());
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(GL_CLAMP_TO_EDGE));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLint(GL_CLAMP_TO_EDGE));
+ gl::BindTexture(GL_TEXTURE_2D, 0);
+ status_ = "Loaded image " + std::to_string(refImage_.width) + "x" + std::to_string(refImage_.height);
+ return true;
+}
+
+void App::projectImageFromView() {
+ if (refImage_.empty()) return;
+ int w = 0, h = 0;
+ SDL_GetWindowSize(window_, &w, &h);
+ const AABB b = doc_.mesh.bounds();
+ ProjectOptions o;
+ o.depth = projectDepth_ * glm::length(b.extent());
+ o.invert = projectInvert_;
+ Mesh m = doc_.mesh;
+ size_t n = projectImage(m, doc_.activeLayer, refImage_, camera_.projection() * camera_.view(),
+ float(w) / float(std::max(h, 1)), camera_.position(), o);
+ if (n == 0) {
+ status_ = "The image didn't land on the model - aim the view at it first";
+ return;
+ }
+ doc_.replaceMeshUndoable(std::move(m), "Project Image");
+ clearLods();
+ status_ = "Stamped image onto " + std::to_string(n) + " vertices (Ctrl+Z to undo)";
+ updateTitle();
+}
+
+void App::startGenerator() {
+ if (pendingGenerator_.valid()) return;
+ if (textMode_ ? textPrompt_[0] == '\0' : refImagePath_.empty()) return;
+ aiSettings_.generatorCommand = generatorCommand_;
+ aiSettings_.falKey = falKey_;
+ aiSettings_.falModel = falModel_;
+ aiSettings_.meshyKey = meshyKey_;
+ aiSettings_.hfToken = hfToken_;
+ auto stem = (std::filesystem::temp_directory_path() / ("sculptforge_generated_" + std::to_string(SDL_GetTicksNS()))).u8string();
+ generatorTime_ = 0.0f;
+ generatorProgress_ = std::make_shared<ai::GenerationProgress>();
+ generatorProgress_->setStatus("Starting...");
+ auto promise = std::make_shared<std::promise<ai::GeneratorResult>>();
+ pendingGenerator_ = promise->get_future();
+ std::thread([promise, settings = aiSettings_, in = refImagePath_, text = textMode_ ? std::string(textPrompt_) : std::string(),
+ out = std::string(stem.begin(), stem.end()), progress = generatorProgress_] {
+ promise->set_value(text.empty() ? ai::generate3D(settings, in, out, progress.get())
+ : ai::generate3DFromText(settings, text, out, progress.get()));
+ }).detach();
+}
+
+void App::pollGenerator() {
+ if (!pendingGenerator_.valid() || pendingGenerator_.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
+ return;
+ ai::GeneratorResult r = pendingGenerator_.get();
+ if (!r.ok) {
+ status_ = "Image to 3D failed: " + r.error;
+ return;
+ }
+ runCommand("open", {{"path", r.outputPath}});
+ std::error_code ec;
+ std::filesystem::remove(std::filesystem::path(std::u8string(r.outputPath.begin(), r.outputPath.end())), ec);
+ const size_t raw = doc_.mesh.triangleCount();
+ if (remeshGenerated_) runCommand("remesh", {{"resolution", double(remeshResolution_)}});
+ doc_.path.clear();
+ status_ = "Generated model imported (" + std::to_string(raw) + " tris" +
+ (remeshGenerated_ ? ", remeshed to " + std::to_string(doc_.mesh.triangleCount()) : std::string()) +
+ ") - ready to sculpt";
+ updateTitle();
+}
+
+void App::drawImageTo3D() {
+ const float scale = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + vp->Size.x - 590 * scale, vp->Pos.y + 34 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(290 * scale, 0), ImVec2(290 * scale, FLT_MAX));
+ if (!ImGui::Begin("Generate 3D", &showImageTo3D_, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+ if (ImGui::BeginTabBar("##source")) {
+ if (ImGui::BeginTabItem("From image")) {
+ textMode_ = false;
+ ImGui::EndTabItem();
+ }
+ if (ImGui::BeginTabItem("From text")) {
+ textMode_ = true;
+ ImGui::EndTabItem();
+ }
+ ImGui::EndTabBar();
+ }
+ if (textMode_) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextMultiline("##textprompt", textPrompt_, sizeof textPrompt_, ImVec2(-1, ImGui::GetTextLineHeight() * 3.5f));
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Describe one object: \"a stylised dragon head with curled horns\", \"a cartoon fox sitting\".");
+ ImGui::PopStyleColor();
+ } else {
+ if (ImGui::Button(refImage_.empty() ? "Choose image..." : "Change image...", ImVec2(-1, 0)))
+ SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::OpenImage)], window_, kImageFilters, 2,
+ nullptr, false);
+ if (refImage_.empty()) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Or drop a sketch, concept, logo, photo or height map onto the window.");
+ ImGui::PopStyleColor();
+ ImGui::End();
+ return;
+ }
+ const float thumbW = ImGui::GetContentRegionAvail().x;
+ const float thumbH = std::min(thumbW / refImage_.aspect(), 180.0f * scale);
+ const float drawW = thumbH * refImage_.aspect();
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (thumbW - drawW) * 0.5f);
+ ImGui::Image(ImTextureID(uintptr_t(refTexture_)), ImVec2(drawW, thumbH));
+ auto fileName = std::filesystem::path(std::u8string(refImagePath_.begin(), refImagePath_.end())).filename().u8string();
+ ImGui::TextDisabled("%s (%dx%d)", std::string(fileName.begin(), fileName.end()).c_str(), refImage_.width,
+ refImage_.height);
+ }
+
+ auto hint = [](const char* text) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("%s", text);
+ ImGui::PopStyleColor();
+ };
+ const float labelW = ImGui::CalcTextSize("Resolution").x + ImGui::GetStyle().ItemInnerSpacing.x;
+
+ ImGui::SeparatorText(textMode_ ? "Text to 3D (AI)" : "Full 3D model (AI reconstruction)");
+ hint("Builds the whole model - limbs, face, back - from one picture with a reconstruction model, then makes it "
+ "sculptable. Characters on a transparent background work best.");
+ static const char* services[] = {"Hugging Face - free models", "fal.ai - paid, your key", "Meshy - paid, your key",
+ "My generator command", "Offline blockout (inflate silhouette)"};
+ static const char* serviceIds[] = {"huggingface", "fal", "meshy", "command", "inflate"};
+ int service = 0;
+ for (int i = 0; i < 5; ++i)
+ if (aiSettings_.generatorService == serviceIds[i]) service = i;
+ ImGui::SetNextItemWidth(-1);
+ if (ImGui::Combo("##service", &service, services, 5)) aiSettings_.generatorService = serviceIds[service];
+ ImGui::PushItemWidth(-labelW);
+ if (service == 0) {
+ const auto& presets = ai::hfPresets();
+ const char* preview = presets[0].label;
+ for (const auto& p : presets)
+ if (aiSettings_.hfModel == p.id) preview = p.label;
+ if (ImGui::BeginCombo("Model", preview)) {
+ for (const auto& p : presets)
+ if (ImGui::Selectable(p.label, aiSettings_.hfModel == p.id)) aiSettings_.hfModel = p.id;
+ ImGui::EndCombo();
+ }
+ ImGui::InputText("HF token", hfToken_, sizeof hfToken_, ImGuiInputTextFlags_Password);
+ hint(hfToken_[0] || std::getenv("HF_TOKEN")
+ ? "Runs on Hugging Face's shared GPUs with your account's free daily allowance."
+ : "Runs free on Hugging Face's shared GPUs with a small daily allowance. A free token "
+ "(huggingface.co/settings/tokens, read access) raises it; TRELLIS.2 needs one.");
+ } else if (service == 1) {
+ const auto& models = ai::falModels();
+ const char* preview = falModel_;
+ for (const auto& m : models)
+ if (std::string(falModel_) == m.id) preview = m.label;
+ if (ImGui::BeginCombo("Model", preview)) {
+ for (const auto& m : models)
+ if (ImGui::Selectable(m.label, std::string(falModel_) == m.id))
+ std::snprintf(falModel_, sizeof falModel_, "%s", m.id);
+ ImGui::EndCombo();
+ }
+ ImGui::InputText("Model id", falModel_, sizeof falModel_);
+ ImGui::InputText("API key", falKey_, sizeof falKey_, ImGuiInputTextFlags_Password);
+ if (!falKey_[0]) hint(std::getenv("FAL_KEY") ? "Using FAL_KEY from the environment." : "Get a key at fal.ai/dashboard/keys");
+ } else if (service == 2) {
+ ImGui::InputText("API key", meshyKey_, sizeof meshyKey_, ImGuiInputTextFlags_Password);
+ if (!meshyKey_[0])
+ hint(std::getenv("MESHY_API_KEY") ? "Using MESHY_API_KEY from the environment." : "Get a key at meshy.ai (API settings)");
+ } else if (service == 3) {
+ hint("Any local model or script: {input} = image, {output} = .glb/.obj to write. See docs/generators.md.");
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextMultiline("##generator", generatorCommand_, sizeof generatorCommand_,
+ ImVec2(-1, ImGui::GetTextLineHeight() * 4));
+ } else {
+ hint("Offline and instant, but only a puffy blockout of the outline - not a real reconstruction.");
+ }
+ if (service != 4) {
+ ImGui::Checkbox("Remesh for sculpting", &remeshGenerated_);
+ if (remeshGenerated_) ImGui::SliderInt("Resolution", &remeshResolution_, 96, 400);
+ }
+ ImGui::PopItemWidth();
+ if (pendingGenerator_.valid()) {
+ generatorTime_ += ImGui::GetIO().DeltaTime;
+ const int pct = generatorProgress_ ? generatorProgress_->percent.load() : -1;
+ ImGui::ProgressBar(pct >= 0 ? float(pct) / 100.0f : -1.0f * float(ImGui::GetTime()), ImVec2(-1, 0),
+ generatorProgress_ ? generatorProgress_->status().c_str() : "Working...");
+ if (ImGui::Button("Cancel", ImVec2(-1, 0)) && generatorProgress_) generatorProgress_->cancel = true;
+ } else if (ImGui::Button("Generate 3D model", ImVec2(-1, 0))) {
+ startGenerator();
+ }
+ if (ImGui::SmallButton("Save settings")) {
+ aiSettings_.generatorCommand = generatorCommand_;
+ aiSettings_.falKey = falKey_;
+ aiSettings_.falModel = falModel_;
+ aiSettings_.meshyKey = meshyKey_;
+ aiSettings_.hfToken = hfToken_;
+ std::string err;
+ status_ = !aiSettingsPath_.empty() && aiSettings_.save(aiSettingsPath_, err) ? "Image to 3D settings saved"
+ : "Save failed " + err;
+ }
+
+ if (textMode_) {
+ ImGui::End();
+ return;
+ }
+ ImGui::SeparatorText("Quick shapes (offline)");
+ if (ImGui::TreeNode("Silhouette blockout")) {
+ hint("Inflates the outline into a rounded blob - good for simple shapes, not characters.");
+ ImGui::PushItemWidth(-labelW);
+ ImGui::SliderFloat("Thickness", &inflateThickness_, 0.2f, 2.0f, "%.2f");
+ ImGui::SliderInt("Detail##inflate", &inflateDetail_, 64, 384);
+ ImGui::PopItemWidth();
+ if (ImGui::Button("Inflate", ImVec2(-1, 0)))
+ runCommand("image_inflate", {{"path", refImagePath_},
+ {"thickness", double(inflateThickness_)},
+ {"resolution", double(inflateDetail_)},
+ {"subdivisions", 2.0}});
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Relief")) {
+ hint("Light areas rise: logos, coins, emblems, height maps, texture photos.");
+ ImGui::PushItemWidth(-labelW);
+ ImGui::SliderFloat("Depth##relief", &reliefDepth_, 0.01f, 0.5f, "%.2f");
+ ImGui::SliderInt("Detail##relief", &reliefDetail_, 64, 1024);
+ ImGui::PopItemWidth();
+ ImGui::Checkbox("Dark is high##relief", &reliefInvert_);
+ if (ImGui::Button("Make relief", ImVec2(-1, 0)))
+ runCommand("image_relief", {{"path", refImagePath_},
+ {"depth", double(reliefDepth_)},
+ {"resolution", double(reliefDetail_)},
+ {"invert", reliefInvert_}});
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Stamp onto model")) {
+ hint("Projects the image onto the model from the current view as surface detail (uses the active layer).");
+ ImGui::PushItemWidth(-labelW);
+ ImGui::SliderFloat("Depth##project", &projectDepth_, 0.001f, 0.1f, "%.3f", ImGuiSliderFlags_Logarithmic);
+ ImGui::PopItemWidth();
+ ImGui::Checkbox("Dark is high##project", &projectInvert_);
+ if (ImGui::Button("Stamp from this view", ImVec2(-1, 0))) projectImageFromView();
+ ImGui::TreePop();
+ }
+ ImGui::End();
+}
+
+void App::drawToolPanel() {
+ const float scale = uiScale_;
+ ImGui::SetNextWindowPos(ImVec2(10 * scale, 34 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(250 * scale, 0), ImVec2(250 * scale, FLT_MAX));
+ if (!ImGui::Begin("Tools", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+
+ ImGui::SeparatorText("Brush");
+ const float bw = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ for (int i = 0; i < int(BrushType::Count); ++i) {
+ const auto type = BrushType(i);
+ const bool selected = brush_ == type && doc_.activeBrush < 0;
+ if (selected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive));
+ std::string label = std::to_string(i + 1) + " " + brushName(type);
+ if (ImGui::Button(label.c_str(), ImVec2(bw, 0))) {
+ brush_ = type;
+ doc_.activeBrush = -1;
+ }
+ if (selected) ImGui::PopStyleColor();
+ if (i % 2 == 0) ImGui::SameLine();
+ }
+
+ ImGui::SeparatorText("Custom brushes");
+ if (ImGui::BeginListBox("##custom", ImVec2(-1, ImGui::GetTextLineHeightWithSpacing() * 5.5f))) {
+ for (int i = 0; i < int(doc_.brushes.size()); ++i) {
+ if (ImGui::Selectable(doc_.brushes[i].name.c_str(), doc_.activeBrush == i)) doc_.activeBrush = i;
+ if (ImGui::IsItemHovered() && !doc_.brushes[i].description.empty())
+ ImGui::SetTooltip("%s", doc_.brushes[i].description.c_str());
+ }
+ ImGui::EndListBox();
+ }
+ if (ImGui::Button(showBrushLab_ ? "Hide Brush Lab" : "Brush Lab (AI)...", ImVec2(-1, 0)))
+ showBrushLab_ = !showBrushLab_;
+ if (ImGui::Button(showImageTo3D_ ? "Hide Generate 3D" : "Generate 3D...", ImVec2(-1, 0)))
+ showImageTo3D_ = !showImageTo3D_;
+
+ ImGui::PushItemWidth(-ImGui::CalcTextSize("Strength").x - ImGui::GetStyle().ItemInnerSpacing.x);
+ ImGui::SliderFloat("Size", &radiusPx_, 2.0f, 800.0f, "%.0f px", ImGuiSliderFlags_Logarithmic);
+ ImGui::SliderFloat("Strength", &strength_, 0.01f, 1.0f, "%.2f");
+ ImGui::PopItemWidth();
+ ImGui::Checkbox("Invert (Alt)", &invertToggle_);
+ ImGui::Checkbox("Front faces only", &frontFacesOnly_);
+
+ ImGui::SeparatorText("Symmetry");
+ ImGui::Checkbox("X", &symmetry_.x);
+ ImGui::SameLine();
+ ImGui::Checkbox("Y", &symmetry_.y);
+ ImGui::SameLine();
+ ImGui::Checkbox("Z", &symmetry_.z);
+
+ ImGui::SeparatorText("Tablet");
+ ImGui::Checkbox("Pressure > strength", &pressureStrength_);
+ ImGui::Checkbox("Pressure > size", &pressureSize_);
+ if (penSeen_) ImGui::Text("Pen pressure: %.2f", penPressure_);
+ else ImGui::TextDisabled("No pen detected");
+
+ ImGui::SeparatorText("Mesh");
+ if (ImGui::Button("Subdivide (Ctrl+D)", ImVec2(-1, 0))) runCommand("subdivide");
+ if (ImGui::Button("Voxel remesh", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 0)))
+ runCommand("remesh", {{"resolution", double(voxelResolution_)}});
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("Rebuild as an even, watertight surface (like DynaMesh): merges parts, fixes scans and generated models.");
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderInt("##voxres", &voxelResolution_, 64, 400, "res %d");
+ ImGui::Checkbox("Wireframe", &renderSettings_.wireframe);
+ ImGui::ColorEdit3("Material", &renderSettings_.baseColor.x, ImGuiColorEditFlags_NoInputs);
+
+ ImGui::Separator();
+ ImGui::Text("%zu verts %zu tris", doc_.mesh.vertexCount(), doc_.mesh.triangleCount());
+ ImGui::Text("%.0f fps", ImGui::GetIO().Framerate);
+ if (!status_.empty()) ImGui::TextWrapped("%s", status_.c_str());
+ ImGui::End();
+}
+
+void App::drawSplatSection() {
+ // Opens by itself whenever splats arrive (file, command or AI agent).
+ if (doc_.splatsVersion != seenSplatsVersion_) {
+ seenSplatsVersion_ = doc_.splatsVersion;
+ if (!doc_.splats.empty()) showSplatsPanel_ = true;
+ }
+ if (!showSplatsPanel_) return;
+ const float scale = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + vp->Size.x - 590 * scale, vp->Pos.y + 34 * scale), ImGuiCond_FirstUseEver);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(280 * scale, 0), ImVec2(280 * scale, FLT_MAX));
+ if (!ImGui::Begin("Gaussian Splats", &showSplatsPanel_, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::End();
+ return;
+ }
+ struct EndWindow {
+ ~EndWindow() { ImGui::End(); }
+ } endWindow;
+ if (doc_.splats.empty()) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("Open or drop a .ply capture (Polycam, Luma, Postshot, Scaniverse...) to sculpt against it.");
+ ImGui::PopStyleColor();
+ if (ImGui::Button("Sculpt to splats", ImVec2(-1, 0))) runCommand("mesh_to_splats");
+ return;
+ }
+ ImGui::Text("%zu splats (SH %d)", doc_.splats.size(), doc_.splats.shDegree);
+ ImGui::Checkbox("Show##splats", &renderSettings_.showSplats);
+ ImGui::SameLine();
+ ImGui::Checkbox("Show mesh", &renderSettings_.showMesh);
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderFloat("##splatopacity", &renderSettings_.splatOpacity, 0.05f, 1.0f, "opacity %.2f");
+ const float third = (ImGui::GetContentRegionAvail().x - 2 * ImGui::GetStyle().ItemSpacing.x) / 3.0f;
+ if (ImGui::Button("Flip", ImVec2(third, 0))) runCommand("splat_transform", {{"rotate_x", 180.0}});
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Turn upside down (most captures are)");
+ ImGui::SameLine();
+ if (ImGui::Button("Turn 90", ImVec2(third, 0))) runCommand("splat_transform", {{"rotate_y", 90.0}});
+ ImGui::SameLine();
+ if (ImGui::Button("Fit", ImVec2(third, 0))) runCommand("splat_transform", {{"fit", true}});
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Centre and scale to the sculpt");
+ if (ImGui::Button("Clean floaters", ImVec2(-1, 0))) runCommand("splat_clean", {{"min_opacity", 0.1}, {"keep", 0.97}});
+ if (ImGui::Button("Convert to mesh", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 0)))
+ runCommand("splat_to_mesh", {{"resolution", double(splatMeshResolution_)}});
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Build a watertight sculpting mesh from the capture (undoable)");
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderInt("##splatres", &splatMeshResolution_, 64, 400, "res %d");
+ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ if (ImGui::Button("Save splats...", ImVec2(half, 0))) saveFileDialog(FileAction::SaveSplats);
+ ImGui::SameLine();
+ if (ImGui::Button("Clear##splats", ImVec2(half, 0))) runCommand("splat_clear");
+}
+
+void App::drawBrushCursor() {
+ ImDrawList* dl = ImGui::GetForegroundDrawList();
+ const float r = radiusPx_ * (pressureSize_ && lastInputPen_ ? std::max(penPressure_, 0.05f) : 1.0f);
+ const ImVec2 c(mouseX_, mouseY_);
+ const bool inverted = invertToggle_ != ((SDL_GetModState() & SDL_KMOD_ALT) != 0);
+ const ImU32 col = activeBrush() == BrushType::Smooth ? IM_COL32(120, 200, 255, 200)
+ : inverted ? IM_COL32(255, 110, 110, 200)
+ : IM_COL32(255, 190, 120, 200);
+ dl->AddCircle(c, r, col, 64, 1.5f);
+ dl->AddCircle(c, r * (0.25f + 0.75f * (1.0f - strength_)), IM_COL32(255, 255, 255, 60), 48, 1.0f);
+}
+
+} // namespace sf
diff --git a/src/app/App.h b/src/app/App.h
new file mode 100644
index 00000000..e828cdb1
--- /dev/null
+++ b/src/app/App.h
@@ -0,0 +1,233 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "ai/BrushAssistant.h"
+#include "ai/ImageTo3DService.h"
+#include "core/Commands.h"
+#include "core/Image.h"
+#include "core/Document.h"
+#include "render/Camera.h"
+#include "render/Renderer.h"
+
+#include <SDL3/SDL.h>
+#include <imgui.h>
+
+#include <future>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct AppOptions {
+ std::string openPath; // model or image to open at start
+ std::string script; // commands to run after start-up (same language as sculptforge-cli)
+ std::string renderPath; // headless: render a PNG and exit
+ int width = 1024, height = 1024;
+ float yawDegrees = -30.0f, pitchDegrees = -15.0f;
+ int turntable = 0; // headless: render N frames around the model (<path>_000.png ...)
+ bool wireframe = false;
+ bool hideMesh = false; // headless: show only the splats
+ std::string demo; // scripted demo to play (see Demo.h)
+ std::string recordPath; // record the session to this .mp4 (needs ffmpeg) and exit
+ std::string demoAsset; // file the demo opens (image or model)
+ std::string demoOutput; // where the demo saves its result (optional)
+ int fps = 30;
+};
+
+class Demo;
+
+class App {
+ friend class Demo;
+
+public:
+ App();
+ ~App();
+ bool init(const AppOptions& options);
+ int run(); // returns the process exit code
+ void shutdown();
+
+ enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, Count };
+ struct DialogRequest {
+ App* app;
+ FileAction action;
+ };
+ // Thread-safe: called from native file dialog callbacks.
+ void queueFile(FileAction action, std::string path);
+
+private:
+ enum class Drag { None, Stroke, Orbit, Pan, Zoom };
+
+ void handleEvent(const SDL_Event& e);
+ void onMouseDown(float x, float y, Uint8 button);
+ void onMouseMove(float x, float y, float dx, float dy, bool fromPen);
+ void onMouseUp();
+ void onKey(SDL_Keycode key, SDL_Keymod mod);
+
+ bool pick(float x, float y, RayHit& hit) const;
+ BrushType activeBrush() const;
+ void beginStroke(float x, float y, const RayHit& hit);
+ void strokeTo(float x, float y);
+ void dabAt(float x, float y);
+ void endStroke();
+
+ void runCommand(const std::string& name, const Args& args = {});
+ void openFileDialog();
+ void saveFileDialog(FileAction action);
+ AABB sceneBounds() const; // mesh plus the main body of any splats
+ void drawSplatSection();
+ void processPendingFiles();
+
+ void setLayerWeight(int index, float weight);
+ void animateLayers(float dt);
+ void generateLods();
+ void clearLods();
+ Mesh& displayedMesh();
+
+ void drawUi();
+ void drawToolPanel();
+ void drawMenuBar();
+ void drawLayersPanel();
+ void drawGameExportPanel();
+ void drawBrushLab();
+ void drawImageTo3D();
+ bool loadReferenceImage(const std::string& path);
+ void projectImageFromView();
+ void startGenerator();
+ void pollGenerator();
+ int renderHeadless();
+ void openPath(const std::string& path);
+ void drawRecipeEditor(BrushRecipe& recipe);
+ void drawAiSettings();
+ void sendBrushRequest(const std::string& text);
+ void pollBrushRequest();
+ const BrushRecipe* activeRecipe() const;
+ void drawBrushCursor();
+ void updateTitle();
+
+ int runRecording();
+ std::unique_ptr<Demo> demo_;
+ float uiScale_ = 1.0f; // UI layout scale (fonts are rasterised at this scale)
+ ImFont* fontCaption_ = nullptr;
+ ImFont* fontCaptionSub_ = nullptr;
+
+ SDL_Window* window_ = nullptr;
+ SDL_GLContext glContext_ = nullptr;
+ bool running_ = true;
+ std::string iniPath_;
+
+ Document doc_;
+ CommandRegistry commands_;
+ Renderer renderer_;
+ RenderSettings renderSettings_;
+ Camera camera_;
+
+ // Brush settings
+ BrushType brush_ = BrushType::Standard;
+ float radiusPx_ = 60.0f;
+ float strength_ = 0.5f;
+ Symmetry symmetry_;
+ bool invertToggle_ = false;
+ bool frontFacesOnly_ = false;
+ bool pressureStrength_ = true;
+ bool pressureSize_ = false;
+
+ // Input / stroke state
+ Drag drag_ = Drag::None;
+ float mouseX_ = 0.0f, mouseY_ = 0.0f;
+ float lastX_ = 0.0f, lastY_ = 0.0f, residual_ = 0.0f;
+ float penPressure_ = 1.0f;
+ bool lastInputPen_ = false;
+ bool penSeen_ = false;
+ BrushType strokeBrush_ = BrushType::Standard;
+ bool strokeInvert_ = false;
+ glm::vec3 grabPlanePoint_{0.0f}, grabLast_{0.0f};
+
+ std::string status_;
+ bool showHelp_ = false;
+ bool showAbout_ = false;
+
+ // Results from asynchronous native file dialogs (called off the main thread).
+ struct PendingFile {
+ FileAction action;
+ std::string path;
+ };
+ DialogRequest dialogRequests_[int(FileAction::Count)];
+
+ // Brush Lab (AI brush designer)
+ bool showBrushLab_ = true;
+ bool showLayersPanel_ = true;
+ bool showGamePanel_ = true;
+ bool showSplatsPanel_ = false;
+ uint64_t seenSplatsVersion_ = 0;
+ ai::AiSettings aiSettings_;
+ std::string aiSettingsPath_;
+ std::vector<ai::ChatMessage> chat_; // what the model sees (append-only, successful turns only)
+ struct ChatLine {
+ enum class Kind { User, Assistant, Error } kind;
+ std::string text;
+ };
+ std::vector<ChatLine> chatLog_; // what the panel shows
+ char chatInput_[1024] = "";
+ bool refineCurrent_ = true;
+ struct BrushReply {
+ ai::BrushSuggestion suggestion;
+ std::string raw;
+ };
+ std::future<BrushReply> pendingBrush_;
+ float busyTime_ = 0.0f;
+ bool scrollChat_ = false;
+ // Image to 3D
+ AppOptions options_;
+ bool showImageTo3D_ = false;
+ bool textMode_ = false;
+ char textPrompt_[512] = "";
+ Image refImage_;
+ std::string refImagePath_;
+ GLuint refTexture_ = 0;
+ float inflateThickness_ = 1.0f;
+ int inflateDetail_ = 160;
+ float reliefDepth_ = 0.12f;
+ int reliefDetail_ = 384;
+ bool reliefInvert_ = false;
+ float projectDepth_ = 0.02f;
+ bool projectInvert_ = false;
+ char generatorCommand_[1024] = "";
+ char falKey_[256] = "", falModel_[256] = "", meshyKey_[256] = "", hfToken_[256] = "";
+ bool remeshGenerated_ = true;
+ int voxelResolution_ = 200;
+ int splatMeshResolution_ = 192;
+ int remeshResolution_ = 256;
+ std::future<ai::GeneratorResult> pendingGenerator_;
+ std::shared_ptr<ai::GenerationProgress> generatorProgress_;
+ float generatorTime_ = 0.0f;
+
+ glm::vec3 lastDabHit_{0.0f};
+ bool haveLastDab_ = false;
+ uint32_t jitterSeed_ = 1;
+
+ // Sculpt layers / expression preview
+ char newLayerName_[64] = "Smile";
+ int playingLayer_ = -1;
+ float playTime_ = 0.0f;
+
+ // Game export / LOD preview
+ int lodLevels_ = 4;
+ float lodRatio_ = 0.5f;
+ std::vector<Mesh> lods_;
+ // Unreal Engine hand-off.
+ char unrealDestination_[256] = "/Game/SculptForge";
+ float unrealHeightCm_ = 0.0f; // 0 = 1 unit = 1 m
+ bool unrealNetwork_ = false; // editor on another computer
+ std::future<std::string> pendingUnreal_; // resolves to the status message
+ void sendToUnreal();
+ void pollUnreal();
+ int previewLod_ = -1;
+ const Mesh* lastDisplayed_ = nullptr;
+ std::mutex pendingMutex_;
+ std::vector<PendingFile> pendingFiles_;
+};
+
+} // namespace sf
diff --git a/src/app/Demo.cpp b/src/app/Demo.cpp
new file mode 100644
index 00000000..691bc97a
--- /dev/null
+++ b/src/app/Demo.cpp
@@ -0,0 +1,553 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/Demo.h"
+
+#include "app/App.h"
+
+#include <imgui_internal.h>
+
+#include <algorithm>
+#include <cstdlib>
+#include <cmath>
+#include <cstdarg>
+#include <chrono>
+#include <future>
+#include <map>
+#include <memory>
+
+// ---------------------------------------------------------------------------
+// Dear ImGui test-engine hooks: record where every labelled item was drawn.
+// ---------------------------------------------------------------------------
+
+namespace {
+
+struct ItemTable {
+ std::map<ImGuiID, ImRect> rects;
+ std::map<std::string, ImRect> byLabel;
+};
+ItemTable& items() {
+ static ItemTable t;
+ return t;
+}
+
+} // namespace
+
+void ImGuiTestEngineHook_ItemAdd(ImGuiContext*, ImGuiID id, const ImRect& bb, const ImGuiLastItemData*) {
+ items().rects[id] = bb;
+}
+
+void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID id, const char* label, ImGuiItemStatusFlags) {
+ auto it = items().rects.find(id);
+ if (!label || it == items().rects.end()) return;
+ std::string text(label);
+ items().byLabel[text] = it->second;
+ if (const size_t hash = text.find("##"); hash != std::string::npos && hash > 0)
+ items().byLabel.try_emplace(text.substr(0, hash), it->second);
+}
+
+void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {}
+const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext*, ImGuiID) { return nullptr; }
+
+namespace sf {
+
+namespace {
+
+template <class T> bool ready(const std::future<T>& f) {
+ return !f.valid() || f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
+}
+
+float smooth(float u) {
+ u = std::clamp(u, 0.0f, 1.0f);
+ return u * u * (3.0f - 2.0f * u);
+}
+
+// Point on a sphere of radius `r` from latitude/longitude in degrees (front = +Z).
+glm::vec3 onSphere(float latDeg, float lonDeg, float r = 1.0f) {
+ const float lat = glm::radians(latDeg), lon = glm::radians(lonDeg);
+ return r * glm::vec3(std::cos(lat) * std::sin(lon), std::sin(lat), std::cos(lat) * std::cos(lon));
+}
+
+} // namespace
+
+void Demo::beginFrame() { items().byLabel.clear(); }
+
+bool Demo::findItem(const std::string& label, ImVec2& center) const {
+ auto it = items().byLabel.find(label);
+ if (it == items().byLabel.end()) return false;
+ center = it->second.GetCenter();
+ return true;
+}
+
+std::vector<std::string> Demo::names() { return {"sculpt", "image-to-3d", "brush-lab", "game-ready", "splats"}; }
+
+bool Demo::load(const std::string& name, std::string& error) {
+ if (name == "sculpt") buildSculpt();
+ else if (name == "image-to-3d") buildImageTo3D();
+ else if (name == "brush-lab") buildBrushLab();
+ else if (name == "game-ready") buildGameReady();
+ else if (name == "splats") buildSplats();
+ else {
+ error = "Unknown demo '" + name + "'";
+ return false;
+ }
+ wait(1.0f); // hold the last frame
+ return true;
+}
+
+void Demo::update(float dt) {
+ clock_ += dt;
+ if (ImGuiWindow* w = ImGui::FindWindowByName("Brush Lab"); w && std::getenv("SF_DEMO_TRACE"))
+ SDL_Log("t=%.2f step=%zu brushlab=(%.0f,%.0f) mouse=(%.0f,%.0f) down=%d", clock_, step_, w->Pos.x, w->Pos.y, mouse_.x,
+ mouse_.y, int(buttonDown_));
+ stride_ = 1;
+ while (step_ < steps_.size()) {
+ if (!steps_[step_](stepTime_)) {
+ stepTime_ += dt;
+ return;
+ }
+ ++step_;
+ stepTime_ = 0.0f;
+ }
+}
+
+// ---------------------------------------------------------------- input
+
+void Demo::mouseMotion(float x, float y) {
+ SDL_Event e{};
+ e.type = SDL_EVENT_MOUSE_MOTION;
+ e.motion.windowID = SDL_GetWindowID(app_.window_);
+ e.motion.x = x;
+ e.motion.y = y;
+ e.motion.xrel = x - mouse_.x;
+ e.motion.yrel = y - mouse_.y;
+ e.motion.state = buttonDown_ ? SDL_BUTTON_LMASK : 0;
+ mouse_ = ImVec2(x, y);
+ app_.handleEvent(e);
+}
+
+void Demo::mouseButton(bool down, int button) {
+ SDL_Event e{};
+ e.type = down ? SDL_EVENT_MOUSE_BUTTON_DOWN : SDL_EVENT_MOUSE_BUTTON_UP;
+ e.button.windowID = SDL_GetWindowID(app_.window_);
+ e.button.button = Uint8(button);
+ e.button.down = down;
+ e.button.clicks = 1;
+ e.button.x = mouse_.x;
+ e.button.y = mouse_.y;
+ buttonDown_ = down && button == SDL_BUTTON_LEFT;
+ app_.handleEvent(e);
+}
+
+ImVec2 Demo::project(const glm::vec3& p) const {
+ int w = 0, h = 0;
+ SDL_GetWindowSize(app_.window_, &w, &h);
+ const glm::vec4 c = app_.camera_.projection() * app_.camera_.view() * glm::vec4(p, 1.0f);
+ const glm::vec2 ndc = glm::vec2(c) / c.w;
+ return ImVec2((ndc.x * 0.5f + 0.5f) * float(w), (0.5f - ndc.y * 0.5f) * float(h));
+}
+
+// ---------------------------------------------------------------- building blocks
+
+void Demo::wait(float seconds) {
+ steps_.push_back([seconds](float t) { return t >= seconds; });
+}
+
+void Demo::caption(const std::string& title, const std::string& subtitle, float seconds) {
+ steps_.push_back([this, title, subtitle, seconds](float) {
+ captions_.push_back({title, subtitle, clock_, seconds});
+ return true;
+ });
+}
+
+void Demo::moveTo(float x, float y, float seconds) {
+ auto from = std::make_shared<ImVec2>();
+ steps_.push_back([this, x, y, seconds, from](float t) {
+ if (t == 0.0f) *from = mouse_;
+ const float u = smooth(t / seconds);
+ mouseMotion(from->x + (x - from->x) * u, from->y + (y - from->y) * u);
+ return t >= seconds;
+ });
+}
+
+void Demo::moveToItem(const std::string& label, float seconds) {
+ auto from = std::make_shared<ImVec2>();
+ steps_.push_back([this, label, seconds, from](float t) {
+ ImVec2 to;
+ if (!findItem(label, to)) return t > 3.0f; // not on screen yet: give the UI a moment
+ if (t == 0.0f || (from->x == 0 && from->y == 0)) *from = mouse_;
+ const float u = smooth(t / seconds);
+ mouseMotion(from->x + (to.x - from->x) * u, from->y + (to.y - from->y) * u);
+ return t >= seconds;
+ });
+}
+
+void Demo::click(const std::string& label) {
+ moveToItem(label);
+ steps_.push_back([this](float t) {
+ if (t == 0.0f) mouseButton(true, SDL_BUTTON_LEFT);
+ if (t >= 0.08f) {
+ mouseButton(false, SDL_BUTTON_LEFT);
+ return true;
+ }
+ return false;
+ });
+ wait(0.25f);
+}
+
+void Demo::stroke(std::function<ImVec2(float u)> path, float seconds, bool invert) {
+ // Glide to the start, press, follow the path, release.
+ auto started = std::make_shared<bool>(false);
+ auto from = std::make_shared<ImVec2>();
+ steps_.push_back([this, path, from](float t) {
+ const ImVec2 p = path(0.0f);
+ const float u = smooth(t / 0.35f);
+ if (t == 0.0f) *from = mouse_;
+ mouseMotion(from->x + (p.x - from->x) * u, from->y + (p.y - from->y) * u);
+ return t >= 0.35f;
+ });
+ steps_.push_back([this, path, seconds, invert, started](float t) {
+ if (!*started) {
+ app_.invertToggle_ = invert;
+ mouseButton(true, SDL_BUTTON_LEFT);
+ *started = true;
+ }
+ const ImVec2 p = path(std::min(t / seconds, 1.0f));
+ mouseMotion(p.x, p.y);
+ if (t >= seconds) {
+ mouseButton(false, SDL_BUTTON_LEFT);
+ app_.invertToggle_ = false;
+ *started = false;
+ return true;
+ }
+ return false;
+ });
+}
+
+void Demo::orbit(float dx, float dy, float seconds) {
+ steps_.push_back([this, dx, dy, seconds](float t) {
+ if (t == 0.0f) mouseButton(true, SDL_BUTTON_RIGHT);
+ const float u0 = smooth(std::max(0.0f, t - 1.0f / 30.0f) / seconds), u1 = smooth(t / seconds);
+ SDL_Event e{};
+ e.type = SDL_EVENT_MOUSE_MOTION;
+ e.motion.windowID = SDL_GetWindowID(app_.window_);
+ e.motion.x = mouse_.x;
+ e.motion.y = mouse_.y;
+ e.motion.xrel = dx * (u1 - u0);
+ e.motion.yrel = dy * (u1 - u0);
+ e.motion.state = SDL_BUTTON_RMASK;
+ app_.handleEvent(e);
+ if (t >= seconds) {
+ mouseButton(false, SDL_BUTTON_RIGHT);
+ return true;
+ }
+ return false;
+ });
+}
+
+void Demo::type(char* buffer, size_t size, const std::string& text, float seconds) {
+ steps_.push_back([buffer, size, text, seconds](float t) {
+ const size_t n = std::min(text.size(), size_t(float(text.size()) * std::min(t / seconds, 1.0f)));
+ std::snprintf(buffer, size, "%s", text.substr(0, n).c_str());
+ return t >= seconds;
+ });
+}
+
+void Demo::run(std::function<void()> action) {
+ steps_.push_back([action](float) {
+ action();
+ return true;
+ });
+}
+
+void Demo::waitUntil(std::function<bool()> done, float timeout, int stride) {
+ steps_.push_back([this, done, timeout, stride](float t) {
+ stride_ = stride;
+ // Real work (network, AI) runs in real time: pace the timeline to the clock so the
+ // on-screen "N x speed" label is accurate.
+ SDL_Delay(Uint32(1000 / std::max(app_.options_.fps, 1)));
+ return done() || t >= timeout;
+ });
+}
+
+// ---------------------------------------------------------------- overlay
+
+void Demo::drawOverlay() {
+ ImDrawList* dl = ImGui::GetForegroundDrawList();
+ const ImVec2 size = ImGui::GetIO().DisplaySize;
+
+ // Lower-third captions.
+ for (const auto& c : captions_) {
+ const float t = clock_ - c.start;
+ if (t < 0.0f || t > c.duration) continue;
+ const float a = std::min({1.0f, t / 0.35f, (c.duration - t) / 0.35f});
+ ImFont* big = app_.fontCaption_ ? app_.fontCaption_ : ImGui::GetFont();
+ ImFont* small = app_.fontCaptionSub_ ? app_.fontCaptionSub_ : ImGui::GetFont();
+ const float bigSize = size.y * 0.042f, smallSize = size.y * 0.024f;
+ const ImVec2 tsz = big->CalcTextSizeA(bigSize, FLT_MAX, 0.0f, c.title.c_str());
+ const ImVec2 ssz = small->CalcTextSizeA(smallSize, FLT_MAX, 0.0f, c.subtitle.c_str());
+ const float pad = size.y * 0.022f;
+ const ImVec2 p0(size.x * 0.5f - std::max(tsz.x, ssz.x) * 0.5f - pad * 1.5f, size.y * 0.80f);
+ const ImVec2 p1(size.x * 0.5f + std::max(tsz.x, ssz.x) * 0.5f + pad * 1.5f,
+ p0.y + tsz.y + (c.subtitle.empty() ? 0.0f : ssz.y + pad * 0.3f) + pad * 2.0f);
+ dl->AddRectFilled(p0, p1, IM_COL32(12, 12, 14, int(215 * a)), pad * 0.6f);
+ dl->AddRectFilled(ImVec2(p0.x, p1.y - 4.0f), ImVec2(p1.x, p1.y), IM_COL32(242, 140, 60, int(255 * a)), pad * 0.6f,
+ ImDrawFlags_RoundCornersBottom);
+ dl->AddText(big, bigSize, ImVec2(size.x * 0.5f - tsz.x * 0.5f, p0.y + pad), IM_COL32(255, 255, 255, int(255 * a)),
+ c.title.c_str());
+ if (!c.subtitle.empty())
+ dl->AddText(small, smallSize, ImVec2(size.x * 0.5f - ssz.x * 0.5f, p0.y + pad + tsz.y + pad * 0.3f),
+ IM_COL32(205, 205, 210, int(255 * a)), c.subtitle.c_str());
+ }
+
+ // Honest time-lapse marker while waiting on a model.
+ if (stride_ > 1) {
+ char text[48];
+ std::snprintf(text, sizeof text, "%dx speed - waiting for the model", stride_);
+ ImFont* f = app_.fontCaptionSub_ ? app_.fontCaptionSub_ : ImGui::GetFont();
+ const float fs = size.y * 0.022f;
+ const ImVec2 ts = f->CalcTextSizeA(fs, FLT_MAX, 0.0f, text);
+ const ImVec2 p(size.x - ts.x - 40.0f, 60.0f);
+ dl->AddRectFilled(ImVec2(p.x - 14, p.y - 8), ImVec2(p.x + ts.x + 14, p.y + ts.y + 8), IM_COL32(12, 12, 14, 200), 8.0f);
+ dl->AddText(f, fs, p, IM_COL32(255, 200, 150, 255), text);
+ }
+
+ // Cursor arrow.
+ const float s = size.y / 1080.0f * 1.15f;
+ const ImVec2 m = mouse_;
+ const ImVec2 pts[] = {ImVec2(m.x, m.y), ImVec2(m.x, m.y + 22 * s), ImVec2(m.x + 5.5f * s, m.y + 16.5f * s),
+ ImVec2(m.x + 9.5f * s, m.y + 25 * s), ImVec2(m.x + 13 * s, m.y + 23.5f * s),
+ ImVec2(m.x + 9 * s, m.y + 15 * s), ImVec2(m.x + 16 * s, m.y + 15 * s)};
+ dl->AddConcavePolyFilled(pts, 7, IM_COL32(255, 255, 255, 255));
+ dl->AddPolyline(pts, 7, IM_COL32(0, 0, 0, 255), ImDrawFlags_Closed, 1.5f * s);
+ if (buttonDown_) dl->AddCircle(m, 14.0f * s, IM_COL32(255, 160, 80, 220), 32, 2.5f * s);
+}
+
+// ---------------------------------------------------------------- demos
+
+void Demo::buildSculpt() {
+ run([this] {
+ app_.runCommand("new_sphere", {{"subdivisions", 6.0}});
+ app_.symmetry_.x = true;
+ app_.strength_ = 0.8f;
+ app_.camera_.yaw = 0.0f;
+ app_.camera_.pitch = glm::radians(-4.0f);
+ app_.camera_.distance *= 0.78f;
+ app_.showBrushLab_ = false;
+ });
+ caption("Sculpt the way you already do", "ZBrush-style brushes, symmetry, tablet pressure", 4.5f);
+ wait(1.0f);
+ auto arc = [this](float lat0, float lon0, float lat1, float lon1) {
+ return [this, lat0, lon0, lat1, lon1](float u) {
+ return project(onSphere(lat0 + (lat1 - lat0) * u, lon0 + (lon1 - lon0) * u));
+ };
+ };
+ // Pull a point on the surface across the screen (Move brush).
+ auto pull = [this](float lat, float lon, float dx, float dy) {
+ return [this, lat, lon, dx, dy](float u) {
+ const ImVec2 p = project(onSphere(lat, lon));
+ const float e = smooth(u);
+ return ImVec2(p.x + dx * e, p.y + dy * e);
+ };
+ };
+ const float k = float(app_.options_.height) / 1080.0f; // screen offsets were authored at 1080p
+
+ // Horns: drag the upper skull out with the Move brush (mirrored by symmetry).
+ run([this, k] { app_.radiusPx_ = 110.0f * k; });
+ click("4 Move");
+ stroke(pull(52, -38, -150 * k, -170 * k), 1.6f);
+ run([this, k] { app_.radiusPx_ = 70.0f * k; });
+ stroke(pull(70, -48, -140 * k, -150 * k), 1.3f);
+ caption("Symmetry mirrors every stroke", "", 3.0f);
+
+ // Heavy brow and cheekbones with Clay.
+ run([this, k] { app_.radiusPx_ = 62.0f * k; });
+ click("2 Clay");
+ for (int pass = 0; pass < 3; ++pass) stroke(arc(24, -52, 30, -4), 0.9f);
+ for (int pass = 0; pass < 2; ++pass) stroke(arc(-14, -58, -6, -24), 0.9f);
+
+ // Eye sockets carved under the brow.
+ run([this, k] {
+ app_.radiusPx_ = 40.0f * k;
+ app_.strength_ = 0.9f;
+ });
+ click("1 Standard");
+ stroke(arc(10, -30, 10, -16), 0.7f, true);
+ stroke(arc(6, -32, 6, -14), 0.7f, true);
+
+ // Turn to the side and pull a snout forward.
+ orbit(-330.0f * k, 0.0f, 1.6f);
+ run([this, k] { app_.radiusPx_ = 120.0f * k; });
+ click("4 Move");
+ stroke(pull(-14, 0, -190 * k, 30 * k), 1.6f);
+ orbit(250.0f * k, 0.0f, 1.4f);
+
+ // Nostrils and a mouth line.
+ run([this, k] { app_.radiusPx_ = 30.0f * k; });
+ click("6 Crease");
+ stroke(arc(-36, -30, -33, 0), 1.0f, true);
+ run([this, k] { app_.radiusPx_ = 34.0f * k; });
+ click("5 Inflate");
+ stroke(arc(-6, -10, -4, -6), 0.5f);
+
+ // Soften.
+ run([this, k] {
+ app_.radiusPx_ = 80.0f * k;
+ app_.strength_ = 0.35f;
+ });
+ click("3 Smooth");
+ stroke(arc(-45, -60, 45, -60), 1.0f);
+ caption("Smooth, fast and scriptable", "Unlimited undo, layers, voxel remesh, one-click LODs", 5.0f);
+ orbit(-760.0f * k, 30.0f * k, 6.0f);
+ wait(0.5f);
+ run([this] {
+ if (!app_.options_.demoOutput.empty()) app_.runCommand("export_glb", {{"path", app_.options_.demoOutput}});
+ });
+}
+
+void Demo::buildImageTo3D() {
+ run([this] {
+ app_.runCommand("new_sphere", {{"subdivisions", 4.0}});
+ app_.showBrushLab_ = false;
+ app_.aiSettings_.generatorService = "huggingface";
+ app_.aiSettings_.hfModel = "hunyuan3d-2.1";
+ app_.remeshGenerated_ = true;
+ app_.remeshResolution_ = 256;
+ });
+ caption("Image to 3D", "Drop in a drawing or concept - get a sculptable model", 4.0f);
+ wait(1.0f);
+ run([this] {
+ app_.openPath(app_.options_.demoAsset);
+ SDL_Log("demo: opened %s -> %s", app_.options_.demoAsset.c_str(), app_.status_.c_str());
+ });
+ wait(1.5f);
+ caption("Free models, no account needed", "Hunyuan3D, TRELLIS.2 and Stable Fast 3D via Hugging Face", 4.0f);
+ click("Generate 3D model");
+ waitUntil([this] { return ready(app_.pendingGenerator_); }, 600.0f, 10);
+ run([this] {
+ app_.pollGenerator();
+ app_.showImageTo3D_ = false;
+ app_.camera_.frame(app_.doc_.mesh.bounds());
+ app_.camera_.yaw = glm::radians(-25.0f);
+ });
+ caption("Ready to sculpt", "Remeshed into one clean, watertight surface", 4.0f);
+ orbit(520.0f, 0.0f, 4.0f);
+ run([this] {
+ app_.radiusPx_ = 55.0f;
+ app_.symmetry_.x = true;
+ });
+ click("2 Clay");
+ stroke([this](float u) { return project(glm::vec3(-0.25f + 0.15f * u, 0.15f - 0.3f * u, 0.38f)); }, 1.2f);
+ orbit(-260.0f, 30.0f, 2.5f);
+}
+
+void Demo::buildBrushLab() {
+ run([this] {
+ app_.runCommand("new_plane", {{"resolution", 320.0}});
+ app_.runCommand("subdivide");
+ app_.showBrushLab_ = true;
+ app_.showGamePanel_ = false;
+ app_.showLayersPanel_ = false;
+ app_.camera_.yaw = glm::radians(-20.0f);
+ app_.camera_.pitch = glm::radians(-50.0f);
+ app_.camera_.distance *= 0.62f;
+ app_.camera_.target = glm::vec3(-0.42f, 0.0f, 0.05f); // plane to the right of the Brush Lab panel
+ app_.radiusPx_ = 70.0f * float(app_.options_.height) / 1080.0f;
+ app_.strength_ = 0.6f;
+ });
+ caption("Brush Lab", "Describe the brush you want. AI builds it.", 4.0f);
+ wait(1.0f);
+ moveToItem("##prompt");
+ type(app_.chatInput_, sizeof app_.chatInput_, "dry cracked mud", 1.4f);
+ click("Create");
+ waitUntil([this] { return ready(app_.pendingBrush_); }, 240.0f, 8);
+ run([this] { app_.pollBrushRequest(); });
+ caption("Your own AI, even fully local", "This brush came from a small open model running on this machine", 4.5f);
+ auto line = [this](float z0, float z1) {
+ return [this, z0, z1](float u) { return project(glm::vec3(-0.45f + 0.9f * u, 0.0f, z0 + (z1 - z0) * u)); };
+ };
+ stroke(line(-0.4f, -0.3f), 1.6f);
+ stroke(line(-0.05f, 0.0f), 1.6f);
+ stroke(line(0.3f, 0.25f), 1.6f);
+ moveToItem("##prompt");
+ type(app_.chatInput_, sizeof app_.chatInput_, "deeper cracks, sharper edges", 1.6f);
+ click("Create");
+ waitUntil([this] { return ready(app_.pendingBrush_); }, 240.0f, 8);
+ run([this] { app_.pollBrushRequest(); });
+ caption("Refine it in plain words", "Every setting is also a slider", 3.5f);
+ stroke(line(-0.45f, 0.45f), 1.8f);
+ stroke(line(0.45f, -0.45f), 1.8f);
+ wait(1.5f);
+}
+
+void Demo::buildGameReady() {
+ run([this] {
+ app_.openPath(app_.options_.demoAsset);
+ app_.symmetry_.x = true;
+ app_.strength_ = 0.8f;
+ app_.showBrushLab_ = false;
+ app_.camera_.frame(app_.doc_.mesh.bounds());
+ app_.camera_.yaw = glm::radians(-20.0f);
+ app_.camera_.pitch = glm::radians(-6.0f);
+ app_.camera_.distance *= 0.85f;
+ std::snprintf(app_.newLayerName_, sizeof app_.newLayerName_, "Grin");
+ });
+ caption("Built for game & animation pipelines", "Sculpt layers become blend shapes / morph targets", 4.0f);
+ click("+ Add");
+ const float k = float(app_.options_.height) / 1080.0f;
+ run([this, k] { app_.radiusPx_ = 70.0f * k; });
+ click("4 Move");
+ // Pull the mouth corners up and back into a grin, on the new layer only.
+ stroke([this, k](float u) {
+ const ImVec2 p = project(onSphere(-32.0f, -28.0f));
+ return ImVec2(p.x - 40.0f * k * smooth(u), p.y - 70.0f * k * smooth(u));
+ }, 1.2f);
+ stroke([this, k](float u) {
+ const ImVec2 p = project(onSphere(-20.0f, -45.0f));
+ return ImVec2(p.x - 30.0f * k * smooth(u), p.y - 55.0f * k * smooth(u));
+ }, 1.0f);
+ caption("Animate the expression", "Weights export as glTF morph targets and UsdSkel blend shapes", 4.0f);
+ click("Play");
+ wait(4.0f);
+ click("Stop");
+ caption("One-click LOD chain", "Blend shapes survive on every level", 4.0f);
+ click("Generate LOD chain");
+ click("LOD1");
+ wait(1.0f);
+ click("LOD2");
+ wait(1.0f);
+ click("LOD3");
+ wait(1.5f);
+ click("Sculpt");
+ run([this] { app_.renderSettings_.wireframe = false; });
+ caption("Send to Unreal Engine", "FBX with LODs and morph targets, straight into the editor", 4.5f);
+ moveToItem("Send to Unreal", 0.8f);
+ wait(1.5f);
+ moveToItem("Export FBX for Unreal...", 0.6f);
+ wait(1.0f);
+ caption("Plus glTF, USD/USDZ and OBJ", "Validated with the Khronos and OpenUSD tools", 3.5f);
+ orbit(500.0f * k, 0.0f, 3.5f);
+}
+
+void Demo::buildSplats() {
+ run([this] {
+ app_.openPath(app_.options_.demoAsset);
+ app_.showBrushLab_ = false;
+ app_.showSplatsPanel_ = true;
+ app_.camera_.frame(app_.sceneBounds());
+ app_.camera_.yaw = glm::radians(-30.0f);
+ });
+ caption("Gaussian splats", "Turn a sculpt into splats for web viewers and engines", 4.0f);
+ wait(1.0f);
+ click("Sculpt to splats");
+ click("Show mesh");
+ orbit(450.0f, 20.0f, 4.0f);
+ caption("And captures back into meshes", "Splat -> watertight, sculptable mesh in under a second", 4.0f);
+ click("Convert to mesh");
+ click("Show mesh");
+ click("Show##splats");
+ orbit(-450.0f, -20.0f, 4.0f);
+ caption("Open standards", "PLY, .splat, glTF KHR_gaussian_splatting, OpenUSD ParticleField", 3.5f);
+ wait(2.0f);
+}
+
+} // namespace sf
diff --git a/src/app/Demo.h b/src/app/Demo.h
new file mode 100644
index 00000000..b294d8de
--- /dev/null
+++ b/src/app/Demo.h
@@ -0,0 +1,84 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Scripted demos for recording product videos: a timeline of real input
+// (mouse moves, clicks, brush strokes, typing) played into the running app,
+// with captions and a visible cursor drawn on top. UI elements are found by
+// their labels through Dear ImGui's test-engine hooks, so the demo clicks the
+// real buttons rather than calling functions behind the UI's back.
+//
+// sculptforge --demo sculpt --record sculpt.mp4 --size 1920x1080
+#pragma once
+
+#include <glm/glm.hpp>
+#include <imgui.h>
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class App;
+
+class Demo {
+public:
+ explicit Demo(App& app) : app_(app) {}
+
+ static std::vector<std::string> names();
+ bool load(const std::string& name, std::string& error);
+
+ void update(float dt); // before the UI is built: plays the timeline
+ void drawOverlay(); // inside the ImGui frame: captions and cursor
+ bool finished() const { return step_ >= steps_.size(); }
+ int frameStride() const { return stride_; } // >1 while fast-forwarding through waits
+
+ // Screen rect of the most recent UI item with this label (text before "##" also matches).
+ bool findItem(const std::string& label, ImVec2& center) const;
+ static void beginFrame(); // clears the item table (called before ImGui::NewFrame)
+
+private:
+ using Step = std::function<bool(float t)>; // returns true when done; t = seconds since the step began
+
+ // Timeline building blocks.
+ void wait(float seconds);
+ void caption(const std::string& title, const std::string& subtitle, float seconds);
+ void moveTo(float x, float y, float seconds);
+ void moveToItem(const std::string& label, float seconds = 0.6f);
+ void click(const std::string& label); // move to the item and click it
+ void stroke(std::function<ImVec2(float u)> path, float seconds, bool invert = false);
+ void orbit(float dx, float dy, float seconds); // right-drag on the background
+ void type(char* buffer, size_t size, const std::string& text, float seconds);
+ void run(std::function<void()> action);
+ void waitUntil(std::function<bool()> done, float timeout, int stride);
+
+ void buildSculpt();
+ void buildImageTo3D();
+ void buildBrushLab();
+ void buildGameReady();
+ void buildSplats();
+
+ // Input injection.
+ void mouseMotion(float x, float y);
+ void mouseButton(bool down, int button);
+
+ // World -> screen in window coordinates.
+ ImVec2 project(const glm::vec3& p) const;
+
+ App& app_;
+ std::vector<Step> steps_;
+ size_t step_ = 0;
+ float stepTime_ = 0.0f;
+ int stride_ = 1;
+ ImVec2 mouse_{960, 540};
+ bool buttonDown_ = false;
+
+ struct Caption {
+ std::string title, subtitle;
+ float start = 0.0f, duration = 0.0f;
+ };
+ std::vector<Caption> captions_;
+ float clock_ = 0.0f;
+};
+
+} // namespace sf
diff --git a/src/app/main.cpp b/src/app/main.cpp
new file mode 100644
index 00000000..dcc37953
--- /dev/null
+++ b/src/app/main.cpp
@@ -0,0 +1,68 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/App.h"
+
+#include <SDL3/SDL_main.h>
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+
+namespace {
+
+void usage() {
+ std::puts(
+ "Usage: sculptforge [model / splats / image file] [options]\n"
+ "\n"
+ " --run \"<commands>\" Run commands at start-up (see sculptforge-cli --list)\n"
+ " --render out.png Render headless and exit (thumbnails, review sheets)\n"
+ " --turntable N With --render: N frames around the model (out_000.png ...)\n"
+ " --size WxH Render size (default 1024x1024)\n"
+ " --view YAW,PITCH Camera angles in degrees (default -30,-15)\n"
+ " --wireframe Render with wireframe overlay\n"
+ " --hide-mesh Render only the Gaussian splats\n"
+ " --demo NAME Play a scripted demo (sculpt, image-to-3d, brush-lab, game-ready, splats)\n"
+ " --record out.mp4 Record the demo offscreen to a video (needs ffmpeg) and exit\n"
+ " --demo-asset FILE Image or model the demo opens\n"
+ " --demo-output FILE Save the demo's result (e.g. creature.glb)\n"
+ " --fps N Recording frame rate (default 30)");
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ sf::AppOptions options;
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
+ if (a == "--run") options.script += next() + "\n";
+ else if (a == "--render") options.renderPath = next();
+ else if (a == "--turntable") options.turntable = std::atoi(next().c_str());
+ else if (a == "--size") std::sscanf(next().c_str(), "%dx%d", &options.width, &options.height);
+ else if (a == "--view") std::sscanf(next().c_str(), "%f,%f", &options.yawDegrees, &options.pitchDegrees);
+ else if (a == "--wireframe") options.wireframe = true;
+ else if (a == "--hide-mesh") options.hideMesh = true;
+ else if (a == "--demo") options.demo = next();
+ else if (a == "--record") options.recordPath = next();
+ else if (a == "--demo-asset") options.demoAsset = next();
+ else if (a == "--demo-output") options.demoOutput = next();
+ else if (a == "--fps") options.fps = std::atoi(next().c_str());
+ else if (a == "-h" || a == "--help") {
+ usage();
+ return 0;
+ } else if (!a.empty() && a[0] != '-') options.openPath = a;
+ else {
+ std::fprintf(stderr, "Unknown option %s\n", a.c_str());
+ usage();
+ return 1;
+ }
+ }
+ sf::App app;
+ if (!app.init(options)) {
+ app.shutdown();
+ return 1;
+ }
+ int code = app.run();
+ app.shutdown();
+ return code;
+}
diff --git a/src/cli/McpServer.cpp b/src/cli/McpServer.cpp
new file mode 100644
index 00000000..ac900bd1
--- /dev/null
+++ b/src/cli/McpServer.cpp
@@ -0,0 +1,126 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "cli/McpServer.h"
+
+#include "core/Json.h"
+
+#include <iostream>
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kLatestProtocol = "2025-06-18";
+
+Json toolList(const CommandRegistry& registry) {
+ Json tools = Json::array();
+ for (const auto& c : registry.all()) {
+ Json props = Json::object(), required = Json::array();
+ for (const auto& p : c.params) {
+ Json prop = Json::object();
+ prop.set("type", p.type == ParamSpec::Type::Bool ? "boolean" : p.type == ParamSpec::Type::Number ? "number" : "string");
+ prop.set("description", p.description);
+ props.set(p.name, prop);
+ if (p.required) required.push(p.name);
+ }
+ Json schema = Json::object();
+ schema.set("type", "object");
+ schema.set("properties", props);
+ schema.set("required", required);
+ Json tool = Json::object();
+ tool.set("name", c.name);
+ tool.set("description", c.description);
+ tool.set("inputSchema", schema);
+ tools.push(tool);
+ }
+ Json result = Json::object();
+ result.set("tools", tools);
+ return result;
+}
+
+Json reply(const Json& id, Json result) {
+ Json r = Json::object();
+ r.set("jsonrpc", "2.0");
+ r.set("id", id);
+ r.set("result", std::move(result));
+ return r;
+}
+
+Json errorReply(const Json& id, int code, const std::string& message) {
+ Json e = Json::object();
+ e.set("code", code);
+ e.set("message", message);
+ Json r = Json::object();
+ r.set("jsonrpc", "2.0");
+ r.set("id", id);
+ r.set("error", e);
+ return r;
+}
+
+} // namespace
+
+std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, const std::string& line) {
+ Json msg;
+ std::string err;
+ if (!Json::parse(line, msg, err) || !msg.isObject()) return errorReply(Json(), -32700, "Parse error: " + err).dump();
+ const std::string method = msg["method"].asString();
+ const Json& id = msg["id"];
+ if (!msg.has("id")) return {}; // notification (e.g. notifications/initialized)
+
+ if (method == "initialize") {
+ Json result = Json::object();
+ const std::string requested = msg["params"]["protocolVersion"].asString();
+ result.set("protocolVersion", requested.empty() ? kLatestProtocol : requested);
+ Json caps = Json::object(), tools = Json::object();
+ tools.set("listChanged", false);
+ caps.set("tools", tools);
+ result.set("capabilities", caps);
+ Json info = Json::object();
+ info.set("name", "sculptforge");
+ info.set("version", "0.1.0");
+ result.set("serverInfo", info);
+ result.set("instructions",
+ "SculptForge is a digital sculpting tool. One scene is kept for the whole session: start with "
+ "new_sphere, open (models, Gaussian-splat captures, USD) or image_to_3d, shape it with "
+ "subdivide/remesh/layers/decimate, then export_glb, export_usd, export_lods or splat_save. "
+ "Use mesh_info and splat_info to check results. File paths are on the user's machine.");
+ return reply(id, result).dump();
+ }
+ if (method == "ping") return reply(id, Json::object()).dump();
+ if (method == "tools/list") return reply(id, toolList(registry)).dump();
+ if (method == "tools/call") {
+ const std::string name = msg["params"]["name"].asString();
+ if (!registry.find(name)) return errorReply(id, -32602, "Unknown tool: " + name).dump();
+ Args args;
+ for (const auto& [key, value] : msg["params"]["arguments"].members()) {
+ if (value.isBool()) args[key] = value.asBool();
+ else if (value.isNumber()) args[key] = value.asNumber();
+ else if (value.isString()) args[key] = value.asString();
+ else args[key] = value.dump();
+ }
+ CommandResult r = registry.execute(doc, name, args);
+ Json text = Json::object();
+ text.set("type", "text");
+ text.set("text", r.message);
+ Json content = Json::array();
+ content.push(text);
+ Json result = Json::object();
+ result.set("content", content);
+ result.set("isError", !r.ok);
+ return reply(id, result).dump();
+ }
+ return errorReply(id, -32601, "Method not found: " + method).dump();
+}
+
+int runMcpServer(const CommandRegistry& registry, std::istream& in, std::ostream& out) {
+ Document doc;
+ std::string line;
+ while (std::getline(in, line)) {
+ if (line.find_first_not_of(" \t\r") == std::string::npos) continue;
+ const std::string response = handleMcpMessage(registry, doc, line);
+ if (!response.empty()) out << response << "\n" << std::flush;
+ }
+ return 0;
+}
+
+} // namespace sf
diff --git a/src/cli/McpServer.h b/src/cli/McpServer.h
new file mode 100644
index 00000000..c9823705
--- /dev/null
+++ b/src/cli/McpServer.h
@@ -0,0 +1,23 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0).
+// Every SculptForge command becomes an MCP tool acting on one live document,
+// so an agent (Claude Code, Claude Desktop, Cursor, ...) can build, sculpt,
+// remesh, convert and export assets conversationally.
+#pragma once
+
+#include "core/Commands.h"
+
+#include <iosfwd>
+#include <string>
+
+namespace sf {
+
+// Handles one JSON-RPC message; returns the response line, or "" for notifications.
+std::string handleMcpMessage(const CommandRegistry& registry, Document& doc, const std::string& line);
+
+// Serves until `in` closes. Returns the process exit code.
+int runMcpServer(const CommandRegistry& registry, std::istream& in, std::ostream& out);
+
+} // namespace sf
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
new file mode 100644
index 00000000..ff464735
--- /dev/null
+++ b/src/cli/main.cpp
@@ -0,0 +1,137 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// sculptforge-cli: run SculptForge commands headless, for build farms, asset
+// pipelines and AI agents.
+#include "ai/AiCommands.h"
+#include "cli/McpServer.h"
+#include "core/Commands.h"
+#include "core/Script.h"
+
+#include <cstdio>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <string>
+
+namespace {
+
+void usage() {
+ std::puts(
+ "Usage: sculptforge-cli [options]\n"
+ "\n"
+ " -c, --command \"<script>\" Run commands, separated by ';'\n"
+ " -f, --file <script.txt> Run commands from a file ('-' reads stdin)\n"
+ " --set NAME=VALUE Define a variable; script values written $NAME are replaced\n"
+ " -l, --list List available commands\n"
+ " --schema Print commands as LLM tool definitions (JSON)\n"
+ " --mcp Run as an MCP server on stdio (Claude Code, Claude Desktop, any MCP client)\n"
+ " -q, --quiet Only print errors\n"
+ " -h, --help Show this help\n"
+ "\n"
+ "Connect Claude Code: claude mcp add sculptforge -- sculptforge-cli --mcp\n"
+ "\n"
+ "Example (game LOD pipeline):\n"
+ " sculptforge-cli -c 'open_obj path=rock.obj; export_lods path=out/rock.glb levels=4 ratio=0.5'");
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ sf::CommandRegistry registry;
+ // AI commands use the same settings file as the app (keys can also come from the environment).
+ sf::ai::registerAiCommands(registry, [] { return sf::ai::AiSettings::load(sf::ai::defaultAiSettingsPath()); });
+ std::string script;
+ bool quiet = false;
+ std::map<std::string, std::string> vars;
+
+ if (argc < 2) {
+ usage();
+ return 1;
+ }
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if ((a == "-c" || a == "--command") && i + 1 < argc) {
+ script += argv[++i];
+ script += "\n";
+ } else if ((a == "-f" || a == "--file") && i + 1 < argc) {
+ std::string path = argv[++i];
+ std::stringstream ss;
+ if (path == "-") {
+ ss << std::cin.rdbuf();
+ } else {
+ std::ifstream f(path);
+ if (!f) {
+ std::fprintf(stderr, "error: cannot read %s\n", path.c_str());
+ return 1;
+ }
+ ss << f.rdbuf();
+ }
+ script += ss.str();
+ script += "\n";
+ } else if (a == "--set" && i + 1 < argc) {
+ std::string kv = argv[++i];
+ size_t eq = kv.find('=');
+ if (eq == std::string::npos || eq == 0) {
+ std::fprintf(stderr, "error: --set expects NAME=VALUE\n");
+ return 1;
+ }
+ vars[kv.substr(0, eq)] = kv.substr(eq + 1);
+ } else if (a == "-l" || a == "--list") {
+ for (const auto& c : registry.all()) {
+ std::printf("%-18s %s\n", c.name.c_str(), c.description.c_str());
+ for (const auto& p : c.params)
+ std::printf(" %s%s %s\n", p.name.c_str(), p.required ? " (required)" : "", p.description.c_str());
+ }
+ return 0;
+ } else if (a == "--mcp") {
+ return sf::runMcpServer(registry, std::cin, std::cout);
+ } else if (a == "--schema") {
+ std::puts(registry.toolSchemaJson().c_str());
+ return 0;
+ } else if (a == "-q" || a == "--quiet") {
+ quiet = true;
+ } else if (a == "-h" || a == "--help") {
+ usage();
+ return 0;
+ } else {
+ std::fprintf(stderr, "error: unknown option %s\n", a.c_str());
+ usage();
+ return 1;
+ }
+ }
+
+ std::vector<sf::ScriptStatement> statements;
+ std::string error;
+ if (!sf::parseScript(script, statements, error)) {
+ std::fprintf(stderr, "error: %s\n", error.c_str());
+ return 1;
+ }
+
+ // Substitute $NAME variables (whole values only, so paths with spaces stay intact).
+ for (auto& st : statements) {
+ for (auto& [key, value] : st.args) {
+ auto* s = std::get_if<std::string>(&value);
+ if (!s || s->size() < 2 || (*s)[0] != '$') continue;
+ auto it = vars.find(s->substr(1));
+ if (it == vars.end()) {
+ std::fprintf(stderr, "error (line %d): undefined variable %s\n", st.line, s->c_str());
+ return 1;
+ }
+ *s = it->second;
+ }
+ }
+
+ sf::Document doc;
+ for (const auto& st : statements) {
+ sf::CommandResult r = registry.execute(doc, st.command, st.args);
+ if (!r.ok) {
+ std::fprintf(stderr, "error (line %d, %s): %s\n", st.line, st.command.c_str(), r.message.c_str());
+ return 2;
+ }
+ if (!quiet) std::printf("%s: %s\n", st.command.c_str(), r.message.c_str());
+ }
+ return 0;
+}
diff --git a/src/core/BVH.cpp b/src/core/BVH.cpp
new file mode 100644
index 00000000..fd6f4241
--- /dev/null
+++ b/src/core/BVH.cpp
@@ -0,0 +1,232 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/BVH.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+constexpr uint32_t kLeafSize = 16;
+
+bool rayBox(const AABB& b, const glm::vec3& o, const glm::vec3& invDir, float tMax) {
+ glm::vec3 t0 = (b.min - o) * invDir;
+ glm::vec3 t1 = (b.max - o) * invDir;
+ glm::vec3 tmin = glm::min(t0, t1), tmax = glm::max(t0, t1);
+ float enter = std::max(std::max(tmin.x, tmin.y), std::max(tmin.z, 0.0f));
+ float exit = std::min(std::min(tmax.x, tmax.y), std::min(tmax.z, tMax));
+ return enter <= exit;
+}
+
+bool sphereBox(const AABB& b, const glm::vec3& c, float r2) {
+ glm::vec3 d = glm::max(glm::max(b.min - c, c - b.max), glm::vec3(0.0f));
+ return glm::dot(d, d) <= r2;
+}
+
+// Two-sided Moller-Trumbore.
+bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, const glm::vec3& b,
+ const glm::vec3& c, float& t) {
+ glm::vec3 e1 = b - a, e2 = c - a;
+ glm::vec3 p = glm::cross(d, e2);
+ float det = glm::dot(e1, p);
+ if (std::abs(det) < 1e-12f) return false;
+ float inv = 1.0f / det;
+ glm::vec3 s = o - a;
+ float u = glm::dot(s, p) * inv;
+ if (u < 0.0f || u > 1.0f) return false;
+ glm::vec3 q = glm::cross(s, e1);
+ float v = glm::dot(d, q) * inv;
+ if (v < 0.0f || u + v > 1.0f) return false;
+ t = glm::dot(e2, q) * inv;
+ return t > 0.0f;
+}
+
+} // namespace
+
+void BVH::build(const Mesh& mesh) {
+ const size_t nt = mesh.triangleCount();
+ nodes_.clear();
+ triIndices_.resize(nt);
+ triLeaf_.assign(nt, 0);
+ vertStamp_.assign(mesh.vertexCount(), 0);
+ vertStampValue_ = 0;
+ if (nt == 0) return;
+
+ std::vector<glm::vec3> centroids(nt);
+ for (uint32_t i = 0; i < nt; ++i) {
+ const auto& t = mesh.triangles[i];
+ centroids[i] = (mesh.positions[t.x] + mesh.positions[t.y] + mesh.positions[t.z]) / 3.0f;
+ triIndices_[i] = i;
+ }
+
+ nodes_.reserve(2 * (nt / kLeafSize + 1));
+ nodes_.push_back(Node{AABB{}, 0, static_cast<uint32_t>(nt), 0});
+
+ struct Task { uint32_t node; };
+ std::vector<Task> tasks{{0}};
+ while (!tasks.empty()) {
+ uint32_t ni = tasks.back().node;
+ tasks.pop_back();
+ uint32_t first = nodes_[ni].first, count = nodes_[ni].count;
+
+ AABB cb;
+ for (uint32_t i = first; i < first + count; ++i) cb.expand(centroids[triIndices_[i]]);
+
+ glm::vec3 ext = cb.extent();
+ int axis = ext.x > ext.y ? (ext.x > ext.z ? 0 : 2) : (ext.y > ext.z ? 1 : 2);
+ if (count <= kLeafSize || ext[axis] <= 0.0f) {
+ recomputeLeaf(mesh, nodes_[ni]);
+ continue;
+ }
+
+ uint32_t mid = first + count / 2;
+ std::nth_element(triIndices_.begin() + first, triIndices_.begin() + mid, triIndices_.begin() + first + count,
+ [&](uint32_t a, uint32_t b) { return centroids[a][axis] < centroids[b][axis]; });
+
+ uint32_t left = static_cast<uint32_t>(nodes_.size());
+ nodes_.push_back(Node{AABB{}, first, mid - first, ni});
+ nodes_.push_back(Node{AABB{}, mid, first + count - mid, ni});
+ nodes_[ni].first = left;
+ nodes_[ni].count = 0;
+ tasks.push_back({left});
+ tasks.push_back({left + 1});
+ }
+
+ // Inner node bounds, bottom-up (children always have larger indices).
+ for (size_t i = nodes_.size(); i-- > 0;) {
+ Node& n = nodes_[i];
+ if (n.count == 0) {
+ n.box = nodes_[n.first].box;
+ n.box.expand(nodes_[n.first + 1].box);
+ }
+ }
+ leafStamp_.assign(nodes_.size(), 0);
+ leafStampValue_ = 0;
+}
+
+void BVH::recomputeLeaf(const Mesh& mesh, Node& n) {
+ n.box = AABB{};
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const auto& t = mesh.triangles[triIndices_[i]];
+ n.box.expand(mesh.positions[t.x]);
+ n.box.expand(mesh.positions[t.y]);
+ n.box.expand(mesh.positions[t.z]);
+ triLeaf_[triIndices_[i]] = static_cast<uint32_t>(&n - nodes_.data());
+ }
+}
+
+uint32_t BVH::nextStamp(std::vector<uint32_t>& stamps, uint32_t& stamp) const {
+ if (++stamp == 0) {
+ std::fill(stamps.begin(), stamps.end(), 0);
+ stamp = 1;
+ }
+ return stamp;
+}
+
+bool BVH::raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) const {
+ if (nodes_.empty()) return false;
+ // Avoid 0 * inf = NaN in the slab test for axis-aligned rays.
+ glm::vec3 safeDir = dir;
+ for (int i = 0; i < 3; ++i)
+ if (std::abs(safeDir[i]) < 1e-20f) safeDir[i] = std::copysign(1e-20f, safeDir[i]);
+ glm::vec3 invDir = 1.0f / safeDir;
+ float best = std::numeric_limits<float>::max();
+ uint32_t bestTri = 0;
+ bool found = false;
+
+ stack_.clear();
+ stack_.push_back(0);
+ while (!stack_.empty()) {
+ const Node& n = nodes_[stack_.back()];
+ stack_.pop_back();
+ if (!rayBox(n.box, origin, invDir, best)) continue;
+ if (n.count > 0) {
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const auto& t = mesh.triangles[triIndices_[i]];
+ float tt;
+ if (rayTriangle(origin, dir, mesh.positions[t.x], mesh.positions[t.y], mesh.positions[t.z], tt) &&
+ tt < best) {
+ best = tt;
+ bestTri = triIndices_[i];
+ found = true;
+ }
+ }
+ } else {
+ stack_.push_back(n.first);
+ stack_.push_back(n.first + 1);
+ }
+ }
+ if (!found) return false;
+
+ const auto& t = mesh.triangles[bestTri];
+ hit.t = best;
+ hit.triangle = bestTri;
+ hit.position = origin + dir * best;
+ glm::vec3 n = glm::cross(mesh.positions[t.y] - mesh.positions[t.x], mesh.positions[t.z] - mesh.positions[t.x]);
+ float len = glm::length(n);
+ hit.normal = len > 0.0f ? n / len : -dir;
+ return true;
+}
+
+void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const {
+ out.clear();
+ if (nodes_.empty()) return;
+ const float r2 = radius * radius;
+ const uint32_t s = nextStamp(vertStamp_, vertStampValue_);
+
+ stack_.clear();
+ stack_.push_back(0);
+ while (!stack_.empty()) {
+ const Node& n = nodes_[stack_.back()];
+ stack_.pop_back();
+ if (!sphereBox(n.box, center, r2)) continue;
+ if (n.count > 0) {
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const auto& t = mesh.triangles[triIndices_[i]];
+ for (int c = 0; c < 3; ++c) {
+ uint32_t v = t[c];
+ if (vertStamp_[v] == s) continue;
+ vertStamp_[v] = s;
+ glm::vec3 d = mesh.positions[v] - center;
+ if (glm::dot(d, d) <= r2) out.push_back(v);
+ }
+ }
+ } else {
+ stack_.push_back(n.first);
+ stack_.push_back(n.first + 1);
+ }
+ }
+}
+
+void BVH::refit(const Mesh& mesh, std::span<const uint32_t> movedVerts) {
+ if (nodes_.empty()) return;
+ const uint32_t s = nextStamp(leafStamp_, leafStampValue_);
+ scratchLeaves_.clear();
+ for (uint32_t v : movedVerts) {
+ for (uint32_t ti : mesh.vertexTriangles(v)) {
+ uint32_t leaf = triLeaf_[ti];
+ if (leafStamp_[leaf] != s) {
+ leafStamp_[leaf] = s;
+ scratchLeaves_.push_back(leaf);
+ }
+ }
+ }
+ for (uint32_t li : scratchLeaves_) {
+ recomputeLeaf(mesh, nodes_[li]);
+ // Grow ancestors until one already contains the new bounds.
+ AABB box = nodes_[li].box;
+ uint32_t ni = li;
+ while (ni != 0) {
+ ni = nodes_[ni].parent;
+ AABB& pb = nodes_[ni].box;
+ if (glm::all(glm::lessThanEqual(pb.min, box.min)) && glm::all(glm::greaterThanEqual(pb.max, box.max)))
+ break;
+ pb.expand(box);
+ box = pb;
+ }
+ }
+}
+
+} // namespace sf
diff --git a/src/core/BVH.h b/src/core/BVH.h
new file mode 100644
index 00000000..901d3730
--- /dev/null
+++ b/src/core/BVH.h
@@ -0,0 +1,56 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <span>
+#include <vector>
+
+namespace sf {
+
+struct RayHit {
+ float t = 0.0f;
+ uint32_t triangle = 0;
+ glm::vec3 position{0.0f};
+ glm::vec3 normal{0.0f}; // geometric normal of the hit triangle
+};
+
+// Bounding volume hierarchy over a mesh's triangles. Supports ray casts,
+// sphere queries for brushes, and cheap incremental refits while sculpting.
+class BVH {
+public:
+ void build(const Mesh& mesh);
+ bool raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) const;
+ // Appends every vertex within `radius` of `center` to `out` (cleared first).
+ void queryVertices(const Mesh& mesh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) const;
+ // Updates bounds after the given vertices moved. Bounds only ever grow
+ // conservatively for ancestors, which keeps queries correct.
+ void refit(const Mesh& mesh, std::span<const uint32_t> movedVerts);
+
+ size_t nodeCount() const { return nodes_.size(); }
+
+private:
+ struct Node {
+ AABB box;
+ uint32_t first = 0; // leaf: offset into triIndices_, inner: index of left child (right = first + 1)
+ uint32_t count = 0; // > 0 for leaves
+ uint32_t parent = 0;
+ };
+
+ uint32_t nextStamp(std::vector<uint32_t>& stamps, uint32_t& stamp) const;
+ void recomputeLeaf(const Mesh& mesh, Node& n);
+
+ std::vector<Node> nodes_;
+ std::vector<uint32_t> triIndices_;
+ std::vector<uint32_t> triLeaf_;
+
+ mutable std::vector<uint32_t> vertStamp_;
+ mutable uint32_t vertStampValue_ = 0;
+ std::vector<uint32_t> leafStamp_;
+ uint32_t leafStampValue_ = 0;
+ std::vector<uint32_t> scratchLeaves_;
+ mutable std::vector<uint32_t> stack_;
+};
+
+} // namespace sf
diff --git a/src/core/BrushRecipe.cpp b/src/core/BrushRecipe.cpp
new file mode 100644
index 00000000..36cdbf44
--- /dev/null
+++ b/src/core/BrushRecipe.cpp
@@ -0,0 +1,334 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/BrushRecipe.h"
+
+#include <algorithm>
+#include <cmath>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+namespace sf {
+
+namespace {
+
+using K = RecipeParam::Kind;
+
+const char* kDirections[] = {"normal", "inflate", "view", "stroke"};
+const char* kPlanes[] = {"none", "clay", "flatten", "fill", "scrape"};
+const char* kPatterns[] = {"none", "noise", "scales", "ridges", "pores", "cracks"};
+
+template <typename E, size_t N>
+E enumFromString(const std::string& s, const char* (&names)[N], E fallback) {
+ for (size_t i = 0; i < N; ++i)
+ if (s == names[i]) return E(i);
+ return fallback;
+}
+
+float* floatField(BrushRecipe& r, const std::string& key) {
+ if (key == "depth") return &r.depth;
+ if (key == "planeAmount") return &r.planeAmount;
+ if (key == "pinch") return &r.pinch;
+ if (key == "drag") return &r.drag;
+ if (key == "smooth") return &r.smooth;
+ if (key == "hardness") return &r.hardness;
+ if (key == "tipSharpness") return &r.tipSharpness;
+ if (key == "patternScale") return &r.patternScale;
+ if (key == "patternAmount") return &r.patternAmount;
+ if (key == "spacing") return &r.spacing;
+ if (key == "jitter") return &r.jitter;
+ if (key == "pressureCurve") return &r.pressureCurve;
+ if (key == "cavityMask") return &r.cavityMask;
+ return nullptr;
+}
+
+std::filesystem::path utf8Path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
+
+} // namespace
+
+const std::vector<RecipeParam>& recipeParams() {
+ static const std::vector<RecipeParam> params = {
+ {"direction", "Direction",
+ "Which way the surface moves: 'normal' = out of the surface (like adding clay), 'inflate' = puffs "
+ "outward in every direction, 'view' = toward the camera, 'stroke' = pushes along the stroke direction.",
+ K::Enum, 0, 0, {kDirections[0], kDirections[1], kDirections[2], kDirections[3]}},
+ {"depth", "Depth", "How much material is added (positive) or carved away (negative). Range -1 to 1.",
+ K::Float, -1.0f, 1.0f, {}},
+ {"plane", "Plane",
+ "Planar behaviour: 'clay' builds up flat-topped layers, 'flatten' levels everything, 'fill' only raises "
+ "low spots, 'scrape' only cuts down high spots, 'none' disables it.",
+ K::Enum, 0, 0, {kPlanes[0], kPlanes[1], kPlanes[2], kPlanes[3], kPlanes[4]}},
+ {"planeAmount", "Plane amount", "Strength of the plane behaviour. Range 0 to 1.", K::Float, 0.0f, 1.0f, {}},
+ {"pinch", "Pinch",
+ "Pulls the surface toward the centre of the stroke for crisp creases and edges (negative spreads it "
+ "apart). Range -1 to 1.",
+ K::Float, -1.0f, 1.0f, {}},
+ {"drag", "Drag", "Smears and drags the surface along with the stroke, like a palette knife. Range 0 to 1.",
+ K::Float, 0.0f, 1.0f, {}},
+ {"smooth", "Auto smooth", "Relaxes the surface as you paint for softer, cleaner results. Range 0 to 1.",
+ K::Float, 0.0f, 1.0f, {}},
+ {"hardness", "Hardness", "Edge of the brush tip: 0 = soft airbrush falloff, 1 = hard-edged stamp. Range 0 to 1.",
+ K::Float, 0.0f, 1.0f, {}},
+ {"tipSharpness", "Tip sharpness",
+ "Profile of the tip: 0 = round and broad, 1 = narrow needle point for fine lines. Range 0 to 1.", K::Float,
+ 0.0f, 1.0f, {}},
+ {"pattern", "Pattern",
+ "Surface texture stamped by the brush: 'noise' = organic bumps, 'scales' = rounded reptile scales, "
+ "'ridges' = sinewy ridges, 'pores' = small skin pits, 'cracks' = cracked stone/dry earth lines, 'none'.",
+ K::Enum, 0, 0, {kPatterns[0], kPatterns[1], kPatterns[2], kPatterns[3], kPatterns[4], kPatterns[5]}},
+ {"patternScale", "Pattern size", "Size of texture features relative to the brush size. Range 0.03 to 2.",
+ K::Float, 0.03f, 2.0f, {}},
+ {"patternAmount", "Pattern amount", "How strongly the texture shows. Range 0 to 1.", K::Float, 0.0f, 1.0f, {}},
+ {"spacing", "Spacing",
+ "Distance between dabs relative to brush size: small = continuous line, large = separate stamps. Range "
+ "0.02 to 2.",
+ K::Float, 0.02f, 2.0f, {}},
+ {"jitter", "Jitter", "Random scatter of dabs around the stroke. Range 0 to 1.", K::Float, 0.0f, 1.0f, {}},
+ {"pressureCurve", "Pressure curve",
+ "Tablet response: below 1 reacts to a light touch, above 1 needs a firm press. Range 0.3 to 3.", K::Float,
+ 0.3f, 3.0f, {}},
+ {"frontFacesOnly", "Front faces only", "Only affect surfaces facing the camera (protects thin parts).",
+ K::Bool, 0, 1, {}},
+ {"cavityMask", "Cavity mask",
+ "Limits the brush to cavities (positive, e.g. dirt in crevices) or to peaks and ridges (negative, e.g. "
+ "wear on edges). 0 = everywhere. Range -1 to 1.",
+ K::Float, -1.0f, 1.0f, {}},
+ };
+ return params;
+}
+
+float* BrushRecipe::field(const std::string& key) { return floatField(*this, key); }
+
+int BrushRecipe::enumIndex(const std::string& key) const {
+ if (key == "direction") return int(direction);
+ if (key == "plane") return int(plane);
+ if (key == "pattern") return int(pattern);
+ return 0;
+}
+
+void BrushRecipe::setEnumIndex(const std::string& key, int index) {
+ if (key == "direction") direction = Direction(std::clamp(index, 0, 3));
+ else if (key == "plane") plane = Plane(std::clamp(index, 0, 4));
+ else if (key == "pattern") pattern = Pattern(std::clamp(index, 0, 5));
+}
+
+void BrushRecipe::clamp() {
+ for (const auto& p : recipeParams())
+ if (p.kind == K::Float)
+ if (float* f = floatField(*this, p.key)) *f = std::clamp(*f, p.min, p.max);
+ if (name.empty()) name = "Custom Brush";
+ if (name.size() > 64) name.resize(64);
+ if (description.size() > 500) description.resize(500);
+}
+
+Json BrushRecipe::toJson() const {
+ BrushRecipe r = *this;
+ Json j = Json::object();
+ j.set("name", r.name);
+ j.set("description", r.description);
+ for (const auto& p : recipeParams()) {
+ switch (p.kind) {
+ case K::Float: j.set(p.key, std::round(double(*floatField(r, p.key)) * 1000.0) / 1000.0); break;
+ case K::Bool: j.set(p.key, frontFacesOnly); break;
+ case K::Enum:
+ if (std::string(p.key) == "direction") j.set(p.key, kDirections[int(direction)]);
+ else if (std::string(p.key) == "plane") j.set(p.key, kPlanes[int(plane)]);
+ else j.set(p.key, kPatterns[int(pattern)]);
+ break;
+ }
+ }
+ return j;
+}
+
+void BrushRecipe::applyJson(const Json& j) {
+ if (!j.isObject()) return;
+ if (j["name"].isString()) name = j["name"].asString();
+ if (j["description"].isString()) description = j["description"].asString();
+ for (const auto& p : recipeParams()) {
+ const Json& v = j[p.key];
+ if (v.isNull()) continue;
+ switch (p.kind) {
+ case K::Float:
+ if (v.isNumber()) *floatField(*this, p.key) = float(v.asNumber());
+ break;
+ case K::Bool:
+ if (v.isBool()) frontFacesOnly = v.asBool();
+ break;
+ case K::Enum: {
+ const std::string& s = v.asString();
+ if (std::string(p.key) == "direction") direction = enumFromString(s, kDirections, direction);
+ else if (std::string(p.key) == "plane") plane = enumFromString(s, kPlanes, plane);
+ else pattern = enumFromString(s, kPatterns, pattern);
+ break;
+ }
+ }
+ }
+ clamp();
+}
+
+BrushRecipe BrushRecipe::fromJson(const Json& j) {
+ BrushRecipe r;
+ r.applyJson(j);
+ return r;
+}
+
+bool BrushRecipe::save(const std::string& path, std::string& error) const {
+ Json j = toJson();
+ j.set("format", "sfbrush");
+ j.set("version", 1);
+ std::ofstream f(utf8Path(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ f << j.dump(true) << "\n";
+ return bool(f);
+}
+
+bool BrushRecipe::load(const std::string& path, BrushRecipe& out, std::string& error) {
+ std::ifstream f(utf8Path(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ Json j;
+ if (!Json::parse(text, j, error)) return false;
+ if (!j.isObject()) {
+ error = "Not a brush file";
+ return false;
+ }
+ out = fromJson(j);
+ return true;
+}
+
+Json recipeJsonSchema() {
+ Json props = Json::object();
+ Json required = Json::array();
+ auto addString = [&](const char* key, const char* desc) {
+ Json p = Json::object();
+ p.set("type", "string");
+ p.set("description", desc);
+ props.set(key, p);
+ required.push(key);
+ };
+ addString("name", "Short, evocative brush name an artist would recognise (max ~4 words).");
+ addString("description", "One sentence describing what the brush does and when to use it.");
+ for (const auto& rp : recipeParams()) {
+ Json p = Json::object();
+ p.set("description", rp.help);
+ if (rp.kind == K::Float) {
+ p.set("type", "number");
+ } else if (rp.kind == K::Bool) {
+ p.set("type", "boolean");
+ } else {
+ p.set("type", "string");
+ Json e = Json::array();
+ for (const char* o : rp.options) e.push(o);
+ p.set("enum", e);
+ }
+ props.set(rp.key, p);
+ required.push(rp.key);
+ }
+ Json schema = Json::object();
+ schema.set("type", "object");
+ schema.set("properties", props);
+ schema.set("required", required);
+ schema.set("additionalProperties", false);
+ return schema;
+}
+
+std::vector<BrushRecipe> builtinBrushRecipes() {
+ std::vector<BrushRecipe> out;
+ auto add = [&](BrushRecipe r) {
+ r.clamp();
+ out.push_back(std::move(r));
+ };
+ {
+ BrushRecipe r;
+ r.name = "Wrinkle";
+ r.description = "Fine, sharp creases for skin folds and fabric wrinkles.";
+ r.depth = -0.55f;
+ r.pinch = 0.7f;
+ r.tipSharpness = 0.7f;
+ r.hardness = 0.15f;
+ r.spacing = 0.06f;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Palette Knife";
+ r.description = "Flattens and drags clay sideways like a sculptor's knife.";
+ r.depth = 0.0f;
+ r.plane = BrushRecipe::Plane::Flatten;
+ r.planeAmount = 0.8f;
+ r.drag = 0.6f;
+ r.hardness = 0.75f;
+ r.spacing = 0.1f;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Dragon Scales";
+ r.description = "Stamps rounded overlapping scales along the stroke.";
+ r.depth = 0.45f;
+ r.pattern = BrushRecipe::Pattern::Scales;
+ r.patternScale = 0.35f;
+ r.patternAmount = 0.95f;
+ r.hardness = 0.35f;
+ r.spacing = 0.35f;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Stone Chisel";
+ r.description = "Scrapes hard planes and breaks them up with cracks for rocks and ruins.";
+ r.depth = -0.25f;
+ r.plane = BrushRecipe::Plane::Scrape;
+ r.planeAmount = 0.8f;
+ r.pattern = BrushRecipe::Pattern::Cracks;
+ r.patternScale = 0.45f;
+ r.patternAmount = 0.6f;
+ r.hardness = 0.85f;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Skin Pores";
+ r.description = "Sprinkles tiny pores for close-up skin detail.";
+ r.depth = -0.2f;
+ r.pattern = BrushRecipe::Pattern::Pores;
+ r.patternScale = 0.08f;
+ r.patternAmount = 1.0f;
+ r.spacing = 0.3f;
+ r.jitter = 0.3f;
+ r.frontFacesOnly = true;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Clay Buildup";
+ r.description = "Builds up flat-topped strokes of clay for blocking in forms.";
+ r.depth = 0.3f;
+ r.plane = BrushRecipe::Plane::Clay;
+ r.planeAmount = 0.7f;
+ r.hardness = 0.35f;
+ r.smooth = 0.1f;
+ add(r);
+ }
+ {
+ BrushRecipe r;
+ r.name = "Edge Wear";
+ r.description = "Chips and softens only the sharp edges and ridges, for weathered props.";
+ r.depth = -0.35f;
+ r.pattern = BrushRecipe::Pattern::Noise;
+ r.patternScale = 0.25f;
+ r.patternAmount = 0.7f;
+ r.cavityMask = -0.8f;
+ r.hardness = 0.4f;
+ add(r);
+ }
+ return out;
+}
+
+} // namespace sf
diff --git a/src/core/BrushRecipe.h b/src/core/BrushRecipe.h
new file mode 100644
index 00000000..a87794f0
--- /dev/null
+++ b/src/core/BrushRecipe.h
@@ -0,0 +1,84 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// A brush recipe describes a sculpting brush as data: how the surface moves,
+// the shape of the tip, surface texture, stroke behaviour and masking. Recipes
+// are what artists (or the AI brush assistant) create; they are saved as
+// shareable .sfbrush JSON files and never contain executable code.
+#pragma once
+
+#include "core/Json.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct BrushRecipe {
+ enum class Direction { Normal, Inflate, View, Stroke };
+ enum class Plane { None, Clay, Flatten, Fill, Scrape };
+ enum class Pattern { None, Noise, Scales, Ridges, Pores, Cracks };
+
+ std::string name = "Custom Brush";
+ std::string description;
+
+ // Surface motion
+ Direction direction = Direction::Normal;
+ float depth = 0.5f; // -1..1: positive builds up, negative carves
+ Plane plane = Plane::None;
+ float planeAmount = 0.5f; // 0..1
+ float pinch = 0.0f; // -1..1: pulls surface toward the stroke centre line (crisp edges)
+ float drag = 0.0f; // 0..1: smears the surface along the stroke
+ float smooth = 0.0f; // 0..1: relaxes the surface after each dab
+
+ // Tip shape
+ float hardness = 0.0f; // 0 = soft airbrush edge, 1 = hard stamp edge
+ float tipSharpness = 0.0f; // 0 = rounded, 1 = needle-like point
+
+ // Surface texture
+ Pattern pattern = Pattern::None;
+ float patternScale = 0.3f; // feature size as a fraction of brush radius (0.03..2)
+ float patternAmount = 0.0f; // 0..1
+
+ // Stroke
+ float spacing = 0.15f; // dab spacing as a fraction of brush size (0.02..2)
+ float jitter = 0.0f; // 0..1 random scatter of dabs
+ float pressureCurve = 1.0f; // 0.3..3: >1 needs a harder press, <1 responds to light touch
+
+ // Masking
+ bool frontFacesOnly = false;
+ float cavityMask = 0.0f; // -1..1: >0 only affects cavities, <0 only ridges/peaks
+
+ void clamp();
+ // Numeric parameter by key (see recipeParams()), or nullptr.
+ float* field(const std::string& key);
+ // Enum parameters as indices into RecipeParam::options.
+ int enumIndex(const std::string& key) const;
+ void setEnumIndex(const std::string& key, int index);
+ Json toJson() const;
+ // Lenient: missing keys keep their current values, values are clamped.
+ void applyJson(const Json& j);
+ static BrushRecipe fromJson(const Json& j);
+
+ bool save(const std::string& path, std::string& error) const;
+ static bool load(const std::string& path, BrushRecipe& out, std::string& error);
+};
+
+// Describes each recipe parameter once, for UI, AI schema and commands.
+struct RecipeParam {
+ const char* key;
+ const char* label;
+ const char* help; // written for artists
+ enum class Kind { Float, Enum, Bool } kind;
+ float min = 0.0f, max = 1.0f;
+ std::vector<const char*> options; // Enum values
+};
+const std::vector<RecipeParam>& recipeParams();
+
+// JSON Schema (structured-output compatible: all keys required, no
+// additionalProperties, ranges given in descriptions).
+Json recipeJsonSchema();
+
+std::vector<BrushRecipe> builtinBrushRecipes();
+
+} // namespace sf
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
new file mode 100644
index 00000000..22da76d6
--- /dev/null
+++ b/src/core/Commands.cpp
@@ -0,0 +1,642 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Commands.h"
+
+#include "core/Decimate.h"
+#include "core/EnginePresets.h"
+#include "core/ImageTo3D.h"
+#include "core/Primitives.h"
+#include "core/Splats.h"
+#include "core/Voxel.h"
+#include "io/FbxIO.h"
+#include "io/GltfIO.h"
+#include "io/ObjIO.h"
+#include "io/PlyIO.h"
+#include "io/UsdIO.h"
+
+#include <algorithm>
+#include <filesystem>
+#include <glm/gtc/matrix_transform.hpp>
+#include <sstream>
+
+namespace sf {
+
+double argNumber(const Args& args, const std::string& key, double fallback) {
+ auto it = args.find(key);
+ if (it == args.end()) return fallback;
+ if (auto* d = std::get_if<double>(&it->second)) return *d;
+ if (auto* b = std::get_if<bool>(&it->second)) return *b ? 1.0 : 0.0;
+ return fallback;
+}
+
+bool argBool(const Args& args, const std::string& key, bool fallback) {
+ auto it = args.find(key);
+ if (it == args.end()) return fallback;
+ if (auto* b = std::get_if<bool>(&it->second)) return *b;
+ if (auto* d = std::get_if<double>(&it->second)) return *d != 0.0;
+ return fallback;
+}
+
+std::string argString(const Args& args, const std::string& key, const std::string& fallback) {
+ auto it = args.find(key);
+ if (it == args.end()) return fallback;
+ if (auto* s = std::get_if<std::string>(&it->second)) return *s;
+ return fallback;
+}
+
+namespace {
+
+constexpr size_t kMaxSubdivideTriangles = 50'000'000;
+
+std::string lowerExtension(const std::string& path) {
+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return ext;
+}
+
+std::string jsonEscape(const std::string& s) {
+ std::string out;
+ for (char c : s) {
+ switch (c) {
+ case '"': out += "\\\""; break;
+ case '\\': out += "\\\\"; break;
+ case '\n': out += "\\n"; break;
+ default: out += c;
+ }
+ }
+ return out;
+}
+
+} // namespace
+
+CommandRegistry::CommandRegistry() {
+ using T = ParamSpec::Type;
+
+ add({"new_sphere",
+ "Replace the scene with a new sphere ready for sculpting.",
+ {{"subdivisions", T::Number, "Icosphere subdivision level (0-8). Default 6.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int level = std::clamp(int(argNumber(a, "subdivisions", 6)), 0, 8);
+ doc.setMesh(makeIcosphere(level));
+ doc.path.clear();
+ return {true, "Created sphere with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"new_plane",
+ "Replace the scene with a flat grid plane.",
+ {{"resolution", T::Number, "Grid cells per side (1-2000). Default 128.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int res = std::clamp(int(argNumber(a, "resolution", 128)), 1, 2000);
+ doc.setMesh(makePlane(res));
+ doc.path.clear();
+ return {true, "Created plane with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"open_obj",
+ "Load a Wavefront OBJ file, replacing the current scene.",
+ {{"path", T::String, "File path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path");
+ Mesh m;
+ std::string err;
+ if (!loadObj(path, m, err)) return {false, err};
+ doc.setMesh(std::move(m));
+ doc.path = path;
+ return {true, "Loaded " + path};
+ }});
+
+ add({"open",
+ "Open a file: models (.obj, .fbx, .glb, .gltf, .ply, .usda, .usdz) replace the scene; Gaussian splats "
+ "(.ply/.splat captures, KHR_gaussian_splatting .glb, USD ParticleField) load as a reference next to the sculpt. "
+ "glTF morph targets and FBX/USD blend shapes become sculpt layers.",
+ {{"path", T::String, "File path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path");
+ const std::string ext = lowerExtension(path);
+ Mesh m;
+ SplatCloud splats;
+ std::string err;
+ bool ok;
+ if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, m, err, &splats);
+ else if (ext == ".usda" || ext == ".usd" || ext == ".usdz") ok = loadUsd(path, m, splats, err);
+ else if (ext == ".splat") ok = loadDotSplat(path, splats, err);
+ else if (ext == ".fbx") ok = loadFbx(path, m, err);
+ else if (ext == ".ply") {
+ PlyContent content;
+ ok = loadPly(path, m, splats, content, err);
+ } else ok = loadObj(path, m, err);
+ if (!ok) return {false, err};
+ std::string msg = "Opened " + path;
+ if (m.triangleCount()) {
+ doc.setMesh(std::move(m));
+ doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitly
+ msg += " (" + std::to_string(doc.mesh.triangleCount()) + " triangles" +
+ (doc.mesh.layers.empty() ? "" : ", " + std::to_string(doc.mesh.layers.size()) + " layers") + ")";
+ }
+ if (!splats.empty()) {
+ doc.splats = std::move(splats);
+ doc.splatsChanged();
+ msg += " (" + std::to_string(doc.splats.size()) + " Gaussian splats, SH degree " +
+ std::to_string(doc.splats.shDegree) + ")";
+ }
+ return {true, msg};
+ }});
+
+ add({"remesh",
+ "Voxel remesh (like DynaMesh): rebuild the sculpt as an even, watertight surface, merging overlapping "
+ "parts and fixing broken scans or generated models. Sculpt layers are baked in.",
+ {{"resolution", T::Number, "Voxels across the longest side (32-512). Default 200; higher keeps more detail.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string err;
+ Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 200)), 32, 512), &err);
+ if (m.triangleCount() == 0) return {false, err};
+ doc.replaceMeshUndoable(std::move(m), "Remesh");
+ return {true, "Remeshed to " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"image_relief",
+ "Turn an image into a sculpted relief: light areas rise, dark areas stay low (logos, coins, emblems, "
+ "height maps, texture photos). Replaces the scene.",
+ {{"path", T::String, "Image file (png, jpg, bmp, tga...).", true},
+ {"depth", T::Number, "Relief height as a fraction of the width (0.01-1). Default 0.12.", false},
+ {"resolution", T::Number, "Detail: grid cells along the long side (32-2048). Default 384.", false},
+ {"invert", T::Bool, "Make dark areas high instead.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Image img;
+ std::string err;
+ if (!Image::load(argString(a, "path"), img, err)) return {false, err};
+ ReliefOptions o;
+ o.depth = float(std::clamp(argNumber(a, "depth", o.depth), 0.01, 1.0));
+ o.resolution = int(std::clamp(argNumber(a, "resolution", o.resolution), 32.0, 2048.0));
+ o.invert = argBool(a, "invert", false);
+ doc.replaceMeshUndoable(makeImageRelief(img, o), "Image Relief");
+ doc.path.clear();
+ return {true, "Relief with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"image_inflate",
+ "Inflate a sketch or silhouette (transparent background or plain backdrop) into a rounded, closed 3D base "
+ "mesh ready for sculpting. Replaces the scene.",
+ {{"path", T::String, "Image file.", true},
+ {"thickness", T::Number, "1 = round, lower = flatter (0.1-3). Default 1.", false},
+ {"resolution", T::Number, "Detail along the long side (32-512). Default 160.", false},
+ {"subdivisions", T::Number, "Smoothing subdivision passes (0-3). Default 1.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Image img;
+ std::string err;
+ if (!Image::load(argString(a, "path"), img, err)) return {false, err};
+ InflateOptions o;
+ o.thickness = float(std::clamp(argNumber(a, "thickness", 1.0), 0.1, 3.0));
+ o.resolution = int(std::clamp(argNumber(a, "resolution", o.resolution), 32.0, 512.0));
+ o.subdivisions = int(std::clamp(argNumber(a, "subdivisions", 1.0), 0.0, 3.0));
+ Mesh m = inflateSilhouette(img, o, &err);
+ if (m.triangleCount() == 0) return {false, err};
+ doc.replaceMeshUndoable(std::move(m), "Inflate Sketch");
+ doc.path.clear();
+ return {true, "Inflated sketch into " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"image_project",
+ "Stamp an image onto the current model as surface detail, projected from the front (+Z). Light = raised. "
+ "Goes into the active sculpt layer.",
+ {{"path", T::String, "Image file.", true},
+ {"depth", T::Number, "Displacement at full brightness, as a fraction of the model size (0.001-0.5). Default 0.03.", false},
+ {"invert", T::Bool, "Make dark areas raised instead.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Image img;
+ std::string err;
+ if (!Image::load(argString(a, "path"), img, err)) return {false, err};
+ AABB b = doc.mesh.bounds();
+ if (!b.valid()) return {false, "Nothing to project onto"};
+ const float size = glm::length(b.extent());
+ const glm::vec3 eye = b.center() + glm::vec3(0, 0, size * 2.0f);
+ const float halfH = std::max(b.extent().x / std::max(img.aspect(), 1e-3f), b.extent().y) * 0.5f;
+ const float halfW = halfH * img.aspect();
+ glm::mat4 proj = glm::ortho(-halfW, halfW, -halfH, halfH, 0.01f, size * 4.0f);
+ glm::mat4 view = glm::lookAt(eye, b.center(), glm::vec3(0, 1, 0));
+ ProjectOptions o;
+ o.depth = float(std::clamp(argNumber(a, "depth", 0.03), 0.001, 0.5)) * size;
+ o.invert = argBool(a, "invert", false);
+ o.coverage = 1.0f;
+ Mesh m = doc.mesh;
+ size_t n = projectImage(m, doc.activeLayer, img, proj * view, img.aspect(), eye, o);
+ if (n == 0) return {false, "The image did not land on any front-facing surface"};
+ doc.replaceMeshUndoable(std::move(m), "Project Image");
+ return {true, "Projected onto " + std::to_string(n) + " vertices"};
+ }});
+
+ add({"save_obj",
+ "Save the mesh as a Wavefront OBJ file.",
+ {{"path", T::String, "File path (UTF-8). Defaults to the current document path.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path", doc.path);
+ if (path.empty()) return {false, "No path given"};
+ std::string err;
+ if (!saveObj(path, doc.mesh, err)) return {false, err};
+ doc.path = path;
+ doc.modified = false;
+ return {true, "Saved " + path};
+ }});
+
+ add({"subdivide",
+ "Smoothly subdivide the mesh (Loop subdivision). Each level multiplies the triangle count by 4.",
+ {{"levels", T::Number, "Number of subdivision levels to apply (1-4). Default 1.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int levels = std::clamp(int(argNumber(a, "levels", 1)), 1, 4);
+ size_t projected = doc.mesh.triangleCount();
+ for (int i = 0; i < levels; ++i) projected *= 4;
+ if (projected > kMaxSubdivideTriangles)
+ return {false, "Subdividing would exceed " + std::to_string(kMaxSubdivideTriangles) + " triangles"};
+ Mesh m = loopSubdivide(doc.mesh);
+ for (int i = 1; i < levels; ++i) m = loopSubdivide(m);
+ doc.replaceMeshUndoable(std::move(m), "Subdivide");
+ return {true, "Subdivided to " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"layer_add",
+ "Add a sculpt layer (blend shape / morph target). New strokes go into it until another layer is made active.",
+ {{"name", T::String, "Layer name, e.g. 'Smile' or 'BlinkL'.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh m = doc.mesh;
+ int idx = m.addLayer(argString(a, "name", "Layer " + std::to_string(doc.mesh.layers.size() + 1)));
+ doc.replaceMeshUndoable(std::move(m), "Add Layer");
+ doc.activeLayer = idx;
+ return {true, "Added layer '" + doc.mesh.layers[idx].name + "' (index " + std::to_string(idx) + ")"};
+ }});
+
+ add({"layer_remove",
+ "Delete a sculpt layer and its offsets.",
+ {{"index", T::Number, "Layer index (0-based).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int idx = int(argNumber(a, "index", -1));
+ if (idx < 0 || idx >= int(doc.mesh.layers.size())) return {false, "No layer " + std::to_string(idx)};
+ Mesh m = doc.mesh;
+ m.removeLayer(idx);
+ doc.replaceMeshUndoable(std::move(m), "Remove Layer");
+ doc.activeLayer = -1;
+ return {true, "Removed layer " + std::to_string(idx)};
+ }});
+
+ add({"layer_set_weight",
+ "Set how strongly a sculpt layer is applied (0 = off, 1 = as sculpted; negative or >1 exaggerates).",
+ {{"index", T::Number, "Layer index (0-based).", true},
+ {"weight", T::Number, "Blend weight, typically 0-1.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int idx = int(argNumber(a, "index", -1));
+ if (idx < 0 || idx >= int(doc.mesh.layers.size())) return {false, "No layer " + std::to_string(idx)};
+ doc.mesh.setLayerWeight(idx, float(argNumber(a, "weight", 1.0)));
+ doc.bvhDirty = true;
+ doc.modified = true;
+ return {true, "Layer " + std::to_string(idx) + " weight set"};
+ }});
+
+ add({"layer_set_active",
+ "Choose which sculpt layer new strokes go into (-1 = base mesh).",
+ {{"index", T::Number, "Layer index, or -1 for the base mesh.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ int idx = int(argNumber(a, "index", -1));
+ if (idx < -1 || idx >= int(doc.mesh.layers.size())) return {false, "No layer " + std::to_string(idx)};
+ doc.activeLayer = idx;
+ return {true, idx < 0 ? "Sculpting on base mesh" : "Sculpting on layer " + doc.mesh.layers[idx].name};
+ }});
+
+ add({"decimate",
+ "Reduce triangle count while preserving shape (quadric edge collapse). Sculpt layers are kept.",
+ {{"ratio", T::Number, "Fraction of triangles to keep (0.01-1). Default 0.5.", false},
+ {"triangles", T::Number, "Exact target triangle count (overrides ratio).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ size_t target = a.contains("triangles")
+ ? size_t(std::max(4.0, argNumber(a, "triangles", 4)))
+ : size_t(double(doc.mesh.triangleCount()) *
+ std::clamp(argNumber(a, "ratio", 0.5), 0.01, 1.0));
+ doc.replaceMeshUndoable(decimate(doc.mesh, target), "Decimate");
+ return {true, "Decimated to " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ add({"export_glb",
+ "Export a game-ready binary glTF (.glb). Sculpt layers become morph targets (blend shapes).",
+ {{"path", T::String, "Output .glb path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path");
+ std::string err;
+ if (!saveGlb(path, doc.mesh, doc.assetName(), err)) return {false, err};
+ return {true, "Exported " + path};
+ }});
+
+ add({"export_usd",
+ "Export OpenUSD (.usda text, or .usdz package for AR Quick Look / Vision Pro). Sculpt layers become "
+ "UsdSkel blend shapes with their current weights; loaded Gaussian splats are included as a "
+ "ParticleField3DGaussianSplat prim.",
+ {{"path", T::String, "Output .usda, .usd or .usdz path (UTF-8).", true},
+ {"splats", T::Bool, "Include the loaded Gaussian splats. Default true.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path");
+ std::string err;
+ const SplatCloud* splats = argBool(a, "splats", true) && !doc.splats.empty() ? &doc.splats : nullptr;
+ if (!saveUsd(path, &doc.mesh, splats, doc.assetName(), err)) return {false, err};
+ return {true, "Exported " + path + (splats ? " (mesh + " + std::to_string(splats->size()) + " splats)" : "")};
+ }});
+
+ add({"export_fbx",
+ "Export binary FBX: sculpt layers become blend shapes; with lods > 1 the LOD chain is written as an FBX "
+ "LOD group in the same file.",
+ {{"path", T::String, "Output .fbx path (UTF-8).", true},
+ {"lods", T::Number, "LOD levels including LOD0 (1-8). Default 1.", false},
+ {"ratio", T::Number, "Triangle ratio between LODs (0.1-0.9). Default 0.5.", false},
+ {"scale", T::Number, "Multiply positions (FBX units are centimetres). Default 100 (1 unit = 1 m).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int levels = std::clamp(int(argNumber(a, "lods", 1)), 1, 8);
+ std::vector<Mesh> lods;
+ std::vector<const Mesh*> meshes = {&doc.mesh};
+ if (levels > 1) {
+ lods = generateLods(doc.mesh, levels, float(std::clamp(argNumber(a, "ratio", 0.5), 0.1, 0.9)));
+ meshes.clear();
+ for (const auto& l : lods) meshes.push_back(&l);
+ }
+ FbxExportOptions o;
+ o.scale = float(argNumber(a, "scale", 100.0));
+ std::string err;
+ const std::string path = argString(a, "path");
+ if (!saveFbx(path, doc.assetName(), meshes, o, err)) return {false, err};
+ return {true, "Exported " + path};
+ }});
+
+ add({"export_unreal",
+ "Export an Unreal Engine-ready FBX: centimetres, SM_/SK_ naming, LOD chain packed for automatic LOD "
+ "import; a sculpt with layers becomes a skeletal mesh with morph targets.",
+ {{"folder", T::String, "Output folder (UTF-8). The file is named after the asset.", true},
+ {"name", T::String, "Asset name (default SM_<document> or SK_<document>).", false},
+ {"height_cm", T::Number, "Model height in Unreal, in cm. Default: 1 unit = 1 m.", false},
+ {"lods", T::Number, "LOD levels for static meshes (1-8). Default 4.", false},
+ {"ratio", T::Number, "Triangle ratio between LODs (0.1-0.9). Default 0.5.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ UnrealExportOptions o;
+ o.folder = argString(a, "folder");
+ o.assetName = argString(a, "name");
+ o.heightCm = float(argNumber(a, "height_cm", 0.0));
+ o.lods = int(argNumber(a, "lods", 4));
+ o.ratio = float(argNumber(a, "ratio", 0.5));
+ UnrealExportResult r;
+ std::string err;
+ if (!exportForUnreal(doc, o, r, err)) return {false, err};
+ return {true, "Exported " + r.path + " (" + (r.skeletal ? "skeletal mesh, " + std::to_string(doc.mesh.layers.size()) + " morph targets"
+ : "static mesh, " + std::to_string(r.lodCount) + " LODs") + ")"};
+ }});
+
+ add({"export_lods",
+ "Generate a LOD chain and export each level as <name>_LOD<n>.glb next to `path`. Blend shapes are kept on every LOD.",
+ {{"path", T::String, "Base output path, e.g. /assets/rock.glb.", true},
+ {"levels", T::Number, "Number of LODs including LOD0 (1-8). Default 4.", false},
+ {"ratio", T::Number, "Triangle ratio between consecutive LODs (0.1-0.9). Default 0.5.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string pathArg = argString(a, "path");
+ std::filesystem::path base(std::u8string(pathArg.begin(), pathArg.end()));
+ int levels = std::clamp(int(argNumber(a, "levels", 4)), 1, 8);
+ float ratio = float(std::clamp(argNumber(a, "ratio", 0.5), 0.1, 0.9));
+ auto lods = generateLods(doc.mesh, levels, ratio);
+ auto stemU8 = base.stem().u8string();
+ std::string stem(stemU8.begin(), stemU8.end());
+ std::ostringstream msg;
+ msg << "Exported";
+ for (size_t i = 0; i < lods.size(); ++i) {
+ std::string fileName = stem + "_LOD" + std::to_string(i) + ".glb";
+ auto out = (base.parent_path() / std::u8string(fileName.begin(), fileName.end())).u8string();
+ std::string outPath(out.begin(), out.end());
+ std::string err;
+ if (!saveGlb(outPath, lods[i], stem + "_LOD" + std::to_string(i), err)) return {false, err};
+ msg << " LOD" << i << " (" << lods[i].triangleCount() << " tris)";
+ }
+ return {true, msg.str()};
+ }});
+
+ {
+ // brush_create takes every recipe parameter, so AI tool calls and scripts can design brushes.
+ std::vector<ParamSpec> params = {{"name", T::String, "Brush name.", true},
+ {"description", T::String, "What the brush is for.", false}};
+ for (const auto& rp : recipeParams()) {
+ T type = rp.kind == RecipeParam::Kind::Float ? T::Number
+ : rp.kind == RecipeParam::Kind::Bool ? T::Bool
+ : T::String;
+ params.push_back({rp.key, type, rp.help, false});
+ }
+ add({"brush_create",
+ "Create (or update, by name) a custom sculpting brush from a recipe and make it the active brush. "
+ "Omitted parameters use neutral defaults.",
+ params, [](Document& doc, const Args& a) -> CommandResult {
+ Json j = Json::object();
+ for (const auto& [key, value] : a) {
+ if (auto* d = std::get_if<double>(&value)) j.set(key, *d);
+ else if (auto* b = std::get_if<bool>(&value)) j.set(key, *b);
+ else j.set(key, std::get<std::string>(value));
+ }
+ doc.activeBrush = doc.addBrush(BrushRecipe::fromJson(j));
+ return {true, "Brush '" + doc.brushes[doc.activeBrush].name + "' ready"};
+ }});
+ }
+
+ add({"brush_list", "List the custom brushes in the library.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ std::string out;
+ for (size_t i = 0; i < doc.brushes.size(); ++i)
+ out += (i ? "\n" : "") + std::to_string(i) + ": " + doc.brushes[i].name + " - " +
+ doc.brushes[i].description;
+ return {true, out};
+ }});
+
+ add({"brush_save", "Save a custom brush as a shareable .sfbrush file.",
+ {{"path", T::String, "Output .sfbrush path.", true},
+ {"name", T::String, "Brush name (defaults to the active brush).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string name = argString(a, "name");
+ const BrushRecipe* r = nullptr;
+ for (const auto& b : doc.brushes)
+ if (b.name == name) r = &b;
+ if (!r && name.empty() && doc.activeBrush >= 0) r = &doc.brushes[doc.activeBrush];
+ if (!r) return {false, "No such brush: " + name};
+ std::string err;
+ if (!r->save(argString(a, "path"), err)) return {false, err};
+ return {true, "Saved brush '" + r->name + "'"};
+ }});
+
+ add({"brush_load", "Load a .sfbrush file into the library and make it active.",
+ {{"path", T::String, ".sfbrush path.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ BrushRecipe r;
+ std::string err;
+ if (!BrushRecipe::load(argString(a, "path"), r, err)) return {false, err};
+ doc.activeBrush = doc.addBrush(std::move(r));
+ return {true, "Loaded brush '" + doc.brushes[doc.activeBrush].name + "'"};
+ }});
+
+ add({"splat_info", "Report the loaded Gaussian splats.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (doc.splats.empty()) return {true, "No splats loaded"};
+ const AABB b = doc.splats.bounds(0.98f);
+ std::ostringstream s;
+ s << doc.splats.size() << " splats, SH degree " << doc.splats.shDegree << ", main body ("
+ << b.min.x << ", " << b.min.y << ", " << b.min.z << ") - (" << b.max.x << ", " << b.max.y << ", " << b.max.z << ")";
+ return {true, s.str()};
+ }});
+
+ add({"splat_save",
+ "Save the loaded Gaussian splats: .ply (standard 3DGS layout, e.g. for SuperSplat/Postshot), .splat (compact web viewers), .glb "
+ "(glTF KHR_gaussian_splatting) or .usda/.usdz (OpenUSD ParticleField3DGaussianSplat).",
+ {{"path", T::String, "Output path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.splats.empty()) return {false, "No splats loaded"};
+ const std::string path = argString(a, "path");
+ const std::string ext = lowerExtension(path);
+ std::string err;
+ bool ok = ext == ".ply" ? saveSplatPly(path, doc.splats, err)
+ : ext == ".splat" ? saveDotSplat(path, doc.splats, err)
+ : ext == ".glb" ? saveSplatGlb(path, doc.splats, err)
+ : (ext == ".usda" || ext == ".usd" || ext == ".usdz")
+ ? saveUsd(path, nullptr, &doc.splats, doc.assetName(), err)
+ : (err = "Use a .ply, .splat, .glb, .usda or .usdz file name", false);
+ if (!ok) return {false, err};
+ return {true, "Saved " + std::to_string(doc.splats.size()) + " splats to " + path};
+ }});
+
+ add({"splat_clean", "Remove faint splats and outlying floaters from a capture.",
+ {{"min_opacity", T::Number, "Remove splats fainter than this (0-1). Default 0.05.", false},
+ {"keep", T::Number, "Fraction of the capture to keep per axis, trimming outliers (0.5-1). Default 0.98.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.splats.empty()) return {false, "No splats loaded"};
+ const size_t removed = cleanSplats(doc.splats, float(std::clamp(argNumber(a, "min_opacity", 0.05), 0.0, 1.0)),
+ float(std::clamp(argNumber(a, "keep", 0.98), 0.5, 1.0)));
+ doc.splatsChanged();
+ return {true, "Removed " + std::to_string(removed) + " splats, " + std::to_string(doc.splats.size()) + " left"};
+ }});
+
+ add({"splat_transform",
+ "Turn and place the splats (captures are often upside down or off-centre). Rotations are in degrees "
+ "about the capture's centre, applied X then Y then Z.",
+ {{"rotate_x", T::Number, "Degrees about X (180 flips an upside-down capture).", false},
+ {"rotate_y", T::Number, "Degrees about Y.", false},
+ {"rotate_z", T::Number, "Degrees about Z.", false},
+ {"fit", T::Bool, "Centre at the origin and scale to the size of a new sphere.", false},
+ {"reset", T::Bool, "Undo all placement first.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.splats.empty()) return {false, "No splats loaded"};
+ if (argBool(a, "reset", false)) doc.splats.transform = glm::mat4(1.0f);
+ rotateSplats(doc.splats, glm::vec3(float(argNumber(a, "rotate_x", 0)), float(argNumber(a, "rotate_y", 0)),
+ float(argNumber(a, "rotate_z", 0))));
+ if (argBool(a, "fit", false)) fitSplats(doc.splats);
+ doc.splatsChanged();
+ return {true, "Splats placed"};
+ }});
+
+ add({"splat_to_mesh",
+ "Convert a Gaussian-splat capture into a watertight, sculptable mesh (replaces the sculpt; the splats "
+ "stay as a reference). Trim the capture first so only the subject remains.",
+ {{"resolution", T::Number, "Voxels across the subject (32-512). Default 192.", false},
+ {"min_opacity", T::Number, "Ignore splats fainter than this (0-1). Default 0.25.", false},
+ {"keep", T::Number, "Fraction of splats to keep per axis, trimming floaters (0.5-1). Default 0.97.", false},
+ {"close", T::Number, "Seal holes up to this many voxels (0-8). Default 2.", false},
+ {"smooth", T::Number, "Smoothing passes (0-50). Default 6.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.splats.empty()) return {false, "No splats loaded"};
+ SplatToMeshOptions o;
+ o.resolution = int(argNumber(a, "resolution", o.resolution));
+ o.minOpacity = float(argNumber(a, "min_opacity", o.minOpacity));
+ o.keepFraction = float(argNumber(a, "keep", o.keepFraction));
+ o.closeRadius = int(argNumber(a, "close", o.closeRadius));
+ o.smoothIterations = int(argNumber(a, "smooth", o.smoothIterations));
+ std::string err;
+ Mesh m = splatsToMesh(doc.splats, o, &err);
+ if (m.triangleCount() == 0) return {false, err};
+ doc.replaceMeshUndoable(std::move(m), "Splats to Mesh");
+ return {true, "Built a " + std::to_string(doc.mesh.triangleCount()) + "-triangle mesh from the splats"};
+ }});
+
+ add({"mesh_to_splats",
+ "Turn the sculpt into Gaussian splats (flat oriented surfels with baked clay shading), replacing any "
+ "loaded splats - for splat viewers, web scenes and engines that render 3DGS.",
+ {{"count", T::Number, "Number of splats (1000-5000000). Default 250000.", false},
+ {"shading", T::Bool, "Bake soft lighting and cavity darkening into the colour. Default true.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.mesh.triangleCount() == 0) return {false, "The mesh is empty"};
+ MeshToSplatsOptions o;
+ o.count = size_t(std::clamp(argNumber(a, "count", 250000), 1000.0, 5000000.0));
+ o.shading = argBool(a, "shading", true);
+ doc.splats = meshToSplats(doc.mesh, o);
+ doc.splats.name = doc.assetName();
+ doc.splatsChanged();
+ return {true, "Made " + std::to_string(doc.splats.size()) + " splats from the sculpt"};
+ }});
+
+ add({"splat_clear", "Remove the loaded Gaussian splats.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ doc.splats.clear();
+ doc.splatsChanged();
+ return {true, "Splats cleared"};
+ }});
+
+ add({"undo", "Undo the last action.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (!doc.undo.undo(doc.mesh, doc.bvh)) return {false, "Nothing to undo"};
+ doc.modified = true;
+ return {true, "Undone"};
+ }});
+
+ add({"redo", "Redo the last undone action.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ if (!doc.undo.redo(doc.mesh, doc.bvh)) return {false, "Nothing to redo"};
+ doc.modified = true;
+ return {true, "Redone"};
+ }});
+
+ add({"mesh_info", "Report vertex/triangle counts and bounding box of the mesh.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ AABB b = doc.mesh.bounds();
+ std::ostringstream s;
+ s << doc.mesh.vertexCount() << " vertices, " << doc.mesh.triangleCount() << " triangles";
+ if (b.valid())
+ s << ", bounds (" << b.min.x << ", " << b.min.y << ", " << b.min.z << ") - (" << b.max.x << ", "
+ << b.max.y << ", " << b.max.z << ")";
+ return {true, s.str()};
+ }});
+}
+
+void CommandRegistry::add(Command cmd) { commands_.push_back(std::move(cmd)); }
+
+const Command* CommandRegistry::find(const std::string& name) const {
+ for (const auto& c : commands_)
+ if (c.name == name) return &c;
+ return nullptr;
+}
+
+CommandResult CommandRegistry::execute(Document& doc, const std::string& name, const Args& args) const {
+ const Command* cmd = find(name);
+ if (!cmd) return {false, "Unknown command: " + name};
+ for (const auto& p : cmd->params)
+ if (p.required && !args.contains(p.name)) return {false, "Missing required argument: " + p.name};
+ return cmd->run(doc, args);
+}
+
+std::string CommandRegistry::toolSchemaJson() const {
+ std::ostringstream s;
+ s << "[";
+ for (size_t i = 0; i < commands_.size(); ++i) {
+ const auto& c = commands_[i];
+ s << (i ? "," : "") << "{\"name\":\"" << jsonEscape(c.name) << "\",\"description\":\""
+ << jsonEscape(c.description) << "\",\"input_schema\":{\"type\":\"object\",\"properties\":{";
+ std::vector<std::string> required;
+ for (size_t j = 0; j < c.params.size(); ++j) {
+ const auto& p = c.params[j];
+ const char* type = p.type == ParamSpec::Type::Bool ? "boolean"
+ : p.type == ParamSpec::Type::Number ? "number"
+ : "string";
+ s << (j ? "," : "") << "\"" << jsonEscape(p.name) << "\":{\"type\":\"" << type
+ << "\",\"description\":\"" << jsonEscape(p.description) << "\"}";
+ if (p.required) required.push_back(p.name);
+ }
+ s << "},\"required\":[";
+ for (size_t j = 0; j < required.size(); ++j) s << (j ? "," : "") << "\"" << jsonEscape(required[j]) << "\"";
+ s << "]}}";
+ }
+ s << "]";
+ return s.str();
+}
+
+} // namespace sf
diff --git a/src/core/Commands.h b/src/core/Commands.h
new file mode 100644
index 00000000..1357cd4a
--- /dev/null
+++ b/src/core/Commands.h
@@ -0,0 +1,63 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Every editor operation is a named command with typed parameters. The UI,
+// keyboard shortcuts, future scripting and the bring-your-own-AI assistant
+// all go through this registry, so anything an AI does is the same undoable
+// action a user could perform. `toolSchemaJson()` exports the registry in the
+// JSON-schema "tools" shape used by LLM function-calling APIs.
+#pragma once
+
+#include "core/Document.h"
+
+#include <functional>
+#include <map>
+#include <string>
+#include <variant>
+#include <vector>
+
+namespace sf {
+
+using ArgValue = std::variant<bool, double, std::string>;
+using Args = std::map<std::string, ArgValue>;
+
+struct ParamSpec {
+ std::string name;
+ enum class Type { Bool, Number, String } type;
+ std::string description;
+ bool required = false;
+};
+
+struct CommandResult {
+ bool ok = true;
+ std::string message;
+};
+
+struct Command {
+ std::string name;
+ std::string description;
+ std::vector<ParamSpec> params;
+ std::function<CommandResult(Document&, const Args&)> run;
+};
+
+class CommandRegistry {
+public:
+ CommandRegistry(); // registers the built-in commands
+
+ void add(Command cmd);
+ const Command* find(const std::string& name) const;
+ const std::vector<Command>& all() const { return commands_; }
+
+ CommandResult execute(Document& doc, const std::string& name, const Args& args = {}) const;
+ std::string toolSchemaJson() const;
+
+private:
+ std::vector<Command> commands_;
+};
+
+// Argument helpers with defaults.
+double argNumber(const Args& args, const std::string& key, double fallback);
+bool argBool(const Args& args, const std::string& key, bool fallback);
+std::string argString(const Args& args, const std::string& key, const std::string& fallback = {});
+
+} // namespace sf
diff --git a/src/core/Decimate.cpp b/src/core/Decimate.cpp
new file mode 100644
index 00000000..be759c0c
--- /dev/null
+++ b/src/core/Decimate.cpp
@@ -0,0 +1,240 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Decimate.h"
+
+#include <algorithm>
+#include <cmath>
+#include <queue>
+#include <unordered_map>
+
+namespace sf {
+
+namespace {
+
+// Symmetric 4x4 quadric, upper triangle: xx xy xz xw yy yz yw zz zw ww.
+struct Quadric {
+ double q[10] = {};
+
+ static Quadric plane(const glm::dvec3& n, double d, double w) {
+ Quadric r;
+ r.q[0] = w * n.x * n.x; r.q[1] = w * n.x * n.y; r.q[2] = w * n.x * n.z; r.q[3] = w * n.x * d;
+ r.q[4] = w * n.y * n.y; r.q[5] = w * n.y * n.z; r.q[6] = w * n.y * d;
+ r.q[7] = w * n.z * n.z; r.q[8] = w * n.z * d;
+ r.q[9] = w * d * d;
+ return r;
+ }
+ Quadric& operator+=(const Quadric& o) {
+ for (int i = 0; i < 10; ++i) q[i] += o.q[i];
+ return *this;
+ }
+ Quadric operator+(const Quadric& o) const {
+ Quadric r = *this;
+ return r += o;
+ }
+ double eval(const glm::vec3& p) const {
+ const double x = p.x, y = p.y, z = p.z;
+ return q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x + q[4] * y * y + 2 * q[5] * y * z +
+ 2 * q[6] * y + q[7] * z * z + 2 * q[8] * z + q[9];
+ }
+};
+
+struct Candidate {
+ double cost;
+ uint32_t from, to;
+ uint32_t fromVersion, toVersion;
+ bool operator>(const Candidate& o) const { return cost > o.cost; }
+};
+
+uint64_t edgeKey(uint32_t a, uint32_t b) {
+ if (a > b) std::swap(a, b);
+ return (uint64_t(a) << 32) | b;
+}
+
+} // namespace
+
+Mesh decimate(const Mesh& src, size_t targetTriangles) {
+ const size_t nv = src.vertexCount();
+ const size_t nt = src.triangleCount();
+ targetTriangles = std::max<size_t>(targetTriangles, 4);
+ if (nt <= targetTriangles) return src;
+
+ const auto& P = src.positions;
+ std::vector<glm::uvec3> F = src.triangles;
+ std::vector<char> faceAlive(nt, 1);
+ std::vector<std::vector<uint32_t>> vFaces(nv);
+ for (uint32_t f = 0; f < nt; ++f)
+ for (int c = 0; c < 3; ++c) vFaces[F[f][c]].push_back(f);
+
+ // Area-weighted plane quadrics.
+ std::vector<Quadric> Q(nv);
+ std::vector<glm::dvec3> faceN(nt);
+ for (uint32_t f = 0; f < nt; ++f) {
+ glm::dvec3 a = P[F[f].x], b = P[F[f].y], c = P[F[f].z];
+ glm::dvec3 n = glm::cross(b - a, c - a);
+ double len = glm::length(n);
+ if (len <= 0.0) continue;
+ n /= len;
+ faceN[f] = n;
+ Quadric q = Quadric::plane(n, -glm::dot(n, a), len * 0.5);
+ for (int c2 = 0; c2 < 3; ++c2) Q[F[f][c2]] += q;
+ }
+
+ // Boundary edges get strong perpendicular constraint planes.
+ std::unordered_map<uint64_t, std::pair<uint32_t, uint32_t>> edgeUse; // key -> (count, face)
+ edgeUse.reserve(nt * 2);
+ for (uint32_t f = 0; f < nt; ++f) {
+ for (int e = 0; e < 3; ++e) {
+ auto& u = edgeUse[edgeKey(F[f][e], F[f][(e + 1) % 3])];
+ ++u.first;
+ u.second = f;
+ }
+ }
+ for (const auto& [key, use] : edgeUse) {
+ if (use.first != 1) continue;
+ uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ glm::dvec3 pa = P[a], pb = P[b];
+ glm::dvec3 e = pb - pa;
+ glm::dvec3 bn = glm::cross(e, faceN[use.second]);
+ double len = glm::length(bn);
+ if (len <= 0.0) continue;
+ bn /= len;
+ Quadric q = Quadric::plane(bn, -glm::dot(bn, pa), glm::dot(e, e) * 100.0);
+ Q[a] += q;
+ Q[b] += q;
+ }
+
+ std::vector<uint32_t> version(nv, 0);
+ std::vector<char> vAlive(nv, 1);
+ std::priority_queue<Candidate, std::vector<Candidate>, std::greater<>> heap;
+
+ auto pushEdge = [&](uint32_t a, uint32_t b) {
+ Quadric qs = Q[a] + Q[b];
+ heap.push({qs.eval(P[b]), a, b, version[a], version[b]}); // a collapses onto b
+ heap.push({qs.eval(P[a]), b, a, version[b], version[a]}); // b collapses onto a
+ };
+ for (const auto& [key, use] : edgeUse) pushEdge(uint32_t(key >> 32), uint32_t(key & 0xffffffffu));
+ edgeUse.clear();
+
+ std::vector<uint32_t> nbrU, nbrV, shared;
+ auto gatherNeighbors = [&](uint32_t v, std::vector<uint32_t>& out) {
+ out.clear();
+ for (uint32_t f : vFaces[v]) {
+ if (!faceAlive[f]) continue;
+ for (int c = 0; c < 3; ++c)
+ if (F[f][c] != v) out.push_back(F[f][c]);
+ }
+ std::sort(out.begin(), out.end());
+ out.erase(std::unique(out.begin(), out.end()), out.end());
+ };
+
+ size_t liveFaces = nt;
+ while (liveFaces > targetTriangles && !heap.empty()) {
+ const Candidate c = heap.top();
+ heap.pop();
+ const uint32_t u = c.from, v = c.to;
+ if (!vAlive[u] || !vAlive[v] || version[u] != c.fromVersion || version[v] != c.toVersion) continue;
+
+ shared.clear();
+ for (uint32_t f : vFaces[u]) {
+ if (!faceAlive[f]) continue;
+ if (F[f].x == v || F[f].y == v || F[f].z == v) shared.push_back(f);
+ }
+ if (shared.empty()) continue; // no longer an edge
+
+ // Link condition: the edge's endpoints may share only the vertices
+ // opposite the edge, otherwise collapsing makes the mesh non-manifold.
+ gatherNeighbors(u, nbrU);
+ gatherNeighbors(v, nbrV);
+ size_t common = 0;
+ for (size_t i = 0, j = 0; i < nbrU.size() && j < nbrV.size();) {
+ if (nbrU[i] < nbrV[j]) ++i;
+ else if (nbrU[i] > nbrV[j]) ++j;
+ else ++common, ++i, ++j;
+ }
+ if (common != shared.size()) continue;
+
+ // Reject collapses that flip or degenerate surrounding triangles.
+ bool ok = true;
+ for (uint32_t f : vFaces[u]) {
+ if (!faceAlive[f] || std::find(shared.begin(), shared.end(), f) != shared.end()) continue;
+ glm::uvec3 t = F[f];
+ glm::vec3 before = glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x]);
+ for (int k = 0; k < 3; ++k)
+ if (t[k] == u) t[k] = v;
+ glm::vec3 after = glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x]);
+ float la = glm::length(after), lb = glm::length(before);
+ if (la <= 1e-12f || (lb > 0.0f && glm::dot(after, before) < 0.2f * la * lb)) {
+ ok = false;
+ break;
+ }
+ }
+ if (!ok) continue;
+
+ for (uint32_t f : shared) {
+ faceAlive[f] = 0;
+ --liveFaces;
+ }
+ for (uint32_t f : vFaces[u]) {
+ if (!faceAlive[f]) continue;
+ for (int k = 0; k < 3; ++k)
+ if (F[f][k] == u) F[f][k] = v;
+ vFaces[v].push_back(f);
+ }
+ vFaces[u].clear();
+ vAlive[u] = 0;
+ Q[v] += Q[u];
+ ++version[v];
+ std::erase_if(vFaces[v], [&](uint32_t f) { return !faceAlive[f]; });
+
+ gatherNeighbors(v, nbrV);
+ for (uint32_t w : nbrV) pushEdge(v, w);
+ }
+
+ // Compact into a new mesh, carrying every per-vertex array across.
+ constexpr uint32_t kUnused = ~0u;
+ std::vector<uint32_t> remap(nv, kUnused);
+ std::vector<uint32_t> kept;
+ Mesh out;
+ out.triangles.reserve(liveFaces);
+ for (uint32_t f = 0; f < nt; ++f) {
+ if (!faceAlive[f]) continue;
+ glm::uvec3 t;
+ for (int k = 0; k < 3; ++k) {
+ uint32_t& r = remap[F[f][k]];
+ if (r == kUnused) {
+ r = static_cast<uint32_t>(kept.size());
+ kept.push_back(F[f][k]);
+ }
+ t[k] = r;
+ }
+ out.triangles.push_back(t);
+ }
+ out.positions.reserve(kept.size());
+ for (uint32_t v : kept) out.positions.push_back(src.positions[v]);
+ if (!src.layers.empty()) {
+ for (uint32_t v : kept) out.base.push_back(src.base[v]);
+ for (const auto& l : src.layers) {
+ SculptLayer nl{l.name, {}, l.weight};
+ nl.delta.reserve(kept.size());
+ for (uint32_t v : kept) nl.delta.push_back(l.delta[v]);
+ out.layers.push_back(std::move(nl));
+ }
+ }
+ out.rebuildTopology();
+ out.recomputeAllNormals();
+ return out;
+}
+
+std::vector<Mesh> generateLods(const Mesh& src, int levels, float ratio) {
+ std::vector<Mesh> lods;
+ levels = std::max(levels, 1);
+ ratio = std::clamp(ratio, 0.01f, 0.99f);
+ lods.push_back(src);
+ for (int i = 1; i < levels; ++i) {
+ size_t target = static_cast<size_t>(std::llround(double(lods.back().triangleCount()) * ratio));
+ lods.push_back(decimate(lods.back(), target));
+ }
+ return lods;
+}
+
+} // namespace sf
diff --git a/src/core/Decimate.h b/src/core/Decimate.h
new file mode 100644
index 00000000..a0ea8e7c
--- /dev/null
+++ b/src/core/Decimate.h
@@ -0,0 +1,21 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <vector>
+
+namespace sf {
+
+// Quadric-error-metric edge-collapse decimation (Garland & Heckbert), with
+// boundary preservation, normal-flip and manifold (link condition) checks.
+// Collapses keep one endpoint, so output vertices are a subset of the input's
+// and sculpt layers / blend shapes carry over exactly.
+Mesh decimate(const Mesh& src, size_t targetTriangles);
+
+// LOD chain: lods[0] is a copy of `src`, each following level has
+// `ratio` times the triangles of the previous one.
+std::vector<Mesh> generateLods(const Mesh& src, int levels, float ratio);
+
+} // namespace sf
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
new file mode 100644
index 00000000..02feb890
--- /dev/null
+++ b/src/core/Document.cpp
@@ -0,0 +1,51 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Document.h"
+
+#include <filesystem>
+#include <memory>
+
+namespace sf {
+
+void Document::setMesh(Mesh m) {
+ mesh = std::move(m);
+ mesh.topologyDirty = true;
+ bvh.build(mesh);
+ undo.clear();
+ modified = false;
+ activeLayer = -1;
+ bvhDirty = false;
+}
+
+int Document::addBrush(BrushRecipe recipe) {
+ recipe.clamp();
+ for (size_t i = 0; i < brushes.size(); ++i) {
+ if (brushes[i].name == recipe.name) {
+ brushes[i] = std::move(recipe);
+ return int(i);
+ }
+ }
+ brushes.push_back(std::move(recipe));
+ return int(brushes.size()) - 1;
+}
+
+std::string Document::assetName() const {
+ if (path.empty()) return "Sculpt";
+ auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ return std::string(stem.begin(), stem.end());
+}
+
+void Document::replaceMeshUndoable(Mesh m, std::string label) {
+ UndoRecord r;
+ r.label = std::move(label);
+ r.mesh = std::make_unique<Mesh>(std::move(mesh));
+ mesh = std::move(m);
+ mesh.topologyDirty = true;
+ bvh.build(mesh);
+ bvhDirty = false;
+ undo.push(std::move(r));
+ modified = true;
+ if (activeLayer >= static_cast<int>(mesh.layers.size())) activeLayer = -1;
+}
+
+} // namespace sf
diff --git a/src/core/Document.h b/src/core/Document.h
new file mode 100644
index 00000000..1920f1a7
--- /dev/null
+++ b/src/core/Document.h
@@ -0,0 +1,52 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/BVH.h"
+#include "core/BrushRecipe.h"
+#include "core/Mesh.h"
+#include "core/Sculpt.h"
+#include "core/Splats.h"
+#include "core/Undo.h"
+
+#include <string>
+
+namespace sf {
+
+// Everything that makes up the open scene: the mesh, its acceleration
+// structure and edit history. UI-independent so it can be driven by tests,
+// scripts or an AI assistant through the command registry.
+struct Document {
+ Mesh mesh;
+ BVH bvh;
+ UndoStack undo;
+ Sculptor sculptor;
+ std::string path; // empty until saved/loaded
+ bool modified = false;
+ int activeLayer = -1; // sculpt layer strokes write into (-1 = base)
+ // Recipe brush library (built-ins, loaded .sfbrush files, AI-made brushes).
+ std::vector<BrushRecipe> brushes = builtinBrushRecipes();
+ int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush type
+ // Adds or replaces (by name) a recipe and returns its index.
+ int addBrush(BrushRecipe recipe);
+ // Gaussian splats shown alongside the mesh (a capture used as reference or
+ // source, or the sculpt converted for splat viewers). Not part of undo.
+ SplatCloud splats;
+ uint64_t splatsVersion = 0; // bump after editing `splats` so views re-upload
+ void splatsChanged() { ++splatsVersion; }
+ bool bvhDirty = false; // set after whole-mesh deformations (e.g. layer weights)
+
+ void syncBvh() {
+ if (bvhDirty) bvh.build(mesh);
+ bvhDirty = false;
+ }
+ // Asset name derived from the document path (for exports).
+ std::string assetName() const;
+
+ // Replaces the mesh and clears the edit history.
+ void setMesh(Mesh m);
+ // Replaces the mesh as an undoable topology change.
+ void replaceMeshUndoable(Mesh m, std::string label);
+};
+
+} // namespace sf
diff --git a/src/core/EnginePresets.cpp b/src/core/EnginePresets.cpp
new file mode 100644
index 00000000..3ebaffd5
--- /dev/null
+++ b/src/core/EnginePresets.cpp
@@ -0,0 +1,59 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/EnginePresets.h"
+
+#include "core/Decimate.h"
+#include "io/FbxIO.h"
+
+#include <algorithm>
+#include <cctype>
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+// Unreal asset names: letters, digits and underscores.
+std::string unrealName(const std::string& text) {
+ std::string out;
+ for (unsigned char c : text) out += std::isalnum(c) ? char(c) : '_';
+ return out.empty() ? std::string("Sculpt") : out;
+}
+
+} // namespace
+
+bool exportForUnreal(const Document& doc, const UnrealExportOptions& o, UnrealExportResult& r, std::string& error) {
+ const Mesh& mesh = doc.mesh;
+ if (mesh.triangleCount() == 0) {
+ error = "The mesh is empty";
+ return false;
+ }
+ // Morph targets only exist on skeletal meshes in Unreal; a skeletal mesh can't use an FBX LOD group
+ // the same way, so layered sculpts export LOD0 only.
+ r.skeletal = !mesh.layers.empty();
+ r.assetName = !o.assetName.empty() ? unrealName(o.assetName) : (r.skeletal ? "SK_" : "SM_") + unrealName(doc.assetName());
+ const float height = mesh.bounds().extent().y;
+ r.scale = o.heightCm > 0.0f && height > 0.0f ? o.heightCm / height : 100.0f;
+
+ std::vector<Mesh> lods;
+ std::vector<const Mesh*> levels = {&mesh};
+ if (!r.skeletal && o.lods > 1) {
+ lods = generateLods(mesh, std::clamp(o.lods, 2, 8), std::clamp(o.ratio, 0.1f, 0.9f));
+ levels.clear();
+ for (const auto& l : lods) levels.push_back(&l);
+ }
+ r.lodCount = int(levels.size());
+
+ std::filesystem::path folder(std::u8string(o.folder.begin(), o.folder.end()));
+ if (folder.empty()) folder = std::filesystem::temp_directory_path();
+ std::error_code ec;
+ std::filesystem::create_directories(folder, ec);
+ const auto file = (folder / std::u8string(reinterpret_cast<const char8_t*>(r.assetName.data()), r.assetName.size())).u8string() + u8".fbx";
+ r.path.assign(file.begin(), file.end());
+
+ FbxExportOptions fo;
+ fo.scale = r.scale;
+ return saveFbx(r.path, r.assetName, levels, fo, error);
+}
+
+} // namespace sf
diff --git a/src/core/EnginePresets.h b/src/core/EnginePresets.h
new file mode 100644
index 00000000..14eb6071
--- /dev/null
+++ b/src/core/EnginePresets.h
@@ -0,0 +1,35 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// One-click export presets for game engines: sizes, units, naming and LOD
+// packaging set the way each engine's importer expects.
+#pragma once
+
+#include "core/Document.h"
+
+#include <string>
+
+namespace sf {
+
+struct UnrealExportOptions {
+ std::string folder; // where to write; the file name is chosen by the preset
+ float heightCm = 0.0f; // model height in Unreal (cm); 0 = 1 SculptForge unit = 1 m
+ int lods = 4; // LOD0..N-1 in one file (1 = no LOD group)
+ float ratio = 0.5f; // triangle ratio between LODs
+ std::string assetName; // empty = SM_/SK_ + document name
+};
+
+struct UnrealExportResult {
+ std::string path; // the written .fbx
+ std::string assetName; // SM_Name, or SK_Name when the sculpt has layers (morph targets)
+ bool skeletal = false; // Unreal needs a skeletal mesh for morph targets
+ int lodCount = 1;
+ float scale = 1.0f; // SculptForge units -> cm
+};
+
+// Unreal: FBX in centimetres, SM_/SK_ prefix, LODs as an FBX LOD group (static
+// meshes), sculpt layers as blend shapes (skeletal meshes; Unreal adds a root bone).
+bool exportForUnreal(const Document& doc, const UnrealExportOptions& options, UnrealExportResult& result,
+ std::string& error);
+
+} // namespace sf
diff --git a/src/core/Image.cpp b/src/core/Image.cpp
new file mode 100644
index 00000000..1b57bdab
--- /dev/null
+++ b/src/core/Image.cpp
@@ -0,0 +1,177 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Image.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+#define STB_IMAGE_IMPLEMENTATION
+#define STBI_NO_STDIO
+#define STBI_FAILURE_USERMSG
+#if defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
+#pragma GCC diagnostic ignored "-Wsign-compare"
+#pragma GCC diagnostic ignored "-Wunused-function"
+#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
+#endif
+#include "stb_image.h"
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#define STBI_WRITE_NO_STDIO
+#include "stb_image_write.h"
+#if defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
+namespace sf {
+
+float Image::sampleChannel(float u, float v, int channel) const {
+ if (empty()) return 0.0f;
+ float x = std::clamp(u, 0.0f, 1.0f) * float(width - 1);
+ float y = std::clamp(v, 0.0f, 1.0f) * float(height - 1);
+ int x0 = int(x), y0 = int(y);
+ int x1 = std::min(x0 + 1, width - 1), y1 = std::min(y0 + 1, height - 1);
+ float fx = x - float(x0), fy = y - float(y0);
+ auto at = [&](int xi, int yi) { return float(rgba[(size_t(yi) * size_t(width) + size_t(xi)) * 4 + size_t(channel)]); };
+ float top = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * fx;
+ float bottom = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * fx;
+ return (top + (bottom - top) * fy) / 255.0f;
+}
+
+float Image::luminance(float u, float v) const {
+ return 0.2126f * sampleChannel(u, v, 0) + 0.7152f * sampleChannel(u, v, 1) + 0.0722f * sampleChannel(u, v, 2);
+}
+
+float Image::alpha(float u, float v) const { return sampleChannel(u, v, 3); }
+
+bool Image::hasTransparency() const {
+ for (size_t i = 3; i < rgba.size(); i += 4)
+ if (rgba[i] < 128) return true;
+ return false;
+}
+
+bool Image::encodePng(std::vector<uint8_t>& out) const {
+ out.clear();
+ if (empty()) return false;
+ auto write = [](void* ctx, void* data, int size) {
+ auto* o = static_cast<std::vector<uint8_t>*>(ctx);
+ o->insert(o->end(), static_cast<uint8_t*>(data), static_cast<uint8_t*>(data) + size);
+ };
+ return stbi_write_png_to_func(write, &out, width, height, 4, rgba.data(), width * 4) != 0;
+}
+
+bool Image::savePng(const std::string& path, std::string& error) const {
+ if (empty()) {
+ error = "Empty image";
+ return false;
+ }
+ std::vector<uint8_t> png;
+ if (!encodePng(png)) {
+ error = "PNG encoding failed";
+ return false;
+ }
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f.write(reinterpret_cast<const char*>(png.data()), std::streamsize(png.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+Image Image::downscaled(int maxSide) const {
+ if (empty() || std::max(width, height) <= maxSide) return *this;
+ const float f = float(std::max(width, height)) / float(maxSide);
+ Image out;
+ out.width = std::max(1, int(float(width) / f));
+ out.height = std::max(1, int(float(height) / f));
+ out.rgba.resize(size_t(out.width) * size_t(out.height) * 4);
+ for (int y = 0; y < out.height; ++y)
+ for (int x = 0; x < out.width; ++x) {
+ const int x0 = int(float(x) * f), x1 = std::max(x0 + 1, std::min(width, int(float(x + 1) * f)));
+ const int y0 = int(float(y) * f), y1 = std::max(y0 + 1, std::min(height, int(float(y + 1) * f)));
+ // Alpha-weighted average so transparent pixels don't darken the edges.
+ float sum[4] = {0, 0, 0, 0};
+ for (int sy = y0; sy < y1; ++sy)
+ for (int sx = x0; sx < x1; ++sx) {
+ const uint8_t* p = &rgba[(size_t(sy) * size_t(width) + size_t(sx)) * 4];
+ const float a = float(p[3]);
+ for (int c = 0; c < 3; ++c) sum[c] += float(p[c]) * a;
+ sum[3] += a;
+ }
+ const float n = float((x1 - x0) * (y1 - y0));
+ uint8_t* o = &out.rgba[(size_t(y) * size_t(out.width) + size_t(x)) * 4];
+ for (int c = 0; c < 3; ++c) o[c] = uint8_t(sum[3] > 0.0f ? sum[c] / sum[3] + 0.5f : 0.0f);
+ o[3] = uint8_t(sum[3] / n + 0.5f);
+ }
+ return out;
+}
+
+Image Image::framedSubject(float margin) const {
+ if (!hasTransparency()) return *this;
+ int x0 = width, y0 = height, x1 = -1, y1 = -1;
+ for (int y = 0; y < height; ++y)
+ for (int x = 0; x < width; ++x)
+ if (rgba[(size_t(y) * size_t(width) + size_t(x)) * 4 + 3] > 8) {
+ x0 = std::min(x0, x);
+ y0 = std::min(y0, y);
+ x1 = std::max(x1, x);
+ y1 = std::max(y1, y);
+ }
+ if (x1 < 0) return *this;
+ const int w = x1 - x0 + 1, h = y1 - y0 + 1;
+ const int side = int(float(std::max(w, h)) * (1.0f + 2.0f * margin)) + 1;
+ Image out;
+ out.width = out.height = side;
+ out.rgba.assign(size_t(side) * size_t(side) * 4, 0);
+ const int ox = (side - w) / 2, oy = (side - h) / 2;
+ for (int y = 0; y < h; ++y)
+ std::copy_n(&rgba[(size_t(y0 + y) * size_t(width) + size_t(x0)) * 4], size_t(w) * 4,
+ &out.rgba[(size_t(oy + y) * size_t(side) + size_t(ox)) * 4]);
+ return out;
+}
+
+bool Image::isImagePath(const std::string& path) {
+ std::string ext = std::filesystem::path(std::u8string(path.begin(), path.end())).extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".tga" || ext == ".psd" ||
+ ext == ".gif" || ext == ".hdr";
+}
+
+bool Image::load(const std::string& path, Image& out, std::string& error) {
+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<unsigned char> bytes((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ if (bytes.empty() || bytes.size() > size_t(1) << 30) {
+ error = "Unsupported image size: " + path;
+ return false;
+ }
+ return decode(bytes.data(), bytes.size(), out, error);
+}
+
+bool Image::decode(const unsigned char* bytes, size_t size, Image& out, std::string& error) {
+ int w = 0, h = 0, channels = 0;
+ unsigned char* data = stbi_load_from_memory(bytes, int(size), &w, &h, &channels, 4);
+ if (!data) {
+ error = std::string("Cannot decode image: ") + stbi_failure_reason();
+ return false;
+ }
+ if (size_t(w) * size_t(h) > size_t(16384) * 16384) {
+ stbi_image_free(data);
+ error = "Image is too large";
+ return false;
+ }
+ out.width = w;
+ out.height = h;
+ out.rgba.assign(data, data + size_t(w) * size_t(h) * 4);
+ stbi_image_free(data);
+ return true;
+}
+
+} // namespace sf
diff --git a/src/core/Image.h b/src/core/Image.h
new file mode 100644
index 00000000..cc8b28d9
--- /dev/null
+++ b/src/core/Image.h
@@ -0,0 +1,38 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+// 8-bit RGBA image with float helpers for sculpting (PNG, JPEG, BMP, TGA, PSD, GIF, HDR via stb_image).
+struct Image {
+ int width = 0, height = 0;
+ std::vector<uint8_t> rgba;
+
+ bool empty() const { return width <= 0 || height <= 0; }
+ float aspect() const { return height > 0 ? float(width) / float(height) : 1.0f; }
+ // Luminance and alpha in 0..1 with bilinear filtering; u, v in 0..1 (v = 0 at the top), clamped.
+ float luminance(float u, float v) const;
+ float alpha(float u, float v) const;
+ bool hasTransparency() const;
+
+ static bool load(const std::string& path, Image& out, std::string& error);
+ static bool decode(const unsigned char* bytes, size_t size, Image& out, std::string& error);
+ bool savePng(const std::string& path, std::string& error) const;
+ bool encodePng(std::vector<uint8_t>& out) const;
+ // Box-filtered copy whose longer side is at most `maxSide` (unchanged if already smaller).
+ Image downscaled(int maxSide) const;
+ // Crops to the opaque subject plus `margin` (fraction of its size) and centres
+ // it on a transparent square canvas. Unchanged if there is no transparency.
+ Image framedSubject(float margin) const;
+ static bool isImagePath(const std::string& path);
+
+private:
+ float sampleChannel(float u, float v, int channel) const;
+};
+
+} // namespace sf
diff --git a/src/core/ImageTo3D.cpp b/src/core/ImageTo3D.cpp
new file mode 100644
index 00000000..131056e4
--- /dev/null
+++ b/src/core/ImageTo3D.cpp
@@ -0,0 +1,365 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/ImageTo3D.h"
+
+#include "core/Primitives.h"
+
+#include <algorithm>
+#include <cmath>
+#include <unordered_map>
+
+namespace sf {
+
+namespace {
+
+float heightAt(const Image& img, float u, float v, bool invert) {
+ float h = img.luminance(u, v);
+ if (invert) h = 1.0f - h;
+ return h * img.alpha(u, v);
+}
+
+} // namespace
+
+Mesh makeImageRelief(const Image& image, const ReliefOptions& o) {
+ Mesh m;
+ if (image.empty()) return m;
+ const int res = std::clamp(o.resolution, 8, 2048);
+ const float aspect = image.aspect();
+ const int nx = aspect >= 1.0f ? res : std::max(2, int(std::lround(res * aspect)));
+ const int ny = aspect >= 1.0f ? std::max(2, int(std::lround(res / aspect))) : res;
+ const float width = 2.0f, height = 2.0f / aspect;
+ const float depth = o.depth * width;
+
+ m.positions.reserve(size_t(nx + 1) * size_t(ny + 1));
+ for (int j = 0; j <= ny; ++j) {
+ for (int i = 0; i <= nx; ++i) {
+ float u = float(i) / float(nx), v = float(j) / float(ny);
+ m.positions.emplace_back((u - 0.5f) * width, (0.5f - v) * height, heightAt(image, u, v, o.invert) * depth);
+ }
+ }
+ for (int j = 0; j < ny; ++j) {
+ for (int i = 0; i < nx; ++i) {
+ uint32_t a = uint32_t(j * (nx + 1) + i), b = a + 1, c = a + uint32_t(nx + 1), d = c + 1;
+ m.triangles.push_back({a, c, b});
+ m.triangles.push_back({b, c, d});
+ }
+ }
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ return m;
+}
+
+size_t projectImage(Mesh& mesh, int layer, const Image& image, const glm::mat4& viewProj, float viewAspect,
+ const glm::vec3& cameraPos, const ProjectOptions& o) {
+ if (image.empty() || mesh.vertexCount() == 0) return 0;
+ // Fit the image inside the view ("contain"), scaled by coverage.
+ const float ia = image.aspect();
+ float sx = 1.0f, sy = 1.0f;
+ if (ia > viewAspect) sy = viewAspect / ia;
+ else sx = ia / viewAspect;
+ sx *= o.coverage;
+ sy *= o.coverage;
+
+ auto& target = mesh.layerTarget(layer);
+ const float invWeight = 1.0f / mesh.layerTargetWeight(layer);
+ const bool layered = !mesh.layers.empty();
+ std::vector<uint32_t> moved;
+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {
+ const glm::vec3 p = mesh.positions[v];
+ glm::vec4 clip = viewProj * glm::vec4(p, 1.0f);
+ if (clip.w <= 0.0f) continue;
+ glm::vec2 ndc = glm::vec2(clip) / clip.w;
+ float u = (ndc.x / sx + 1.0f) * 0.5f;
+ float t = 1.0f - (ndc.y / sy + 1.0f) * 0.5f;
+ if (u < 0.0f || u > 1.0f || t < 0.0f || t > 1.0f) continue;
+ float facing = glm::dot(mesh.normals[v], glm::normalize(cameraPos - p));
+ float f = std::clamp((facing - 0.05f) / 0.25f, 0.0f, 1.0f); // fade at grazing angles
+ float h = heightAt(image, u, t, o.invert) * f;
+ if (h <= 0.0f) continue;
+ glm::vec3 d = mesh.normals[v] * (o.depth * h);
+ mesh.positions[v] += d;
+ if (layered) target[v] += d * invWeight;
+ moved.push_back(v);
+ }
+ mesh.updateNormals(moved);
+ return moved.size();
+}
+
+Mesh inflateSilhouette(const Image& image, const InflateOptions& o, std::string* error) {
+ auto fail = [&](const char* msg) {
+ if (error) *error = msg;
+ return Mesh{};
+ };
+ if (image.empty()) return fail("No image");
+
+ const int res = std::clamp(o.resolution, 16, 512);
+ const float aspect = image.aspect();
+ const int gw = aspect >= 1.0f ? res : std::max(4, int(std::lround(res * aspect)));
+ const int gh = aspect >= 1.0f ? std::max(4, int(std::lround(res / aspect))) : res;
+ // Grid with a one-cell empty border so every shape has an outside.
+ const int W = gw + 2, H = gh + 2;
+ auto idx = [W](int x, int y) { return size_t(y) * size_t(W) + size_t(x); };
+
+ // 1. Mask: opaque pixels, or pixels that differ from the border colour.
+ std::vector<uint8_t> inside(size_t(W) * size_t(H), 0);
+ const bool useAlpha = image.hasTransparency();
+ float border = 0.0f;
+ if (!useAlpha) {
+ int n = 0;
+ for (int k = 0; k < 64; ++k) {
+ float s = float(k) / 63.0f;
+ border += image.luminance(s, 0.0f) + image.luminance(s, 1.0f) + image.luminance(0.0f, s) +
+ image.luminance(1.0f, s);
+ n += 4;
+ }
+ border /= float(n);
+ }
+ for (int y = 0; y < gh; ++y) {
+ for (int x = 0; x < gw; ++x) {
+ float u = (float(x) + 0.5f) / float(gw), v = (float(y) + 0.5f) / float(gh);
+ bool in = useAlpha ? image.alpha(u, v) > 0.5f : std::abs(image.luminance(u, v) - border) > 0.2f;
+ inside[idx(x + 1, y + 1)] = in;
+ }
+ }
+
+ // 2. Drop specks: keep connected components at least 5% the size of the largest.
+ std::vector<int> label(inside.size(), -1);
+ std::vector<size_t> sizes;
+ std::vector<size_t> stack;
+ for (size_t start = 0; start < inside.size(); ++start) {
+ if (!inside[start] || label[start] >= 0) continue;
+ int l = int(sizes.size());
+ size_t count = 0;
+ stack.assign(1, start);
+ label[start] = l;
+ while (!stack.empty()) {
+ size_t c = stack.back();
+ stack.pop_back();
+ ++count;
+ int cx = int(c % size_t(W)), cy = int(c / size_t(W));
+ const int nx[4] = {cx + 1, cx - 1, cx, cx}, ny[4] = {cy, cy, cy + 1, cy - 1};
+ for (int k = 0; k < 4; ++k) {
+ size_t n = idx(nx[k], ny[k]);
+ if (inside[n] && label[n] < 0) {
+ label[n] = l;
+ stack.push_back(n);
+ }
+ }
+ }
+ sizes.push_back(count);
+ }
+ if (sizes.empty()) return fail("No shape found - use an image with a transparent background or a plain backdrop");
+ const size_t largest = *std::max_element(sizes.begin(), sizes.end());
+ for (size_t c = 0; c < inside.size(); ++c)
+ if (inside[c] && sizes[size_t(label[c])] < std::max<size_t>(4, largest / 20)) inside[c] = 0;
+
+ // 3. Quads between four inside cells form the sheet. Iteratively remove
+ // quads that would make the closed surface degenerate: quads whose four
+ // corners are all on the rim (front and back would coincide) and
+ // "bow-tie" corners where two quads touch only diagonally.
+ std::vector<uint8_t> quad(inside.size(), 0); // quad anchored at its top-left cell
+ for (int y = 1; y < H - 2; ++y)
+ for (int x = 1; x < W - 2; ++x)
+ quad[idx(x, y)] = inside[idx(x, y)] && inside[idx(x + 1, y)] && inside[idx(x, y + 1)] &&
+ inside[idx(x + 1, y + 1)];
+ auto q = [&](int x, int y) { return x >= 0 && y >= 0 && x < W && y < H && quad[idx(x, y)]; };
+ auto incident = [&](int x, int y) { return int(q(x - 1, y - 1)) + q(x, y - 1) + q(x - 1, y) + q(x, y); };
+ std::vector<uint8_t> rim(inside.size(), 0);
+ for (bool changed = true; changed;) {
+ changed = false;
+ for (int y = 1; y < H - 1; ++y)
+ for (int x = 1; x < W - 1; ++x) {
+ // Bow-tie: only the two diagonal quads around this corner exist.
+ bool d1 = q(x - 1, y - 1) && q(x, y) && !q(x, y - 1) && !q(x - 1, y);
+ bool d2 = q(x, y - 1) && q(x - 1, y) && !q(x - 1, y - 1) && !q(x, y);
+ if (d1) { quad[idx(x, y)] = 0; changed = true; }
+ if (d2) { quad[idx(x - 1, y)] = 0; changed = true; }
+ }
+ for (int y = 1; y < H - 1; ++y)
+ for (int x = 1; x < W - 1; ++x) {
+ int n = incident(x, y);
+ rim[idx(x, y)] = n > 0 && n < 4;
+ }
+ for (int y = 1; y < H - 2; ++y)
+ for (int x = 1; x < W - 2; ++x)
+ if (quad[idx(x, y)] && rim[idx(x, y)] && rim[idx(x + 1, y)] && rim[idx(x, y + 1)] &&
+ rim[idx(x + 1, y + 1)]) {
+ quad[idx(x, y)] = 0;
+ changed = true;
+ }
+ }
+
+ // 4. Distance from each sheet vertex to the rim.
+ std::vector<glm::vec2> contour;
+ for (int y = 1; y < H - 1; ++y)
+ for (int x = 1; x < W - 1; ++x)
+ if (rim[idx(x, y)]) contour.emplace_back(float(x), float(y));
+ std::vector<float> dist(inside.size(), 0.0f);
+ float maxDist = 0.0f;
+ for (int y = 1; y < H - 1; ++y) {
+ for (int x = 1; x < W - 1; ++x) {
+ if (rim[idx(x, y)] || incident(x, y) == 0) continue;
+ float best = 1e30f;
+ for (const auto& c : contour) {
+ float dx = c.x - float(x), dy = c.y - float(y);
+ best = std::min(best, dx * dx + dy * dy);
+ }
+ dist[idx(x, y)] = std::sqrt(best);
+ maxDist = std::max(maxDist, dist[idx(x, y)]);
+ }
+ }
+ if (maxDist <= 0.0f) return fail("The shape is too thin to inflate - try a bolder silhouette");
+
+ // 4b. Heights from a circular profile, then relaxed so the creases along
+ // the shape's medial axis round off (rim stays pinned at zero).
+ auto profile = [&](float d) { return std::sqrt(std::max(0.0f, 2.0f * maxDist * d - d * d)); };
+ std::vector<float> height(inside.size(), 0.0f);
+ for (size_t c = 0; c < inside.size(); ++c) height[c] = dist[c] > 0.0f ? profile(dist[c]) : 0.0f;
+ {
+ std::vector<float> next = height;
+ const int iterations = std::max(4, int(maxDist * 0.6f));
+ for (int it = 0; it < iterations; ++it) {
+ for (int y = 1; y < H - 1; ++y)
+ for (int x = 1; x < W - 1; ++x) {
+ size_t c = idx(x, y);
+ if (dist[c] <= 0.0f) continue;
+ float sum = 0.0f;
+ int n = 0;
+ const int nx[4] = {x + 1, x - 1, x, x}, ny[4] = {y, y, y + 1, y - 1};
+ for (int k = 0; k < 4; ++k) {
+ size_t nc = idx(nx[k], ny[k]);
+ if (dist[nc] > 0.0f || rim[nc]) {
+ sum += height[nc];
+ ++n;
+ }
+ }
+ // Blend toward the neighbour average but never below the
+ // profile's rounded rim, so edges keep their fullness.
+ if (n) next[c] = std::max(0.5f * height[c] + 0.5f * sum / float(n), profile(std::min(dist[c], 2.0f)));
+ }
+ height.swap(next);
+ }
+ }
+
+ // 5. Front sheet over the quads. A circular cross-section profile gives
+ // a rounded, "balloon" body: h = sqrt(2Rd - d^2).
+ struct SheetVertex {
+ glm::vec2 xy; // grid units
+ float h;
+ bool rim;
+ float d = 0.0f; // distance to the rim in cells
+ };
+ std::vector<SheetVertex> sheet;
+ std::vector<glm::uvec3> tris;
+ constexpr uint32_t kNone = ~0u;
+ std::vector<uint32_t> slot(inside.size(), kNone);
+ auto vertexFor = [&](int x, int y) {
+ size_t c = idx(x, y);
+ if (slot[c] == kNone) {
+ slot[c] = uint32_t(sheet.size());
+ sheet.push_back({glm::vec2(float(x), float(y)), rim[c] ? 0.0f : height[c], rim[c] != 0, dist[c]});
+ }
+ return slot[c];
+ };
+ for (int y = 1; y < H - 2; ++y) {
+ for (int x = 1; x < W - 2; ++x) {
+ if (!quad[idx(x, y)]) continue;
+ uint32_t a = vertexFor(x, y), b = vertexFor(x + 1, y), c = vertexFor(x, y + 1), d = vertexFor(x + 1, y + 1);
+ tris.push_back({a, c, b});
+ tris.push_back({b, c, d});
+ }
+ }
+ if (tris.empty()) return fail("The shape is too thin to inflate - try a bolder silhouette");
+
+ // 6. Split "chords": interior edges whose ends are both on the rim. Front
+ // and back would otherwise share them and pinch the surface.
+ {
+ std::unordered_map<uint64_t, int> edgeUse;
+ auto key = [](uint32_t a, uint32_t b) { return a < b ? (uint64_t(a) << 32 | b) : (uint64_t(b) << 32 | a); };
+ for (const auto& t : tris)
+ for (int k = 0; k < 3; ++k) ++edgeUse[key(t[k], t[(k + 1) % 3])];
+ std::vector<std::pair<uint32_t, uint32_t>> chords;
+ for (const auto& [k, n] : edgeUse) {
+ uint32_t a = uint32_t(k >> 32), b = uint32_t(k & 0xffffffffu);
+ if (n == 2 && sheet[a].rim && sheet[b].rim) chords.emplace_back(a, b);
+ }
+ for (const auto& [a, b] : chords) {
+ const uint32_t mid = uint32_t(sheet.size());
+ sheet.push_back({(sheet[a].xy + sheet[b].xy) * 0.5f, profile(0.5f), false, 0.5f});
+ const size_t count = tris.size();
+ for (size_t i = 0; i < count; ++i) {
+ glm::uvec3 t = tris[i];
+ for (int k = 0; k < 3; ++k) {
+ uint32_t p = t[k], qv = t[(k + 1) % 3], o = t[(k + 2) % 3];
+ if ((p == a && qv == b) || (p == b && qv == a)) {
+ tris[i] = {p, mid, o};
+ tris.push_back({mid, qv, o});
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // 7. Mirror into a back sheet that shares the rim, giving a closed surface.
+ const float cell = 2.0f / float(std::max(gw, gh));
+ Mesh m;
+ std::vector<uint32_t> backIndex(sheet.size());
+ for (const auto& v : sheet)
+ m.positions.emplace_back((v.xy.x - float(W) * 0.5f) * cell, (float(H) * 0.5f - v.xy.y) * cell,
+ v.h * cell * o.thickness);
+ for (uint32_t i = 0; i < sheet.size(); ++i) {
+ if (sheet[i].rim) {
+ backIndex[i] = i;
+ } else {
+ backIndex[i] = uint32_t(m.positions.size());
+ glm::vec3 p = m.positions[i];
+ m.positions.emplace_back(p.x, p.y, -p.z);
+ }
+ }
+ for (const auto& t : tris) {
+ m.triangles.push_back(t);
+ m.triangles.push_back({backIndex[t.x], backIndex[t.z], backIndex[t.y]});
+ }
+
+ m.rebuildTopology();
+ {
+ // Rim and near-rim flags per mesh vertex (back copies share the front's flags).
+ std::vector<uint8_t> isRim(m.vertexCount(), 0), nearRim(m.vertexCount(), 0);
+ for (uint32_t i = 0; i < sheet.size(); ++i) {
+ isRim[i] = sheet[i].rim;
+ nearRim[i] = nearRim[backIndex[i]] = !sheet[i].rim && sheet[i].d <= 4.0f;
+ }
+ // Straighten the pixel-stepped outline along itself.
+ std::vector<glm::vec3> next = m.positions;
+ for (int it = 0; it < 12; ++it) {
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ if (!isRim[v]) continue;
+ glm::vec3 sum(0.0f);
+ int n = 0;
+ for (uint32_t u : m.neighbors(v))
+ if (isRim[u]) sum += m.positions[u], ++n;
+ if (n >= 2) next[v] = glm::mix(m.positions[v], sum / float(n), 0.5f);
+ }
+ m.positions = next;
+ }
+ // Even out the steep band around the rim, rim included, so the seam rounds off.
+ for (int it = 0; it < 20; ++it) {
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ if (!nearRim[v] && !(isRim[v] && it % 2)) continue;
+ glm::vec3 sum(0.0f);
+ auto ring = m.neighbors(v);
+ for (uint32_t u : ring) sum += m.positions[u];
+ next[v] = glm::mix(m.positions[v], sum / float(ring.size()), 0.5f);
+ }
+ m.positions = next;
+ }
+ }
+ taubinSmooth(m, 12);
+ for (int i = 0; i < std::clamp(o.subdivisions, 0, 3); ++i) m = loopSubdivide(m);
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ return m;
+}
+
+} // namespace sf
diff --git a/src/core/ImageTo3D.h b/src/core/ImageTo3D.h
new file mode 100644
index 00000000..e84bf78d
--- /dev/null
+++ b/src/core/ImageTo3D.h
@@ -0,0 +1,46 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Turning pictures into geometry, entirely locally:
+// - relief: an image becomes a height-mapped surface (emblems, coins, height maps, textures)
+// - project: an image is stamped onto the current model from a view (like a stencil)
+// - inflate: a sketch's silhouette is inflated into a closed, puffy 3D base mesh
+// Full photo-to-3D reconstruction is delegated to external generators (see ai/Generator3D.h).
+#pragma once
+
+#include "core/Image.h"
+#include "core/Mesh.h"
+
+#include <glm/glm.hpp>
+
+namespace sf {
+
+struct ReliefOptions {
+ int resolution = 384; // grid cells along the image's long side
+ float depth = 0.12f; // relief height as a fraction of the plane width
+ bool invert = false; // dark = high instead of light = high
+};
+Mesh makeImageRelief(const Image& image, const ReliefOptions& options);
+
+struct ProjectOptions {
+ float depth = 0.05f; // world-space displacement at full brightness
+ bool invert = false;
+ float coverage = 0.9f; // fraction of the view the image fills
+};
+// Displaces vertices along their normals by the image as seen through
+// `viewProj` (image fitted to a view of aspect `viewAspect`). Only surfaces
+// facing the camera are affected. Offsets go into sculpt layer `layer`
+// (-1 = base). Returns the number of vertices moved; normals are updated.
+size_t projectImage(Mesh& mesh, int layer, const Image& image, const glm::mat4& viewProj, float viewAspect,
+ const glm::vec3& cameraPos, const ProjectOptions& options);
+
+struct InflateOptions {
+ int resolution = 160; // grid cells along the long side
+ float thickness = 1.0f; // 1 = round cross-sections, lower = flatter
+ int subdivisions = 1; // Loop subdivision passes for smoothness
+};
+// The shape is the image's opaque area (if it has transparency) or whatever
+// contrasts with the border colour. Returns an empty mesh if no shape is found.
+Mesh inflateSilhouette(const Image& image, const InflateOptions& options, std::string* error = nullptr);
+
+} // namespace sf
diff --git a/src/core/Json.cpp b/src/core/Json.cpp
new file mode 100644
index 00000000..8abff8d5
--- /dev/null
+++ b/src/core/Json.cpp
@@ -0,0 +1,312 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Json.h"
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+
+namespace sf {
+
+namespace {
+
+const Json kNull;
+const std::string kEmpty;
+
+struct Parser {
+ explicit Parser(const std::string& text) : s(text) {}
+ const std::string& s;
+ size_t i = 0;
+ std::string error;
+ int depth = 0;
+
+ void ws() {
+ while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i;
+ }
+ bool fail(const std::string& msg) {
+ if (error.empty()) error = msg + " at offset " + std::to_string(i);
+ return false;
+ }
+ bool literal(const char* lit) {
+ size_t n = std::char_traits<char>::length(lit);
+ if (s.compare(i, n, lit) != 0) return fail("Invalid literal");
+ i += n;
+ return true;
+ }
+ static void appendUtf8(std::string& out, unsigned cp) {
+ if (cp < 0x80) {
+ out += char(cp);
+ } else if (cp < 0x800) {
+ out += char(0xC0 | (cp >> 6));
+ out += char(0x80 | (cp & 0x3F));
+ } else if (cp < 0x10000) {
+ out += char(0xE0 | (cp >> 12));
+ out += char(0x80 | ((cp >> 6) & 0x3F));
+ out += char(0x80 | (cp & 0x3F));
+ } else {
+ out += char(0xF0 | (cp >> 18));
+ out += char(0x80 | ((cp >> 12) & 0x3F));
+ out += char(0x80 | ((cp >> 6) & 0x3F));
+ out += char(0x80 | (cp & 0x3F));
+ }
+ }
+ bool hex4(unsigned& v) {
+ if (i + 4 > s.size()) return fail("Truncated escape");
+ v = 0;
+ for (int k = 0; k < 4; ++k) {
+ char c = s[i++];
+ v <<= 4;
+ if (c >= '0' && c <= '9') v |= unsigned(c - '0');
+ else if (c >= 'a' && c <= 'f') v |= unsigned(c - 'a' + 10);
+ else if (c >= 'A' && c <= 'F') v |= unsigned(c - 'A' + 10);
+ else return fail("Bad hex escape");
+ }
+ return true;
+ }
+ bool string(std::string& out) {
+ ++i; // opening quote
+ while (i < s.size()) {
+ char c = s[i++];
+ if (c == '"') return true;
+ if (c != '\\') {
+ out += c;
+ continue;
+ }
+ if (i >= s.size()) break;
+ char e = s[i++];
+ switch (e) {
+ case '"': out += '"'; break;
+ case '\\': out += '\\'; break;
+ case '/': out += '/'; break;
+ case 'b': out += '\b'; break;
+ case 'f': out += '\f'; break;
+ case 'n': out += '\n'; break;
+ case 'r': out += '\r'; break;
+ case 't': out += '\t'; break;
+ case 'u': {
+ unsigned cp;
+ if (!hex4(cp)) return false;
+ if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < s.size() && s[i] == '\\' && s[i + 1] == 'u') {
+ i += 2;
+ unsigned lo;
+ if (!hex4(lo)) return false;
+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
+ }
+ appendUtf8(out, cp);
+ break;
+ }
+ default: return fail("Bad escape");
+ }
+ }
+ return fail("Unterminated string");
+ }
+ bool value(Json& out) {
+ if (++depth > 256) return fail("Nesting too deep");
+ ws();
+ if (i >= s.size()) return fail("Unexpected end");
+ char c = s[i];
+ bool ok = true;
+ if (c == '{') {
+ out = Json::object();
+ ++i;
+ ws();
+ if (i < s.size() && s[i] == '}') {
+ ++i;
+ } else {
+ while (true) {
+ ws();
+ if (i >= s.size() || s[i] != '"') { ok = fail("Expected key"); break; }
+ std::string key;
+ if (!string(key)) { ok = false; break; }
+ ws();
+ if (i >= s.size() || s[i] != ':') { ok = fail("Expected ':'"); break; }
+ ++i;
+ Json v;
+ if (!value(v)) { ok = false; break; }
+ out.set(key, std::move(v));
+ ws();
+ if (i < s.size() && s[i] == ',') { ++i; continue; }
+ if (i < s.size() && s[i] == '}') { ++i; break; }
+ ok = fail("Expected ',' or '}'");
+ break;
+ }
+ }
+ } else if (c == '[') {
+ out = Json::array();
+ ++i;
+ ws();
+ if (i < s.size() && s[i] == ']') {
+ ++i;
+ } else {
+ while (true) {
+ Json v;
+ if (!value(v)) { ok = false; break; }
+ out.push(std::move(v));
+ ws();
+ if (i < s.size() && s[i] == ',') { ++i; continue; }
+ if (i < s.size() && s[i] == ']') { ++i; break; }
+ ok = fail("Expected ',' or ']'");
+ break;
+ }
+ }
+ } else if (c == '"') {
+ std::string str;
+ ok = string(str);
+ out = Json(std::move(str));
+ } else if (c == 't') {
+ ok = literal("true");
+ out = Json(true);
+ } else if (c == 'f') {
+ ok = literal("false");
+ out = Json(false);
+ } else if (c == 'n') {
+ ok = literal("null");
+ out = Json();
+ } else if (c == '-' || (c >= '0' && c <= '9')) {
+ const char* start = s.c_str() + i;
+ char* end = nullptr;
+ double d = std::strtod(start, &end);
+ if (end == start) ok = fail("Bad number");
+ i += size_t(end - start);
+ out = Json(d);
+ } else {
+ ok = fail("Unexpected character");
+ }
+ --depth;
+ return ok;
+ }
+};
+
+void newline(std::string& out, bool pretty, int indent) {
+ if (!pretty) return;
+ out += '\n';
+ out.append(size_t(indent) * 2, ' ');
+}
+
+} // namespace
+
+std::string jsonQuote(const std::string& s) {
+ std::string out = "\"";
+ for (unsigned char c : s) {
+ switch (c) {
+ case '"': out += "\\\""; break;
+ case '\\': out += "\\\\"; break;
+ case '\n': out += "\\n"; break;
+ case '\r': out += "\\r"; break;
+ case '\t': out += "\\t"; break;
+ default:
+ if (c < 0x20) {
+ char buf[8];
+ std::snprintf(buf, sizeof buf, "\\u%04x", c);
+ out += buf;
+ } else {
+ out += char(c);
+ }
+ }
+ }
+ return out + "\"";
+}
+
+const std::string& Json::asString() const { return type_ == Type::String ? string_ : kEmpty; }
+
+size_t Json::size() const { return type_ == Type::Array ? array_.size() : type_ == Type::Object ? object_.size() : 0; }
+
+const Json& Json::operator[](size_t i) const { return type_ == Type::Array && i < array_.size() ? array_[i] : kNull; }
+
+Json& Json::push(Json v) {
+ if (type_ != Type::Array) *this = array();
+ array_.push_back(std::move(v));
+ return array_.back();
+}
+
+const Json& Json::operator[](const std::string& key) const {
+ if (type_ == Type::Object)
+ for (const auto& [k, v] : object_)
+ if (k == key) return v;
+ return kNull;
+}
+
+Json& Json::set(const std::string& key, Json v) {
+ if (type_ != Type::Object) *this = object();
+ for (auto& [k, existing] : object_) {
+ if (k == key) {
+ existing = std::move(v);
+ return existing;
+ }
+ }
+ object_.emplace_back(key, std::move(v));
+ return object_.back().second;
+}
+
+bool Json::has(const std::string& key) const {
+ if (type_ != Type::Object) return false;
+ for (const auto& [k, v] : object_)
+ if (k == key) return true;
+ return false;
+}
+
+void Json::dumpTo(std::string& out, bool pretty, int indent) const {
+ switch (type_) {
+ case Type::Null: out += "null"; break;
+ case Type::Bool: out += bool_ ? "true" : "false"; break;
+ case Type::Number: {
+ if (!std::isfinite(number_)) {
+ out += "null";
+ } else if (number_ == std::floor(number_) && std::abs(number_) < 1e15) {
+ out += std::to_string(static_cast<long long>(number_));
+ } else {
+ char buf[32];
+ std::snprintf(buf, sizeof buf, "%.9g", number_);
+ out += buf;
+ }
+ break;
+ }
+ case Type::String: out += jsonQuote(string_); break;
+ case Type::Array:
+ out += '[';
+ for (size_t k = 0; k < array_.size(); ++k) {
+ if (k) out += ',';
+ newline(out, pretty, indent + 1);
+ array_[k].dumpTo(out, pretty, indent + 1);
+ }
+ if (!array_.empty()) newline(out, pretty, indent);
+ out += ']';
+ break;
+ case Type::Object:
+ out += '{';
+ for (size_t k = 0; k < object_.size(); ++k) {
+ if (k) out += ',';
+ newline(out, pretty, indent + 1);
+ out += jsonQuote(object_[k].first);
+ out += pretty ? ": " : ":";
+ object_[k].second.dumpTo(out, pretty, indent + 1);
+ }
+ if (!object_.empty()) newline(out, pretty, indent);
+ out += '}';
+ break;
+ }
+}
+
+std::string Json::dump(bool pretty) const {
+ std::string out;
+ dumpTo(out, pretty, 0);
+ return out;
+}
+
+bool Json::parse(const std::string& text, Json& out, std::string& error) {
+ Parser p(text);
+ Json v;
+ if (!p.value(v)) {
+ error = p.error;
+ return false;
+ }
+ p.ws();
+ if (p.i != text.size()) {
+ error = "Trailing characters at offset " + std::to_string(p.i);
+ return false;
+ }
+ out = std::move(v);
+ return true;
+}
+
+} // namespace sf
diff --git a/src/core/Json.h b/src/core/Json.h
new file mode 100644
index 00000000..b9f36756
--- /dev/null
+++ b/src/core/Json.h
@@ -0,0 +1,70 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Minimal JSON value, parser and writer (brush files, AI provider requests
+// and responses). Numbers are doubles; object key order is preserved.
+#pragma once
+
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace sf {
+
+class Json {
+public:
+ enum class Type { Null, Bool, Number, String, Array, Object };
+
+ Json() = default;
+ Json(std::nullptr_t) {}
+ Json(bool b) : type_(Type::Bool), bool_(b) {}
+ Json(double d) : type_(Type::Number), number_(d) {}
+ Json(int i) : type_(Type::Number), number_(i) {}
+ Json(const char* s) : type_(Type::String), string_(s) {}
+ Json(std::string s) : type_(Type::String), string_(std::move(s)) {}
+
+ static Json array() { Json j; j.type_ = Type::Array; return j; }
+ static Json object() { Json j; j.type_ = Type::Object; return j; }
+
+ Type type() const { return type_; }
+ bool isNull() const { return type_ == Type::Null; }
+ bool isBool() const { return type_ == Type::Bool; }
+ bool isNumber() const { return type_ == Type::Number; }
+ bool isString() const { return type_ == Type::String; }
+ bool isArray() const { return type_ == Type::Array; }
+ bool isObject() const { return type_ == Type::Object; }
+
+ bool asBool(bool fallback = false) const { return type_ == Type::Bool ? bool_ : fallback; }
+ double asNumber(double fallback = 0.0) const { return type_ == Type::Number ? number_ : fallback; }
+ const std::string& asString() const;
+
+ // Arrays
+ size_t size() const;
+ const Json& operator[](size_t i) const;
+ Json& push(Json v);
+ const std::vector<Json>& items() const { return array_; }
+
+ // Objects: get returns a shared null value when the key is missing.
+ const Json& operator[](const std::string& key) const;
+ Json& set(const std::string& key, Json v);
+ bool has(const std::string& key) const;
+ const std::vector<std::pair<std::string, Json>>& members() const { return object_; }
+
+ std::string dump(bool pretty = false) const;
+ static bool parse(const std::string& text, Json& out, std::string& error);
+
+private:
+ void dumpTo(std::string& out, bool pretty, int indent) const;
+
+ Type type_ = Type::Null;
+ bool bool_ = false;
+ double number_ = 0.0;
+ std::string string_;
+ std::vector<Json> array_;
+ std::vector<std::pair<std::string, Json>> object_;
+};
+
+std::string jsonQuote(const std::string& s);
+
+} // namespace sf
diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cpp
new file mode 100644
index 00000000..cba43b86
--- /dev/null
+++ b/src/core/Mesh.cpp
@@ -0,0 +1,234 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Mesh.h"
+
+#include <algorithm>
+#include <unordered_map>
+
+namespace sf {
+
+static glm::vec3 faceNormal(const std::vector<glm::vec3>& p, const glm::uvec3& t) {
+ // Unnormalised: magnitude is twice the triangle area, giving area weighting.
+ return glm::cross(p[t.y] - p[t.x], p[t.z] - p[t.x]);
+}
+
+void Mesh::rebuildTopology() {
+ const size_t nv = positions.size();
+
+ vtOffsets_.assign(nv + 1, 0);
+ for (const auto& t : triangles)
+ for (int c = 0; c < 3; ++c) ++vtOffsets_[t[c] + 1];
+ for (size_t i = 0; i < nv; ++i) vtOffsets_[i + 1] += vtOffsets_[i];
+ vtList_.resize(vtOffsets_[nv]);
+ {
+ std::vector<uint32_t> cursor(vtOffsets_.begin(), vtOffsets_.end() - 1);
+ for (uint32_t ti = 0; ti < triangles.size(); ++ti)
+ for (int c = 0; c < 3; ++c) vtList_[cursor[triangles[ti][c]]++] = ti;
+ }
+
+ adjOffsets_.assign(nv + 1, 0);
+ adjList_.clear();
+ adjList_.reserve(vtList_.size() * 2);
+ std::vector<uint32_t> ring;
+ for (uint32_t v = 0; v < nv; ++v) {
+ ring.clear();
+ for (uint32_t ti : vertexTriangles(v))
+ for (int c = 0; c < 3; ++c)
+ if (triangles[ti][c] != v) ring.push_back(triangles[ti][c]);
+ std::sort(ring.begin(), ring.end());
+ ring.erase(std::unique(ring.begin(), ring.end()), ring.end());
+ adjList_.insert(adjList_.end(), ring.begin(), ring.end());
+ adjOffsets_[v + 1] = static_cast<uint32_t>(adjList_.size());
+ }
+
+ faceNormals_.resize(triangles.size());
+ triStamp_.assign(triangles.size(), 0);
+ vertStamp_.assign(nv, 0);
+ stamp_ = 0;
+ normals.resize(nv);
+ topologyDirty = true;
+}
+
+uint32_t Mesh::nextStamp() {
+ if (++stamp_ == 0) {
+ std::fill(triStamp_.begin(), triStamp_.end(), 0);
+ std::fill(vertStamp_.begin(), vertStamp_.end(), 0);
+ stamp_ = 1;
+ }
+ return stamp_;
+}
+
+void Mesh::recomputeAllNormals() {
+ faceNormals_.resize(triangles.size());
+ for (size_t i = 0; i < triangles.size(); ++i) faceNormals_[i] = faceNormal(positions, triangles[i]);
+ normals.assign(positions.size(), glm::vec3(0.0f));
+ for (size_t i = 0; i < triangles.size(); ++i)
+ for (int c = 0; c < 3; ++c) normals[triangles[i][c]] += faceNormals_[i];
+ for (auto& n : normals) {
+ float len = glm::length(n);
+ n = len > 1e-20f ? n / len : glm::vec3(0, 1, 0);
+ }
+ if (!positions.empty()) {
+ dirtyBegin = 0;
+ dirtyEnd = static_cast<uint32_t>(positions.size());
+ }
+}
+
+void Mesh::updateNormals(std::span<const uint32_t> verts) {
+ const uint32_t s = nextStamp();
+
+ scratchTris_.clear();
+ for (uint32_t v : verts) {
+ markDirty(v);
+ for (uint32_t ti : vertexTriangles(v)) {
+ if (triStamp_[ti] != s) {
+ triStamp_[ti] = s;
+ scratchTris_.push_back(ti);
+ }
+ }
+ }
+ for (uint32_t ti : scratchTris_) faceNormals_[ti] = faceNormal(positions, triangles[ti]);
+
+ scratchVerts_.clear();
+ for (uint32_t ti : scratchTris_) {
+ for (int c = 0; c < 3; ++c) {
+ uint32_t v = triangles[ti][c];
+ if (vertStamp_[v] != s) {
+ vertStamp_[v] = s;
+ scratchVerts_.push_back(v);
+ }
+ }
+ }
+ for (uint32_t v : scratchVerts_) {
+ glm::vec3 n(0.0f);
+ for (uint32_t ti : vertexTriangles(v)) n += faceNormals_[ti];
+ float len = glm::length(n);
+ if (len > 1e-20f) normals[v] = n / len;
+ markDirty(v);
+ }
+}
+
+int Mesh::addLayer(std::string name) {
+ if (layers.empty()) base = positions;
+ layers.push_back({std::move(name), std::vector<glm::vec3>(positions.size(), glm::vec3(0.0f)), 1.0f});
+ return static_cast<int>(layers.size()) - 1;
+}
+
+void Mesh::removeLayer(int index) {
+ if (index < 0 || index >= static_cast<int>(layers.size())) return;
+ layers.erase(layers.begin() + index);
+ if (layers.empty()) {
+ positions = base;
+ base.clear();
+ } else {
+ evaluateAll();
+ }
+ recomputeAllNormals();
+}
+
+void Mesh::setLayerWeight(int index, float weight) {
+ if (index < 0 || index >= static_cast<int>(layers.size())) return;
+ layers[index].weight = weight;
+ evaluateAll();
+ recomputeAllNormals();
+}
+
+std::vector<glm::vec3>& Mesh::layerTarget(int layer) {
+ if (layers.empty()) return positions;
+ if (layer < 0 || layer >= static_cast<int>(layers.size())) return base;
+ return layers[layer].delta;
+}
+
+float Mesh::layerTargetWeight(int layer) const {
+ if (layers.empty() || layer < 0 || layer >= static_cast<int>(layers.size())) return 1.0f;
+ return layers[layer].weight;
+}
+
+void Mesh::evaluate(std::span<const uint32_t> verts) {
+ if (layers.empty()) return;
+ for (uint32_t v : verts) {
+ glm::vec3 p = base[v];
+ for (const auto& l : layers) p += l.weight * l.delta[v];
+ positions[v] = p;
+ }
+}
+
+void Mesh::evaluateAll() {
+ if (layers.empty()) return;
+ for (size_t v = 0; v < positions.size(); ++v) {
+ glm::vec3 p = base[v];
+ for (const auto& l : layers) p += l.weight * l.delta[v];
+ positions[v] = p;
+ }
+}
+
+AABB Mesh::bounds() const {
+ AABB b;
+ for (const auto& p : positions) b.expand(p);
+ return b;
+}
+
+static void laplacianStep(Mesh& m, float lambda, std::vector<glm::vec3>& next) {
+ next.resize(m.vertexCount());
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ auto ring = m.neighbors(v);
+ if (ring.empty()) {
+ next[v] = m.positions[v];
+ continue;
+ }
+ glm::vec3 avg(0.0f);
+ for (uint32_t n : ring) avg += m.positions[n];
+ avg /= float(ring.size());
+ next[v] = glm::mix(m.positions[v], avg, lambda);
+ }
+ m.positions.swap(next);
+}
+
+void taubinSmooth(Mesh& m, int iterations) {
+ std::vector<glm::vec3> next;
+ for (int it = 0; it < iterations; ++it) {
+ laplacianStep(m, 0.5f, next);
+ laplacianStep(m, -0.53f, next);
+ }
+}
+
+Mesh weldImported(const Mesh& m, const std::vector<SculptLayer>& layers) {
+ AABB box = m.bounds();
+ const float tol = box.valid() ? std::max(glm::length(box.extent()) * 1e-6f, 1e-12f) : 1.0f;
+ struct KeyHash {
+ size_t operator()(const glm::ivec3& k) const {
+ return size_t(k.x) * 73856093u ^ size_t(k.y) * 19349663u ^ size_t(k.z) * 83492791u;
+ }
+ };
+ std::unordered_map<glm::ivec3, uint32_t, KeyHash> unique;
+ unique.reserve(m.positions.size());
+ std::vector<uint32_t> remap(m.positions.size());
+ std::vector<uint32_t> kept;
+ for (uint32_t v = 0; v < m.positions.size(); ++v) {
+ glm::ivec3 key(glm::round(m.positions[v] / tol));
+ auto [it, inserted] = unique.try_emplace(key, uint32_t(kept.size()));
+ if (inserted) kept.push_back(v);
+ remap[v] = it->second;
+ }
+ Mesh welded;
+ for (uint32_t v : kept) welded.positions.push_back(m.positions[v]);
+ for (const auto& t : m.triangles) {
+ glm::uvec3 nt(remap[t.x], remap[t.y], remap[t.z]);
+ if (nt.x != nt.y && nt.y != nt.z && nt.x != nt.z) welded.triangles.push_back(nt);
+ }
+ if (!layers.empty()) {
+ welded.base = welded.positions;
+ for (const auto& src : layers) {
+ SculptLayer layer{src.name, {}, src.weight};
+ layer.delta.reserve(kept.size());
+ for (uint32_t v : kept) layer.delta.push_back(v < src.delta.size() ? src.delta[v] : glm::vec3(0.0f));
+ welded.layers.push_back(std::move(layer));
+ }
+ welded.evaluateAll();
+ }
+ welded.rebuildTopology();
+ welded.recomputeAllNormals();
+ return welded;
+}
+
+} // namespace sf
diff --git a/src/core/Mesh.h b/src/core/Mesh.h
new file mode 100644
index 00000000..f362ef3e
--- /dev/null
+++ b/src/core/Mesh.h
@@ -0,0 +1,119 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <glm/glm.hpp>
+
+#include <cstdint>
+#include <limits>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct AABB {
+ glm::vec3 min{std::numeric_limits<float>::max()};
+ glm::vec3 max{std::numeric_limits<float>::lowest()};
+
+ void expand(const glm::vec3& p) {
+ min = glm::min(min, p);
+ max = glm::max(max, p);
+ }
+ void expand(const AABB& b) {
+ min = glm::min(min, b.min);
+ max = glm::max(max, b.max);
+ }
+ bool valid() const { return min.x <= max.x; }
+ glm::vec3 center() const { return (min + max) * 0.5f; }
+ glm::vec3 extent() const { return max - min; }
+};
+
+// A sculpt layer: per-vertex offsets blended in with a weight. Layers are
+// exported as glTF morph targets (blend shapes) for facial/corrective animation.
+struct SculptLayer {
+ std::string name;
+ std::vector<glm::vec3> delta;
+ float weight = 1.0f;
+};
+
+// Triangle mesh with vertex adjacency, suitable for sculpting.
+class Mesh {
+public:
+ std::vector<glm::vec3> positions;
+ std::vector<glm::vec3> normals;
+ std::vector<glm::uvec3> triangles;
+
+ // Sculpt layers. While any exist, `base` holds the positions with every
+ // layer at zero and positions == base + sum(layer.weight * layer.delta).
+ std::vector<glm::vec3> base;
+ std::vector<SculptLayer> layers;
+
+ int addLayer(std::string name);
+ void removeLayer(int index);
+ // Re-evaluates every vertex and recomputes normals (BVH must be rebuilt by the caller).
+ void setLayerWeight(int index, float weight);
+ // The array a stroke on `layer` writes to (-1 = base), and the weight its offsets are scaled by.
+ std::vector<glm::vec3>& layerTarget(int layer);
+ float layerTargetWeight(int layer) const;
+ // Recomputes positions of `verts` from base + layers.
+ void evaluate(std::span<const uint32_t> verts);
+ void evaluateAll();
+ const std::vector<glm::vec3>& basePositions() const { return layers.empty() ? positions : base; }
+
+ size_t vertexCount() const { return positions.size(); }
+ size_t triangleCount() const { return triangles.size(); }
+
+ // Must be called after the triangle list or vertex count changes.
+ void rebuildTopology();
+ void recomputeAllNormals();
+ // Recompute normals of the faces around `verts` and of every vertex they touch.
+ void updateNormals(std::span<const uint32_t> verts);
+
+ std::span<const uint32_t> neighbors(uint32_t v) const {
+ return {adjList_.data() + adjOffsets_[v], adjList_.data() + adjOffsets_[v + 1]};
+ }
+ std::span<const uint32_t> vertexTriangles(uint32_t v) const {
+ return {vtList_.data() + vtOffsets_[v], vtList_.data() + vtOffsets_[v + 1]};
+ }
+
+ AABB bounds() const;
+
+ // GPU synchronisation state: [dirtyBegin, dirtyEnd) needs re-uploading,
+ // topologyDirty means everything (including indices) does.
+ uint32_t dirtyBegin = std::numeric_limits<uint32_t>::max();
+ uint32_t dirtyEnd = 0;
+ bool topologyDirty = true;
+
+ void markDirty(uint32_t v) {
+ dirtyBegin = std::min(dirtyBegin, v);
+ dirtyEnd = std::max(dirtyEnd, v + 1);
+ }
+ void clearDirty() {
+ dirtyBegin = std::numeric_limits<uint32_t>::max();
+ dirtyEnd = 0;
+ topologyDirty = false;
+ }
+
+private:
+ uint32_t nextStamp();
+
+ std::vector<uint32_t> adjOffsets_, adjList_;
+ std::vector<uint32_t> vtOffsets_, vtList_;
+ std::vector<glm::vec3> faceNormals_;
+
+ std::vector<uint32_t> triStamp_, vertStamp_;
+ uint32_t stamp_ = 0;
+ std::vector<uint32_t> scratchTris_, scratchVerts_;
+};
+
+// Shape-preserving Taubin (lambda/mu) smoothing of positions; needs topology.
+// Ignores sculpt layers, so use it on freshly built meshes.
+void taubinSmooth(Mesh& m, int iterations);
+
+// Merges coincident vertices (UV/normal seams from importers), drops
+// degenerate triangles and builds topology and normals. `layers` (optional)
+// hold per-vertex deltas indexed like m.positions and become sculpt layers.
+Mesh weldImported(const Mesh& m, const std::vector<SculptLayer>& layers = {});
+
+} // namespace sf
diff --git a/src/core/Primitives.cpp b/src/core/Primitives.cpp
new file mode 100644
index 00000000..c3a6a021
--- /dev/null
+++ b/src/core/Primitives.cpp
@@ -0,0 +1,163 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Primitives.h"
+
+#include <cmath>
+#include <numbers>
+#include <unordered_map>
+
+namespace sf {
+
+namespace {
+
+uint64_t edgeKey(uint32_t a, uint32_t b) {
+ if (a > b) std::swap(a, b);
+ return (uint64_t(a) << 32) | b;
+}
+
+void finalize(Mesh& m) {
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+}
+
+} // namespace
+
+Mesh makeIcosphere(int subdivisions, float radius) {
+ const float t = (1.0f + std::sqrt(5.0f)) / 2.0f;
+ Mesh m;
+ m.positions = {{-1, t, 0}, {1, t, 0}, {-1, -t, 0}, {1, -t, 0}, {0, -1, t}, {0, 1, t},
+ {0, -1, -t}, {0, 1, -t}, {t, 0, -1}, {t, 0, 1}, {-t, 0, -1}, {-t, 0, 1}};
+ m.triangles = {{0, 11, 5}, {0, 5, 1}, {0, 1, 7}, {0, 7, 10}, {0, 10, 11}, {1, 5, 9}, {5, 11, 4},
+ {11, 10, 2}, {10, 7, 6}, {7, 1, 8}, {3, 9, 4}, {3, 4, 2}, {3, 2, 6}, {3, 6, 8},
+ {3, 8, 9}, {4, 9, 5}, {2, 4, 11}, {6, 2, 10}, {8, 6, 7}, {9, 8, 1}};
+ for (auto& p : m.positions) p = glm::normalize(p);
+
+ for (int level = 0; level < subdivisions; ++level) {
+ std::unordered_map<uint64_t, uint32_t> mids;
+ mids.reserve(m.triangles.size() * 2);
+ auto mid = [&](uint32_t a, uint32_t b) {
+ auto [it, inserted] = mids.try_emplace(edgeKey(a, b), uint32_t(m.positions.size()));
+ if (inserted) m.positions.push_back(glm::normalize(m.positions[a] + m.positions[b]));
+ return it->second;
+ };
+ std::vector<glm::uvec3> tris;
+ tris.reserve(m.triangles.size() * 4);
+ for (const auto& tri : m.triangles) {
+ uint32_t ab = mid(tri.x, tri.y), bc = mid(tri.y, tri.z), ca = mid(tri.z, tri.x);
+ tris.push_back({tri.x, ab, ca});
+ tris.push_back({tri.y, bc, ab});
+ tris.push_back({tri.z, ca, bc});
+ tris.push_back({ab, bc, ca});
+ }
+ m.triangles = std::move(tris);
+ }
+ for (auto& p : m.positions) p *= radius;
+ finalize(m);
+ return m;
+}
+
+Mesh makePlane(int resolution, float size) {
+ Mesh m;
+ const int n = std::max(resolution, 1);
+ for (int j = 0; j <= n; ++j)
+ for (int i = 0; i <= n; ++i)
+ m.positions.emplace_back((float(i) / n - 0.5f) * size, 0.0f, (float(j) / n - 0.5f) * size);
+ for (int j = 0; j < n; ++j) {
+ for (int i = 0; i < n; ++i) {
+ uint32_t a = j * (n + 1) + i, b = a + 1, c = a + (n + 1), d = c + 1;
+ m.triangles.push_back({a, c, b});
+ m.triangles.push_back({b, c, d});
+ }
+ }
+ finalize(m);
+ return m;
+}
+
+Mesh loopSubdivide(const Mesh& src) {
+ const uint32_t nv = static_cast<uint32_t>(src.vertexCount());
+
+ // Edge -> (new vertex index, use count, opposite vertices).
+ struct EdgeInfo {
+ uint32_t index;
+ uint32_t count;
+ uint32_t opp[2];
+ };
+ std::unordered_map<uint64_t, EdgeInfo> edges;
+ edges.reserve(src.triangles.size() * 2);
+ uint32_t next = nv;
+ for (const auto& t : src.triangles) {
+ for (int e = 0; e < 3; ++e) {
+ uint32_t a = t[e], b = t[(e + 1) % 3], c = t[(e + 2) % 3];
+ auto [it, inserted] = edges.try_emplace(edgeKey(a, b), EdgeInfo{next, 0, {c, c}});
+ if (inserted) ++next;
+ if (it->second.count < 2) it->second.opp[it->second.count] = c;
+ ++it->second.count;
+ }
+ }
+
+ // Boundary neighbours per vertex (edges used by exactly one triangle).
+ std::vector<std::vector<uint32_t>> boundaryNbrs(nv);
+ for (const auto& [key, e] : edges) {
+ if (e.count == 1) {
+ uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ boundaryNbrs[a].push_back(b);
+ boundaryNbrs[b].push_back(a);
+ }
+ }
+
+ // Loop subdivision is linear, so the same stencils apply to positions and
+ // to sculpt-layer offsets, keeping layers consistent across levels.
+ auto subdivideAttribute = [&](const std::vector<glm::vec3>& P) {
+ std::vector<glm::vec3> out(next);
+ for (uint32_t v = 0; v < nv; ++v) {
+ const auto& bn = boundaryNbrs[v];
+ if (bn.size() == 2) {
+ out[v] = 0.75f * P[v] + 0.125f * (P[bn[0]] + P[bn[1]]);
+ } else if (!bn.empty()) {
+ out[v] = P[v]; // corner / non-manifold: keep fixed
+ } else {
+ auto ring = src.neighbors(v);
+ const float n = static_cast<float>(ring.size());
+ if (n < 2) {
+ out[v] = P[v];
+ continue;
+ }
+ float c = 0.375f + 0.25f * std::cos(2.0f * std::numbers::pi_v<float> / n);
+ float beta = (0.625f - c * c) / n;
+ glm::vec3 sum(0.0f);
+ for (uint32_t u : ring) sum += P[u];
+ out[v] = (1.0f - n * beta) * P[v] + beta * sum;
+ }
+ }
+ for (const auto& [key, e] : edges) {
+ uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ if (e.count == 2)
+ out[e.index] = 0.375f * (P[a] + P[b]) + 0.125f * (P[e.opp[0]] + P[e.opp[1]]);
+ else
+ out[e.index] = 0.5f * (P[a] + P[b]);
+ }
+ return out;
+ };
+
+ Mesh out;
+ out.positions = subdivideAttribute(src.positions);
+ if (!src.layers.empty()) {
+ out.base = subdivideAttribute(src.base);
+ for (const auto& l : src.layers) out.layers.push_back({l.name, subdivideAttribute(l.delta), l.weight});
+ }
+
+ out.triangles.reserve(src.triangles.size() * 4);
+ for (const auto& t : src.triangles) {
+ uint32_t ab = edges.at(edgeKey(t.x, t.y)).index;
+ uint32_t bc = edges.at(edgeKey(t.y, t.z)).index;
+ uint32_t ca = edges.at(edgeKey(t.z, t.x)).index;
+ out.triangles.push_back({t.x, ab, ca});
+ out.triangles.push_back({t.y, bc, ab});
+ out.triangles.push_back({t.z, ca, bc});
+ out.triangles.push_back({ab, bc, ca});
+ }
+ finalize(out);
+ return out;
+}
+
+} // namespace sf
diff --git a/src/core/Primitives.h b/src/core/Primitives.h
new file mode 100644
index 00000000..cc965172
--- /dev/null
+++ b/src/core/Primitives.h
@@ -0,0 +1,15 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+
+namespace sf {
+
+// Returned meshes have topology and normals built.
+Mesh makeIcosphere(int subdivisions, float radius = 1.0f);
+Mesh makePlane(int resolution, float size = 2.0f);
+// Loop subdivision (smooth; boundaries follow the cubic B-spline rule).
+Mesh loopSubdivide(const Mesh& mesh);
+
+} // namespace sf
diff --git a/src/core/Script.cpp b/src/core/Script.cpp
new file mode 100644
index 00000000..668282b9
--- /dev/null
+++ b/src/core/Script.cpp
@@ -0,0 +1,103 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Script.h"
+
+#include <cctype>
+#include <cstdlib>
+
+namespace sf {
+
+namespace {
+
+ArgValue parseValue(const std::string& raw, bool quoted) {
+ if (!quoted) {
+ if (raw == "true") return true;
+ if (raw == "false") return false;
+ char* end = nullptr;
+ double d = std::strtod(raw.c_str(), &end);
+ if (!raw.empty() && end == raw.c_str() + raw.size()) return d;
+ }
+ return raw;
+}
+
+} // namespace
+
+bool parseScript(const std::string& text, std::vector<ScriptStatement>& out, std::string& error) {
+ out.clear();
+ size_t i = 0;
+ int line = 1;
+ std::vector<std::pair<std::string, bool>> tokens; // (text, quoted)
+ int stmtLine = 1;
+
+ auto flush = [&]() -> bool {
+ if (tokens.empty()) return true;
+ ScriptStatement st;
+ st.line = stmtLine;
+ st.command = tokens[0].first;
+ for (size_t t = 1; t < tokens.size(); ++t) {
+ // Tokens look like key=value; a quoted value arrives as key= followed by the quoted token.
+ std::string tok = tokens[t].first;
+ size_t eq = tok.find('=');
+ if (eq == std::string::npos || eq == 0) {
+ error = "Line " + std::to_string(stmtLine) + ": expected key=value, got '" + tok + "'";
+ return false;
+ }
+ std::string key = tok.substr(0, eq);
+ std::string value = tok.substr(eq + 1);
+ bool quoted = false;
+ if (value.empty() && t + 1 < tokens.size() && tokens[t + 1].second) {
+ value = tokens[++t].first;
+ quoted = true;
+ }
+ st.args[key] = parseValue(value, quoted);
+ }
+ out.push_back(std::move(st));
+ tokens.clear();
+ return true;
+ };
+
+ while (i < text.size()) {
+ char c = text[i];
+ if (c == '\n' || c == ';') {
+ if (!flush()) return false;
+ if (c == '\n') ++line;
+ ++i;
+ continue;
+ }
+ if (c == '#') {
+ while (i < text.size() && text[i] != '\n') ++i;
+ continue;
+ }
+ if (std::isspace(static_cast<unsigned char>(c))) {
+ ++i;
+ continue;
+ }
+ if (tokens.empty()) stmtLine = line;
+ if (c == '"') {
+ std::string s;
+ ++i;
+ while (i < text.size() && text[i] != '"') {
+ if (text[i] == '\\' && i + 1 < text.size()) ++i;
+ if (text[i] == '\n') ++line;
+ s += text[i++];
+ }
+ if (i >= text.size()) {
+ error = "Line " + std::to_string(line) + ": unterminated string";
+ return false;
+ }
+ ++i;
+ tokens.emplace_back(std::move(s), true);
+ continue;
+ }
+ std::string s;
+ while (i < text.size() && !std::isspace(static_cast<unsigned char>(text[i])) && text[i] != ';' &&
+ text[i] != '#') {
+ if (text[i] == '"' && !s.empty() && s.back() == '=') break; // key="quoted value"
+ s += text[i++];
+ }
+ tokens.emplace_back(std::move(s), false);
+ }
+ return flush();
+}
+
+} // namespace sf
diff --git a/src/core/Script.h b/src/core/Script.h
new file mode 100644
index 00000000..5b5e7207
--- /dev/null
+++ b/src/core/Script.h
@@ -0,0 +1,26 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tiny command script language used by sculptforge-cli and (later) the in-app
+// console: open_obj path="my head.obj"; subdivide levels=2
+// export_lods path=out/head.glb levels=4 # comment
+// Statements end at ';' or newline. Values: true/false, numbers, or strings
+// (quote strings containing spaces).
+#pragma once
+
+#include "core/Commands.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct ScriptStatement {
+ std::string command;
+ Args args;
+ int line = 0;
+};
+
+bool parseScript(const std::string& text, std::vector<ScriptStatement>& out, std::string& error);
+
+} // namespace sf
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
new file mode 100644
index 00000000..36b1041f
--- /dev/null
+++ b/src/core/Sculpt.cpp
@@ -0,0 +1,410 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Sculpt.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+const char* brushName(BrushType type) {
+ switch (type) {
+ case BrushType::Standard: return "Standard";
+ case BrushType::Clay: return "Clay";
+ case BrushType::Smooth: return "Smooth";
+ case BrushType::Move: return "Move";
+ case BrushType::Inflate: return "Inflate";
+ case BrushType::Crease: return "Crease";
+ case BrushType::Flatten: return "Flatten";
+ case BrushType::Pinch: return "Pinch";
+ default: return "?";
+ }
+}
+
+namespace {
+
+float falloff(float dist, float radius) {
+ float t = std::clamp(1.0f - dist / radius, 0.0f, 1.0f);
+ return t * t * (3.0f - 2.0f * t);
+}
+
+glm::vec3 projectOnPlane(const glm::vec3& v, const glm::vec3& n) { return v - n * glm::dot(v, n); }
+
+// --- Procedural 3D patterns (deterministic, so texture sticks to the surface) ---
+
+uint32_t hash3(int x, int y, int z) {
+ uint32_t h = uint32_t(x) * 0x8da6b343u ^ uint32_t(y) * 0xd8163841u ^ uint32_t(z) * 0xcb1ab31fu;
+ h ^= h >> 13;
+ h *= 0x5bd1e995u;
+ h ^= h >> 15;
+ return h;
+}
+float hashFloat(uint32_t h) { return float(h & 0xffffffu) / float(0xffffff); }
+
+float valueNoise(const glm::vec3& p) {
+ glm::vec3 i = glm::floor(p), f = p - i;
+ glm::vec3 u = f * f * (3.0f - 2.0f * f);
+ auto at = [&](int dx, int dy, int dz) {
+ return hashFloat(hash3(int(i.x) + dx, int(i.y) + dy, int(i.z) + dz));
+ };
+ float x00 = glm::mix(at(0, 0, 0), at(1, 0, 0), u.x), x10 = glm::mix(at(0, 1, 0), at(1, 1, 0), u.x);
+ float x01 = glm::mix(at(0, 0, 1), at(1, 0, 1), u.x), x11 = glm::mix(at(0, 1, 1), at(1, 1, 1), u.x);
+ return glm::mix(glm::mix(x00, x10, u.y), glm::mix(x01, x11, u.y), u.z);
+}
+
+float fbm(const glm::vec3& p) {
+ return (valueNoise(p) * 0.57f + valueNoise(p * 2.03f + 17.0f) * 0.29f + valueNoise(p * 4.01f + 31.0f) * 0.14f);
+}
+
+// Distances to the nearest and second-nearest jittered feature points.
+void worley(const glm::vec3& p, float& f1, float& f2) {
+ glm::vec3 c = glm::floor(p);
+ f1 = f2 = 1e9f;
+ for (int dz = -1; dz <= 1; ++dz)
+ for (int dy = -1; dy <= 1; ++dy)
+ for (int dx = -1; dx <= 1; ++dx) {
+ int x = int(c.x) + dx, y = int(c.y) + dy, z = int(c.z) + dz;
+ uint32_t h = hash3(x, y, z);
+ glm::vec3 feature(float(x) + hashFloat(h), float(y) + hashFloat(h * 747796405u + 1u),
+ float(z) + hashFloat(h * 2891336453u + 7u));
+ float d = glm::distance(p, feature);
+ if (d < f1) {
+ f2 = f1;
+ f1 = d;
+ } else if (d < f2) {
+ f2 = d;
+ }
+ }
+}
+
+// Returns 0..1, where 1 means "full brush effect here".
+float samplePattern(BrushRecipe::Pattern pattern, const glm::vec3& p) {
+ switch (pattern) {
+ case BrushRecipe::Pattern::Noise: return std::clamp(fbm(p) * 1.4f - 0.2f, 0.0f, 1.0f);
+ case BrushRecipe::Pattern::Ridges: {
+ float n = 1.0f - std::abs(2.0f * fbm(p) - 1.0f);
+ return n * n * n;
+ }
+ case BrushRecipe::Pattern::Scales: {
+ float f1, f2;
+ worley(p, f1, f2);
+ float t = std::clamp(f1 / std::max(f2, 1e-4f), 0.0f, 1.0f); // 0 at centre, 1 at the border
+ return std::sqrt(std::max(0.0f, 1.0f - t * t)); // domed scale
+ }
+ case BrushRecipe::Pattern::Pores: {
+ float f1, f2;
+ worley(p, f1, f2);
+ float t = std::clamp(f1 / 0.3f, 0.0f, 1.0f);
+ return (1.0f - t) * (1.0f - t);
+ }
+ case BrushRecipe::Pattern::Cracks: {
+ float f1, f2;
+ worley(p, f1, f2);
+ float t = std::clamp((f2 - f1) / 0.12f, 0.0f, 1.0f);
+ return 1.0f - t * t * (3.0f - 2.0f * t);
+ }
+ default: return 1.0f;
+ }
+}
+
+} // namespace
+
+std::vector<glm::vec3> Sculptor::mirrors(Symmetry sym) {
+ std::vector<glm::vec3> out;
+ for (int mask = 0; mask < 8; ++mask) {
+ if ((mask & 1 && !sym.x) || (mask & 2 && !sym.y) || (mask & 4 && !sym.z)) continue;
+ out.emplace_back(mask & 1 ? -1.0f : 1.0f, mask & 2 ? -1.0f : 1.0f, mask & 4 ? -1.0f : 1.0f);
+ }
+ return out;
+}
+
+bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {
+ if (layer >= static_cast<int>(mesh.layers.size())) layer = -1;
+ if (std::abs(mesh.layerTargetWeight(layer)) < 1e-3f) return false;
+ layer_ = layer;
+ record_ = UndoRecord{};
+ record_.label = std::move(label);
+ record_.layer = layer;
+ if (touchStamp_.size() != mesh.vertexCount()) {
+ touchStamp_.assign(mesh.vertexCount(), 0);
+ stamp_ = 0;
+ }
+ if (++stamp_ == 0) {
+ std::fill(touchStamp_.begin(), touchStamp_.end(), 0);
+ stamp_ = 1;
+ }
+ active_ = true;
+ return true;
+}
+
+void Sculptor::touch(Mesh& mesh, uint32_t v) {
+ if (touchStamp_[v] == stamp_) return;
+ touchStamp_[v] = stamp_;
+ record_.indices.push_back(v);
+ record_.positions.push_back(mesh.layerTarget(layer_)[v]);
+}
+
+// Moves a vertex and attributes the offset to the active layer.
+void Sculptor::displace(Mesh& mesh, uint32_t v, const glm::vec3& d) {
+ touch(mesh, v);
+ mesh.positions[v] += d;
+ if (!mesh.layers.empty()) mesh.layerTarget(layer_)[v] += d / mesh.layerTargetWeight(layer_);
+}
+
+UndoRecord Sculptor::endStroke() {
+ active_ = false;
+ grab_.clear();
+ return std::move(record_);
+}
+
+void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {
+ if (!active_) return;
+ for (const glm::vec3& m : mirrors(sym)) {
+ DabParams mp = p;
+ mp.center *= m;
+ mp.viewDir *= m;
+ dabSingle(mesh, bvh, type, mp);
+ }
+}
+
+void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p) {
+ bvh.queryVertices(mesh, p.center, p.radius, verts_);
+ if (verts_.empty()) return;
+
+ auto& pos = mesh.positions;
+ const auto& nrm = mesh.normals;
+
+ if (p.frontFacesOnly) {
+ std::erase_if(verts_, [&](uint32_t v) { return glm::dot(nrm[v], p.viewDir) > 0.0f; });
+ if (verts_.empty()) return;
+ }
+
+ // Weighted area normal and centre of the brush region.
+ glm::vec3 areaNormal(0.0f), areaCenter(0.0f);
+ float wsum = 0.0f;
+ for (uint32_t v : verts_) {
+ float w = falloff(glm::distance(pos[v], p.center), p.radius);
+ areaNormal += nrm[v] * w;
+ areaCenter += pos[v] * w;
+ wsum += w;
+ }
+ if (wsum <= 0.0f) return;
+ areaCenter /= wsum;
+ float nlen = glm::length(areaNormal);
+ areaNormal = nlen > 1e-12f ? areaNormal / nlen : -p.viewDir;
+
+ const float s = std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f);
+ const float sign = p.invert ? -1.0f : 1.0f;
+ const float r = p.radius;
+
+ scratch_.resize(verts_.size());
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ const uint32_t v = verts_[i];
+ const glm::vec3& x = pos[v];
+ const float f = falloff(glm::distance(x, p.center), r);
+ glm::vec3 d(0.0f);
+
+ switch (type) {
+ case BrushType::Standard:
+ d = areaNormal * (sign * s * r * 0.06f * f);
+ break;
+ case BrushType::Inflate:
+ d = nrm[v] * (sign * s * r * 0.05f * f);
+ break;
+ case BrushType::Smooth: {
+ auto ring = mesh.neighbors(v);
+ if (ring.empty()) break;
+ glm::vec3 avg(0.0f);
+ for (uint32_t n : ring) avg += pos[n];
+ avg /= static_cast<float>(ring.size());
+ d = (avg - x) * std::min(1.0f, s * f);
+ break;
+ }
+ case BrushType::Flatten: {
+ float h = glm::dot(x - areaCenter, areaNormal);
+ d = -areaNormal * (h * s * f * (p.invert ? -0.5f : 1.0f));
+ break;
+ }
+ case BrushType::Clay: {
+ // Raise a plane slightly above the surface and pull everything below up to it.
+ glm::vec3 planePoint = areaCenter + areaNormal * (sign * r * 0.05f * s);
+ float h = glm::dot(x - planePoint, areaNormal);
+ if (sign * h < 0.0f) d = -areaNormal * (h * f);
+ break;
+ }
+ case BrushType::Crease: {
+ // Carves a sharp valley by default (raises a ridge when inverted).
+ float sharp = f * f;
+ d = areaNormal * (-sign * s * r * 0.05f * sharp);
+ d += projectOnPlane(p.center - x, areaNormal) * (0.25f * s * f);
+ break;
+ }
+ case BrushType::Pinch:
+ d = projectOnPlane(p.center - x, areaNormal) * (sign * 0.2f * s * f);
+ break;
+ default:
+ break;
+ }
+ scratch_[i] = d;
+ }
+
+ for (size_t i = 0; i < verts_.size(); ++i) displace(mesh, verts_[i], scratch_[i]);
+ mesh.updateNormals(verts_);
+ bvh.refit(mesh, verts_);
+}
+
+void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const DabParams& p, Symmetry sym) {
+ if (!active_) return;
+ DabParams base = p;
+ base.pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);
+ base.frontFacesOnly = p.frontFacesOnly || recipe.frontFacesOnly;
+ for (const glm::vec3& m : mirrors(sym)) {
+ DabParams mp = base;
+ mp.center *= m;
+ mp.viewDir *= m;
+ mp.strokeDelta *= m;
+ dabRecipeSingle(mesh, bvh, recipe, mp);
+ }
+}
+
+void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p) {
+ bvh.queryVertices(mesh, p.center, p.radius, verts_);
+ if (verts_.empty()) return;
+ const auto& pos = mesh.positions;
+ const auto& nrm = mesh.normals;
+ if (p.frontFacesOnly) {
+ std::erase_if(verts_, [&](uint32_t v) { return glm::dot(nrm[v], p.viewDir) > 0.0f; });
+ if (verts_.empty()) return;
+ }
+
+ const float rad = p.radius;
+ const float s = std::clamp(p.strength, 0.0f, 1.0f) * p.pressure;
+ const float sign = p.invert ? -1.0f : 1.0f;
+
+ // Per-vertex weight: tip shape, cavity mask and pattern.
+ weights_.resize(verts_.size());
+ const float edge = std::max(0.05f, 1.0f - r.hardness * 0.95f);
+ const float exponent = 1.0f + r.tipSharpness * 5.0f;
+ const float patternFreq = 1.0f / std::max(rad * r.patternScale, 1e-6f);
+ glm::vec3 areaNormal(0.0f), areaCenter(0.0f);
+ float wsum = 0.0f;
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ const uint32_t v = verts_[i];
+ float t = std::clamp((1.0f - glm::distance(pos[v], p.center) / rad) / edge, 0.0f, 1.0f);
+ float w = std::pow(t * t * (3.0f - 2.0f * t), exponent);
+ areaNormal += nrm[v] * w;
+ areaCenter += pos[v] * w;
+ wsum += w;
+ if (r.cavityMask != 0.0f) {
+ auto ring = mesh.neighbors(v);
+ if (!ring.empty()) {
+ glm::vec3 avg(0.0f);
+ float edgeLen = 0.0f;
+ for (uint32_t n : ring) {
+ avg += pos[n];
+ edgeLen += glm::distance(pos[n], pos[v]);
+ }
+ avg /= float(ring.size());
+ edgeLen /= float(ring.size());
+ // > 0 in cavities (neighbours sit above the vertex), < 0 on ridges.
+ float c = std::clamp(glm::dot(nrm[v], avg - pos[v]) / std::max(edgeLen, 1e-9f) * 6.0f, -1.0f, 1.0f);
+ float m = r.cavityMask > 0.0f ? std::max(c, 0.0f) : std::max(-c, 0.0f);
+ w *= glm::mix(1.0f, m, std::abs(r.cavityMask));
+ }
+ }
+ if (r.pattern != BrushRecipe::Pattern::None && r.patternAmount > 0.0f)
+ w *= glm::mix(1.0f, samplePattern(r.pattern, pos[v] * patternFreq), r.patternAmount);
+ weights_[i] = w;
+ }
+ if (wsum <= 0.0f) return;
+ areaCenter /= wsum;
+ float nlen = glm::length(areaNormal);
+ areaNormal = nlen > 1e-12f ? areaNormal / nlen : -p.viewDir;
+
+ glm::vec3 strokeDir = p.strokeDelta;
+ float strokeLen = glm::length(strokeDir);
+ strokeDir = strokeLen > 1e-12f ? strokeDir / strokeLen : glm::vec3(0.0f);
+
+ scratch_.resize(verts_.size());
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ const uint32_t v = verts_[i];
+ const glm::vec3& x = pos[v];
+ const float f = weights_[i];
+ glm::vec3 dir;
+ switch (r.direction) {
+ case BrushRecipe::Direction::Inflate: dir = nrm[v]; break;
+ case BrushRecipe::Direction::View: dir = -p.viewDir; break;
+ case BrushRecipe::Direction::Stroke: dir = strokeDir; break;
+ default: dir = areaNormal; break;
+ }
+ glm::vec3 d = dir * (sign * r.depth * 0.12f * rad * s * f);
+
+ const float h = glm::dot(x - areaCenter, areaNormal);
+ switch (r.plane) {
+ case BrushRecipe::Plane::Clay: {
+ glm::vec3 planePoint = areaCenter + areaNormal * (sign * rad * 0.06f * s);
+ float hc = glm::dot(x - planePoint, areaNormal);
+ if (sign * hc < 0.0f) d -= areaNormal * (hc * f * r.planeAmount);
+ break;
+ }
+ case BrushRecipe::Plane::Flatten: d -= areaNormal * (h * s * f * r.planeAmount); break;
+ case BrushRecipe::Plane::Fill:
+ if (h < 0.0f) d -= areaNormal * (h * s * f * r.planeAmount);
+ break;
+ case BrushRecipe::Plane::Scrape:
+ if (h > 0.0f) d -= areaNormal * (h * s * f * r.planeAmount);
+ break;
+ default: break;
+ }
+ if (r.pinch != 0.0f) d += projectOnPlane(p.center - x, areaNormal) * (r.pinch * 0.25f * s * f);
+ if (r.drag > 0.0f) d += p.strokeDelta * (r.drag * f);
+ scratch_[i] = d;
+ }
+ for (size_t i = 0; i < verts_.size(); ++i) displace(mesh, verts_[i], scratch_[i]);
+
+ if (r.smooth > 0.0f) {
+ for (size_t i = 0; i < verts_.size(); ++i) {
+ auto ring = mesh.neighbors(verts_[i]);
+ if (ring.empty()) {
+ scratch_[i] = glm::vec3(0.0f);
+ continue;
+ }
+ glm::vec3 avg(0.0f);
+ for (uint32_t n : ring) avg += pos[n];
+ avg /= float(ring.size());
+ scratch_[i] = (avg - pos[verts_[i]]) * std::min(1.0f, r.smooth * weights_[i]);
+ }
+ for (size_t i = 0; i < verts_.size(); ++i) displace(mesh, verts_[i], scratch_[i]);
+ }
+
+ mesh.updateNormals(verts_);
+ bvh.refit(mesh, verts_);
+}
+
+void Sculptor::beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym) {
+ grab_.clear();
+ grabVerts_.clear();
+ if (!active_) return;
+ for (const glm::vec3& m : mirrors(sym)) {
+ glm::vec3 c = p.center * m;
+ bvh.queryVertices(mesh, c, p.radius, verts_);
+ for (uint32_t v : verts_) {
+ float w = falloff(glm::distance(mesh.positions[v], c), p.radius) *
+ std::clamp(p.strength * 2.0f, 0.0f, 1.0f);
+ if (w <= 0.0f) continue;
+ grab_.push_back({v, w, m});
+ grabVerts_.push_back(v);
+ }
+ }
+ std::sort(grabVerts_.begin(), grabVerts_.end());
+ grabVerts_.erase(std::unique(grabVerts_.begin(), grabVerts_.end()), grabVerts_.end());
+}
+
+void Sculptor::grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta) {
+ if (grab_.empty()) return;
+ for (const auto& g : grab_) displace(mesh, g.vertex, delta * g.mirror * g.weight);
+ mesh.updateNormals(grabVerts_);
+ bvh.refit(mesh, grabVerts_);
+}
+
+} // namespace sf
diff --git a/src/core/Sculpt.h b/src/core/Sculpt.h
new file mode 100644
index 00000000..6c58df4b
--- /dev/null
+++ b/src/core/Sculpt.h
@@ -0,0 +1,78 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/BVH.h"
+#include "core/BrushRecipe.h"
+#include "core/Mesh.h"
+#include "core/Undo.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+enum class BrushType { Standard, Clay, Smooth, Move, Inflate, Crease, Flatten, Pinch, Count };
+
+const char* brushName(BrushType type);
+
+struct DabParams {
+ glm::vec3 center{0.0f}; // surface point under the cursor
+ glm::vec3 viewDir{0.0f, 0.0f, -1.0f}; // camera ray direction (into the scene)
+ float radius = 0.1f; // world units
+ float strength = 0.5f; // 0..1
+ float pressure = 1.0f; // tablet pressure, 0..1
+ bool invert = false;
+ bool frontFacesOnly = false;
+ glm::vec3 strokeDelta{0.0f}; // world-space movement since the previous dab (recipe brushes)
+};
+
+struct Symmetry {
+ bool x = true, y = false, z = false;
+};
+
+// Applies brush dabs to a mesh, keeping normals and the BVH in sync and
+// recording the original positions of every touched vertex for undo.
+class Sculptor {
+public:
+ // Strokes write into sculpt layer `layer` (-1 = base). Returns false if the
+ // layer's weight is ~0, since its offsets would be invisible.
+ bool beginStroke(const Mesh& mesh, std::string label, int layer = -1);
+ void dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym);
+ // Custom brush defined by a recipe (see BrushRecipe.h).
+ void dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const DabParams& p, Symmetry sym);
+
+ // Move brush: capture the region once, then drag it by world deltas.
+ void beginGrab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym);
+ void grab(Mesh& mesh, BVH& bvh, const glm::vec3& delta);
+
+ UndoRecord endStroke();
+ bool strokeActive() const { return active_; }
+
+private:
+ struct GrabEntry {
+ uint32_t vertex;
+ float weight;
+ glm::vec3 mirror;
+ };
+
+ void dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p);
+ void dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const DabParams& p);
+ void touch(Mesh& mesh, uint32_t v);
+ void displace(Mesh& mesh, uint32_t v, const glm::vec3& d);
+ static std::vector<glm::vec3> mirrors(Symmetry sym);
+
+ bool active_ = false;
+ int layer_ = -1;
+ UndoRecord record_;
+ std::vector<uint32_t> touchStamp_;
+ uint32_t stamp_ = 0;
+
+ std::vector<uint32_t> verts_;
+ std::vector<glm::vec3> scratch_;
+ std::vector<float> weights_;
+ std::vector<GrabEntry> grab_;
+ std::vector<uint32_t> grabVerts_;
+};
+
+} // namespace sf
diff --git a/src/core/Splats.cpp b/src/core/Splats.cpp
new file mode 100644
index 00000000..3a67b676
--- /dev/null
+++ b/src/core/Splats.cpp
@@ -0,0 +1,254 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Splats.h"
+
+#include "core/Voxel.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <algorithm>
+#include <cmath>
+#include <random>
+
+namespace sf {
+
+namespace {
+
+glm::quat rotationFromZ(const glm::vec3& n) {
+ const glm::vec3 z(0.0f, 0.0f, 1.0f);
+ const float d = glm::dot(z, n);
+ if (d < -0.999999f) return glm::quat(0.0f, 1.0f, 0.0f, 0.0f); // 180 degrees about X
+ const glm::vec3 c = glm::cross(z, n);
+ return glm::normalize(glm::quat(1.0f + d, c.x, c.y, c.z));
+}
+
+glm::mat4 eulerXYZ(const glm::vec3& degrees) {
+ glm::mat4 r(1.0f);
+ r = glm::rotate(r, glm::radians(degrees.z), glm::vec3(0, 0, 1));
+ r = glm::rotate(r, glm::radians(degrees.y), glm::vec3(0, 1, 0));
+ r = glm::rotate(r, glm::radians(degrees.x), glm::vec3(1, 0, 0));
+ return r;
+}
+
+} // namespace
+
+void SplatCloud::resize(size_t n, int degree) {
+ shDegree = degree;
+ positions.resize(n, glm::vec3(0.0f));
+ rotations.resize(n, glm::quat(1.0f, 0.0f, 0.0f, 0.0f));
+ scales.resize(n, glm::vec3(0.01f));
+ opacities.resize(n, 1.0f);
+ sh.resize(n * size_t(shCount()), glm::vec3(0.0f));
+}
+
+AABB SplatCloud::bounds(float keepFraction) const {
+ AABB b;
+ if (empty()) return b;
+ if (keepFraction >= 1.0f) {
+ for (size_t i = 0; i < size(); ++i) b.expand(worldPosition(i));
+ return b;
+ }
+ std::vector<float> axis(size());
+ const float tail = std::clamp((1.0f - keepFraction) * 0.5f, 0.0f, 0.49f);
+ for (int a = 0; a < 3; ++a) {
+ for (size_t i = 0; i < size(); ++i) axis[i] = worldPosition(i)[a];
+ const size_t lo = size_t(tail * float(size() - 1));
+ const size_t hi = size() - 1 - lo;
+ std::nth_element(axis.begin(), axis.begin() + std::ptrdiff_t(lo), axis.end());
+ b.min[a] = axis[lo];
+ std::nth_element(axis.begin(), axis.begin() + std::ptrdiff_t(hi), axis.end());
+ b.max[a] = axis[hi];
+ }
+ return b;
+}
+
+std::string SplatCloud::validate() const {
+ const size_t n = size();
+ if (rotations.size() != n || scales.size() != n || opacities.size() != n)
+ return "Splat attribute arrays have different lengths";
+ if (shDegree < 0 || shDegree > 3) return "Unsupported spherical-harmonics degree " + std::to_string(shDegree);
+ if (sh.size() != n * size_t(shCount())) return "Spherical-harmonics data does not match the splat count";
+ return {};
+}
+
+float SplatCloud::transformScale() const { return glm::length(glm::vec3(transform[0])); }
+
+glm::quat SplatCloud::transformRotation() const {
+ const float s = transformScale();
+ return glm::normalize(glm::quat_cast(glm::mat3(transform) / (s > 0.0f ? s : 1.0f)));
+}
+
+bool SplatCloud::bakeTransform() {
+ const float s = transformScale();
+ const glm::quat r = transformRotation();
+ for (size_t i = 0; i < size(); ++i) {
+ positions[i] = worldPosition(i);
+ rotations[i] = glm::normalize(r * rotations[i]);
+ scales[i] *= s;
+ }
+ transform = glm::mat4(1.0f);
+ const bool rotated = std::abs(std::abs(r.w) - 1.0f) > 1e-6f;
+ if (rotated && shDegree > 0) {
+ std::vector<glm::vec3> dc(size());
+ for (size_t i = 0; i < size(); ++i) dc[i] = sh[i * size_t(shCount())];
+ sh.swap(dc);
+ shDegree = 0;
+ return false;
+ }
+ return true;
+}
+
+size_t cleanSplats(SplatCloud& cloud, float minOpacity, float keepFraction) {
+ AABB keep = cloud.bounds(keepFraction);
+ if (keepFraction < 1.0f) {
+ const glm::vec3 margin = keep.extent() * 0.02f;
+ keep.min -= margin;
+ keep.max += margin;
+ }
+ return cloud.removeIf([&](size_t i) {
+ if (cloud.opacities[i] < minOpacity) return true;
+ const glm::vec3 p = cloud.worldPosition(i);
+ return glm::any(glm::lessThan(p, keep.min)) || glm::any(glm::greaterThan(p, keep.max));
+ });
+}
+
+void rotateSplats(SplatCloud& cloud, const glm::vec3& degrees) {
+ const glm::vec3 c = cloud.bounds(0.9f).center();
+ cloud.transform = glm::translate(glm::mat4(1.0f), c) * eulerXYZ(degrees) * glm::translate(glm::mat4(1.0f), -c) *
+ cloud.transform;
+}
+
+void fitSplats(SplatCloud& cloud) {
+ if (cloud.empty()) return;
+ const AABB b = cloud.bounds(0.9f);
+ const glm::vec3 e = b.extent();
+ const float radius = std::max({e.x, e.y, e.z, 1e-6f}) * 0.5f;
+ cloud.transform = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f / radius)) * glm::translate(glm::mat4(1.0f), -b.center()) *
+ cloud.transform;
+}
+
+Mesh splatsToMesh(const SplatCloud& cloud, const SplatToMeshOptions& o, std::string* error) {
+ auto fail = [&](const std::string& msg) {
+ if (error) *error = msg;
+ return Mesh();
+ };
+ if (cloud.empty()) return fail("There are no splats to convert");
+ AABB box = cloud.bounds(std::clamp(o.keepFraction, 0.5f, 1.0f));
+ const float boxSize = std::max({box.extent().x, box.extent().y, box.extent().z});
+ if (!(boxSize > 0.0f)) return fail("The splats have no extent");
+ box.min -= box.extent() * 0.02f;
+ box.max += box.extent() * 0.02f;
+
+ VoxelGrid grid;
+ const int closeRadius = std::clamp(o.closeRadius, 0, 8);
+ if (!makeVoxelGrid(box, std::clamp(o.resolution, 16, 512), closeRadius + 4, grid))
+ return fail("Resolution too high");
+
+ // Splat each Gaussian's opacity into the grid. Variance is widened by half
+ // a voxel so thin splats still register.
+ const float s = cloud.transformScale();
+ const glm::quat r = cloud.transformRotation();
+ const float widen = 0.25f * grid.cell * grid.cell;
+ const float maxReach = 6.0f * grid.cell;
+ size_t used = 0;
+ for (size_t i = 0; i < cloud.size(); ++i) {
+ const float alpha = cloud.opacities[i];
+ if (alpha < o.minOpacity) continue;
+ const glm::vec3 p = cloud.worldPosition(i);
+ if (glm::any(glm::lessThan(p, box.min)) || glm::any(glm::greaterThan(p, box.max))) continue;
+ const glm::vec3 sigma = cloud.scales[i] * s;
+ if (std::max({sigma.x, sigma.y, sigma.z}) > 0.25f * boxSize) continue; // background blobs
+ const glm::mat3 R = glm::mat3_cast(glm::normalize(r * cloud.rotations[i]));
+ glm::mat3 cov = R * glm::mat3(glm::vec3(sigma.x * sigma.x, 0, 0), glm::vec3(0, sigma.y * sigma.y, 0),
+ glm::vec3(0, 0, sigma.z * sigma.z)) *
+ glm::transpose(R);
+ cov[0][0] += widen;
+ cov[1][1] += widen;
+ cov[2][2] += widen;
+ const glm::mat3 inv = glm::inverse(cov);
+ const glm::vec3 reach = glm::min(3.0f * glm::sqrt(glm::vec3(cov[0][0], cov[1][1], cov[2][2])), glm::vec3(maxReach));
+ const glm::ivec3 lo = glm::max(glm::ivec3(glm::floor((p - reach - grid.origin) / grid.cell)), glm::ivec3(0));
+ const glm::ivec3 hi = glm::min(glm::ivec3(glm::ceil((p + reach - grid.origin) / grid.cell)), grid.dims - 1);
+ for (int z = lo.z; z <= hi.z; ++z)
+ for (int y = lo.y; y <= hi.y; ++y)
+ for (int x = lo.x; x <= hi.x; ++x) {
+ const glm::vec3 d = grid.position(x, y, z) - p;
+ const float q = glm::dot(d, inv * d);
+ if (q < 9.0f) grid.values[grid.index(x, y, z)] += alpha * std::exp(-0.5f * q);
+ }
+ ++used;
+ }
+ if (used == 0) return fail("No splats are opaque enough - lower the minimum opacity");
+
+ std::vector<uint8_t> solid = solidifyShell(grid, 0.3f, closeRadius, false);
+ Mesh m = meshFromSolid(grid, solid, std::clamp(o.smoothIterations, 0, 50));
+ if (m.triangleCount() == 0) return fail("No closed surface was found - try a larger close radius");
+ return m;
+}
+
+SplatCloud meshToSplats(const Mesh& mesh, const MeshToSplatsOptions& o) {
+ SplatCloud cloud;
+ cloud.name = "Sculpt";
+ const auto& P = mesh.positions;
+ if (mesh.triangleCount() == 0 || o.count == 0) return cloud;
+
+ // Per-vertex normals and a cavity estimate (how far the neighbour average
+ // sits above the surface) from the triangle list alone.
+ std::vector<glm::vec3> normals(P.size(), glm::vec3(0.0f)), ring(P.size(), glm::vec3(0.0f));
+ std::vector<float> ringCount(P.size(), 0.0f), edgeLen(P.size(), 0.0f);
+ std::vector<double> cumulative;
+ cumulative.reserve(mesh.triangleCount());
+ double total = 0.0;
+ for (const auto& t : mesh.triangles) {
+ const glm::vec3 n = glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x]);
+ const uint32_t v[3] = {t.x, t.y, t.z};
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t a = v[k], b = v[(k + 1) % 3], c = v[(k + 2) % 3];
+ normals[a] += n;
+ ring[a] += P[b] + P[c];
+ ringCount[a] += 2.0f;
+ edgeLen[a] += glm::distance(P[a], P[b]) + glm::distance(P[a], P[c]);
+ }
+ total += 0.5 * double(glm::length(n));
+ cumulative.push_back(total);
+ }
+ std::vector<float> shade(P.size(), 1.0f);
+ for (size_t v = 0; v < P.size(); ++v) {
+ const float len = glm::length(normals[v]);
+ normals[v] = len > 0.0f ? normals[v] / len : glm::vec3(0, 1, 0);
+ if (!o.shading || ringCount[v] == 0.0f) continue;
+ const glm::vec3 avg = ring[v] / ringCount[v];
+ const float edge = std::max(edgeLen[v] / ringCount[v], 1e-12f);
+ const float k = glm::dot(normals[v], avg - P[v]) / edge; // > 0 in creases
+ const float cavity = std::clamp(1.0f - 3.0f * k, 0.45f, 1.1f);
+ const float sky = 0.5f + 0.5f * normals[v].y;
+ const float key = std::max(0.0f, glm::dot(normals[v], glm::normalize(glm::vec3(0.4f, 0.8f, 0.45f))));
+ shade[v] = cavity * (0.55f + 0.3f * sky + 0.25f * key);
+ }
+
+ const float spacing = float(std::sqrt(total / double(o.count)));
+ cloud.resize(o.count, 0);
+ std::mt19937 rng(12345);
+ std::uniform_real_distribution<double> pick(0.0, total);
+ std::uniform_real_distribution<float> unit(0.0f, 1.0f);
+ for (size_t i = 0; i < o.count; ++i) {
+ const size_t tri = size_t(std::upper_bound(cumulative.begin(), cumulative.end(), pick(rng)) - cumulative.begin());
+ const auto& t = mesh.triangles[std::min(tri, mesh.triangleCount() - 1)];
+ float a = unit(rng), b = unit(rng);
+ if (a + b > 1.0f) {
+ a = 1.0f - a;
+ b = 1.0f - b;
+ }
+ const float c = 1.0f - a - b;
+ const glm::vec3 n = glm::normalize(c * normals[t.x] + a * normals[t.y] + b * normals[t.z] + glm::vec3(1e-9f));
+ cloud.positions[i] = c * P[t.x] + a * P[t.y] + b * P[t.z];
+ cloud.rotations[i] = rotationFromZ(n);
+ cloud.scales[i] = glm::vec3(spacing * 0.6f, spacing * 0.6f, spacing * 0.08f);
+ cloud.opacities[i] = 0.95f;
+ const float lit = c * shade[t.x] + a * shade[t.y] + b * shade[t.z];
+ cloud.setColor(i, glm::clamp(o.color * lit, glm::vec3(0.0f), glm::vec3(1.0f)));
+ }
+ return cloud;
+}
+
+} // namespace sf
diff --git a/src/core/Splats.h b/src/core/Splats.h
new file mode 100644
index 00000000..7f4a8acb
--- /dev/null
+++ b/src/core/Splats.h
@@ -0,0 +1,118 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// 3D Gaussian splats: the capture format behind Polycam, Luma, Postshot,
+// Scaniverse, KIRI and friends, and now a first-class type in OpenUSD 26.03
+// (ParticleField3DGaussianSplat) and glTF (KHR_gaussian_splatting).
+//
+// SculptForge uses splats three ways:
+// - as a live reference: load a phone capture and sculpt next to/over it
+// - as a source: convert a capture into a watertight, sculptable mesh
+// - as an output: turn a sculpt into splats for splat-based viewers/engines
+//
+// Values are stored the way USD and glTF store them: linear scales (standard
+// deviations), linear opacity, unit quaternions, and spherical-harmonic
+// coefficients grouped per splat with the DC term first. PLY files (log
+// scales, logit opacity) are converted on load and save.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <glm/glm.hpp>
+#include <glm/gtc/quaternion.hpp>
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+constexpr float kShC0 = 0.28209479177387814f; // band-0 spherical harmonic
+
+struct SplatCloud {
+ std::vector<glm::vec3> positions;
+ std::vector<glm::quat> rotations;
+ std::vector<glm::vec3> scales;
+ std::vector<float> opacities;
+ int shDegree = 0;
+ std::vector<glm::vec3> sh; // shCount() coefficients per splat, DC first
+ // Placement in the scene (rotation, translation and uniform scale). Kept
+ // separate so exports to USD/glTF stay lossless; PLY export bakes it.
+ glm::mat4 transform{1.0f};
+ std::string name = "Splats";
+
+ size_t size() const { return positions.size(); }
+ bool empty() const { return positions.empty(); }
+ int shCount() const { return (shDegree + 1) * (shDegree + 1); }
+ void resize(size_t n, int degree);
+ void clear() { *this = SplatCloud(); }
+
+ glm::vec3 color(size_t i) const { return glm::vec3(0.5f) + kShC0 * sh[i * size_t(shCount())]; }
+ void setColor(size_t i, const glm::vec3& rgb) { sh[i * size_t(shCount())] = (rgb - glm::vec3(0.5f)) / kShC0; }
+ glm::vec3 worldPosition(size_t i) const { return glm::vec3(transform * glm::vec4(positions[i], 1.0f)); }
+ // Bounds in world space; `keepFraction` < 1 ignores outliers per axis.
+ AABB bounds(float keepFraction = 1.0f) const;
+ // Empty string when all arrays agree in size.
+ std::string validate() const;
+
+ // Uniform scale and rotation of `transform`.
+ float transformScale() const;
+ glm::quat transformRotation() const;
+ // Bakes `transform` into the splats. View-dependent colour (SH degree >= 1)
+ // is dropped when the rotation is not identity, because it would point the
+ // wrong way. Returns false if SH data was dropped.
+ bool bakeTransform();
+ // Removes splats by predicate; keeps every array in sync.
+ template <class Pred> size_t removeIf(Pred pred);
+};
+
+// Drops faint and outlying splats (floaters). Returns how many were removed.
+size_t cleanSplats(SplatCloud& cloud, float minOpacity, float keepFraction);
+
+// Rotates the cloud's placement; `degrees` about X, then Y, then Z, around the cloud centre.
+void rotateSplats(SplatCloud& cloud, const glm::vec3& degrees);
+// Moves and scales the cloud so its main body is centred at the origin with
+// radius ~1 (matching a new sphere).
+void fitSplats(SplatCloud& cloud);
+
+struct SplatToMeshOptions {
+ int resolution = 192; // voxels across the longest side
+ float minOpacity = 0.25f; // ignore fainter splats
+ float keepFraction = 0.97f; // ignore positional outliers (per axis)
+ int closeRadius = 2; // seal holes up to this many voxels
+ int smoothIterations = 6;
+};
+// Builds a watertight sculpting mesh from a capture (largest solid only).
+Mesh splatsToMesh(const SplatCloud& cloud, const SplatToMeshOptions& options, std::string* error = nullptr);
+
+struct MeshToSplatsOptions {
+ size_t count = 250'000;
+ glm::vec3 color{0.80f, 0.55f, 0.45f}; // clay
+ bool shading = true; // bake soft light and cavity darkening into the colour
+};
+// Covers the surface with flat, oriented splats (surfels).
+SplatCloud meshToSplats(const Mesh& mesh, const MeshToSplatsOptions& options);
+
+template <class Pred> size_t SplatCloud::removeIf(Pred pred) {
+ const size_t k = size_t(shCount());
+ size_t w = 0;
+ for (size_t i = 0; i < size(); ++i) {
+ if (pred(i)) continue;
+ if (w != i) {
+ positions[w] = positions[i];
+ rotations[w] = rotations[i];
+ scales[w] = scales[i];
+ opacities[w] = opacities[i];
+ for (size_t c = 0; c < k; ++c) sh[w * k + c] = sh[i * k + c];
+ }
+ ++w;
+ }
+ const size_t removed = size() - w;
+ positions.resize(w);
+ rotations.resize(w);
+ scales.resize(w);
+ opacities.resize(w);
+ sh.resize(w * k);
+ return removed;
+}
+
+} // namespace sf
diff --git a/src/core/Undo.cpp b/src/core/Undo.cpp
new file mode 100644
index 00000000..6c622230
--- /dev/null
+++ b/src/core/Undo.cpp
@@ -0,0 +1,72 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Undo.h"
+
+#include <utility>
+
+namespace sf {
+
+size_t UndoRecord::approxBytes() const {
+ size_t bytes = indices.size() * sizeof(uint32_t) + positions.size() * sizeof(glm::vec3);
+ if (mesh)
+ bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +
+ 8 * sizeof(uint32_t)) +
+ mesh->triangleCount() * (sizeof(glm::uvec3) + sizeof(glm::vec3) + 4 * sizeof(uint32_t));
+ return bytes;
+}
+
+void UndoStack::push(UndoRecord record) {
+ if (record.empty()) return;
+ undo_.push_back(std::move(record));
+ redo_.clear();
+ enforceBudget();
+}
+
+// Swaps the record's state with the mesh, so the record now holds the inverse.
+void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {
+ if (r.mesh) {
+ std::swap(*r.mesh, mesh);
+ mesh.topologyDirty = true;
+ bvh.build(mesh);
+ return;
+ }
+ auto& target = mesh.layerTarget(r.layer);
+ for (size_t i = 0; i < r.indices.size(); ++i) std::swap(target[r.indices[i]], r.positions[i]);
+ mesh.evaluate(r.indices);
+ mesh.updateNormals(r.indices);
+ bvh.refit(mesh, r.indices);
+}
+
+bool UndoStack::undo(Mesh& mesh, BVH& bvh) {
+ if (undo_.empty()) return false;
+ UndoRecord r = std::move(undo_.back());
+ undo_.pop_back();
+ apply(r, mesh, bvh);
+ redo_.push_back(std::move(r));
+ return true;
+}
+
+bool UndoStack::redo(Mesh& mesh, BVH& bvh) {
+ if (redo_.empty()) return false;
+ UndoRecord r = std::move(redo_.back());
+ redo_.pop_back();
+ apply(r, mesh, bvh);
+ undo_.push_back(std::move(r));
+ return true;
+}
+
+void UndoStack::clear() {
+ undo_.clear();
+ redo_.clear();
+}
+
+void UndoStack::enforceBudget() {
+ size_t total = 0;
+ for (const auto& r : undo_) total += r.approxBytes();
+ while (undo_.size() > 1 && total > byteBudget) {
+ total -= undo_.front().approxBytes();
+ undo_.pop_front();
+ }
+}
+
+} // namespace sf
diff --git a/src/core/Undo.h b/src/core/Undo.h
new file mode 100644
index 00000000..3ad74f12
--- /dev/null
+++ b/src/core/Undo.h
@@ -0,0 +1,51 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/BVH.h"
+#include "core/Mesh.h"
+
+#include <deque>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+// One undoable step. Either a sparse set of per-vertex values of the stroke's
+// target array (positions, layer base or a layer's offsets; see
+// Mesh::layerTarget) or a full mesh snapshot (topology/layer-set changes).
+struct UndoRecord {
+ std::string label;
+ int layer = -1;
+ std::vector<uint32_t> indices;
+ std::vector<glm::vec3> positions;
+ std::unique_ptr<Mesh> mesh;
+
+ bool empty() const { return indices.empty() && !mesh; }
+ size_t approxBytes() const;
+};
+
+class UndoStack {
+public:
+ void push(UndoRecord record);
+ bool canUndo() const { return !undo_.empty(); }
+ bool canRedo() const { return !redo_.empty(); }
+ const std::string& undoLabel() const { return undo_.back().label; }
+ const std::string& redoLabel() const { return redo_.back().label; }
+
+ // Both rebuild/refit the BVH as needed.
+ bool undo(Mesh& mesh, BVH& bvh);
+ bool redo(Mesh& mesh, BVH& bvh);
+ void clear();
+
+ size_t byteBudget = size_t(1) << 30; // 1 GiB
+
+private:
+ static void apply(UndoRecord& r, Mesh& mesh, BVH& bvh);
+ void enforceBudget();
+
+ std::deque<UndoRecord> undo_, redo_;
+};
+
+} // namespace sf
diff --git a/src/core/Voxel.cpp b/src/core/Voxel.cpp
new file mode 100644
index 00000000..81f17abb
--- /dev/null
+++ b/src/core/Voxel.cpp
@@ -0,0 +1,289 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Voxel.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+// Running max (dilate) or min (erode) over a window of +-radius along one axis.
+void filterAxis(std::vector<uint8_t>& data, const glm::ivec3& dims, int axis, int radius, bool dilate) {
+ const glm::ivec3 step(1, dims.x, dims.x * dims.y);
+ const int n = dims[axis];
+ const int u = (axis + 1) % 3, v = (axis + 2) % 3;
+ std::vector<uint8_t> line(static_cast<size_t>(n)), out(static_cast<size_t>(n));
+ for (int b = 0; b < dims[v]; ++b)
+ for (int a = 0; a < dims[u]; ++a) {
+ const size_t start = size_t(a) * size_t(step[u]) + size_t(b) * size_t(step[v]);
+ for (int i = 0; i < n; ++i) line[size_t(i)] = data[start + size_t(i) * size_t(step[axis])];
+ for (int i = 0; i < n; ++i) {
+ uint8_t r = line[size_t(i)];
+ for (int k = std::max(0, i - radius); k <= std::min(n - 1, i + radius); ++k)
+ r = dilate ? std::max(r, line[size_t(k)]) : std::min(r, line[size_t(k)]);
+ out[size_t(i)] = r;
+ }
+ for (int i = 0; i < n; ++i) data[start + size_t(i) * size_t(step[axis])] = out[size_t(i)];
+ }
+}
+
+void morph(std::vector<uint8_t>& data, const glm::ivec3& dims, int radius, bool dilate) {
+ if (radius <= 0) return;
+ for (int axis = 0; axis < 3; ++axis) filterAxis(data, dims, axis, radius, dilate);
+}
+
+// Labels 6-connected regions where data[i] == value, starting from `seeds`.
+void floodFill(const std::vector<uint8_t>& data, uint8_t value, const glm::ivec3& dims, std::vector<uint32_t>& stack,
+ std::vector<uint8_t>& reached) {
+ const int64_t sx = 1, sy = dims.x, sz = int64_t(dims.x) * dims.y;
+ while (!stack.empty()) {
+ const uint32_t i = stack.back();
+ stack.pop_back();
+ const int x = int(i % uint32_t(dims.x));
+ const int y = int((i / uint32_t(dims.x)) % uint32_t(dims.y));
+ const int z = int(i / uint32_t(sz));
+ auto visit = [&](bool inRange, int64_t offset) {
+ if (!inRange) return;
+ const uint32_t j = uint32_t(int64_t(i) + offset);
+ if (!reached[j] && data[j] == value) {
+ reached[j] = 1;
+ stack.push_back(j);
+ }
+ };
+ visit(x > 0, -sx);
+ visit(x + 1 < dims.x, sx);
+ visit(y > 0, -sy);
+ visit(y + 1 < dims.y, sy);
+ visit(z > 0, -sz);
+ visit(z + 1 < dims.z, sz);
+ }
+}
+
+void blurAxis(std::vector<float>& f, const glm::ivec3& dims, int axis) {
+ static const std::array<float, 5> w = [] {
+ std::array<float, 5> k{};
+ float sum = 0.0f;
+ for (int i = 0; i < 5; ++i) sum += k[size_t(i)] = std::exp(-0.5f * float((i - 2) * (i - 2)));
+ for (float& x : k) x /= sum;
+ return k;
+ }();
+ const glm::ivec3 step(1, dims.x, dims.x * dims.y);
+ const int n = dims[axis];
+ const int u = (axis + 1) % 3, v = (axis + 2) % 3;
+ std::vector<float> line(static_cast<size_t>(n));
+ for (int b = 0; b < dims[v]; ++b)
+ for (int a = 0; a < dims[u]; ++a) {
+ const size_t start = size_t(a) * size_t(step[u]) + size_t(b) * size_t(step[v]);
+ for (int i = 0; i < n; ++i) line[size_t(i)] = f[start + size_t(i) * size_t(step[axis])];
+ for (int i = 0; i < n; ++i) {
+ float s = 0.0f;
+ for (int k = -2; k <= 2; ++k) s += w[size_t(k + 2)] * line[size_t(std::clamp(i + k, 0, n - 1))];
+ f[start + size_t(i) * size_t(step[axis])] = s;
+ }
+ }
+}
+
+} // namespace
+
+bool makeVoxelGrid(const AABB& box, int resolution, int padding, VoxelGrid& grid, size_t maxCells) {
+ if (!box.valid()) return false;
+ resolution = std::max(resolution, 4);
+ const glm::vec3 ext = glm::max(box.extent(), glm::vec3(1e-6f));
+ const float cell = std::max({ext.x, ext.y, ext.z}) / float(resolution);
+ glm::ivec3 dims = glm::ivec3(glm::ceil(ext / cell)) + 1 + 2 * padding;
+ if (double(dims.x) * dims.y * dims.z > double(maxCells)) return false;
+ grid.dims = dims;
+ grid.cell = cell;
+ grid.origin = box.center() - glm::vec3(dims - 1) * 0.5f * cell;
+ grid.values.assign(grid.size(), 0.0f);
+ return true;
+}
+
+std::vector<uint8_t> solidifyShell(const VoxelGrid& shell, float threshold, int closeRadius, bool keepAllParts) {
+ const glm::ivec3 dims = shell.dims;
+ const size_t n = shell.size();
+ std::vector<uint8_t> wall(n);
+ for (size_t i = 0; i < n; ++i) wall[i] = shell.values[i] > threshold ? 1 : 0;
+ morph(wall, dims, closeRadius, true);
+
+ // Flood the empty space from the grid border; whatever it can't reach is inside.
+ std::vector<uint8_t> outside(n, 0);
+ std::vector<uint32_t> stack;
+ for (int z = 0; z < dims.z; ++z)
+ for (int y = 0; y < dims.y; ++y)
+ for (int x = 0; x < dims.x; ++x) {
+ const bool border = x == 0 || y == 0 || z == 0 || x == dims.x - 1 || y == dims.y - 1 || z == dims.z - 1;
+ const size_t i = shell.index(x, y, z);
+ if (border && !wall[i] && !outside[i]) {
+ outside[i] = 1;
+ stack.push_back(uint32_t(i));
+ }
+ }
+ floodFill(wall, 0, dims, stack, outside);
+
+ std::vector<uint8_t> solid(n);
+ for (size_t i = 0; i < n; ++i) solid[i] = outside[i] ? 0 : 1;
+ morph(solid, dims, closeRadius, false); // undo the gap-closing dilation
+
+ if (!keepAllParts) {
+ // Keep the largest connected piece (captures are full of floaters).
+ std::vector<uint32_t> label(n, 0);
+ const int64_t sy = dims.x, sz = int64_t(dims.x) * dims.y;
+ uint32_t current = 0, bestLabel = 0;
+ size_t bestCount = 0;
+ for (size_t seed = 0; seed < n; ++seed) {
+ if (!solid[seed] || label[seed]) continue;
+ label[seed] = ++current;
+ stack.assign(1, uint32_t(seed));
+ size_t count = 0;
+ while (!stack.empty()) {
+ const uint32_t i = stack.back();
+ stack.pop_back();
+ ++count;
+ const int x = int(i % uint32_t(dims.x));
+ const int y = int((i / uint32_t(dims.x)) % uint32_t(dims.y));
+ const int z = int(i / uint32_t(sz));
+ const int64_t offsets[6] = {-1, 1, -sy, sy, -sz, sz};
+ const bool valid[6] = {x > 0, x + 1 < dims.x, y > 0, y + 1 < dims.y, z > 0, z + 1 < dims.z};
+ for (int k = 0; k < 6; ++k) {
+ if (!valid[k]) continue;
+ const uint32_t j = uint32_t(int64_t(i) + offsets[k]);
+ if (solid[j] && !label[j]) {
+ label[j] = current;
+ stack.push_back(j);
+ }
+ }
+ }
+ if (count > bestCount) {
+ bestCount = count;
+ bestLabel = current;
+ }
+ }
+ for (size_t i = 0; i < n; ++i) solid[i] = label[i] == bestLabel && bestLabel ? 1 : 0;
+ }
+ return solid;
+}
+
+Mesh meshFromSolid(const VoxelGrid& grid, const std::vector<uint8_t>& solid, int smoothIterations) {
+ const glm::ivec3 dims = grid.dims;
+ std::vector<float> f(solid.begin(), solid.end());
+ for (int axis = 0; axis < 3; ++axis) blurAxis(f, dims, axis);
+ constexpr float iso = 0.5f;
+
+ // One vertex per cell that the surface passes through (surface nets).
+ const glm::ivec3 cells = dims - 1;
+ std::vector<int32_t> cellVertex(size_t(cells.x) * size_t(cells.y) * size_t(cells.z), -1);
+ auto cellIndex = [&](int x, int y, int z) { return (size_t(z) * size_t(cells.y) + size_t(y)) * size_t(cells.x) + size_t(x); };
+ Mesh m;
+ for (int z = 0; z < cells.z; ++z)
+ for (int y = 0; y < cells.y; ++y)
+ for (int x = 0; x < cells.x; ++x) {
+ std::array<float, 8> c;
+ int inside = 0;
+ for (int k = 0; k < 8; ++k) {
+ c[size_t(k)] = f[grid.index(x + (k & 1), y + ((k >> 1) & 1), z + ((k >> 2) & 1))];
+ inside += c[size_t(k)] > iso;
+ }
+ if (inside == 0 || inside == 8) continue;
+ glm::vec3 sum(0.0f);
+ int crossings = 0;
+ for (int a = 0; a < 8; ++a)
+ for (int bit = 1; bit < 8; bit <<= 1) {
+ if (a & bit) continue;
+ const int b = a | bit;
+ const float fa = c[size_t(a)], fb = c[size_t(b)];
+ if ((fa > iso) == (fb > iso)) continue;
+ const float t = (iso - fa) / (fb - fa);
+ const glm::vec3 pa(a & 1, (a >> 1) & 1, (a >> 2) & 1);
+ const glm::vec3 pb(b & 1, (b >> 1) & 1, (b >> 2) & 1);
+ sum += glm::mix(pa, pb, t);
+ ++crossings;
+ }
+ cellVertex[cellIndex(x, y, z)] = int32_t(m.positions.size());
+ m.positions.push_back(grid.position(x, y, z) + sum / float(crossings) * grid.cell);
+ }
+
+ // One quad per grid edge with a sign change, joining the four cells around it.
+ for (int z = 0; z < dims.z; ++z)
+ for (int y = 0; y < dims.y; ++y)
+ for (int x = 0; x < dims.x; ++x) {
+ const glm::ivec3 p(x, y, z);
+ const bool in0 = f[grid.index(x, y, z)] > iso;
+ for (int axis = 0; axis < 3; ++axis) {
+ glm::ivec3 q = p;
+ q[axis] += 1;
+ if (q[axis] >= dims[axis]) continue;
+ const bool in1 = f[grid.index(q.x, q.y, q.z)] > iso;
+ if (in0 == in1) continue;
+ const int u = (axis + 1) % 3, v = (axis + 2) % 3;
+ if (p[u] < 1 || p[v] < 1 || p[u] > cells[u] - 1 || p[v] > cells[v] - 1 || p[axis] > cells[axis] - 1)
+ continue;
+ std::array<int32_t, 4> quad;
+ const int du[4] = {-1, 0, 0, -1}, dv[4] = {-1, -1, 0, 0};
+ bool ok = true;
+ for (int k = 0; k < 4; ++k) {
+ glm::ivec3 c = p;
+ c[u] += du[k];
+ c[v] += dv[k];
+ quad[size_t(k)] = cellVertex[cellIndex(c.x, c.y, c.z)];
+ ok &= quad[size_t(k)] >= 0;
+ }
+ if (!ok) continue;
+ if (!in0) std::swap(quad[1], quad[3]); // outward normal must point to the outside sample
+ const auto& P = m.positions;
+ const bool diag02 = glm::distance(P[size_t(quad[0])], P[size_t(quad[2])]) <=
+ glm::distance(P[size_t(quad[1])], P[size_t(quad[3])]);
+ const glm::uvec4 qq(quad[0], quad[1], quad[2], quad[3]);
+ if (diag02) {
+ m.triangles.push_back({qq.x, qq.y, qq.z});
+ m.triangles.push_back({qq.x, qq.z, qq.w});
+ } else {
+ m.triangles.push_back({qq.x, qq.y, qq.w});
+ m.triangles.push_back({qq.y, qq.z, qq.w});
+ }
+ }
+ }
+ m.rebuildTopology();
+ taubinSmooth(m, smoothIterations);
+ m.recomputeAllNormals();
+ return m;
+}
+
+void rasterizeMeshShell(const Mesh& mesh, VoxelGrid& grid) {
+ const auto& P = mesh.positions;
+ for (const auto& t : mesh.triangles) {
+ const glm::vec3 a = (P[t.x] - grid.origin) / grid.cell;
+ const glm::vec3 b = (P[t.y] - grid.origin) / grid.cell;
+ const glm::vec3 c = (P[t.z] - grid.origin) / grid.cell;
+ const float longest = std::max({glm::distance(a, b), glm::distance(b, c), glm::distance(c, a)});
+ const int steps = std::max(1, int(std::ceil(longest * 2.0f)));
+ for (int i = 0; i <= steps; ++i)
+ for (int j = 0; i + j <= steps; ++j) {
+ const float u = float(i) / float(steps), v = float(j) / float(steps);
+ const glm::ivec3 s(glm::round(a + (b - a) * u + (c - a) * v));
+ if (glm::any(glm::lessThan(s, glm::ivec3(0))) || glm::any(glm::greaterThanEqual(s, grid.dims))) continue;
+ grid.values[grid.index(s.x, s.y, s.z)] = 1.0f;
+ }
+ }
+}
+
+Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error) {
+ VoxelGrid grid;
+ if (mesh.triangleCount() == 0 || !makeVoxelGrid(mesh.bounds(), resolution, 4, grid)) {
+ if (error) *error = mesh.triangleCount() == 0 ? "The mesh is empty" : "Resolution too high for this mesh";
+ return {};
+ }
+ rasterizeMeshShell(mesh, grid);
+ std::vector<uint8_t> solid = solidifyShell(grid, 0.5f, 1, true);
+ Mesh out = meshFromSolid(grid, solid, 4);
+ if (out.triangleCount() == 0 && error) *error = "Remesh produced no surface";
+ // Voxels touched by the surface count as solid, which puts the result half a voxel outside.
+ for (size_t v = 0; v < out.vertexCount(); ++v) out.positions[v] -= out.normals[v] * (0.5f * grid.cell);
+ out.recomputeAllNormals();
+ return out;
+}
+
+} // namespace sf
diff --git a/src/core/Voxel.h b/src/core/Voxel.h
new file mode 100644
index 00000000..23dd0f66
--- /dev/null
+++ b/src/core/Voxel.h
@@ -0,0 +1,52 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Voxel toolkit shared by the voxel remesher (DynaMesh-style: merge parts and
+// even out topology), splat-to-mesh conversion and future boolean tools:
+// rasterise a surface "shell" into a grid, close small gaps, flood-fill the
+// outside to get a watertight solid, then extract a smooth surface with
+// surface nets.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct VoxelGrid {
+ glm::ivec3 dims{0};
+ glm::vec3 origin{0.0f}; // world position of sample (0,0,0)
+ float cell = 1.0f; // sample spacing
+ std::vector<float> values;
+
+ size_t index(int x, int y, int z) const { return (size_t(z) * size_t(dims.y) + size_t(y)) * size_t(dims.x) + size_t(x); }
+ size_t size() const { return size_t(dims.x) * size_t(dims.y) * size_t(dims.z); }
+ glm::vec3 position(int x, int y, int z) const { return origin + glm::vec3(x, y, z) * cell; }
+};
+
+// A zeroed grid covering `box` with `resolution` cells along its longest side
+// and `padding` empty cells around it. Returns false if the grid would exceed
+// `maxCells`.
+bool makeVoxelGrid(const AABB& box, int resolution, int padding, VoxelGrid& grid, size_t maxCells = 400'000'000);
+
+// Converts a shell (cells with value > threshold) into a watertight solid:
+// gaps up to `closeRadius` cells are closed, the outside is flood-filled from
+// the grid border, and only the largest solid piece is kept (drops floaters)
+// unless `keepAllParts`. Returns 1 for inside cells, 0 outside.
+std::vector<uint8_t> solidifyShell(const VoxelGrid& shell, float threshold, int closeRadius, bool keepAllParts = false);
+
+// Smooth surface of a solid occupancy grid (blurred, iso 0.5, surface nets),
+// followed by `smoothIterations` of Taubin smoothing. Triangles face outwards.
+Mesh meshFromSolid(const VoxelGrid& grid, const std::vector<uint8_t>& solid, int smoothIterations);
+
+// Marks the shell of a triangle mesh in `grid` (value 1 where the surface passes).
+void rasterizeMeshShell(const Mesh& mesh, VoxelGrid& grid);
+
+// Rebuilds the mesh as an even, watertight surface (`resolution` cells across
+// its longest side). Overlapping parts are merged. Sculpt layers are baked.
+Mesh voxelRemesh(const Mesh& mesh, int resolution, std::string* error = nullptr);
+
+} // namespace sf
diff --git a/src/io/FbxIO.cpp b/src/io/FbxIO.cpp
new file mode 100644
index 00000000..0f243eb8
--- /dev/null
+++ b/src/io/FbxIO.cpp
@@ -0,0 +1,537 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/FbxIO.h"
+
+#include "ufbx.h"
+
+#include <cstring>
+#include <map>
+#include <filesystem>
+#include <fstream>
+#include <variant>
+
+namespace sf {
+
+namespace {
+
+// ---------------------------------------------------------------- binary node tree
+
+struct Property {
+ char type;
+ std::vector<uint8_t> bytes; // encoded payload (after the type code)
+};
+
+struct Node {
+ std::string name;
+ std::vector<Property> props;
+ std::vector<Node> children;
+
+ Node(std::string n = {}) : name(std::move(n)) {}
+
+ template <class T> static void put(std::vector<uint8_t>& out, T v) {
+ uint8_t b[sizeof(T)];
+ std::memcpy(b, &v, sizeof(T)); // FBX is little-endian; so are all platforms we ship on
+ out.insert(out.end(), b, b + sizeof(T));
+ }
+ Node& i16(int16_t v) { return scalar('Y', v); }
+ Node& b(bool v) { return scalar('C', uint8_t(v ? 1 : 0)); }
+ Node& i32(int32_t v) { return scalar('I', v); }
+ Node& f64(double v) { return scalar('D', v); }
+ Node& f32(float v) { return scalar('F', v); }
+ Node& i64(int64_t v) { return scalar('L', v); }
+ Node& str(const std::string& s) {
+ Property p{'S', {}};
+ put(p.bytes, uint32_t(s.size()));
+ p.bytes.insert(p.bytes.end(), s.begin(), s.end());
+ props.push_back(std::move(p));
+ return *this;
+ }
+ // "Name\x00\x01Class": how objects carry their name and class in one string.
+ Node& objName(const std::string& n, const std::string& cls) { return str(n + std::string("\x00\x01", 2) + cls); }
+ Node& raw(const std::vector<uint8_t>& data) {
+ Property p{'R', {}};
+ put(p.bytes, uint32_t(data.size()));
+ p.bytes.insert(p.bytes.end(), data.begin(), data.end());
+ props.push_back(std::move(p));
+ return *this;
+ }
+ template <class T> Node& array(char type, const std::vector<T>& v) {
+ Property p{type, {}};
+ put(p.bytes, uint32_t(v.size()));
+ put(p.bytes, uint32_t(0)); // not compressed
+ put(p.bytes, uint32_t(v.size() * sizeof(T)));
+ const auto* d = reinterpret_cast<const uint8_t*>(v.data());
+ p.bytes.insert(p.bytes.end(), d, d + v.size() * sizeof(T));
+ props.push_back(std::move(p));
+ return *this;
+ }
+ Node& f64s(const std::vector<double>& v) { return array('d', v); }
+ Node& i32s(const std::vector<int32_t>& v) { return array('i', v); }
+
+ Node& add(std::string childName) {
+ children.emplace_back(std::move(childName));
+ return children.back();
+ }
+
+ template <class T> Node& scalar(char type, T v) {
+ Property p{type, {}};
+ put(p.bytes, v);
+ props.push_back(std::move(p));
+ return *this;
+ }
+
+ // FBX 7.4 record: endOffset, propertyCount, propertyBytes (uint32), name length (uint8), name,
+ // properties, children, and a 13-byte zero record closing the child list.
+ // Null-record rule as in real-world files: always after children; for a bare node (no properties,
+ // no children) unless it is the last in its list.
+ void write(std::vector<uint8_t>& out, bool isLast = false) const {
+ const size_t start = out.size();
+ put(out, uint32_t(0)); // end offset, patched below
+ put(out, uint32_t(props.size()));
+ size_t propBytes = 0;
+ for (const auto& p : props) propBytes += 1 + p.bytes.size();
+ put(out, uint32_t(propBytes));
+ out.push_back(uint8_t(name.size()));
+ out.insert(out.end(), name.begin(), name.end());
+ for (const auto& p : props) {
+ out.push_back(uint8_t(p.type));
+ out.insert(out.end(), p.bytes.begin(), p.bytes.end());
+ }
+ if (!children.empty()) {
+ for (size_t i = 0; i < children.size(); ++i) children[i].write(out, i + 1 == children.size());
+ out.insert(out.end(), 13, 0);
+ } else if (props.empty() && !isLast) {
+ out.insert(out.end(), 13, 0);
+ }
+ const uint32_t end = uint32_t(out.size());
+ std::memcpy(out.data() + start, &end, 4);
+ }
+};
+
+// Properties70 entry: P: "Name", "Type", "Label", "Flags", values...
+Node& prop70(Node& p70, const std::string& name, const std::string& type, const std::string& label,
+ const std::string& flags) {
+ return p70.add("P").str(name).str(type).str(label).str(flags);
+}
+
+// ---------------------------------------------------------------- scene
+
+struct Ids {
+ int64_t next = 1000000;
+ int64_t operator()() { return next++; }
+};
+
+void addConnection(Node& connections, const char* kind, int64_t child, int64_t parent) {
+ connections.add("C").str(kind).i64(child).i64(parent);
+}
+
+void addHeader(Node& root) {
+ Node& ext = root.add("FBXHeaderExtension");
+ ext.add("FBXHeaderVersion").i32(1003);
+ ext.add("FBXVersion").i32(7400);
+ ext.add("EncryptionType").i32(0);
+ Node& ts = ext.add("CreationTimeStamp");
+ ts.add("Version").i32(1000);
+ ts.add("Year").i32(1970);
+ ts.add("Month").i32(1);
+ ts.add("Day").i32(1);
+ ts.add("Hour").i32(10);
+ ts.add("Minute").i32(0);
+ ts.add("Second").i32(0);
+ ts.add("Millisecond").i32(0);
+ ext.add("Creator").str("SculptForge");
+ Node& info = ext.add("SceneInfo").objName("GlobalInfo", "SceneInfo").str("UserData");
+ info.add("Type").str("UserData");
+ info.add("Version").i32(100);
+ Node& meta = info.add("MetaData");
+ meta.add("Version").i32(100);
+ meta.add("Title").str("");
+ meta.add("Subject").str("");
+ meta.add("Author").str("");
+ meta.add("Keywords").str("");
+ meta.add("Revision").str("");
+ meta.add("Comment").str("");
+ Node& p70 = info.add("Properties70");
+ prop70(p70, "DocumentUrl", "KString", "Url", "").str("");
+ prop70(p70, "SrcDocumentUrl", "KString", "Url", "").str("");
+ prop70(p70, "Original", "Compound", "", "");
+ prop70(p70, "Original|ApplicationVendor", "KString", "", "").str("SculptForge");
+ prop70(p70, "Original|ApplicationName", "KString", "", "").str("SculptForge");
+ prop70(p70, "Original|ApplicationVersion", "KString", "", "").str("0.1");
+
+ // FileId and CreationTime must agree with the footer for some readers; these fixed
+ // values are the ones widely used by open-source writers.
+ static const uint8_t fileId[16] = {0x28, 0xb3, 0x2a, 0xeb, 0xb6, 0x24, 0xcc, 0xc2,
+ 0xbf, 0xc8, 0xb0, 0x2a, 0xa9, 0x2b, 0xfc, 0xf1};
+ root.add("FileId").raw(std::vector<uint8_t>(fileId, fileId + 16));
+ root.add("CreationTime").str("1970-01-01 10:00:00:000");
+ root.add("Creator").str("SculptForge");
+}
+
+void addGlobalSettings(Node& root) {
+ Node& gs = root.add("GlobalSettings");
+ gs.add("Version").i32(1000);
+ Node& p70 = gs.add("Properties70");
+ prop70(p70, "UpAxis", "int", "Integer", "").i32(1);
+ prop70(p70, "UpAxisSign", "int", "Integer", "").i32(1);
+ prop70(p70, "FrontAxis", "int", "Integer", "").i32(2);
+ prop70(p70, "FrontAxisSign", "int", "Integer", "").i32(1);
+ prop70(p70, "CoordAxis", "int", "Integer", "").i32(0);
+ prop70(p70, "CoordAxisSign", "int", "Integer", "").i32(1);
+ prop70(p70, "OriginalUpAxis", "int", "Integer", "").i32(1);
+ prop70(p70, "OriginalUpAxisSign", "int", "Integer", "").i32(1);
+ prop70(p70, "UnitScaleFactor", "double", "Number", "").f64(1.0);
+ prop70(p70, "OriginalUnitScaleFactor", "double", "Number", "").f64(1.0);
+ prop70(p70, "AmbientColor", "ColorRGB", "Color", "").f64(0).f64(0).f64(0);
+ prop70(p70, "DefaultCamera", "KString", "", "").str("Producer Perspective");
+ prop70(p70, "TimeMode", "enum", "", "").i32(11);
+ prop70(p70, "TimeSpanStart", "KTime", "Time", "").i64(0);
+ prop70(p70, "TimeSpanStop", "KTime", "Time", "").i64(46186158000);
+ prop70(p70, "CustomFrameRate", "double", "Number", "").f64(24.0);
+}
+
+// Geometry for one mesh: positions, polygons, per-corner normals, smoothing, one material.
+Node makeGeometry(int64_t id, const std::string& name, const Mesh& mesh, float scale) {
+ Node g("Geometry");
+ g.i64(id).objName(name, "Geometry").str("Mesh");
+ g.add("Properties70");
+ g.add("GeometryVersion").i32(124);
+
+ const auto& base = mesh.basePositions();
+ std::vector<double> verts;
+ verts.reserve(base.size() * 3);
+ for (const auto& p : base) verts.insert(verts.end(), {double(p.x * scale), double(p.y * scale), double(p.z * scale)});
+ g.add("Vertices").f64s(verts);
+
+ std::vector<int32_t> poly;
+ poly.reserve(mesh.triangleCount() * 3);
+ for (const auto& t : mesh.triangles) poly.insert(poly.end(), {int32_t(t.x), int32_t(t.y), ~int32_t(t.z)});
+ g.add("PolygonVertexIndex").i32s(poly);
+
+ // Normals of the base shape, per polygon corner.
+ Mesh shape;
+ shape.positions = base;
+ shape.triangles = mesh.triangles;
+ shape.rebuildTopology();
+ shape.recomputeAllNormals();
+ std::vector<double> normals;
+ normals.reserve(mesh.triangleCount() * 9);
+ for (const auto& t : mesh.triangles)
+ for (uint32_t v : {t.x, t.y, t.z}) {
+ const glm::vec3& n = shape.normals[v];
+ normals.insert(normals.end(), {double(n.x), double(n.y), double(n.z)});
+ }
+ Node& ln = g.add("LayerElementNormal").i32(0);
+ ln.add("Version").i32(101);
+ ln.add("Name").str("");
+ ln.add("MappingInformationType").str("ByPolygonVertex");
+ ln.add("ReferenceInformationType").str("Direct");
+ ln.add("Normals").f64s(normals);
+
+ Node& ls = g.add("LayerElementSmoothing").i32(0);
+ ls.add("Version").i32(102);
+ ls.add("Name").str("");
+ ls.add("MappingInformationType").str("ByPolygon");
+ ls.add("ReferenceInformationType").str("Direct");
+ ls.add("Smoothing").i32s(std::vector<int32_t>(mesh.triangleCount(), 1));
+
+ Node& lm = g.add("LayerElementMaterial").i32(0);
+ lm.add("Version").i32(101);
+ lm.add("Name").str("");
+ lm.add("MappingInformationType").str("AllSame");
+ lm.add("ReferenceInformationType").str("IndexToDirect");
+ lm.add("Materials").i32s({0});
+
+ Node& layer = g.add("Layer").i32(0);
+ layer.add("Version").i32(100);
+ for (const char* type : {"LayerElementNormal", "LayerElementSmoothing", "LayerElementMaterial"}) {
+ Node& le = layer.add("LayerElement");
+ le.add("Type").str(type);
+ le.add("TypedIndex").i32(0);
+ }
+ return g;
+}
+
+Node makeModel(int64_t id, const std::string& name, const std::string& type) {
+ Node m("Model");
+ m.i64(id).objName(name, "Model").str(type);
+ m.add("Version").i32(232);
+ Node& p70 = m.add("Properties70");
+ prop70(p70, "DefaultAttributeIndex", "int", "Integer", "").i32(0);
+ prop70(p70, "InheritType", "enum", "", "").i32(1);
+ m.add("MultiLayer").i32(0);
+ m.add("MultiTake").i32(0);
+ m.add("Shading").b(true);
+ m.add("Culling").str("CullingOff");
+ return m;
+}
+
+} // namespace
+
+bool saveFbx(const std::string& path, const std::string& name, const std::vector<const Mesh*>& lods,
+ const FbxExportOptions& o, std::string& error) {
+ if (lods.empty() || !lods[0] || lods[0]->triangleCount() == 0) {
+ error = "The mesh is empty";
+ return false;
+ }
+ Ids ids;
+ Node root;
+ addHeader(root);
+ addGlobalSettings(root);
+
+ Node& documents = root.add("Documents");
+ documents.add("Count").i32(1);
+ const int64_t docId = ids();
+ Node& document = documents.add("Document").i64(docId).str("Scene").str("Scene");
+ prop70(document.add("Properties70"), "SourceObject", "object", "", "");
+ document.add("RootNode").i64(0);
+ root.add("References");
+
+ Node definitions("Definitions");
+ Node objects("Objects");
+ Node connections("Connections");
+ int models = 0, geometries = 0, deformers = 0, attributes = 0;
+
+ // Material shared by every LOD.
+ const int64_t materialId = ids();
+ {
+ Node& mat = objects.add("Material").i64(materialId).objName(o.materialName, "Material").str("");
+ mat.add("Version").i32(102);
+ mat.add("ShadingModel").str("Phong");
+ mat.add("MultiLayer").i32(0);
+ Node& p70 = mat.add("Properties70");
+ prop70(p70, "DiffuseColor", "Color", "", "A").f64(o.color.x).f64(o.color.y).f64(o.color.z);
+ prop70(p70, "Diffuse", "Vector3D", "Vector", "").f64(o.color.x).f64(o.color.y).f64(o.color.z);
+ prop70(p70, "SpecularFactor", "Number", "", "A").f64(0.2);
+ prop70(p70, "Shininess", "double", "Number", "").f64(20.0);
+ prop70(p70, "ShininessExponent", "double", "Number", "").f64(20.0);
+ }
+
+ const bool grouped = lods.size() > 1;
+ int64_t parentId = 0;
+ if (grouped) {
+ const int64_t groupId = ids(), attrId = ids();
+ Node attr("NodeAttribute");
+ attr.i64(attrId).objName("", "NodeAttribute").str("LodGroup");
+ Node& p70 = attr.add("Properties70");
+ prop70(p70, "MinMaxDistance", "bool", "", "").i32(0);
+ prop70(p70, "MinDistance", "double", "Number", "").f64(-100.0);
+ prop70(p70, "MaxDistance", "double", "Number", "").f64(100.0);
+ prop70(p70, "WorldSpace", "bool", "", "").i32(0);
+ prop70(p70, "ThresholdsUsedAsPercentage", "bool", "", "").i32(1);
+ for (size_t i = 1; i < lods.size(); ++i)
+ prop70(p70, "Thresholds|Level" + std::to_string(i - 1), "Distance", "", "")
+ .f32(100.0f / float(1u << i))
+ .str("cm");
+ for (size_t i = 0; i < lods.size(); ++i)
+ prop70(p70, "DisplayLevels|Level" + std::to_string(i), "enum", "", "").i32(0);
+ attr.add("TypeFlags").str("LodGroup");
+ objects.children.push_back(std::move(attr));
+ objects.children.push_back(makeModel(groupId, name, "LodGroup"));
+ addConnection(connections, "OO", attrId, groupId);
+ addConnection(connections, "OO", groupId, 0);
+ parentId = groupId;
+ ++models;
+ ++attributes;
+ }
+
+ for (size_t level = 0; level < lods.size(); ++level) {
+ const Mesh& mesh = *lods[level];
+ const std::string meshName = grouped ? name + "_LOD" + std::to_string(level) : name;
+ const int64_t modelId = ids(), geometryId = ids();
+ objects.children.push_back(makeGeometry(geometryId, meshName, mesh, o.scale));
+ objects.children.push_back(makeModel(modelId, meshName, "Mesh"));
+ addConnection(connections, "OO", geometryId, modelId);
+ addConnection(connections, "OO", materialId, modelId);
+ if (grouped) {
+ // Like Maya/FBX SDK files: LOD group -> one Null per level -> the level's mesh.
+ const int64_t levelId = ids(), levelAttrId = ids();
+ Node attr("NodeAttribute");
+ attr.i64(levelAttrId).objName("", "NodeAttribute").str("Null");
+ attr.add("TypeFlags").str("Null");
+ objects.children.push_back(std::move(attr));
+ objects.children.push_back(makeModel(levelId, "LOD_" + std::to_string(level), "Null"));
+ addConnection(connections, "OO", levelAttrId, levelId);
+ addConnection(connections, "OO", levelId, parentId);
+ addConnection(connections, "OO", modelId, levelId);
+ ++models;
+ ++attributes;
+ } else {
+ addConnection(connections, "OO", modelId, parentId);
+ }
+ ++models;
+ ++geometries;
+
+ // Sculpt layers -> blend shape channels (LOD0 only).
+ if (level == 0 && o.layers && !mesh.layers.empty()) {
+ const int64_t blendId = ids();
+ Node& blend = objects.add("Deformer").i64(blendId).objName(meshName, "Deformer").str("BlendShape");
+ blend.add("Version").i32(100);
+ addConnection(connections, "OO", blendId, geometryId);
+ ++deformers;
+ for (const auto& layer : mesh.layers) {
+ const int64_t channelId = ids(), shapeId = ids();
+ Node& channel = objects.add("Deformer").i64(channelId).objName(layer.name, "SubDeformer").str("BlendShapeChannel");
+ channel.add("Version").i32(100);
+ channel.add("DeformPercent").f64(double(layer.weight) * 100.0);
+
+ std::vector<int32_t> indexes;
+ std::vector<double> offsets;
+ for (uint32_t v = 0; v < layer.delta.size(); ++v) {
+ if (layer.delta[v] == glm::vec3(0.0f)) continue;
+ indexes.push_back(int32_t(v));
+ const glm::vec3 d = layer.delta[v] * o.scale;
+ offsets.insert(offsets.end(), {double(d.x), double(d.y), double(d.z)});
+ }
+ if (indexes.empty()) {
+ indexes.push_back(0);
+ offsets.insert(offsets.end(), {0.0, 0.0, 0.0});
+ }
+ channel.add("FullWeights").f64s(std::vector<double>(indexes.size(), 100.0));
+ Node& shape = objects.add("Geometry").i64(shapeId).objName(layer.name, "Geometry").str("Shape");
+ shape.add("Properties70");
+ shape.add("Version").i32(100);
+ shape.add("Indexes").i32s(indexes);
+ shape.add("Vertices").f64s(offsets);
+ std::vector<double> shapeNormals(offsets.size(), 0.0);
+ shapeNormals[0] = 1.1e-6; // all-zero shape normals break some importers (Unity)
+ shape.add("Normals").f64s(shapeNormals);
+ addConnection(connections, "OO", shapeId, channelId);
+ addConnection(connections, "OO", channelId, blendId);
+ ++deformers;
+ ++geometries;
+ }
+ }
+ }
+
+ // Definitions: object type counts (property templates are optional).
+ definitions.add("Version").i32(100);
+ const int total = 1 + models + geometries + 1 + deformers + attributes;
+ definitions.add("Count").i32(total);
+ auto defType = [&](const char* type, int count) {
+ if (count == 0) return;
+ Node& t = definitions.add("ObjectType").str(type);
+ t.add("Count").i32(count);
+ };
+ defType("GlobalSettings", 1);
+ defType("Model", models);
+ defType("Geometry", geometries);
+ defType("Material", 1);
+ defType("Deformer", deformers);
+ defType("NodeAttribute", attributes);
+
+ root.children.push_back(std::move(definitions));
+ root.children.push_back(std::move(objects));
+ root.children.push_back(std::move(connections));
+ Node& takes = root.add("Takes");
+ takes.add("Current").str("");
+
+ // File: header, top-level records, closing null record, footer.
+ std::vector<uint8_t> out;
+ const char magic[] = "Kaydara FBX Binary ";
+ out.insert(out.end(), magic, magic + sizeof magic); // includes the terminating zero
+ out.push_back(0x1A);
+ out.push_back(0x00);
+ Node::put(out, uint32_t(7400));
+ for (const auto& n : root.children) n.write(out);
+ out.insert(out.end(), 13, 0); // end of the top-level list
+ static const uint8_t footerId[16] = {0xfa, 0xbc, 0xab, 0x09, 0xd0, 0xc8, 0xd4, 0x66,
+ 0xb1, 0x76, 0xfb, 0x83, 0x1c, 0xf7, 0x26, 0x7e};
+ out.insert(out.end(), footerId, footerId + 16);
+ out.insert(out.end(), 4, 0);
+ size_t pad = ((out.size() + 15) & ~size_t(15)) - out.size();
+ if (pad == 0) pad = 16;
+ out.insert(out.end(), pad, 0);
+ Node::put(out, uint32_t(7400));
+ out.insert(out.end(), 120, 0);
+ static const uint8_t footerMagic[16] = {0xf8, 0x5a, 0x8c, 0x6a, 0xde, 0xf5, 0xd9, 0x7e,
+ 0xec, 0xe9, 0x0c, 0xe3, 0x75, 0x8f, 0x29, 0x0b};
+ out.insert(out.end(), footerMagic, footerMagic + 16);
+
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(out.data()), std::streamsize(out.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+namespace {
+
+// True if `node` sits under a LOD group via any child other than the first (LOD0).
+bool isLowerLod(const ufbx_node* node) {
+ for (const ufbx_node* n = node; n && n->parent; n = n->parent) {
+ const ufbx_node* p = n->parent;
+ if (p->attrib_type != UFBX_ELEMENT_LOD_GROUP) continue;
+ if (p->children.count > 0 && p->children.data[0] != n) return true;
+ }
+ return false;
+}
+
+glm::vec3 toVec(const ufbx_vec3& v) { return {float(v.x), float(v.y), float(v.z)}; }
+
+} // namespace
+
+bool loadFbx(const std::string& path, Mesh& out, std::string& error) {
+ ufbx_load_opts opts = {};
+ opts.target_axes = ufbx_axes_right_handed_y_up;
+ opts.target_unit_meters = 1.0;
+ opts.space_conversion = UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY;
+ ufbx_error err;
+ ufbx_scene* scene = ufbx_load_file_len(path.data(), path.size(), &opts, &err);
+ if (!scene) {
+ char buf[512];
+ ufbx_format_error(buf, sizeof buf, &err);
+ error = "Cannot read FBX: " + std::string(buf);
+ return false;
+ }
+ Mesh m;
+ std::vector<SculptLayer> layers;
+ std::map<std::string, size_t> layerIndex;
+ std::vector<uint32_t> tri;
+ for (size_t ni = 0; ni < scene->nodes.count; ++ni) {
+ const ufbx_node* node = scene->nodes.data[ni];
+ const ufbx_mesh* mesh = node->mesh;
+ if (!mesh || !node->visible || isLowerLod(node)) continue;
+ const uint32_t base = uint32_t(m.positions.size());
+ const ufbx_matrix& xf = node->geometry_to_world;
+ const ufbx_vec3 origin = ufbx_transform_position(&xf, ufbx_vec3{0, 0, 0});
+ for (size_t v = 0; v < mesh->vertices.count; ++v) m.positions.push_back(toVec(ufbx_transform_position(&xf, mesh->vertices.data[v])));
+ tri.resize(mesh->max_face_triangles * 3);
+ for (size_t f = 0; f < mesh->faces.count; ++f) {
+ const uint32_t n = ufbx_triangulate_face(tri.data(), tri.size(), mesh, mesh->faces.data[f]);
+ for (uint32_t t = 0; t < n; ++t)
+ m.triangles.push_back(glm::uvec3(base + mesh->vertex_indices.data[tri[t * 3]], base + mesh->vertex_indices.data[tri[t * 3 + 1]],
+ base + mesh->vertex_indices.data[tri[t * 3 + 2]]));
+ }
+ for (auto& l : layers) l.delta.resize(m.positions.size(), glm::vec3(0.0f));
+ for (size_t d = 0; d < mesh->blend_deformers.count; ++d) {
+ const ufbx_blend_deformer* blend = mesh->blend_deformers.data[d];
+ for (size_t c = 0; c < blend->channels.count; ++c) {
+ const ufbx_blend_channel* ch = blend->channels.data[c];
+ const ufbx_blend_shape* shape = ch->target_shape;
+ if (!shape) continue;
+ const std::string name(ch->name.data, ch->name.length);
+ auto [it, inserted] = layerIndex.try_emplace(name, layers.size());
+ if (inserted) layers.push_back({name, std::vector<glm::vec3>(m.positions.size(), glm::vec3(0.0f)), float(ch->weight)});
+ SculptLayer& layer = layers[it->second];
+ for (size_t k = 0; k < shape->num_offsets; ++k) {
+ const uint32_t v = shape->offset_vertices.data[k];
+ if (v >= mesh->vertices.count) continue;
+ const ufbx_vec3 moved = ufbx_transform_position(&xf, shape->position_offsets.data[k]);
+ layer.delta[base + v] = toVec(moved) - toVec(origin);
+ }
+ }
+ }
+ }
+ ufbx_free_scene(scene);
+ if (m.triangles.empty()) {
+ error = "No meshes found in " + path;
+ return false;
+ }
+ for (auto& l : layers) l.delta.resize(m.positions.size(), glm::vec3(0.0f));
+ out = weldImported(m, layers);
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/FbxIO.h b/src/io/FbxIO.h
new file mode 100644
index 00000000..22741831
--- /dev/null
+++ b/src/io/FbxIO.h
@@ -0,0 +1,39 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Binary FBX (7.4) export, written from the publicly documented file layout
+// (no Autodesk SDK, so it can ship under the GPL). FBX is still what Unreal
+// Engine imports most completely:
+// - the sculpt as a triangle mesh with per-corner normals, smoothing and a
+// material slot
+// - sculpt layers as blend shapes (Unreal: morph targets on a skeletal mesh)
+// - a LOD chain as an FBX LOD group (Unreal: LOD0..N of one static mesh)
+// Import uses ufbx (third_party/ufbx).
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct FbxExportOptions {
+ float scale = 1.0f; // applied to positions and layer offsets
+ std::string materialName = "M_Clay"; // becomes the engine's material slot
+ glm::vec3 color{0.80f, 0.55f, 0.45f};
+ bool layers = true; // export sculpt layers as blend shapes (on LOD0)
+};
+
+// `lods[0]` is the full-resolution mesh. With more than one entry the meshes
+// are grouped under an FBX LOD group named `name`. Units are centimetres
+// (FBX default) and the scene is Y-up; importers convert to their own axes.
+bool saveFbx(const std::string& path, const std::string& name, const std::vector<const Mesh*>& lods,
+ const FbxExportOptions& options, std::string& error);
+
+// Reads .fbx (binary or ASCII, any version) via ufbx: all visible meshes are
+// merged in world space (Y-up, 1 unit = 1 m, matching saveFbx with scale 100),
+// only LOD0 of LOD groups is taken, and blend shapes become sculpt layers.
+bool loadFbx(const std::string& path, Mesh& out, std::string& error);
+
+} // namespace sf
diff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cpp
new file mode 100644
index 00000000..fc269454
--- /dev/null
+++ b/src/io/GltfIO.cpp
@@ -0,0 +1,617 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/GltfIO.h"
+
+#include "core/Json.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+#include <glm/gtc/quaternion.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+#include <cmath>
+#include <functional>
+#include <iterator>
+#include <map>
+#include <unordered_map>
+
+#include <array>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+std::string jsonEscape(const std::string& s) {
+ std::string out;
+ for (char c : s) {
+ if (c == '"' || c == '\\') out += '\\';
+ if (static_cast<unsigned char>(c) < 0x20) continue;
+ out += c;
+ }
+ return out;
+}
+
+struct BinWriter {
+ std::vector<uint8_t> data;
+ // Appends 4-byte aligned data and returns its byte offset.
+ size_t append(const void* src, size_t bytes) {
+ size_t offset = data.size();
+ data.resize(offset + bytes);
+ std::memcpy(data.data() + offset, src, bytes);
+ while (data.size() % 4) data.push_back(0);
+ return offset;
+ }
+};
+
+void minMax(const std::vector<glm::vec3>& v, glm::vec3& lo, glm::vec3& hi) {
+ lo = glm::vec3(std::numeric_limits<float>::max());
+ hi = glm::vec3(std::numeric_limits<float>::lowest());
+ for (const auto& p : v) {
+ lo = glm::min(lo, p);
+ hi = glm::max(hi, p);
+ }
+ if (v.empty()) lo = hi = glm::vec3(0.0f);
+}
+
+std::string vec3Json(const glm::vec3& v) {
+ std::ostringstream s;
+ s.precision(9);
+ s << "[" << v.x << "," << v.y << "," << v.z << "]";
+ return s.str();
+}
+
+bool writeGlbFile(const std::string& path, std::string jsonStr, const std::vector<uint8_t>& bin, std::string& error) {
+ while (jsonStr.size() % 4) jsonStr += ' ';
+ const uint32_t totalLength = 12 + 8 + uint32_t(jsonStr.size()) + 8 + uint32_t(bin.size());
+ std::ofstream file(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!file) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ auto u32 = [&](uint32_t v) { file.write(reinterpret_cast<const char*>(&v), 4); };
+ u32(0x46546C67); // "glTF"
+ u32(2);
+ u32(totalLength);
+ u32(uint32_t(jsonStr.size()));
+ u32(0x4E4F534A); // "JSON"
+ file.write(jsonStr.data(), std::streamsize(jsonStr.size()));
+ u32(uint32_t(bin.size()));
+ u32(0x004E4942); // "BIN\0"
+ file.write(reinterpret_cast<const char*>(bin.data()), std::streamsize(bin.size()));
+ if (!file) {
+ error = "Write failed for " + path;
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error) {
+ if (mesh.triangleCount() == 0) {
+ error = "Mesh is empty";
+ return false;
+ }
+
+ // Base shape and its normals.
+ Mesh baseMesh;
+ baseMesh.positions = mesh.basePositions();
+ baseMesh.triangles = mesh.triangles;
+ baseMesh.rebuildTopology();
+ baseMesh.recomputeAllNormals();
+
+ BinWriter bin;
+ struct View {
+ size_t offset, length;
+ bool indices;
+ };
+ std::vector<View> views;
+ std::ostringstream accessors;
+ int accessorCount = 0;
+
+ auto addVec3 = [&](const std::vector<glm::vec3>& v, bool withMinMax) {
+ size_t off = bin.append(v.data(), v.size() * sizeof(glm::vec3));
+ views.push_back({off, v.size() * sizeof(glm::vec3), false});
+ accessors << (accessorCount ? "," : "") << "{\"bufferView\":" << views.size() - 1
+ << ",\"componentType\":5126,\"count\":" << v.size() << ",\"type\":\"VEC3\"";
+ if (withMinMax) {
+ glm::vec3 lo, hi;
+ minMax(v, lo, hi);
+ accessors << ",\"min\":" << vec3Json(lo) << ",\"max\":" << vec3Json(hi);
+ }
+ accessors << "}";
+ return accessorCount++;
+ };
+
+ int posAcc = addVec3(baseMesh.positions, true);
+ int nrmAcc = addVec3(baseMesh.normals, false);
+
+ size_t idxOff = bin.append(mesh.triangles.data(), mesh.triangleCount() * sizeof(glm::uvec3));
+ views.push_back({idxOff, mesh.triangleCount() * sizeof(glm::uvec3), true});
+ accessors << ",{\"bufferView\":" << views.size() - 1 << ",\"componentType\":5125,\"count\":"
+ << mesh.triangleCount() * 3 << ",\"type\":\"SCALAR\"}";
+ int idxAcc = accessorCount++;
+
+ std::vector<int> targetAccs;
+ for (const auto& l : mesh.layers) targetAccs.push_back(addVec3(l.delta, true));
+
+ std::ostringstream json;
+ json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"scene\":0,"
+ << "\"scenes\":[{\"nodes\":[0]}],\"nodes\":[{\"mesh\":0,\"name\":\"" << jsonEscape(name) << "\"}],"
+ << "\"meshes\":[{\"name\":\"" << jsonEscape(name) << "\",\"primitives\":[{\"attributes\":{\"POSITION\":"
+ << posAcc << ",\"NORMAL\":" << nrmAcc << "},\"indices\":" << idxAcc << ",\"mode\":4";
+ if (!mesh.layers.empty()) {
+ json << ",\"targets\":[";
+ for (size_t i = 0; i < targetAccs.size(); ++i) json << (i ? "," : "") << "{\"POSITION\":" << targetAccs[i] << "}";
+ json << "]";
+ }
+ json << "}]";
+ if (!mesh.layers.empty()) {
+ json << ",\"weights\":[";
+ for (size_t i = 0; i < mesh.layers.size(); ++i) json << (i ? "," : "") << mesh.layers[i].weight;
+ json << "],\"extras\":{\"targetNames\":[";
+ for (size_t i = 0; i < mesh.layers.size(); ++i)
+ json << (i ? "," : "") << "\"" << jsonEscape(mesh.layers[i].name) << "\"";
+ json << "]}";
+ }
+ json << "}],\"accessors\":[" << accessors.str() << "],\"bufferViews\":[";
+ for (size_t i = 0; i < views.size(); ++i)
+ json << (i ? "," : "") << "{\"buffer\":0,\"byteOffset\":" << views[i].offset << ",\"byteLength\":"
+ << views[i].length << ",\"target\":" << (views[i].indices ? 34963 : 34962) << "}";
+ json << "],\"buffers\":[{\"byteLength\":" << bin.data.size() << "}]}";
+
+ return writeGlbFile(path, json.str(), bin.data, error);
+}
+
+bool saveSplatGlb(const std::string& path, const SplatCloud& c, std::string& error) {
+ if (c.empty()) {
+ error = "There are no splats to export";
+ return false;
+ }
+ if (std::string v = c.validate(); !v.empty()) {
+ error = v;
+ return false;
+ }
+ BinWriter bin;
+ std::ostringstream accessors, views;
+ int count = 0;
+ auto add = [&](const std::vector<float>& data, const char* type, bool withMinMax, const std::vector<glm::vec3>* v3) {
+ const size_t off = bin.append(data.data(), data.size() * sizeof(float));
+ views << (count ? "," : "") << "{\"buffer\":0,\"byteOffset\":" << off << ",\"byteLength\":"
+ << data.size() * sizeof(float) << ",\"target\":34962}";
+ accessors << (count ? "," : "") << "{\"bufferView\":" << count << ",\"componentType\":5126,\"count\":" << c.size()
+ << ",\"type\":\"" << type << "\"";
+ if (withMinMax && v3) {
+ glm::vec3 lo, hi;
+ minMax(*v3, lo, hi);
+ accessors << ",\"min\":" << vec3Json(lo) << ",\"max\":" << vec3Json(hi);
+ }
+ accessors << "}";
+ return count++;
+ };
+ auto flat3 = [](const std::vector<glm::vec3>& v) {
+ std::vector<float> f;
+ f.reserve(v.size() * 3);
+ for (const auto& x : v) f.insert(f.end(), {x.x, x.y, x.z});
+ return f;
+ };
+ const size_t K = size_t(c.shCount());
+ std::vector<float> rot, color, sh0;
+ for (size_t i = 0; i < c.size(); ++i) {
+ const glm::quat& q = c.rotations[i];
+ rot.insert(rot.end(), {q.x, q.y, q.z, q.w});
+ const glm::vec3 rgb = glm::clamp(c.color(i), glm::vec3(0.0f), glm::vec3(1.0f));
+ color.insert(color.end(), {rgb.x, rgb.y, rgb.z, c.opacities[i]});
+ sh0.insert(sh0.end(), {c.sh[i * K].x, c.sh[i * K].y, c.sh[i * K].z});
+ }
+ std::ostringstream attrs;
+ const std::string prefix = "\"KHR_gaussian_splatting:";
+ attrs << "\"POSITION\":" << add(flat3(c.positions), "VEC3", true, &c.positions);
+ attrs << ",\"COLOR_0\":" << add(color, "VEC4", false, nullptr);
+ attrs << "," << prefix << "ROTATION\":" << add(rot, "VEC4", false, nullptr);
+ attrs << "," << prefix << "SCALE\":" << add(flat3(c.scales), "VEC3", false, nullptr);
+ attrs << "," << prefix << "OPACITY\":" << add(c.opacities, "SCALAR", false, nullptr);
+ attrs << "," << prefix << "SH_DEGREE_0_COEF_0\":" << add(sh0, "VEC3", false, nullptr);
+ for (size_t k = 1; k < K; ++k) {
+ const int d = int(std::sqrt(double(k)) + 1e-9), m = int(k) - d * d;
+ std::vector<float> coef;
+ coef.reserve(c.size() * 3);
+ for (size_t i = 0; i < c.size(); ++i) coef.insert(coef.end(), {c.sh[i * K + k].x, c.sh[i * K + k].y, c.sh[i * K + k].z});
+ attrs << "," << prefix << "SH_DEGREE_" << d << "_COEF_" << m << "\":" << add(coef, "VEC3", false, nullptr);
+ }
+
+ std::ostringstream json;
+ json.precision(9);
+ json << "{\"asset\":{\"version\":\"2.0\",\"generator\":\"SculptForge\"},\"extensionsUsed\":[\"KHR_gaussian_splatting\"],"
+ << "\"scene\":0,\"scenes\":[{\"nodes\":[0]}],\"nodes\":[{\"mesh\":0,\"name\":\"" << jsonEscape(c.name) << "\"";
+ if (c.transform != glm::mat4(1.0f)) {
+ json << ",\"matrix\":[";
+ for (int i = 0; i < 16; ++i) json << (i ? "," : "") << glm::value_ptr(c.transform)[i];
+ json << "]";
+ }
+ json << "}],\"meshes\":[{\"name\":\"" << jsonEscape(c.name) << "\",\"primitives\":[{\"mode\":0,\"attributes\":{"
+ << attrs.str() << "},\"extensions\":{\"KHR_gaussian_splatting\":{\"kernel\":\"ellipse\","
+ << "\"colorSpace\":\"srgb_rec709_display\",\"projection\":\"perspective\",\"sortingMethod\":\"cameraDistance\"}}}]}],"
+ << "\"accessors\":[" << accessors.str() << "],\"bufferViews\":[" << views.str() << "],\"buffers\":[{\"byteLength\":"
+ << bin.data.size() << "}]}";
+ return writeGlbFile(path, json.str(), bin.data, error);
+}
+
+namespace {
+
+std::vector<uint8_t> base64Decode(const std::string& in) {
+ static const auto table = [] {
+ std::array<int, 256> t;
+ t.fill(-1);
+ const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ for (int i = 0; i < 64; ++i) t[uint8_t(chars[i])] = i;
+ return t;
+ }();
+ std::vector<uint8_t> out;
+ out.reserve(in.size() * 3 / 4);
+ int val = 0, bits = -8;
+ for (unsigned char c : in) {
+ if (table[c] < 0) continue;
+ val = (val << 6) | table[c];
+ bits += 6;
+ if (bits >= 0) {
+ out.push_back(uint8_t((val >> bits) & 0xff));
+ bits -= 8;
+ }
+ }
+ return out;
+}
+
+bool readFile(const std::filesystem::path& p, std::vector<uint8_t>& out) {
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return false;
+ out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
+ return true;
+}
+
+struct GltfReader {
+ Json doc;
+ std::vector<std::vector<uint8_t>> buffers;
+ std::string error;
+
+ // Reads accessor `index` as floats (VEC3) or indices (SCALAR); returns false on unsupported layouts.
+ bool readVec3(int index, std::vector<glm::vec3>& out) {
+ const Json& acc = doc["accessors"][size_t(index)];
+ if (acc["type"].asString() != "VEC3" || int(acc["componentType"].asNumber()) != 5126) {
+ error = "Only float VEC3 positions are supported";
+ return false;
+ }
+ const size_t count = size_t(acc["count"].asNumber());
+ out.assign(count, glm::vec3(0.0f));
+ if (acc["bufferView"].isNull()) return true; // all zeros (sparse not supported)
+ const uint8_t* base;
+ size_t stride, available;
+ if (!view(acc, 12, base, stride, available)) return false;
+ if (count && (count - 1) * stride + 12 > available) return fail("Accessor out of range");
+ for (size_t i = 0; i < count; ++i) std::memcpy(&out[i], base + i * stride, 12);
+ return true;
+ }
+
+ // Reads `components` values per element as floats, decoding normalized integers.
+ bool readFloats(int index, int components, std::vector<float>& out) {
+ const Json& acc = doc["accessors"][size_t(index)];
+ static const std::map<std::string, int> typeComponents = {{"SCALAR", 1}, {"VEC2", 2}, {"VEC3", 3}, {"VEC4", 4}};
+ auto tc = typeComponents.find(acc["type"].asString());
+ if (tc == typeComponents.end() || tc->second != components) return fail("Unexpected accessor type");
+ const int type = int(acc["componentType"].asNumber());
+ const size_t size = type == 5126 ? 4 : (type == 5122 || type == 5123) ? 2 : (type == 5120 || type == 5121) ? 1 : 0;
+ if (!size) return fail("Unsupported accessor component type");
+ const bool normalized = acc["normalized"].asBool(false);
+ const size_t count = size_t(acc["count"].asNumber());
+ out.assign(count * size_t(components), 0.0f);
+ if (acc["bufferView"].isNull()) return true;
+ const uint8_t* base;
+ size_t stride, available;
+ const size_t element = size * size_t(components);
+ if (!view(acc, element, base, stride, available)) return false;
+ if (count && (count - 1) * stride + element > available) return fail("Accessor out of range");
+ for (size_t i = 0; i < count; ++i)
+ for (int c = 0; c < components; ++c) {
+ const uint8_t* p = base + i * stride + size_t(c) * size;
+ float v = 0.0f;
+ switch (type) {
+ case 5126: std::memcpy(&v, p, 4); break;
+ case 5120: v = normalized ? std::max(float(int8_t(p[0])) / 127.0f, -1.0f) : float(int8_t(p[0])); break;
+ case 5121: v = normalized ? float(p[0]) / 255.0f : float(p[0]); break;
+ case 5122: {
+ int16_t x;
+ std::memcpy(&x, p, 2);
+ v = normalized ? std::max(float(x) / 32767.0f, -1.0f) : float(x);
+ break;
+ }
+ default: {
+ uint16_t x;
+ std::memcpy(&x, p, 2);
+ v = normalized ? float(x) / 65535.0f : float(x);
+ }
+ }
+ out[i * size_t(components) + size_t(c)] = v;
+ }
+ return true;
+ }
+
+ bool readIndices(int index, std::vector<uint32_t>& out) {
+ const Json& acc = doc["accessors"][size_t(index)];
+ const int type = int(acc["componentType"].asNumber());
+ const size_t size = type == 5125 ? 4 : type == 5123 ? 2 : type == 5121 ? 1 : 0;
+ if (!size) return fail("Unsupported index type");
+ const size_t count = size_t(acc["count"].asNumber());
+ const uint8_t* base;
+ size_t stride, available;
+ if (!view(acc, size, base, stride, available)) return false;
+ if (count && (count - 1) * stride + size > available) return fail("Accessor out of range");
+ out.resize(count);
+ for (size_t i = 0; i < count; ++i) {
+ const uint8_t* p = base + i * stride;
+ out[i] = size == 4 ? uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24)
+ : size == 2 ? uint32_t(p[0] | p[1] << 8)
+ : uint32_t(p[0]);
+ }
+ return true;
+ }
+
+ bool view(const Json& acc, size_t elementSize, const uint8_t*& base, size_t& stride, size_t& available) {
+ const Json& bv = doc["bufferViews"][size_t(acc["bufferView"].asNumber())];
+ const size_t buf = size_t(bv["buffer"].asNumber());
+ if (buf >= buffers.size()) return fail("Missing buffer");
+ const size_t viewOffset = size_t(bv["byteOffset"].asNumber());
+ const size_t viewLength = size_t(bv["byteLength"].asNumber());
+ const size_t accOffset = size_t(acc["byteOffset"].asNumber());
+ if (viewOffset + viewLength > buffers[buf].size() || accOffset > viewLength) return fail("Buffer view out of range");
+ base = buffers[buf].data() + viewOffset + accOffset;
+ stride = bv["byteStride"].isNumber() ? size_t(bv["byteStride"].asNumber()) : elementSize;
+ available = viewLength - accOffset;
+ return true;
+ }
+
+ bool fail(const std::string& msg) {
+ if (error.empty()) error = msg;
+ return false;
+ }
+};
+
+glm::mat4 nodeMatrix(const Json& node) {
+ if (node["matrix"].size() == 16) {
+ glm::mat4 m;
+ for (int i = 0; i < 16; ++i) glm::value_ptr(m)[i] = float(node["matrix"][size_t(i)].asNumber());
+ return m;
+ }
+ glm::mat4 m(1.0f);
+ const Json& t = node["translation"];
+ if (t.size() == 3)
+ m = glm::translate(m, glm::vec3(float(t[0].asNumber()), float(t[1].asNumber()), float(t[2].asNumber())));
+ const Json& r = node["rotation"];
+ if (r.size() == 4)
+ m *= glm::mat4_cast(glm::quat(float(r[3].asNumber()), float(r[0].asNumber()), float(r[1].asNumber()),
+ float(r[2].asNumber())));
+ const Json& s = node["scale"];
+ if (s.size() == 3) m = glm::scale(m, glm::vec3(float(s[0].asNumber()), float(s[1].asNumber()), float(s[2].asNumber())));
+ return m;
+}
+
+} // namespace
+
+bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud* splatsOut) {
+ const std::filesystem::path fsPath(std::u8string(path.begin(), path.end()));
+ std::vector<uint8_t> file;
+ if (!readFile(fsPath, file)) {
+ error = "Cannot open " + path;
+ return false;
+ }
+
+ GltfReader r;
+ std::string jsonText;
+ std::vector<uint8_t> glbBin;
+ bool hasGlbBin = false;
+ if (file.size() >= 12 && std::memcmp(file.data(), "glTF", 4) == 0) {
+ size_t offset = 12;
+ while (offset + 8 <= file.size()) {
+ uint32_t len, type;
+ std::memcpy(&len, file.data() + offset, 4);
+ std::memcpy(&type, file.data() + offset + 4, 4);
+ offset += 8;
+ if (offset + len > file.size()) {
+ error = "Truncated GLB file";
+ return false;
+ }
+ if (type == 0x4E4F534A) jsonText.assign(reinterpret_cast<const char*>(file.data() + offset), len);
+ else if (type == 0x004E4942) {
+ glbBin.assign(file.begin() + std::ptrdiff_t(offset), file.begin() + std::ptrdiff_t(offset + len));
+ hasGlbBin = true;
+ }
+ offset += (len + 3) & ~size_t(3);
+ }
+ } else {
+ jsonText.assign(file.begin(), file.end());
+ }
+ if (!Json::parse(jsonText, r.doc, error)) {
+ error = "Invalid glTF JSON: " + error;
+ return false;
+ }
+
+ for (size_t i = 0; i < r.doc["buffers"].size(); ++i) {
+ const std::string& uri = r.doc["buffers"][i]["uri"].asString();
+ std::vector<uint8_t> data;
+ if (uri.empty() && i == 0 && hasGlbBin) {
+ data = std::move(glbBin);
+ } else if (uri.rfind("data:", 0) == 0) {
+ size_t comma = uri.find(',');
+ if (comma == std::string::npos) {
+ error = "Bad data URI";
+ return false;
+ }
+ data = base64Decode(uri.substr(comma + 1));
+ } else if (!uri.empty()) {
+ if (uri.find("..") != std::string::npos || std::filesystem::path(uri).is_absolute()) {
+ error = "Refusing buffer path outside the model's folder: " + uri;
+ return false;
+ }
+ if (!readFile(fsPath.parent_path() / std::filesystem::path(uri), data)) {
+ error = "Missing buffer file: " + uri;
+ return false;
+ }
+ }
+ r.buffers.push_back(std::move(data));
+ }
+
+ Mesh m;
+ std::vector<std::vector<glm::vec3>> targetDeltas;
+ std::vector<std::string> targetNames;
+ std::vector<float> targetWeights;
+ bool targetsConsistent = true;
+
+ SplatCloud splats;
+ auto readSplats = [&](const Json& prim, const glm::mat4& world) -> bool {
+ const Json& at = prim["attributes"];
+ const char* prefix = "KHR_gaussian_splatting:";
+ auto attr = [&](const std::string& n) { return at[n].isNumber() ? int(at[n].asNumber()) : -1; };
+ const int pos = attr("POSITION"), rot = attr(std::string(prefix) + "ROTATION"),
+ scl = attr(std::string(prefix) + "SCALE"), opa = attr(std::string(prefix) + "OPACITY"),
+ dc = attr(std::string(prefix) + "SH_DEGREE_0_COEF_0");
+ if (pos < 0 || rot < 0 || scl < 0 || opa < 0 || dc < 0) return r.fail("Incomplete KHR_gaussian_splatting primitive");
+ std::vector<glm::vec3> p;
+ std::vector<float> q, sc, op, c0;
+ if (!r.readVec3(pos, p) || !r.readFloats(rot, 4, q) || !r.readFloats(scl, 3, sc) || !r.readFloats(opa, 1, op) ||
+ !r.readFloats(dc, 3, c0))
+ return false;
+ const size_t n = p.size();
+ if (q.size() != n * 4 || sc.size() != n * 3 || op.size() != n || c0.size() != n * 3)
+ return r.fail("KHR_gaussian_splatting attributes have different counts");
+ int degree = 0;
+ for (int d = 1; d <= 3; ++d) {
+ bool complete = true;
+ for (int m = 0; m < 2 * d + 1; ++m)
+ complete &= attr(std::string(prefix) + "SH_DEGREE_" + std::to_string(d) + "_COEF_" + std::to_string(m)) >= 0;
+ if (!complete) break;
+ degree = d;
+ }
+ splats.resize(n, degree);
+ const size_t K = size_t(splats.shCount());
+ for (size_t i = 0; i < n; ++i) {
+ splats.positions[i] = p[i];
+ glm::quat qq(q[i * 4 + 3], q[i * 4], q[i * 4 + 1], q[i * 4 + 2]); // glTF stores x, y, z, w
+ const float len = glm::length(qq);
+ splats.rotations[i] = len > 0.0f ? qq / len : glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
+ splats.scales[i] = glm::vec3(sc[i * 3], sc[i * 3 + 1], sc[i * 3 + 2]);
+ splats.opacities[i] = op[i];
+ splats.sh[i * K] = glm::vec3(c0[i * 3], c0[i * 3 + 1], c0[i * 3 + 2]);
+ }
+ for (size_t k = 1; k < K; ++k) {
+ const int d = int(std::sqrt(double(k)) + 1e-9), m = int(k) - d * d;
+ std::vector<float> coef;
+ if (!r.readFloats(attr(std::string(prefix) + "SH_DEGREE_" + std::to_string(d) + "_COEF_" + std::to_string(m)), 3, coef))
+ return false;
+ if (coef.size() != n * 3) return r.fail("KHR_gaussian_splatting SH count mismatch");
+ for (size_t i = 0; i < n; ++i) splats.sh[i * K + k] = glm::vec3(coef[i * 3], coef[i * 3 + 1], coef[i * 3 + 2]);
+ }
+ splats.transform = world;
+ return true;
+ };
+
+ std::function<bool(int, const glm::mat4&, int)> visit = [&](int nodeIndex, const glm::mat4& parent, int depth) {
+ if (depth > 64) return r.fail("Node hierarchy too deep");
+ const Json& node = r.doc["nodes"][size_t(nodeIndex)];
+ const glm::mat4 world = parent * nodeMatrix(node);
+ const glm::mat3 linear(world);
+ if (node["mesh"].isNumber()) {
+ const Json& mesh = r.doc["meshes"][size_t(node["mesh"].asNumber())];
+ for (const Json& prim : mesh["primitives"].items()) {
+ const Json& gs = prim["extensions"]["KHR_gaussian_splatting"];
+ if (gs.isObject()) {
+ if (splatsOut && splats.empty() && !readSplats(prim, world)) return false;
+ continue;
+ }
+ if (prim["mode"].isNumber() && int(prim["mode"].asNumber()) != 4) continue; // triangles only
+ if (!prim["attributes"]["POSITION"].isNumber()) continue;
+ std::vector<glm::vec3> pos;
+ if (!r.readVec3(int(prim["attributes"]["POSITION"].asNumber()), pos)) return false;
+ std::vector<uint32_t> idx;
+ if (prim["indices"].isNumber()) {
+ if (!r.readIndices(int(prim["indices"].asNumber()), idx)) return false;
+ } else {
+ idx.resize(pos.size());
+ for (uint32_t i = 0; i < idx.size(); ++i) idx[i] = i;
+ }
+ const uint32_t baseIndex = uint32_t(m.positions.size());
+ for (const auto& p : pos) m.positions.push_back(glm::vec3(world * glm::vec4(p, 1.0f)));
+ for (size_t t = 0; t + 2 < idx.size(); t += 3) {
+ if (idx[t] >= pos.size() || idx[t + 1] >= pos.size() || idx[t + 2] >= pos.size())
+ return r.fail("Index out of range");
+ m.triangles.push_back({baseIndex + idx[t], baseIndex + idx[t + 1], baseIndex + idx[t + 2]});
+ }
+
+ // Morph targets -> sculpt layers (only when every primitive has the same set).
+ const Json& targets = prim["targets"];
+ if (targetDeltas.empty() && baseIndex == 0) {
+ targetDeltas.resize(targets.size());
+ for (size_t k = 0; k < targets.size(); ++k) {
+ const Json& names = mesh["extras"]["targetNames"];
+ targetNames.push_back(names[k].isString() ? names[k].asString() : "Shape " + std::to_string(k + 1));
+ targetWeights.push_back(float(mesh["weights"][k].asNumber(0.0)));
+ }
+ } else if (targets.size() != targetDeltas.size()) {
+ targetsConsistent = false;
+ }
+ for (size_t k = 0; k < targetDeltas.size(); ++k) {
+ std::vector<glm::vec3> d(pos.size(), glm::vec3(0.0f));
+ if (k < targets.size() && targets[k]["POSITION"].isNumber() &&
+ !r.readVec3(int(targets[k]["POSITION"].asNumber()), d))
+ return false;
+ d.resize(pos.size(), glm::vec3(0.0f));
+ for (const auto& v : d) targetDeltas[k].push_back(linear * v);
+ }
+ }
+ }
+ for (const Json& child : node["children"].items())
+ if (!visit(int(child.asNumber()), world, depth + 1)) return false;
+ return true;
+ };
+
+ const Json& scenes = r.doc["scenes"];
+ if (scenes.size() > 0) {
+ const Json& scene = scenes[size_t(r.doc["scene"].asNumber(0))];
+ for (const Json& n : scene["nodes"].items())
+ if (!visit(int(n.asNumber()), glm::mat4(1.0f), 0)) {
+ error = r.error;
+ return false;
+ }
+ } else {
+ for (size_t i = 0; i < r.doc["nodes"].size(); ++i)
+ if (!visit(int(i), glm::mat4(1.0f), 0)) {
+ error = r.error;
+ return false;
+ }
+ }
+ if (splatsOut && !splats.empty()) {
+ auto stem = std::filesystem::path(fsPath).stem().u8string();
+ splats.name = std::string(stem.begin(), stem.end());
+ *splatsOut = std::move(splats);
+ if (m.triangles.empty()) {
+ out = Mesh();
+ return true;
+ }
+ }
+ if (m.triangles.empty()) {
+ error = r.error.empty() ? "No triangle meshes found in " + path : r.error;
+ return false;
+ }
+
+ // Weld vertices split along UV/normal seams so strokes don't tear the surface.
+ std::vector<SculptLayer> layers;
+ if (targetsConsistent)
+ for (size_t k = 0; k < targetDeltas.size(); ++k)
+ layers.push_back({targetNames[k], std::move(targetDeltas[k]), targetWeights[k]});
+ Mesh welded = weldImported(m, layers);
+ out = std::move(welded);
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/GltfIO.h b/src/io/GltfIO.h
new file mode 100644
index 00000000..7d2503f6
--- /dev/null
+++ b/src/io/GltfIO.h
@@ -0,0 +1,30 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+#include "core/Splats.h"
+
+#include <string>
+
+namespace sf {
+
+// Writes a binary glTF 2.0 (.glb). The base shape (all layers at zero) is the
+// mesh; each sculpt layer becomes a morph target with its current weight as
+// the default, and target names stored in mesh.extras.targetNames (the
+// convention read by Blender, Unity, Unreal, Godot and three.js).
+bool saveGlb(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error);
+
+// Reads .glb or .gltf (embedded/data-URI or external buffers). All triangle
+// primitives in the default scene are merged with their node transforms
+// applied, duplicate vertices along UV/normal seams are welded so the mesh can
+// be sculpted, and morph targets become sculpt layers.
+// With `splats`, a KHR_gaussian_splatting primitive is read into it too (the
+// first one found); a file with only splats then succeeds with an empty mesh.
+bool loadGltf(const std::string& path, Mesh& out, std::string& error, SplatCloud* splats = nullptr);
+
+// Writes Gaussian splats as a KHR_gaussian_splatting POINTS primitive (with a
+// COLOR_0 point-cloud fallback for viewers without splat support).
+bool saveSplatGlb(const std::string& path, const SplatCloud& splats, std::string& error);
+
+} // namespace sf
diff --git a/src/io/ObjIO.cpp b/src/io/ObjIO.cpp
new file mode 100644
index 00000000..a830ce81
--- /dev/null
+++ b/src/io/ObjIO.cpp
@@ -0,0 +1,118 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/ObjIO.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+std::filesystem::path utf8Path(const std::string& s) {
+ return std::filesystem::path(std::u8string(s.begin(), s.end()));
+}
+
+const char* skipSpace(const char* p, const char* end) {
+ while (p < end && (*p == ' ' || *p == '\t')) ++p;
+ return p;
+}
+
+} // namespace
+
+bool loadObj(const std::string& path, Mesh& out, std::string& error) {
+ std::ifstream file(utf8Path(path), std::ios::binary);
+ if (!file) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
+
+ Mesh m;
+ std::vector<uint32_t> poly;
+ const char* p = data.c_str();
+ const char* end = p + data.size();
+ size_t lineNo = 0;
+
+ while (p < end) {
+ const char* lineEnd = p;
+ while (lineEnd < end && *lineEnd != '\n') ++lineEnd;
+ ++lineNo;
+ std::string line(p, lineEnd); // null-terminated copy for strtof/strtol
+ p = lineEnd + 1;
+
+ const char* s = skipSpace(line.c_str(), line.c_str() + line.size());
+ if (s[0] == 'v' && (s[1] == ' ' || s[1] == '\t')) {
+ char* cur = const_cast<char*>(s + 1);
+ glm::vec3 v;
+ for (int i = 0; i < 3; ++i) {
+ char* next;
+ v[i] = std::strtof(cur, &next);
+ if (next == cur) {
+ error = "Malformed vertex on line " + std::to_string(lineNo);
+ return false;
+ }
+ cur = next;
+ }
+ m.positions.push_back(v);
+ } else if (s[0] == 'f' && (s[1] == ' ' || s[1] == '\t')) {
+ poly.clear();
+ char* cur = const_cast<char*>(s + 1);
+ while (true) {
+ char* next;
+ long idx = std::strtol(cur, &next, 10);
+ if (next == cur) break;
+ cur = next;
+ while (*cur && *cur != ' ' && *cur != '\t' && *cur != '\r') ++cur; // skip /vt/vn
+ long n = static_cast<long>(m.positions.size());
+ long resolved = idx > 0 ? idx - 1 : n + idx;
+ if (idx == 0 || resolved < 0 || resolved >= n) {
+ error = "Invalid face index on line " + std::to_string(lineNo);
+ return false;
+ }
+ poly.push_back(static_cast<uint32_t>(resolved));
+ }
+ for (size_t i = 2; i < poly.size(); ++i) m.triangles.push_back({poly[0], poly[i - 1], poly[i]});
+ }
+ }
+
+ if (m.triangles.empty()) {
+ error = "No faces found in " + path;
+ return false;
+ }
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ out = std::move(m);
+ return true;
+}
+
+bool saveObj(const std::string& path, const Mesh& mesh, std::string& error) {
+ std::ofstream file(utf8Path(path), std::ios::binary);
+ if (!file) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ std::string buf;
+ buf.reserve(mesh.vertexCount() * 40 + mesh.triangleCount() * 30);
+ buf += "# Exported by SculptForge\n";
+ char line[128];
+ for (const auto& v : mesh.positions) {
+ int n = std::snprintf(line, sizeof line, "v %.7g %.7g %.7g\n", v.x, v.y, v.z);
+ buf.append(line, n);
+ }
+ for (const auto& t : mesh.triangles) {
+ int n = std::snprintf(line, sizeof line, "f %u %u %u\n", t.x + 1, t.y + 1, t.z + 1);
+ buf.append(line, n);
+ }
+ file.write(buf.data(), static_cast<std::streamsize>(buf.size()));
+ if (!file) {
+ error = "Write failed for " + path;
+ return false;
+ }
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/ObjIO.h b/src/io/ObjIO.h
new file mode 100644
index 00000000..62284ead
--- /dev/null
+++ b/src/io/ObjIO.h
@@ -0,0 +1,15 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <string>
+
+namespace sf {
+
+// Paths are UTF-8. Polygons are fan-triangulated; UVs and normals are ignored.
+bool loadObj(const std::string& path, Mesh& out, std::string& error);
+bool saveObj(const std::string& path, const Mesh& mesh, std::string& error);
+
+} // namespace sf
diff --git a/src/io/PlyIO.cpp b/src/io/PlyIO.cpp
new file mode 100644
index 00000000..aa41176c
--- /dev/null
+++ b/src/io/PlyIO.cpp
@@ -0,0 +1,447 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/PlyIO.h"
+
+#include <algorithm>
+#include <bit>
+#include <cctype>
+#include <cmath>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <map>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+enum class Type { I8, U8, I16, U16, I32, U32, F32, F64, Invalid };
+
+Type parseType(const std::string& s) {
+ if (s == "char" || s == "int8") return Type::I8;
+ if (s == "uchar" || s == "uint8") return Type::U8;
+ if (s == "short" || s == "int16") return Type::I16;
+ if (s == "ushort" || s == "uint16") return Type::U16;
+ if (s == "int" || s == "int32") return Type::I32;
+ if (s == "uint" || s == "uint32") return Type::U32;
+ if (s == "float" || s == "float32") return Type::F32;
+ if (s == "double" || s == "float64") return Type::F64;
+ return Type::Invalid;
+}
+
+size_t typeSize(Type t) {
+ switch (t) {
+ case Type::I8:
+ case Type::U8: return 1;
+ case Type::I16:
+ case Type::U16: return 2;
+ case Type::I32:
+ case Type::U32:
+ case Type::F32: return 4;
+ case Type::F64: return 8;
+ default: return 0;
+ }
+}
+
+struct Property {
+ std::string name;
+ Type type = Type::Invalid;
+ bool list = false;
+ Type countType = Type::Invalid;
+};
+
+struct Element {
+ std::string name;
+ size_t count = 0;
+ std::vector<Property> props;
+ int find(const std::string& n) const {
+ for (size_t i = 0; i < props.size(); ++i)
+ if (props[i].name == n) return int(i);
+ return -1;
+ }
+};
+
+// Sequential reader over the body, binary (either endianness) or ASCII.
+struct Body {
+ const uint8_t* data;
+ size_t size, pos = 0;
+ bool ascii, bigEndian;
+ bool ok = true;
+
+ double read(Type t) {
+ if (ascii) return readAscii();
+ const size_t n = typeSize(t);
+ if (pos + n > size) {
+ ok = false;
+ return 0.0;
+ }
+ uint8_t b[8];
+ std::memcpy(b, data + pos, n);
+ pos += n;
+ if (bigEndian != (std::endian::native == std::endian::big)) std::reverse(b, b + n);
+ switch (t) {
+ case Type::I8: return double(int8_t(b[0]));
+ case Type::U8: return double(b[0]);
+ case Type::I16: { int16_t v; std::memcpy(&v, b, 2); return v; }
+ case Type::U16: { uint16_t v; std::memcpy(&v, b, 2); return v; }
+ case Type::I32: { int32_t v; std::memcpy(&v, b, 4); return v; }
+ case Type::U32: { uint32_t v; std::memcpy(&v, b, 4); return v; }
+ case Type::F32: { float v; std::memcpy(&v, b, 4); return v; }
+ case Type::F64: { double v; std::memcpy(&v, b, 8); return v; }
+ default: ok = false; return 0.0;
+ }
+ }
+
+ double readAscii() {
+ while (pos < size && std::isspace(data[pos])) ++pos;
+ const size_t start = pos;
+ while (pos < size && !std::isspace(data[pos])) ++pos;
+ if (start == pos) {
+ ok = false;
+ return 0.0;
+ }
+ return std::strtod(std::string(reinterpret_cast<const char*>(data + start), pos - start).c_str(), nullptr);
+ }
+};
+
+float sigmoid(float x) { return 1.0f / (1.0f + std::exp(-x)); }
+
+} // namespace
+
+bool loadPly(const std::string& path, Mesh& mesh, SplatCloud& splats, PlyContent& content, std::string& error) {
+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<uint8_t> file((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+
+ // Header.
+ const std::string marker = "end_header";
+ auto it = std::search(file.begin(), file.end(), marker.begin(), marker.end());
+ if (file.size() < 4 || std::memcmp(file.data(), "ply", 3) != 0 || it == file.end()) {
+ error = path + " is not a PLY file";
+ return false;
+ }
+ size_t bodyStart = size_t(it - file.begin()) + marker.size();
+ if (bodyStart < file.size() && file[bodyStart] == '\r') ++bodyStart;
+ if (bodyStart < file.size() && file[bodyStart] == '\n') ++bodyStart;
+ std::istringstream header(std::string(file.begin(), it));
+ std::vector<Element> elements;
+ std::string line, format;
+ while (std::getline(header, line)) {
+ std::istringstream ls(line);
+ std::string word;
+ ls >> word;
+ if (word == "format") ls >> format;
+ else if (word == "element") {
+ Element e;
+ ls >> e.name >> e.count;
+ elements.push_back(e);
+ } else if (word == "property" && !elements.empty()) {
+ Property p;
+ std::string t;
+ ls >> t;
+ if (t == "list") {
+ std::string ct, it2;
+ ls >> ct >> it2 >> p.name;
+ p.list = true;
+ p.countType = parseType(ct);
+ p.type = parseType(it2);
+ } else {
+ p.type = parseType(t);
+ ls >> p.name;
+ }
+ if (p.type == Type::Invalid || (p.list && p.countType == Type::Invalid)) {
+ error = "Unsupported PLY property type in: " + line;
+ return false;
+ }
+ elements.back().props.push_back(p);
+ }
+ }
+ if (format != "ascii" && format != "binary_little_endian" && format != "binary_big_endian") {
+ error = "Unsupported PLY format '" + format + "'";
+ return false;
+ }
+ for (const auto& e : elements)
+ if (e.name == "chunk") {
+ error = "Compressed splat PLY is not supported yet - export an uncompressed .ply (e.g. from SuperSplat)";
+ return false;
+ }
+
+ const Element* vertex = nullptr;
+ const Element* face = nullptr;
+ for (const auto& e : elements) {
+ if (e.name == "vertex") vertex = &e;
+ if (e.name == "face") face = &e;
+ }
+ if (!vertex || vertex->count == 0) {
+ error = "The PLY file has no vertices";
+ return false;
+ }
+ const bool isSplat = vertex->find("scale_0") >= 0 && vertex->find("rot_0") >= 0 && vertex->find("opacity") >= 0;
+ const bool isMesh = !isSplat && face && face->count > 0;
+ content = isMesh ? PlyContent::Mesh : PlyContent::Splats;
+
+ // Column lookups for the vertex element.
+ auto col = [&](const std::string& n) { return vertex->find(n); };
+ const int px = col("x"), py = col("y"), pz = col("z");
+ if (px < 0 || py < 0 || pz < 0) {
+ error = "The PLY vertices have no x/y/z";
+ return false;
+ }
+ int restCount = 0;
+ while (col("f_rest_" + std::to_string(restCount)) >= 0) ++restCount;
+ int degree = 0;
+ for (int d = 3; d >= 1; --d)
+ if (restCount == 3 * ((d + 1) * (d + 1) - 1)) {
+ degree = d;
+ break;
+ }
+ const int perChannel = (degree + 1) * (degree + 1) - 1;
+ std::vector<int> rest(size_t(3 * perChannel));
+ for (int k = 0; k < 3 * perChannel; ++k) rest[size_t(k)] = col("f_rest_" + std::to_string(k));
+ const int dc[3] = {col("f_dc_0"), col("f_dc_1"), col("f_dc_2")};
+ const int sc[3] = {col("scale_0"), col("scale_1"), col("scale_2")};
+ const int rt[4] = {col("rot_0"), col("rot_1"), col("rot_2"), col("rot_3")};
+ const int op = col("opacity");
+ int rgb[3] = {col("red"), col("green"), col("blue")};
+ if (rgb[0] < 0) rgb[0] = col("r"), rgb[1] = col("g"), rgb[2] = col("b");
+ const bool rgbIsByte = rgb[0] >= 0 && typeSize(vertex->props[size_t(rgb[0])].type) == 1;
+
+ Body body{file.data() + bodyStart, file.size() - bodyStart, 0, format == "ascii", format == "binary_big_endian"};
+ Mesh m;
+ SplatCloud cloud;
+ std::vector<double> row;
+ std::vector<glm::vec3> pointColors;
+
+ for (const auto& e : elements) {
+ const bool isVertex = &e == vertex, isFace = &e == face;
+ if (isVertex) {
+ if (isMesh) m.positions.reserve(e.count);
+ else cloud.resize(e.count, isSplat ? degree : 0);
+ if (!isSplat && !isMesh) pointColors.assign(e.count, glm::vec3(0.8f));
+ }
+ for (size_t r = 0; r < e.count; ++r) {
+ row.assign(e.props.size(), 0.0);
+ std::vector<uint32_t> poly;
+ for (size_t p = 0; p < e.props.size(); ++p) {
+ const Property& prop = e.props[p];
+ if (!prop.list) {
+ row[p] = body.read(prop.type);
+ continue;
+ }
+ const size_t n = size_t(body.read(prop.countType));
+ if (!body.ok || n > 1'000'000) {
+ error = "Corrupt PLY list";
+ return false;
+ }
+ const bool wanted = isFace && (prop.name == "vertex_indices" || prop.name == "vertex_index");
+ for (size_t k = 0; k < n; ++k) {
+ const double v = body.read(prop.type);
+ if (wanted) poly.push_back(uint32_t(v));
+ }
+ }
+ if (!body.ok) {
+ error = "Truncated PLY file";
+ return false;
+ }
+ if (isVertex) {
+ const glm::vec3 pos{float(row[size_t(px)]), float(row[size_t(py)]), float(row[size_t(pz)])};
+ if (isMesh) {
+ m.positions.push_back(pos);
+ continue;
+ }
+ cloud.positions[r] = pos;
+ if (isSplat) {
+ const size_t K = size_t(cloud.shCount());
+ for (int c = 0; c < 3; ++c) {
+ if (dc[c] >= 0) cloud.sh[r * K][c] = float(row[size_t(dc[c])]);
+ for (int k = 0; k < perChannel; ++k) {
+ const int idx = rest[size_t(c * perChannel + k)];
+ cloud.sh[r * K + size_t(k) + 1][c] = idx >= 0 ? float(row[size_t(idx)]) : 0.0f;
+ }
+ cloud.scales[r][c] = std::exp(float(row[size_t(sc[c])]));
+ }
+ glm::quat q(float(row[size_t(rt[0])]), float(row[size_t(rt[1])]), float(row[size_t(rt[2])]),
+ float(row[size_t(rt[3])]));
+ const float len = glm::length(q);
+ cloud.rotations[r] = len > 0.0f ? q / len : glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
+ cloud.opacities[r] = sigmoid(float(row[size_t(op)]));
+ } else if (rgb[0] >= 0 && rgb[1] >= 0 && rgb[2] >= 0) {
+ glm::vec3 c(float(row[size_t(rgb[0])]), float(row[size_t(rgb[1])]), float(row[size_t(rgb[2])]));
+ pointColors[r] = rgbIsByte ? c / 255.0f : c;
+ }
+ } else if (isFace && poly.size() >= 3) {
+ for (size_t k = 1; k + 1 < poly.size(); ++k) m.triangles.push_back({poly[0], poly[k], poly[k + 1]});
+ }
+ }
+ }
+
+ if (isMesh) {
+ for (const auto& t : m.triangles)
+ if (t.x >= m.positions.size() || t.y >= m.positions.size() || t.z >= m.positions.size()) {
+ error = "PLY face index out of range";
+ return false;
+ }
+ mesh = weldImported(m);
+ if (mesh.triangleCount() == 0) {
+ error = "The PLY mesh has no usable faces";
+ return false;
+ }
+ return true;
+ }
+ if (!isSplat) {
+ // Plain point cloud (LiDAR, photogrammetry): round splats sized to the point spacing.
+ const AABB b = cloud.bounds();
+ const glm::vec3 e = b.extent();
+ const float area = std::max(e.x * e.y + e.y * e.z + e.z * e.x, 1e-12f);
+ const float sigma = 0.7f * std::sqrt(area / float(cloud.size()));
+ for (size_t i = 0; i < cloud.size(); ++i) {
+ cloud.scales[i] = glm::vec3(sigma);
+ cloud.setColor(i, pointColors[i]);
+ }
+ }
+ auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ cloud.name = std::string(stem.begin(), stem.end());
+ splats = std::move(cloud);
+ return true;
+}
+
+bool saveSplatPly(const std::string& path, const SplatCloud& input, std::string& error) {
+ if (input.empty()) {
+ error = "There are no splats to save";
+ return false;
+ }
+ if (std::string v = input.validate(); !v.empty()) {
+ error = v;
+ return false;
+ }
+ SplatCloud cloud = input;
+ cloud.bakeTransform();
+ const int perChannel = cloud.shCount() - 1;
+
+ std::ostringstream h;
+ h << "ply\nformat binary_little_endian 1.0\ncomment Generated by SculptForge\nelement vertex " << cloud.size() << "\n";
+ for (const char* n : {"x", "y", "z", "nx", "ny", "nz", "f_dc_0", "f_dc_1", "f_dc_2"}) h << "property float " << n << "\n";
+ for (int k = 0; k < 3 * perChannel; ++k) h << "property float f_rest_" << k << "\n";
+ for (const char* n : {"opacity", "scale_0", "scale_1", "scale_2", "rot_0", "rot_1", "rot_2", "rot_3"})
+ h << "property float " << n << "\n";
+ h << "end_header\n";
+
+ std::vector<float> data;
+ const size_t stride = size_t(9 + 3 * perChannel + 8);
+ data.reserve(cloud.size() * stride);
+ const size_t K = size_t(cloud.shCount());
+ for (size_t i = 0; i < cloud.size(); ++i) {
+ const glm::vec3& p = cloud.positions[i];
+ data.insert(data.end(), {p.x, p.y, p.z, 0.0f, 0.0f, 0.0f});
+ const glm::vec3& d = cloud.sh[i * K];
+ data.insert(data.end(), {d.x, d.y, d.z});
+ for (int c = 0; c < 3; ++c)
+ for (int k = 0; k < perChannel; ++k) data.push_back(cloud.sh[i * K + size_t(k) + 1][c]);
+ const float o = std::clamp(cloud.opacities[i], 1e-6f, 1.0f - 1e-6f);
+ data.push_back(std::log(o / (1.0f - o)));
+ for (int c = 0; c < 3; ++c) data.push_back(std::log(std::max(cloud.scales[i][c], 1e-12f)));
+ const glm::quat& q = cloud.rotations[i];
+ data.insert(data.end(), {q.w, q.x, q.y, q.z});
+ }
+ if constexpr (std::endian::native == std::endian::big)
+ for (float& v : data) {
+ uint32_t u;
+ std::memcpy(&u, &v, 4);
+ u = (u >> 24) | ((u >> 8) & 0xFF00u) | ((u << 8) & 0xFF0000u) | (u << 24);
+ std::memcpy(&v, &u, 4);
+ }
+
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ const std::string hs = h.str();
+ f.write(hs.data(), std::streamsize(hs.size()));
+ f.write(reinterpret_cast<const char*>(data.data()), std::streamsize(data.size() * sizeof(float)));
+ if (!f) {
+ error = "Write failed for " + path;
+ return false;
+ }
+ return true;
+}
+
+bool loadDotSplat(const std::string& path, SplatCloud& splats, std::string& error) {
+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<uint8_t> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ if (data.empty() || data.size() % 32 != 0) {
+ error = path + " is not a .splat file (size must be a multiple of 32 bytes)";
+ return false;
+ }
+ SplatCloud cloud;
+ const size_t n = data.size() / 32;
+ cloud.resize(n, 0);
+ for (size_t i = 0; i < n; ++i) {
+ const uint8_t* p = data.data() + i * 32;
+ float v[6];
+ std::memcpy(v, p, sizeof v);
+ if constexpr (std::endian::native == std::endian::big)
+ for (float& x : v) {
+ uint32_t u;
+ std::memcpy(&u, &x, 4);
+ u = (u >> 24) | ((u >> 8) & 0xFF00u) | ((u << 8) & 0xFF0000u) | (u << 24);
+ std::memcpy(&x, &u, 4);
+ }
+ cloud.positions[i] = glm::vec3(v[0], v[1], v[2]);
+ cloud.scales[i] = glm::vec3(v[3], v[4], v[5]);
+ cloud.setColor(i, glm::vec3(p[24], p[25], p[26]) / 255.0f);
+ cloud.opacities[i] = float(p[27]) / 255.0f;
+ glm::quat q((float(p[28]) - 128.0f) / 128.0f, (float(p[29]) - 128.0f) / 128.0f, (float(p[30]) - 128.0f) / 128.0f,
+ (float(p[31]) - 128.0f) / 128.0f);
+ const float len = glm::length(q);
+ cloud.rotations[i] = len > 0.0f ? q / len : glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
+ }
+ auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ cloud.name = std::string(stem.begin(), stem.end());
+ splats = std::move(cloud);
+ return true;
+}
+
+bool saveDotSplat(const std::string& path, const SplatCloud& input, std::string& error) {
+ if (input.empty()) {
+ error = "There are no splats to save";
+ return false;
+ }
+ SplatCloud c = input;
+ c.bakeTransform();
+ std::vector<uint8_t> out(c.size() * 32);
+ auto byte = [](float x) { return uint8_t(std::clamp(int(std::lround(x * 255.0f)), 0, 255)); };
+ auto qbyte = [](float x) { return uint8_t(std::clamp(int(std::lround(x * 128.0f + 128.0f)), 0, 255)); };
+ for (size_t i = 0; i < c.size(); ++i) {
+ uint8_t* p = out.data() + i * 32;
+ const float v[6] = {c.positions[i].x, c.positions[i].y, c.positions[i].z, c.scales[i].x, c.scales[i].y, c.scales[i].z};
+ std::memcpy(p, v, sizeof v);
+ const glm::vec3 rgb = c.color(i);
+ p[24] = byte(rgb.x);
+ p[25] = byte(rgb.y);
+ p[26] = byte(rgb.z);
+ p[27] = byte(c.opacities[i]);
+ const glm::quat& q = c.rotations[i];
+ p[28] = qbyte(q.w);
+ p[29] = qbyte(q.x);
+ p[30] = qbyte(q.y);
+ p[31] = qbyte(q.z);
+ }
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(out.data()), std::streamsize(out.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/PlyIO.h b/src/io/PlyIO.h
new file mode 100644
index 00000000..382749a1
--- /dev/null
+++ b/src/io/PlyIO.h
@@ -0,0 +1,33 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// PLY: the de-facto exchange format for 3D Gaussian splats (INRIA layout used
+// by Polycam, Luma, Postshot, Scaniverse, nerfstudio, SuperSplat...) and a
+// common format for scans. ASCII and binary (either endianness) are read.
+#pragma once
+
+#include "core/Mesh.h"
+#include "core/Splats.h"
+
+#include <string>
+
+namespace sf {
+
+enum class PlyContent { Mesh, Splats };
+
+// Reads a mesh (if the file has faces), Gaussian splats (if it has splat
+// properties), or turns a plain point cloud into small round splats so it can
+// be converted to a mesh. `content` says which output was filled.
+bool loadPly(const std::string& path, Mesh& mesh, SplatCloud& splats, PlyContent& content, std::string& error);
+
+// Writes splats in the standard binary 3DGS layout (log scales, logit
+// opacity). The cloud's transform is baked in.
+bool saveSplatPly(const std::string& path, const SplatCloud& splats, std::string& error);
+
+// The compact ".splat" format used by many web viewers (antimatter15/splat):
+// 32 bytes per splat - position, linear scale, RGBA8 colour/opacity and an
+// 8-bit quaternion. Lossy (colour and rotation are quantised, no SH).
+bool loadDotSplat(const std::string& path, SplatCloud& splats, std::string& error);
+bool saveDotSplat(const std::string& path, const SplatCloud& splats, std::string& error);
+
+} // namespace sf
diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cpp
new file mode 100644
index 00000000..b80fbb4f
--- /dev/null
+++ b/src/io/UsdIO.cpp
@@ -0,0 +1,810 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/UsdIO.h"
+
+#include "io/Zip.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <functional>
+#include <iterator>
+#include <map>
+#include <set>
+#include <string_view>
+
+namespace sf {
+
+namespace {
+
+std::filesystem::path fsPath(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
+
+std::string lowerExtension(const std::string& path) {
+ std::string ext = fsPath(path).extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return ext;
+}
+
+// ---------------------------------------------------------------- writing
+
+struct Writer {
+ std::string s;
+ int depth = 0;
+
+ void line(std::string_view text) {
+ s.append(size_t(depth) * 4, ' ');
+ s.append(text);
+ s += '\n';
+ }
+ void indent() { s.append(size_t(depth) * 4, ' '); }
+ void num(double v) {
+ if (!std::isfinite(v)) v = 0.0;
+ char b[32];
+ const int n = std::snprintf(b, sizeof b, "%.9g", v);
+ s.append(b, size_t(n));
+ }
+ void vec3(const glm::vec3& v) {
+ s += '(';
+ num(v.x);
+ s += ", ";
+ num(v.y);
+ s += ", ";
+ num(v.z);
+ s += ')';
+ }
+ void quat(const glm::quat& q) { // USD text order is (real, i, j, k)
+ s += '(';
+ num(q.w);
+ s += ", ";
+ num(q.x);
+ s += ", ";
+ num(q.y);
+ s += ", ";
+ num(q.z);
+ s += ')';
+ }
+ template <class T, class F> void array(std::string_view decl, const std::vector<T>& values, F&& each) {
+ indent();
+ s.append(decl);
+ s += " = [";
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (i) s += ", ";
+ each(values[i]);
+ }
+ s += "]\n";
+ }
+ void open(std::string_view header) {
+ line(header);
+ line("{");
+ ++depth;
+ }
+ void close() {
+ --depth;
+ line("}");
+ }
+};
+
+std::string quoted(const std::string& t) { return "\"" + t + "\""; }
+
+void writeExtent(Writer& w, const AABB& b) {
+ w.indent();
+ w.s += "float3[] extent = [";
+ w.vec3(b.valid() ? b.min : glm::vec3(0.0f));
+ w.s += ", ";
+ w.vec3(b.valid() ? b.max : glm::vec3(0.0f));
+ w.s += "]\n";
+}
+
+void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::string& material) {
+ const bool skinned = !mesh.layers.empty();
+ const std::string meshPath = skinned ? "/" + root + "/Sculpt/Mesh" : "/" + root + "/Sculpt";
+ // Unique, valid names for the blend shapes.
+ std::vector<std::string> shapeNames;
+ std::set<std::string> used;
+ for (const auto& l : mesh.layers) {
+ std::string n = usdIdentifier(l.name), unique = n;
+ for (int k = 2; used.count(unique); ++k) unique = n + "_" + std::to_string(k);
+ used.insert(unique);
+ shapeNames.push_back(unique);
+ }
+
+ Mesh base;
+ base.positions = mesh.basePositions();
+ base.triangles = mesh.triangles;
+ base.rebuildTopology();
+ base.recomputeAllNormals();
+
+ if (skinned) w.open("def SkelRoot \"Sculpt\"");
+ w.line(std::string("def Mesh \"") + (skinned ? "Mesh" : "Sculpt") + "\" (");
+ w.line(skinned ? " prepend apiSchemas = [\"SkelBindingAPI\", \"MaterialBindingAPI\"]"
+ : " prepend apiSchemas = [\"MaterialBindingAPI\"]");
+ w.line(")");
+ w.line("{");
+ ++w.depth;
+ writeExtent(w, base.bounds());
+ w.indent();
+ w.s += "int[] faceVertexCounts = [";
+ for (size_t i = 0; i < mesh.triangleCount(); ++i) w.s += i ? ", 3" : "3";
+ w.s += "]\n";
+ w.array("int[] faceVertexIndices", mesh.triangles, [&](const glm::uvec3& t) {
+ w.s += std::to_string(t.x) + ", " + std::to_string(t.y) + ", " + std::to_string(t.z);
+ });
+ w.line("rel material:binding = <" + material + ">");
+ w.array("normal3f[] normals", base.normals, [&](const glm::vec3& n) { w.vec3(n); });
+ w.s.pop_back();
+ w.s += " (\n";
+ w.line(" interpolation = \"vertex\"");
+ w.line(")");
+ w.array("point3f[] points", base.positions, [&](const glm::vec3& p) { w.vec3(p); });
+ w.line("uniform token subdivisionScheme = \"none\"");
+ if (skinned) {
+ w.array("uniform token[] skel:blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });
+ w.array("rel skel:blendShapeTargets", shapeNames, [&](const std::string& n) { w.s += "<" + meshPath + "/" + n + ">"; });
+ w.line("rel skel:skeleton = </" + root + "/Sculpt/Skel>");
+ for (size_t k = 0; k < mesh.layers.size(); ++k) {
+ // Sparse: only the points the layer actually moves.
+ std::vector<uint32_t> idx;
+ const auto& d = mesh.layers[k].delta;
+ for (uint32_t v = 0; v < d.size(); ++v)
+ if (d[v] != glm::vec3(0.0f)) idx.push_back(v);
+ if (idx.empty()) idx.push_back(0);
+ w.s += '\n';
+ w.open("def BlendShape \"" + shapeNames[k] + "\"");
+ w.array("uniform vector3f[] offsets", idx, [&](uint32_t v) { w.vec3(d[v]); });
+ w.array("uniform int[] pointIndices", idx, [&](uint32_t v) { w.s += std::to_string(v); });
+ w.close();
+ }
+ }
+ w.close();
+
+ if (skinned) {
+ // A joint-less skeleton is how UsdSkel drives pure blend-shape rigs.
+ w.s += '\n';
+ w.line("def Skeleton \"Skel\" (");
+ w.line(" prepend apiSchemas = [\"SkelBindingAPI\"]");
+ w.line(")");
+ w.line("{");
+ ++w.depth;
+ w.line("uniform matrix4d[] bindTransforms = []");
+ w.line("uniform token[] joints = []");
+ w.line("uniform matrix4d[] restTransforms = []");
+ w.line("rel skel:animationSource = </" + root + "/Sculpt/Skel/Weights>");
+ w.s += '\n';
+ w.open("def SkelAnimation \"Weights\"");
+ w.array("uniform token[] blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });
+ w.array("float[] blendShapeWeights", mesh.layers, [&](const SculptLayer& l) { w.num(l.weight); });
+ w.close();
+ w.close();
+ w.close();
+ }
+}
+
+void writeSplats(Writer& w, const SplatCloud& c) {
+ w.open("def ParticleField3DGaussianSplat \"Splats\""); // fixed name: never collides with the mesh prims
+ AABB local;
+ for (const auto& p : c.positions) local.expand(p);
+ writeExtent(w, local);
+ w.array("float[] opacities", c.opacities, [&](float o) { w.num(o); });
+ w.array("quatf[] orientations", c.rotations, [&](const glm::quat& q) { w.quat(q); });
+ w.array("point3f[] positions", c.positions, [&](const glm::vec3& p) { w.vec3(p); });
+ w.line("uniform token projectionModeHint = \"perspective\"");
+ w.array("float3[] radiance:sphericalHarmonicsCoefficients", c.sh, [&](const glm::vec3& v) { w.vec3(v); });
+ w.line("uniform int radiance:sphericalHarmonicsDegree = " + std::to_string(c.shDegree));
+ w.array("float3[] scales", c.scales, [&](const glm::vec3& v) { w.vec3(v); });
+ w.line("uniform token sortingModeHint = \"zDepth\"");
+ if (c.transform != glm::mat4(1.0f)) {
+ w.indent();
+ w.s += "matrix4d xformOp:transform = (";
+ for (int col = 0; col < 4; ++col) { // USD rows are glm columns (row-vector convention)
+ w.s += col ? ", (" : "(";
+ for (int r = 0; r < 4; ++r) {
+ if (r) w.s += ", ";
+ w.num(c.transform[col][r]);
+ }
+ w.s += ')';
+ }
+ w.s += ")\n";
+ w.line("uniform token[] xformOpOrder = [\"xformOp:transform\"]");
+ }
+ w.close();
+}
+
+std::string buildUsda(const Mesh* mesh, const SplatCloud* splats, const std::string& name) {
+ const std::string root = usdIdentifier(name.empty() ? "Sculpt" : name);
+ const std::string material = "/" + root + "/Materials/Clay";
+ Writer w;
+ w.line("#usda 1.0");
+ w.line("(");
+ w.line(" defaultPrim = " + quoted(root));
+ w.line(" doc = \"Created with SculptForge\"");
+ w.line(" metersPerUnit = 1");
+ w.line(" upAxis = \"Y\"");
+ w.line(")");
+ w.s += '\n';
+ w.line("def Xform " + quoted(root) + " (");
+ w.line(" kind = \"component\"");
+ w.line(")");
+ w.line("{");
+ ++w.depth;
+ if (mesh && mesh->triangleCount()) {
+ writeMesh(w, *mesh, root, material);
+ w.s += '\n';
+ w.open("def Scope \"Materials\"");
+ w.open("def Material \"Clay\"");
+ w.line("token outputs:surface.connect = <" + material + "/PreviewSurface.outputs:surface>");
+ w.s += '\n';
+ w.open("def Shader \"PreviewSurface\"");
+ w.line("uniform token info:id = \"UsdPreviewSurface\"");
+ w.line("color3f inputs:diffuseColor = (0.8, 0.55, 0.45)");
+ w.line("float inputs:metallic = 0");
+ w.line("float inputs:roughness = 0.65");
+ w.line("token outputs:surface");
+ w.close();
+ w.close();
+ w.close();
+ }
+ if (splats && !splats->empty()) {
+ if (mesh && mesh->triangleCount()) w.s += '\n';
+ writeSplats(w, *splats);
+ }
+ w.close();
+ return w.s;
+}
+
+// ---------------------------------------------------------------- reading
+
+struct Token {
+ enum Kind { Ident, Number, String, Path, Asset, Punct, End } kind = End;
+ std::string_view text;
+ double number = 0.0;
+};
+
+class Lexer {
+public:
+ explicit Lexer(const std::string& src) : s_(src) {}
+
+ Token next() {
+ skipSpace();
+ Token t;
+ if (pos_ >= s_.size()) return t;
+ const char c = s_[pos_];
+ const size_t start = pos_;
+ if (c == '"' || c == '\'') {
+ const bool triple = s_.compare(pos_, 3, std::string(3, c)) == 0;
+ pos_ += triple ? 3 : 1;
+ while (pos_ < s_.size()) {
+ if (s_[pos_] == '\\') {
+ pos_ += 2;
+ continue;
+ }
+ if (triple ? s_.compare(pos_, 3, std::string(3, c)) == 0 : s_[pos_] == c) break;
+ ++pos_;
+ }
+ const size_t q = triple ? 3 : 1;
+ t = {Token::String, std::string_view(s_).substr(start + q, std::min(pos_, s_.size()) - start - q)};
+ pos_ = std::min(s_.size(), pos_ + q);
+ return t;
+ }
+ if (c == '<') {
+ const size_t end = s_.find('>', pos_);
+ pos_ = end == std::string::npos ? s_.size() : end + 1;
+ return {Token::Path, std::string_view(s_).substr(start + 1, pos_ - start - 2)};
+ }
+ if (c == '@') {
+ const bool triple = s_.compare(pos_, 3, "@@@") == 0;
+ const size_t end = s_.find(triple ? "@@@" : "@", pos_ + (triple ? 3 : 1));
+ pos_ = end == std::string::npos ? s_.size() : end + (triple ? 3 : 1);
+ return {Token::Asset, std::string_view(s_).substr(start, pos_ - start)};
+ }
+ if (std::isdigit(static_cast<unsigned char>(c)) ||
+ ((c == '-' || c == '+' || c == '.') && pos_ + 1 < s_.size() &&
+ (std::isdigit(static_cast<unsigned char>(s_[pos_ + 1])) || s_[pos_ + 1] == '.'))) {
+ char* end = nullptr;
+ t.number = std::strtod(s_.c_str() + pos_, &end);
+ pos_ = size_t(end - s_.c_str());
+ if (pos_ == start) ++pos_;
+ t.kind = Token::Number;
+ t.text = std::string_view(s_).substr(start, pos_ - start);
+ return t;
+ }
+ if (std::isalpha(static_cast<unsigned char>(c)) || c == '_' || c == '-') {
+ ++pos_;
+ while (pos_ < s_.size()) {
+ const char d = s_[pos_];
+ if (std::isalnum(static_cast<unsigned char>(d)) || d == '_' || d == ':' || d == '.') ++pos_;
+ else break;
+ }
+ t = {Token::Ident, std::string_view(s_).substr(start, pos_ - start)};
+ if (t.text == "inf" || t.text == "-inf" || t.text == "nan") {
+ t.kind = Token::Number;
+ t.number = t.text == "-inf" ? -HUGE_VAL : t.text == "inf" ? HUGE_VAL : 0.0;
+ }
+ return t;
+ }
+ ++pos_;
+ return {Token::Punct, std::string_view(s_).substr(start, 1)};
+ }
+
+private:
+ void skipSpace() {
+ while (pos_ < s_.size()) {
+ if (std::isspace(static_cast<unsigned char>(s_[pos_]))) ++pos_;
+ else if (s_[pos_] == '#') {
+ while (pos_ < s_.size() && s_[pos_] != '\n') ++pos_;
+ } else break;
+ }
+ }
+ const std::string& s_;
+ size_t pos_ = 0;
+};
+
+struct Value {
+ std::vector<double> nums;
+ std::vector<std::string> strs;
+};
+
+struct Prim {
+ std::string type, path;
+ bool abstract = false;
+ int parent = -1;
+ std::map<std::string, Value> attrs;
+ const Value* get(const std::string& n) const {
+ auto it = attrs.find(n);
+ return it == attrs.end() ? nullptr : &it->second;
+ }
+};
+
+class Parser {
+public:
+ explicit Parser(const std::string& text) : lex_(text) { advance(); }
+
+ std::vector<Prim> prims;
+ std::string upAxis = "Y";
+ std::string error;
+
+ bool parse() {
+ if (isPunct("(")) parseLayerMetadata();
+ while (tok_.kind != Token::End) {
+ if (!parsePrim(-1, "")) return false;
+ }
+ return true;
+ }
+
+private:
+ Lexer lex_;
+ Token tok_;
+ int guard_ = 0;
+
+ void advance() { tok_ = lex_.next(); }
+ bool isPunct(const char* p) const { return tok_.kind == Token::Punct && tok_.text == p; }
+ bool isIdent(std::string_view s) const { return tok_.kind == Token::Ident && tok_.text == s; }
+ bool fail(const std::string& msg) {
+ if (error.empty()) error = msg;
+ return false;
+ }
+ bool expect(const char* p) {
+ if (!isPunct(p)) return fail(std::string("USD syntax error: expected '") + p + "' near '" + std::string(tok_.text) + "'");
+ advance();
+ return true;
+ }
+
+ void skipBalanced() { // at an opening bracket
+ int level = 0;
+ do {
+ if (tok_.kind == Token::End) return;
+ if (isPunct("(") || isPunct("[") || isPunct("{")) ++level;
+ else if (isPunct(")") || isPunct("]") || isPunct("}")) --level;
+ advance();
+ } while (level > 0);
+ }
+
+ void parseLayerMetadata() {
+ advance();
+ while (tok_.kind != Token::End && !isPunct(")")) {
+ if (isIdent("upAxis")) {
+ advance();
+ if (isPunct("=")) advance();
+ if (tok_.kind == Token::String) upAxis = std::string(tok_.text);
+ advance();
+ } else if (isPunct("(") || isPunct("[") || isPunct("{")) {
+ skipBalanced();
+ } else {
+ advance();
+ }
+ }
+ if (isPunct(")")) advance();
+ }
+
+ bool parseValue(Value& v) {
+ if (++guard_ > 256) return fail("USD value nested too deeply");
+ bool ok = true;
+ if (isPunct("[") || isPunct("(")) {
+ const char* close = isPunct("[") ? "]" : ")";
+ advance();
+ while (ok && !isPunct(close)) {
+ if (tok_.kind == Token::End) {
+ ok = fail("Unterminated USD array");
+ break;
+ }
+ ok = parseValue(v);
+ if (isPunct(",")) advance();
+ }
+ if (ok) advance();
+ } else if (isPunct("{")) { // timeSamples: use the first sample
+ advance();
+ bool first = true;
+ while (ok && !isPunct("}")) {
+ if (tok_.kind == Token::End) {
+ ok = fail("Unterminated USD dictionary");
+ break;
+ }
+ advance(); // key
+ if (isPunct(":")) advance();
+ Value sample;
+ ok = parseValue(sample);
+ if (first) v = std::move(sample);
+ first = false;
+ if (isPunct(",")) advance();
+ }
+ if (ok) advance();
+ } else if (tok_.kind == Token::Number) {
+ v.nums.push_back(tok_.number);
+ advance();
+ } else if (tok_.kind == Token::Ident) {
+ if (tok_.text == "true") v.nums.push_back(1.0);
+ else if (tok_.text == "false") v.nums.push_back(0.0);
+ else if (tok_.text != "None") v.strs.emplace_back(tok_.text);
+ advance();
+ } else if (tok_.kind == Token::String || tok_.kind == Token::Path || tok_.kind == Token::Asset) {
+ v.strs.emplace_back(tok_.text);
+ advance();
+ } else {
+ ok = fail("Unexpected '" + std::string(tok_.text) + "' in USD value");
+ }
+ --guard_;
+ return ok;
+ }
+
+ bool parsePrim(int parent, const std::string& parentPath) {
+ if (!(isIdent("def") || isIdent("over") || isIdent("class")))
+ return fail("USD syntax error: expected a prim near '" + std::string(tok_.text) + "'");
+ const bool abstract = isIdent("class") || (parent >= 0 && prims[size_t(parent)].abstract);
+ advance();
+ Prim prim;
+ if (tok_.kind == Token::Ident) {
+ prim.type = std::string(tok_.text);
+ advance();
+ }
+ if (tok_.kind != Token::String) return fail("USD syntax error: prim without a name");
+ prim.path = parentPath + "/" + std::string(tok_.text);
+ prim.parent = parent;
+ prim.abstract = abstract;
+ advance();
+ if (isPunct("(")) skipBalanced();
+ if (!expect("{")) return false;
+ const int index = int(prims.size());
+ prims.push_back(std::move(prim));
+ const std::string path = prims.back().path;
+
+ while (!isPunct("}")) {
+ if (tok_.kind == Token::End) return fail("Unterminated prim " + path);
+ if (isIdent("def") || isIdent("over") || isIdent("class")) {
+ if (!parsePrim(index, path)) return false;
+ continue;
+ }
+ if (isIdent("variantSet")) {
+ while (tok_.kind != Token::End && !isPunct("{")) advance();
+ skipBalanced();
+ continue;
+ }
+ if (!parseProperty(index)) return false;
+ }
+ advance();
+ return true;
+ }
+
+ bool parseProperty(int primIndex) {
+ static const std::set<std::string_view> qualifiers = {"custom", "uniform", "varying", "prepend", "append",
+ "add", "delete", "reorder", "config"};
+ while (tok_.kind == Token::Ident && qualifiers.count(tok_.text)) advance();
+ if (tok_.kind != Token::Ident) {
+ if (isPunct(";")) {
+ advance();
+ return true;
+ }
+ return fail("USD syntax error near '" + std::string(tok_.text) + "'");
+ }
+ advance(); // type name or 'rel'
+ if (isPunct("[")) {
+ advance();
+ if (!expect("]")) return false;
+ }
+ if (tok_.kind != Token::Ident) return fail("USD syntax error: property without a name");
+ std::string name(tok_.text);
+ advance();
+ bool timeSamples = false;
+ if (name.size() > 12 && name.ends_with(".timeSamples")) {
+ name.resize(name.size() - 12);
+ timeSamples = true;
+ }
+ if (isPunct("=")) {
+ advance();
+ Value v;
+ if (!parseValue(v)) return false;
+ auto& slot = prims[size_t(primIndex)].attrs[name];
+ if (timeSamples || (slot.nums.empty() && slot.strs.empty())) slot = std::move(v);
+ }
+ if (isPunct("(")) skipBalanced();
+ return true;
+ }
+};
+
+glm::mat4 axisRotation(char axis, float degrees) {
+ const glm::vec3 a = axis == 'X' ? glm::vec3(1, 0, 0) : axis == 'Y' ? glm::vec3(0, 1, 0) : glm::vec3(0, 0, 1);
+ return glm::rotate(glm::mat4(1.0f), glm::radians(degrees), a);
+}
+
+// Local transform from xformOpOrder (first op is outermost).
+glm::mat4 localTransform(const Prim& p, bool& resetsStack) {
+ resetsStack = false;
+ glm::mat4 m(1.0f);
+ const Value* order = p.get("xformOpOrder");
+ if (!order) return m;
+ for (std::string op : order->strs) {
+ if (op == "!resetXformStack!") {
+ resetsStack = true;
+ m = glm::mat4(1.0f);
+ continue;
+ }
+ bool invert = false;
+ if (op.rfind("!invert!", 0) == 0) {
+ invert = true;
+ op = op.substr(8);
+ }
+ const Value* v = p.get(op);
+ std::vector<double> n = v ? v->nums : std::vector<double>();
+ const std::string kind = op.substr(0, op.find(':', 8)); // "xformOp:translate" without its suffix
+ glm::mat4 x(1.0f);
+ if (kind == "xformOp:translate" && n.size() >= 3) x = glm::translate(x, glm::vec3(n[0], n[1], n[2]));
+ else if (kind == "xformOp:scale" && n.size() >= 3) x = glm::scale(x, glm::vec3(n[0], n[1], n[2]));
+ else if (kind == "xformOp:scale" && n.size() == 1) x = glm::scale(x, glm::vec3(float(n[0])));
+ else if (kind == "xformOp:orient" && n.size() >= 4)
+ x = glm::mat4_cast(glm::normalize(glm::quat(float(n[0]), float(n[1]), float(n[2]), float(n[3]))));
+ else if (kind == "xformOp:transform" && n.size() >= 16) {
+ for (int i = 0; i < 16; ++i) glm::value_ptr(x)[i] = float(n[size_t(i)]);
+ } else if (kind.rfind("xformOp:rotate", 0) == 0 && !n.empty()) {
+ const std::string axes = kind.substr(14); // "X", "XYZ", "ZXY"...
+ if (axes.size() == 1) x = axisRotation(axes[0], float(n[0]));
+ else if (axes.size() == 3 && n.size() >= 3)
+ for (int k = 2; k >= 0; --k) // first listed axis is applied first
+ x = x * axisRotation(axes[size_t(k)], float(n[size_t(axes[size_t(k)] - 'X')]));
+ }
+ m = m * (invert ? glm::inverse(x) : x);
+ }
+ return m;
+}
+
+std::vector<glm::vec3> vec3s(const Value* v) {
+ std::vector<glm::vec3> out;
+ if (!v) return out;
+ out.reserve(v->nums.size() / 3);
+ for (size_t i = 0; i + 2 < v->nums.size(); i += 3)
+ out.emplace_back(float(v->nums[i]), float(v->nums[i + 1]), float(v->nums[i + 2]));
+ return out;
+}
+
+bool readUsdaText(const std::string& text, Mesh& outMesh, SplatCloud& outSplats, std::string& error) {
+ Parser parser(text);
+ if (!parser.parse()) {
+ error = parser.error;
+ return false;
+ }
+ auto& prims = parser.prims;
+ std::map<std::string, size_t> byPath;
+ for (size_t i = 0; i < prims.size(); ++i) byPath[prims[i].path] = i;
+
+ // World transforms (parents come first in `prims`).
+ const glm::mat4 up = parser.upAxis == "Z" ? glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1, 0, 0))
+ : glm::mat4(1.0f);
+ std::vector<glm::mat4> world(prims.size());
+ for (size_t i = 0; i < prims.size(); ++i) {
+ bool reset = false;
+ const glm::mat4 local = localTransform(prims[i], reset);
+ world[i] = (prims[i].parent >= 0 && !reset ? world[size_t(prims[i].parent)] : up) * local;
+ }
+
+ // Blend-shape weights from any SkelAnimation.
+ std::map<std::string, float> weights;
+ for (const auto& p : prims) {
+ if (p.type != "SkelAnimation") continue;
+ const Value* names = p.get("blendShapes");
+ const Value* w = p.get("blendShapeWeights");
+ if (!names || !w) continue;
+ for (size_t k = 0; k < names->strs.size() && k < w->nums.size(); ++k)
+ weights.try_emplace(names->strs[k], float(w->nums[k]));
+ }
+
+ Mesh m;
+ std::vector<SculptLayer> layers;
+ auto layerFor = [&](const std::string& name) -> SculptLayer& {
+ for (auto& l : layers)
+ if (l.name == name) return l;
+ auto it = weights.find(name);
+ layers.push_back({name, std::vector<glm::vec3>(m.positions.size(), glm::vec3(0.0f)),
+ it == weights.end() ? 0.0f : it->second});
+ return layers.back();
+ };
+ bool splatsFound = false;
+ SplatCloud cloud;
+
+ for (size_t i = 0; i < prims.size(); ++i) {
+ const Prim& p = prims[i];
+ if (p.abstract) continue;
+ if (p.type == "Mesh") {
+ const auto pts = vec3s(p.get("points"));
+ const Value* counts = p.get("faceVertexCounts");
+ const Value* indices = p.get("faceVertexIndices");
+ if (pts.empty() || !counts || !indices) continue;
+ const Value* orient = p.get("orientation");
+ const bool leftHanded = orient && !orient->strs.empty() && orient->strs[0] == "leftHanded";
+ const uint32_t baseIndex = uint32_t(m.positions.size());
+ for (const auto& q : pts) m.positions.push_back(glm::vec3(world[i] * glm::vec4(q, 1.0f)));
+ size_t cursor = 0;
+ for (double c : counts->nums) {
+ const size_t n = size_t(std::max(0.0, c));
+ if (cursor + n > indices->nums.size()) {
+ error = "Mesh " + p.path + " has fewer indices than its face counts need";
+ return false;
+ }
+ for (size_t k = 1; k + 1 < n; ++k) {
+ glm::uvec3 t(uint32_t(indices->nums[cursor]), uint32_t(indices->nums[cursor + k]),
+ uint32_t(indices->nums[cursor + k + 1]));
+ if (t.x >= pts.size() || t.y >= pts.size() || t.z >= pts.size()) {
+ error = "Mesh " + p.path + " has a face index out of range";
+ return false;
+ }
+ if (leftHanded) std::swap(t.y, t.z);
+ m.triangles.push_back(t + glm::uvec3(baseIndex));
+ }
+ cursor += n;
+ }
+ for (auto& l : layers) l.delta.resize(m.positions.size(), glm::vec3(0.0f));
+ // Blend shapes bound to this mesh.
+ const Value* names = p.get("skel:blendShapes");
+ const Value* targets = p.get("skel:blendShapeTargets");
+ if (names && targets) {
+ const glm::mat3 linear(world[i]);
+ for (size_t k = 0; k < names->strs.size() && k < targets->strs.size(); ++k) {
+ std::string target = targets->strs[k];
+ if (!target.empty() && target[0] != '/') target = p.path + "/" + target;
+ auto it = byPath.find(target);
+ if (it == byPath.end()) continue;
+ const Prim& shape = prims[it->second];
+ const auto offsets = vec3s(shape.get("offsets"));
+ const Value* pointIndices = shape.get("pointIndices");
+ SculptLayer& layer = layerFor(names->strs[k]);
+ layer.delta.resize(m.positions.size(), glm::vec3(0.0f));
+ for (size_t o = 0; o < offsets.size(); ++o) {
+ const size_t v = pointIndices ? (o < pointIndices->nums.size() ? size_t(pointIndices->nums[o]) : pts.size())
+ : o;
+ if (v < pts.size()) layer.delta[baseIndex + v] = linear * offsets[o];
+ }
+ }
+ }
+ } else if ((p.type == "ParticleField3DGaussianSplat" || p.type == "ParticleField") && !splatsFound) {
+ const auto pos = vec3s(p.get("positions"));
+ if (pos.empty()) continue;
+ const size_t n = pos.size();
+ const Value* degree = p.get("radiance:sphericalHarmonicsDegree");
+ int d = degree && !degree->nums.empty() ? std::clamp(int(degree->nums[0]), 0, 3) : 0;
+ auto coeffs = vec3s(p.get("radiance:sphericalHarmonicsCoefficients"));
+ if (coeffs.size() < n * size_t((d + 1) * (d + 1))) d = 0;
+ cloud.resize(n, d);
+ cloud.positions = pos;
+ const size_t K = size_t(cloud.shCount());
+ if (coeffs.size() >= n * K) std::copy(coeffs.begin(), coeffs.begin() + std::ptrdiff_t(n * K), cloud.sh.begin());
+ const auto sc = vec3s(p.get("scales"));
+ if (sc.size() >= n) std::copy(sc.begin(), sc.begin() + std::ptrdiff_t(n), cloud.scales.begin());
+ if (const Value* o = p.get("opacities"); o && o->nums.size() >= n)
+ for (size_t k = 0; k < n; ++k) cloud.opacities[k] = float(o->nums[k]);
+ if (const Value* q = p.get("orientations"); q && q->nums.size() >= n * 4)
+ for (size_t k = 0; k < n; ++k) {
+ const glm::quat r(float(q->nums[k * 4]), float(q->nums[k * 4 + 1]), float(q->nums[k * 4 + 2]),
+ float(q->nums[k * 4 + 3]));
+ const float len = glm::length(r);
+ cloud.rotations[k] = len > 0.0f ? r / len : glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
+ }
+ cloud.transform = world[i];
+ cloud.name = p.path.substr(p.path.rfind('/') + 1);
+ splatsFound = true;
+ }
+ }
+
+ if (m.triangles.empty() && !splatsFound) {
+ error = "No meshes or Gaussian splats found (references, payloads and binary .usdc layers are not supported yet)";
+ return false;
+ }
+ outMesh = m.triangles.empty() ? Mesh() : weldImported(m, layers);
+ outSplats = splatsFound ? std::move(cloud) : SplatCloud();
+ return true;
+}
+
+} // namespace
+
+std::string usdIdentifier(const std::string& text) {
+ std::string out;
+ for (unsigned char c : text) out += std::isalnum(c) ? char(c) : '_';
+ if (out.empty() || std::isdigit(static_cast<unsigned char>(out[0]))) out = "_" + out;
+ return out;
+}
+
+bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats, const std::string& name,
+ std::string& error) {
+ const bool hasMesh = mesh && mesh->triangleCount() > 0;
+ const bool hasSplats = splats && !splats->empty();
+ if (!hasMesh && !hasSplats) {
+ error = "Nothing to export";
+ return false;
+ }
+ if (hasSplats) {
+ if (std::string v = splats->validate(); !v.empty()) {
+ error = v;
+ return false;
+ }
+ }
+ const std::string text = buildUsda(hasMesh ? mesh : nullptr, hasSplats ? splats : nullptr, name);
+ const std::string ext = lowerExtension(path);
+ if (ext == ".usdz") {
+ std::string inner = usdIdentifier(name.empty() ? "Sculpt" : name) + ".usda";
+ return writeStoredZip(path, {{inner, std::vector<uint8_t>(text.begin(), text.end())}}, 64, error);
+ }
+ if (ext != ".usda" && ext != ".usd") {
+ error = "USD export needs a .usda, .usd or .usdz file name";
+ return false;
+ }
+ std::ofstream f(fsPath(path), std::ios::binary);
+ if (!f || !f.write(text.data(), std::streamsize(text.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::string& error) {
+ std::string text;
+ if (lowerExtension(path) == ".usdz") {
+ std::vector<ZipEntry> entries;
+ if (!readStoredZip(path, entries, error)) return false;
+ if (entries.empty()) {
+ error = "The USDZ package is empty";
+ return false;
+ }
+ text.assign(entries[0].data.begin(), entries[0].data.end());
+ } else {
+ std::ifstream f(fsPath(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ text.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
+ }
+ if (text.rfind("PXR-USDC", 0) == 0) {
+ error = "Binary USD (usdc) is not supported yet - save as .usda (e.g. usdcat in.usd -o out.usda)";
+ return false;
+ }
+ if (text.rfind("#usda", 0) != 0) {
+ error = path + " is not a text USD layer";
+ return false;
+ }
+ return readUsdaText(text, mesh, splats, error);
+}
+
+} // namespace sf
diff --git a/src/io/UsdIO.h b/src/io/UsdIO.h
new file mode 100644
index 00000000..93caf301
--- /dev/null
+++ b/src/io/UsdIO.h
@@ -0,0 +1,34 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// OpenUSD interchange without the OpenUSD SDK (keeps builds small and
+// portable). Writes text USD (.usda) and USDZ packages (.usdz, for AR Quick
+// Look / Vision Pro, Omniverse, Houdini Solaris, Blender, Maya, Unreal):
+// - the sculpt as a UsdGeomMesh with a UsdPreviewSurface clay material
+// - sculpt layers as UsdSkel blend shapes, current weights on a SkelAnimation
+// - Gaussian splats as a UsdVol ParticleField3DGaussianSplat prim (OpenUSD 26.03+)
+//
+// Reads .usda files and .usdz packages whose root layer is text: meshes (any
+// polygon counts, xform ops, Z-up stages), blend shapes and Gaussian splats.
+// Binary .usdc layers and external references are not resolved yet.
+#pragma once
+
+#include "core/Mesh.h"
+#include "core/Splats.h"
+
+#include <string>
+
+namespace sf {
+
+// Either pointer may be null (or empty) but not both. Format by extension.
+bool saveUsd(const std::string& path, const Mesh* mesh, const SplatCloud* splats, const std::string& name,
+ std::string& error);
+
+// Fills whichever of `mesh` / `splats` the file contains (the other is left
+// empty). Fails if it contains neither.
+bool loadUsd(const std::string& path, Mesh& mesh, SplatCloud& splats, std::string& error);
+
+// A valid USD prim name from arbitrary text ("Smile 2" -> "Smile_2").
+std::string usdIdentifier(const std::string& text);
+
+} // namespace sf
diff --git a/src/io/Zip.cpp b/src/io/Zip.cpp
new file mode 100644
index 00000000..cba404c7
--- /dev/null
+++ b/src/io/Zip.cpp
@@ -0,0 +1,171 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/Zip.h"
+
+#include <array>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+namespace sf {
+
+namespace {
+
+void put16(std::vector<uint8_t>& out, uint32_t v) {
+ out.push_back(uint8_t(v));
+ out.push_back(uint8_t(v >> 8));
+}
+void put32(std::vector<uint8_t>& out, uint32_t v) {
+ put16(out, v & 0xFFFF);
+ put16(out, v >> 16);
+}
+uint32_t get16(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8; }
+uint32_t get32(const uint8_t* p) { return get16(p) | get16(p + 2) << 16; }
+
+} // namespace
+
+uint32_t crc32(const uint8_t* data, size_t size) {
+ static const auto table = [] {
+ std::array<uint32_t, 256> t{};
+ for (uint32_t i = 0; i < 256; ++i) {
+ uint32_t c = i;
+ for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
+ t[i] = c;
+ }
+ return t;
+ }();
+ uint32_t c = 0xFFFFFFFFu;
+ for (size_t i = 0; i < size; ++i) c = table[(c ^ data[i]) & 0xFF] ^ (c >> 8);
+ return c ^ 0xFFFFFFFFu;
+}
+
+bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error) {
+ std::vector<uint8_t> out, central;
+ for (const auto& e : entries) {
+ if (e.data.size() > 0xFFFFFFFEu || out.size() > 0xFFFFFFFEu) {
+ error = "Archive too large (ZIP64 is not supported)";
+ return false;
+ }
+ const uint32_t crc = crc32(e.data.data(), e.data.size());
+ const uint32_t offset = uint32_t(out.size());
+ // Pad with an extra field so the file data starts on an aligned offset.
+ size_t dataStart = offset + 30 + e.name.size();
+ size_t pad = alignment > 1 ? (alignment - dataStart % alignment) % alignment : 0;
+ if (pad > 0 && pad < 4) pad += alignment; // an extra field needs at least its 4-byte header
+ put32(out, 0x04034B50);
+ put16(out, 20); // version needed
+ put16(out, 0); // flags
+ put16(out, 0); // stored
+ put16(out, 0); // time
+ put16(out, 0x21); // date (1980-01-01)
+ put32(out, crc);
+ put32(out, uint32_t(e.data.size()));
+ put32(out, uint32_t(e.data.size()));
+ put16(out, uint32_t(e.name.size()));
+ put16(out, uint32_t(pad));
+ out.insert(out.end(), e.name.begin(), e.name.end());
+ if (pad) {
+ put16(out, 0x1986); // padding extra field (same id as Pixar's usdzip)
+ put16(out, uint32_t(pad - 4));
+ out.insert(out.end(), pad - 4, 0);
+ }
+ out.insert(out.end(), e.data.begin(), e.data.end());
+
+ put32(central, 0x02014B50);
+ put16(central, 20); // version made by
+ put16(central, 20);
+ put16(central, 0);
+ put16(central, 0);
+ put16(central, 0);
+ put16(central, 0x21);
+ put32(central, crc);
+ put32(central, uint32_t(e.data.size()));
+ put32(central, uint32_t(e.data.size()));
+ put16(central, uint32_t(e.name.size()));
+ put16(central, 0); // extra
+ put16(central, 0); // comment
+ put16(central, 0); // disk
+ put16(central, 0); // internal attributes
+ put32(central, 0); // external attributes
+ put32(central, offset);
+ central.insert(central.end(), e.name.begin(), e.name.end());
+ }
+ const uint32_t centralOffset = uint32_t(out.size());
+ out.insert(out.end(), central.begin(), central.end());
+ put32(out, 0x06054B50);
+ put16(out, 0);
+ put16(out, 0);
+ put16(out, uint32_t(entries.size()));
+ put16(out, uint32_t(entries.size()));
+ put32(out, uint32_t(central.size()));
+ put32(out, centralOffset);
+ put16(out, 0);
+
+ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(out.data()), std::streamsize(out.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+bool readStoredZip(const std::string& path, std::vector<ZipEntry>& entries, std::string& error) {
+ std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<uint8_t> z((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ // Find the end-of-central-directory record.
+ size_t eocd = std::string::npos;
+ for (size_t i = z.size() >= 22 ? z.size() - 22 : 0; i + 22 <= z.size(); --i) {
+ if (get32(&z[i]) == 0x06054B50) {
+ eocd = i;
+ break;
+ }
+ if (i == 0 || z.size() - i > 65557) break;
+ }
+ if (eocd == std::string::npos) {
+ error = path + " is not a ZIP/USDZ archive";
+ return false;
+ }
+ const size_t count = get16(&z[eocd + 10]);
+ size_t p = get32(&z[eocd + 16]);
+ entries.clear();
+ for (size_t k = 0; k < count; ++k) {
+ if (p + 46 > z.size() || get32(&z[p]) != 0x02014B50) {
+ error = "Corrupt ZIP central directory";
+ return false;
+ }
+ const uint32_t method = get16(&z[p + 10]);
+ const uint32_t size = get32(&z[p + 20]);
+ const size_t nameLen = get16(&z[p + 28]), extraLen = get16(&z[p + 30]), commentLen = get16(&z[p + 32]);
+ const size_t local = get32(&z[p + 42]);
+ if (p + 46 + nameLen > z.size()) {
+ error = "Corrupt ZIP central directory";
+ return false;
+ }
+ ZipEntry e;
+ e.name.assign(reinterpret_cast<const char*>(&z[p + 46]), nameLen);
+ p += 46 + nameLen + extraLen + commentLen;
+ if (method != 0) {
+ error = "'" + e.name + "' is compressed; USDZ files must be uncompressed";
+ return false;
+ }
+ if (local + 30 > z.size() || get32(&z[local]) != 0x04034B50) {
+ error = "Corrupt ZIP entry " + e.name;
+ return false;
+ }
+ const size_t data = local + 30 + get16(&z[local + 26]) + get16(&z[local + 28]);
+ if (data + size > z.size()) {
+ error = "Truncated ZIP entry " + e.name;
+ return false;
+ }
+ e.data.assign(z.begin() + std::ptrdiff_t(data), z.begin() + std::ptrdiff_t(data + size));
+ entries.push_back(std::move(e));
+ }
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/Zip.h b/src/io/Zip.h
new file mode 100644
index 00000000..cb285872
--- /dev/null
+++ b/src/io/Zip.h
@@ -0,0 +1,27 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Minimal uncompressed ("stored") ZIP archives, which is exactly what USDZ
+// is: no compression, no encryption, every file's data 64-byte aligned.
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct ZipEntry {
+ std::string name;
+ std::vector<uint8_t> data;
+};
+
+uint32_t crc32(const uint8_t* data, size_t size);
+
+// Writes entries in order with each file's data aligned to `alignment` bytes.
+bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error);
+
+// Reads a ZIP whose entries are stored (uncompressed), as USDZ requires.
+bool readStoredZip(const std::string& path, std::vector<ZipEntry>& entries, std::string& error);
+
+} // namespace sf
diff --git a/src/link/Socket.cpp b/src/link/Socket.cpp
new file mode 100644
index 00000000..3000e83a
--- /dev/null
+++ b/src/link/Socket.cpp
@@ -0,0 +1,268 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "link/Socket.h"
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <ws2tcpip.h>
+using SockLen = int;
+#define SF_CLOSESOCKET closesocket
+#else
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <poll.h>
+#include <sys/socket.h>
+#include <unistd.h>
+using SockLen = socklen_t;
+#define SF_CLOSESOCKET ::close
+#endif
+#if defined(MSG_NOSIGNAL)
+constexpr int kSendFlags = MSG_NOSIGNAL; // a closed editor connection must not kill us with SIGPIPE
+#else
+constexpr int kSendFlags = 0;
+#endif
+
+#include <cstring>
+#include <mutex>
+
+namespace sf::link {
+
+namespace {
+
+#if defined(_WIN32)
+using Native = SOCKET;
+Native native(int64_t fd) { return fd < 0 ? INVALID_SOCKET : Native(fd); }
+bool invalid(Native s) { return s == INVALID_SOCKET; }
+std::string lastError() { return "socket error " + std::to_string(WSAGetLastError()); }
+#else
+using Native = int;
+Native native(int64_t fd) { return Native(fd); }
+bool invalid(Native s) { return s < 0; }
+std::string lastError() { return std::strerror(errno); }
+#endif
+
+bool parseAddress(const std::string& address, uint16_t port, sockaddr_in& out) {
+ std::memset(&out, 0, sizeof out);
+ out.sin_family = AF_INET;
+ out.sin_port = htons(port);
+ return inet_pton(AF_INET, address.c_str(), &out.sin_addr) == 1;
+}
+
+} // namespace
+
+bool initSockets() {
+#if defined(_WIN32)
+ static std::once_flag once;
+ static bool ok = false;
+ std::call_once(once, [] {
+ WSADATA data;
+ ok = WSAStartup(MAKEWORD(2, 2), &data) == 0;
+ });
+ return ok;
+#else
+ return true;
+#endif
+}
+
+Socket& Socket::operator=(Socket&& o) noexcept {
+ if (this != &o) {
+ close();
+ fd_ = o.fd_;
+ o.fd_ = -1;
+ }
+ return *this;
+}
+
+void Socket::close() {
+ if (fd_ >= 0) SF_CLOSESOCKET(native(fd_));
+ fd_ = -1;
+}
+
+bool Socket::waitReadable(int timeoutMs) const {
+#if defined(_WIN32)
+ WSAPOLLFD p{native(fd_), POLLRDNORM, 0};
+ return WSAPoll(&p, 1, timeoutMs) > 0;
+#else
+ pollfd p{native(fd_), POLLIN, 0};
+ return poll(&p, 1, timeoutMs) > 0;
+#endif
+}
+
+bool Socket::openMulticast(const std::string& group, uint16_t port, const std::string& bindAddress, int ttl,
+ std::string& error) {
+ close();
+ if (!initSockets()) {
+ error = "Networking is unavailable";
+ return false;
+ }
+ Native s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (invalid(s)) {
+ error = lastError();
+ return false;
+ }
+ fd_ = int64_t(s);
+ int yes = 1;
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&yes), sizeof yes);
+#if defined(SO_REUSEPORT)
+ setsockopt(s, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<const char*>(&yes), sizeof yes);
+#endif
+ sockaddr_in local;
+ // Bind to the group port on all interfaces so other nodes' multicasts reach us.
+ if (!parseAddress("0.0.0.0", port, local) || bind(s, reinterpret_cast<sockaddr*>(&local), sizeof local) != 0) {
+ error = "Cannot bind UDP port " + std::to_string(port) + ": " + lastError();
+ close();
+ return false;
+ }
+ ip_mreq mreq{};
+ in_addr iface{};
+ if (inet_pton(AF_INET, group.c_str(), &mreq.imr_multiaddr) != 1 || inet_pton(AF_INET, bindAddress.c_str(), &iface) != 1) {
+ error = "Invalid multicast address";
+ close();
+ return false;
+ }
+ mreq.imr_interface = iface;
+ bool joined = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof mreq) == 0;
+ if (!joined && iface.s_addr != htonl(INADDR_ANY)) {
+ // Some systems can't multicast on the requested interface (e.g. Linux loopback): let the OS pick.
+ mreq.imr_interface.s_addr = iface.s_addr = htonl(INADDR_ANY);
+ joined = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof mreq) == 0;
+ }
+ if (!joined) {
+ error = "Cannot join multicast group " + group + ": " + lastError();
+ close();
+ return false;
+ }
+ setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char*>(&iface), sizeof iface);
+ const unsigned char loop = 1, t = static_cast<unsigned char>(ttl);
+#if defined(_WIN32)
+ const DWORD loopW = loop, ttlW = t;
+ setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, reinterpret_cast<const char*>(&loopW), sizeof loopW);
+ setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, reinterpret_cast<const char*>(&ttlW), sizeof ttlW);
+#else
+ setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop);
+ setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &t, sizeof t);
+#endif
+ return true;
+}
+
+bool Socket::sendTo(const std::string& data, const std::string& address, uint16_t port, std::string& error) {
+ sockaddr_in to;
+ if (!parseAddress(address, port, to)) {
+ error = "Invalid address " + address;
+ return false;
+ }
+ const auto sent = sendto(native(fd_), data.data(), int(data.size()), 0, reinterpret_cast<sockaddr*>(&to), sizeof to);
+ if (sent < 0 || size_t(sent) != data.size()) {
+ error = lastError();
+ return false;
+ }
+ return true;
+}
+
+bool Socket::receive(std::string& data, int timeoutMs, std::string* from) {
+ if (!valid() || !waitReadable(timeoutMs)) return false;
+ char buf[65536];
+ sockaddr_in sender{};
+ SockLen len = sizeof sender;
+ const auto n = recvfrom(native(fd_), buf, sizeof buf, 0, reinterpret_cast<sockaddr*>(&sender), &len);
+ if (n <= 0) return false;
+ data.assign(buf, size_t(n));
+ if (from) {
+ char text[INET_ADDRSTRLEN] = {};
+ inet_ntop(AF_INET, &sender.sin_addr, text, sizeof text);
+ *from = text;
+ }
+ return true;
+}
+
+std::string localAddressToward(const std::string& remote) {
+ if (!initSockets()) return {};
+ Native s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (invalid(s)) return {};
+ sockaddr_in to;
+ std::string result;
+ // Connecting a UDP socket sends nothing; it just picks the route and source address.
+ if (parseAddress(remote, 9, to) && connect(s, reinterpret_cast<sockaddr*>(&to), sizeof to) == 0) {
+ sockaddr_in local{};
+ SockLen len = sizeof local;
+ if (getsockname(s, reinterpret_cast<sockaddr*>(&local), &len) == 0) {
+ char text[INET_ADDRSTRLEN] = {};
+ inet_ntop(AF_INET, &local.sin_addr, text, sizeof text);
+ result = text;
+ }
+ }
+ SF_CLOSESOCKET(s);
+ return result;
+}
+
+std::string hostName() {
+ if (!initSockets()) return {};
+ char name[256] = {};
+ return gethostname(name, sizeof name - 1) == 0 ? std::string(name) : std::string();
+}
+
+bool Socket::listen(const std::string& address, uint16_t port, uint16_t& boundPort, std::string& error) {
+ close();
+ if (!initSockets()) {
+ error = "Networking is unavailable";
+ return false;
+ }
+ Native s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (invalid(s)) {
+ error = lastError();
+ return false;
+ }
+ fd_ = int64_t(s);
+ sockaddr_in local;
+ if (!parseAddress(address, port, local) || bind(s, reinterpret_cast<sockaddr*>(&local), sizeof local) != 0 ||
+ ::listen(s, 1) != 0) {
+ error = "Cannot listen on " + address + ": " + lastError();
+ close();
+ return false;
+ }
+ SockLen len = sizeof local;
+ getsockname(s, reinterpret_cast<sockaddr*>(&local), &len);
+ boundPort = ntohs(local.sin_port);
+ return true;
+}
+
+bool Socket::accept(Socket& client, int timeoutMs) {
+ if (!valid() || !waitReadable(timeoutMs)) return false;
+ Native c = ::accept(native(fd_), nullptr, nullptr);
+ if (invalid(c)) return false;
+ client.close();
+ client.fd_ = int64_t(c);
+#if defined(SO_NOSIGPIPE)
+ int yes = 1;
+ setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof yes);
+#endif
+ return true;
+}
+
+bool Socket::sendAll(const std::string& data, std::string& error) {
+ size_t sent = 0;
+ while (sent < data.size()) {
+ const auto n = send(native(fd_), data.data() + sent, int(data.size() - sent), kSendFlags);
+ if (n <= 0) {
+ error = lastError();
+ return false;
+ }
+ sent += size_t(n);
+ }
+ return true;
+}
+
+bool Socket::receiveSome(std::string& data, size_t maxBytes, int timeoutMs) {
+ if (!valid() || !waitReadable(timeoutMs)) return false;
+ data.resize(maxBytes);
+ const auto n = recv(native(fd_), data.data(), int(maxBytes), 0);
+ if (n <= 0) {
+ data.clear();
+ return false;
+ }
+ data.resize(size_t(n));
+ return true;
+}
+
+} // namespace sf::link
diff --git a/src/link/Socket.h b/src/link/Socket.h
new file mode 100644
index 00000000..fb298f68
--- /dev/null
+++ b/src/link/Socket.h
@@ -0,0 +1,51 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tiny blocking socket wrapper (POSIX / Winsock) for talking to game-engine
+// editors on the local machine or network: UDP multicast discovery and a TCP
+// command channel. All calls take timeouts so a missing editor never hangs.
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+namespace sf::link {
+
+class Socket {
+public:
+ Socket() = default;
+ ~Socket() { close(); }
+ Socket(const Socket&) = delete;
+ Socket& operator=(const Socket&) = delete;
+ Socket(Socket&& o) noexcept : fd_(o.fd_) { o.fd_ = -1; }
+ Socket& operator=(Socket&& o) noexcept;
+
+ // UDP socket joined to `group` on `port`, sending with `ttl` (0 = this machine only).
+ bool openMulticast(const std::string& group, uint16_t port, const std::string& bindAddress, int ttl,
+ std::string& error);
+ bool sendTo(const std::string& data, const std::string& address, uint16_t port, std::string& error);
+ // Receives one datagram; false on timeout or error. `from` gets the sender's IPv4 address.
+ bool receive(std::string& data, int timeoutMs, std::string* from = nullptr);
+
+ // TCP listener on `address` (port 0 = any free port); `boundPort` reports the port.
+ bool listen(const std::string& address, uint16_t port, uint16_t& boundPort, std::string& error);
+ bool accept(Socket& client, int timeoutMs);
+ bool sendAll(const std::string& data, std::string& error);
+ // Reads whatever is available (up to `maxBytes`), waiting at most `timeoutMs`.
+ bool receiveSome(std::string& data, size_t maxBytes, int timeoutMs);
+
+ bool valid() const { return fd_ >= 0; }
+ void close();
+
+private:
+ bool waitReadable(int timeoutMs) const;
+ int64_t fd_ = -1;
+};
+
+// Initialises the socket library once (Winsock); harmless elsewhere.
+bool initSockets();
+// This machine's IPv4 address on the route to `remote` (e.g. its LAN address), or "" if unknown.
+std::string localAddressToward(const std::string& remote);
+std::string hostName();
+
+} // namespace sf::link
diff --git a/src/link/UnrealLink.cpp b/src/link/UnrealLink.cpp
new file mode 100644
index 00000000..70a97bac
--- /dev/null
+++ b/src/link/UnrealLink.cpp
@@ -0,0 +1,307 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "link/UnrealLink.h"
+
+#include "core/Json.h"
+#include "link/Socket.h"
+
+#include <atomic>
+#include <cctype>
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <random>
+#include <thread>
+
+namespace sf::link {
+
+namespace {
+
+constexpr int kProtocolVersion = 1;
+constexpr const char* kProtocolMagic = "ue_py";
+
+std::string newNodeId() {
+ std::random_device rd;
+ std::mt19937_64 rng((uint64_t(rd()) << 32) ^ rd() ^ uint64_t(std::chrono::steady_clock::now().time_since_epoch().count()));
+ const char* hex = "0123456789abcdef";
+ std::string id;
+ for (int i = 0; i < 32; ++i) {
+ if (i == 8 || i == 12 || i == 16 || i == 20) id += '-';
+ id += hex[rng() & 15];
+ }
+ return id;
+}
+
+bool parseMessage(const std::string& text, Json& msg) {
+ std::string err;
+ return Json::parse(text, msg, err) && msg["magic"].asString() == kProtocolMagic &&
+ int(msg["version"].asNumber()) == kProtocolVersion;
+}
+
+// Answers GET /<token>/... with `data` (once), until `done`.
+void serveFileOnce(Socket& listener, const std::string& token, const std::string& data, const std::atomic<bool>& done) {
+ while (!done) {
+ Socket client;
+ if (!listener.accept(client, 200)) continue;
+ std::string request, chunk;
+ while (request.find("\r\n\r\n") == std::string::npos && request.size() < 8192 && client.receiveSome(chunk, 4096, 5000))
+ request += chunk;
+ std::string err;
+ if (request.rfind("GET /" + token + "/", 0) != 0) {
+ client.sendAll("HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n", err);
+ continue;
+ }
+ client.sendAll("HTTP/1.0 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: " +
+ std::to_string(data.size()) + "\r\nConnection: close\r\n\r\n",
+ err);
+ client.sendAll(data, err);
+ return;
+ }
+}
+
+// Python string literal (repr-safe) for embedding paths and names in the import script.
+std::string pyString(const std::string& s) {
+ std::string out = "'";
+ for (unsigned char c : s) {
+ if (c == '\\' || c == '\'') {
+ out += '\\';
+ out += char(c);
+ } else if (c < 0x20) {
+ char buf[8];
+ std::snprintf(buf, sizeof buf, "\\x%02x", c);
+ out += buf;
+ } else {
+ out += char(c);
+ }
+ }
+ return out + "'";
+}
+
+} // namespace
+
+std::string unrealMessage(const std::string& type, const std::string& source, const std::string& dest,
+ const std::string& dataJson) {
+ std::string m = "{\"version\":" + std::to_string(kProtocolVersion) + ",\"magic\":\"" + kProtocolMagic +
+ "\",\"type\":" + jsonQuote(type) + ",\"source\":" + jsonQuote(source);
+ if (!dest.empty()) m += ",\"dest\":" + jsonQuote(dest);
+ if (!dataJson.empty()) m += ",\"data\":" + dataJson;
+ return m + "}";
+}
+
+bool UnrealEditor::local() const {
+ if (address.empty() || address.rfind("127.", 0) == 0) return true;
+ std::string a = machine, b = hostName();
+ for (auto* t : {&a, &b})
+ for (char& c : *t) c = char(std::tolower(static_cast<unsigned char>(c)));
+ return !a.empty() && a == b;
+}
+
+std::vector<UnrealEditor> findUnrealEditors(const UnrealEndpoint& e, int timeoutMs, std::string& error) {
+ std::vector<UnrealEditor> editors;
+ Socket udp;
+ if (!udp.openMulticast(e.multicastGroup, e.multicastPort, e.multicastBind, e.multicastTtl, error)) return editors;
+ const std::string self = newNodeId();
+ if (!udp.sendTo(unrealMessage("ping", self, "", ""), e.multicastGroup, e.multicastPort, error)) return editors;
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
+ while (true) {
+ const int left = int(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count());
+ if (left <= 0) break;
+ std::string data, from;
+ if (!udp.receive(data, left, &from)) continue;
+ Json msg;
+ if (!parseMessage(data, msg) || msg["type"].asString() != "pong" || msg["dest"].asString() != self) continue;
+ UnrealEditor ed;
+ ed.nodeId = msg["source"].asString();
+ const Json& d = msg["data"];
+ ed.projectName = d["project_name"].asString();
+ ed.projectRoot = d["project_root"].asString();
+ ed.engineVersion = d["engine_version"].asString();
+ ed.machine = d["machine"].asString();
+ ed.user = d["user"].asString();
+ ed.address = from;
+ bool known = false;
+ for (const auto& x : editors) known = known || x.nodeId == ed.nodeId;
+ if (!known && !ed.nodeId.empty()) editors.push_back(ed);
+ }
+ return editors;
+}
+
+bool runInUnreal(const UnrealEndpoint& e, const UnrealEditor& editor, const std::string& python, std::string& output,
+ std::string& error, int timeoutMs) {
+ Socket udp;
+ if (!udp.openMulticast(e.multicastGroup, e.multicastPort, e.multicastBind, e.multicastTtl, error)) return false;
+ // The editor connects back to us for the command channel.
+ std::string commandIp = e.commandAddress;
+ if (commandIp.empty()) commandIp = editor.local() ? "127.0.0.1" : localAddressToward(editor.address);
+ if (commandIp.empty()) {
+ error = "Cannot find a network route to " + editor.machine;
+ return false;
+ }
+ Socket server;
+ uint16_t port = 0;
+ if (!server.listen(commandIp, 0, port, error)) return false;
+ const std::string self = newNodeId();
+ const std::string open = "{\"command_ip\":" + jsonQuote(commandIp) + ",\"command_port\":" + std::to_string(port) + "}";
+ if (!udp.sendTo(unrealMessage("open_connection", self, editor.nodeId, open), e.multicastGroup, e.multicastPort, error))
+ return false;
+ Socket channel;
+ bool connected = false;
+ for (int attempt = 0; attempt < 3 && !connected; ++attempt) {
+ if (attempt > 0)
+ udp.sendTo(unrealMessage("open_connection", self, editor.nodeId, open), e.multicastGroup, e.multicastPort, error);
+ connected = server.accept(channel, 4000);
+ }
+ if (!connected) {
+ error = "Unreal didn't connect back to " + commandIp + ":" + std::to_string(port) +
+ " (a firewall on this computer may be blocking it)";
+ return false;
+ }
+ Json data = Json::object();
+ data.set("command", python);
+ data.set("unattended", true);
+ data.set("exec_mode", "ExecuteFile");
+ bool ok = channel.sendAll(unrealMessage("command", self, editor.nodeId, data.dump()), error);
+ std::string reply;
+ Json result;
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
+ while (ok) {
+ const int left = int(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count());
+ std::string chunk;
+ if (left <= 0) {
+ error = "Unreal didn't answer in time (the import may still be running)";
+ ok = false;
+ break;
+ }
+ if (!channel.receiveSome(chunk, 1 << 16, left)) {
+ if (!channel.valid()) break;
+ continue;
+ }
+ reply += chunk;
+ // The reply is one JSON object with no framing: wait until it parses.
+ if (parseMessage(reply, result) && result["type"].asString() == "command_result") break;
+ if (reply.size() > (64u << 20)) {
+ error = "Unreasonably large reply from Unreal";
+ ok = false;
+ break;
+ }
+ }
+ udp.sendTo(unrealMessage("close_connection", self, editor.nodeId, ""), e.multicastGroup, e.multicastPort, error);
+ if (!ok) return false;
+ const Json& d = result["data"];
+ for (const auto& line : d["output"].items()) output += line["output"].asString() + "\n";
+ if (d["result"].isString() && d["result"].asString() != "None") output += d["result"].asString() + "\n";
+ if (!d["success"].asBool(false)) {
+ error = output.empty() ? "The Python command failed in Unreal" : output;
+ return false;
+ }
+ return true;
+}
+
+std::string unrealImportScript(const UnrealImport& im) {
+ std::string py;
+ py += "import unreal\n";
+ std::string fileExpr = pyString(im.fbxPath);
+ if (!im.downloadUrl.empty()) {
+ // The editor is on another computer: fetch the file from SculptForge into its temp folder.
+ const std::string name = std::filesystem::path(std::u8string(im.fbxPath.begin(), im.fbxPath.end())).filename().string();
+ py += "import os, tempfile, urllib.request\n";
+ py += "folder = os.path.join(tempfile.gettempdir(), 'sculptforge')\n";
+ py += "os.makedirs(folder, exist_ok=True)\n";
+ py += "fbx_path = os.path.join(folder, " + pyString(name) + ")\n";
+ py += "with urllib.request.urlopen(" + pyString(im.downloadUrl) + ", timeout=120) as r, open(fbx_path, 'wb') as f:\n";
+ py += " f.write(r.read())\n";
+ fileExpr = "fbx_path";
+ }
+ py += "task = unreal.AssetImportTask()\n";
+ py += "task.set_editor_property('filename', " + fileExpr + ")\n";
+ py += "task.set_editor_property('destination_path', " + pyString(im.destination) + ")\n";
+ py += "task.set_editor_property('destination_name', " + pyString(im.assetName) + ")\n";
+ py += "task.set_editor_property('replace_existing', True)\n";
+ py += "task.set_editor_property('automated', True)\n";
+ py += "task.set_editor_property('save', True)\n";
+ py += "ui = unreal.FbxImportUI()\n";
+ py += "ui.set_editor_property('import_mesh', True)\n";
+ py += "ui.set_editor_property('import_materials', True)\n";
+ py += "ui.set_editor_property('import_textures', False)\n";
+ py += "ui.set_editor_property('import_animations', False)\n";
+ if (im.skeletal) {
+ py += "ui.set_editor_property('import_as_skeletal', True)\n";
+ py += "ui.set_editor_property('mesh_type_to_import', unreal.FBXImportType.FBXIT_SKELETAL_MESH)\n";
+ py += "ui.skeletal_mesh_import_data.set_editor_property('import_morph_targets', True)\n";
+ } else {
+ py += "ui.set_editor_property('import_as_skeletal', False)\n";
+ py += "ui.set_editor_property('mesh_type_to_import', unreal.FBXImportType.FBXIT_STATIC_MESH)\n";
+ py += "ui.static_mesh_import_data.set_editor_property('import_mesh_lo_ds', " + std::string(im.lods ? "True" : "False") + ")\n";
+ py += "ui.static_mesh_import_data.set_editor_property('combine_meshes', True)\n";
+ }
+ py += "ui.set_editor_property('automated_import_should_detect_type', False)\n";
+ py += "task.set_editor_property('options', ui)\n";
+ // Use the FBX factory directly so these options apply as-is (UE 5.5+ would otherwise route
+ // through Interchange, which ignores the asset name and maps only some options).
+ // (The factory reads its options from task.options.)
+ py += "try:\n";
+ py += " task.set_editor_property('factory', unreal.FbxFactory())\n";
+ py += "except Exception as e:\n";
+ py += " unreal.log_warning('SculptForge: using the default importer (' + str(e) + ')')\n";
+ py += "unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])\n";
+ py += "paths = list(task.get_editor_property('imported_object_paths') or [])\n";
+ py += "print('SCULPTFORGE_IMPORTED ' + (', '.join(paths) if paths else 'nothing'))\n";
+ return py;
+}
+
+bool sendToUnreal(const UnrealEndpoint& endpoint, const UnrealImport& import, std::string& message,
+ const std::string& projectName) {
+ std::string error;
+ auto editors = findUnrealEditors(endpoint, 1500, error);
+ if (editors.empty()) {
+ message = error.empty() ? "No Unreal Editor found - enable the Python Editor Script Plugin and Project Settings > "
+ "Plugins > Python > Enable Remote Execution, then try again"
+ : "Unreal discovery failed: " + error;
+ return false;
+ }
+ const UnrealEditor* target = &editors[0];
+ for (const auto& ed : editors)
+ if (!projectName.empty() && ed.projectName == projectName) target = &ed;
+ UnrealImport send = import;
+ // A remote editor can't read our file path: serve the file once over HTTP while the import runs.
+ Socket http;
+ std::thread server;
+ std::atomic<bool> done{false};
+ if (!target->local()) {
+ std::string data;
+ {
+ std::ifstream f(std::filesystem::path(std::u8string(send.fbxPath.begin(), send.fbxPath.end())), std::ios::binary);
+ data.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
+ }
+ const std::string ip = localAddressToward(target->address);
+ uint16_t port = 0;
+ if (data.empty() || ip.empty() || !http.listen(ip, 0, port, error)) {
+ message = data.empty() ? "Cannot read " + send.fbxPath : "Cannot serve the file to " + target->machine + ": " + error;
+ return false;
+ }
+ const std::string token = newNodeId();
+ send.downloadUrl = "http://" + ip + ":" + std::to_string(port) + "/" + token + "/" +
+ std::filesystem::path(std::u8string(send.fbxPath.begin(), send.fbxPath.end())).filename().string();
+ server = std::thread([&http, &done, token, data = std::move(data)] { serveFileOnce(http, token, data, done); });
+ }
+ std::string output;
+ const bool ran = runInUnreal(endpoint, *target, unrealImportScript(send), output, error, 300000);
+ done = true;
+ if (server.joinable()) server.join();
+ if (!ran) {
+ message = "Unreal import failed: " + error;
+ return false;
+ }
+ const size_t at = output.find("SCULPTFORGE_IMPORTED ");
+ std::string imported = at == std::string::npos ? std::string() : output.substr(at + 20);
+ while (!imported.empty() && (imported.back() == '\n' || imported.back() == '\r')) imported.pop_back();
+ if (imported.empty() || imported == "nothing") {
+ message = "Unreal ran the import but reported no asset - check the Output Log in " + target->projectName;
+ return false;
+ }
+ message = "Sent to Unreal (" + target->projectName + "): " + imported;
+ return true;
+}
+
+} // namespace sf::link
diff --git a/src/link/UnrealLink.h b/src/link/UnrealLink.h
new file mode 100644
index 00000000..873022dc
--- /dev/null
+++ b/src/link/UnrealLink.h
@@ -0,0 +1,71 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// "Send to Unreal": pushes an exported FBX into a running Unreal Editor
+// through Unreal's built-in Python remote execution (the same channel Epic's
+// own tools use). No plugin to install - the project needs the Python Editor
+// Script Plugin enabled and "Enable Remote Execution" ticked in
+// Project Settings > Plugins > Python.
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf::link {
+
+struct UnrealEndpoint {
+ std::string multicastGroup = "239.0.0.1";
+ uint16_t multicastPort = 6766;
+ std::string multicastBind = "127.0.0.1"; // multicast interface; must match Unreal's "Multicast Bind Address"
+ int multicastTtl = 0; // 0 = this machine only; 1 = editors on the local network
+ std::string commandAddress; // empty = pick automatically (127.0.0.1, or our LAN address)
+
+ // Settings for an Unreal Editor on another computer (it must use the same TTL and bind address).
+ static UnrealEndpoint network() {
+ UnrealEndpoint e;
+ e.multicastTtl = 1;
+ e.multicastBind = "0.0.0.0";
+ return e;
+ }
+};
+
+struct UnrealEditor {
+ std::string nodeId;
+ std::string projectName;
+ std::string projectRoot;
+ std::string engineVersion;
+ std::string machine;
+ std::string user;
+ std::string address; // where its discovery reply came from
+ bool local() const; // running on this computer
+};
+
+// Finds running editors with remote execution enabled.
+std::vector<UnrealEditor> findUnrealEditors(const UnrealEndpoint& endpoint, int timeoutMs, std::string& error);
+
+// Runs Python in the editor. `output` collects what the script printed.
+bool runInUnreal(const UnrealEndpoint& endpoint, const UnrealEditor& editor, const std::string& python,
+ std::string& output, std::string& error, int timeoutMs = 60000);
+
+struct UnrealImport {
+ std::string fbxPath; // file on this machine
+ std::string downloadUrl; // if set, the editor fetches the file from here (other computer)
+ std::string destination = "/Game/SculptForge"; // content folder
+ std::string assetName; // e.g. SM_Rock
+ bool skeletal = false; // needed for morph targets (blend shapes)
+ bool lods = false; // file has an LOD group
+};
+// Python that imports (or reimports, replacing) the asset and prints a result line.
+std::string unrealImportScript(const UnrealImport& import);
+
+// Finds an editor (the first one, or the one whose project name matches) and
+// imports. `message` is a human-readable result either way.
+bool sendToUnreal(const UnrealEndpoint& endpoint, const UnrealImport& import, std::string& message,
+ const std::string& projectName = {});
+
+// Protocol messages (exposed for tests).
+std::string unrealMessage(const std::string& type, const std::string& source, const std::string& dest,
+ const std::string& dataJson);
+
+} // namespace sf::link
diff --git a/src/render/Camera.cpp b/src/render/Camera.cpp
new file mode 100644
index 00000000..ac890e2b
--- /dev/null
+++ b/src/render/Camera.cpp
@@ -0,0 +1,62 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "render/Camera.h"
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+glm::quat Camera::orientation() const {
+ return glm::angleAxis(yaw, glm::vec3(0, 1, 0)) * glm::angleAxis(pitch, glm::vec3(1, 0, 0));
+}
+
+glm::vec3 Camera::position() const { return target + orientation() * glm::vec3(0, 0, distance); }
+
+glm::vec3 Camera::forward() const { return orientation() * glm::vec3(0, 0, -1); }
+
+glm::mat4 Camera::view() const {
+ glm::mat4 world = glm::translate(glm::mat4(1.0f), position()) * glm::mat4_cast(orientation());
+ return glm::inverse(world);
+}
+
+glm::mat4 Camera::projection() const { return glm::perspective(fovY, aspect, nearPlane(), farPlane()); }
+
+void Camera::orbit(float dx, float dy) {
+ yaw -= dx * 0.008f;
+ pitch = std::clamp(pitch - dy * 0.008f, -glm::radians(89.0f), glm::radians(89.0f));
+}
+
+void Camera::pan(float dx, float dy, float viewportHeight) {
+ float scale = 2.0f * distance * std::tan(fovY * 0.5f) / std::max(viewportHeight, 1.0f);
+ glm::quat q = orientation();
+ target += q * glm::vec3(-dx * scale, dy * scale, 0.0f);
+}
+
+void Camera::zoom(float steps) { distance = std::clamp(distance * std::pow(0.88f, steps), 1e-4f, 1e6f); }
+
+void Camera::frame(const AABB& box) {
+ if (!box.valid()) return;
+ target = box.center();
+ float radius = std::max(glm::length(box.extent()) * 0.5f, 1e-4f);
+ distance = radius / std::sin(fovY * 0.5f) * 1.1f;
+}
+
+void Camera::screenRay(float x, float y, float width, float height, glm::vec3& origin, glm::vec3& dir) const {
+ float nx = 2.0f * x / width - 1.0f;
+ float ny = 1.0f - 2.0f * y / height;
+ glm::mat4 inv = glm::inverse(projection() * view());
+ glm::vec4 a = inv * glm::vec4(nx, ny, -1.0f, 1.0f);
+ glm::vec4 b = inv * glm::vec4(nx, ny, 1.0f, 1.0f);
+ origin = glm::vec3(a) / a.w;
+ dir = glm::normalize(glm::vec3(b) / b.w - origin);
+}
+
+float Camera::worldPerPixel(const glm::vec3& point, float viewportHeight) const {
+ float depth = std::max(glm::dot(point - position(), forward()), nearPlane());
+ return 2.0f * depth * std::tan(fovY * 0.5f) / std::max(viewportHeight, 1.0f);
+}
+
+} // namespace sf
diff --git a/src/render/Camera.h b/src/render/Camera.h
new file mode 100644
index 00000000..801affd0
--- /dev/null
+++ b/src/render/Camera.h
@@ -0,0 +1,43 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <glm/glm.hpp>
+#include <glm/gtc/quaternion.hpp>
+
+namespace sf {
+
+// Turntable orbit camera.
+class Camera {
+public:
+ glm::vec3 target{0.0f};
+ float distance = 4.0f;
+ float yaw = 0.0f; // radians around world Y
+ float pitch = 0.0f; // radians, clamped to avoid flipping
+ float fovY = glm::radians(35.0f);
+ float aspect = 1.0f;
+
+ glm::quat orientation() const;
+ glm::vec3 position() const;
+ glm::vec3 forward() const;
+ glm::mat4 view() const;
+ glm::mat4 projection() const;
+
+ void orbit(float dxPixels, float dyPixels);
+ void pan(float dxPixels, float dyPixels, float viewportHeight);
+ void zoom(float steps);
+ void frame(const AABB& box);
+
+ // Ray through a window coordinate (origin top-left).
+ void screenRay(float x, float y, float width, float height, glm::vec3& origin, glm::vec3& dir) const;
+ // World units covered by one window pixel at the depth of `point`.
+ float worldPerPixel(const glm::vec3& point, float viewportHeight) const;
+
+private:
+ float nearPlane() const { return distance * 0.01f; }
+ float farPlane() const { return distance * 100.0f; }
+};
+
+} // namespace sf
diff --git a/src/render/GL.cpp b/src/render/GL.cpp
new file mode 100644
index 00000000..98bf666e
--- /dev/null
+++ b/src/render/GL.cpp
@@ -0,0 +1,20 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "render/GL.h"
+
+namespace gl {
+
+#define SF_GL_DEFINE(ret, name, ...) PFN_##name name = nullptr;
+SF_GL_FUNCTIONS(SF_GL_DEFINE)
+#undef SF_GL_DEFINE
+
+const char* load(ProcLoader loader) {
+#define SF_GL_LOAD(ret, name, ...) \
+ name = reinterpret_cast<PFN_##name>(loader("gl" #name)); \
+ if (!name) return "gl" #name;
+ SF_GL_FUNCTIONS(SF_GL_LOAD)
+#undef SF_GL_LOAD
+ return nullptr;
+}
+
+} // namespace gl
diff --git a/src/render/GL.h b/src/render/GL.h
new file mode 100644
index 00000000..30459a85
--- /dev/null
+++ b/src/render/GL.h
@@ -0,0 +1,168 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Minimal OpenGL 3.3 core loader covering exactly the functions we use.
+// Avoids a generated loader dependency; works on Linux, macOS and Windows.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#if defined(_WIN32)
+#define SF_GLAPI __stdcall
+#else
+#define SF_GLAPI
+#endif
+
+using GLenum = unsigned int;
+using GLbitfield = unsigned int;
+using GLuint = unsigned int;
+using GLint = int;
+using GLsizei = int;
+using GLboolean = unsigned char;
+using GLfloat = float;
+using GLchar = char;
+using GLubyte = unsigned char;
+using GLsizeiptr = std::ptrdiff_t;
+using GLintptr = std::ptrdiff_t;
+
+constexpr GLenum GL_FALSE = 0;
+constexpr GLenum GL_TRUE = 1;
+constexpr GLenum GL_TRIANGLES = 0x0004;
+constexpr GLenum GL_LEQUAL = 0x0203;
+constexpr GLenum GL_SRC_ALPHA = 0x0302;
+constexpr GLenum GL_ONE_MINUS_SRC_ALPHA = 0x0303;
+constexpr GLenum GL_FRONT_AND_BACK = 0x0408;
+constexpr GLenum GL_DEPTH_TEST = 0x0B71;
+constexpr GLenum GL_BLEND = 0x0BE2;
+constexpr GLenum GL_UNSIGNED_INT = 0x1405;
+constexpr GLenum GL_FLOAT = 0x1406;
+constexpr GLenum GL_LINE = 0x1B01;
+constexpr GLenum GL_FILL = 0x1B02;
+constexpr GLenum GL_RENDERER = 0x1F01;
+constexpr GLenum GL_VERSION = 0x1F02;
+constexpr GLenum GL_POLYGON_OFFSET_FILL = 0x8037;
+constexpr GLenum GL_MULTISAMPLE = 0x809D;
+constexpr GLenum GL_ARRAY_BUFFER = 0x8892;
+constexpr GLenum GL_ELEMENT_ARRAY_BUFFER = 0x8893;
+constexpr GLenum GL_STATIC_DRAW = 0x88E4;
+constexpr GLenum GL_DYNAMIC_DRAW = 0x88E8;
+constexpr GLenum GL_FRAGMENT_SHADER = 0x8B30;
+constexpr GLenum GL_VERTEX_SHADER = 0x8B31;
+constexpr GLenum GL_COMPILE_STATUS = 0x8B81;
+constexpr GLenum GL_LINK_STATUS = 0x8B82;
+constexpr GLenum GL_TEXTURE_2D = 0x0DE1;
+constexpr GLenum GL_UNPACK_ALIGNMENT = 0x0CF5;
+constexpr GLenum GL_PACK_ALIGNMENT = 0x0D05;
+constexpr GLenum GL_UNSIGNED_BYTE = 0x1401;
+constexpr GLenum GL_RGBA = 0x1908;
+constexpr GLenum GL_NEAREST = 0x2600;
+constexpr GLenum GL_LINEAR = 0x2601;
+constexpr GLenum GL_TEXTURE_MAG_FILTER = 0x2800;
+constexpr GLenum GL_TEXTURE_MIN_FILTER = 0x2801;
+constexpr GLenum GL_TEXTURE_WRAP_S = 0x2802;
+constexpr GLenum GL_TEXTURE_WRAP_T = 0x2803;
+constexpr GLenum GL_RGBA8 = 0x8058;
+constexpr GLenum GL_DEPTH_COMPONENT24 = 0x81A6;
+constexpr GLenum GL_CLAMP_TO_EDGE = 0x812F;
+constexpr GLenum GL_READ_FRAMEBUFFER = 0x8CA8;
+constexpr GLenum GL_DRAW_FRAMEBUFFER = 0x8CA9;
+constexpr GLenum GL_FRAMEBUFFER_COMPLETE = 0x8CD5;
+constexpr GLenum GL_COLOR_ATTACHMENT0 = 0x8CE0;
+constexpr GLenum GL_DEPTH_ATTACHMENT = 0x8D00;
+constexpr GLenum GL_FRAMEBUFFER = 0x8D40;
+constexpr GLenum GL_RENDERBUFFER = 0x8D41;
+constexpr GLenum GL_ONE = 1;
+constexpr GLenum GL_TRIANGLE_STRIP = 0x0005;
+constexpr GLenum GL_TEXTURE0 = 0x84C0;
+constexpr GLenum GL_RGBA32F = 0x8814;
+constexpr GLenum GL_STREAM_DRAW = 0x88E0;
+constexpr GLenum GL_TEXTURE_BUFFER = 0x8C2A;
+constexpr GLenum GL_MAX_TEXTURE_BUFFER_SIZE = 0x8C2B;
+constexpr GLbitfield GL_DEPTH_BUFFER_BIT = 0x0100;
+constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;
+
+#define SF_GL_FUNCTIONS(X) \
+ X(void, Clear, GLbitfield) \
+ X(void, ClearColor, GLfloat, GLfloat, GLfloat, GLfloat) \
+ X(void, Viewport, GLint, GLint, GLsizei, GLsizei) \
+ X(void, Enable, GLenum) \
+ X(void, Disable, GLenum) \
+ X(void, DepthFunc, GLenum) \
+ X(void, DepthMask, GLboolean) \
+ X(void, BlendFunc, GLenum, GLenum) \
+ X(void, PolygonMode, GLenum, GLenum) \
+ X(void, PolygonOffset, GLfloat, GLfloat) \
+ X(const GLubyte*, GetString, GLenum) \
+ X(void, GenBuffers, GLsizei, GLuint*) \
+ X(void, DeleteBuffers, GLsizei, const GLuint*) \
+ X(void, BindBuffer, GLenum, GLuint) \
+ X(void, BufferData, GLenum, GLsizeiptr, const void*, GLenum) \
+ X(void, BufferSubData, GLenum, GLintptr, GLsizeiptr, const void*) \
+ X(void, GenVertexArrays, GLsizei, GLuint*) \
+ X(void, DeleteVertexArrays, GLsizei, const GLuint*) \
+ X(void, BindVertexArray, GLuint) \
+ X(void, EnableVertexAttribArray, GLuint) \
+ X(void, VertexAttribPointer, GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) \
+ X(GLuint, CreateShader, GLenum) \
+ X(void, ShaderSource, GLuint, GLsizei, const GLchar* const*, const GLint*) \
+ X(void, CompileShader, GLuint) \
+ X(void, GetShaderiv, GLuint, GLenum, GLint*) \
+ X(void, GetShaderInfoLog, GLuint, GLsizei, GLsizei*, GLchar*) \
+ X(GLuint, CreateProgram) \
+ X(void, AttachShader, GLuint, GLuint) \
+ X(void, LinkProgram, GLuint) \
+ X(void, GetProgramiv, GLuint, GLenum, GLint*) \
+ X(void, GetProgramInfoLog, GLuint, GLsizei, GLsizei*, GLchar*) \
+ X(void, DeleteShader, GLuint) \
+ X(void, DeleteProgram, GLuint) \
+ X(void, UseProgram, GLuint) \
+ X(GLint, GetUniformLocation, GLuint, const GLchar*) \
+ X(void, UniformMatrix4fv, GLint, GLsizei, GLboolean, const GLfloat*) \
+ X(void, Uniform3fv, GLint, GLsizei, const GLfloat*) \
+ X(void, Uniform4fv, GLint, GLsizei, const GLfloat*) \
+ X(void, DrawElements, GLenum, GLsizei, GLenum, const void*) \
+ X(void, DrawArrays, GLenum, GLint, GLsizei) \
+ X(void, GenTextures, GLsizei, GLuint*) \
+ X(void, DeleteTextures, GLsizei, const GLuint*) \
+ X(void, BindTexture, GLenum, GLuint) \
+ X(void, TexImage2D, GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) \
+ X(void, TexParameteri, GLenum, GLenum, GLint) \
+ X(void, PixelStorei, GLenum, GLint) \
+ X(void, ReadPixels, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) \
+ X(void, GenFramebuffers, GLsizei, GLuint*) \
+ X(void, DeleteFramebuffers, GLsizei, const GLuint*) \
+ X(void, BindFramebuffer, GLenum, GLuint) \
+ X(GLenum, CheckFramebufferStatus, GLenum) \
+ X(void, FramebufferRenderbuffer, GLenum, GLenum, GLenum, GLuint) \
+ X(void, GenRenderbuffers, GLsizei, GLuint*) \
+ X(void, DeleteRenderbuffers, GLsizei, const GLuint*) \
+ X(void, BindRenderbuffer, GLenum, GLuint) \
+ X(void, RenderbufferStorage, GLenum, GLenum, GLsizei, GLsizei) \
+ X(void, RenderbufferStorageMultisample, GLenum, GLsizei, GLenum, GLsizei, GLsizei) \
+ X(void, BlitFramebuffer, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) \
+ X(void, TexBuffer, GLenum, GLenum, GLuint) \
+ X(void, VertexAttribIPointer, GLuint, GLint, GLenum, GLsizei, const void*) \
+ X(void, VertexAttribDivisor, GLuint, GLuint) \
+ X(void, DrawArraysInstanced, GLenum, GLint, GLsizei, GLsizei) \
+ X(void, ActiveTexture, GLenum) \
+ X(void, GetIntegerv, GLenum, GLint*) \
+ X(void, Uniform1i, GLint, GLint) \
+ X(void, Uniform1f, GLint, GLfloat) \
+ X(void, Uniform2f, GLint, GLfloat, GLfloat)
+
+namespace gl {
+
+#define SF_GL_DECLARE(ret, name, ...) \
+ using PFN_##name = ret(SF_GLAPI*)(__VA_ARGS__); \
+ extern PFN_##name name;
+SF_GL_FUNCTIONS(SF_GL_DECLARE)
+#undef SF_GL_DECLARE
+
+using GenericProc = void (*)();
+using ProcLoader = GenericProc (*)(const char* name);
+
+// Returns the name of the first missing function, or nullptr on success.
+const char* load(ProcLoader loader);
+
+} // namespace gl
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
new file mode 100644
index 00000000..1759dd62
--- /dev/null
+++ b/src/render/Renderer.cpp
@@ -0,0 +1,485 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "render/Renderer.h"
+
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+#include <limits>
+#include <vector>
+
+namespace sf {
+
+namespace {
+
+const char* kMeshVS = R"(#version 330 core
+layout(location = 0) in vec3 aPos;
+layout(location = 1) in vec3 aNormal;
+uniform mat4 uView;
+uniform mat4 uProj;
+out vec3 vNormal;
+out vec3 vPos;
+void main() {
+ vec4 p = uView * vec4(aPos, 1.0);
+ vPos = p.xyz;
+ vNormal = mat3(uView) * aNormal;
+ gl_Position = uProj * p;
+}
+)";
+
+// Studio "clay" shading: wrapped key light, cool fill, rim and soft spec.
+const char* kMeshFS = R"(#version 330 core
+in vec3 vNormal;
+in vec3 vPos;
+uniform vec3 uColor;
+out vec4 fragColor;
+void main() {
+ vec3 n = normalize(vNormal);
+ if (!gl_FrontFacing) n = -n;
+ vec3 v = normalize(-vPos);
+ vec3 key = normalize(vec3(0.45, 0.65, 0.6));
+ vec3 fill = normalize(vec3(-0.7, -0.1, 0.4));
+ float diff = max((dot(n, key) + 0.25) / 1.25, 0.0);
+ float fillL = max(dot(n, fill), 0.0) * 0.25;
+ float hemi = 0.5 + 0.5 * n.y;
+ vec3 h = normalize(key + v);
+ float spec = pow(max(dot(n, h), 0.0), 40.0) * 0.18;
+ float rim = pow(1.0 - max(dot(n, v), 0.0), 3.0) * 0.3;
+ float cavity = smoothstep(-0.2, 0.6, dot(n, v));
+ vec3 c = uColor * (0.18 * hemi + 0.85 * diff + fillL * vec3(0.7, 0.8, 1.0)) * mix(0.75, 1.0, cavity);
+ c += vec3(spec) + rim * vec3(0.8, 0.85, 1.0);
+ fragColor = vec4(pow(c, vec3(1.0 / 2.2)), 1.0);
+}
+)";
+
+const char* kWireFS = R"(#version 330 core
+out vec4 fragColor;
+void main() { fragColor = vec4(0.05, 0.05, 0.08, 0.35); }
+)";
+
+const char* kBgVS = R"(#version 330 core
+out vec2 vUv;
+void main() {
+ vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
+ vUv = p;
+ gl_Position = vec4(p * 2.0 - 1.0, 1.0, 1.0);
+}
+)";
+
+const char* kBgFS = R"(#version 330 core
+in vec2 vUv;
+out vec4 fragColor;
+void main() {
+ vec3 top = vec3(0.20, 0.21, 0.24);
+ vec3 bottom = vec3(0.08, 0.08, 0.09);
+ float d = length(vUv - vec2(0.5, 0.55));
+ vec3 c = mix(bottom, top, clamp(vUv.y, 0.0, 1.0)) * (1.0 - 0.35 * d);
+ fragColor = vec4(c, 1.0);
+}
+)";
+
+// 3D Gaussian splats (EWA projection of each 3D covariance to a screen-space ellipse).
+const char* kSplatVS = R"(#version 330 core
+layout(location = 0) in uint aIndex;
+uniform samplerBuffer uSplats;
+uniform mat4 uView;
+uniform mat4 uProj;
+uniform vec2 uViewport;
+uniform float uOpacity;
+out vec4 vColor;
+out vec2 vOffset;
+const vec2 kCorners[4] = vec2[4](vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0));
+void main() {
+ int base = int(aIndex) * 4;
+ vec4 t0 = texelFetch(uSplats, base); // centre, opacity
+ vec4 t1 = texelFetch(uSplats, base + 1); // covariance xx xy xz yy
+ vec4 t2 = texelFetch(uSplats, base + 2); // covariance yz zz
+ vec4 t3 = texelFetch(uSplats, base + 3); // colour
+ vec4 cam = uView * vec4(t0.xyz, 1.0);
+ vec4 clip = uProj * cam;
+ float depth = -cam.z;
+ if (depth <= 0.0 || abs(clip.x) > 1.3 * clip.w || abs(clip.y) > 1.3 * clip.w) {
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
+ return;
+ }
+ mat3 sigma = mat3(t1.x, t1.y, t1.z, t1.y, t1.w, t2.x, t1.z, t2.x, t2.y);
+ vec2 focal = vec2(uProj[0][0], uProj[1][1]) * uViewport * 0.5;
+ mat3 J = mat3(focal.x / depth, 0.0, 0.0,
+ 0.0, focal.y / depth, 0.0,
+ focal.x * cam.x / (depth * depth), focal.y * cam.y / (depth * depth), 0.0);
+ mat3 T = J * mat3(uView);
+ mat3 cov = T * sigma * transpose(T);
+ float a = cov[0][0] + 0.3, b = cov[0][1], c = cov[1][1] + 0.3;
+ float mid = 0.5 * (a + c);
+ float rad = length(vec2(0.5 * (a - c), b));
+ float l1 = mid + rad, l2 = max(mid - rad, 0.1);
+ vec2 axis1 = abs(b) > 1e-6 ? normalize(vec2(b, l1 - a)) : (a >= c ? vec2(1.0, 0.0) : vec2(0.0, 1.0));
+ vec2 axis2 = vec2(-axis1.y, axis1.x);
+ vec2 corner = kCorners[gl_VertexID];
+ vec2 px = corner.x * 3.0 * min(sqrt(l1), 1024.0) * axis1 + corner.y * 3.0 * min(sqrt(l2), 1024.0) * axis2;
+ gl_Position = clip + vec4(px / uViewport * 2.0 * clip.w, 0.0, 0.0);
+ vOffset = corner * 3.0;
+ vColor = vec4(t3.rgb, t0.w * uOpacity);
+}
+)";
+
+const char* kSplatFS = R"(#version 330 core
+in vec4 vColor;
+in vec2 vOffset;
+out vec4 fragColor;
+void main() {
+ float alpha = min(vColor.a * exp(-0.5 * dot(vOffset, vOffset)), 0.99);
+ if (alpha < 1.0 / 255.0) discard;
+ fragColor = vec4(vColor.rgb, alpha);
+}
+)";
+
+GLuint compile(GLenum type, const char* src, std::string& error) {
+ GLuint s = gl::CreateShader(type);
+ gl::ShaderSource(s, 1, &src, nullptr);
+ gl::CompileShader(s);
+ GLint ok = 0;
+ gl::GetShaderiv(s, GL_COMPILE_STATUS, &ok);
+ if (!ok) {
+ char log[2048];
+ gl::GetShaderInfoLog(s, sizeof log, nullptr, log);
+ error = std::string("Shader compile error: ") + log;
+ gl::DeleteShader(s);
+ return 0;
+ }
+ return s;
+}
+
+GLuint link(const char* vs, const char* fs, std::string& error) {
+ GLuint v = compile(GL_VERTEX_SHADER, vs, error);
+ if (!v) return 0;
+ GLuint f = compile(GL_FRAGMENT_SHADER, fs, error);
+ if (!f) {
+ gl::DeleteShader(v);
+ return 0;
+ }
+ GLuint p = gl::CreateProgram();
+ gl::AttachShader(p, v);
+ gl::AttachShader(p, f);
+ gl::LinkProgram(p);
+ gl::DeleteShader(v);
+ gl::DeleteShader(f);
+ GLint ok = 0;
+ gl::GetProgramiv(p, GL_LINK_STATUS, &ok);
+ if (!ok) {
+ char log[2048];
+ gl::GetProgramInfoLog(p, sizeof log, nullptr, log);
+ error = std::string("Shader link error: ") + log;
+ gl::DeleteProgram(p);
+ return 0;
+ }
+ return p;
+}
+
+} // namespace
+
+bool Renderer::init(std::string& error) {
+ meshProgram_ = link(kMeshVS, kMeshFS, error);
+ if (!meshProgram_) return false;
+ wireProgram_ = link(kMeshVS, kWireFS, error);
+ if (!wireProgram_) return false;
+ bgProgram_ = link(kBgVS, kBgFS, error);
+ if (!bgProgram_) return false;
+ splatProgram_ = link(kSplatVS, kSplatFS, error);
+ if (!splatProgram_) return false;
+ gl::GenVertexArrays(1, &splatVao_);
+ gl::GenBuffers(1, &splatData_);
+ gl::GenBuffers(1, &splatOrder_);
+ gl::GenTextures(1, &splatTexture_);
+ gl::BindVertexArray(splatVao_);
+ gl::BindBuffer(GL_ARRAY_BUFFER, splatOrder_);
+ gl::EnableVertexAttribArray(0);
+ gl::VertexAttribIPointer(0, 1, GL_UNSIGNED_INT, sizeof(uint32_t), nullptr);
+ gl::VertexAttribDivisor(0, 1);
+ gl::BindVertexArray(0);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+
+ gl::GenVertexArrays(1, &vao_);
+ gl::GenVertexArrays(1, &emptyVao_);
+ gl::GenBuffers(1, &posBuffer_);
+ gl::GenBuffers(1, &nrmBuffer_);
+ gl::GenBuffers(1, &indexBuffer_);
+
+ gl::BindVertexArray(vao_);
+ gl::BindBuffer(GL_ARRAY_BUFFER, posBuffer_);
+ gl::EnableVertexAttribArray(0);
+ gl::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);
+ gl::BindBuffer(GL_ARRAY_BUFFER, nrmBuffer_);
+ gl::EnableVertexAttribArray(1);
+ gl::VertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), nullptr);
+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer_);
+ gl::BindVertexArray(0);
+ return true;
+}
+
+void Renderer::shutdown() {
+ gl::DeleteBuffers(1, &posBuffer_);
+ gl::DeleteBuffers(1, &nrmBuffer_);
+ gl::DeleteBuffers(1, &indexBuffer_);
+ gl::DeleteVertexArrays(1, &vao_);
+ gl::DeleteVertexArrays(1, &emptyVao_);
+ gl::DeleteProgram(meshProgram_);
+ gl::DeleteProgram(wireProgram_);
+ gl::DeleteProgram(bgProgram_);
+ gl::DeleteProgram(splatProgram_);
+ gl::DeleteBuffers(1, &splatData_);
+ gl::DeleteBuffers(1, &splatOrder_);
+ gl::DeleteTextures(1, &splatTexture_);
+ gl::DeleteVertexArrays(1, &splatVao_);
+}
+
+void Renderer::syncSplats(const SplatCloud& c, uint64_t version) {
+ if (version == splatVersion_) return;
+ splatVersion_ = version;
+ GLint maxTexels = 0;
+ gl::GetIntegerv(GL_MAX_TEXTURE_BUFFER_SIZE, &maxTexels);
+ const size_t n = std::min(c.size(), size_t(std::max(maxTexels, 0)) / 4);
+ std::vector<glm::vec4> texels(n * 4);
+ splatCenters_.resize(n);
+ const glm::mat3 M(c.transform);
+ for (size_t i = 0; i < n; ++i) {
+ const glm::vec3 p = c.worldPosition(i);
+ const glm::mat3 A = M * glm::mat3_cast(c.rotations[i]) *
+ glm::mat3(glm::vec3(c.scales[i].x, 0, 0), glm::vec3(0, c.scales[i].y, 0), glm::vec3(0, 0, c.scales[i].z));
+ const glm::mat3 S = A * glm::transpose(A);
+ splatCenters_[i] = p;
+ texels[i * 4 + 0] = glm::vec4(p, c.opacities[i]);
+ texels[i * 4 + 1] = glm::vec4(S[0][0], S[0][1], S[0][2], S[1][1]);
+ texels[i * 4 + 2] = glm::vec4(S[1][2], S[2][2], 0.0f, 0.0f);
+ texels[i * 4 + 3] = glm::vec4(glm::clamp(c.color(i), glm::vec3(0.0f), glm::vec3(1.0f)), 1.0f);
+ }
+ gl::BindBuffer(GL_TEXTURE_BUFFER, splatData_);
+ gl::BufferData(GL_TEXTURE_BUFFER, GLsizeiptr(texels.size() * sizeof(glm::vec4)), texels.data(), GL_STATIC_DRAW);
+ gl::BindTexture(GL_TEXTURE_BUFFER, splatTexture_);
+ gl::TexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, splatData_);
+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);
+ gl::BindBuffer(GL_TEXTURE_BUFFER, 0);
+ splatCount_ = GLsizei(n);
+ lastSortView_ = glm::mat4(0.0f); // force a re-sort
+}
+
+void Renderer::drawSplats(const glm::mat4& view, const glm::mat4& proj, int fbWidth, int fbHeight, float opacity) {
+ if (splatCount_ == 0) return;
+ // Back-to-front order, re-sorted only when the camera moves (16-bit counting sort).
+ if (view != lastSortView_) {
+ lastSortView_ = view;
+ const size_t n = size_t(splatCount_);
+ std::vector<float> depth(n);
+ float lo = std::numeric_limits<float>::max(), hi = std::numeric_limits<float>::lowest();
+ for (size_t i = 0; i < n; ++i) {
+ const glm::vec3& p = splatCenters_[i];
+ depth[i] = -(view[0][2] * p.x + view[1][2] * p.y + view[2][2] * p.z + view[3][2]);
+ lo = std::min(lo, depth[i]);
+ hi = std::max(hi, depth[i]);
+ }
+ const float scale = hi > lo ? 65535.0f / (hi - lo) : 0.0f;
+ std::vector<uint32_t> count(65537, 0);
+ std::vector<uint16_t> key(n);
+ for (size_t i = 0; i < n; ++i) {
+ key[i] = uint16_t(65535 - int((depth[i] - lo) * scale)); // far first
+ ++count[size_t(key[i]) + 1];
+ }
+ for (size_t k = 1; k < count.size(); ++k) count[k] += count[k - 1];
+ splatSorted_.resize(n);
+ for (size_t i = 0; i < n; ++i) splatSorted_[count[key[i]]++] = uint32_t(i);
+ gl::BindBuffer(GL_ARRAY_BUFFER, splatOrder_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(n * sizeof(uint32_t)), splatSorted_.data(), GL_STREAM_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ }
+ gl::UseProgram(splatProgram_);
+ gl::UniformMatrix4fv(gl::GetUniformLocation(splatProgram_, "uView"), 1, GL_FALSE, glm::value_ptr(view));
+ gl::UniformMatrix4fv(gl::GetUniformLocation(splatProgram_, "uProj"), 1, GL_FALSE, glm::value_ptr(proj));
+ gl::Uniform2f(gl::GetUniformLocation(splatProgram_, "uViewport"), float(fbWidth), float(fbHeight));
+ gl::Uniform1f(gl::GetUniformLocation(splatProgram_, "uOpacity"), opacity);
+ gl::Uniform1i(gl::GetUniformLocation(splatProgram_, "uSplats"), 0);
+ gl::ActiveTexture(GL_TEXTURE0);
+ gl::BindTexture(GL_TEXTURE_BUFFER, splatTexture_);
+ gl::Enable(GL_DEPTH_TEST);
+ gl::DepthMask(GL_FALSE);
+ gl::Enable(GL_BLEND);
+ gl::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ gl::BindVertexArray(splatVao_);
+ gl::DrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, splatCount_);
+ gl::BindVertexArray(0);
+ gl::Disable(GL_BLEND);
+ gl::DepthMask(GL_TRUE);
+ gl::BindTexture(GL_TEXTURE_BUFFER, 0);
+}
+
+void Renderer::sync(Mesh& mesh) {
+ const size_t nv = mesh.vertexCount();
+ if (mesh.topologyDirty || nv != vertexCapacity_) {
+ gl::BindVertexArray(vao_);
+ gl::BindBuffer(GL_ARRAY_BUFFER, posBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * sizeof(glm::vec3)), mesh.positions.data(), GL_DYNAMIC_DRAW);
+ gl::BindBuffer(GL_ARRAY_BUFFER, nrmBuffer_);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(nv * sizeof(glm::vec3)), mesh.normals.data(), GL_DYNAMIC_DRAW);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(mesh.triangleCount() * sizeof(glm::uvec3)),
+ mesh.triangles.data(), GL_STATIC_DRAW);
+ gl::BindVertexArray(0);
+ indexCount_ = GLsizei(mesh.triangleCount() * 3);
+ vertexCapacity_ = nv;
+ } else if (mesh.dirtyBegin < mesh.dirtyEnd) {
+ const GLintptr offset = GLintptr(mesh.dirtyBegin * sizeof(glm::vec3));
+ const GLsizeiptr size = GLsizeiptr((mesh.dirtyEnd - mesh.dirtyBegin) * sizeof(glm::vec3));
+ gl::BindBuffer(GL_ARRAY_BUFFER, posBuffer_);
+ gl::BufferSubData(GL_ARRAY_BUFFER, offset, size, mesh.positions.data() + mesh.dirtyBegin);
+ gl::BindBuffer(GL_ARRAY_BUFFER, nrmBuffer_);
+ gl::BufferSubData(GL_ARRAY_BUFFER, offset, size, mesh.normals.data() + mesh.dirtyBegin);
+ }
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ mesh.clearDirty();
+}
+
+bool Renderer::renderToImage(const Camera& camera, int width, int height, const RenderSettings& settings,
+ std::vector<uint8_t>& rgba, std::string& error) {
+ GLuint fbo[2] = {}, rb[3] = {};
+ gl::GenFramebuffers(2, fbo);
+ gl::GenRenderbuffers(3, rb);
+ // Multisampled colour + depth for drawing, plain colour for resolving.
+ gl::BindRenderbuffer(GL_RENDERBUFFER, rb[0]);
+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, width, height);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, rb[1]);
+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT24, width, height);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, rb[2]);
+ gl::RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo[0]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb[0]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb[1]);
+ bool ok = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo[1]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb[2]);
+ ok = ok && gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ if (ok) {
+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo[0]);
+ draw(camera, width, height, settings);
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]);
+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]);
+ gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, fbo[1]);
+ std::vector<uint8_t> pixels(size_t(width) * size_t(height) * 4);
+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
+ gl::ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
+ rgba.resize(pixels.size());
+ const size_t row = size_t(width) * 4;
+ for (int y = 0; y < height; ++y) // GL rows are bottom-up
+ std::copy_n(pixels.data() + size_t(height - 1 - y) * row, row, rgba.data() + size_t(y) * row);
+ } else {
+ error = "Offscreen framebuffer is not supported by this GPU/driver";
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+ gl::DeleteFramebuffers(2, fbo);
+ gl::DeleteRenderbuffers(3, rb);
+ return ok;
+}
+
+bool Renderer::beginCapture(int width, int height, std::string& error) {
+ if (width != captureW_ || height != captureH_) {
+ if (captureFbo_[0]) {
+ gl::DeleteFramebuffers(2, captureFbo_);
+ gl::DeleteRenderbuffers(3, captureRb_);
+ }
+ gl::GenFramebuffers(2, captureFbo_);
+ gl::GenRenderbuffers(3, captureRb_);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, captureRb_[0]);
+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, width, height);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, captureRb_[1]);
+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT24, width, height);
+ gl::BindRenderbuffer(GL_RENDERBUFFER, captureRb_[2]);
+ gl::RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, captureFbo_[0]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, captureRb_[0]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, captureRb_[1]);
+ bool ok = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ gl::BindFramebuffer(GL_FRAMEBUFFER, captureFbo_[1]);
+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, captureRb_[2]);
+ ok = ok && gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ if (!ok) {
+ error = "Offscreen framebuffer is not supported by this GPU/driver";
+ return false;
+ }
+ captureW_ = width;
+ captureH_ = height;
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, captureFbo_[0]);
+ return true;
+}
+
+void Renderer::endCapture(std::vector<uint8_t>& rgba) {
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, captureFbo_[0]);
+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, captureFbo_[1]);
+ gl::BlitFramebuffer(0, 0, captureW_, captureH_, 0, 0, captureW_, captureH_, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, captureFbo_[1]);
+ rgba.resize(size_t(captureW_) * size_t(captureH_) * 4);
+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
+ gl::ReadPixels(0, 0, captureW_, captureH_, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data());
+ // Flip to top-down rows for video encoders.
+ const size_t row = size_t(captureW_) * 4;
+ std::vector<uint8_t> tmp(row);
+ for (int y = 0; y < captureH_ / 2; ++y) {
+ uint8_t* a = rgba.data() + size_t(y) * row;
+ uint8_t* b = rgba.data() + size_t(captureH_ - 1 - y) * row;
+ std::copy_n(a, row, tmp.data());
+ std::copy_n(b, row, a);
+ std::copy_n(tmp.data(), row, b);
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+}
+
+void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const RenderSettings& settings) {
+ gl::Viewport(0, 0, fbWidth, fbHeight);
+ gl::ClearColor(0.1f, 0.1f, 0.11f, 1.0f);
+ gl::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ gl::Enable(GL_MULTISAMPLE);
+
+ // Background gradient.
+ gl::Disable(GL_DEPTH_TEST);
+ gl::UseProgram(bgProgram_);
+ gl::BindVertexArray(emptyVao_);
+ gl::DrawArrays(GL_TRIANGLES, 0, 3);
+
+ glm::mat4 view = camera.view(), proj = camera.projection();
+ gl::Enable(GL_DEPTH_TEST);
+ gl::DepthFunc(GL_LEQUAL);
+ if (indexCount_ == 0 || !settings.showMesh) {
+ if (settings.showSplats) drawSplats(view, proj, fbWidth, fbHeight, settings.splatOpacity);
+ gl::UseProgram(0);
+ return;
+ }
+ gl::BindVertexArray(vao_);
+
+ auto setMatrices = [&](GLuint prog) {
+ gl::UseProgram(prog);
+ gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uView"), 1, GL_FALSE, glm::value_ptr(view));
+ gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uProj"), 1, GL_FALSE, glm::value_ptr(proj));
+ };
+
+ setMatrices(meshProgram_);
+ gl::Uniform3fv(gl::GetUniformLocation(meshProgram_, "uColor"), 1, glm::value_ptr(settings.baseColor));
+ gl::Enable(GL_POLYGON_OFFSET_FILL);
+ gl::PolygonOffset(1.0f, 1.0f);
+ gl::DrawElements(GL_TRIANGLES, indexCount_, GL_UNSIGNED_INT, nullptr);
+ gl::Disable(GL_POLYGON_OFFSET_FILL);
+
+ if (settings.wireframe) {
+ setMatrices(wireProgram_);
+ gl::Enable(GL_BLEND);
+ gl::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ gl::DepthMask(GL_FALSE);
+ gl::PolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ gl::DrawElements(GL_TRIANGLES, indexCount_, GL_UNSIGNED_INT, nullptr);
+ gl::PolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ gl::DepthMask(GL_TRUE);
+ gl::Disable(GL_BLEND);
+ }
+ gl::BindVertexArray(0);
+ if (settings.showSplats) drawSplats(view, proj, fbWidth, fbHeight, settings.splatOpacity);
+ gl::UseProgram(0);
+}
+
+} // namespace sf
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
new file mode 100644
index 00000000..62684c68
--- /dev/null
+++ b/src/render/Renderer.h
@@ -0,0 +1,60 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "core/Mesh.h"
+#include "core/Splats.h"
+#include "render/Camera.h"
+#include "render/GL.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct RenderSettings {
+ bool wireframe = false;
+ glm::vec3 baseColor{0.80f, 0.55f, 0.45f}; // clay
+ bool showMesh = true;
+ bool showSplats = true;
+ float splatOpacity = 1.0f; // global fade for using a capture as reference
+};
+
+class Renderer {
+public:
+ bool init(std::string& error);
+ void shutdown();
+ // Uploads whatever the mesh marked dirty, then clears its dirty state.
+ void sync(Mesh& mesh);
+ // Re-uploads the splats when `version` differs from the last upload.
+ void syncSplats(const SplatCloud& splats, uint64_t version);
+ void draw(const Camera& camera, int fbWidth, int fbHeight, const RenderSettings& settings);
+ // Offscreen render (4x MSAA) into top-down RGBA8 pixels.
+ bool renderToImage(const Camera& camera, int width, int height, const RenderSettings& settings,
+ std::vector<uint8_t>& rgba, std::string& error);
+
+ // Persistent offscreen target (4x MSAA) for recording: draw between these calls.
+ bool beginCapture(int width, int height, std::string& error);
+ void endCapture(std::vector<uint8_t>& rgba); // top-down RGBA rows
+
+private:
+ void drawSplats(const glm::mat4& view, const glm::mat4& proj, int fbWidth, int fbHeight, float opacity);
+
+ GLuint meshProgram_ = 0, wireProgram_ = 0, bgProgram_ = 0, splatProgram_ = 0;
+ // Splats: per-splat data in a texture buffer, drawn as instanced quads in back-to-front order.
+ GLuint splatVao_ = 0, splatData_ = 0, splatTexture_ = 0, splatOrder_ = 0;
+ GLsizei splatCount_ = 0;
+ uint64_t splatVersion_ = ~uint64_t(0);
+ std::vector<glm::vec3> splatCenters_;
+ std::vector<uint32_t> splatSorted_;
+ glm::mat4 lastSortView_{0.0f};
+ GLuint captureFbo_[2] = {}, captureRb_[3] = {};
+ int captureW_ = 0, captureH_ = 0;
+ GLuint vao_ = 0, emptyVao_ = 0;
+ GLuint posBuffer_ = 0, nrmBuffer_ = 0, indexBuffer_ = 0;
+ GLsizei indexCount_ = 0;
+ size_t vertexCapacity_ = 0;
+};
+
+} // namespace sf
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
new file mode 100644
index 00000000..b3b102f1
--- /dev/null
+++ b/tests/test_main.cpp
@@ -0,0 +1,1306 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Dependency-free unit tests for the core library.
+#include "ai/BrushAssistant.h"
+#include "ai/GradioClient.h"
+#include "ai/ImageTo3DService.h"
+#include "cli/McpServer.h"
+#include "core/BrushRecipe.h"
+#include "core/Commands.h"
+#include "core/Json.h"
+#include "core/Decimate.h"
+#include "core/ImageTo3D.h"
+#include "core/Script.h"
+#include "io/GltfIO.h"
+#include "core/Primitives.h"
+#include "core/Sculpt.h"
+#include "io/ObjIO.h"
+#include "io/FbxIO.h"
+#include "io/PlyIO.h"
+#include "core/EnginePresets.h"
+#include "link/UnrealLink.h"
+#include "io/UsdIO.h"
+#include "io/Zip.h"
+#include "core/Splats.h"
+#include "core/Voxel.h"
+
+#include <cmath>
+#include <algorithm>
+#include <cstring>
+#include <glm/gtc/matrix_transform.hpp>
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+#include <functional>
+#include <map>
+#include <string>
+#include <vector>
+
+using namespace sf;
+
+namespace {
+
+int g_failures = 0;
+int g_checks = 0;
+
+#define CHECK(cond) \
+ do { \
+ ++g_checks; \
+ if (!(cond)) { \
+ ++g_failures; \
+ std::printf(" FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
+ } \
+ } while (0)
+
+struct TestCase {
+ const char* name;
+ std::function<void()> fn;
+};
+std::vector<TestCase>& registry() {
+ static std::vector<TestCase> r;
+ return r;
+}
+struct Register {
+ Register(const char* n, std::function<void()> f) { registry().push_back({n, std::move(f)}); }
+};
+#define TEST(name) \
+ static void name(); \
+ static Register reg_##name(#name, name); \
+ static void name()
+
+Document makeDoc(Mesh m) {
+ Document d;
+ d.setMesh(std::move(m));
+ return d;
+}
+
+std::string tempPath(const char* name) { return (std::filesystem::temp_directory_path() / name).string(); }
+
+} // namespace
+
+TEST(icosphere_counts) {
+ Mesh m = makeIcosphere(3);
+ CHECK(m.triangleCount() == 20u * 64u);
+ // Closed genus-0 surface: V - E + F = 2 with E = 3F/2.
+ CHECK(long(m.vertexCount()) - long(m.triangleCount() * 3 / 2) + long(m.triangleCount()) == 2);
+ for (const auto& p : m.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-5f);
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::dot(m.normals[v], m.positions[v]) > 0.99f);
+}
+
+TEST(bvh_raycast_and_query) {
+ Mesh m = makeIcosphere(4);
+ BVH bvh;
+ bvh.build(m);
+ RayHit hit;
+ CHECK(bvh.raycast(m, glm::vec3(0, 0, 5), glm::vec3(0, 0, -1), hit));
+ CHECK(std::abs(hit.position.z - 1.0f) < 0.01f);
+ CHECK(!bvh.raycast(m, glm::vec3(0, 3, 5), glm::vec3(0, 0, -1), hit));
+
+ std::vector<uint32_t> found;
+ glm::vec3 c(0, 0, 1);
+ bvh.queryVertices(m, c, 0.3f, found);
+ size_t brute = 0;
+ for (const auto& p : m.positions) brute += glm::distance(p, c) <= 0.3f;
+ CHECK(found.size() == brute);
+ CHECK(brute > 0);
+}
+
+TEST(standard_brush_raises_surface_with_symmetry) {
+ Document d = makeDoc(makeIcosphere(4));
+ DabParams p;
+ p.center = glm::normalize(glm::vec3(0.5f, 0.2f, 0.8f));
+ p.viewDir = -p.center;
+ p.radius = 0.3f;
+ p.strength = 1.0f;
+ d.sculptor.beginStroke(d.mesh, "Standard");
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{true, false, false});
+ UndoRecord r = d.sculptor.endStroke();
+ CHECK(!r.empty());
+
+ float maxR = 0, maxMirroredR = 0;
+ for (const auto& v : d.mesh.positions) {
+ if (v.x > 0.2f) maxR = std::max(maxR, glm::length(v));
+ if (v.x < -0.2f) maxMirroredR = std::max(maxMirroredR, glm::length(v));
+ }
+ CHECK(maxR > 1.01f);
+ CHECK(std::abs(maxR - maxMirroredR) < 1e-4f);
+
+ // BVH must still find the raised surface.
+ RayHit hit;
+ CHECK(d.bvh.raycast(d.mesh, p.center * 5.0f, -p.center, hit));
+ CHECK(glm::length(hit.position) > 1.005f);
+}
+
+TEST(undo_redo_restores_positions) {
+ Document d = makeDoc(makeIcosphere(3));
+ const std::vector<glm::vec3> original = d.mesh.positions;
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.viewDir = glm::vec3(0, 0, -1);
+ p.radius = 0.5f;
+ for (BrushType t : {BrushType::Standard, BrushType::Clay, BrushType::Inflate, BrushType::Crease}) {
+ d.sculptor.beginStroke(d.mesh, brushName(t));
+ d.sculptor.dab(d.mesh, d.bvh, t, p, Symmetry{});
+ d.undo.push(d.sculptor.endStroke());
+ }
+ const std::vector<glm::vec3> sculpted = d.mesh.positions;
+ CHECK(sculpted != original);
+ while (d.undo.canUndo()) d.undo.undo(d.mesh, d.bvh);
+ CHECK(d.mesh.positions == original);
+ while (d.undo.canRedo()) d.undo.redo(d.mesh, d.bvh);
+ CHECK(d.mesh.positions == sculpted);
+}
+
+TEST(smooth_reduces_noise) {
+ Document d = makeDoc(makeIcosphere(4));
+ for (size_t i = 0; i < d.mesh.vertexCount(); ++i)
+ d.mesh.positions[i] *= 1.0f + 0.05f * float((i * 2654435761u) % 7) / 7.0f;
+ d.mesh.recomputeAllNormals();
+ d.bvh.build(d.mesh);
+ // Roughness: mean distance of each vertex from its neighbours' average.
+ auto spread = [&] {
+ float sum = 0;
+ int n = 0;
+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) {
+ if (d.mesh.positions[v].z < 0.95f) continue;
+ glm::vec3 avg(0.0f);
+ for (uint32_t u : d.mesh.neighbors(v)) avg += d.mesh.positions[u];
+ avg /= float(d.mesh.neighbors(v).size());
+ sum += glm::distance(avg, d.mesh.positions[v]);
+ ++n;
+ }
+ return sum / float(n);
+ };
+ float before = spread();
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.radius = 0.6f;
+ p.strength = 1.0f;
+ d.sculptor.beginStroke(d.mesh, "Smooth");
+ for (int i = 0; i < 5; ++i) d.sculptor.dab(d.mesh, d.bvh, BrushType::Smooth, p, Symmetry{false, false, false});
+ d.sculptor.endStroke();
+ CHECK(spread() < before * 0.5f);
+}
+
+TEST(move_brush_drags_region) {
+ Document d = makeDoc(makeIcosphere(4));
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.radius = 0.4f;
+ p.strength = 1.0f;
+ d.sculptor.beginStroke(d.mesh, "Move");
+ d.sculptor.beginGrab(d.mesh, d.bvh, p, Symmetry{false, false, false});
+ d.sculptor.grab(d.mesh, d.bvh, glm::vec3(0, 0, 0.5f));
+ d.sculptor.endStroke();
+ float maxZ = 0;
+ for (const auto& v : d.mesh.positions) maxZ = std::max(maxZ, v.z);
+ CHECK(std::abs(maxZ - 1.5f) < 0.01f);
+}
+
+TEST(loop_subdivision) {
+ Mesh m = makeIcosphere(2);
+ Mesh s = loopSubdivide(m);
+ CHECK(s.triangleCount() == m.triangleCount() * 4);
+ CHECK(s.vertexCount() == m.vertexCount() + m.triangleCount() * 3 / 2);
+ for (const auto& p : s.positions) CHECK(glm::length(p) > 0.9f && glm::length(p) < 1.01f);
+
+ Mesh plane = makePlane(4);
+ Mesh sp = loopSubdivide(plane);
+ CHECK(sp.triangleCount() == plane.triangleCount() * 4);
+ for (const auto& p : sp.positions) CHECK(std::abs(p.y) < 1e-6f); // stays flat
+ // Corners are kept in place.
+ AABB b = sp.bounds();
+ CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.z - 1.0f) < 1e-5f);
+}
+
+TEST(obj_roundtrip) {
+ const std::string in = tempPath("sculptforge_test_in.obj");
+ {
+ std::ofstream f(in);
+ f << "# quad + negative indices\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\n"
+ "f 1/1 2/1 3/1 4/1\nv 2 0 0\nf -4 -1 -3\n";
+ }
+ Mesh m;
+ std::string err;
+ CHECK(loadObj(in, m, err));
+ CHECK(m.vertexCount() == 5);
+ CHECK(m.triangleCount() == 3);
+
+ const std::string out = tempPath("sculptforge_test_out.obj");
+ CHECK(saveObj(out, m, err));
+ Mesh back;
+ CHECK(loadObj(out, back, err));
+ CHECK(back.positions == m.positions);
+ CHECK(back.triangles == m.triangles);
+
+ CHECK(!loadObj(tempPath("does_not_exist_sculptforge.obj"), back, err));
+ {
+ std::ofstream f(in);
+ f << "v 0 0 0\nf 1 2 3\n";
+ }
+ CHECK(!loadObj(in, back, err));
+ std::filesystem::remove(in);
+ std::filesystem::remove(out);
+}
+
+TEST(commands_and_tool_schema) {
+ CommandRegistry reg;
+ Document d;
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);
+ CHECK(d.mesh.triangleCount() == 320);
+ CHECK(reg.execute(d, "subdivide").ok);
+ CHECK(d.mesh.triangleCount() == 1280);
+ CHECK(reg.execute(d, "undo").ok);
+ CHECK(d.mesh.triangleCount() == 320);
+ CHECK(reg.execute(d, "redo").ok);
+ CHECK(d.mesh.triangleCount() == 1280);
+ CHECK(!reg.execute(d, "open_obj").ok); // missing required path
+ CHECK(!reg.execute(d, "no_such_command").ok);
+
+ std::string schema = reg.toolSchemaJson();
+ CHECK(schema.front() == '[' && schema.back() == ']');
+ CHECK(schema.find("\"name\":\"subdivide\"") != std::string::npos);
+ CHECK(schema.find("\"required\":[\"path\"]") != std::string::npos);
+}
+
+TEST(sculpt_layers_blend_and_undo) {
+ Document d = makeDoc(makeIcosphere(3));
+ const std::vector<glm::vec3> original = d.mesh.positions;
+ int smile = d.mesh.addLayer("Smile");
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.viewDir = glm::vec3(0, 0, -1);
+ p.radius = 0.5f;
+ p.strength = 1.0f;
+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard", smile));
+ d.sculptor.dab(d.mesh, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});
+ d.undo.push(d.sculptor.endStroke());
+ const std::vector<glm::vec3> sculpted = d.mesh.positions;
+ CHECK(sculpted != original);
+ CHECK(d.mesh.base == original); // stroke went into the layer, not the base
+
+ d.mesh.setLayerWeight(smile, 0.0f);
+ for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);
+ d.mesh.setLayerWeight(smile, 0.5f);
+ for (size_t i = 0; i < original.size(); ++i)
+ CHECK(glm::distance(d.mesh.positions[i], (original[i] + sculpted[i]) * 0.5f) < 1e-5f);
+
+ // Undo after changing the weight removes exactly the stroke's offsets.
+ d.undo.undo(d.mesh, d.bvh);
+ for (size_t i = 0; i < original.size(); ++i) CHECK(glm::distance(d.mesh.positions[i], original[i]) < 1e-6f);
+
+ // A layer at weight 0 refuses strokes.
+ d.mesh.setLayerWeight(smile, 0.0f);
+ CHECK(!d.sculptor.beginStroke(d.mesh, "Standard", smile));
+}
+
+TEST(layers_survive_subdivision) {
+ Mesh m = makeIcosphere(2);
+ int l = m.addLayer("Bulge");
+ for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = m.positions[v] * 0.1f;
+ m.setLayerWeight(l, 0.7f);
+ Mesh s = loopSubdivide(m);
+ CHECK(s.layers.size() == 1 && s.layers[0].weight == 0.7f);
+ for (size_t v = 0; v < s.vertexCount(); ++v)
+ CHECK(glm::distance(s.positions[v], s.base[v] + 0.7f * s.layers[0].delta[v]) < 1e-5f);
+}
+
+TEST(decimation_and_lods) {
+ Mesh m = makeIcosphere(5); // 20480 tris
+ Mesh d = decimate(m, 2000);
+ CHECK(d.triangleCount() <= 2000 && d.triangleCount() > 1800);
+ // Still closed and manifold: V - E + F = 2.
+ CHECK(long(d.vertexCount()) - long(d.triangleCount() * 3 / 2) + long(d.triangleCount()) == 2);
+ for (const auto& p : d.positions) CHECK(std::abs(glm::length(p) - 1.0f) < 1e-4f); // subset of sphere verts
+ float minR = 1e9f;
+ for (const auto& t : d.triangles)
+ minR = std::min(minR, glm::length((d.positions[t.x] + d.positions[t.y] + d.positions[t.z]) / 3.0f));
+ CHECK(minR > 0.95f); // shape preserved
+
+ m.addLayer("Blink");
+ auto lods = generateLods(m, 4, 0.5f);
+ CHECK(lods.size() == 4);
+ CHECK(lods[3].triangleCount() <= lods[0].triangleCount() / 8 + 8);
+ for (const auto& lod : lods) CHECK(lod.layers.size() == 1 && lod.layers[0].delta.size() == lod.vertexCount());
+
+ Mesh plane = makePlane(32);
+ Mesh dp = decimate(plane, 200);
+ AABB b = dp.bounds();
+ CHECK(std::abs(b.min.x + 1.0f) < 1e-5f && std::abs(b.max.x - 1.0f) < 1e-5f); // boundary kept
+}
+
+TEST(glb_export) {
+ Mesh m = makeIcosphere(1);
+ int l = m.addLayer("Smile");
+ m.layers[l].delta[0] = glm::vec3(0, 0.1f, 0);
+ const std::string path = tempPath("sculptforge_test.glb");
+ std::string err;
+ CHECK(saveGlb(path, m, "Head", err));
+ std::ifstream f(path, std::ios::binary);
+ std::string data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ CHECK(data.size() > 20 && data.substr(0, 4) == "glTF");
+ uint32_t total = 0, jsonLen = 0;
+ std::memcpy(&total, data.data() + 8, 4);
+ std::memcpy(&jsonLen, data.data() + 12, 4);
+ CHECK(total == data.size());
+ CHECK(jsonLen % 4 == 0);
+ std::string json = data.substr(20, jsonLen);
+ CHECK(json.find("\"targets\"") != std::string::npos);
+ CHECK(json.find("\"targetNames\":[\"Smile\"]") != std::string::npos);
+ f.close();
+ std::filesystem::remove(path);
+}
+
+TEST(script_parser_and_pipeline) {
+ std::vector<ScriptStatement> st;
+ std::string err;
+ CHECK(parseScript("new_sphere subdivisions=2; layer_add name=\"Big Smile\"\n# comment\ndecimate ratio=0.5", st, err));
+ CHECK(st.size() == 3);
+ CHECK(st[0].command == "new_sphere" && std::get<double>(st[0].args["subdivisions"]) == 2.0);
+ CHECK(std::get<std::string>(st[1].args["name"]) == "Big Smile");
+ CHECK(!parseScript("subdivide oops", st, err));
+
+ CommandRegistry reg;
+ Document d;
+ CHECK(parseScript("new_sphere subdivisions=4; layer_add name=Smile; decimate ratio=0.25", st, err));
+ for (const auto& s : st) CHECK(reg.execute(d, s.command, s.args).ok);
+ CHECK(d.mesh.layers.size() == 1);
+ CHECK(d.mesh.triangleCount() <= 1280);
+ const std::string base = tempPath("sculptforge_lod.glb");
+ CHECK(reg.execute(d, "export_lods", {{"path", base}, {"levels", 3.0}}).ok);
+ for (int i = 0; i < 3; ++i) {
+ auto p = std::filesystem::temp_directory_path() / ("sculptforge_lod_LOD" + std::to_string(i) + ".glb");
+ CHECK(std::filesystem::exists(p));
+ std::filesystem::remove(p);
+ }
+}
+
+TEST(json_roundtrip) {
+ Json j;
+ std::string err;
+ CHECK(Json::parse(R"({"a":[1,2.5,-3e2],"b":{"c":"x\"yé\n"},"d":true,"e":null})", j, err));
+ CHECK(j["a"].size() == 3 && j["a"][1].asNumber() == 2.5 && j["a"][2].asNumber() == -300.0);
+ CHECK(j["b"]["c"].asString() == "x\"y\xc3\xa9\n");
+ CHECK(j["d"].asBool() && j["e"].isNull() && j["missing"].isNull());
+ Json back;
+ CHECK(Json::parse(j.dump(), back, err));
+ CHECK(back.dump() == j.dump());
+ CHECK(!Json::parse("{\"a\":}", back, err));
+ CHECK(!Json::parse("[1,2", back, err));
+ CHECK(!Json::parse("{} trailing", back, err));
+}
+
+TEST(brush_recipe_roundtrip_and_clamp) {
+ auto presets = builtinBrushRecipes();
+ CHECK(presets.size() >= 6);
+ for (const auto& r : presets) {
+ BrushRecipe back = BrushRecipe::fromJson(r.toJson());
+ CHECK(back.toJson().dump() == r.toJson().dump());
+ }
+ Json wild;
+ std::string err;
+ CHECK(Json::parse(R"({"name":"Wild","depth":7,"pattern":"scales","plane":"bogus","spacing":-1})", wild, err));
+ BrushRecipe r = BrushRecipe::fromJson(wild);
+ CHECK(r.depth == 1.0f && r.spacing == 0.02f);
+ CHECK(r.pattern == BrushRecipe::Pattern::Scales && r.plane == BrushRecipe::Plane::None);
+
+ const std::string path = tempPath("sculptforge_test.sfbrush");
+ CHECK(presets[2].save(path, err));
+ BrushRecipe loaded;
+ CHECK(BrushRecipe::load(path, loaded, err));
+ CHECK(loaded.name == presets[2].name && loaded.pattern == presets[2].pattern);
+ std::filesystem::remove(path);
+
+ // Schema lists every parameter as required (structured-output compatible).
+ Json schema = recipeJsonSchema();
+ CHECK(schema["required"].size() == recipeParams().size() + 2);
+ CHECK(schema["additionalProperties"].isBool() && !schema["additionalProperties"].asBool());
+}
+
+TEST(recipe_brushes_sculpt) {
+ for (const auto& recipe : builtinBrushRecipes()) {
+ Document d = makeDoc(makeIcosphere(5));
+ const auto before = d.mesh.positions;
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.viewDir = glm::vec3(0, 0, -1);
+ p.radius = 0.4f;
+ p.strength = 1.0f;
+ p.strokeDelta = glm::vec3(0.05f, 0, 0);
+ CHECK(d.sculptor.beginStroke(d.mesh, recipe.name));
+ for (int i = 0; i < 3; ++i) d.sculptor.dabRecipe(d.mesh, d.bvh, recipe, p, Symmetry{false, false, false});
+ UndoRecord rec = d.sculptor.endStroke();
+ CHECK(!rec.empty());
+ bool finite = true;
+ float moved = 0;
+ for (size_t i = 0; i < before.size(); ++i) {
+ finite = finite && std::isfinite(d.mesh.positions[i].x) && std::isfinite(d.mesh.positions[i].y);
+ moved = std::max(moved, glm::distance(before[i], d.mesh.positions[i]));
+ }
+ CHECK(finite);
+ if (moved <= 1e-5f) std::printf(" recipe '%s' did not move the surface\n", recipe.name.c_str());
+ CHECK(moved > 1e-5f);
+ }
+ // Carving vs building: depth sign controls direction.
+ BrushRecipe carve;
+ carve.depth = -1.0f;
+ Document d = makeDoc(makeIcosphere(4));
+ DabParams p;
+ p.center = glm::vec3(0, 0, 1);
+ p.viewDir = glm::vec3(0, 0, -1);
+ p.radius = 0.4f;
+ p.strength = 1.0f;
+ d.sculptor.beginStroke(d.mesh, "Carve");
+ d.sculptor.dabRecipe(d.mesh, d.bvh, carve, p, Symmetry{false, false, false});
+ d.sculptor.endStroke();
+ float minR = 2.0f;
+ for (const auto& v : d.mesh.positions) minR = std::min(minR, glm::length(v));
+ CHECK(minR < 0.99f);
+}
+
+TEST(brush_commands) {
+ CommandRegistry reg;
+ Document d;
+ CHECK(reg.execute(d, "brush_create", {{"name", std::string("Lizard Skin")}, {"pattern", std::string("scales")},
+ {"patternAmount", 0.8}, {"depth", 0.3}}).ok);
+ CHECK(d.activeBrush >= 0 && d.brushes[d.activeBrush].name == "Lizard Skin");
+ CHECK(d.brushes[d.activeBrush].pattern == BrushRecipe::Pattern::Scales);
+ const std::string path = tempPath("sculptforge_lizard.sfbrush");
+ CHECK(reg.execute(d, "brush_save", {{"path", path}}).ok);
+ Document d2;
+ CHECK(reg.execute(d2, "brush_load", {{"path", path}}).ok);
+ CHECK(d2.brushes[d2.activeBrush].patternAmount == 0.8f);
+ std::filesystem::remove(path);
+ CHECK(reg.toolSchemaJson().find("\"tipSharpness\"") != std::string::npos);
+}
+
+TEST(ai_request_and_response_parsing) {
+ using namespace sf::ai;
+ AiSettings anth = AiSettings::defaults(AiSettings::Provider::Anthropic);
+ anth.apiKey = "test-key";
+ BrushRecipe current = builtinBrushRecipes()[0];
+ std::vector<ChatMessage> history = {composeUserMessage("make it sharper", &current)};
+ std::string body = buildRequestBody(anth, history);
+ Json req;
+ std::string err;
+ CHECK(Json::parse(body, req, err));
+ CHECK(req["model"].asString() == "claude-opus-5-5");
+ CHECK(req["output_config"]["format"]["type"].asString() == "json_schema");
+ CHECK(req["output_config"]["effort"].asString() == "low");
+ CHECK(req["fallbacks"].asString() == "default");
+ CHECK(req["messages"][0]["content"].asString().find("Wrinkle") != std::string::npos);
+ auto headers = requestHeaders(anth);
+ CHECK(std::find(headers.begin(), headers.end(), "x-api-key: test-key") != headers.end());
+ CHECK(std::find(headers.begin(), headers.end(), "anthropic-version: 2023-06-01") != headers.end());
+
+ // Anthropic response with an (empty) thinking block followed by the JSON text.
+ Json resp = Json::object();
+ resp.set("stop_reason", "end_turn");
+ Json content = Json::array();
+ Json thinking = Json::object();
+ thinking.set("type", "thinking");
+ thinking.set("thinking", "");
+ content.push(thinking);
+ Json text = Json::object();
+ text.set("type", "text");
+ text.set("text", R"({"reply":"Sharper now.","brush":{"name":"Wrinkle","depth":-0.7,"tipSharpness":0.9}})");
+ content.push(text);
+ resp.set("content", content);
+ std::string raw;
+ BrushSuggestion s = parseResponse(anth, 200, resp.dump(), &raw);
+ CHECK(s.ok && s.reply == "Sharper now." && s.recipe.tipSharpness == 0.9f && s.recipe.depth == -0.7f);
+ CHECK(raw.find("Sharper") != std::string::npos);
+
+ resp.set("stop_reason", "refusal");
+ CHECK(!parseResponse(anth, 200, resp.dump()).ok);
+ CHECK(parseResponse(anth, 401, R"({"type":"error","error":{"message":"invalid x-api-key"}})").error.find("rejected") !=
+ std::string::npos);
+
+ // OpenAI-compatible (e.g. Ollama) reply wrapped in a code fence.
+ AiSettings local = AiSettings::defaults(AiSettings::Provider::OpenAICompatible);
+ Json req2;
+ CHECK(Json::parse(buildRequestBody(local, history), req2, err));
+ CHECK(req2["messages"][0]["role"].asString() == "system");
+ std::string fenced = "Here you go:\n```json\n{\"reply\":\"Gritty!\",\"brush\":{\"name\":\"Grit\",\"pattern\":\"noise\","
+ "\"patternAmount\":0.9}}\n```";
+ Json oresp = Json::object();
+ Json choices = Json::array();
+ Json choice = Json::object();
+ Json msg = Json::object();
+ msg.set("content", fenced);
+ choice.set("message", msg);
+ choices.push(choice);
+ oresp.set("choices", choices);
+ BrushSuggestion s2 = parseResponse(local, 200, oresp.dump());
+ CHECK(s2.ok && s2.recipe.name == "Grit" && s2.recipe.pattern == BrushRecipe::Pattern::Noise);
+}
+
+namespace {
+
+Image makeImage(int w, int h, const std::function<glm::vec4(float, float)>& f) {
+ Image img;
+ img.width = w;
+ img.height = h;
+ img.rgba.resize(size_t(w) * size_t(h) * 4);
+ for (int y = 0; y < h; ++y)
+ for (int x = 0; x < w; ++x) {
+ glm::vec4 c = glm::clamp(f((x + 0.5f) / w, (y + 0.5f) / h), 0.0f, 1.0f) * 255.0f;
+ for (int k = 0; k < 4; ++k) img.rgba[(size_t(y) * w + x) * 4 + k] = uint8_t(c[k] + 0.5f);
+ }
+ return img;
+}
+
+// Minimal 32-bit BMP writer so command tests can load real files.
+void writeBmp(const std::string& path, const Image& img) {
+ std::ofstream f(path, std::ios::binary);
+ auto u32 = [&](uint32_t v) { f.write(reinterpret_cast<const char*>(&v), 4); };
+ auto u16 = [&](uint16_t v) { f.write(reinterpret_cast<const char*>(&v), 2); };
+ const uint32_t dataSize = uint32_t(img.width * img.height * 4);
+ f.write("BM", 2);
+ u32(54 + dataSize); u32(0); u32(54);
+ u32(40); u32(uint32_t(img.width)); u32(uint32_t(-img.height)); u16(1); u16(32); u32(0); u32(dataSize);
+ u32(2835); u32(2835); u32(0); u32(0);
+ for (size_t i = 0; i < img.rgba.size(); i += 4) {
+ const char px[4] = {char(img.rgba[i + 2]), char(img.rgba[i + 1]), char(img.rgba[i]), char(255)};
+ f.write(px, 4);
+ }
+}
+
+} // namespace
+
+TEST(image_relief) {
+ Image ramp = makeImage(64, 32, [](float u, float) { return glm::vec4(u, u, u, 1.0f); });
+ ReliefOptions o;
+ o.resolution = 64;
+ Mesh m = makeImageRelief(ramp, o);
+ AABB b = m.bounds();
+ CHECK(std::abs(b.extent().x - 2.0f) < 1e-4f && std::abs(b.extent().y - 1.0f) < 1e-4f); // keeps aspect
+ float leftZ = 0, rightZ = 0;
+ for (const auto& p : m.positions) {
+ if (p.x < -0.95f) leftZ = std::max(leftZ, p.z);
+ if (p.x > 0.95f) rightZ = std::max(rightZ, p.z);
+ }
+ CHECK(rightZ > leftZ + 0.1f); // light side is higher
+}
+
+TEST(image_inflate_silhouette) {
+ // A disk on a transparent background inflates into a closed, symmetric, ball-like shape.
+ Image disk = makeImage(96, 96, [](float u, float v) {
+ float d = glm::length(glm::vec2(u, v) - 0.5f);
+ return glm::vec4(0.2f, 0.2f, 0.2f, d < 0.4f ? 1.0f : 0.0f);
+ });
+ InflateOptions o;
+ o.resolution = 64;
+ o.subdivisions = 0;
+ std::string err;
+ Mesh m = inflateSilhouette(disk, o, &err);
+ CHECK(m.triangleCount() > 100);
+ {
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const auto& t : m.triangles)
+ for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];
+ bool manifold = true;
+ for (const auto& [e, n] : edges) manifold = manifold && n == 2;
+ CHECK(manifold); // closed, no pinches
+ CHECK(long(m.vertexCount()) - long(edges.size()) + long(m.triangleCount()) == 2); // sphere topology
+ }
+ AABB b = m.bounds();
+ CHECK(b.extent().z > b.extent().x * 0.6f); // round, not flat
+ CHECK(std::abs(b.max.z + b.min.z) < 0.02f * b.extent().z); // front/back symmetric
+
+ // Dark shape on a white page (no transparency) also works.
+ Image sketch = makeImage(80, 60, [](float u, float v) {
+ bool in = std::abs(u - 0.5f) < 0.3f && std::abs(v - 0.5f) < 0.2f;
+ return in ? glm::vec4(0, 0, 0, 1) : glm::vec4(1, 1, 1, 1);
+ });
+ CHECK(inflateSilhouette(sketch, o, &err).triangleCount() > 0);
+ Image blank = makeImage(32, 32, [](float, float) { return glm::vec4(1); });
+ CHECK(inflateSilhouette(blank, o, &err).triangleCount() == 0 && !err.empty());
+}
+
+TEST(image_projection) {
+ Mesh m = makeIcosphere(4);
+ const auto before = m.positions;
+ Image white = makeImage(16, 16, [](float, float) { return glm::vec4(1); });
+ glm::vec3 eye(0, 0, 5);
+ glm::mat4 vp = glm::perspective(glm::radians(35.0f), 1.0f, 0.1f, 20.0f) *
+ glm::lookAt(eye, glm::vec3(0), glm::vec3(0, 1, 0));
+ ProjectOptions o;
+ o.depth = 0.1f;
+ size_t n = projectImage(m, -1, white, vp, 1.0f, eye, o);
+ CHECK(n > 0);
+ bool backUntouched = true, frontRaised = false;
+ for (size_t i = 0; i < before.size(); ++i) {
+ if (before[i].z < -0.1f) backUntouched = backUntouched && m.positions[i] == before[i];
+ if (before[i].z > 0.95f) frontRaised = frontRaised || glm::length(m.positions[i]) > 1.05f;
+ }
+ CHECK(backUntouched && frontRaised);
+}
+
+TEST(gltf_roundtrip_with_layers) {
+ Mesh m = makeIcosphere(3);
+ int l = m.addLayer("Smile");
+ for (size_t v = 0; v < m.vertexCount(); ++v) m.layers[l].delta[v] = glm::vec3(0, m.positions[v].y * 0.1f, 0);
+ m.setLayerWeight(l, 0.25f);
+ const std::string path = tempPath("sculptforge_roundtrip.glb");
+ std::string err;
+ CHECK(saveGlb(path, m, "Head", err));
+ Mesh back;
+ CHECK(loadGltf(path, back, err));
+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());
+ CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.25f) < 1e-6f);
+ for (size_t v = 0; v < m.vertexCount(); ++v) CHECK(glm::distance(back.positions[v], m.positions[v]) < 1e-5f);
+ std::filesystem::remove(path);
+
+ CommandRegistry reg;
+ Document d;
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 2.0}}).ok);
+ CHECK(reg.execute(d, "export_glb", {{"path", path}}).ok);
+ CHECK(reg.execute(d, "open", {{"path", path}}).ok);
+ CHECK(d.mesh.triangleCount() == 320);
+ std::filesystem::remove(path);
+}
+
+TEST(image_commands) {
+ const std::string bmp = tempPath("sculptforge_sketch.bmp");
+ writeBmp(bmp, makeImage(64, 64, [](float u, float v) {
+ float d = glm::length(glm::vec2(u, v) - 0.5f);
+ return d < 0.35f ? glm::vec4(0.1f, 0.1f, 0.1f, 1) : glm::vec4(1, 1, 1, 1);
+ }));
+ CommandRegistry reg;
+ Document d;
+ CommandResult r = reg.execute(d, "image_inflate", {{"path", bmp}});
+ CHECK(r.ok);
+ if (!r.ok) std::printf(" %s\n", r.message.c_str());
+ CHECK(d.mesh.triangleCount() > 500);
+ CHECK(reg.execute(d, "image_project", {{"path", bmp}, {"depth", 0.02}}).ok);
+ CHECK(reg.execute(d, "undo").ok);
+ CHECK(reg.execute(d, "image_relief", {{"path", bmp}, {"resolution", 64.0}}).ok);
+ CHECK(d.mesh.triangleCount() == 64u * 64u * 2u);
+ CHECK(!reg.execute(d, "image_relief", {{"path", tempPath("missing_sculptforge.png")}}).ok);
+ std::filesystem::remove(bmp);
+}
+
+// --- Voxel remesh, splats, PLY, USD, glTF splats, MCP, image-to-3D services ---
+
+bool isClosedManifold(const Mesh& m) {
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const auto& t : m.triangles)
+ for (int k = 0; k < 3; ++k) ++edges[std::minmax(t[k], t[(k + 1) % 3])];
+ for (const auto& [e, n] : edges)
+ if (n != 2) return false;
+ return !edges.empty();
+}
+
+double signedVolume(const Mesh& m) {
+ double v = 0.0;
+ for (const auto& t : m.triangles)
+ v += double(glm::dot(m.positions[t.x], glm::cross(m.positions[t.y], m.positions[t.z]))) / 6.0;
+ return v;
+}
+
+TEST(voxel_remesh) {
+ Mesh sphere = makeIcosphere(4);
+ std::string err;
+ Mesh r = voxelRemesh(sphere, 64, &err);
+ CHECK(r.triangleCount() > 1000);
+ CHECK(isClosedManifold(r));
+ const double vol = signedVolume(r);
+ CHECK(vol > 0.0); // faces point outwards
+ CHECK(std::abs(vol - 4.18879) < 0.04 * 4.18879); // unit-sphere volume preserved within 4%
+ float worst = 0.0f;
+ for (const auto& p : r.positions) worst = std::max(worst, std::abs(glm::length(p) - 1.0f));
+ CHECK(worst < 0.03f);
+
+ // Two overlapping spheres merge into one closed surface.
+ Mesh a = makeIcosphere(3), b = makeIcosphere(3), both;
+ for (auto& p : b.positions) p += glm::vec3(1.2f, 0, 0);
+ both.positions = a.positions;
+ both.positions.insert(both.positions.end(), b.positions.begin(), b.positions.end());
+ both.triangles = a.triangles;
+ for (auto t : b.triangles) both.triangles.push_back(t + glm::uvec3(uint32_t(a.vertexCount())));
+ both.rebuildTopology();
+ Mesh merged = voxelRemesh(both, 80, &err);
+ CHECK(isClosedManifold(merged));
+ CHECK(long(merged.vertexCount()) - long(merged.triangleCount() * 3 / 2) + long(merged.triangleCount()) == 2); // one piece
+
+ CommandRegistry reg;
+ Document d;
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ CHECK(reg.execute(d, "remesh", {{"resolution", 48.0}}).ok);
+ CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);
+ CHECK(!voxelRemesh(Mesh(), 64, &err).triangleCount() && !err.empty());
+}
+
+TEST(splats_mesh_conversions) {
+ Mesh sphere = makeIcosphere(4);
+ MeshToSplatsOptions o;
+ o.count = 40000;
+ SplatCloud c = meshToSplats(sphere, o);
+ CHECK(c.size() == 40000 && c.validate().empty());
+ bool onSurface = true, flat = true;
+ for (size_t i = 0; i < c.size(); ++i) {
+ onSurface = onSurface && std::abs(glm::length(c.positions[i]) - 1.0f) < 0.01f;
+ const glm::vec3 n = glm::mat3_cast(c.rotations[i])[2]; // thin axis
+ flat = flat && std::abs(glm::dot(n, glm::normalize(c.positions[i]))) > 0.98f && c.scales[i].z < c.scales[i].x * 0.2f;
+ }
+ CHECK(onSurface && flat);
+
+ std::string err;
+ SplatToMeshOptions so;
+ so.resolution = 64;
+ Mesh back = splatsToMesh(c, so, &err);
+ CHECK(back.triangleCount() > 1000);
+ CHECK(isClosedManifold(back));
+ CHECK(signedVolume(back) > 0.0);
+ const AABB b = back.bounds();
+ CHECK(std::abs(b.extent().x - 2.0f) < 0.15f && std::abs(b.center().y) < 0.05f);
+
+ // Floaters are dropped: only the largest solid survives.
+ SplatCloud noisy = c;
+ noisy.positions.push_back(glm::vec3(0, 3, 0));
+ noisy.rotations.push_back(glm::quat(1, 0, 0, 0));
+ noisy.scales.push_back(glm::vec3(0.1f));
+ noisy.opacities.push_back(1.0f);
+ noisy.sh.push_back(glm::vec3(0));
+ so.keepFraction = 1.0f;
+ CHECK(splatsToMesh(noisy, so, &err).bounds().max.y < 1.2f);
+
+ // Placement: rotate/fit keep the data, bake applies it.
+ SplatCloud t = c;
+ t.transform = glm::translate(glm::mat4(1.0f), glm::vec3(5, 0, 0)) * glm::scale(glm::mat4(1.0f), glm::vec3(3.0f));
+ fitSplats(t);
+ CHECK(glm::length(t.bounds(0.9f).center()) < 0.05f);
+ CHECK(std::abs(t.bounds(0.9f).extent().x - 2.0f) < 0.05f);
+ t.bakeTransform();
+ CHECK(t.transform == glm::mat4(1.0f) && glm::length(t.bounds(0.9f).center()) < 0.05f);
+ CHECK(cleanSplats(noisy, 0.05f, 0.9f) > 0);
+}
+
+SplatCloud testCloud(int degree) {
+ SplatCloud c;
+ c.resize(50, degree);
+ for (size_t i = 0; i < c.size(); ++i) {
+ const float f = float(i);
+ c.positions[i] = glm::vec3(std::sin(f), std::cos(f * 0.7f), f * 0.01f);
+ c.rotations[i] = glm::normalize(glm::quat(1.0f, 0.1f * f, -0.05f * f, 0.3f));
+ c.scales[i] = glm::vec3(0.01f + 0.001f * f, 0.02f, 0.005f);
+ c.opacities[i] = 0.1f + 0.015f * f;
+ for (int k = 0; k < c.shCount(); ++k) c.sh[i * size_t(c.shCount()) + size_t(k)] = glm::vec3(0.1f * float(k), -0.2f * f / 50.0f, 0.3f);
+ }
+ return c;
+}
+
+bool sameRotation(const glm::quat& a, const glm::quat& b, float tol) { return std::abs(std::abs(glm::dot(a, b)) - 1.0f) < tol; }
+
+TEST(splat_ply_and_dot_splat_roundtrip) {
+ for (int degree : {0, 1, 3}) {
+ SplatCloud c = testCloud(degree);
+ const std::string path = tempPath("sculptforge_splats.ply");
+ std::string err;
+ CHECK(saveSplatPly(path, c, err));
+ Mesh m;
+ SplatCloud back;
+ PlyContent content;
+ CHECK(loadPly(path, m, back, content, err) && content == PlyContent::Splats);
+ CHECK(back.size() == c.size() && back.shDegree == degree);
+ bool same = true;
+ for (size_t i = 0; i < c.size(); ++i) {
+ same = same && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;
+ same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-6f;
+ same = same && std::abs(back.opacities[i] - c.opacities[i]) < 1e-5f;
+ same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);
+ }
+ for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;
+ CHECK(same);
+ std::filesystem::remove(path);
+ }
+ SplatCloud c = testCloud(0);
+ const std::string path = tempPath("sculptforge_splats.splat");
+ std::string err;
+ CHECK(saveDotSplat(path, c, err));
+ SplatCloud back;
+ CHECK(loadDotSplat(path, back, err) && back.size() == c.size());
+ bool close = true;
+ for (size_t i = 0; i < c.size(); ++i) {
+ close = close && glm::distance(back.positions[i], c.positions[i]) < 1e-6f;
+ close = close && glm::distance(back.color(i), glm::clamp(c.color(i), 0.0f, 1.0f)) < 0.01f;
+ close = close && sameRotation(back.rotations[i], c.rotations[i], 0.01f);
+ }
+ CHECK(close);
+ std::filesystem::remove(path);
+}
+
+TEST(ply_mesh_and_point_cloud) {
+ const std::string path = tempPath("sculptforge_quad.ply");
+ {
+ std::ofstream f(path);
+ f << "ply\nformat ascii 1.0\ncomment a unit quad pyramid\nelement vertex 5\nproperty float x\nproperty float y\n"
+ "property float z\nelement face 5\nproperty list uchar int vertex_indices\nend_header\n"
+ "0 0 0\n1 0 0\n1 1 0\n0 1 0\n0.5 0.5 1\n4 3 2 1 0\n3 0 1 4\n3 1 2 4\n3 2 3 4\n3 3 0 4\n";
+ }
+ Mesh m;
+ SplatCloud s;
+ PlyContent content;
+ std::string err;
+ CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Mesh);
+ CHECK(m.vertexCount() == 5 && m.triangleCount() == 6 && isClosedManifold(m));
+ {
+ std::ofstream f(path, std::ios::binary);
+ f << "ply\nformat binary_big_endian 1.0\nelement vertex 2\nproperty double x\nproperty double y\nproperty double z\n"
+ "property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n";
+ auto be = [&](double d) {
+ uint64_t u;
+ std::memcpy(&u, &d, 8);
+ for (int k = 7; k >= 0; --k) f.put(char((u >> (k * 8)) & 0xFF));
+ };
+ be(1); be(2); be(3); f.put(char(255)); f.put(0); f.put(0);
+ be(-1); be(0); be(0); f.put(0); f.put(0); f.put(char(255));
+ }
+ CHECK(loadPly(path, m, s, content, err) && content == PlyContent::Splats);
+ CHECK(s.size() == 2 && s.positions[0] == glm::vec3(1, 2, 3) && glm::distance(s.color(0), glm::vec3(1, 0, 0)) < 1e-5f);
+ std::filesystem::remove(path);
+ CHECK(!loadPly(tempPath("missing_sculptforge.ply"), m, s, content, err));
+}
+
+TEST(zip_and_usdz_alignment) {
+ const char* digits = "123456789";
+ CHECK(crc32(reinterpret_cast<const uint8_t*>(digits), 9) == 0xCBF43926u);
+ const std::string path = tempPath("sculptforge_test.zip");
+ std::vector<ZipEntry> entries = {{"a.usda", std::vector<uint8_t>(100, 'a')}, {"textures/b.png", std::vector<uint8_t>(7, 'b')}};
+ std::string err;
+ CHECK(writeStoredZip(path, entries, 64, err));
+ std::ifstream f(path, std::ios::binary);
+ std::vector<uint8_t> z((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ // Find each entry's data via the local headers and check 64-byte alignment.
+ size_t p = 0, aligned = 0;
+ while (p + 30 <= z.size() && z[p] == 'P' && z[p + 1] == 'K' && z[p + 2] == 3 && z[p + 3] == 4) {
+ const size_t nameLen = z[p + 26] | z[p + 27] << 8, extra = z[p + 28] | z[p + 29] << 8;
+ const size_t size = z[p + 18] | z[p + 19] << 8 | z[p + 20] << 16 | size_t(z[p + 21]) << 24;
+ const size_t data = p + 30 + nameLen + extra;
+ aligned += data % 64 == 0;
+ p = data + size;
+ }
+ CHECK(aligned == 2);
+ std::vector<ZipEntry> back;
+ CHECK(readStoredZip(path, back, err) && back.size() == 2 && back[1].name == "textures/b.png" && back[0].data == entries[0].data);
+ std::filesystem::remove(path);
+}
+
+TEST(usd_roundtrip_mesh_layers_splats) {
+ Mesh m = makeIcosphere(2);
+ int smile = m.addLayer("Smile 2");
+ int blink = m.addLayer("Blink");
+ for (size_t v = 0; v < m.vertexCount(); ++v)
+ if (m.positions[v].y > 0.5f) m.layers[smile].delta[v] = glm::vec3(0, 0.1f, 0);
+ m.layers[blink].delta[3] = glm::vec3(0.2f, 0, 0);
+ m.setLayerWeight(smile, 0.75f);
+ m.setLayerWeight(blink, 0.0f);
+ SplatCloud c = testCloud(1);
+ c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(0, 2, 0));
+
+ for (const char* name : {"sculptforge_test.usda", "sculptforge_test.usdz"}) {
+ const std::string path = tempPath(name);
+ std::string err;
+ CHECK(saveUsd(path, &m, &c, "Hero Head", err));
+ Mesh back;
+ SplatCloud sback;
+ CHECK(loadUsd(path, back, sback, err));
+ if (!err.empty()) std::printf(" %s\n", err.c_str());
+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());
+ CHECK(back.layers.size() == 2 && back.layers[0].name == "Smile_2" && std::abs(back.layers[0].weight - 0.75f) < 1e-6f);
+ bool same = true;
+ for (size_t v = 0; v < m.vertexCount(); ++v) {
+ same = same && glm::distance(back.base[v], m.base[v]) < 1e-6f;
+ same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-6f;
+ same = same && glm::distance(back.layers[1].delta[v], m.layers[1].delta[v]) < 1e-6f;
+ same = same && glm::distance(back.positions[v], m.positions[v]) < 1e-5f;
+ }
+ CHECK(same);
+ CHECK(sback.size() == c.size() && sback.shDegree == 1);
+ bool splatsSame = true;
+ for (size_t i = 0; i < c.size(); ++i) {
+ splatsSame = splatsSame && glm::distance(sback.worldPosition(i), c.worldPosition(i)) < 1e-5f;
+ splatsSame = splatsSame && sameRotation(sback.rotations[i], c.rotations[i], 1e-6f);
+ splatsSame = splatsSame && std::abs(sback.opacities[i] - c.opacities[i]) < 1e-6f;
+ }
+ for (size_t k = 0; k < c.sh.size(); ++k) splatsSame = splatsSame && glm::distance(sback.sh[k], c.sh[k]) < 1e-6f;
+ CHECK(splatsSame);
+ std::filesystem::remove(path);
+ }
+ CHECK(usdIdentifier("3 eyes!") == "_3_eyes_");
+}
+
+TEST(usd_reader_handles_foreign_files) {
+ const std::string path = tempPath("sculptforge_foreign.usda");
+ {
+ std::ofstream f(path);
+ f << R"(#usda 1.0
+(
+ doc = """A multi-line
+ doc with { braces } and "quotes" """
+ upAxis = "Z"
+ customLayerData = { string creator = "test" }
+)
+
+class "Template" { def Mesh "Ignored" { point3f[] points = [(9,9,9),(9,9,8),(9,8,9)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0,1,2] } }
+
+def Xform "World" (
+ kind = "assembly"
+)
+{
+ double3 xformOp:translate = (0, 0, 10) # moved up 10 in Z-up
+ float3 xformOp:scale = (2, 2, 2)
+ uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
+
+ def Mesh "Quad" (
+ prepend apiSchemas = ["MaterialBindingAPI"]
+ )
+ {
+ uniform token orientation = "leftHanded"
+ int[] faceVertexCounts = [4]
+ int[] faceVertexIndices = [0, 1, 2, 3]
+ point3f[] points.timeSamples = {
+ 1: [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)],
+ 2: [(5, 5, 5), (6, 5, 5), (6, 6, 5), (5, 6, 5)],
+ }
+ color3f[] primvars:displayColor = [(1, 0, 0)] (
+ interpolation = "constant"
+ )
+ rel material:binding = </World/Looks/Red>
+ }
+
+ variantSet "lod" = {
+ "high" { def Mesh "Variant" { point3f[] points = [(7,7,7)] } }
+ }
+}
+)";
+ }
+ Mesh m;
+ SplatCloud s;
+ std::string err;
+ CHECK(loadUsd(path, m, s, err));
+ if (!err.empty()) std::printf(" %s\n", err.c_str());
+ CHECK(m.vertexCount() == 4 && m.triangleCount() == 2 && s.empty());
+ const AABB b = m.bounds();
+ // Z-up converted to Y-up: translate (0,0,10) becomes +10 in Y; scale 2 makes the quad 2x2 in the X/-Z plane.
+ CHECK(std::abs(b.min.y - 10.0f) < 1e-5f && std::abs(b.max.y - 10.0f) < 1e-5f);
+ CHECK(std::abs(b.extent().x - 2.0f) < 1e-5f && std::abs(b.extent().z - 2.0f) < 1e-5f);
+ // Left-handed winding was flipped: the quad (CCW in XY seen from +Z) now faces -Z-up = ... down after conversion.
+ const glm::vec3 n = glm::cross(m.positions[m.triangles[0].y] - m.positions[m.triangles[0].x],
+ m.positions[m.triangles[0].z] - m.positions[m.triangles[0].x]);
+ CHECK(n.y < 0.0f);
+ {
+ std::ofstream f(path, std::ios::binary);
+ f << "PXR-USDC binary";
+ }
+ CHECK(!loadUsd(path, m, s, err) && err.find("usdc") != std::string::npos);
+ std::filesystem::remove(path);
+}
+
+TEST(gltf_gaussian_splatting_roundtrip) {
+ SplatCloud c = testCloud(2);
+ c.transform = glm::translate(glm::mat4(1.0f), glm::vec3(1, 2, 3)) * glm::scale(glm::mat4(1.0f), glm::vec3(0.5f));
+ const std::string path = tempPath("sculptforge_splats.glb");
+ std::string err;
+ CHECK(saveSplatGlb(path, c, err));
+ Mesh m;
+ SplatCloud back;
+ CHECK(loadGltf(path, m, err, &back));
+ CHECK(m.triangleCount() == 0 && back.size() == c.size() && back.shDegree == 2);
+ bool same = true;
+ for (size_t i = 0; i < c.size(); ++i) {
+ same = same && glm::distance(back.worldPosition(i), c.worldPosition(i)) < 1e-5f;
+ same = same && sameRotation(back.rotations[i], c.rotations[i], 1e-6f);
+ same = same && glm::distance(back.scales[i], c.scales[i]) < 1e-7f;
+ }
+ for (size_t k = 0; k < c.sh.size(); ++k) same = same && glm::distance(back.sh[k], c.sh[k]) < 1e-6f;
+ CHECK(same);
+ // Opening it as a document keeps the mesh and adds the splats.
+ CommandRegistry reg;
+ Document d;
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 1.0}}).ok);
+ CHECK(reg.execute(d, "open", {{"path", path}}).ok && d.splats.size() == c.size() && d.mesh.triangleCount() == 80);
+ CHECK(!loadGltf(path, m, err)); // without a splat target, a splat-only file has no meshes
+ std::filesystem::remove(path);
+}
+
+TEST(splat_commands) {
+ CommandRegistry reg;
+ Document d;
+ CHECK(!reg.execute(d, "splat_to_mesh").ok); // nothing loaded
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ const uint64_t v0 = d.splatsVersion;
+ CHECK(reg.execute(d, "mesh_to_splats", {{"count", 20000.0}}).ok && d.splats.size() == 20000 && d.splatsVersion != v0);
+ CHECK(reg.execute(d, "splat_transform", {{"rotate_x", 180.0}, {"fit", true}}).ok);
+ CHECK(reg.execute(d, "splat_clean", {{"min_opacity", 0.5}}).ok);
+ CHECK(reg.execute(d, "splat_to_mesh", {{"resolution", 48.0}}).ok && isClosedManifold(d.mesh));
+ CHECK(reg.execute(d, "undo").ok && d.mesh.triangleCount() == 1280);
+ for (const char* ext : {".ply", ".splat", ".glb", ".usda", ".usdz"}) {
+ const std::string path = tempPath((std::string("sculptforge_cmd_splats") + ext).c_str());
+ CHECK(reg.execute(d, "splat_save", {{"path", path}}).ok);
+ Document e;
+ CHECK(reg.execute(e, "open", {{"path", path}}).ok && e.splats.size() == d.splats.size());
+ std::filesystem::remove(path);
+ }
+ CHECK(!reg.execute(d, "splat_save", {{"path", tempPath("sculptforge_bad.txt")}}).ok);
+ const std::string usd = tempPath("sculptforge_cmd.usdz");
+ CHECK(reg.execute(d, "export_usd", {{"path", usd}}).ok);
+ std::filesystem::remove(usd);
+ CHECK(reg.execute(d, "splat_clear").ok && d.splats.empty());
+}
+
+TEST(mcp_server_protocol) {
+ CommandRegistry reg;
+ Document d;
+ auto call = [&](const std::string& line) {
+ Json j;
+ std::string err;
+ const std::string out = handleMcpMessage(reg, d, line);
+ if (!out.empty()) Json::parse(out, j, err);
+ return j;
+ };
+ Json init = call(R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}})");
+ CHECK(init["result"]["protocolVersion"].asString() == "2025-06-18");
+ CHECK(init["result"]["serverInfo"]["name"].asString() == "sculptforge" && init["result"]["capabilities"]["tools"].isObject());
+ CHECK(handleMcpMessage(reg, d, R"({"jsonrpc":"2.0","method":"notifications/initialized"})").empty());
+ Json list = call(R"({"jsonrpc":"2.0","id":2,"method":"tools/list"})");
+ bool hasRemesh = false, schemasOk = true;
+ for (const auto& t : list["result"]["tools"].items()) {
+ hasRemesh = hasRemesh || t["name"].asString() == "remesh";
+ schemasOk = schemasOk && t["inputSchema"]["type"].asString() == "object";
+ }
+ CHECK(hasRemesh && schemasOk && list["result"]["tools"].size() == reg.all().size());
+ Json ok = call(R"({"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":2}}})");
+ CHECK(ok["id"].asString() == "a" && !ok["result"]["isError"].asBool(true) && d.mesh.triangleCount() == 320);
+ CHECK(ok["result"]["content"][0]["text"].asString().find("320") != std::string::npos);
+ Json bad = call(R"({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"open","arguments":{"path":"/nonexistent/x.obj"}}})");
+ CHECK(bad["result"]["isError"].asBool(false));
+ CHECK(call(R"({"jsonrpc":"2.0","id":5,"method":"nope"})")["error"]["code"].asNumber() == -32601);
+ CHECK(call("not json")["error"]["code"].asNumber() == -32700);
+ CHECK(call(R"({"jsonrpc":"2.0","id":6,"method":"ping"})")["result"].isObject());
+}
+
+TEST(image_to_3d_service_requests) {
+ const uint8_t man[] = {'M', 'a', 'n'};
+ CHECK(ai::base64Encode(man, 3) == "TWFu" && ai::base64Encode(man, 2) == "TWE=" && ai::base64Encode(man, 1) == "TQ==");
+ Json body;
+ std::string err;
+ CHECK(Json::parse(ai::falSubmitBody("fal-ai/trellis-2", "data:x"), body, err) && body["image_url"].asString() == "data:x");
+ CHECK(Json::parse(ai::falSubmitBody("fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d", "data:x"), body, err) &&
+ body["input_image_url"].asString() == "data:x" && body["enable_geometry"].asBool());
+ CHECK(Json::parse(ai::meshySubmitBody("", "data:x"), body, err) && body["ai_model"].asString() == "latest" &&
+ !body["should_texture"].asBool(true) && body["target_formats"][0].asString() == "glb");
+
+ std::string ext;
+ Json r;
+ Json::parse(R"({"model_glb":{"url":"https://cdn/x/model.glb","content_type":"model/gltf-binary"}})", r, err);
+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.glb" && ext == ".glb");
+ Json::parse(R"({"model_glb":{"url":"https://cdn/x/mesh.obj?sig=1","content_type":"text/plain"}})", r, err);
+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/mesh.obj?sig=1" && ext == ".obj");
+ Json::parse(R"({"model_urls":{"glb":"https://assets.meshy.ai/t/model.glb?Expires=1","fbx":"https://a/b.fbx"}})", r, err);
+ CHECK(ai::findModelUrl(r, &ext) == "https://assets.meshy.ai/t/model.glb?Expires=1");
+ Json::parse(R"({"outputs":[{"file":{"href":"https://x/deep.glb"}}]})", r, err);
+ CHECK(ai::findModelUrl(r, &ext) == "https://x/deep.glb");
+ Json::parse(R"({"images":[]})", r, err);
+ CHECK(ai::findModelUrl(r, &ext).empty());
+
+ // A small character on a big transparent canvas is cropped and centred on a square.
+ Image canvas = makeImage(400, 200, [](float u, float v) {
+ const bool body = u > 0.1f && u < 0.2f && v > 0.5f && v < 0.9f;
+ return glm::vec4(1, 0, 0, body ? 1.0f : 0.0f);
+ });
+ Image framed = canvas.framedSubject(0.08f);
+ CHECK(framed.width == framed.height && framed.width < 120 && framed.width > 80);
+ CHECK(framed.rgba[(size_t(framed.height / 2) * size_t(framed.width) + size_t(framed.width / 2)) * 4 + 3] == 255);
+ Image big = makeImage(3000, 1500, [](float, float) { return glm::vec4(0.5f, 0.5f, 0.5f, 1); });
+ Image small = big.downscaled(1024);
+ CHECK(small.width == 1024 && small.height == 512 && small.rgba[0] > 120 && small.rgba[0] < 135);
+ std::vector<uint8_t> png;
+ CHECK(small.encodePng(png) && png.size() > 8 && png[1] == 'P' && png[2] == 'N' && png[3] == 'G');
+
+ // Missing keys fail fast with a helpful message, without touching the network.
+ ai::AiSettings s;
+ s.falKey.clear();
+ s.generatorService = "fal";
+ if (!std::getenv("FAL_KEY")) {
+ ai::GeneratorResult g = ai::generate3D(s, "unused.png", tempPath("sculptforge_gen"));
+ CHECK(!g.ok && g.error.find("fal.ai") != std::string::npos);
+ }
+ // Settings survive a save/load.
+ s.generatorService = "meshy";
+ s.falModel = "fal-ai/hunyuan-3d/v3.1/pro/image-to-3d";
+ ai::AiSettings loaded = ai::AiSettings::fromJson(s.toJson());
+ CHECK(loaded.generatorService == "meshy" && loaded.falModel == s.falModel && loaded.meshyEndpoint == "https://api.meshy.ai");
+}
+
+// --- FBX export/import, Unreal preset and link ---
+
+TEST(fbx_roundtrip_layers_and_lods) {
+ Mesh m = makeIcosphere(3);
+ int smile = m.addLayer("Smile");
+ for (size_t v = 0; v < m.vertexCount(); ++v)
+ if (m.positions[v].y > 0.3f) m.layers[smile].delta[v] = glm::vec3(0.0f, 0.05f, 0.02f);
+ m.setLayerWeight(smile, 0.3f);
+ const std::string path = tempPath("sculptforge_test.fbx");
+ std::string err;
+ FbxExportOptions o;
+ o.scale = 100.0f; // metres -> centimetres
+ CHECK(saveFbx(path, "Head", {&m}, o, err));
+ {
+ std::ifstream f(path, std::ios::binary);
+ std::vector<char> head(27);
+ f.read(head.data(), 27);
+ CHECK(std::memcmp(head.data(), "Kaydara FBX Binary \0\x1a\0", 23) == 0);
+ uint32_t version;
+ std::memcpy(&version, head.data() + 23, 4);
+ CHECK(version == 7400);
+ }
+ Mesh back;
+ CHECK(loadFbx(path, back, err));
+ if (!err.empty()) std::printf(" %s\n", err.c_str());
+ CHECK(back.vertexCount() == m.vertexCount() && back.triangleCount() == m.triangleCount());
+ CHECK(back.layers.size() == 1 && back.layers[0].name == "Smile" && std::abs(back.layers[0].weight - 0.3f) < 1e-5f);
+ bool same = true;
+ for (size_t v = 0; v < m.vertexCount(); ++v) {
+ same = same && glm::distance(back.base[v], m.base[v]) < 1e-5f;
+ same = same && glm::distance(back.layers[0].delta[v], m.layers[0].delta[v]) < 1e-5f;
+ }
+ CHECK(same);
+ CHECK(signedVolume(back) > 0.0); // winding survives the trip
+
+ // LOD group: import takes LOD0 only.
+ std::vector<Mesh> lods = generateLods(makeIcosphere(4), 3, 0.5f);
+ CHECK(saveFbx(path, "Rock", {&lods[0], &lods[1], &lods[2]}, o, err));
+ CHECK(loadFbx(path, back, err) && back.triangleCount() == lods[0].triangleCount());
+ CHECK(!saveFbx(path, "Empty", {}, o, err));
+ std::filesystem::remove(path);
+ CHECK(!loadFbx(tempPath("missing_sculptforge.fbx"), back, err));
+}
+
+TEST(unreal_export_preset) {
+ Document d;
+ CommandRegistry reg;
+ CHECK(reg.execute(d, "new_sphere", {{"subdivisions", 3.0}}).ok);
+ const std::string folder = tempPath("sculptforge_unreal_test");
+ UnrealExportOptions o;
+ o.folder = folder;
+ o.heightCm = 180.0f;
+ o.lods = 3;
+ UnrealExportResult r;
+ std::string err;
+ CHECK(exportForUnreal(d, o, r, err));
+ CHECK(r.assetName == "SM_Sculpt" && !r.skeletal && r.lodCount == 3 && std::abs(r.scale - 90.0f) < 1e-3f);
+ Mesh back;
+ CHECK(loadFbx(r.path, back, err) && std::abs(back.bounds().extent().y - 1.8f) < 1e-3f); // 180 cm = 1.8 m
+
+ CHECK(reg.execute(d, "layer_add", {{"name", std::string("Blink")}}).ok);
+ CHECK(exportForUnreal(d, o, r, err));
+ CHECK(r.assetName == "SK_Sculpt" && r.skeletal && r.lodCount == 1); // morph targets need a skeletal mesh
+ o.assetName = "My Rock!";
+ CHECK(exportForUnreal(d, o, r, err) && r.assetName == "My_Rock_");
+ CHECK(reg.execute(d, "export_unreal", {{"folder", folder}, {"lods", 2.0}}).ok);
+ CHECK(reg.execute(d, "export_fbx", {{"path", folder + "/plain.fbx"}, {"lods", 2.0}}).ok);
+ std::filesystem::remove_all(folder);
+}
+
+TEST(unreal_link_messages_and_script) {
+ Json msg;
+ std::string err;
+ CHECK(Json::parse(link::unrealMessage("ping", "abc", "", ""), msg, err));
+ CHECK(msg["version"].asNumber() == 1 && msg["magic"].asString() == "ue_py" && msg["type"].asString() == "ping" &&
+ msg["source"].asString() == "abc" && !msg.has("dest") && !msg.has("data"));
+ CHECK(Json::parse(link::unrealMessage("open_connection", "a", "b", R"({"command_ip":"127.0.0.1","command_port":6776})"), msg, err));
+ CHECK(msg["dest"].asString() == "b" && msg["data"]["command_port"].asNumber() == 6776);
+
+ link::UnrealImport im;
+ im.fbxPath = "C:\\Art\\it's.fbx";
+ im.assetName = "SK_Head";
+ im.skeletal = true;
+ std::string py = link::unrealImportScript(im);
+ CHECK(py.find("'C:\\\\Art\\\\it\\'s.fbx'") != std::string::npos); // escaped Python literal
+ CHECK(py.find("FBXIT_SKELETAL_MESH") != std::string::npos && py.find("import_morph_targets', True") != std::string::npos);
+ CHECK(py.find("automated_import_should_detect_type', False") != std::string::npos);
+ CHECK(py.find("SCULPTFORGE_IMPORTED") != std::string::npos && py.find("urllib") == std::string::npos);
+ im.skeletal = false;
+ im.lods = true;
+ im.downloadUrl = "http://10.0.0.5:5000/token/SM_Rock.fbx";
+ py = link::unrealImportScript(im);
+ CHECK(py.find("import_mesh_lo_ds', True") != std::string::npos && py.find("FBXIT_STATIC_MESH") != std::string::npos);
+ CHECK(py.find("urlopen('http://10.0.0.5:5000/token/SM_Rock.fbx'") != std::string::npos);
+
+ link::UnrealEditor ed;
+ ed.address = "127.0.0.1";
+ CHECK(ed.local());
+ ed.address = "192.0.2.10";
+ ed.machine = "some-other-machine-name";
+ CHECK(!ed.local());
+ CHECK(link::UnrealEndpoint().multicastTtl == 0 && link::UnrealEndpoint::network().multicastTtl == 1);
+}
+
+TEST(free_huggingface_models) {
+ const auto& presets = ai::hfPresets();
+ CHECK(presets.size() >= 4);
+ bool wellFormed = true, usesImage = true;
+ for (const auto& p : presets) {
+ wellFormed = wellFormed && std::string(p.space).rfind("https://", 0) == 0 && !p.steps.empty();
+ bool image = false;
+ for (const auto& step : p.steps)
+ for (const auto& a : step.args) {
+ image = image || a == "$IMG";
+ if (a != "$IMG" && a.rfind("$OUT", 0) != 0) {
+ Json v;
+ std::string err;
+ wellFormed = wellFormed && Json::parse(a, v, err); // literal args must be valid JSON
+ }
+ }
+ usesImage = usesImage && image;
+ }
+ CHECK(wellFormed && usesImage);
+ ai::AiSettings defaults;
+ CHECK(defaults.generatorService == "huggingface" && defaults.hfModel == presets[0].id);
+ defaults.hfModel = "trellis-2";
+ defaults.hfToken = "hf_test";
+ ai::AiSettings loaded = ai::AiSettings::fromJson(defaults.toJson());
+ CHECK(loaded.hfModel == "trellis-2" && loaded.resolvedHfToken() == "hf_test");
+ CHECK(ai::friendlyGradioError("You have exceeded your ZeroGPU quota (120s requested vs. 0s left).").find("free GPU time") !=
+ std::string::npos);
+ CHECK(ai::friendlyGradioError("some other failure") == "some other failure");
+ std::string png, err;
+ CHECK(!ai::prepareImagePng(tempPath("missing_sculptforge.png"), png, err));
+
+ // Text to 3D.
+ CHECK(!ai::hfTextPresets().empty());
+ bool usesPrompt = true;
+ for (const auto& p : ai::hfTextPresets()) {
+ bool prompt = false;
+ for (const auto& step : p.steps)
+ for (const auto& a : step.args) prompt = prompt || a == "$PROMPT";
+ usesPrompt = usesPrompt && prompt;
+ }
+ CHECK(usesPrompt);
+ Json body;
+ CHECK(Json::parse(ai::meshyTextBody("", "a fox"), body, err) && body["mode"].asString() == "preview" &&
+ body["prompt"].asString() == "a fox" && body["ai_model"].asString() == "latest");
+ CHECK(Json::parse(ai::falTextBody(std::string(300, 'x')), body, err) && body["prompt"].asString().size() == 200 &&
+ body["enable_geometry"].asBool());
+ ai::AiSettings offline;
+ offline.generatorService = "inflate";
+ CHECK(!ai::generate3DFromText(offline, "a fox", tempPath("sf_text")).ok);
+ CHECK(!ai::generate3DFromText(offline, " ", tempPath("sf_text")).ok);
+ Json r;
+ Json::parse(R"({"model_obj":{"url":"https://cdn/x/model.obj"},"model_urls":{"obj":"https://cdn/x/model.obj"}})", r, err);
+ std::string ext;
+ CHECK(ai::findModelUrl(r, &ext) == "https://cdn/x/model.obj" && ext == ".obj");
+}
+
+int main() {
+ for (const auto& t : registry()) {
+ int before = g_failures;
+ t.fn();
+ std::printf("%s %s\n", g_failures == before ? "[ OK ]" : "[FAIL]", t.name);
+ }
+ std::printf("\n%d checks, %d failures\n", g_checks, g_failures);
+ return g_failures == 0 ? 0 : 1;
+}
diff --git a/third_party/stb/SOURCE.txt b/third_party/stb/SOURCE.txt
new file mode 100644
index 00000000..26ac0e01
--- /dev/null
+++ b/third_party/stb/SOURCE.txt
@@ -0,0 +1 @@
+stb_image.h, stb_image_write.h from https://github.com/nothings/stb commit 013ac3beddff3dbffafd5177e7972067cd2b5083 (public domain / MIT)
diff --git a/third_party/stb/stb_image.h b/third_party/stb/stb_image.h
new file mode 100644
index 00000000..9eedabed
--- /dev/null
+++ b/third_party/stb/stb_image.h
@@ -0,0 +1,7988 @@
+/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb
+ no warranty implied; use at your own risk
+
+ Do this:
+ #define STB_IMAGE_IMPLEMENTATION
+ before you include this file in *one* C or C++ file to create the implementation.
+
+ // i.e. it should look like this:
+ #include ...
+ #include ...
+ #include ...
+ #define STB_IMAGE_IMPLEMENTATION
+ #include "stb_image.h"
+
+ You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
+ And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
+
+
+ QUICK NOTES:
+ Primarily of interest to game developers and other people who can
+ avoid problematic images and only need the trivial interface
+
+ JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
+ PNG 1/2/4/8/16-bit-per-channel
+
+ TGA (not sure what subset, if a subset)
+ BMP non-1bpp, non-RLE
+ PSD (composited view only, no extra channels, 8/16 bit-per-channel)
+
+ GIF (*comp always reports as 4-channel)
+ HDR (radiance rgbE format)
+ PIC (Softimage PIC)
+ PNM (PPM and PGM binary only)
+
+ Animated GIF still needs a proper API, but here's one way to do it:
+ http://gist.github.com/urraka/685d9a6340b26b830d49
+
+ - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
+ - decode from arbitrary I/O callbacks
+ - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
+
+ Full documentation under "DOCUMENTATION" below.
+
+
+LICENSE
+
+ See end of file for license information.
+
+RECENT REVISION HISTORY:
+
+ 2.30 (2024-05-31) avoid erroneous gcc warning
+ 2.29 (2023-05-xx) optimizations
+ 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff
+ 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
+ 2.26 (2020-07-13) many minor fixes
+ 2.25 (2020-02-02) fix warnings
+ 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
+ 2.23 (2019-08-11) fix clang static analysis warning
+ 2.22 (2019-03-04) gif fixes, fix warnings
+ 2.21 (2019-02-25) fix typo in comment
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes
+ 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
+ RGB-format JPEG; remove white matting in PSD;
+ allocate large structures on the stack;
+ correct channel count for PNG & BMP
+ 2.10 (2016-01-22) avoid warning introduced in 2.09
+ 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
+
+ See end of file for full revision history.
+
+
+ ============================ Contributors =========================
+
+ Image formats Extensions, features
+ Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
+ Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
+ Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
+ Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
+ Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
+ Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
+ Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
+ github:urraka (animated gif) Junggon Kim (PNM comments)
+ Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
+ socks-the-fox (16-bit PNG)
+ Jeremy Sawicki (handle all ImageNet JPGs)
+ Optimizations & bugfixes Mikhail Morozov (1-bit BMP)
+ Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)
+ Arseny Kapoulkine Simon Breuss (16-bit PNM)
+ John-Mark Allen
+ Carmelo J Fdez-Aguera
+
+ Bug & warning fixes
+ Marc LeBlanc David Woo Guillaume George Martins Mozeiko
+ Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski
+ Phil Jordan Dave Moore Roy Eltham
+ Hayaki Saito Nathan Reed Won Chun
+ Luke Graham Johan Duparc Nick Verigakis the Horde3D community
+ Thomas Ruf Ronny Chevalier github:rlyeh
+ Janez Zemva John Bartholomew Michal Cichon github:romigrou
+ Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
+ Eugene Golushkov Laurent Gomila Cort Stratton github:snagar
+ Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex
+ Cass Everitt Ryamond Barbiero github:grim210
+ Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw
+ Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus
+ Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo
+ Julian Raschke Gregory Mullen Christian Floisand github:darealshinji
+ Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007
+ Brad Weinberger Matvey Cherevko github:mosra
+ Luca Sas Alexander Veselov Zack Middleton [reserved]
+ Ryan C. Gordon [reserved] [reserved]
+ DO NOT ADD YOUR NAME HERE
+
+ Jacko Dirks
+
+ To add your name to the credits, pick a random blank space in the middle and fill it.
+ 80% of merge conflicts on stb PRs are due to people adding their name at the end
+ of the credits.
+*/
+
+#ifndef STBI_INCLUDE_STB_IMAGE_H
+#define STBI_INCLUDE_STB_IMAGE_H
+
+// DOCUMENTATION
+//
+// Limitations:
+// - no 12-bit-per-channel JPEG
+// - no JPEGs with arithmetic coding
+// - GIF always returns *comp=4
+//
+// Basic usage (see HDR discussion below for HDR usage):
+// int x,y,n;
+// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
+// // ... process data if not NULL ...
+// // ... x = width, y = height, n = # 8-bit components per pixel ...
+// // ... replace '0' with '1'..'4' to force that many components per pixel
+// // ... but 'n' will always be the number that it would have been if you said 0
+// stbi_image_free(data);
+//
+// Standard parameters:
+// int *x -- outputs image width in pixels
+// int *y -- outputs image height in pixels
+// int *channels_in_file -- outputs # of image components in image file
+// int desired_channels -- if non-zero, # of image components requested in result
+//
+// The return value from an image loader is an 'unsigned char *' which points
+// to the pixel data, or NULL on an allocation failure or if the image is
+// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
+// with each pixel consisting of N interleaved 8-bit components; the first
+// pixel pointed to is top-left-most in the image. There is no padding between
+// image scanlines or between pixels, regardless of format. The number of
+// components N is 'desired_channels' if desired_channels is non-zero, or
+// *channels_in_file otherwise. If desired_channels is non-zero,
+// *channels_in_file has the number of components that _would_ have been
+// output otherwise. E.g. if you set desired_channels to 4, you will always
+// get RGBA output, but you can check *channels_in_file to see if it's trivially
+// opaque because e.g. there were only 3 channels in the source image.
+//
+// An output image with N components has the following components interleaved
+// in this order in each pixel:
+//
+// N=#comp components
+// 1 grey
+// 2 grey, alpha
+// 3 red, green, blue
+// 4 red, green, blue, alpha
+//
+// If image loading fails for any reason, the return value will be NULL,
+// and *x, *y, *channels_in_file will be unchanged. The function
+// stbi_failure_reason() can be queried for an extremely brief, end-user
+// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
+// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
+// more user-friendly ones.
+//
+// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
+//
+// To query the width, height and component count of an image without having to
+// decode the full file, you can use the stbi_info family of functions:
+//
+// int x,y,n,ok;
+// ok = stbi_info(filename, &x, &y, &n);
+// // returns ok=1 and sets x, y, n if image is a supported format,
+// // 0 otherwise.
+//
+// Note that stb_image pervasively uses ints in its public API for sizes,
+// including sizes of memory buffers. This is now part of the API and thus
+// hard to change without causing breakage. As a result, the various image
+// loaders all have certain limits on image size; these differ somewhat
+// by format but generally boil down to either just under 2GB or just under
+// 1GB. When the decoded image would be larger than this, stb_image decoding
+// will fail.
+//
+// Additionally, stb_image will reject image files that have any of their
+// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
+// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
+// the only way to have an image with such dimensions load correctly
+// is for it to have a rather extreme aspect ratio. Either way, the
+// assumption here is that such larger images are likely to be malformed
+// or malicious. If you do need to load an image with individual dimensions
+// larger than that, and it still fits in the overall size limit, you can
+// #define STBI_MAX_DIMENSIONS on your own to be something larger.
+//
+// ===========================================================================
+//
+// UNICODE:
+//
+// If compiling for Windows and you wish to use Unicode filenames, compile
+// with
+// #define STBI_WINDOWS_UTF8
+// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert
+// Windows wchar_t filenames to utf8.
+//
+// ===========================================================================
+//
+// Philosophy
+//
+// stb libraries are designed with the following priorities:
+//
+// 1. easy to use
+// 2. easy to maintain
+// 3. good performance
+//
+// Sometimes I let "good performance" creep up in priority over "easy to maintain",
+// and for best performance I may provide less-easy-to-use APIs that give higher
+// performance, in addition to the easy-to-use ones. Nevertheless, it's important
+// to keep in mind that from the standpoint of you, a client of this library,
+// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.
+//
+// Some secondary priorities arise directly from the first two, some of which
+// provide more explicit reasons why performance can't be emphasized.
+//
+// - Portable ("ease of use")
+// - Small source code footprint ("easy to maintain")
+// - No dependencies ("ease of use")
+//
+// ===========================================================================
+//
+// I/O callbacks
+//
+// I/O callbacks allow you to read from arbitrary sources, like packaged
+// files or some other source. Data read from callbacks are processed
+// through a small internal buffer (currently 128 bytes) to try to reduce
+// overhead.
+//
+// The three functions you must define are "read" (reads some bytes of data),
+// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
+//
+// ===========================================================================
+//
+// SIMD support
+//
+// The JPEG decoder will try to automatically use SIMD kernels on x86 when
+// supported by the compiler. For ARM Neon support, you must explicitly
+// request it.
+//
+// (The old do-it-yourself SIMD API is no longer supported in the current
+// code.)
+//
+// On x86, SSE2 will automatically be used when available based on a run-time
+// test; if not, the generic C versions are used as a fall-back. On ARM targets,
+// the typical path is to have separate builds for NEON and non-NEON devices
+// (at least this is true for iOS and Android). Therefore, the NEON support is
+// toggled by a build flag: define STBI_NEON to get NEON loops.
+//
+// If for some reason you do not want to use any of SIMD code, or if
+// you have issues compiling it, you can disable it entirely by
+// defining STBI_NO_SIMD.
+//
+// ===========================================================================
+//
+// HDR image support (disable by defining STBI_NO_HDR)
+//
+// stb_image supports loading HDR images in general, and currently the Radiance
+// .HDR file format specifically. You can still load any file through the existing
+// interface; if you attempt to load an HDR file, it will be automatically remapped
+// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
+// both of these constants can be reconfigured through this interface:
+//
+// stbi_hdr_to_ldr_gamma(2.2f);
+// stbi_hdr_to_ldr_scale(1.0f);
+//
+// (note, do not use _inverse_ constants; stbi_image will invert them
+// appropriately).
+//
+// Additionally, there is a new, parallel interface for loading files as
+// (linear) floats to preserve the full dynamic range:
+//
+// float *data = stbi_loadf(filename, &x, &y, &n, 0);
+//
+// If you load LDR images through this interface, those images will
+// be promoted to floating point values, run through the inverse of
+// constants corresponding to the above:
+//
+// stbi_ldr_to_hdr_scale(1.0f);
+// stbi_ldr_to_hdr_gamma(2.2f);
+//
+// Finally, given a filename (or an open file or memory block--see header
+// file for details) containing image data, you can query for the "most
+// appropriate" interface to use (that is, whether the image is HDR or
+// not), using:
+//
+// stbi_is_hdr(char *filename);
+//
+// ===========================================================================
+//
+// iPhone PNG support:
+//
+// We optionally support converting iPhone-formatted PNGs (which store
+// premultiplied BGRA) back to RGB, even though they're internally encoded
+// differently. To enable this conversion, call
+// stbi_convert_iphone_png_to_rgb(1).
+//
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
+// pixel to remove any premultiplied alpha *only* if the image file explicitly
+// says there's premultiplied data (currently only happens in iPhone images,
+// and only if iPhone convert-to-rgb processing is on).
+//
+// ===========================================================================
+//
+// ADDITIONAL CONFIGURATION
+//
+// - You can suppress implementation of any of the decoders to reduce
+// your code footprint by #defining one or more of the following
+// symbols before creating the implementation.
+//
+// STBI_NO_JPEG
+// STBI_NO_PNG
+// STBI_NO_BMP
+// STBI_NO_PSD
+// STBI_NO_TGA
+// STBI_NO_GIF
+// STBI_NO_HDR
+// STBI_NO_PIC
+// STBI_NO_PNM (.ppm and .pgm)
+//
+// - You can request *only* certain decoders and suppress all other ones
+// (this will be more forward-compatible, as addition of new decoders
+// doesn't require you to disable them explicitly):
+//
+// STBI_ONLY_JPEG
+// STBI_ONLY_PNG
+// STBI_ONLY_BMP
+// STBI_ONLY_PSD
+// STBI_ONLY_TGA
+// STBI_ONLY_GIF
+// STBI_ONLY_HDR
+// STBI_ONLY_PIC
+// STBI_ONLY_PNM (.ppm and .pgm)
+//
+// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
+// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
+//
+// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
+// than that size (in either width or height) without further processing.
+// This is to let programs in the wild set an upper bound to prevent
+// denial-of-service attacks on untrusted data, as one could generate a
+// valid image of gigantic dimensions and force stb_image to allocate a
+// huge block of memory and spend disproportionate time decoding it. By
+// default this is set to (1 << 24), which is 16777216, but that's still
+// very big.
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif // STBI_NO_STDIO
+
+#define STBI_VERSION 1
+
+enum
+{
+ STBI_default = 0, // only used for desired_channels
+
+ STBI_grey = 1,
+ STBI_grey_alpha = 2,
+ STBI_rgb = 3,
+ STBI_rgb_alpha = 4
+};
+
+#include <stdlib.h>
+typedef unsigned char stbi_uc;
+typedef unsigned short stbi_us;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef STBIDEF
+#ifdef STB_IMAGE_STATIC
+#define STBIDEF static
+#else
+#define STBIDEF extern
+#endif
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PRIMARY API - works on images of any type
+//
+
+//
+// load image by filename, open file, or memory buffer
+//
+
+typedef struct
+{
+ int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
+ void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
+ int (*eof) (void *user); // returns nonzero if we are at end of file/data
+} stbi_io_callbacks;
+
+////////////////////////////////////
+//
+// 8-bits-per-channel interface
+//
+
+STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+// for stbi_load_from_file, file pointer is left pointing immediately after image
+#endif
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+#endif
+
+#ifdef STBI_WINDOWS_UTF8
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
+#endif
+
+////////////////////////////////////
+//
+// 16-bits-per-channel interface
+//
+
+STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+#endif
+
+////////////////////////////////////
+//
+// float-per-channel interface
+//
+#ifndef STBI_NO_LINEAR
+ STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+ #ifndef STBI_NO_STDIO
+ STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+ #endif
+#endif
+
+#ifndef STBI_NO_HDR
+ STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
+ STBIDEF void stbi_hdr_to_ldr_scale(float scale);
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_LINEAR
+ STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
+ STBIDEF void stbi_ldr_to_hdr_scale(float scale);
+#endif // STBI_NO_LINEAR
+
+// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename);
+STBIDEF int stbi_is_hdr_from_file(FILE *f);
+#endif // STBI_NO_STDIO
+
+
+// get a VERY brief reason for failure
+// on most compilers (and ALL modern mainstream compilers) this is threadsafe
+STBIDEF const char *stbi_failure_reason (void);
+
+// free the loaded image -- this is just free()
+STBIDEF void stbi_image_free (void *retval_from_stbi_load);
+
+// get image dimensions & components without fully decoding
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len);
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit (char const *filename);
+STBIDEF int stbi_is_16_bit_from_file(FILE *f);
+#endif
+
+
+
+// for image formats that explicitly notate that they have premultiplied alpha,
+// we just return the colors as stored in the file. set this flag to force
+// unpremultiplication. results are undefined if the unpremultiply overflow.
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+
+// indicate whether we should process iphone images back to canonical format,
+// or just pass them through "as-is"
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
+
+// flip the image vertically, so the first pixel in the output array is the bottom left
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
+
+// as above, but only applies to images loaded on the thread that calls the function
+// this function is only available if your compiler supports thread-local variables;
+// calling it will fail to link if your compiler doesn't
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
+
+// ZLIB client - used by PNG, available for other purposes
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
+STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+//
+//
+//// end header file /////////////////////////////////////////////////////
+#endif // STBI_INCLUDE_STB_IMAGE_H
+
+#ifdef STB_IMAGE_IMPLEMENTATION
+
+#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
+ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
+ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
+ || defined(STBI_ONLY_ZLIB)
+ #ifndef STBI_ONLY_JPEG
+ #define STBI_NO_JPEG
+ #endif
+ #ifndef STBI_ONLY_PNG
+ #define STBI_NO_PNG
+ #endif
+ #ifndef STBI_ONLY_BMP
+ #define STBI_NO_BMP
+ #endif
+ #ifndef STBI_ONLY_PSD
+ #define STBI_NO_PSD
+ #endif
+ #ifndef STBI_ONLY_TGA
+ #define STBI_NO_TGA
+ #endif
+ #ifndef STBI_ONLY_GIF
+ #define STBI_NO_GIF
+ #endif
+ #ifndef STBI_ONLY_HDR
+ #define STBI_NO_HDR
+ #endif
+ #ifndef STBI_ONLY_PIC
+ #define STBI_NO_PIC
+ #endif
+ #ifndef STBI_ONLY_PNM
+ #define STBI_NO_PNM
+ #endif
+#endif
+
+#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
+#define STBI_NO_ZLIB
+#endif
+
+
+#include <stdarg.h>
+#include <stddef.h> // ptrdiff_t on osx
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
+#include <math.h> // ldexp, pow
+#endif
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif
+
+#ifndef STBI_ASSERT
+#include <assert.h>
+#define STBI_ASSERT(x) assert(x)
+#endif
+
+#ifdef __cplusplus
+#define STBI_EXTERN extern "C"
+#else
+#define STBI_EXTERN extern
+#endif
+
+
+#ifndef _MSC_VER
+ #ifdef __cplusplus
+ #define stbi_inline inline
+ #else
+ #define stbi_inline
+ #endif
+#else
+ #define stbi_inline __forceinline
+#endif
+
+#ifndef STBI_NO_THREAD_LOCALS
+ #if defined(__cplusplus) && __cplusplus >= 201103L
+ #define STBI_THREAD_LOCAL thread_local
+ #elif defined(__GNUC__) && __GNUC__ < 5
+ #define STBI_THREAD_LOCAL __thread
+ #elif defined(_MSC_VER)
+ #define STBI_THREAD_LOCAL __declspec(thread)
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
+ #define STBI_THREAD_LOCAL _Thread_local
+ #endif
+
+ #ifndef STBI_THREAD_LOCAL
+ #if defined(__GNUC__)
+ #define STBI_THREAD_LOCAL __thread
+ #endif
+ #endif
+#endif
+
+#if defined(_MSC_VER) || defined(__SYMBIAN32__)
+typedef unsigned short stbi__uint16;
+typedef signed short stbi__int16;
+typedef unsigned int stbi__uint32;
+typedef signed int stbi__int32;
+#else
+#include <stdint.h>
+typedef uint16_t stbi__uint16;
+typedef int16_t stbi__int16;
+typedef uint32_t stbi__uint32;
+typedef int32_t stbi__int32;
+#endif
+
+// should produce compiler error if size is wrong
+typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
+
+#ifdef _MSC_VER
+#define STBI_NOTUSED(v) (void)(v)
+#else
+#define STBI_NOTUSED(v) (void)sizeof(v)
+#endif
+
+#ifdef _MSC_VER
+#define STBI_HAS_LROTL
+#endif
+
+#ifdef STBI_HAS_LROTL
+ #define stbi_lrot(x,y) _lrotl(x,y)
+#else
+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31)))
+#endif
+
+#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
+// ok
+#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
+// ok
+#else
+#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
+#endif
+
+#ifndef STBI_MALLOC
+#define STBI_MALLOC(sz) malloc(sz)
+#define STBI_REALLOC(p,newsz) realloc(p,newsz)
+#define STBI_FREE(p) free(p)
+#endif
+
+#ifndef STBI_REALLOC_SIZED
+#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)
+#endif
+
+// x86/x64 detection
+#if defined(__x86_64__) || defined(_M_X64)
+#define STBI__X64_TARGET
+#elif defined(__i386) || defined(_M_IX86)
+#define STBI__X86_TARGET
+#endif
+
+#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
+// gcc doesn't support sse2 intrinsics unless you compile with -msse2,
+// which in turn means it gets to use SSE2 everywhere. This is unfortunate,
+// but previous attempts to provide the SSE2 functions with runtime
+// detection caused numerous issues. The way architecture extensions are
+// exposed in GCC/Clang is, sadly, not really suited for one-file libs.
+// New behavior: if compiled with -msse2, we use SSE2 without any
+// detection; if not, we don't use it at all.
+#define STBI_NO_SIMD
+#endif
+
+#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
+// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
+//
+// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
+// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
+// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
+// simultaneously enabling "-mstackrealign".
+//
+// See https://github.com/nothings/stb/issues/81 for more information.
+//
+// So default to no SSE2 on 32-bit MinGW. If you've read this far and added
+// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
+#define STBI_NO_SIMD
+#endif
+
+#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
+#define STBI_SSE2
+#include <emmintrin.h>
+
+#ifdef _MSC_VER
+
+#if _MSC_VER >= 1400 // not VC6
+#include <intrin.h> // __cpuid
+static int stbi__cpuid3(void)
+{
+ int info[4];
+ __cpuid(info,1);
+ return info[3];
+}
+#else
+static int stbi__cpuid3(void)
+{
+ int res;
+ __asm {
+ mov eax,1
+ cpuid
+ mov res,edx
+ }
+ return res;
+}
+#endif
+
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ int info3 = stbi__cpuid3();
+ return ((info3 >> 26) & 1) != 0;
+}
+#endif
+
+#else // assume GCC-style if not VC++
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ // If we're even attempting to compile this on GCC/Clang, that means
+ // -msse2 is on, which means the compiler is allowed to use SSE2
+ // instructions at will, and so are we.
+ return 1;
+}
+#endif
+
+#endif
+#endif
+
+// ARM NEON
+#if defined(STBI_NO_SIMD) && defined(STBI_NEON)
+#undef STBI_NEON
+#endif
+
+#ifdef STBI_NEON
+#include <arm_neon.h>
+#ifdef _MSC_VER
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+#else
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+#endif
+#endif
+
+#ifndef STBI_SIMD_ALIGN
+#define STBI_SIMD_ALIGN(type, name) type name
+#endif
+
+#ifndef STBI_MAX_DIMENSIONS
+#define STBI_MAX_DIMENSIONS (1 << 24)
+#endif
+
+///////////////////////////////////////////////
+//
+// stbi__context struct and start_xxx functions
+
+// stbi__context structure is our basic context used by all images, so it
+// contains all the IO context, plus some basic image information
+typedef struct
+{
+ stbi__uint32 img_x, img_y;
+ int img_n, img_out_n;
+
+ stbi_io_callbacks io;
+ void *io_user_data;
+
+ int read_from_callbacks;
+ int buflen;
+ stbi_uc buffer_start[128];
+ int callback_already_read;
+
+ stbi_uc *img_buffer, *img_buffer_end;
+ stbi_uc *img_buffer_original, *img_buffer_original_end;
+} stbi__context;
+
+
+static void stbi__refill_buffer(stbi__context *s);
+
+// initialize a memory-decode context
+static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
+{
+ s->io.read = NULL;
+ s->read_from_callbacks = 0;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
+ s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
+}
+
+// initialize a callback-based context
+static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
+{
+ s->io = *c;
+ s->io_user_data = user;
+ s->buflen = sizeof(s->buffer_start);
+ s->read_from_callbacks = 1;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = s->buffer_start;
+ stbi__refill_buffer(s);
+ s->img_buffer_original_end = s->img_buffer_end;
+}
+
+#ifndef STBI_NO_STDIO
+
+static int stbi__stdio_read(void *user, char *data, int size)
+{
+ return (int) fread(data,1,size,(FILE*) user);
+}
+
+static void stbi__stdio_skip(void *user, int n)
+{
+ int ch;
+ fseek((FILE*) user, n, SEEK_CUR);
+ ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */
+ if (ch != EOF) {
+ ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */
+ }
+}
+
+static int stbi__stdio_eof(void *user)
+{
+ return feof((FILE*) user) || ferror((FILE *) user);
+}
+
+static stbi_io_callbacks stbi__stdio_callbacks =
+{
+ stbi__stdio_read,
+ stbi__stdio_skip,
+ stbi__stdio_eof,
+};
+
+static void stbi__start_file(stbi__context *s, FILE *f)
+{
+ stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
+}
+
+//static void stop_file(stbi__context *s) { }
+
+#endif // !STBI_NO_STDIO
+
+static void stbi__rewind(stbi__context *s)
+{
+ // conceptually rewind SHOULD rewind to the beginning of the stream,
+ // but we just rewind to the beginning of the initial buffer, because
+ // we only use it after doing 'test', which only ever looks at at most 92 bytes
+ s->img_buffer = s->img_buffer_original;
+ s->img_buffer_end = s->img_buffer_original_end;
+}
+
+enum
+{
+ STBI_ORDER_RGB,
+ STBI_ORDER_BGR
+};
+
+typedef struct
+{
+ int bits_per_channel;
+ int num_channels;
+ int channel_order;
+} stbi__result_info;
+
+#ifndef STBI_NO_JPEG
+static int stbi__jpeg_test(stbi__context *s);
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNG
+static int stbi__png_test(stbi__context *s);
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__png_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test(stbi__context *s);
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_TGA
+static int stbi__tga_test(stbi__context *s);
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s);
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc);
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__psd_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test(stbi__context *s);
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_test(stbi__context *s);
+static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_GIF
+static int stbi__gif_test(stbi__context *s);
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNM
+static int stbi__pnm_test(stbi__context *s);
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__pnm_is16(stbi__context *s);
+#endif
+
+static
+#ifdef STBI_THREAD_LOCAL
+STBI_THREAD_LOCAL
+#endif
+const char *stbi__g_failure_reason;
+
+STBIDEF const char *stbi_failure_reason(void)
+{
+ return stbi__g_failure_reason;
+}
+
+#ifndef STBI_NO_FAILURE_STRINGS
+static int stbi__err(const char *str)
+{
+ stbi__g_failure_reason = str;
+ return 0;
+}
+#endif
+
+static void *stbi__malloc(size_t size)
+{
+ return STBI_MALLOC(size);
+}
+
+// stb_image uses ints pervasively, including for offset calculations.
+// therefore the largest decoded image size we can support with the
+// current code, even on 64-bit targets, is INT_MAX. this is not a
+// significant limitation for the intended use case.
+//
+// we do, however, need to make sure our size calculations don't
+// overflow. hence a few helper functions for size calculations that
+// multiply integers together, making sure that they're non-negative
+// and no overflow occurs.
+
+// return 1 if the sum is valid, 0 on overflow.
+// negative terms are considered invalid.
+static int stbi__addsizes_valid(int a, int b)
+{
+ if (b < 0) return 0;
+ // now 0 <= b <= INT_MAX, hence also
+ // 0 <= INT_MAX - b <= INTMAX.
+ // And "a + b <= INT_MAX" (which might overflow) is the
+ // same as a <= INT_MAX - b (no overflow)
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product is valid, 0 on overflow.
+// negative factors are considered invalid.
+static int stbi__mul2sizes_valid(int a, int b)
+{
+ if (a < 0 || b < 0) return 0;
+ if (b == 0) return 1; // mul-by-0 is always safe
+ // portable way to check for no overflows in a*b
+ return a <= INT_MAX/b;
+}
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad2sizes_valid(int a, int b, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);
+}
+#endif
+
+// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad3sizes_valid(int a, int b, int c, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__addsizes_valid(a*b*c, add);
+}
+
+// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);
+}
+#endif
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// mallocs with size overflow checking
+static void *stbi__malloc_mad2(int a, int b, int add)
+{
+ if (!stbi__mad2sizes_valid(a, b, add)) return NULL;
+ return stbi__malloc(a*b + add);
+}
+#endif
+
+static void *stbi__malloc_mad3(int a, int b, int c, int add)
+{
+ if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;
+ return stbi__malloc(a*b*c + add);
+}
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)
+{
+ if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;
+ return stbi__malloc(a*b*c*d + add);
+}
+#endif
+
+// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.
+static int stbi__addints_valid(int a, int b)
+{
+ if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow
+ if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product of two ints fits in a signed short, 0 on overflow.
+static int stbi__mul2shorts_valid(int a, int b)
+{
+ if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow
+ if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid
+ if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN
+ return a >= SHRT_MIN / b;
+}
+
+// stbi__err - error
+// stbi__errpf - error returning pointer to float
+// stbi__errpuc - error returning pointer to unsigned char
+
+#ifdef STBI_NO_FAILURE_STRINGS
+ #define stbi__err(x,y) 0
+#elif defined(STBI_FAILURE_USERMSG)
+ #define stbi__err(x,y) stbi__err(y)
+#else
+ #define stbi__err(x,y) stbi__err(x)
+#endif
+
+#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))
+#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))
+
+STBIDEF void stbi_image_free(void *retval_from_stbi_load)
+{
+ STBI_FREE(retval_from_stbi_load);
+}
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
+#endif
+
+#ifndef STBI_NO_HDR
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
+#endif
+
+static int stbi__vertically_flip_on_load_global = 0;
+
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_global = flag_true_if_should_flip;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global
+#else
+static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;
+
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
+ stbi__vertically_flip_on_load_set = 1;
+}
+
+#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \
+ ? stbi__vertically_flip_on_load_local \
+ : stbi__vertically_flip_on_load_global)
+#endif // STBI_THREAD_LOCAL
+
+static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields
+ ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed
+ ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
+ ri->num_channels = 0;
+
+ // test the formats with a very explicit header first (at least a FOURCC
+ // or distinctive magic number first)
+ #ifndef STBI_NO_PNG
+ if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc);
+ #else
+ STBI_NOTUSED(bpc);
+ #endif
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ // then the formats that can end up attempting to load with just 1 or 2
+ // bytes matching expectations; these are prone to false positives, so
+ // try them later
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri);
+ return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
+ }
+ #endif
+
+ #ifndef STBI_NO_TGA
+ // test tga last because it's a crappy test!
+ if (stbi__tga_test(s))
+ return stbi__tga_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi_uc *reduced;
+
+ reduced = (stbi_uc *) stbi__malloc(img_len);
+ if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling
+
+ STBI_FREE(orig);
+ return reduced;
+}
+
+static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi__uint16 *enlarged;
+
+ enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);
+ if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff
+
+ STBI_FREE(orig);
+ return enlarged;
+}
+
+static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)
+{
+ int row;
+ size_t bytes_per_row = (size_t)w * bytes_per_pixel;
+ stbi_uc temp[2048];
+ stbi_uc *bytes = (stbi_uc *)image;
+
+ for (row = 0; row < (h>>1); row++) {
+ stbi_uc *row0 = bytes + row*bytes_per_row;
+ stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row;
+ // swap row0 with row1
+ size_t bytes_left = bytes_per_row;
+ while (bytes_left) {
+ size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
+ memcpy(temp, row0, bytes_copy);
+ memcpy(row0, row1, bytes_copy);
+ memcpy(row1, temp, bytes_copy);
+ row0 += bytes_copy;
+ row1 += bytes_copy;
+ bytes_left -= bytes_copy;
+ }
+ }
+}
+
+#ifndef STBI_NO_GIF
+static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel)
+{
+ int slice;
+ int slice_size = w * h * bytes_per_pixel;
+
+ stbi_uc *bytes = (stbi_uc *)image;
+ for (slice = 0; slice < z; ++slice) {
+ stbi__vertical_flip(bytes, w, h, bytes_per_pixel);
+ bytes += slice_size;
+ }
+}
+#endif
+
+static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 8) {
+ result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 8;
+ }
+
+ // @TODO: move stbi__convert_format to here
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
+ }
+
+ return (unsigned char *) result;
+}
+
+static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 16) {
+ result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 16;
+ }
+
+ // @TODO: move stbi__convert_format16 to here
+ // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));
+ }
+
+ return (stbi__uint16 *) result;
+}
+
+#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
+static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
+{
+ if (stbi__vertically_flip_on_load && result != NULL) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
+ }
+}
+#endif
+
+#ifndef STBI_NO_STDIO
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
+STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
+#endif
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
+{
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
+}
+#endif
+
+static FILE *stbi__fopen(char const *filename, char const *mode)
+{
+ FILE *f;
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+ wchar_t wMode[64];
+ wchar_t wFilename[1024];
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
+ return 0;
+
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
+ return 0;
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != _wfopen_s(&f, wFilename, wMode))
+ f = 0;
+#else
+ f = _wfopen(wFilename, wMode);
+#endif
+
+#elif defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != fopen_s(&f, filename, mode))
+ f=0;
+#else
+ f = fopen(filename, mode);
+#endif
+ return f;
+}
+
+
+STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ unsigned char *result;
+ if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__uint16 *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ stbi__uint16 *result;
+ if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file_16(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+
+#endif //!STBI_NO_STDIO
+
+STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+
+ result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
+ if (stbi__vertically_flip_on_load) {
+ stbi__vertical_flip_slices( result, *x, *y, *z, *comp );
+ }
+
+ return result;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *data;
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ stbi__result_info ri;
+ float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri);
+ if (hdr_data)
+ stbi__float_postprocess(hdr_data,x,y,comp,req_comp);
+ return hdr_data;
+ }
+ #endif
+ data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);
+ if (data)
+ return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+ return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
+}
+
+STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ float *result;
+ FILE *f = stbi__fopen(filename, "rb");
+ if (!f) return stbi__errpf("can't fopen", "Unable to open file");
+ result = stbi_loadf_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_file(&s,f);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+#endif // !STBI_NO_STDIO
+
+#endif // !STBI_NO_LINEAR
+
+// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
+// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
+// reports false!
+
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(buffer);
+ STBI_NOTUSED(len);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result=0;
+ if (f) {
+ result = stbi_is_hdr_from_file(f);
+ fclose(f);
+ }
+ return result;
+}
+
+STBIDEF int stbi_is_hdr_from_file(FILE *f)
+{
+ #ifndef STBI_NO_HDR
+ long pos = ftell(f);
+ int res;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ res = stbi__hdr_test(&s);
+ fseek(f, pos, SEEK_SET);
+ return res;
+ #else
+ STBI_NOTUSED(f);
+ return 0;
+ #endif
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(clbk);
+ STBI_NOTUSED(user);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_LINEAR
+static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
+
+STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
+STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
+#endif
+
+static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
+
+STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
+STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Common code used by all image loaders
+//
+
+enum
+{
+ STBI__SCAN_load=0,
+ STBI__SCAN_type,
+ STBI__SCAN_header
+};
+
+static void stbi__refill_buffer(stbi__context *s)
+{
+ int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
+ s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);
+ if (n == 0) {
+ // at end of file, treat same as if from memory, but need to handle case
+ // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
+ s->read_from_callbacks = 0;
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start+1;
+ *s->img_buffer = 0;
+ } else {
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start + n;
+ }
+}
+
+stbi_inline static stbi_uc stbi__get8(stbi__context *s)
+{
+ if (s->img_buffer < s->img_buffer_end)
+ return *s->img_buffer++;
+ if (s->read_from_callbacks) {
+ stbi__refill_buffer(s);
+ return *s->img_buffer++;
+ }
+ return 0;
+}
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+stbi_inline static int stbi__at_eof(stbi__context *s)
+{
+ if (s->io.read) {
+ if (!(s->io.eof)(s->io_user_data)) return 0;
+ // if feof() is true, check if buffer = end
+ // special case: we've only got the special 0 character at the end
+ if (s->read_from_callbacks == 0) return 1;
+ }
+
+ return s->img_buffer >= s->img_buffer_end;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)
+// nothing
+#else
+static void stbi__skip(stbi__context *s, int n)
+{
+ if (n == 0) return; // already there!
+ if (n < 0) {
+ s->img_buffer = s->img_buffer_end;
+ return;
+ }
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ s->img_buffer = s->img_buffer_end;
+ (s->io.skip)(s->io_user_data, n - blen);
+ return;
+ }
+ }
+ s->img_buffer += n;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)
+// nothing
+#else
+static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
+{
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ int res, count;
+
+ memcpy(buffer, s->img_buffer, blen);
+
+ count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
+ res = (count == (n-blen));
+ s->img_buffer = s->img_buffer_end;
+ return res;
+ }
+ }
+
+ if (s->img_buffer+n <= s->img_buffer_end) {
+ memcpy(buffer, s->img_buffer, n);
+ s->img_buffer += n;
+ return 1;
+ } else
+ return 0;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static int stbi__get16be(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return (z << 8) + stbi__get8(s);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static stbi__uint32 stbi__get32be(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16be(s);
+ return (z << 16) + stbi__get16be(s);
+}
+#endif
+
+#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
+// nothing
+#else
+static int stbi__get16le(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return z + (stbi__get8(s) << 8);
+}
+#endif
+
+#ifndef STBI_NO_BMP
+static stbi__uint32 stbi__get32le(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16le(s);
+ z += (stbi__uint32)stbi__get16le(s) << 16;
+ return z;
+}
+#endif
+
+#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+//////////////////////////////////////////////////////////////////////////////
+//
+// generic converter from built-in img_n to req_comp
+// individual types do this automatically as much as possible (e.g. jpeg
+// does all cases internally since it needs to colorspace convert anyway,
+// and it never has alpha, so very few cases ). png can automatically
+// interleave an alpha=255 channel, but falls back to this for other cases
+//
+// assume data buffer is malloced, so malloc a new one and free that one
+// only failure mode is malloc failing
+
+static stbi_uc stbi__compute_y(int r, int g, int b)
+{
+ return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ unsigned char *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ unsigned char *src = data + j * x * img_n ;
+ unsigned char *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 stbi__compute_y_16(int r, int g, int b)
+{
+ return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ stbi__uint16 *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ stbi__uint16 *src = data + j * x * img_n ;
+ stbi__uint16 *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
+{
+ int i,k,n;
+ float *output;
+ if (!data) return NULL;
+ output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
+ }
+ }
+ if (n < comp) {
+ for (i=0; i < x*y; ++i) {
+ output[i*comp + n] = data[i*comp + n]/255.0f;
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+#ifndef STBI_NO_HDR
+#define stbi__float2int(x) ((int) (x))
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
+{
+ int i,k,n;
+ stbi_uc *output;
+ if (!data) return NULL;
+ output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ if (k < comp) {
+ float z = data[i*comp+k] * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// "baseline" JPEG/JFIF decoder
+//
+// simple implementation
+// - doesn't support delayed output of y-dimension
+// - simple interface (only one output format: 8-bit interleaved RGB)
+// - doesn't try to recover corrupt jpegs
+// - doesn't allow partial loading, loading multiple at once
+// - still fast on x86 (copying globals into locals doesn't help x86)
+// - allocates lots of intermediate memory (full size of all components)
+// - non-interleaved case requires this anyway
+// - allows good upsampling (see next)
+// high-quality
+// - upsampled channels are bilinearly interpolated, even across blocks
+// - quality integer IDCT derived from IJG's 'slow'
+// performance
+// - fast huffman; reasonable integer IDCT
+// - some SIMD kernels for common paths on targets with SSE2/NEON
+// - uses a lot of intermediate memory, could cache poorly
+
+#ifndef STBI_NO_JPEG
+
+// huffman decoding acceleration
+#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
+
+typedef struct
+{
+ stbi_uc fast[1 << FAST_BITS];
+ // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
+ stbi__uint16 code[256];
+ stbi_uc values[256];
+ stbi_uc size[257];
+ unsigned int maxcode[18];
+ int delta[17]; // old 'firstsymbol' - old 'firstcode'
+} stbi__huffman;
+
+typedef struct
+{
+ stbi__context *s;
+ stbi__huffman huff_dc[4];
+ stbi__huffman huff_ac[4];
+ stbi__uint16 dequant[4][64];
+ stbi__int16 fast_ac[4][1 << FAST_BITS];
+
+// sizes for components, interleaved MCUs
+ int img_h_max, img_v_max;
+ int img_mcu_x, img_mcu_y;
+ int img_mcu_w, img_mcu_h;
+
+// definition of jpeg image component
+ struct
+ {
+ int id;
+ int h,v;
+ int tq;
+ int hd,ha;
+ int dc_pred;
+
+ int x,y,w2,h2;
+ stbi_uc *data;
+ void *raw_data, *raw_coeff;
+ stbi_uc *linebuf;
+ short *coeff; // progressive only
+ int coeff_w, coeff_h; // number of 8x8 coefficient blocks
+ } img_comp[4];
+
+ stbi__uint32 code_buffer; // jpeg entropy-coded buffer
+ int code_bits; // number of valid bits
+ unsigned char marker; // marker seen while filling entropy buffer
+ int nomore; // flag if we saw a marker so must stop
+
+ int progressive;
+ int spec_start;
+ int spec_end;
+ int succ_high;
+ int succ_low;
+ int eob_run;
+ int jfif;
+ int app14_color_transform; // Adobe APP14 tag
+ int rgb;
+
+ int scan_n, order[4];
+ int restart_interval, todo;
+
+// kernels
+ void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);
+ void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);
+ stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);
+} stbi__jpeg;
+
+static int stbi__build_huffman(stbi__huffman *h, int *count)
+{
+ int i,j,k=0;
+ unsigned int code;
+ // build size list for each symbol (from JPEG spec)
+ for (i=0; i < 16; ++i) {
+ for (j=0; j < count[i]; ++j) {
+ h->size[k++] = (stbi_uc) (i+1);
+ if(k >= 257) return stbi__err("bad size list","Corrupt JPEG");
+ }
+ }
+ h->size[k] = 0;
+
+ // compute actual symbols (from jpeg spec)
+ code = 0;
+ k = 0;
+ for(j=1; j <= 16; ++j) {
+ // compute delta to add to code to compute symbol id
+ h->delta[j] = k - code;
+ if (h->size[k] == j) {
+ while (h->size[k] == j)
+ h->code[k++] = (stbi__uint16) (code++);
+ if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG");
+ }
+ // compute largest code + 1 for this size, preshifted as needed later
+ h->maxcode[j] = code << (16-j);
+ code <<= 1;
+ }
+ h->maxcode[j] = 0xffffffff;
+
+ // build non-spec acceleration table; 255 is flag for not-accelerated
+ memset(h->fast, 255, 1 << FAST_BITS);
+ for (i=0; i < k; ++i) {
+ int s = h->size[i];
+ if (s <= FAST_BITS) {
+ int c = h->code[i] << (FAST_BITS-s);
+ int m = 1 << (FAST_BITS-s);
+ for (j=0; j < m; ++j) {
+ h->fast[c+j] = (stbi_uc) i;
+ }
+ }
+ }
+ return 1;
+}
+
+// build a table that decodes both magnitude and value of small ACs in
+// one go.
+static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
+{
+ int i;
+ for (i=0; i < (1 << FAST_BITS); ++i) {
+ stbi_uc fast = h->fast[i];
+ fast_ac[i] = 0;
+ if (fast < 255) {
+ int rs = h->values[fast];
+ int run = (rs >> 4) & 15;
+ int magbits = rs & 15;
+ int len = h->size[fast];
+
+ if (magbits && len + magbits <= FAST_BITS) {
+ // magnitude code followed by receive_extend code
+ int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
+ int m = 1 << (magbits - 1);
+ if (k < m) k += (~0U << magbits) + 1;
+ // if the result is small enough, we can fit it in fast_ac table
+ if (k >= -128 && k <= 127)
+ fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits));
+ }
+ }
+ }
+}
+
+static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
+{
+ do {
+ unsigned int b = j->nomore ? 0 : stbi__get8(j->s);
+ if (b == 0xff) {
+ int c = stbi__get8(j->s);
+ while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes
+ if (c != 0) {
+ j->marker = (unsigned char) c;
+ j->nomore = 1;
+ return;
+ }
+ }
+ j->code_buffer |= b << (24 - j->code_bits);
+ j->code_bits += 8;
+ } while (j->code_bits <= 24);
+}
+
+// (1 << n) - 1
+static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
+
+// decode a jpeg huffman value from the bitstream
+stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
+{
+ unsigned int temp;
+ int c,k;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ // look at the top FAST_BITS and determine what symbol ID it is,
+ // if the code is <= FAST_BITS
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ k = h->fast[c];
+ if (k < 255) {
+ int s = h->size[k];
+ if (s > j->code_bits)
+ return -1;
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ return h->values[k];
+ }
+
+ // naive test is to shift the code_buffer down so k bits are
+ // valid, then test against maxcode. To speed this up, we've
+ // preshifted maxcode left so that it has (16-k) 0s at the
+ // end; in other words, regardless of the number of bits, it
+ // wants to be compared against something shifted to have 16;
+ // that way we don't need to shift inside the loop.
+ temp = j->code_buffer >> 16;
+ for (k=FAST_BITS+1 ; ; ++k)
+ if (temp < h->maxcode[k])
+ break;
+ if (k == 17) {
+ // error! code not found
+ j->code_bits -= 16;
+ return -1;
+ }
+
+ if (k > j->code_bits)
+ return -1;
+
+ // convert the huffman code to the symbol id
+ c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
+ if(c < 0 || c >= 256) // symbol id out of bounds!
+ return -1;
+ STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
+
+ // convert the id to a symbol
+ j->code_bits -= k;
+ j->code_buffer <<= k;
+ return h->values[c];
+}
+
+// bias[n] = (-1<<n) + 1
+static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};
+
+// combined JPEG 'receive' and JPEG 'extend', since baseline
+// always extends everything it receives.
+stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ int sgn;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+
+ sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k + (stbi__jbias[n] & (sgn - 1));
+}
+
+// get some unsigned bits
+stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k;
+}
+
+stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
+{
+ unsigned int k;
+ if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = j->code_buffer;
+ j->code_buffer <<= 1;
+ --j->code_bits;
+ return k & 0x80000000;
+}
+
+// given a value that's at position X in the zigzag stream,
+// where does it appear in the 8x8 matrix coded as row-major?
+static const stbi_uc stbi__jpeg_dezigzag[64+15] =
+{
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ // let corrupt input sample past end
+ 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63
+};
+
+// decode one 64-entry block--
+static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant)
+{
+ int diff,dc,k;
+ int t;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG");
+
+ // 0 all the ac values now so we can do it 32-bits at a time
+ memset(data,0,64*sizeof(data[0]));
+
+ diff = t ? stbi__extend_receive(j, t) : 0;
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * dequant[0]);
+
+ // decode AC components, see JPEG spec
+ k = 1;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * dequant[zig]);
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (rs != 0xf0) break; // end block
+ k += 16;
+ } else {
+ k += r;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);
+ }
+ }
+ } while (k < 64);
+ return 1;
+}
+
+static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)
+{
+ int diff,dc;
+ int t;
+ if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ if (j->succ_high == 0) {
+ // first scan for DC coefficient, must be first
+ memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ diff = t ? stbi__extend_receive(j, t) : 0;
+
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * (1 << j->succ_low));
+ } else {
+ // refinement scan for DC coefficient
+ if (stbi__jpeg_get_bit(j))
+ data[0] += (short) (1 << j->succ_low);
+ }
+ return 1;
+}
+
+// @OPTIMIZE: store non-zigzagged during the decode passes,
+// and only de-zigzag when dequantizing
+static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)
+{
+ int k;
+ if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->succ_high == 0) {
+ int shift = j->succ_low;
+
+ if (j->eob_run) {
+ --j->eob_run;
+ return 1;
+ }
+
+ k = j->spec_start;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * (1 << shift));
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r);
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ --j->eob_run;
+ break;
+ }
+ k += 16;
+ } else {
+ k += r;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));
+ }
+ }
+ } while (k <= j->spec_end);
+ } else {
+ // refinement scan for these AC coefficients
+
+ short bit = (short) (1 << j->succ_low);
+
+ if (j->eob_run) {
+ --j->eob_run;
+ for (k = j->spec_start; k <= j->spec_end; ++k) {
+ short *p = &data[stbi__jpeg_dezigzag[k]];
+ if (*p != 0)
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ }
+ } else {
+ k = j->spec_start;
+ do {
+ int r,s;
+ int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r) - 1;
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ r = 64; // force end of block
+ } else {
+ // r=15 s=0 should write 16 0s, so we just do
+ // a run of 15 0s and then write s (which is 0),
+ // so we don't have to do anything special here
+ }
+ } else {
+ if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
+ // sign bit
+ if (stbi__jpeg_get_bit(j))
+ s = bit;
+ else
+ s = -bit;
+ }
+
+ // advance by r
+ while (k <= j->spec_end) {
+ short *p = &data[stbi__jpeg_dezigzag[k++]];
+ if (*p != 0) {
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ } else {
+ if (r == 0) {
+ *p = (short) s;
+ break;
+ }
+ --r;
+ }
+ }
+ } while (k <= j->spec_end);
+ }
+ }
+ return 1;
+}
+
+// take a -128..127 value and stbi__clamp it and convert to 0..255
+stbi_inline static stbi_uc stbi__clamp(int x)
+{
+ // trick to use a single test to catch both cases
+ if ((unsigned int) x > 255) {
+ if (x < 0) return 0;
+ if (x > 255) return 255;
+ }
+ return (stbi_uc) x;
+}
+
+#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5)))
+#define stbi__fsh(x) ((x) * 4096)
+
+// derived from jidctint -- DCT_ISLOW
+#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
+ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
+ p2 = s2; \
+ p3 = s6; \
+ p1 = (p2+p3) * stbi__f2f(0.5411961f); \
+ t2 = p1 + p3*stbi__f2f(-1.847759065f); \
+ t3 = p1 + p2*stbi__f2f( 0.765366865f); \
+ p2 = s0; \
+ p3 = s4; \
+ t0 = stbi__fsh(p2+p3); \
+ t1 = stbi__fsh(p2-p3); \
+ x0 = t0+t3; \
+ x3 = t0-t3; \
+ x1 = t1+t2; \
+ x2 = t1-t2; \
+ t0 = s7; \
+ t1 = s5; \
+ t2 = s3; \
+ t3 = s1; \
+ p3 = t0+t2; \
+ p4 = t1+t3; \
+ p1 = t0+t3; \
+ p2 = t1+t2; \
+ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
+ t0 = t0*stbi__f2f( 0.298631336f); \
+ t1 = t1*stbi__f2f( 2.053119869f); \
+ t2 = t2*stbi__f2f( 3.072711026f); \
+ t3 = t3*stbi__f2f( 1.501321110f); \
+ p1 = p5 + p1*stbi__f2f(-0.899976223f); \
+ p2 = p5 + p2*stbi__f2f(-2.562915447f); \
+ p3 = p3*stbi__f2f(-1.961570560f); \
+ p4 = p4*stbi__f2f(-0.390180644f); \
+ t3 += p1+p4; \
+ t2 += p2+p3; \
+ t1 += p2+p4; \
+ t0 += p1+p3;
+
+static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
+{
+ int i,val[64],*v=val;
+ stbi_uc *o;
+ short *d = data;
+
+ // columns
+ for (i=0; i < 8; ++i,++d, ++v) {
+ // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
+ if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
+ && d[40]==0 && d[48]==0 && d[56]==0) {
+ // no shortcut 0 seconds
+ // (1|2|3|4|5|6|7)==0 0 seconds
+ // all separate -0.047 seconds
+ // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
+ int dcterm = d[0]*4;
+ v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
+ } else {
+ STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])
+ // constants scaled things up by 1<<12; let's bring them back
+ // down, but keep 2 extra bits of precision
+ x0 += 512; x1 += 512; x2 += 512; x3 += 512;
+ v[ 0] = (x0+t3) >> 10;
+ v[56] = (x0-t3) >> 10;
+ v[ 8] = (x1+t2) >> 10;
+ v[48] = (x1-t2) >> 10;
+ v[16] = (x2+t1) >> 10;
+ v[40] = (x2-t1) >> 10;
+ v[24] = (x3+t0) >> 10;
+ v[32] = (x3-t0) >> 10;
+ }
+ }
+
+ for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
+ // no fast case since the first 1D IDCT spread components out
+ STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
+ // constants scaled things up by 1<<12, plus we had 1<<2 from first
+ // loop, plus horizontal and vertical each scale by sqrt(8) so together
+ // we've got an extra 1<<3, so 1<<17 total we need to remove.
+ // so we want to round that, which means adding 0.5 * 1<<17,
+ // aka 65536. Also, we'll end up with -128 to 127 that we want
+ // to encode as 0..255 by adding 128, so we'll add that before the shift
+ x0 += 65536 + (128<<17);
+ x1 += 65536 + (128<<17);
+ x2 += 65536 + (128<<17);
+ x3 += 65536 + (128<<17);
+ // tried computing the shifts into temps, or'ing the temps to see
+ // if any were out of range, but that was slower
+ o[0] = stbi__clamp((x0+t3) >> 17);
+ o[7] = stbi__clamp((x0-t3) >> 17);
+ o[1] = stbi__clamp((x1+t2) >> 17);
+ o[6] = stbi__clamp((x1-t2) >> 17);
+ o[2] = stbi__clamp((x2+t1) >> 17);
+ o[5] = stbi__clamp((x2-t1) >> 17);
+ o[3] = stbi__clamp((x3+t0) >> 17);
+ o[4] = stbi__clamp((x3-t0) >> 17);
+ }
+}
+
+#ifdef STBI_SSE2
+// sse2 integer IDCT. not the fastest possible implementation but it
+// produces bit-identical results to the generic C version so it's
+// fully "transparent".
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ // This is constructed to match our regular (generic) integer IDCT exactly.
+ __m128i row0, row1, row2, row3, row4, row5, row6, row7;
+ __m128i tmp;
+
+ // dot product constant: even elems=x, odd elems=y
+ #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))
+
+ // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
+ // out(1) = c1[even]*x + c1[odd]*y
+ #define dct_rot(out0,out1, x,y,c0,c1) \
+ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \
+ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \
+ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
+ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
+ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
+ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
+
+ // out = in << 12 (in 16-bit, out 32-bit)
+ #define dct_widen(out, in) \
+ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
+ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
+
+ // wide add
+ #define dct_wadd(out, a, b) \
+ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_add_epi32(a##_h, b##_h)
+
+ // wide sub
+ #define dct_wsub(out, a, b) \
+ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
+
+ // butterfly a/b, add bias, then shift by "s" and pack
+ #define dct_bfly32o(out0, out1, a,b,bias,s) \
+ { \
+ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \
+ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \
+ dct_wadd(sum, abiased, b); \
+ dct_wsub(dif, abiased, b); \
+ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
+ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
+ }
+
+ // 8-bit interleave step (for transposes)
+ #define dct_interleave8(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi8(a, b); \
+ b = _mm_unpackhi_epi8(tmp, b)
+
+ // 16-bit interleave step (for transposes)
+ #define dct_interleave16(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi16(a, b); \
+ b = _mm_unpackhi_epi16(tmp, b)
+
+ #define dct_pass(bias,shift) \
+ { \
+ /* even part */ \
+ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \
+ __m128i sum04 = _mm_add_epi16(row0, row4); \
+ __m128i dif04 = _mm_sub_epi16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \
+ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \
+ __m128i sum17 = _mm_add_epi16(row1, row7); \
+ __m128i sum35 = _mm_add_epi16(row3, row5); \
+ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \
+ dct_wadd(x4, y0o, y4o); \
+ dct_wadd(x5, y1o, y5o); \
+ dct_wadd(x6, y2o, y5o); \
+ dct_wadd(x7, y3o, y4o); \
+ dct_bfly32o(row0,row7, x0,x7,bias,shift); \
+ dct_bfly32o(row1,row6, x1,x6,bias,shift); \
+ dct_bfly32o(row2,row5, x2,x5,bias,shift); \
+ dct_bfly32o(row3,row4, x3,x4,bias,shift); \
+ }
+
+ __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
+ __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));
+ __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
+ __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
+ __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));
+ __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));
+ __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));
+ __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));
+
+ // rounding biases in column/row passes, see stbi__idct_block for explanation.
+ __m128i bias_0 = _mm_set1_epi32(512);
+ __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));
+
+ // load
+ row0 = _mm_load_si128((const __m128i *) (data + 0*8));
+ row1 = _mm_load_si128((const __m128i *) (data + 1*8));
+ row2 = _mm_load_si128((const __m128i *) (data + 2*8));
+ row3 = _mm_load_si128((const __m128i *) (data + 3*8));
+ row4 = _mm_load_si128((const __m128i *) (data + 4*8));
+ row5 = _mm_load_si128((const __m128i *) (data + 5*8));
+ row6 = _mm_load_si128((const __m128i *) (data + 6*8));
+ row7 = _mm_load_si128((const __m128i *) (data + 7*8));
+
+ // column pass
+ dct_pass(bias_0, 10);
+
+ {
+ // 16bit 8x8 transpose pass 1
+ dct_interleave16(row0, row4);
+ dct_interleave16(row1, row5);
+ dct_interleave16(row2, row6);
+ dct_interleave16(row3, row7);
+
+ // transpose pass 2
+ dct_interleave16(row0, row2);
+ dct_interleave16(row1, row3);
+ dct_interleave16(row4, row6);
+ dct_interleave16(row5, row7);
+
+ // transpose pass 3
+ dct_interleave16(row0, row1);
+ dct_interleave16(row2, row3);
+ dct_interleave16(row4, row5);
+ dct_interleave16(row6, row7);
+ }
+
+ // row pass
+ dct_pass(bias_1, 17);
+
+ {
+ // pack
+ __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
+ __m128i p1 = _mm_packus_epi16(row2, row3);
+ __m128i p2 = _mm_packus_epi16(row4, row5);
+ __m128i p3 = _mm_packus_epi16(row6, row7);
+
+ // 8bit 8x8 transpose pass 1
+ dct_interleave8(p0, p2); // a0e0a1e1...
+ dct_interleave8(p1, p3); // c0g0c1g1...
+
+ // transpose pass 2
+ dct_interleave8(p0, p1); // a0c0e0g0...
+ dct_interleave8(p2, p3); // b0d0f0h0...
+
+ // transpose pass 3
+ dct_interleave8(p0, p2); // a0b0c0d0...
+ dct_interleave8(p1, p3); // a4b4c4d4...
+
+ // store
+ _mm_storel_epi64((__m128i *) out, p0); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p2); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p1); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p3); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));
+ }
+
+#undef dct_const
+#undef dct_rot
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_interleave8
+#undef dct_interleave16
+#undef dct_pass
+}
+
+#endif // STBI_SSE2
+
+#ifdef STBI_NEON
+
+// NEON integer IDCT. should produce bit-identical
+// results to the generic C version.
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
+
+ int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
+ int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
+ int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));
+ int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));
+ int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
+ int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
+ int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
+ int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
+ int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));
+ int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));
+ int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));
+ int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));
+
+#define dct_long_mul(out, inq, coeff) \
+ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
+
+#define dct_long_mac(out, acc, inq, coeff) \
+ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
+
+#define dct_widen(out, inq) \
+ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
+ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
+
+// wide add
+#define dct_wadd(out, a, b) \
+ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
+
+// wide sub
+#define dct_wsub(out, a, b) \
+ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
+
+// butterfly a/b, then shift using "shiftop" by "s" and pack
+#define dct_bfly32o(out0,out1, a,b,shiftop,s) \
+ { \
+ dct_wadd(sum, a, b); \
+ dct_wsub(dif, a, b); \
+ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
+ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
+ }
+
+#define dct_pass(shiftop, shift) \
+ { \
+ /* even part */ \
+ int16x8_t sum26 = vaddq_s16(row2, row6); \
+ dct_long_mul(p1e, sum26, rot0_0); \
+ dct_long_mac(t2e, p1e, row6, rot0_1); \
+ dct_long_mac(t3e, p1e, row2, rot0_2); \
+ int16x8_t sum04 = vaddq_s16(row0, row4); \
+ int16x8_t dif04 = vsubq_s16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ int16x8_t sum15 = vaddq_s16(row1, row5); \
+ int16x8_t sum17 = vaddq_s16(row1, row7); \
+ int16x8_t sum35 = vaddq_s16(row3, row5); \
+ int16x8_t sum37 = vaddq_s16(row3, row7); \
+ int16x8_t sumodd = vaddq_s16(sum17, sum35); \
+ dct_long_mul(p5o, sumodd, rot1_0); \
+ dct_long_mac(p1o, p5o, sum17, rot1_1); \
+ dct_long_mac(p2o, p5o, sum35, rot1_2); \
+ dct_long_mul(p3o, sum37, rot2_0); \
+ dct_long_mul(p4o, sum15, rot2_1); \
+ dct_wadd(sump13o, p1o, p3o); \
+ dct_wadd(sump24o, p2o, p4o); \
+ dct_wadd(sump23o, p2o, p3o); \
+ dct_wadd(sump14o, p1o, p4o); \
+ dct_long_mac(x4, sump13o, row7, rot3_0); \
+ dct_long_mac(x5, sump24o, row5, rot3_1); \
+ dct_long_mac(x6, sump23o, row3, rot3_2); \
+ dct_long_mac(x7, sump14o, row1, rot3_3); \
+ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \
+ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \
+ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \
+ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \
+ }
+
+ // load
+ row0 = vld1q_s16(data + 0*8);
+ row1 = vld1q_s16(data + 1*8);
+ row2 = vld1q_s16(data + 2*8);
+ row3 = vld1q_s16(data + 3*8);
+ row4 = vld1q_s16(data + 4*8);
+ row5 = vld1q_s16(data + 5*8);
+ row6 = vld1q_s16(data + 6*8);
+ row7 = vld1q_s16(data + 7*8);
+
+ // add DC bias
+ row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
+
+ // column pass
+ dct_pass(vrshrn_n_s32, 10);
+
+ // 16bit 8x8 transpose
+ {
+// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
+// whether compilers actually get this is another story, sadly.
+#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }
+#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }
+
+ // pass 1
+ dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
+ dct_trn16(row2, row3);
+ dct_trn16(row4, row5);
+ dct_trn16(row6, row7);
+
+ // pass 2
+ dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
+ dct_trn32(row1, row3);
+ dct_trn32(row4, row6);
+ dct_trn32(row5, row7);
+
+ // pass 3
+ dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
+ dct_trn64(row1, row5);
+ dct_trn64(row2, row6);
+ dct_trn64(row3, row7);
+
+#undef dct_trn16
+#undef dct_trn32
+#undef dct_trn64
+ }
+
+ // row pass
+ // vrshrn_n_s32 only supports shifts up to 16, we need
+ // 17. so do a non-rounding shift of 16 first then follow
+ // up with a rounding shift by 1.
+ dct_pass(vshrn_n_s32, 16);
+
+ {
+ // pack and round
+ uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
+ uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
+ uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
+ uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
+ uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
+ uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
+ uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
+ uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
+
+ // again, these can translate into one instruction, but often don't.
+#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }
+#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }
+
+ // sadly can't use interleaved stores here since we only write
+ // 8 bytes to each scan line!
+
+ // 8x8 8-bit transpose pass 1
+ dct_trn8_8(p0, p1);
+ dct_trn8_8(p2, p3);
+ dct_trn8_8(p4, p5);
+ dct_trn8_8(p6, p7);
+
+ // pass 2
+ dct_trn8_16(p0, p2);
+ dct_trn8_16(p1, p3);
+ dct_trn8_16(p4, p6);
+ dct_trn8_16(p5, p7);
+
+ // pass 3
+ dct_trn8_32(p0, p4);
+ dct_trn8_32(p1, p5);
+ dct_trn8_32(p2, p6);
+ dct_trn8_32(p3, p7);
+
+ // store
+ vst1_u8(out, p0); out += out_stride;
+ vst1_u8(out, p1); out += out_stride;
+ vst1_u8(out, p2); out += out_stride;
+ vst1_u8(out, p3); out += out_stride;
+ vst1_u8(out, p4); out += out_stride;
+ vst1_u8(out, p5); out += out_stride;
+ vst1_u8(out, p6); out += out_stride;
+ vst1_u8(out, p7);
+
+#undef dct_trn8_8
+#undef dct_trn8_16
+#undef dct_trn8_32
+ }
+
+#undef dct_long_mul
+#undef dct_long_mac
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_pass
+}
+
+#endif // STBI_NEON
+
+#define STBI__MARKER_none 0xff
+// if there's a pending marker from the entropy stream, return that
+// otherwise, fetch from the stream and get a marker. if there's no
+// marker, return 0xff, which is never a valid marker value
+static stbi_uc stbi__get_marker(stbi__jpeg *j)
+{
+ stbi_uc x;
+ if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
+ x = stbi__get8(j->s);
+ if (x != 0xff) return STBI__MARKER_none;
+ while (x == 0xff)
+ x = stbi__get8(j->s); // consume repeated 0xff fill bytes
+ return x;
+}
+
+// in each scan, we'll have scan_n components, and the order
+// of the components is specified by order[]
+#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
+
+// after a restart interval, stbi__jpeg_reset the entropy decoder and
+// the dc prediction
+static void stbi__jpeg_reset(stbi__jpeg *j)
+{
+ j->code_bits = 0;
+ j->code_buffer = 0;
+ j->nomore = 0;
+ j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0;
+ j->marker = STBI__MARKER_none;
+ j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
+ j->eob_run = 0;
+ // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
+ // since we don't even allow 1<<30 pixels
+}
+
+static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
+{
+ stbi__jpeg_reset(z);
+ if (!z->progressive) {
+ if (z->scan_n == 1) {
+ int i,j;
+ STBI_SIMD_ALIGN(short, data[64]);
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ // if it's NOT a restart, then just bail, so we get corrupt data
+ // rather than no data
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ STBI_SIMD_ALIGN(short, data[64]);
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x)*8;
+ int y2 = (j*z->img_comp[n].v + y)*8;
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ } else {
+ if (z->scan_n == 1) {
+ int i,j;
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ if (z->spec_start == 0) {
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ } else {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
+ return 0;
+ }
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x);
+ int y2 = (j*z->img_comp[n].v + y);
+ short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ }
+}
+
+static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant)
+{
+ int i;
+ for (i=0; i < 64; ++i)
+ data[i] *= dequant[i];
+}
+
+static void stbi__jpeg_finish(stbi__jpeg *z)
+{
+ if (z->progressive) {
+ // dequantize and idct the data
+ int i,j,n;
+ for (n=0; n < z->s->img_n; ++n) {
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ }
+}
+
+static int stbi__process_marker(stbi__jpeg *z, int m)
+{
+ int L;
+ switch (m) {
+ case STBI__MARKER_none: // no marker found
+ return stbi__err("expected marker","Corrupt JPEG");
+
+ case 0xDD: // DRI - specify restart interval
+ if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
+ z->restart_interval = stbi__get16be(z->s);
+ return 1;
+
+ case 0xDB: // DQT - define quantization table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ int q = stbi__get8(z->s);
+ int p = q >> 4, sixteen = (p != 0);
+ int t = q & 15,i;
+ if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG");
+ if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
+
+ for (i=0; i < 64; ++i)
+ z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
+ L -= (sixteen ? 129 : 65);
+ }
+ return L==0;
+
+ case 0xC4: // DHT - define huffman table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ stbi_uc *v;
+ int sizes[16],i,n=0;
+ int q = stbi__get8(z->s);
+ int tc = q >> 4;
+ int th = q & 15;
+ if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
+ for (i=0; i < 16; ++i) {
+ sizes[i] = stbi__get8(z->s);
+ n += sizes[i];
+ }
+ if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values!
+ L -= 17;
+ if (tc == 0) {
+ if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
+ v = z->huff_dc[th].values;
+ } else {
+ if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
+ v = z->huff_ac[th].values;
+ }
+ for (i=0; i < n; ++i)
+ v[i] = stbi__get8(z->s);
+ if (tc != 0)
+ stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
+ L -= n;
+ }
+ return L==0;
+ }
+
+ // check for comment block or APP blocks
+ if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
+ L = stbi__get16be(z->s);
+ if (L < 2) {
+ if (m == 0xFE)
+ return stbi__err("bad COM len","Corrupt JPEG");
+ else
+ return stbi__err("bad APP len","Corrupt JPEG");
+ }
+ L -= 2;
+
+ if (m == 0xE0 && L >= 5) { // JFIF APP0 segment
+ static const unsigned char tag[5] = {'J','F','I','F','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 5; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 5;
+ if (ok)
+ z->jfif = 1;
+ } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment
+ static const unsigned char tag[6] = {'A','d','o','b','e','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 6; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 6;
+ if (ok) {
+ stbi__get8(z->s); // version
+ stbi__get16be(z->s); // flags0
+ stbi__get16be(z->s); // flags1
+ z->app14_color_transform = stbi__get8(z->s); // color transform
+ L -= 6;
+ }
+ }
+
+ stbi__skip(z->s, L);
+ return 1;
+ }
+
+ return stbi__err("unknown marker","Corrupt JPEG");
+}
+
+// after we see SOS
+static int stbi__process_scan_header(stbi__jpeg *z)
+{
+ int i;
+ int Ls = stbi__get16be(z->s);
+ z->scan_n = stbi__get8(z->s);
+ if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG");
+ if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG");
+ for (i=0; i < z->scan_n; ++i) {
+ int id = stbi__get8(z->s), which;
+ int q = stbi__get8(z->s);
+ for (which = 0; which < z->s->img_n; ++which)
+ if (z->img_comp[which].id == id)
+ break;
+ if (which == z->s->img_n) return 0; // no match
+ z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
+ z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
+ z->order[i] = which;
+ }
+
+ {
+ int aa;
+ z->spec_start = stbi__get8(z->s);
+ z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
+ aa = stbi__get8(z->s);
+ z->succ_high = (aa >> 4);
+ z->succ_low = (aa & 15);
+ if (z->progressive) {
+ if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
+ return stbi__err("bad SOS", "Corrupt JPEG");
+ } else {
+ if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ z->spec_end = 63;
+ }
+ }
+
+ return 1;
+}
+
+static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why)
+{
+ int i;
+ for (i=0; i < ncomp; ++i) {
+ if (z->img_comp[i].raw_data) {
+ STBI_FREE(z->img_comp[i].raw_data);
+ z->img_comp[i].raw_data = NULL;
+ z->img_comp[i].data = NULL;
+ }
+ if (z->img_comp[i].raw_coeff) {
+ STBI_FREE(z->img_comp[i].raw_coeff);
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].coeff = 0;
+ }
+ if (z->img_comp[i].linebuf) {
+ STBI_FREE(z->img_comp[i].linebuf);
+ z->img_comp[i].linebuf = NULL;
+ }
+ }
+ return why;
+}
+
+static int stbi__process_frame_header(stbi__jpeg *z, int scan)
+{
+ stbi__context *s = z->s;
+ int Lf,p,i,q, h_max=1,v_max=1,c;
+ Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
+ p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
+ s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
+ s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ c = stbi__get8(s);
+ if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG");
+ s->img_n = c;
+ for (i=0; i < c; ++i) {
+ z->img_comp[i].data = NULL;
+ z->img_comp[i].linebuf = NULL;
+ }
+
+ if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
+
+ z->rgb = 0;
+ for (i=0; i < s->img_n; ++i) {
+ static const unsigned char rgb[3] = { 'R', 'G', 'B' };
+ z->img_comp[i].id = stbi__get8(s);
+ if (s->img_n == 3 && z->img_comp[i].id == rgb[i])
+ ++z->rgb;
+ q = stbi__get8(s);
+ z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
+ z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
+ z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
+ }
+
+ if (scan != STBI__SCAN_load) return 1;
+
+ if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode");
+
+ for (i=0; i < s->img_n; ++i) {
+ if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
+ if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
+ }
+
+ // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
+ // and I've never seen a non-corrupted JPEG file actually use them
+ for (i=0; i < s->img_n; ++i) {
+ if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG");
+ if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG");
+ }
+
+ // compute interleaved mcu info
+ z->img_h_max = h_max;
+ z->img_v_max = v_max;
+ z->img_mcu_w = h_max * 8;
+ z->img_mcu_h = v_max * 8;
+ // these sizes can't be more than 17 bits
+ z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
+ z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
+
+ for (i=0; i < s->img_n; ++i) {
+ // number of effective pixels (e.g. for non-interleaved MCU)
+ z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
+ z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
+ // to simplify generation, we'll allocate enough memory to decode
+ // the bogus oversized data from using interleaved MCUs and their
+ // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
+ // discard the extra data until colorspace conversion
+ //
+ // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)
+ // so these muls can't overflow with 32-bit ints (which we require)
+ z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
+ z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
+ z->img_comp[i].coeff = 0;
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].linebuf = NULL;
+ z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
+ if (z->img_comp[i].raw_data == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ // align blocks for idct using mmx/sse
+ z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
+ if (z->progressive) {
+ // w2, h2 are multiples of 8 (see above)
+ z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
+ z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
+ z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
+ if (z->img_comp[i].raw_coeff == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
+ }
+ }
+
+ return 1;
+}
+
+// use comparisons since in some cases we handle more than one case (e.g. SOF)
+#define stbi__DNL(x) ((x) == 0xdc)
+#define stbi__SOI(x) ((x) == 0xd8)
+#define stbi__EOI(x) ((x) == 0xd9)
+#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
+#define stbi__SOS(x) ((x) == 0xda)
+
+#define stbi__SOF_progressive(x) ((x) == 0xc2)
+
+static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
+{
+ int m;
+ z->jfif = 0;
+ z->app14_color_transform = -1; // valid values are 0,1,2
+ z->marker = STBI__MARKER_none; // initialize cached marker to empty
+ m = stbi__get_marker(z);
+ if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG");
+ if (scan == STBI__SCAN_type) return 1;
+ m = stbi__get_marker(z);
+ while (!stbi__SOF(m)) {
+ if (!stbi__process_marker(z,m)) return 0;
+ m = stbi__get_marker(z);
+ while (m == STBI__MARKER_none) {
+ // some files have extra padding after their blocks, so ok, we'll scan
+ if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
+ m = stbi__get_marker(z);
+ }
+ }
+ z->progressive = stbi__SOF_progressive(m);
+ if (!stbi__process_frame_header(z, scan)) return 0;
+ return 1;
+}
+
+static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j)
+{
+ // some JPEGs have junk at end, skip over it but if we find what looks
+ // like a valid marker, resume there
+ while (!stbi__at_eof(j->s)) {
+ stbi_uc x = stbi__get8(j->s);
+ while (x == 0xff) { // might be a marker
+ if (stbi__at_eof(j->s)) return STBI__MARKER_none;
+ x = stbi__get8(j->s);
+ if (x != 0x00 && x != 0xff) {
+ // not a stuffed zero or lead-in to another marker, looks
+ // like an actual marker, return it
+ return x;
+ }
+ // stuffed zero has x=0 now which ends the loop, meaning we go
+ // back to regular scan loop.
+ // repeated 0xff keeps trying to read the next byte of the marker.
+ }
+ }
+ return STBI__MARKER_none;
+}
+
+// decode image to YCbCr format
+static int stbi__decode_jpeg_image(stbi__jpeg *j)
+{
+ int m;
+ for (m = 0; m < 4; m++) {
+ j->img_comp[m].raw_data = NULL;
+ j->img_comp[m].raw_coeff = NULL;
+ }
+ j->restart_interval = 0;
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
+ m = stbi__get_marker(j);
+ while (!stbi__EOI(m)) {
+ if (stbi__SOS(m)) {
+ if (!stbi__process_scan_header(j)) return 0;
+ if (!stbi__parse_entropy_coded_data(j)) return 0;
+ if (j->marker == STBI__MARKER_none ) {
+ j->marker = stbi__skip_jpeg_junk_at_end(j);
+ // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
+ }
+ m = stbi__get_marker(j);
+ if (STBI__RESTART(m))
+ m = stbi__get_marker(j);
+ } else if (stbi__DNL(m)) {
+ int Ld = stbi__get16be(j->s);
+ stbi__uint32 NL = stbi__get16be(j->s);
+ if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");
+ if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");
+ m = stbi__get_marker(j);
+ } else {
+ if (!stbi__process_marker(j, m)) return 1;
+ m = stbi__get_marker(j);
+ }
+ }
+ if (j->progressive)
+ stbi__jpeg_finish(j);
+ return 1;
+}
+
+// static jfif-centered resampling (across block boundaries)
+
+typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
+ int w, int hs);
+
+#define stbi__div4(x) ((stbi_uc) ((x) >> 2))
+
+static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ STBI_NOTUSED(out);
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(w);
+ STBI_NOTUSED(hs);
+ return in_near;
+}
+
+static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples vertically for every one in input
+ int i;
+ STBI_NOTUSED(hs);
+ for (i=0; i < w; ++i)
+ out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
+ return out;
+}
+
+static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples horizontally for every one in input
+ int i;
+ stbi_uc *input = in_near;
+
+ if (w == 1) {
+ // if only one sample, can't do any interpolation
+ out[0] = out[1] = input[0];
+ return out;
+ }
+
+ out[0] = input[0];
+ out[1] = stbi__div4(input[0]*3 + input[1] + 2);
+ for (i=1; i < w-1; ++i) {
+ int n = 3*input[i]+2;
+ out[i*2+0] = stbi__div4(n+input[i-1]);
+ out[i*2+1] = stbi__div4(n+input[i+1]);
+ }
+ out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
+ out[i*2+1] = input[w-1];
+
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#define stbi__div16(x) ((stbi_uc) ((x) >> 4))
+
+static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i,t0,t1;
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ out[0] = stbi__div4(t1+2);
+ for (i=1; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i=0,t0,t1;
+
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ // process groups of 8 pixels for as long as we can.
+ // note we can't handle the last pixel in a row in this loop
+ // because we need to handle the filter boundary conditions.
+ for (; i < ((w-1) & ~7); i += 8) {
+#if defined(STBI_SSE2)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ __m128i zero = _mm_setzero_si128();
+ __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i));
+ __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));
+ __m128i farw = _mm_unpacklo_epi8(farb, zero);
+ __m128i nearw = _mm_unpacklo_epi8(nearb, zero);
+ __m128i diff = _mm_sub_epi16(farw, nearw);
+ __m128i nears = _mm_slli_epi16(nearw, 2);
+ __m128i curr = _mm_add_epi16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ __m128i prv0 = _mm_slli_si128(curr, 2);
+ __m128i nxt0 = _mm_srli_si128(curr, 2);
+ __m128i prev = _mm_insert_epi16(prv0, t1, 0);
+ __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ __m128i bias = _mm_set1_epi16(8);
+ __m128i curs = _mm_slli_epi16(curr, 2);
+ __m128i prvd = _mm_sub_epi16(prev, curr);
+ __m128i nxtd = _mm_sub_epi16(next, curr);
+ __m128i curb = _mm_add_epi16(curs, bias);
+ __m128i even = _mm_add_epi16(prvd, curb);
+ __m128i odd = _mm_add_epi16(nxtd, curb);
+
+ // interleave even and odd pixels, then undo scaling.
+ __m128i int0 = _mm_unpacklo_epi16(even, odd);
+ __m128i int1 = _mm_unpackhi_epi16(even, odd);
+ __m128i de0 = _mm_srli_epi16(int0, 4);
+ __m128i de1 = _mm_srli_epi16(int1, 4);
+
+ // pack and write output
+ __m128i outv = _mm_packus_epi16(de0, de1);
+ _mm_storeu_si128((__m128i *) (out + i*2), outv);
+#elif defined(STBI_NEON)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ uint8x8_t farb = vld1_u8(in_far + i);
+ uint8x8_t nearb = vld1_u8(in_near + i);
+ int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
+ int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
+ int16x8_t curr = vaddq_s16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ int16x8_t prv0 = vextq_s16(curr, curr, 7);
+ int16x8_t nxt0 = vextq_s16(curr, curr, 1);
+ int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
+ int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ int16x8_t curs = vshlq_n_s16(curr, 2);
+ int16x8_t prvd = vsubq_s16(prev, curr);
+ int16x8_t nxtd = vsubq_s16(next, curr);
+ int16x8_t even = vaddq_s16(curs, prvd);
+ int16x8_t odd = vaddq_s16(curs, nxtd);
+
+ // undo scaling and round, then store with even/odd phases interleaved
+ uint8x8x2_t o;
+ o.val[0] = vqrshrun_n_s16(even, 4);
+ o.val[1] = vqrshrun_n_s16(odd, 4);
+ vst2_u8(out + i*2, o);
+#endif
+
+ // "previous" value for next iter
+ t1 = 3*in_near[i+7] + in_far[i+7];
+ }
+
+ t0 = t1;
+ t1 = 3*in_near[i] + in_far[i];
+ out[i*2] = stbi__div16(3*t1 + t0 + 8);
+
+ for (++i; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+#endif
+
+static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // resample with nearest-neighbor
+ int i,j;
+ STBI_NOTUSED(in_far);
+ for (i=0; i < w; ++i)
+ for (j=0; j < hs; ++j)
+ out[i*hs+j] = in_near[i];
+ return out;
+}
+
+// this is a reduced-precision calculation of YCbCr-to-RGB introduced
+// to make sure the code produces the same results in both SIMD and scalar
+#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
+static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
+{
+ int i;
+ for (i=0; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)
+{
+ int i = 0;
+
+#ifdef STBI_SSE2
+ // step == 3 is pretty ugly on the final interleave, and i'm not convinced
+ // it's useful in practice (you wouldn't use it for textures, for example).
+ // so just accelerate step == 4 case.
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ __m128i signflip = _mm_set1_epi8(-0x80);
+ __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f));
+ __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));
+ __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));
+ __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f));
+ __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
+ __m128i xw = _mm_set1_epi16(255); // alpha channel
+
+ for (; i+7 < count; i += 8) {
+ // load
+ __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));
+ __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));
+ __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));
+ __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
+ __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
+
+ // unpack to short (and left-shift cr, cb by 8)
+ __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
+ __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
+ __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
+
+ // color transform
+ __m128i yws = _mm_srli_epi16(yw, 4);
+ __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
+ __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
+ __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
+ __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
+ __m128i rws = _mm_add_epi16(cr0, yws);
+ __m128i gwt = _mm_add_epi16(cb0, yws);
+ __m128i bws = _mm_add_epi16(yws, cb1);
+ __m128i gws = _mm_add_epi16(gwt, cr1);
+
+ // descale
+ __m128i rw = _mm_srai_epi16(rws, 4);
+ __m128i bw = _mm_srai_epi16(bws, 4);
+ __m128i gw = _mm_srai_epi16(gws, 4);
+
+ // back to byte, set up for transpose
+ __m128i brb = _mm_packus_epi16(rw, bw);
+ __m128i gxb = _mm_packus_epi16(gw, xw);
+
+ // transpose to interleave channels
+ __m128i t0 = _mm_unpacklo_epi8(brb, gxb);
+ __m128i t1 = _mm_unpackhi_epi8(brb, gxb);
+ __m128i o0 = _mm_unpacklo_epi16(t0, t1);
+ __m128i o1 = _mm_unpackhi_epi16(t0, t1);
+
+ // store
+ _mm_storeu_si128((__m128i *) (out + 0), o0);
+ _mm_storeu_si128((__m128i *) (out + 16), o1);
+ out += 32;
+ }
+ }
+#endif
+
+#ifdef STBI_NEON
+ // in this version, step=3 support would be easy to add. but is there demand?
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ uint8x8_t signflip = vdup_n_u8(0x80);
+ int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f));
+ int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));
+ int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));
+ int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f));
+
+ for (; i+7 < count; i += 8) {
+ // load
+ uint8x8_t y_bytes = vld1_u8(y + i);
+ uint8x8_t cr_bytes = vld1_u8(pcr + i);
+ uint8x8_t cb_bytes = vld1_u8(pcb + i);
+ int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
+ int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
+
+ // expand to s16
+ int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
+ int16x8_t crw = vshll_n_s8(cr_biased, 7);
+ int16x8_t cbw = vshll_n_s8(cb_biased, 7);
+
+ // color transform
+ int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
+ int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
+ int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
+ int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
+ int16x8_t rws = vaddq_s16(yws, cr0);
+ int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
+ int16x8_t bws = vaddq_s16(yws, cb1);
+
+ // undo scaling, round, convert to byte
+ uint8x8x4_t o;
+ o.val[0] = vqrshrun_n_s16(rws, 4);
+ o.val[1] = vqrshrun_n_s16(gws, 4);
+ o.val[2] = vqrshrun_n_s16(bws, 4);
+ o.val[3] = vdup_n_u8(255);
+
+ // store, interleaving r/g/b/a
+ vst4_u8(out, o);
+ out += 8*4;
+ }
+ }
+#endif
+
+ for (; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+#endif
+
+// set up the kernels
+static void stbi__setup_jpeg(stbi__jpeg *j)
+{
+ j->idct_block_kernel = stbi__idct_block;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
+
+#ifdef STBI_SSE2
+ if (stbi__sse2_available()) {
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+ }
+#endif
+
+#ifdef STBI_NEON
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+#endif
+}
+
+// clean up the temporary component buffers
+static void stbi__cleanup_jpeg(stbi__jpeg *j)
+{
+ stbi__free_jpeg_components(j, j->s->img_n, 0);
+}
+
+typedef struct
+{
+ resample_row_func resample;
+ stbi_uc *line0,*line1;
+ int hs,vs; // expansion factor in each axis
+ int w_lores; // horizontal pixels pre-expansion
+ int ystep; // how far through vertical expansion we are
+ int ypos; // which pre-expansion row we're on
+} stbi__resample;
+
+// fast 0..255 * 0..255 => 0..255 rounded multiplication
+static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y)
+{
+ unsigned int t = x*y + 128;
+ return (stbi_uc) ((t + (t >>8)) >> 8);
+}
+
+static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
+{
+ int n, decode_n, is_rgb;
+ z->s->img_n = 0; // make stbi__cleanup_jpeg safe
+
+ // validate req_comp
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+
+ // load a jpeg image from whichever source, but leave in YCbCr format
+ if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // determine actual number of components to generate
+ n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;
+
+ is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
+
+ if (z->s->img_n == 3 && n < 3 && !is_rgb)
+ decode_n = 1;
+ else
+ decode_n = z->s->img_n;
+
+ // nothing to do if no components requested; check this now to avoid
+ // accessing uninitialized coutput[0] later
+ if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // resample and color-convert
+ {
+ int k;
+ unsigned int i,j;
+ stbi_uc *output;
+ stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL };
+
+ stbi__resample res_comp[4];
+
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+
+ // allocate line buffer big enough for upsampling off the edges
+ // with upsample factor of 4
+ z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
+ if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ r->hs = z->img_h_max / z->img_comp[k].h;
+ r->vs = z->img_v_max / z->img_comp[k].v;
+ r->ystep = r->vs >> 1;
+ r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
+ r->ypos = 0;
+ r->line0 = r->line1 = z->img_comp[k].data;
+
+ if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
+ else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
+ else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
+ else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
+ else r->resample = stbi__resample_row_generic;
+ }
+
+ // can't error after this so, this is safe
+ output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);
+ if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ // now go ahead and resample
+ for (j=0; j < z->s->img_y; ++j) {
+ stbi_uc *out = output + n * z->s->img_x * j;
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+ int y_bot = r->ystep >= (r->vs >> 1);
+ coutput[k] = r->resample(z->img_comp[k].linebuf,
+ y_bot ? r->line1 : r->line0,
+ y_bot ? r->line0 : r->line1,
+ r->w_lores, r->hs);
+ if (++r->ystep >= r->vs) {
+ r->ystep = 0;
+ r->line0 = r->line1;
+ if (++r->ypos < z->img_comp[k].y)
+ r->line1 += z->img_comp[k].w2;
+ }
+ }
+ if (n >= 3) {
+ stbi_uc *y = coutput[0];
+ if (z->s->img_n == 3) {
+ if (is_rgb) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = y[i];
+ out[1] = coutput[1][i];
+ out[2] = coutput[2][i];
+ out[3] = 255;
+ out += n;
+ }
+ } else {
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else if (z->s->img_n == 4) {
+ if (z->app14_color_transform == 0) { // CMYK
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(coutput[0][i], m);
+ out[1] = stbi__blinn_8x8(coutput[1][i], m);
+ out[2] = stbi__blinn_8x8(coutput[2][i], m);
+ out[3] = 255;
+ out += n;
+ }
+ } else if (z->app14_color_transform == 2) { // YCCK
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(255 - out[0], m);
+ out[1] = stbi__blinn_8x8(255 - out[1], m);
+ out[2] = stbi__blinn_8x8(255 - out[2], m);
+ out += n;
+ }
+ } else { // YCbCr + alpha? Ignore the fourth channel for now
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = out[1] = out[2] = y[i];
+ out[3] = 255; // not used if n==3
+ out += n;
+ }
+ } else {
+ if (is_rgb) {
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i)
+ *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ else {
+ for (i=0; i < z->s->img_x; ++i, out += 2) {
+ out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ out[1] = 255;
+ }
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 0) {
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ stbi_uc r = stbi__blinn_8x8(coutput[0][i], m);
+ stbi_uc g = stbi__blinn_8x8(coutput[1][i], m);
+ stbi_uc b = stbi__blinn_8x8(coutput[2][i], m);
+ out[0] = stbi__compute_y(r, g, b);
+ out[1] = 255;
+ out += n;
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 2) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
+ out[1] = 255;
+ out += n;
+ }
+ } else {
+ stbi_uc *y = coutput[0];
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
+ else
+ for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; }
+ }
+ }
+ }
+ stbi__cleanup_jpeg(z);
+ *out_x = z->s->img_x;
+ *out_y = z->s->img_y;
+ if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output
+ return output;
+ }
+}
+
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ unsigned char* result;
+ stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__errpuc("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ STBI_NOTUSED(ri);
+ j->s = s;
+ stbi__setup_jpeg(j);
+ result = load_jpeg_image(j, x,y,comp,req_comp);
+ STBI_FREE(j);
+ return result;
+}
+
+static int stbi__jpeg_test(stbi__context *s)
+{
+ int r;
+ stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ stbi__setup_jpeg(j);
+ r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
+ stbi__rewind(s);
+ STBI_FREE(j);
+ return r;
+}
+
+static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
+{
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
+ stbi__rewind( j->s );
+ return 0;
+ }
+ if (x) *x = j->s->img_x;
+ if (y) *y = j->s->img_y;
+ if (comp) *comp = j->s->img_n >= 3 ? 3 : 1;
+ return 1;
+}
+
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int result;
+ stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ result = stbi__jpeg_info_raw(j, x, y, comp);
+ STBI_FREE(j);
+ return result;
+}
+#endif
+
+// public domain zlib decode v0.2 Sean Barrett 2006-11-18
+// simple implementation
+// - all input must be provided in an upfront buffer
+// - all output is written to a single output buffer (can malloc/realloc)
+// performance
+// - fast huffman
+
+#ifndef STBI_NO_ZLIB
+
+// fast-way is faster to check than jpeg huffman, but slow way is slower
+#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
+#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
+#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet
+
+// zlib-style huffman encoding
+// (jpegs packs from left, zlib from right, so can't share code)
+typedef struct
+{
+ stbi__uint16 fast[1 << STBI__ZFAST_BITS];
+ stbi__uint16 firstcode[16];
+ int maxcode[17];
+ stbi__uint16 firstsymbol[16];
+ stbi_uc size[STBI__ZNSYMS];
+ stbi__uint16 value[STBI__ZNSYMS];
+} stbi__zhuffman;
+
+stbi_inline static int stbi__bitreverse16(int n)
+{
+ n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
+ n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
+ n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
+ n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
+ return n;
+}
+
+stbi_inline static int stbi__bit_reverse(int v, int bits)
+{
+ STBI_ASSERT(bits <= 16);
+ // to bit reverse n bits, reverse 16 and shift
+ // e.g. 11 bits, bit reverse and shift away 5
+ return stbi__bitreverse16(v) >> (16-bits);
+}
+
+static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num)
+{
+ int i,k=0;
+ int code, next_code[16], sizes[17];
+
+ // DEFLATE spec for generating codes
+ memset(sizes, 0, sizeof(sizes));
+ memset(z->fast, 0, sizeof(z->fast));
+ for (i=0; i < num; ++i)
+ ++sizes[sizelist[i]];
+ sizes[0] = 0;
+ for (i=1; i < 16; ++i)
+ if (sizes[i] > (1 << i))
+ return stbi__err("bad sizes", "Corrupt PNG");
+ code = 0;
+ for (i=1; i < 16; ++i) {
+ next_code[i] = code;
+ z->firstcode[i] = (stbi__uint16) code;
+ z->firstsymbol[i] = (stbi__uint16) k;
+ code = (code + sizes[i]);
+ if (sizes[i])
+ if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
+ z->maxcode[i] = code << (16-i); // preshift for inner loop
+ code <<= 1;
+ k += sizes[i];
+ }
+ z->maxcode[16] = 0x10000; // sentinel
+ for (i=0; i < num; ++i) {
+ int s = sizelist[i];
+ if (s) {
+ int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
+ stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
+ z->size [c] = (stbi_uc ) s;
+ z->value[c] = (stbi__uint16) i;
+ if (s <= STBI__ZFAST_BITS) {
+ int j = stbi__bit_reverse(next_code[s],s);
+ while (j < (1 << STBI__ZFAST_BITS)) {
+ z->fast[j] = fastv;
+ j += (1 << s);
+ }
+ }
+ ++next_code[s];
+ }
+ }
+ return 1;
+}
+
+// zlib-from-memory implementation for PNG reading
+// because PNG allows splitting the zlib stream arbitrarily,
+// and it's annoying structurally to have PNG call ZLIB call PNG,
+// we require PNG read all the IDATs and combine them into a single
+// memory buffer
+
+typedef struct
+{
+ stbi_uc *zbuffer, *zbuffer_end;
+ int num_bits;
+ int hit_zeof_once;
+ stbi__uint32 code_buffer;
+
+ char *zout;
+ char *zout_start;
+ char *zout_end;
+ int z_expandable;
+
+ stbi__zhuffman z_length, z_distance;
+} stbi__zbuf;
+
+stbi_inline static int stbi__zeof(stbi__zbuf *z)
+{
+ return (z->zbuffer >= z->zbuffer_end);
+}
+
+stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
+{
+ return stbi__zeof(z) ? 0 : *z->zbuffer++;
+}
+
+static void stbi__fill_bits(stbi__zbuf *z)
+{
+ do {
+ if (z->code_buffer >= (1U << z->num_bits)) {
+ z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */
+ return;
+ }
+ z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
+ z->num_bits += 8;
+ } while (z->num_bits <= 24);
+}
+
+stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
+{
+ unsigned int k;
+ if (z->num_bits < n) stbi__fill_bits(z);
+ k = z->code_buffer & ((1 << n) - 1);
+ z->code_buffer >>= n;
+ z->num_bits -= n;
+ return k;
+}
+
+static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s,k;
+ // not resolved by fast table, so compute it the slow way
+ // use jpeg approach, which requires MSbits at top
+ k = stbi__bit_reverse(a->code_buffer, 16);
+ for (s=STBI__ZFAST_BITS+1; ; ++s)
+ if (k < z->maxcode[s])
+ break;
+ if (s >= 16) return -1; // invalid code!
+ // code size is s, so:
+ b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
+ if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!
+ if (z->size[b] != s) return -1; // was originally an assert, but report failure instead.
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return z->value[b];
+}
+
+stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s;
+ if (a->num_bits < 16) {
+ if (stbi__zeof(a)) {
+ if (!a->hit_zeof_once) {
+ // This is the first time we hit eof, insert 16 extra padding btis
+ // to allow us to keep going; if we actually consume any of them
+ // though, that is invalid data. This is caught later.
+ a->hit_zeof_once = 1;
+ a->num_bits += 16; // add 16 implicit zero bits
+ } else {
+ // We already inserted our extra 16 padding bits and are again
+ // out, this stream is actually prematurely terminated.
+ return -1;
+ }
+ } else {
+ stbi__fill_bits(a);
+ }
+ }
+ b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
+ if (b) {
+ s = b >> 9;
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return b & 511;
+ }
+ return stbi__zhuffman_decode_slowpath(a, z);
+}
+
+static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes
+{
+ char *q;
+ unsigned int cur, limit, old_limit;
+ z->zout = zout;
+ if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
+ cur = (unsigned int) (z->zout - z->zout_start);
+ limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
+ if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
+ while (cur + n > limit) {
+ if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
+ limit *= 2;
+ }
+ q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
+ STBI_NOTUSED(old_limit);
+ if (q == NULL) return stbi__err("outofmem", "Out of memory");
+ z->zout_start = q;
+ z->zout = q + cur;
+ z->zout_end = q + limit;
+ return 1;
+}
+
+static const int stbi__zlength_base[31] = {
+ 3,4,5,6,7,8,9,10,11,13,
+ 15,17,19,23,27,31,35,43,51,59,
+ 67,83,99,115,131,163,195,227,258,0,0 };
+
+static const int stbi__zlength_extra[31]=
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
+
+static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
+
+static const int stbi__zdist_extra[32] =
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+static int stbi__parse_huffman_block(stbi__zbuf *a)
+{
+ char *zout = a->zout;
+ for(;;) {
+ int z = stbi__zhuffman_decode(a, &a->z_length);
+ if (z < 256) {
+ if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
+ if (zout >= a->zout_end) {
+ if (!stbi__zexpand(a, zout, 1)) return 0;
+ zout = a->zout;
+ }
+ *zout++ = (char) z;
+ } else {
+ stbi_uc *p;
+ int len,dist;
+ if (z == 256) {
+ a->zout = zout;
+ if (a->hit_zeof_once && a->num_bits < 16) {
+ // The first time we hit zeof, we inserted 16 extra zero bits into our bit
+ // buffer so the decoder can just do its speculative decoding. But if we
+ // actually consumed any of those bits (which is the case when num_bits < 16),
+ // the stream actually read past the end so it is malformed.
+ return stbi__err("unexpected end","Corrupt PNG");
+ }
+ return 1;
+ }
+ if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data
+ z -= 257;
+ len = stbi__zlength_base[z];
+ if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
+ z = stbi__zhuffman_decode(a, &a->z_distance);
+ if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data
+ dist = stbi__zdist_base[z];
+ if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
+ if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
+ if (len > a->zout_end - zout) {
+ if (!stbi__zexpand(a, zout, len)) return 0;
+ zout = a->zout;
+ }
+ p = (stbi_uc *) (zout - dist);
+ if (dist == 1) { // run of one byte; common in images.
+ stbi_uc v = *p;
+ if (len) { do *zout++ = v; while (--len); }
+ } else {
+ if (len) { do *zout++ = *p++; while (--len); }
+ }
+ }
+ }
+}
+
+static int stbi__compute_huffman_codes(stbi__zbuf *a)
+{
+ static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
+ stbi__zhuffman z_codelength;
+ stbi_uc lencodes[286+32+137];//padding for maximum single op
+ stbi_uc codelength_sizes[19];
+ int i,n;
+
+ int hlit = stbi__zreceive(a,5) + 257;
+ int hdist = stbi__zreceive(a,5) + 1;
+ int hclen = stbi__zreceive(a,4) + 4;
+ int ntot = hlit + hdist;
+
+ memset(codelength_sizes, 0, sizeof(codelength_sizes));
+ for (i=0; i < hclen; ++i) {
+ int s = stbi__zreceive(a,3);
+ codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
+ }
+ if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
+
+ n = 0;
+ while (n < ntot) {
+ int c = stbi__zhuffman_decode(a, &z_codelength);
+ if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
+ if (c < 16)
+ lencodes[n++] = (stbi_uc) c;
+ else {
+ stbi_uc fill = 0;
+ if (c == 16) {
+ c = stbi__zreceive(a,2)+3;
+ if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
+ fill = lencodes[n-1];
+ } else if (c == 17) {
+ c = stbi__zreceive(a,3)+3;
+ } else if (c == 18) {
+ c = stbi__zreceive(a,7)+11;
+ } else {
+ return stbi__err("bad codelengths", "Corrupt PNG");
+ }
+ if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
+ memset(lencodes+n, fill, c);
+ n += c;
+ }
+ }
+ if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG");
+ if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
+ return 1;
+}
+
+static int stbi__parse_uncompressed_block(stbi__zbuf *a)
+{
+ stbi_uc header[4];
+ int len,nlen,k;
+ if (a->num_bits & 7)
+ stbi__zreceive(a, a->num_bits & 7); // discard
+ // drain the bit-packed data into header
+ k = 0;
+ while (a->num_bits > 0) {
+ header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
+ a->code_buffer >>= 8;
+ a->num_bits -= 8;
+ }
+ if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG");
+ // now fill header the normal way
+ while (k < 4)
+ header[k++] = stbi__zget8(a);
+ len = header[1] * 256 + header[0];
+ nlen = header[3] * 256 + header[2];
+ if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
+ if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
+ if (a->zout + len > a->zout_end)
+ if (!stbi__zexpand(a, a->zout, len)) return 0;
+ memcpy(a->zout, a->zbuffer, len);
+ a->zbuffer += len;
+ a->zout += len;
+ return 1;
+}
+
+static int stbi__parse_zlib_header(stbi__zbuf *a)
+{
+ int cmf = stbi__zget8(a);
+ int cm = cmf & 15;
+ /* int cinfo = cmf >> 4; */
+ int flg = stbi__zget8(a);
+ if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
+ if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
+ // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
+ return 1;
+}
+
+static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =
+{
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8
+};
+static const stbi_uc stbi__zdefault_distance[32] =
+{
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
+};
+/*
+Init algorithm:
+{
+ int i; // use <= to match clearly with spec
+ for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
+ for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
+ for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
+ for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
+
+ for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
+}
+*/
+
+static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
+{
+ int final, type;
+ if (parse_header)
+ if (!stbi__parse_zlib_header(a)) return 0;
+ a->num_bits = 0;
+ a->code_buffer = 0;
+ a->hit_zeof_once = 0;
+ do {
+ final = stbi__zreceive(a,1);
+ type = stbi__zreceive(a,2);
+ if (type == 0) {
+ if (!stbi__parse_uncompressed_block(a)) return 0;
+ } else if (type == 3) {
+ return 0;
+ } else {
+ if (type == 1) {
+ // use fixed code lengths
+ if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
+ } else {
+ if (!stbi__compute_huffman_codes(a)) return 0;
+ }
+ if (!stbi__parse_huffman_block(a)) return 0;
+ }
+ } while (!final);
+ return 1;
+}
+
+static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
+{
+ a->zout_start = obuf;
+ a->zout = obuf;
+ a->zout_end = obuf + olen;
+ a->z_expandable = exp;
+
+ return stbi__parse_zlib(a, parse_header);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
+{
+ return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(16384);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer+len;
+ if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+#endif
+
+// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
+// simple implementation
+// - only 8-bit samples
+// - no CRC checking
+// - allocates lots of intermediate memory
+// - avoids problem of streaming data between subsystems
+// - avoids explicit window management
+// performance
+// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
+
+#ifndef STBI_NO_PNG
+typedef struct
+{
+ stbi__uint32 length;
+ stbi__uint32 type;
+} stbi__pngchunk;
+
+static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
+{
+ stbi__pngchunk c;
+ c.length = stbi__get32be(s);
+ c.type = stbi__get32be(s);
+ return c;
+}
+
+static int stbi__check_png_header(stbi__context *s)
+{
+ static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
+ int i;
+ for (i=0; i < 8; ++i)
+ if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
+ return 1;
+}
+
+typedef struct
+{
+ stbi__context *s;
+ stbi_uc *idata, *expanded, *out;
+ int depth;
+} stbi__png;
+
+
+enum {
+ STBI__F_none=0,
+ STBI__F_sub=1,
+ STBI__F_up=2,
+ STBI__F_avg=3,
+ STBI__F_paeth=4,
+ // synthetic filter used for first scanline to avoid needing a dummy row of 0s
+ STBI__F_avg_first
+};
+
+static stbi_uc first_row_filter[5] =
+{
+ STBI__F_none,
+ STBI__F_sub,
+ STBI__F_none,
+ STBI__F_avg_first,
+ STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub
+};
+
+static int stbi__paeth(int a, int b, int c)
+{
+ // This formulation looks very different from the reference in the PNG spec, but is
+ // actually equivalent and has favorable data dependencies and admits straightforward
+ // generation of branch-free code, which helps performance significantly.
+ int thresh = c*3 - (a + b);
+ int lo = a < b ? a : b;
+ int hi = a < b ? b : a;
+ int t0 = (hi <= thresh) ? lo : c;
+ int t1 = (thresh <= lo) ? hi : t0;
+ return t1;
+}
+
+static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
+
+// adds an extra all-255 alpha channel
+// dest == src is legal
+// img_n must be 1 or 3
+static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)
+{
+ int i;
+ // must process data backwards since we allow dest==src
+ if (img_n == 1) {
+ for (i=x-1; i >= 0; --i) {
+ dest[i*2+1] = 255;
+ dest[i*2+0] = src[i];
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i=x-1; i >= 0; --i) {
+ dest[i*4+3] = 255;
+ dest[i*4+2] = src[i*3+2];
+ dest[i*4+1] = src[i*3+1];
+ dest[i*4+0] = src[i*3+0];
+ }
+ }
+}
+
+// create the png data from post-deflated data
+static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ stbi__context *s = a->s;
+ stbi__uint32 i,j,stride = x*out_n*bytes;
+ stbi__uint32 img_len, img_width_bytes;
+ stbi_uc *filter_buf;
+ int all_ok = 1;
+ int k;
+ int img_n = s->img_n; // copy it into a local for later
+
+ int output_bytes = out_n*bytes;
+ int filter_bytes = img_n*bytes;
+ int width = x;
+
+ STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
+ a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into
+ if (!a->out) return stbi__err("outofmem", "Out of memory");
+
+ // note: error exits here don't need to clean up a->out individually,
+ // stbi__do_png always does on error.
+ if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG");
+ img_width_bytes = (((img_n * x * depth) + 7) >> 3);
+ if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG");
+ img_len = (img_width_bytes + 1) * y;
+
+ // we used to check for exact match between raw_len and img_len on non-interlaced PNGs,
+ // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),
+ // so just check for raw_len < img_len always.
+ if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
+
+ // Allocate two scan lines worth of filter workspace buffer.
+ filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);
+ if (!filter_buf) return stbi__err("outofmem", "Out of memory");
+
+ // Filtering for low-bit-depth images
+ if (depth < 8) {
+ filter_bytes = 1;
+ width = img_width_bytes;
+ }
+
+ for (j=0; j < y; ++j) {
+ // cur/prior filter buffers alternate
+ stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;
+ stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;
+ stbi_uc *dest = a->out + stride*j;
+ int nk = width * filter_bytes;
+ int filter = *raw++;
+
+ // check filter type
+ if (filter > 4) {
+ all_ok = stbi__err("invalid filter","Corrupt PNG");
+ break;
+ }
+
+ // if first row, use special filter that doesn't sample previous row
+ if (j == 0) filter = first_row_filter[filter];
+
+ // perform actual filtering
+ switch (filter) {
+ case STBI__F_none:
+ memcpy(cur, raw, nk);
+ break;
+ case STBI__F_sub:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);
+ break;
+ case STBI__F_up:
+ for (k = 0; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
+ break;
+ case STBI__F_avg:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));
+ break;
+ case STBI__F_paeth:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));
+ break;
+ case STBI__F_avg_first:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));
+ break;
+ }
+
+ raw += nk;
+
+ // expand decoded bits in cur to dest, also adding an extra alpha channel if desired
+ if (depth < 8) {
+ stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
+ stbi_uc *in = cur;
+ stbi_uc *out = dest;
+ stbi_uc inb = 0;
+ stbi__uint32 nsmp = x*img_n;
+
+ // expand bits to bytes first
+ if (depth == 4) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 1) == 0) inb = *in++;
+ *out++ = scale * (inb >> 4);
+ inb <<= 4;
+ }
+ } else if (depth == 2) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 3) == 0) inb = *in++;
+ *out++ = scale * (inb >> 6);
+ inb <<= 2;
+ }
+ } else {
+ STBI_ASSERT(depth == 1);
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 7) == 0) inb = *in++;
+ *out++ = scale * (inb >> 7);
+ inb <<= 1;
+ }
+ }
+
+ // insert alpha=255 values if desired
+ if (img_n != out_n)
+ stbi__create_png_alpha_expand8(dest, dest, x, img_n);
+ } else if (depth == 8) {
+ if (img_n == out_n)
+ memcpy(dest, cur, x*img_n);
+ else
+ stbi__create_png_alpha_expand8(dest, cur, x, img_n);
+ } else if (depth == 16) {
+ // convert the image data from big-endian to platform-native
+ stbi__uint16 *dest16 = (stbi__uint16*)dest;
+ stbi__uint32 nsmp = x*img_n;
+
+ if (img_n == out_n) {
+ for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)
+ *dest16 = (cur[0] << 8) | cur[1];
+ } else {
+ STBI_ASSERT(img_n+1 == out_n);
+ if (img_n == 1) {
+ for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = 0xffff;
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = (cur[2] << 8) | cur[3];
+ dest16[2] = (cur[4] << 8) | cur[5];
+ dest16[3] = 0xffff;
+ }
+ }
+ }
+ }
+ }
+
+ STBI_FREE(filter_buf);
+ if (!all_ok) return 0;
+
+ return 1;
+}
+
+static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ int out_bytes = out_n * bytes;
+ stbi_uc *final;
+ int p;
+ if (!interlaced)
+ return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
+
+ // de-interlacing
+ final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
+ if (!final) return stbi__err("outofmem", "Out of memory");
+ for (p=0; p < 7; ++p) {
+ int xorig[] = { 0,4,0,2,0,1,0 };
+ int yorig[] = { 0,0,4,0,2,0,1 };
+ int xspc[] = { 8,8,4,4,2,2,1 };
+ int yspc[] = { 8,8,8,4,4,2,2 };
+ int i,j,x,y;
+ // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
+ x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
+ y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
+ if (x && y) {
+ stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
+ if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
+ STBI_FREE(final);
+ return 0;
+ }
+ for (j=0; j < y; ++j) {
+ for (i=0; i < x; ++i) {
+ int out_y = j*yspc[p]+yorig[p];
+ int out_x = i*xspc[p]+xorig[p];
+ memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,
+ a->out + (j*x+i)*out_bytes, out_bytes);
+ }
+ }
+ STBI_FREE(a->out);
+ image_data += img_len;
+ image_data_len -= img_len;
+ }
+ }
+ a->out = final;
+
+ return 1;
+}
+
+static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 255 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i=0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 255);
+ p += 2;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi__uint16 *p = (stbi__uint16*) z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 65535 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i = 0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 65535);
+ p += 2;
+ }
+ } else {
+ for (i = 0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
+{
+ stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
+ stbi_uc *p, *temp_out, *orig = a->out;
+
+ p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);
+ if (p == NULL) return stbi__err("outofmem", "Out of memory");
+
+ // between here and free(out) below, exitting would leak
+ temp_out = p;
+
+ if (pal_img_n == 3) {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p += 3;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p[3] = palette[n+3];
+ p += 4;
+ }
+ }
+ STBI_FREE(a->out);
+ a->out = temp_out;
+
+ STBI_NOTUSED(len);
+
+ return 1;
+}
+
+static int stbi__unpremultiply_on_load_global = 0;
+static int stbi__de_iphone_flag_global = 0;
+
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_global = flag_true_if_should_convert;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global
+#define stbi__de_iphone_flag stbi__de_iphone_flag_global
+#else
+static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
+
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
+ stbi__unpremultiply_on_load_set = 1;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_local = flag_true_if_should_convert;
+ stbi__de_iphone_flag_set = 1;
+}
+
+#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \
+ ? stbi__unpremultiply_on_load_local \
+ : stbi__unpremultiply_on_load_global)
+#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \
+ ? stbi__de_iphone_flag_local \
+ : stbi__de_iphone_flag_global)
+#endif // STBI_THREAD_LOCAL
+
+static void stbi__de_iphone(stbi__png *z)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ if (s->img_out_n == 3) { // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 3;
+ }
+ } else {
+ STBI_ASSERT(s->img_out_n == 4);
+ if (stbi__unpremultiply_on_load) {
+ // convert bgr to rgb and unpremultiply
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc a = p[3];
+ stbi_uc t = p[0];
+ if (a) {
+ stbi_uc half = a / 2;
+ p[0] = (p[2] * 255 + half) / a;
+ p[1] = (p[1] * 255 + half) / a;
+ p[2] = ( t * 255 + half) / a;
+ } else {
+ p[0] = p[2];
+ p[2] = t;
+ }
+ p += 4;
+ }
+ } else {
+ // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 4;
+ }
+ }
+ }
+}
+
+#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))
+
+static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
+{
+ stbi_uc palette[1024], pal_img_n=0;
+ stbi_uc has_trans=0, tc[3]={0};
+ stbi__uint16 tc16[3];
+ stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
+ int first=1,k,interlace=0, color=0, is_iphone=0;
+ stbi__context *s = z->s;
+
+ z->expanded = NULL;
+ z->idata = NULL;
+ z->out = NULL;
+
+ if (!stbi__check_png_header(s)) return 0;
+
+ if (scan == STBI__SCAN_type) return 1;
+
+ for (;;) {
+ stbi__pngchunk c = stbi__get_chunk_header(s);
+ switch (c.type) {
+ case STBI__PNG_TYPE('C','g','B','I'):
+ is_iphone = 1;
+ stbi__skip(s, c.length);
+ break;
+ case STBI__PNG_TYPE('I','H','D','R'): {
+ int comp,filter;
+ if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
+ first = 0;
+ if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
+ s->img_x = stbi__get32be(s);
+ s->img_y = stbi__get32be(s);
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
+ color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
+ comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
+ filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
+ interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
+ if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
+ if (!pal_img_n) {
+ s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
+ if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
+ } else {
+ // if paletted, then pal_n is our final components, and
+ // img_n is # components to decompress/filter.
+ s->img_n = 1;
+ if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
+ }
+ // even with SCAN_header, have to scan to see if we have a tRNS
+ break;
+ }
+
+ case STBI__PNG_TYPE('P','L','T','E'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
+ pal_len = c.length / 3;
+ if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
+ for (i=0; i < pal_len; ++i) {
+ palette[i*4+0] = stbi__get8(s);
+ palette[i*4+1] = stbi__get8(s);
+ palette[i*4+2] = stbi__get8(s);
+ palette[i*4+3] = 255;
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('t','R','N','S'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
+ if (pal_img_n) {
+ if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
+ if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
+ if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
+ pal_img_n = 4;
+ for (i=0; i < c.length; ++i)
+ palette[i*4+3] = stbi__get8(s);
+ } else {
+ if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
+ if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
+ has_trans = 1;
+ // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.
+ if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }
+ if (z->depth == 16) {
+ for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning
+ tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is
+ } else {
+ for (k = 0; k < s->img_n && k < 3; ++k)
+ tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger
+ }
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','D','A','T'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
+ if (scan == STBI__SCAN_header) {
+ // header scan definitely stops at first IDAT
+ if (pal_img_n)
+ s->img_n = pal_img_n;
+ return 1;
+ }
+ if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
+ if ((int)(ioff + c.length) < (int)ioff) return 0;
+ if (ioff + c.length > idata_limit) {
+ stbi__uint32 idata_limit_old = idata_limit;
+ stbi_uc *p;
+ if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
+ while (ioff + c.length > idata_limit)
+ idata_limit *= 2;
+ STBI_NOTUSED(idata_limit_old);
+ p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
+ z->idata = p;
+ }
+ if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
+ ioff += c.length;
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','E','N','D'): {
+ stbi__uint32 raw_len, bpl;
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (scan != STBI__SCAN_load) return 1;
+ if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
+ // initial guess for decoded data size to avoid unnecessary reallocs
+ bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
+ raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
+ z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
+ if (z->expanded == NULL) return 0; // zlib should set error
+ STBI_FREE(z->idata); z->idata = NULL;
+ if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
+ s->img_out_n = s->img_n+1;
+ else
+ s->img_out_n = s->img_n;
+ if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;
+ if (has_trans) {
+ if (z->depth == 16) {
+ if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
+ } else {
+ if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
+ }
+ }
+ if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
+ stbi__de_iphone(z);
+ if (pal_img_n) {
+ // pal_img_n == 3 or 4
+ s->img_n = pal_img_n; // record the actual colors we had
+ s->img_out_n = pal_img_n;
+ if (req_comp >= 3) s->img_out_n = req_comp;
+ if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
+ return 0;
+ } else if (has_trans) {
+ // non-paletted image with tRNS -> source image has (constant) alpha
+ ++s->img_n;
+ }
+ STBI_FREE(z->expanded); z->expanded = NULL;
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ return 1;
+ }
+
+ default:
+ // if critical, fail
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if ((c.type & (1 << 29)) == 0) {
+ #ifndef STBI_NO_FAILURE_STRINGS
+ // not threadsafe
+ static char invalid_chunk[] = "XXXX PNG chunk not known";
+ invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
+ invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
+ invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
+ invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
+ #endif
+ return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
+ }
+ stbi__skip(s, c.length);
+ break;
+ }
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ }
+}
+
+static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)
+{
+ void *result=NULL;
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+ if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
+ if (p->depth <= 8)
+ ri->bits_per_channel = 8;
+ else if (p->depth == 16)
+ ri->bits_per_channel = 16;
+ else
+ return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
+ result = p->out;
+ p->out = NULL;
+ if (req_comp && req_comp != p->s->img_out_n) {
+ if (ri->bits_per_channel == 8)
+ result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ else
+ result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ p->s->img_out_n = req_comp;
+ if (result == NULL) return result;
+ }
+ *x = p->s->img_x;
+ *y = p->s->img_y;
+ if (n) *n = p->s->img_n;
+ }
+ STBI_FREE(p->out); p->out = NULL;
+ STBI_FREE(p->expanded); p->expanded = NULL;
+ STBI_FREE(p->idata); p->idata = NULL;
+
+ return result;
+}
+
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__do_png(&p, x,y,comp,req_comp, ri);
+}
+
+static int stbi__png_test(stbi__context *s)
+{
+ int r;
+ r = stbi__check_png_header(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
+{
+ if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
+ stbi__rewind( p->s );
+ return 0;
+ }
+ if (x) *x = p->s->img_x;
+ if (y) *y = p->s->img_y;
+ if (comp) *comp = p->s->img_n;
+ return 1;
+}
+
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__png_info_raw(&p, x, y, comp);
+}
+
+static int stbi__png_is16(stbi__context *s)
+{
+ stbi__png p;
+ p.s = s;
+ if (!stbi__png_info_raw(&p, NULL, NULL, NULL))
+ return 0;
+ if (p.depth != 16) {
+ stbi__rewind(p.s);
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+// Microsoft/Windows BMP image
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test_raw(stbi__context *s)
+{
+ int r;
+ int sz;
+ if (stbi__get8(s) != 'B') return 0;
+ if (stbi__get8(s) != 'M') return 0;
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ stbi__get32le(s); // discard data offset
+ sz = stbi__get32le(s);
+ r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
+ return r;
+}
+
+static int stbi__bmp_test(stbi__context *s)
+{
+ int r = stbi__bmp_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+
+// returns 0..31 for the highest set bit
+static int stbi__high_bit(unsigned int z)
+{
+ int n=0;
+ if (z == 0) return -1;
+ if (z >= 0x10000) { n += 16; z >>= 16; }
+ if (z >= 0x00100) { n += 8; z >>= 8; }
+ if (z >= 0x00010) { n += 4; z >>= 4; }
+ if (z >= 0x00004) { n += 2; z >>= 2; }
+ if (z >= 0x00002) { n += 1;/* >>= 1;*/ }
+ return n;
+}
+
+static int stbi__bitcount(unsigned int a)
+{
+ a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
+ a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
+ a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
+ a = (a + (a >> 8)); // max 16 per 8 bits
+ a = (a + (a >> 16)); // max 32 per 8 bits
+ return a & 0xff;
+}
+
+// extract an arbitrarily-aligned N-bit value (N=bits)
+// from v, and then make it 8-bits long and fractionally
+// extend it to full full range.
+static int stbi__shiftsigned(unsigned int v, int shift, int bits)
+{
+ static unsigned int mul_table[9] = {
+ 0,
+ 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/,
+ 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/,
+ };
+ static unsigned int shift_table[9] = {
+ 0, 0,0,1,0,2,4,6,0,
+ };
+ if (shift < 0)
+ v <<= -shift;
+ else
+ v >>= shift;
+ STBI_ASSERT(v < 256);
+ v >>= (8-bits);
+ STBI_ASSERT(bits >= 0 && bits <= 8);
+ return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits];
+}
+
+typedef struct
+{
+ int bpp, offset, hsz;
+ unsigned int mr,mg,mb,ma, all_a;
+ int extra_read;
+} stbi__bmp_data;
+
+static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)
+{
+ // BI_BITFIELDS specifies masks explicitly, don't override
+ if (compress == 3)
+ return 1;
+
+ if (compress == 0) {
+ if (info->bpp == 16) {
+ info->mr = 31u << 10;
+ info->mg = 31u << 5;
+ info->mb = 31u << 0;
+ } else if (info->bpp == 32) {
+ info->mr = 0xffu << 16;
+ info->mg = 0xffu << 8;
+ info->mb = 0xffu << 0;
+ info->ma = 0xffu << 24;
+ info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
+ } else {
+ // otherwise, use defaults, which is all-0
+ info->mr = info->mg = info->mb = info->ma = 0;
+ }
+ return 1;
+ }
+ return 0; // error
+}
+
+static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
+{
+ int hsz;
+ if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ info->offset = stbi__get32le(s);
+ info->hsz = hsz = stbi__get32le(s);
+ info->mr = info->mg = info->mb = info->ma = 0;
+ info->extra_read = 14;
+
+ if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP");
+
+ if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
+ if (hsz == 12) {
+ s->img_x = stbi__get16le(s);
+ s->img_y = stbi__get16le(s);
+ } else {
+ s->img_x = stbi__get32le(s);
+ s->img_y = stbi__get32le(s);
+ }
+ if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
+ info->bpp = stbi__get16le(s);
+ if (hsz != 12) {
+ int compress = stbi__get32le(s);
+ if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
+ if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes
+ if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
+ stbi__get32le(s); // discard sizeof
+ stbi__get32le(s); // discard hres
+ stbi__get32le(s); // discard vres
+ stbi__get32le(s); // discard colorsused
+ stbi__get32le(s); // discard max important
+ if (hsz == 40 || hsz == 56) {
+ if (hsz == 56) {
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ }
+ if (info->bpp == 16 || info->bpp == 32) {
+ if (compress == 0) {
+ stbi__bmp_set_mask_defaults(info, compress);
+ } else if (compress == 3) {
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->extra_read += 12;
+ // not documented, but generated by photoshop and handled by mspaint
+ if (info->mr == info->mg && info->mg == info->mb) {
+ // ?!?!?
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else {
+ // V4/V5 header
+ int i;
+ if (hsz != 108 && hsz != 124)
+ return stbi__errpuc("bad BMP", "bad BMP");
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->ma = stbi__get32le(s);
+ if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
+ stbi__bmp_set_mask_defaults(info, compress);
+ stbi__get32le(s); // discard color space
+ for (i=0; i < 12; ++i)
+ stbi__get32le(s); // discard color space parameters
+ if (hsz == 124) {
+ stbi__get32le(s); // discard rendering intent
+ stbi__get32le(s); // discard offset of profile data
+ stbi__get32le(s); // discard size of profile data
+ stbi__get32le(s); // discard reserved
+ }
+ }
+ }
+ return (void *) 1;
+}
+
+
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ unsigned int mr=0,mg=0,mb=0,ma=0, all_a;
+ stbi_uc pal[256][4];
+ int psize=0,i,j,width;
+ int flip_vertically, pad, target;
+ stbi__bmp_data info;
+ STBI_NOTUSED(ri);
+
+ info.all_a = 255;
+ if (stbi__bmp_parse_header(s, &info) == NULL)
+ return NULL; // error code already set
+
+ flip_vertically = ((int) s->img_y) > 0;
+ s->img_y = abs((int) s->img_y);
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ mr = info.mr;
+ mg = info.mg;
+ mb = info.mb;
+ ma = info.ma;
+ all_a = info.all_a;
+
+ if (info.hsz == 12) {
+ if (info.bpp < 24)
+ psize = (info.offset - info.extra_read - 24) / 3;
+ } else {
+ if (info.bpp < 16)
+ psize = (info.offset - info.extra_read - info.hsz) >> 2;
+ }
+ if (psize == 0) {
+ // accept some number of extra bytes after the header, but if the offset points either to before
+ // the header ends or implies a large amount of extra data, reject the file as malformed
+ int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);
+ int header_limit = 1024; // max we actually read is below 256 bytes currently.
+ int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.
+ if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) {
+ return stbi__errpuc("bad header", "Corrupt BMP");
+ }
+ // we established that bytes_read_so_far is positive and sensible.
+ // the first half of this test rejects offsets that are either too small positives, or
+ // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn
+ // ensures the number computed in the second half of the test can't overflow.
+ if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) {
+ return stbi__errpuc("bad offset", "Corrupt BMP");
+ } else {
+ stbi__skip(s, info.offset - bytes_read_so_far);
+ }
+ }
+
+ if (info.bpp == 24 && ma == 0xff000000)
+ s->img_n = 3;
+ else
+ s->img_n = ma ? 4 : 3;
+ if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
+ target = req_comp;
+ else
+ target = s->img_n; // if they want monochrome, we'll post-convert
+
+ // sanity-check size
+ if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))
+ return stbi__errpuc("too large", "Corrupt BMP");
+
+ out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (info.bpp < 16) {
+ int z=0;
+ if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
+ for (i=0; i < psize; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ if (info.hsz != 12) stbi__get8(s);
+ pal[i][3] = 255;
+ }
+ stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4));
+ if (info.bpp == 1) width = (s->img_x + 7) >> 3;
+ else if (info.bpp == 4) width = (s->img_x + 1) >> 1;
+ else if (info.bpp == 8) width = s->img_x;
+ else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
+ pad = (-width)&3;
+ if (info.bpp == 1) {
+ for (j=0; j < (int) s->img_y; ++j) {
+ int bit_offset = 7, v = stbi__get8(s);
+ for (i=0; i < (int) s->img_x; ++i) {
+ int color = (v>>bit_offset)&0x1;
+ out[z++] = pal[color][0];
+ out[z++] = pal[color][1];
+ out[z++] = pal[color][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ if((--bit_offset) < 0) {
+ bit_offset = 7;
+ v = stbi__get8(s);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ } else {
+ for (j=0; j < (int) s->img_y; ++j) {
+ for (i=0; i < (int) s->img_x; i += 2) {
+ int v=stbi__get8(s),v2=0;
+ if (info.bpp == 4) {
+ v2 = v & 15;
+ v >>= 4;
+ }
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ v = (info.bpp == 8) ? stbi__get8(s) : v2;
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ }
+ stbi__skip(s, pad);
+ }
+ }
+ } else {
+ int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
+ int z = 0;
+ int easy=0;
+ stbi__skip(s, info.offset - info.extra_read - info.hsz);
+ if (info.bpp == 24) width = 3 * s->img_x;
+ else if (info.bpp == 16) width = 2*s->img_x;
+ else /* bpp = 32 and pad = 0 */ width=0;
+ pad = (-width) & 3;
+ if (info.bpp == 24) {
+ easy = 1;
+ } else if (info.bpp == 32) {
+ if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
+ easy = 2;
+ }
+ if (!easy) {
+ if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ // right shift amt to put high bit in position #7
+ rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
+ gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
+ bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
+ ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
+ if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ }
+ for (j=0; j < (int) s->img_y; ++j) {
+ if (easy) {
+ for (i=0; i < (int) s->img_x; ++i) {
+ unsigned char a;
+ out[z+2] = stbi__get8(s);
+ out[z+1] = stbi__get8(s);
+ out[z+0] = stbi__get8(s);
+ z += 3;
+ a = (easy == 2 ? stbi__get8(s) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = a;
+ }
+ } else {
+ int bpp = info.bpp;
+ for (i=0; i < (int) s->img_x; ++i) {
+ stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
+ unsigned int a;
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
+ a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = STBI__BYTECAST(a);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ }
+
+ // if alpha channel is all 0s, replace with all 255s
+ if (target == 4 && all_a == 0)
+ for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4)
+ out[i] = 255;
+
+ if (flip_vertically) {
+ stbi_uc t;
+ for (j=0; j < (int) s->img_y>>1; ++j) {
+ stbi_uc *p1 = out + j *s->img_x*target;
+ stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
+ for (i=0; i < (int) s->img_x*target; ++i) {
+ t = p1[i]; p1[i] = p2[i]; p2[i] = t;
+ }
+ }
+ }
+
+ if (req_comp && req_comp != target) {
+ out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+ return out;
+}
+#endif
+
+// Targa Truevision - TGA
+// by Jonathan Dummer
+#ifndef STBI_NO_TGA
+// returns STBI_rgb or whatever, 0 on error
+static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)
+{
+ // only RGB or RGBA (incl. 16bit) or grey allowed
+ if (is_rgb16) *is_rgb16 = 0;
+ switch(bits_per_pixel) {
+ case 8: return STBI_grey;
+ case 16: if(is_grey) return STBI_grey_alpha;
+ // fallthrough
+ case 15: if(is_rgb16) *is_rgb16 = 1;
+ return STBI_rgb;
+ case 24: // fallthrough
+ case 32: return bits_per_pixel/8;
+ default: return 0;
+ }
+}
+
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
+ int sz, tga_colormap_type;
+ stbi__get8(s); // discard Offset
+ tga_colormap_type = stbi__get8(s); // colormap type
+ if( tga_colormap_type > 1 ) {
+ stbi__rewind(s);
+ return 0; // only RGB or indexed allowed
+ }
+ tga_image_type = stbi__get8(s); // image type
+ if ( tga_colormap_type == 1 ) { // colormapped (paletted) image
+ if (tga_image_type != 1 && tga_image_type != 9) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip image x and y origin
+ tga_colormap_bpp = sz;
+ } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
+ if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) {
+ stbi__rewind(s);
+ return 0; // only RGB or grey allowed, +/- RLE
+ }
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ tga_colormap_bpp = 0;
+ }
+ tga_w = stbi__get16le(s);
+ if( tga_w < 1 ) {
+ stbi__rewind(s);
+ return 0; // test width
+ }
+ tga_h = stbi__get16le(s);
+ if( tga_h < 1 ) {
+ stbi__rewind(s);
+ return 0; // test height
+ }
+ tga_bits_per_pixel = stbi__get8(s); // bits per pixel
+ stbi__get8(s); // ignore alpha bits
+ if (tga_colormap_bpp != 0) {
+ if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) {
+ // when using a colormap, tga_bits_per_pixel is the size of the indexes
+ // I don't think anything but 8 or 16bit indexes makes sense
+ stbi__rewind(s);
+ return 0;
+ }
+ tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
+ } else {
+ tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);
+ }
+ if(!tga_comp) {
+ stbi__rewind(s);
+ return 0;
+ }
+ if (x) *x = tga_w;
+ if (y) *y = tga_h;
+ if (comp) *comp = tga_comp;
+ return 1; // seems to have passed everything
+}
+
+static int stbi__tga_test(stbi__context *s)
+{
+ int res = 0;
+ int sz, tga_color_type;
+ stbi__get8(s); // discard Offset
+ tga_color_type = stbi__get8(s); // color type
+ if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed
+ sz = stbi__get8(s); // image type
+ if ( tga_color_type == 1 ) { // colormapped (paletted) image
+ if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+ stbi__skip(s,4); // skip image x and y origin
+ } else { // "normal" image w/o colormap
+ if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ }
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height
+ sz = stbi__get8(s); // bits per pixel
+ if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+
+ res = 1; // if we got this far, everything's good and we can return 1 instead of 0
+
+errorEnd:
+ stbi__rewind(s);
+ return res;
+}
+
+// read 16bit value and convert to 24bit RGB
+static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)
+{
+ stbi__uint16 px = (stbi__uint16)stbi__get16le(s);
+ stbi__uint16 fiveBitMask = 31;
+ // we have 3 channels with 5bits each
+ int r = (px >> 10) & fiveBitMask;
+ int g = (px >> 5) & fiveBitMask;
+ int b = px & fiveBitMask;
+ // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later
+ out[0] = (stbi_uc)((r * 255)/31);
+ out[1] = (stbi_uc)((g * 255)/31);
+ out[2] = (stbi_uc)((b * 255)/31);
+
+ // some people claim that the most significant bit might be used for alpha
+ // (possibly if an alpha-bit is set in the "image descriptor byte")
+ // but that only made 16bit test images completely translucent..
+ // so let's treat all 15 and 16bit TGAs as RGB with no alpha.
+}
+
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ // read in the TGA header stuff
+ int tga_offset = stbi__get8(s);
+ int tga_indexed = stbi__get8(s);
+ int tga_image_type = stbi__get8(s);
+ int tga_is_RLE = 0;
+ int tga_palette_start = stbi__get16le(s);
+ int tga_palette_len = stbi__get16le(s);
+ int tga_palette_bits = stbi__get8(s);
+ int tga_x_origin = stbi__get16le(s);
+ int tga_y_origin = stbi__get16le(s);
+ int tga_width = stbi__get16le(s);
+ int tga_height = stbi__get16le(s);
+ int tga_bits_per_pixel = stbi__get8(s);
+ int tga_comp, tga_rgb16=0;
+ int tga_inverted = stbi__get8(s);
+ // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)
+ // image data
+ unsigned char *tga_data;
+ unsigned char *tga_palette = NULL;
+ int i, j;
+ unsigned char raw_data[4] = {0};
+ int RLE_count = 0;
+ int RLE_repeating = 0;
+ int read_next_pixel = 1;
+ STBI_NOTUSED(ri);
+ STBI_NOTUSED(tga_x_origin); // @TODO
+ STBI_NOTUSED(tga_y_origin); // @TODO
+
+ if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // do a tiny bit of precessing
+ if ( tga_image_type >= 8 )
+ {
+ tga_image_type -= 8;
+ tga_is_RLE = 1;
+ }
+ tga_inverted = 1 - ((tga_inverted >> 5) & 1);
+
+ // If I'm paletted, then I'll use the number of bits from the palette
+ if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
+ else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
+
+ if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
+ return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
+
+ // tga info
+ *x = tga_width;
+ *y = tga_height;
+ if (comp) *comp = tga_comp;
+
+ if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))
+ return stbi__errpuc("too large", "Corrupt TGA");
+
+ tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);
+ if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
+
+ // skip to the data's starting position (offset usually = 0)
+ stbi__skip(s, tga_offset );
+
+ if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) {
+ for (i=0; i < tga_height; ++i) {
+ int row = tga_inverted ? tga_height -i - 1 : i;
+ stbi_uc *tga_row = tga_data + row*tga_width*tga_comp;
+ stbi__getn(s, tga_row, tga_width * tga_comp);
+ }
+ } else {
+ // do I need to load a palette?
+ if ( tga_indexed)
+ {
+ if (tga_palette_len == 0) { /* you have to have at least one entry! */
+ STBI_FREE(tga_data);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+
+ // any data to skip? (offset usually = 0)
+ stbi__skip(s, tga_palette_start );
+ // load the palette
+ tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);
+ if (!tga_palette) {
+ STBI_FREE(tga_data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+ if (tga_rgb16) {
+ stbi_uc *pal_entry = tga_palette;
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ for (i=0; i < tga_palette_len; ++i) {
+ stbi__tga_read_rgb16(s, pal_entry);
+ pal_entry += tga_comp;
+ }
+ } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {
+ STBI_FREE(tga_data);
+ STBI_FREE(tga_palette);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+ }
+ // load the data
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
+ if ( tga_is_RLE )
+ {
+ if ( RLE_count == 0 )
+ {
+ // yep, get the next byte as a RLE command
+ int RLE_cmd = stbi__get8(s);
+ RLE_count = 1 + (RLE_cmd & 127);
+ RLE_repeating = RLE_cmd >> 7;
+ read_next_pixel = 1;
+ } else if ( !RLE_repeating )
+ {
+ read_next_pixel = 1;
+ }
+ } else
+ {
+ read_next_pixel = 1;
+ }
+ // OK, if I need to read a pixel, do it now
+ if ( read_next_pixel )
+ {
+ // load however much data we did have
+ if ( tga_indexed )
+ {
+ // read in index, then perform the lookup
+ int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
+ if ( pal_idx >= tga_palette_len ) {
+ // invalid index
+ pal_idx = 0;
+ }
+ pal_idx *= tga_comp;
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = tga_palette[pal_idx+j];
+ }
+ } else if(tga_rgb16) {
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ stbi__tga_read_rgb16(s, raw_data);
+ } else {
+ // read in the data raw
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = stbi__get8(s);
+ }
+ }
+ // clear the reading flag for the next pixel
+ read_next_pixel = 0;
+ } // end of reading a pixel
+
+ // copy data
+ for (j = 0; j < tga_comp; ++j)
+ tga_data[i*tga_comp+j] = raw_data[j];
+
+ // in case we're in RLE mode, keep counting down
+ --RLE_count;
+ }
+ // do I need to invert the image?
+ if ( tga_inverted )
+ {
+ for (j = 0; j*2 < tga_height; ++j)
+ {
+ int index1 = j * tga_width * tga_comp;
+ int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
+ for (i = tga_width * tga_comp; i > 0; --i)
+ {
+ unsigned char temp = tga_data[index1];
+ tga_data[index1] = tga_data[index2];
+ tga_data[index2] = temp;
+ ++index1;
+ ++index2;
+ }
+ }
+ }
+ // clear my palette, if I had one
+ if ( tga_palette != NULL )
+ {
+ STBI_FREE( tga_palette );
+ }
+ }
+
+ // swap RGB - if the source data was RGB16, it already is in the right order
+ if (tga_comp >= 3 && !tga_rgb16)
+ {
+ unsigned char* tga_pixel = tga_data;
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ unsigned char temp = tga_pixel[0];
+ tga_pixel[0] = tga_pixel[2];
+ tga_pixel[2] = temp;
+ tga_pixel += tga_comp;
+ }
+ }
+
+ // convert to target component count
+ if (req_comp && req_comp != tga_comp)
+ tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
+
+ // the things I do to get rid of an error message, and yet keep
+ // Microsoft's C compilers happy... [8^(
+ tga_palette_start = tga_palette_len = tga_palette_bits =
+ tga_x_origin = tga_y_origin = 0;
+ STBI_NOTUSED(tga_palette_start);
+ // OK, done
+ return tga_data;
+}
+#endif
+
+// *************************************************************************************************
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s)
+{
+ int r = (stbi__get32be(s) == 0x38425053);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount)
+{
+ int count, nleft, len;
+
+ count = 0;
+ while ((nleft = pixelCount - count) > 0) {
+ len = stbi__get8(s);
+ if (len == 128) {
+ // No-op.
+ } else if (len < 128) {
+ // Copy next len+1 bytes literally.
+ len++;
+ if (len > nleft) return 0; // corrupt data
+ count += len;
+ while (len) {
+ *p = stbi__get8(s);
+ p += 4;
+ len--;
+ }
+ } else if (len > 128) {
+ stbi_uc val;
+ // Next -len+1 bytes in the dest are replicated from next source byte.
+ // (Interpret len as a negative 8-bit int.)
+ len = 257 - len;
+ if (len > nleft) return 0; // corrupt data
+ val = stbi__get8(s);
+ count += len;
+ while (len) {
+ *p = val;
+ p += 4;
+ len--;
+ }
+ }
+ }
+
+ return 1;
+}
+
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ int pixelCount;
+ int channelCount, compression;
+ int channel, i;
+ int bitdepth;
+ int w,h;
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ if (stbi__get32be(s) != 0x38425053) // "8BPS"
+ return stbi__errpuc("not PSD", "Corrupt PSD image");
+
+ // Check file type version.
+ if (stbi__get16be(s) != 1)
+ return stbi__errpuc("wrong version", "Unsupported version of PSD image");
+
+ // Skip 6 reserved bytes.
+ stbi__skip(s, 6 );
+
+ // Read the number of channels (R, G, B, A, etc).
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16)
+ return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
+
+ // Read the rows and columns of the image.
+ h = stbi__get32be(s);
+ w = stbi__get32be(s);
+
+ if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // Make sure the depth is 8 bits.
+ bitdepth = stbi__get16be(s);
+ if (bitdepth != 8 && bitdepth != 16)
+ return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
+
+ // Make sure the color mode is RGB.
+ // Valid options are:
+ // 0: Bitmap
+ // 1: Grayscale
+ // 2: Indexed color
+ // 3: RGB color
+ // 4: CMYK color
+ // 7: Multichannel
+ // 8: Duotone
+ // 9: Lab color
+ if (stbi__get16be(s) != 3)
+ return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
+
+ // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
+ stbi__skip(s,stbi__get32be(s) );
+
+ // Skip the image resources. (resolution, pen tool paths, etc)
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Skip the reserved data.
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Find out if the data is compressed.
+ // Known values:
+ // 0: no compression
+ // 1: RLE compressed
+ compression = stbi__get16be(s);
+ if (compression > 1)
+ return stbi__errpuc("bad compression", "PSD has an unknown compression format");
+
+ // Check size
+ if (!stbi__mad3sizes_valid(4, w, h, 0))
+ return stbi__errpuc("too large", "Corrupt PSD");
+
+ // Create the destination image.
+
+ if (!compression && bitdepth == 16 && bpc == 16) {
+ out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0);
+ ri->bits_per_channel = 16;
+ } else
+ out = (stbi_uc *) stbi__malloc(4 * w*h);
+
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ pixelCount = w*h;
+
+ // Initialize the data to zero.
+ //memset( out, 0, pixelCount * 4 );
+
+ // Finally, the image data.
+ if (compression) {
+ // RLE as used by .PSD and .TIFF
+ // Loop until you get the number of unpacked bytes you are expecting:
+ // Read the next source byte into n.
+ // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
+ // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
+ // Else if n is 128, noop.
+ // Endloop
+
+ // The RLE-compressed data is preceded by a 2-byte data count for each row in the data,
+ // which we're going to just skip.
+ stbi__skip(s, h * channelCount * 2 );
+
+ // Read the RLE data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ stbi_uc *p;
+
+ p = out+channel;
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (channel == 3 ? 255 : 0);
+ } else {
+ // Read the RLE data.
+ if (!stbi__psd_decode_rle(s, p, pixelCount)) {
+ STBI_FREE(out);
+ return stbi__errpuc("corrupt", "bad RLE data");
+ }
+ }
+ }
+
+ } else {
+ // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
+ // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.
+
+ // Read the data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ if (bitdepth == 16 && bpc == 16) {
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ stbi__uint16 val = channel == 3 ? 65535 : 0;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = val;
+ } else {
+ stbi_uc *p = out+channel;
+ stbi_uc val = channel == 3 ? 255 : 0;
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = val;
+ }
+ } else {
+ if (ri->bits_per_channel == 16) { // output bpc
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = (stbi__uint16) stbi__get16be(s);
+ } else {
+ stbi_uc *p = out+channel;
+ if (bitdepth == 16) { // input bpc
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (stbi_uc) (stbi__get16be(s) >> 8);
+ } else {
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = stbi__get8(s);
+ }
+ }
+ }
+ }
+ }
+
+ // remove weird white matte from PSD
+ if (channelCount >= 4) {
+ if (ri->bits_per_channel == 16) {
+ for (i=0; i < w*h; ++i) {
+ stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 65535) {
+ float a = pixel[3] / 65535.0f;
+ float ra = 1.0f / a;
+ float inv_a = 65535.0f * (1 - ra);
+ pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a);
+ pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a);
+ pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a);
+ }
+ }
+ } else {
+ for (i=0; i < w*h; ++i) {
+ unsigned char *pixel = out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 255) {
+ float a = pixel[3] / 255.0f;
+ float ra = 1.0f / a;
+ float inv_a = 255.0f * (1 - ra);
+ pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);
+ pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);
+ pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);
+ }
+ }
+ }
+ }
+
+ // convert to desired output format
+ if (req_comp && req_comp != 4) {
+ if (ri->bits_per_channel == 16)
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);
+ else
+ out = stbi__convert_format(out, 4, req_comp, w, h);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ if (comp) *comp = 4;
+ *y = h;
+ *x = w;
+
+ return out;
+}
+#endif
+
+// *************************************************************************************************
+// Softimage PIC loader
+// by Tom Seddon
+//
+// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
+// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_is4(stbi__context *s,const char *str)
+{
+ int i;
+ for (i=0; i<4; ++i)
+ if (stbi__get8(s) != (stbi_uc)str[i])
+ return 0;
+
+ return 1;
+}
+
+static int stbi__pic_test_core(stbi__context *s)
+{
+ int i;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
+ return 0;
+
+ for(i=0;i<84;++i)
+ stbi__get8(s);
+
+ if (!stbi__pic_is4(s,"PICT"))
+ return 0;
+
+ return 1;
+}
+
+typedef struct
+{
+ stbi_uc size,type,channel;
+} stbi__pic_packet;
+
+static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
+{
+ int mask=0x80, i;
+
+ for (i=0; i<4; ++i, mask>>=1) {
+ if (channel & mask) {
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
+ dest[i]=stbi__get8(s);
+ }
+ }
+
+ return dest;
+}
+
+static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
+{
+ int mask=0x80,i;
+
+ for (i=0;i<4; ++i, mask>>=1)
+ if (channel&mask)
+ dest[i]=src[i];
+}
+
+static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
+{
+ int act_comp=0,num_packets=0,y,chained;
+ stbi__pic_packet packets[10];
+
+ // this will (should...) cater for even some bizarre stuff like having data
+ // for the same channel in multiple packets.
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return stbi__errpuc("bad format","too many packets");
+
+ packet = &packets[num_packets++];
+
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
+ if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
+
+ for(y=0; y<height; ++y) {
+ int packet_idx;
+
+ for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
+ stbi__pic_packet *packet = &packets[packet_idx];
+ stbi_uc *dest = result+y*width*4;
+
+ switch (packet->type) {
+ default:
+ return stbi__errpuc("bad format","packet has bad compression type");
+
+ case 0: {//uncompressed
+ int x;
+
+ for(x=0;x<width;++x, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ break;
+ }
+
+ case 1://Pure RLE
+ {
+ int left=width, i;
+
+ while (left>0) {
+ stbi_uc count,value[4];
+
+ count=stbi__get8(s);
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
+
+ if (count > left)
+ count = (stbi_uc) left;
+
+ if (!stbi__readval(s,packet->channel,value)) return 0;
+
+ for(i=0; i<count; ++i,dest+=4)
+ stbi__copyval(packet->channel,dest,value);
+ left -= count;
+ }
+ }
+ break;
+
+ case 2: {//Mixed RLE
+ int left=width;
+ while (left>0) {
+ int count = stbi__get8(s), i;
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
+
+ if (count >= 128) { // Repeated
+ stbi_uc value[4];
+
+ if (count==128)
+ count = stbi__get16be(s);
+ else
+ count -= 127;
+ if (count > left)
+ return stbi__errpuc("bad file","scanline overrun");
+
+ if (!stbi__readval(s,packet->channel,value))
+ return 0;
+
+ for(i=0;i<count;++i, dest += 4)
+ stbi__copyval(packet->channel,dest,value);
+ } else { // Raw
+ ++count;
+ if (count>left) return stbi__errpuc("bad file","scanline overrun");
+
+ for(i=0;i<count;++i, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ }
+ left-=count;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *result;
+ int i, x,y, internal_comp;
+ STBI_NOTUSED(ri);
+
+ if (!comp) comp = &internal_comp;
+
+ for (i=0; i<92; ++i)
+ stbi__get8(s);
+
+ x = stbi__get16be(s);
+ y = stbi__get16be(s);
+
+ if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
+ if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode");
+
+ stbi__get32be(s); //skip `ratio'
+ stbi__get16be(s); //skip `fields'
+ stbi__get16be(s); //skip `pad'
+
+ // intermediate buffer is RGBA
+ result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);
+ if (!result) return stbi__errpuc("outofmem", "Out of memory");
+ memset(result, 0xff, x*y*4);
+
+ if (!stbi__pic_load_core(s,x,y,comp, result)) {
+ STBI_FREE(result);
+ result=0;
+ }
+ *px = x;
+ *py = y;
+ if (req_comp == 0) req_comp = *comp;
+ result=stbi__convert_format(result,4,req_comp,x,y);
+
+ return result;
+}
+
+static int stbi__pic_test(stbi__context *s)
+{
+ int r = stbi__pic_test_core(s);
+ stbi__rewind(s);
+ return r;
+}
+#endif
+
+// *************************************************************************************************
+// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
+
+#ifndef STBI_NO_GIF
+typedef struct
+{
+ stbi__int16 prefix;
+ stbi_uc first;
+ stbi_uc suffix;
+} stbi__gif_lzw;
+
+typedef struct
+{
+ int w,h;
+ stbi_uc *out; // output buffer (always 4 components)
+ stbi_uc *background; // The current "background" as far as a gif is concerned
+ stbi_uc *history;
+ int flags, bgindex, ratio, transparent, eflags;
+ stbi_uc pal[256][4];
+ stbi_uc lpal[256][4];
+ stbi__gif_lzw codes[8192];
+ stbi_uc *color_table;
+ int parse, step;
+ int lflags;
+ int start_x, start_y;
+ int max_x, max_y;
+ int cur_x, cur_y;
+ int line_size;
+ int delay;
+} stbi__gif;
+
+static int stbi__gif_test_raw(stbi__context *s)
+{
+ int sz;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
+ sz = stbi__get8(s);
+ if (sz != '9' && sz != '7') return 0;
+ if (stbi__get8(s) != 'a') return 0;
+ return 1;
+}
+
+static int stbi__gif_test(stbi__context *s)
+{
+ int r = stbi__gif_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
+{
+ int i;
+ for (i=0; i < num_entries; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ pal[i][3] = transp == i ? 0 : 255;
+ }
+}
+
+static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
+{
+ stbi_uc version;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
+ return stbi__err("not GIF", "Corrupt GIF");
+
+ version = stbi__get8(s);
+ if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
+ if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
+
+ stbi__g_failure_reason = "";
+ g->w = stbi__get16le(s);
+ g->h = stbi__get16le(s);
+ g->flags = stbi__get8(s);
+ g->bgindex = stbi__get8(s);
+ g->ratio = stbi__get8(s);
+ g->transparent = -1;
+
+ if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+
+ if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
+
+ if (is_info) return 1;
+
+ if (g->flags & 0x80)
+ stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
+
+ return 1;
+}
+
+static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
+ if (!g) return stbi__err("outofmem", "Out of memory");
+ if (!stbi__gif_header(s, g, comp, 1)) {
+ STBI_FREE(g);
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = g->w;
+ if (y) *y = g->h;
+ STBI_FREE(g);
+ return 1;
+}
+
+static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
+{
+ stbi_uc *p, *c;
+ int idx;
+
+ // recurse to decode the prefixes, since the linked-list is backwards,
+ // and working backwards through an interleaved image would be nasty
+ if (g->codes[code].prefix >= 0)
+ stbi__out_gif_code(g, g->codes[code].prefix);
+
+ if (g->cur_y >= g->max_y) return;
+
+ idx = g->cur_x + g->cur_y;
+ p = &g->out[idx];
+ g->history[idx / 4] = 1;
+
+ c = &g->color_table[g->codes[code].suffix * 4];
+ if (c[3] > 128) { // don't render transparent pixels;
+ p[0] = c[2];
+ p[1] = c[1];
+ p[2] = c[0];
+ p[3] = c[3];
+ }
+ g->cur_x += 4;
+
+ if (g->cur_x >= g->max_x) {
+ g->cur_x = g->start_x;
+ g->cur_y += g->step;
+
+ while (g->cur_y >= g->max_y && g->parse > 0) {
+ g->step = (1 << g->parse) * g->line_size;
+ g->cur_y = g->start_y + (g->step >> 1);
+ --g->parse;
+ }
+ }
+}
+
+static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
+{
+ stbi_uc lzw_cs;
+ stbi__int32 len, init_code;
+ stbi__uint32 first;
+ stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
+ stbi__gif_lzw *p;
+
+ lzw_cs = stbi__get8(s);
+ if (lzw_cs > 12) return NULL;
+ clear = 1 << lzw_cs;
+ first = 1;
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ bits = 0;
+ valid_bits = 0;
+ for (init_code = 0; init_code < clear; init_code++) {
+ g->codes[init_code].prefix = -1;
+ g->codes[init_code].first = (stbi_uc) init_code;
+ g->codes[init_code].suffix = (stbi_uc) init_code;
+ }
+
+ // support no starting clear code
+ avail = clear+2;
+ oldcode = -1;
+
+ len = 0;
+ for(;;) {
+ if (valid_bits < codesize) {
+ if (len == 0) {
+ len = stbi__get8(s); // start new block
+ if (len == 0)
+ return g->out;
+ }
+ --len;
+ bits |= (stbi__int32) stbi__get8(s) << valid_bits;
+ valid_bits += 8;
+ } else {
+ stbi__int32 code = bits & codemask;
+ bits >>= codesize;
+ valid_bits -= codesize;
+ // @OPTIMIZE: is there some way we can accelerate the non-clear path?
+ if (code == clear) { // clear code
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ avail = clear + 2;
+ oldcode = -1;
+ first = 0;
+ } else if (code == clear + 1) { // end of stream code
+ stbi__skip(s, len);
+ while ((len = stbi__get8(s)) > 0)
+ stbi__skip(s,len);
+ return g->out;
+ } else if (code <= avail) {
+ if (first) {
+ return stbi__errpuc("no clear code", "Corrupt GIF");
+ }
+
+ if (oldcode >= 0) {
+ p = &g->codes[avail++];
+ if (avail > 8192) {
+ return stbi__errpuc("too many codes", "Corrupt GIF");
+ }
+
+ p->prefix = (stbi__int16) oldcode;
+ p->first = g->codes[oldcode].first;
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;
+ } else if (code == avail)
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+
+ stbi__out_gif_code(g, (stbi__uint16) code);
+
+ if ((avail & codemask) == 0 && avail <= 0x0FFF) {
+ codesize++;
+ codemask = (1 << codesize) - 1;
+ }
+
+ oldcode = code;
+ } else {
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+ }
+ }
+ }
+}
+
+// this function is designed to support animated gifs, although stb_image doesn't support it
+// two back is the image from two frames ago, used for a very specific disposal format
+static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back)
+{
+ int dispose;
+ int first_frame;
+ int pi;
+ int pcount;
+ STBI_NOTUSED(req_comp);
+
+ // on first frame, any non-written pixels get the background colour (non-transparent)
+ first_frame = 0;
+ if (g->out == 0) {
+ if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
+ if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))
+ return stbi__errpuc("too large", "GIF image is too large");
+ pcount = g->w * g->h;
+ g->out = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->background = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->history = (stbi_uc *) stbi__malloc(pcount);
+ if (!g->out || !g->background || !g->history)
+ return stbi__errpuc("outofmem", "Out of memory");
+
+ // image is treated as "transparent" at the start - ie, nothing overwrites the current background;
+ // background colour is only used for pixels that are not rendered first frame, after that "background"
+ // color refers to the color that was there the previous frame.
+ memset(g->out, 0x00, 4 * pcount);
+ memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent)
+ memset(g->history, 0x00, pcount); // pixels that were affected previous frame
+ first_frame = 1;
+ } else {
+ // second frame - how do we dispose of the previous one?
+ dispose = (g->eflags & 0x1C) >> 2;
+ pcount = g->w * g->h;
+
+ if ((dispose == 3) && (two_back == 0)) {
+ dispose = 2; // if I don't have an image to revert back to, default to the old background
+ }
+
+ if (dispose == 3) { // use previous graphic
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 );
+ }
+ }
+ } else if (dispose == 2) {
+ // restore what was changed last frame to background before that frame;
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 );
+ }
+ }
+ } else {
+ // This is a non-disposal case eithe way, so just
+ // leave the pixels as is, and they will become the new background
+ // 1: do not dispose
+ // 0: not specified.
+ }
+
+ // background is what out is after the undoing of the previou frame;
+ memcpy( g->background, g->out, 4 * g->w * g->h );
+ }
+
+ // clear my history;
+ memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame
+
+ for (;;) {
+ int tag = stbi__get8(s);
+ switch (tag) {
+ case 0x2C: /* Image Descriptor */
+ {
+ stbi__int32 x, y, w, h;
+ stbi_uc *o;
+
+ x = stbi__get16le(s);
+ y = stbi__get16le(s);
+ w = stbi__get16le(s);
+ h = stbi__get16le(s);
+ if (((x + w) > (g->w)) || ((y + h) > (g->h)))
+ return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
+
+ g->line_size = g->w * 4;
+ g->start_x = x * 4;
+ g->start_y = y * g->line_size;
+ g->max_x = g->start_x + w * 4;
+ g->max_y = g->start_y + h * g->line_size;
+ g->cur_x = g->start_x;
+ g->cur_y = g->start_y;
+
+ // if the width of the specified rectangle is 0, that means
+ // we may not see *any* pixels or the image is malformed;
+ // to make sure this is caught, move the current y down to
+ // max_y (which is what out_gif_code checks).
+ if (w == 0)
+ g->cur_y = g->max_y;
+
+ g->lflags = stbi__get8(s);
+
+ if (g->lflags & 0x40) {
+ g->step = 8 * g->line_size; // first interlaced spacing
+ g->parse = 3;
+ } else {
+ g->step = g->line_size;
+ g->parse = 0;
+ }
+
+ if (g->lflags & 0x80) {
+ stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
+ g->color_table = (stbi_uc *) g->lpal;
+ } else if (g->flags & 0x80) {
+ g->color_table = (stbi_uc *) g->pal;
+ } else
+ return stbi__errpuc("missing color table", "Corrupt GIF");
+
+ o = stbi__process_gif_raster(s, g);
+ if (!o) return NULL;
+
+ // if this was the first frame,
+ pcount = g->w * g->h;
+ if (first_frame && (g->bgindex > 0)) {
+ // if first frame, any pixel not drawn to gets the background color
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi] == 0) {
+ g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be;
+ memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 );
+ }
+ }
+ }
+
+ return o;
+ }
+
+ case 0x21: // Comment Extension.
+ {
+ int len;
+ int ext = stbi__get8(s);
+ if (ext == 0xF9) { // Graphic Control Extension.
+ len = stbi__get8(s);
+ if (len == 4) {
+ g->eflags = stbi__get8(s);
+ g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths.
+
+ // unset old transparent
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 255;
+ }
+ if (g->eflags & 0x01) {
+ g->transparent = stbi__get8(s);
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 0;
+ }
+ } else {
+ // don't need transparent
+ stbi__skip(s, 1);
+ g->transparent = -1;
+ }
+ } else {
+ stbi__skip(s, len);
+ break;
+ }
+ }
+ while ((len = stbi__get8(s)) != 0) {
+ stbi__skip(s, len);
+ }
+ break;
+ }
+
+ case 0x3B: // gif stream termination code
+ return (stbi_uc *) s; // using '1' causes warning on some compilers
+
+ default:
+ return stbi__errpuc("unknown code", "Corrupt GIF");
+ }
+ }
+}
+
+static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)
+{
+ STBI_FREE(g->out);
+ STBI_FREE(g->history);
+ STBI_FREE(g->background);
+
+ if (out) STBI_FREE(out);
+ if (delays && *delays) STBI_FREE(*delays);
+ return stbi__errpuc("outofmem", "Out of memory");
+}
+
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ if (stbi__gif_test(s)) {
+ int layers = 0;
+ stbi_uc *u = 0;
+ stbi_uc *out = 0;
+ stbi_uc *two_back = 0;
+ stbi__gif g;
+ int stride;
+ int out_size = 0;
+ int delays_size = 0;
+
+ STBI_NOTUSED(out_size);
+ STBI_NOTUSED(delays_size);
+
+ memset(&g, 0, sizeof(g));
+ if (delays) {
+ *delays = 0;
+ }
+
+ do {
+ u = stbi__gif_load_next(s, &g, comp, req_comp, two_back);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+ ++layers;
+ stride = g.w * g.h * 4;
+
+ if (out) {
+ void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );
+ if (!tmp)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ else {
+ out = (stbi_uc*) tmp;
+ out_size = layers * stride;
+ }
+
+ if (delays) {
+ int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );
+ if (!new_delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ *delays = new_delays;
+ delays_size = layers * sizeof(int);
+ }
+ } else {
+ out = (stbi_uc*)stbi__malloc( layers * stride );
+ if (!out)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ out_size = layers * stride;
+ if (delays) {
+ *delays = (int*) stbi__malloc( layers * sizeof(int) );
+ if (!*delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ delays_size = layers * sizeof(int);
+ }
+ }
+ memcpy( out + ((layers - 1) * stride), u, stride );
+ if (layers >= 2) {
+ two_back = out - 2 * stride;
+ }
+
+ if (delays) {
+ (*delays)[layers - 1U] = g.delay;
+ }
+ }
+ } while (u != 0);
+
+ // free temp buffer;
+ STBI_FREE(g.out);
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ // do the final conversion after loading everything;
+ if (req_comp && req_comp != 4)
+ out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h);
+
+ *z = layers;
+ return out;
+ } else {
+ return stbi__errpuc("not GIF", "Image was not as a gif type.");
+ }
+}
+
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *u = 0;
+ stbi__gif g;
+ memset(&g, 0, sizeof(g));
+ STBI_NOTUSED(ri);
+
+ u = stbi__gif_load_next(s, &g, comp, req_comp, 0);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+
+ // moved conversion to after successful load so that the same
+ // can be done for multiple frames.
+ if (req_comp && req_comp != 4)
+ u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
+ } else if (g.out) {
+ // if there was an error and we allocated an image buffer, free it!
+ STBI_FREE(g.out);
+ }
+
+ // free buffers needed for multiple frame loading;
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ return u;
+}
+
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ return stbi__gif_info_raw(s,x,y,comp);
+}
+#endif
+
+// *************************************************************************************************
+// Radiance RGBE HDR loader
+// originally by Nicolas Schulz
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test_core(stbi__context *s, const char *signature)
+{
+ int i;
+ for (i=0; signature[i]; ++i)
+ if (stbi__get8(s) != signature[i])
+ return 0;
+ stbi__rewind(s);
+ return 1;
+}
+
+static int stbi__hdr_test(stbi__context* s)
+{
+ int r = stbi__hdr_test_core(s, "#?RADIANCE\n");
+ stbi__rewind(s);
+ if(!r) {
+ r = stbi__hdr_test_core(s, "#?RGBE\n");
+ stbi__rewind(s);
+ }
+ return r;
+}
+
+#define STBI__HDR_BUFLEN 1024
+static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
+{
+ int len=0;
+ char c = '\0';
+
+ c = (char) stbi__get8(z);
+
+ while (!stbi__at_eof(z) && c != '\n') {
+ buffer[len++] = c;
+ if (len == STBI__HDR_BUFLEN-1) {
+ // flush to end of line
+ while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
+ ;
+ break;
+ }
+ c = (char) stbi__get8(z);
+ }
+
+ buffer[len] = 0;
+ return buffer;
+}
+
+static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
+{
+ if ( input[3] != 0 ) {
+ float f1;
+ // Exponent
+ f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
+ if (req_comp <= 2)
+ output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
+ else {
+ output[0] = input[0] * f1;
+ output[1] = input[1] * f1;
+ output[2] = input[2] * f1;
+ }
+ if (req_comp == 2) output[1] = 1;
+ if (req_comp == 4) output[3] = 1;
+ } else {
+ switch (req_comp) {
+ case 4: output[3] = 1; /* fallthrough */
+ case 3: output[0] = output[1] = output[2] = 0;
+ break;
+ case 2: output[1] = 1; /* fallthrough */
+ case 1: output[0] = 0;
+ break;
+ }
+ }
+}
+
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int width, height;
+ stbi_uc *scanline;
+ float *hdr_data;
+ int len;
+ unsigned char count, value;
+ int i, j, k, c1,c2, z;
+ const char *headerToken;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ headerToken = stbi__hdr_gettoken(s,buffer);
+ if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)
+ return stbi__errpf("not HDR", "Corrupt HDR image");
+
+ // Parse header
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
+
+ // Parse width and height
+ // can't use sscanf() if we're not using stdio!
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ height = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ width = (int) strtol(token, NULL, 10);
+
+ if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+ if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+
+ *x = width;
+ *y = height;
+
+ if (comp) *comp = 3;
+ if (req_comp == 0) req_comp = 3;
+
+ if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))
+ return stbi__errpf("too large", "HDR image is too large");
+
+ // Read data
+ hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);
+ if (!hdr_data)
+ return stbi__errpf("outofmem", "Out of memory");
+
+ // Load image data
+ // image data is stored as some number of sca
+ if ( width < 8 || width >= 32768) {
+ // Read flat data
+ for (j=0; j < height; ++j) {
+ for (i=0; i < width; ++i) {
+ stbi_uc rgbe[4];
+ main_decode_loop:
+ stbi__getn(s, rgbe, 4);
+ stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
+ }
+ }
+ } else {
+ // Read RLE-encoded data
+ scanline = NULL;
+
+ for (j = 0; j < height; ++j) {
+ c1 = stbi__get8(s);
+ c2 = stbi__get8(s);
+ len = stbi__get8(s);
+ if (c1 != 2 || c2 != 2 || (len & 0x80)) {
+ // not run-length encoded, so we have to actually use THIS data as a decoded
+ // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
+ stbi_uc rgbe[4];
+ rgbe[0] = (stbi_uc) c1;
+ rgbe[1] = (stbi_uc) c2;
+ rgbe[2] = (stbi_uc) len;
+ rgbe[3] = (stbi_uc) stbi__get8(s);
+ stbi__hdr_convert(hdr_data, rgbe, req_comp);
+ i = 1;
+ j = 0;
+ STBI_FREE(scanline);
+ goto main_decode_loop; // yes, this makes no sense
+ }
+ len <<= 8;
+ len |= stbi__get8(s);
+ if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
+ if (scanline == NULL) {
+ scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);
+ if (!scanline) {
+ STBI_FREE(hdr_data);
+ return stbi__errpf("outofmem", "Out of memory");
+ }
+ }
+
+ for (k = 0; k < 4; ++k) {
+ int nleft;
+ i = 0;
+ while ((nleft = width - i) > 0) {
+ count = stbi__get8(s);
+ if (count > 128) {
+ // Run
+ value = stbi__get8(s);
+ count -= 128;
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = value;
+ } else {
+ // Dump
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = stbi__get8(s);
+ }
+ }
+ }
+ for (i=0; i < width; ++i)
+ stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
+ }
+ if (scanline)
+ STBI_FREE(scanline);
+ }
+
+ return hdr_data;
+}
+
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int dummy;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (stbi__hdr_test(s) == 0) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *y = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *x = (int) strtol(token, NULL, 10);
+ *comp = 3;
+ return 1;
+}
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ void *p;
+ stbi__bmp_data info;
+
+ info.all_a = 255;
+ p = stbi__bmp_parse_header(s, &info);
+ if (p == NULL) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = s->img_x;
+ if (y) *y = s->img_y;
+ if (comp) {
+ if (info.bpp == 24 && info.ma == 0xff000000)
+ *comp = 3;
+ else
+ *comp = info.ma ? 4 : 3;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int channelCount, dummy, depth;
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *y = stbi__get32be(s);
+ *x = stbi__get32be(s);
+ depth = stbi__get16be(s);
+ if (depth != 8 && depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 3) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *comp = 4;
+ return 1;
+}
+
+static int stbi__psd_is16(stbi__context *s)
+{
+ int channelCount, depth;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ STBI_NOTUSED(stbi__get32be(s));
+ STBI_NOTUSED(stbi__get32be(s));
+ depth = stbi__get16be(s);
+ if (depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int act_comp=0,num_packets=0,chained,dummy;
+ stbi__pic_packet packets[10];
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ stbi__skip(s, 88);
+
+ *x = stbi__get16be(s);
+ *y = stbi__get16be(s);
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s);
+ return 0;
+ }
+ if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ stbi__skip(s, 8);
+
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return 0;
+
+ packet = &packets[num_packets++];
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (packet->size != 8) {
+ stbi__rewind( s );
+ return 0;
+ }
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3);
+
+ return 1;
+}
+#endif
+
+// *************************************************************************************************
+// Portable Gray Map and Portable Pixel Map loader
+// by Ken Miller
+//
+// PGM: http://netpbm.sourceforge.net/doc/pgm.html
+// PPM: http://netpbm.sourceforge.net/doc/ppm.html
+//
+// Known limitations:
+// Does not support comments in the header section
+// Does not support ASCII image data (formats P2 and P3)
+
+#ifndef STBI_NO_PNM
+
+static int stbi__pnm_test(stbi__context *s)
+{
+ char p, t;
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);
+ if (ri->bits_per_channel == 0)
+ return 0;
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+
+ if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
+ return stbi__errpuc("too large", "PNM too large");
+
+ out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {
+ STBI_FREE(out);
+ return stbi__errpuc("bad PNM", "PNM file truncated");
+ }
+
+ if (req_comp && req_comp != s->img_n) {
+ if (ri->bits_per_channel == 16) {
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);
+ } else {
+ out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
+ }
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+ return out;
+}
+
+static int stbi__pnm_isspace(char c)
+{
+ return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
+}
+
+static void stbi__pnm_skip_whitespace(stbi__context *s, char *c)
+{
+ for (;;) {
+ while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
+ *c = (char) stbi__get8(s);
+
+ if (stbi__at_eof(s) || *c != '#')
+ break;
+
+ while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' )
+ *c = (char) stbi__get8(s);
+ }
+}
+
+static int stbi__pnm_isdigit(char c)
+{
+ return c >= '0' && c <= '9';
+}
+
+static int stbi__pnm_getinteger(stbi__context *s, char *c)
+{
+ int value = 0;
+
+ while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
+ value = value*10 + (*c - '0');
+ *c = (char) stbi__get8(s);
+ if((value > 214748364) || (value == 214748364 && *c > '7'))
+ return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int");
+ }
+
+ return value;
+}
+
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int maxv, dummy;
+ char c, p, t;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ stbi__rewind(s);
+
+ // Get identifier
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
+
+ c = (char) stbi__get8(s);
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *x = stbi__pnm_getinteger(s, &c); // read width
+ if(*x == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *y = stbi__pnm_getinteger(s, &c); // read height
+ if (*y == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ maxv = stbi__pnm_getinteger(s, &c); // read max value
+ if (maxv > 65535)
+ return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");
+ else if (maxv > 255)
+ return 16;
+ else
+ return 8;
+}
+
+static int stbi__pnm_is16(stbi__context *s)
+{
+ if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)
+ return 1;
+ return 0;
+}
+#endif
+
+static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
+{
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNG
+ if (stbi__png_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_info(s, x, y, comp)) return 1;
+ #endif
+
+ // test tga last because it's a crappy test!
+ #ifndef STBI_NO_TGA
+ if (stbi__tga_info(s, x, y, comp))
+ return 1;
+ #endif
+ return stbi__err("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static int stbi__is_16_main(stbi__context *s)
+{
+ #ifndef STBI_NO_PNG
+ if (stbi__png_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_is16(s)) return 1;
+ #endif
+ return 0;
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_info_from_file(f, x, y, comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__info_main(&s,x,y,comp);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+
+STBIDEF int stbi_is_16_bit(char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_is_16_bit_from_file(f);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_is_16_bit_from_file(FILE *f)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__is_16_main(&s);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__is_16_main(&s);
+}
+
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__is_16_main(&s);
+}
+
+#endif // STB_IMAGE_IMPLEMENTATION
+
+/*
+ revision history:
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug
+ 1-bit BMP
+ *_is_16_bit api
+ avoid warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants;
+ STBI_NO_STDIO works again;
+ compilation fixes;
+ fix rounding in unpremultiply;
+ optimize vertical flip;
+ disable raw_len validation;
+ documentation fixes
+ 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode;
+ warning fixes; disable run-time SSE detection on gcc;
+ uniform handling of optional "return" values;
+ thread-safe initialization of zlib tables
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) allocate large structures on the stack
+ remove white matting for transparent PSD
+ fix reported channel count for PNG & BMP
+ re-enable SSE2 in non-gcc 64-bit
+ support RGB-formatted JPEG
+ read 16-bit PNGs (only as 8-bit)
+ 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED
+ 2.09 (2016-01-16) allow comments in PNM files
+ 16-bit-per-pixel TGA (not bit-per-component)
+ info() for TGA could break due to .hdr handling
+ info() for BMP to shares code instead of sloppy parse
+ can use STBI_REALLOC_SIZED if allocator doesn't support realloc
+ code cleanup
+ 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
+ 2.07 (2015-09-13) fix compiler warnings
+ partial animated GIF support
+ limited 16-bpc PSD support
+ #ifdef unused functions
+ bug with < 92 byte PIC,PNM,HDR,TGA
+ 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
+ 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
+ 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
+ 2.03 (2015-04-12) extra corruption checking (mmozeiko)
+ stbi_set_flip_vertically_on_load (nguillemot)
+ fix NEON support; fix mingw support
+ 2.02 (2015-01-19) fix incorrect assert, fix warning
+ 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
+ 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
+ 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
+ progressive JPEG (stb)
+ PGM/PPM support (Ken Miller)
+ STBI_MALLOC,STBI_REALLOC,STBI_FREE
+ GIF bugfix -- seemingly never worked
+ STBI_NO_*, STBI_ONLY_*
+ 1.48 (2014-12-14) fix incorrectly-named assert()
+ 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
+ optimize PNG (ryg)
+ fix bug in interlaced PNG with user-specified channel count (stb)
+ 1.46 (2014-08-26)
+ fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
+ 1.45 (2014-08-16)
+ fix MSVC-ARM internal compiler error by wrapping malloc
+ 1.44 (2014-08-07)
+ various warning fixes from Ronny Chevalier
+ 1.43 (2014-07-15)
+ fix MSVC-only compiler problem in code changed in 1.42
+ 1.42 (2014-07-09)
+ don't define _CRT_SECURE_NO_WARNINGS (affects user code)
+ fixes to stbi__cleanup_jpeg path
+ added STBI_ASSERT to avoid requiring assert.h
+ 1.41 (2014-06-25)
+ fix search&replace from 1.36 that messed up comments/error messages
+ 1.40 (2014-06-22)
+ fix gcc struct-initialization warning
+ 1.39 (2014-06-15)
+ fix to TGA optimization when req_comp != number of components in TGA;
+ fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
+ add support for BMP version 5 (more ignored fields)
+ 1.38 (2014-06-06)
+ suppress MSVC warnings on integer casts truncating values
+ fix accidental rename of 'skip' field of I/O
+ 1.37 (2014-06-04)
+ remove duplicate typedef
+ 1.36 (2014-06-03)
+ convert to header file single-file library
+ if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
+ 1.35 (2014-05-27)
+ various warnings
+ fix broken STBI_SIMD path
+ fix bug where stbi_load_from_file no longer left file pointer in correct place
+ fix broken non-easy path for 32-bit BMP (possibly never used)
+ TGA optimization by Arseny Kapoulkine
+ 1.34 (unknown)
+ use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
+ 1.33 (2011-07-14)
+ make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
+ 1.32 (2011-07-13)
+ support for "info" function for all supported filetypes (SpartanJ)
+ 1.31 (2011-06-20)
+ a few more leak fixes, bug in PNG handling (SpartanJ)
+ 1.30 (2011-06-11)
+ added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
+ removed deprecated format-specific test/load functions
+ removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
+ error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
+ fix inefficiency in decoding 32-bit BMP (David Woo)
+ 1.29 (2010-08-16)
+ various warning fixes from Aurelien Pocheville
+ 1.28 (2010-08-01)
+ fix bug in GIF palette transparency (SpartanJ)
+ 1.27 (2010-08-01)
+ cast-to-stbi_uc to fix warnings
+ 1.26 (2010-07-24)
+ fix bug in file buffering for PNG reported by SpartanJ
+ 1.25 (2010-07-17)
+ refix trans_data warning (Won Chun)
+ 1.24 (2010-07-12)
+ perf improvements reading from files on platforms with lock-heavy fgetc()
+ minor perf improvements for jpeg
+ deprecated type-specific functions so we'll get feedback if they're needed
+ attempt to fix trans_data warning (Won Chun)
+ 1.23 fixed bug in iPhone support
+ 1.22 (2010-07-10)
+ removed image *writing* support
+ stbi_info support from Jetro Lauha
+ GIF support from Jean-Marc Lienher
+ iPhone PNG-extensions from James Brown
+ warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
+ 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
+ 1.20 added support for Softimage PIC, by Tom Seddon
+ 1.19 bug in interlaced PNG corruption check (found by ryg)
+ 1.18 (2008-08-02)
+ fix a threading bug (local mutable static)
+ 1.17 support interlaced PNG
+ 1.16 major bugfix - stbi__convert_format converted one too many pixels
+ 1.15 initialize some fields for thread safety
+ 1.14 fix threadsafe conversion bug
+ header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
+ 1.13 threadsafe
+ 1.12 const qualifiers in the API
+ 1.11 Support installable IDCT, colorspace conversion routines
+ 1.10 Fixes for 64-bit (don't use "unsigned long")
+ optimized upsampling by Fabian "ryg" Giesen
+ 1.09 Fix format-conversion for PSD code (bad global variables!)
+ 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
+ 1.07 attempt to fix C++ warning/errors again
+ 1.06 attempt to fix C++ warning/errors again
+ 1.05 fix TGA loading to return correct *comp and use good luminance calc
+ 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
+ 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
+ 1.02 support for (subset of) HDR files, float interface for preferred access to them
+ 1.01 fix bug: possible bug in handling right-side up bmps... not sure
+ fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
+ 1.00 interface to zlib that skips zlib header
+ 0.99 correct handling of alpha in palette
+ 0.98 TGA loader by lonesock; dynamically add loaders (untested)
+ 0.97 jpeg errors on too large a file; also catch another malloc failure
+ 0.96 fix detection of invalid v value - particleman@mollyrocket forum
+ 0.95 during header scan, seek to markers in case of padding
+ 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
+ 0.93 handle jpegtran output; verbose errors
+ 0.92 read 4,8,16,24,32-bit BMP files of several formats
+ 0.91 output 24-bit Windows 3.0 BMP files
+ 0.90 fix a few more warnings; bump version number to approach 1.0
+ 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
+ 0.60 fix compiling as c++
+ 0.59 fix warnings: merge Dave Moore's -Wall fixes
+ 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
+ 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
+ 0.56 fix bug: zlib uncompressed mode len vs. nlen
+ 0.55 fix bug: restart_interval not initialized to 0
+ 0.54 allow NULL for 'int *comp'
+ 0.53 fix bug in png 3->4; speedup png decoding
+ 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
+ 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
+ on 'test' only check type, not whether we support this variant
+ 0.50 (2006-11-19)
+ first released version
+*/
+
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/third_party/stb/stb_image_write.h b/third_party/stb/stb_image_write.h
new file mode 100644
index 00000000..e4b32ed1
--- /dev/null
+++ b/third_party/stb/stb_image_write.h
@@ -0,0 +1,1724 @@
+/* stb_image_write - v1.16 - public domain - http://nothings.org/stb
+ writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
+ no warranty implied; use at your own risk
+
+ Before #including,
+
+ #define STB_IMAGE_WRITE_IMPLEMENTATION
+
+ in the file that you want to have the implementation.
+
+ Will probably not work correctly with strict-aliasing optimizations.
+
+ABOUT:
+
+ This header file is a library for writing images to C stdio or a callback.
+
+ The PNG output is not optimal; it is 20-50% larger than the file
+ written by a decent optimizing implementation; though providing a custom
+ zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that.
+ This library is designed for source code compactness and simplicity,
+ not optimal image file size or run-time performance.
+
+BUILDING:
+
+ You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h.
+ You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace
+ malloc,realloc,free.
+ You can #define STBIW_MEMMOVE() to replace memmove()
+ You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function
+ for PNG compression (instead of the builtin one), it must have the following signature:
+ unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality);
+ The returned data will be freed with STBIW_FREE() (free() by default),
+ so it must be heap allocated with STBIW_MALLOC() (malloc() by default),
+
+UNICODE:
+
+ If compiling for Windows and you wish to use Unicode filenames, compile
+ with
+ #define STBIW_WINDOWS_UTF8
+ and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert
+ Windows wchar_t filenames to utf8.
+
+USAGE:
+
+ There are five functions, one for each image file format:
+
+ int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+ int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+ int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+ int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality);
+ int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);
+
+ void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically
+
+ There are also five equivalent functions that use an arbitrary write function. You are
+ expected to open/close your file-equivalent before and after calling these:
+
+ int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes);
+ int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+ int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+ int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);
+ int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);
+
+ where the callback is:
+ void stbi_write_func(void *context, void *data, int size);
+
+ You can configure it with these global variables:
+ int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE
+ int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression
+ int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode
+
+
+ You can define STBI_WRITE_NO_STDIO to disable the file variant of these
+ functions, so the library will not use stdio.h at all. However, this will
+ also disable HDR writing, because it requires stdio for formatted output.
+
+ Each function returns 0 on failure and non-0 on success.
+
+ The functions create an image file defined by the parameters. The image
+ is a rectangle of pixels stored from left-to-right, top-to-bottom.
+ Each pixel contains 'comp' channels of data stored interleaved with 8-bits
+ per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is
+ monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall.
+ The *data pointer points to the first byte of the top-left-most pixel.
+ For PNG, "stride_in_bytes" is the distance in bytes from the first byte of
+ a row of pixels to the first byte of the next row of pixels.
+
+ PNG creates output files with the same number of components as the input.
+ The BMP format expands Y to RGB in the file format and does not
+ output alpha.
+
+ PNG supports writing rectangles of data even when the bytes storing rows of
+ data are not consecutive in memory (e.g. sub-rectangles of a larger image),
+ by supplying the stride between the beginning of adjacent rows. The other
+ formats do not. (Thus you cannot write a native-format BMP through the BMP
+ writer, both because it is in BGR order and because it may have padding
+ at the end of the line.)
+
+ PNG allows you to set the deflate compression level by setting the global
+ variable 'stbi_write_png_compression_level' (it defaults to 8).
+
+ HDR expects linear float data. Since the format is always 32-bit rgb(e)
+ data, alpha (if provided) is discarded, and for monochrome data it is
+ replicated across all three channels.
+
+ TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed
+ data, set the global variable 'stbi_write_tga_with_rle' to 0.
+
+ JPEG does ignore alpha channels in input data; quality is between 1 and 100.
+ Higher quality looks better but results in a bigger image.
+ JPEG baseline (no JPEG progressive).
+
+CREDITS:
+
+
+ Sean Barrett - PNG/BMP/TGA
+ Baldur Karlsson - HDR
+ Jean-Sebastien Guay - TGA monochrome
+ Tim Kelsey - misc enhancements
+ Alan Hickman - TGA RLE
+ Emmanuel Julien - initial file IO callback implementation
+ Jon Olick - original jo_jpeg.cpp code
+ Daniel Gibson - integrate JPEG, allow external zlib
+ Aarni Koskela - allow choosing PNG filter
+
+ bugfixes:
+ github:Chribba
+ Guillaume Chereau
+ github:jry2
+ github:romigrou
+ Sergio Gonzalez
+ Jonas Karlsson
+ Filip Wasil
+ Thatcher Ulrich
+ github:poppolopoppo
+ Patrick Boettcher
+ github:xeekworx
+ Cap Petschulat
+ Simon Rodriguez
+ Ivan Tikhonov
+ github:ignotion
+ Adam Schackart
+ Andrew Kensler
+
+LICENSE
+
+ See end of file for license information.
+
+*/
+
+#ifndef INCLUDE_STB_IMAGE_WRITE_H
+#define INCLUDE_STB_IMAGE_WRITE_H
+
+#include <stdlib.h>
+
+// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline'
+#ifndef STBIWDEF
+#ifdef STB_IMAGE_WRITE_STATIC
+#define STBIWDEF static
+#else
+#ifdef __cplusplus
+#define STBIWDEF extern "C"
+#else
+#define STBIWDEF extern
+#endif
+#endif
+#endif
+
+#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations
+STBIWDEF int stbi_write_tga_with_rle;
+STBIWDEF int stbi_write_png_compression_level;
+STBIWDEF int stbi_write_force_png_filter;
+#endif
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);
+STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality);
+
+#ifdef STBIW_WINDOWS_UTF8
+STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
+#endif
+#endif
+
+typedef void stbi_write_func(void *context, void *data, int size);
+
+STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes);
+STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);
+STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);
+
+STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean);
+
+#endif//INCLUDE_STB_IMAGE_WRITE_H
+
+#ifdef STB_IMAGE_WRITE_IMPLEMENTATION
+
+#ifdef _WIN32
+ #ifndef _CRT_SECURE_NO_WARNINGS
+ #define _CRT_SECURE_NO_WARNINGS
+ #endif
+ #ifndef _CRT_NONSTDC_NO_DEPRECATE
+ #define _CRT_NONSTDC_NO_DEPRECATE
+ #endif
+#endif
+
+#ifndef STBI_WRITE_NO_STDIO
+#include <stdio.h>
+#endif // STBI_WRITE_NO_STDIO
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED))
+// ok
+#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED)
+// ok
+#else
+#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)."
+#endif
+
+#ifndef STBIW_MALLOC
+#define STBIW_MALLOC(sz) malloc(sz)
+#define STBIW_REALLOC(p,newsz) realloc(p,newsz)
+#define STBIW_FREE(p) free(p)
+#endif
+
+#ifndef STBIW_REALLOC_SIZED
+#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz)
+#endif
+
+
+#ifndef STBIW_MEMMOVE
+#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz)
+#endif
+
+
+#ifndef STBIW_ASSERT
+#include <assert.h>
+#define STBIW_ASSERT(x) assert(x)
+#endif
+
+#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff)
+
+#ifdef STB_IMAGE_WRITE_STATIC
+static int stbi_write_png_compression_level = 8;
+static int stbi_write_tga_with_rle = 1;
+static int stbi_write_force_png_filter = -1;
+#else
+int stbi_write_png_compression_level = 8;
+int stbi_write_tga_with_rle = 1;
+int stbi_write_force_png_filter = -1;
+#endif
+
+static int stbi__flip_vertically_on_write = 0;
+
+STBIWDEF void stbi_flip_vertically_on_write(int flag)
+{
+ stbi__flip_vertically_on_write = flag;
+}
+
+typedef struct
+{
+ stbi_write_func *func;
+ void *context;
+ unsigned char buffer[64];
+ int buf_used;
+} stbi__write_context;
+
+// initialize a callback-based context
+static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context)
+{
+ s->func = c;
+ s->context = context;
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+
+static void stbi__stdio_write(void *context, void *data, int size)
+{
+ fwrite(data,1,size,(FILE*) context);
+}
+
+#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)
+#ifdef __cplusplus
+#define STBIW_EXTERN extern "C"
+#else
+#define STBIW_EXTERN extern
+#endif
+STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
+STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
+
+STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
+{
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
+}
+#endif
+
+static FILE *stbiw__fopen(char const *filename, char const *mode)
+{
+ FILE *f;
+#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)
+ wchar_t wMode[64];
+ wchar_t wFilename[1024];
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
+ return 0;
+
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
+ return 0;
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != _wfopen_s(&f, wFilename, wMode))
+ f = 0;
+#else
+ f = _wfopen(wFilename, wMode);
+#endif
+
+#elif defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != fopen_s(&f, filename, mode))
+ f=0;
+#else
+ f = fopen(filename, mode);
+#endif
+ return f;
+}
+
+static int stbi__start_write_file(stbi__write_context *s, const char *filename)
+{
+ FILE *f = stbiw__fopen(filename, "wb");
+ stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f);
+ return f != NULL;
+}
+
+static void stbi__end_write_file(stbi__write_context *s)
+{
+ fclose((FILE *)s->context);
+}
+
+#endif // !STBI_WRITE_NO_STDIO
+
+typedef unsigned int stbiw_uint32;
+typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
+
+static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v)
+{
+ while (*fmt) {
+ switch (*fmt++) {
+ case ' ': break;
+ case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int));
+ s->func(s->context,&x,1);
+ break; }
+ case '2': { int x = va_arg(v,int);
+ unsigned char b[2];
+ b[0] = STBIW_UCHAR(x);
+ b[1] = STBIW_UCHAR(x>>8);
+ s->func(s->context,b,2);
+ break; }
+ case '4': { stbiw_uint32 x = va_arg(v,int);
+ unsigned char b[4];
+ b[0]=STBIW_UCHAR(x);
+ b[1]=STBIW_UCHAR(x>>8);
+ b[2]=STBIW_UCHAR(x>>16);
+ b[3]=STBIW_UCHAR(x>>24);
+ s->func(s->context,b,4);
+ break; }
+ default:
+ STBIW_ASSERT(0);
+ return;
+ }
+ }
+}
+
+static void stbiw__writef(stbi__write_context *s, const char *fmt, ...)
+{
+ va_list v;
+ va_start(v, fmt);
+ stbiw__writefv(s, fmt, v);
+ va_end(v);
+}
+
+static void stbiw__write_flush(stbi__write_context *s)
+{
+ if (s->buf_used) {
+ s->func(s->context, &s->buffer, s->buf_used);
+ s->buf_used = 0;
+ }
+}
+
+static void stbiw__putc(stbi__write_context *s, unsigned char c)
+{
+ s->func(s->context, &c, 1);
+}
+
+static void stbiw__write1(stbi__write_context *s, unsigned char a)
+{
+ if ((size_t)s->buf_used + 1 > sizeof(s->buffer))
+ stbiw__write_flush(s);
+ s->buffer[s->buf_used++] = a;
+}
+
+static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c)
+{
+ int n;
+ if ((size_t)s->buf_used + 3 > sizeof(s->buffer))
+ stbiw__write_flush(s);
+ n = s->buf_used;
+ s->buf_used = n+3;
+ s->buffer[n+0] = a;
+ s->buffer[n+1] = b;
+ s->buffer[n+2] = c;
+}
+
+static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d)
+{
+ unsigned char bg[3] = { 255, 0, 255}, px[3];
+ int k;
+
+ if (write_alpha < 0)
+ stbiw__write1(s, d[comp - 1]);
+
+ switch (comp) {
+ case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case
+ case 1:
+ if (expand_mono)
+ stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp
+ else
+ stbiw__write1(s, d[0]); // monochrome TGA
+ break;
+ case 4:
+ if (!write_alpha) {
+ // composite against pink background
+ for (k = 0; k < 3; ++k)
+ px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255;
+ stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]);
+ break;
+ }
+ /* FALLTHROUGH */
+ case 3:
+ stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]);
+ break;
+ }
+ if (write_alpha > 0)
+ stbiw__write1(s, d[comp - 1]);
+}
+
+static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono)
+{
+ stbiw_uint32 zero = 0;
+ int i,j, j_end;
+
+ if (y <= 0)
+ return;
+
+ if (stbi__flip_vertically_on_write)
+ vdir *= -1;
+
+ if (vdir < 0) {
+ j_end = -1; j = y-1;
+ } else {
+ j_end = y; j = 0;
+ }
+
+ for (; j != j_end; j += vdir) {
+ for (i=0; i < x; ++i) {
+ unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
+ stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d);
+ }
+ stbiw__write_flush(s);
+ s->func(s->context, &zero, scanline_pad);
+ }
+}
+
+static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...)
+{
+ if (y < 0 || x < 0) {
+ return 0;
+ } else {
+ va_list v;
+ va_start(v, fmt);
+ stbiw__writefv(s, fmt, v);
+ va_end(v);
+ stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono);
+ return 1;
+ }
+}
+
+static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data)
+{
+ if (comp != 4) {
+ // write RGB bitmap
+ int pad = (-x*3) & 3;
+ return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad,
+ "11 4 22 4" "4 44 22 444444",
+ 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
+ 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
+ } else {
+ // RGBA bitmaps need a v4 header
+ // use BI_BITFIELDS mode with 32bpp and alpha mask
+ // (straight BI_RGB with alpha mask doesn't work in most readers)
+ return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0,
+ "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444",
+ 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header
+ 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header
+ }
+}
+
+STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_bmp_core(&s, x, y, comp, data);
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_bmp_core(&s, x, y, comp, data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif //!STBI_WRITE_NO_STDIO
+
+static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data)
+{
+ int has_alpha = (comp == 2 || comp == 4);
+ int colorbytes = has_alpha ? comp-1 : comp;
+ int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3
+
+ if (y < 0 || x < 0)
+ return 0;
+
+ if (!stbi_write_tga_with_rle) {
+ return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0,
+ "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8);
+ } else {
+ int i,j,k;
+ int jend, jdir;
+
+ stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8);
+
+ if (stbi__flip_vertically_on_write) {
+ j = 0;
+ jend = y;
+ jdir = 1;
+ } else {
+ j = y-1;
+ jend = -1;
+ jdir = -1;
+ }
+ for (; j != jend; j += jdir) {
+ unsigned char *row = (unsigned char *) data + j * x * comp;
+ int len;
+
+ for (i = 0; i < x; i += len) {
+ unsigned char *begin = row + i * comp;
+ int diff = 1;
+ len = 1;
+
+ if (i < x - 1) {
+ ++len;
+ diff = memcmp(begin, row + (i + 1) * comp, comp);
+ if (diff) {
+ const unsigned char *prev = begin;
+ for (k = i + 2; k < x && len < 128; ++k) {
+ if (memcmp(prev, row + k * comp, comp)) {
+ prev += comp;
+ ++len;
+ } else {
+ --len;
+ break;
+ }
+ }
+ } else {
+ for (k = i + 2; k < x && len < 128; ++k) {
+ if (!memcmp(begin, row + k * comp, comp)) {
+ ++len;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ if (diff) {
+ unsigned char header = STBIW_UCHAR(len - 1);
+ stbiw__write1(s, header);
+ for (k = 0; k < len; ++k) {
+ stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp);
+ }
+ } else {
+ unsigned char header = STBIW_UCHAR(len - 129);
+ stbiw__write1(s, header);
+ stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin);
+ }
+ }
+ }
+ stbiw__write_flush(s);
+ }
+ return 1;
+}
+
+STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_tga_core(&s, x, y, comp, (void *) data);
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_tga_core(&s, x, y, comp, (void *) data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif
+
+// *************************************************************************************************
+// Radiance RGBE HDR writer
+// by Baldur Karlsson
+
+#define stbiw__max(a, b) ((a) > (b) ? (a) : (b))
+
+#ifndef STBI_WRITE_NO_STDIO
+
+static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear)
+{
+ int exponent;
+ float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2]));
+
+ if (maxcomp < 1e-32f) {
+ rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
+ } else {
+ float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp;
+
+ rgbe[0] = (unsigned char)(linear[0] * normalize);
+ rgbe[1] = (unsigned char)(linear[1] * normalize);
+ rgbe[2] = (unsigned char)(linear[2] * normalize);
+ rgbe[3] = (unsigned char)(exponent + 128);
+ }
+}
+
+static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte)
+{
+ unsigned char lengthbyte = STBIW_UCHAR(length+128);
+ STBIW_ASSERT(length+128 <= 255);
+ s->func(s->context, &lengthbyte, 1);
+ s->func(s->context, &databyte, 1);
+}
+
+static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data)
+{
+ unsigned char lengthbyte = STBIW_UCHAR(length);
+ STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code
+ s->func(s->context, &lengthbyte, 1);
+ s->func(s->context, data, length);
+}
+
+static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline)
+{
+ unsigned char scanlineheader[4] = { 2, 2, 0, 0 };
+ unsigned char rgbe[4];
+ float linear[3];
+ int x;
+
+ scanlineheader[2] = (width&0xff00)>>8;
+ scanlineheader[3] = (width&0x00ff);
+
+ /* skip RLE for images too small or large */
+ if (width < 8 || width >= 32768) {
+ for (x=0; x < width; x++) {
+ switch (ncomp) {
+ case 4: /* fallthrough */
+ case 3: linear[2] = scanline[x*ncomp + 2];
+ linear[1] = scanline[x*ncomp + 1];
+ linear[0] = scanline[x*ncomp + 0];
+ break;
+ default:
+ linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];
+ break;
+ }
+ stbiw__linear_to_rgbe(rgbe, linear);
+ s->func(s->context, rgbe, 4);
+ }
+ } else {
+ int c,r;
+ /* encode into scratch buffer */
+ for (x=0; x < width; x++) {
+ switch(ncomp) {
+ case 4: /* fallthrough */
+ case 3: linear[2] = scanline[x*ncomp + 2];
+ linear[1] = scanline[x*ncomp + 1];
+ linear[0] = scanline[x*ncomp + 0];
+ break;
+ default:
+ linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];
+ break;
+ }
+ stbiw__linear_to_rgbe(rgbe, linear);
+ scratch[x + width*0] = rgbe[0];
+ scratch[x + width*1] = rgbe[1];
+ scratch[x + width*2] = rgbe[2];
+ scratch[x + width*3] = rgbe[3];
+ }
+
+ s->func(s->context, scanlineheader, 4);
+
+ /* RLE each component separately */
+ for (c=0; c < 4; c++) {
+ unsigned char *comp = &scratch[width*c];
+
+ x = 0;
+ while (x < width) {
+ // find first run
+ r = x;
+ while (r+2 < width) {
+ if (comp[r] == comp[r+1] && comp[r] == comp[r+2])
+ break;
+ ++r;
+ }
+ if (r+2 >= width)
+ r = width;
+ // dump up to first run
+ while (x < r) {
+ int len = r-x;
+ if (len > 128) len = 128;
+ stbiw__write_dump_data(s, len, &comp[x]);
+ x += len;
+ }
+ // if there's a run, output it
+ if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd
+ // find next byte after run
+ while (r < width && comp[r] == comp[x])
+ ++r;
+ // output run up to r
+ while (x < r) {
+ int len = r-x;
+ if (len > 127) len = 127;
+ stbiw__write_run_data(s, len, comp[x]);
+ x += len;
+ }
+ }
+ }
+ }
+ }
+}
+
+static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data)
+{
+ if (y <= 0 || x <= 0 || data == NULL)
+ return 0;
+ else {
+ // Each component is stored separately. Allocate scratch space for full output scanline.
+ unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4);
+ int i, len;
+ char buffer[128];
+ char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n";
+ s->func(s->context, header, sizeof(header)-1);
+
+#ifdef __STDC_LIB_EXT1__
+ len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x);
+#else
+ len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x);
+#endif
+ s->func(s->context, buffer, len);
+
+ for(i=0; i < y; i++)
+ stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i));
+ STBIW_FREE(scratch);
+ return 1;
+ }
+}
+
+STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_hdr_core(&s, x, y, comp, (float *) data);
+}
+
+STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif // STBI_WRITE_NO_STDIO
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PNG writer
+//
+
+#ifndef STBIW_ZLIB_COMPRESS
+// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size()
+#define stbiw__sbraw(a) ((int *) (void *) (a) - 2)
+#define stbiw__sbm(a) stbiw__sbraw(a)[0]
+#define stbiw__sbn(a) stbiw__sbraw(a)[1]
+
+#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a))
+#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0)
+#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a)))
+
+#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v))
+#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0)
+#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0)
+
+static void *stbiw__sbgrowf(void **arr, int increment, int itemsize)
+{
+ int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1;
+ void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2);
+ STBIW_ASSERT(p);
+ if (p) {
+ if (!*arr) ((int *) p)[1] = 0;
+ *arr = (void *) ((int *) p + 2);
+ stbiw__sbm(*arr) = m;
+ }
+ return *arr;
+}
+
+static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
+{
+ while (*bitcount >= 8) {
+ stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer));
+ *bitbuffer >>= 8;
+ *bitcount -= 8;
+ }
+ return data;
+}
+
+static int stbiw__zlib_bitrev(int code, int codebits)
+{
+ int res=0;
+ while (codebits--) {
+ res = (res << 1) | (code & 1);
+ code >>= 1;
+ }
+ return res;
+}
+
+static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit)
+{
+ int i;
+ for (i=0; i < limit && i < 258; ++i)
+ if (a[i] != b[i]) break;
+ return i;
+}
+
+static unsigned int stbiw__zhash(unsigned char *data)
+{
+ stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
+ hash ^= hash << 3;
+ hash += hash >> 5;
+ hash ^= hash << 4;
+ hash += hash >> 17;
+ hash ^= hash << 25;
+ hash += hash >> 6;
+ return hash;
+}
+
+#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount))
+#define stbiw__zlib_add(code,codebits) \
+ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush())
+#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c)
+// default huffman tables
+#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8)
+#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9)
+#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7)
+#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8)
+#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n))
+#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n))
+
+#define stbiw__ZHASH 16384
+
+#endif // STBIW_ZLIB_COMPRESS
+
+STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
+{
+#ifdef STBIW_ZLIB_COMPRESS
+ // user provided a zlib compress implementation, use that
+ return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality);
+#else // use builtin
+ static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
+ static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
+ static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
+ static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
+ unsigned int bitbuf=0;
+ int i,j, bitcount=0;
+ unsigned char *out = NULL;
+ unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**));
+ if (hash_table == NULL)
+ return NULL;
+ if (quality < 5) quality = 5;
+
+ stbiw__sbpush(out, 0x78); // DEFLATE 32K window
+ stbiw__sbpush(out, 0x5e); // FLEVEL = 1
+ stbiw__zlib_add(1,1); // BFINAL = 1
+ stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman
+
+ for (i=0; i < stbiw__ZHASH; ++i)
+ hash_table[i] = NULL;
+
+ i=0;
+ while (i < data_len-3) {
+ // hash next 3 bytes of data to be compressed
+ int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3;
+ unsigned char *bestloc = 0;
+ unsigned char **hlist = hash_table[h];
+ int n = stbiw__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32768) { // if entry lies within window
+ int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i);
+ if (d >= best) { best=d; bestloc=hlist[j]; }
+ }
+ }
+ // when hash table entry is too long, delete half the entries
+ if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) {
+ STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
+ stbiw__sbn(hash_table[h]) = quality;
+ }
+ stbiw__sbpush(hash_table[h],data+i);
+
+ if (bestloc) {
+ // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
+ h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1);
+ hlist = hash_table[h];
+ n = stbiw__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32767) {
+ int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1);
+ if (e > best) { // if next match is better, bail on current match
+ bestloc = NULL;
+ break;
+ }
+ }
+ }
+ }
+
+ if (bestloc) {
+ int d = (int) (data+i - bestloc); // distance back
+ STBIW_ASSERT(d <= 32767 && best <= 258);
+ for (j=0; best > lengthc[j+1]-1; ++j);
+ stbiw__zlib_huff(j+257);
+ if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]);
+ for (j=0; d > distc[j+1]-1; ++j);
+ stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5);
+ if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]);
+ i += best;
+ } else {
+ stbiw__zlib_huffb(data[i]);
+ ++i;
+ }
+ }
+ // write out final bytes
+ for (;i < data_len; ++i)
+ stbiw__zlib_huffb(data[i]);
+ stbiw__zlib_huff(256); // end of block
+ // pad with 0 bits to byte boundary
+ while (bitcount)
+ stbiw__zlib_add(0,1);
+
+ for (i=0; i < stbiw__ZHASH; ++i)
+ (void) stbiw__sbfree(hash_table[i]);
+ STBIW_FREE(hash_table);
+
+ // store uncompressed instead if compression was worse
+ if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) {
+ stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1
+ for (j = 0; j < data_len;) {
+ int blocklen = data_len - j;
+ if (blocklen > 32767) blocklen = 32767;
+ stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression
+ stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN
+ stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN
+ stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8));
+ memcpy(out+stbiw__sbn(out), data+j, blocklen);
+ stbiw__sbn(out) += blocklen;
+ j += blocklen;
+ }
+ }
+
+ {
+ // compute adler32 on input
+ unsigned int s1=1, s2=0;
+ int blocklen = (int) (data_len % 5552);
+ j=0;
+ while (j < data_len) {
+ for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; }
+ s1 %= 65521; s2 %= 65521;
+ j += blocklen;
+ blocklen = 5552;
+ }
+ stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(s2));
+ stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(s1));
+ }
+ *out_len = stbiw__sbn(out);
+ // make returned pointer freeable
+ STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len);
+ return (unsigned char *) stbiw__sbraw(out);
+#endif // STBIW_ZLIB_COMPRESS
+}
+
+static unsigned int stbiw__crc32(unsigned char *buffer, int len)
+{
+#ifdef STBIW_CRC32
+ return STBIW_CRC32(buffer, len);
+#else
+ static unsigned int crc_table[256] =
+ {
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+ };
+
+ unsigned int crc = ~0u;
+ int i;
+ for (i=0; i < len; ++i)
+ crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
+ return ~crc;
+#endif
+}
+
+#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4)
+#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
+#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3])
+
+static void stbiw__wpcrc(unsigned char **data, int len)
+{
+ unsigned int crc = stbiw__crc32(*data - len - 4, len+4);
+ stbiw__wp32(*data, crc);
+}
+
+static unsigned char stbiw__paeth(int a, int b, int c)
+{
+ int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
+ if (pa <= pb && pa <= pc) return STBIW_UCHAR(a);
+ if (pb <= pc) return STBIW_UCHAR(b);
+ return STBIW_UCHAR(c);
+}
+
+// @OPTIMIZE: provide an option that always forces left-predict or paeth predict
+static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer)
+{
+ static int mapping[] = { 0,1,2,3,4 };
+ static int firstmap[] = { 0,1,0,5,6 };
+ int *mymap = (y != 0) ? mapping : firstmap;
+ int i;
+ int type = mymap[filter_type];
+ unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y);
+ int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes;
+
+ if (type==0) {
+ memcpy(line_buffer, z, width*n);
+ return;
+ }
+
+ // first loop isn't optimized since it's just one pixel
+ for (i = 0; i < n; ++i) {
+ switch (type) {
+ case 1: line_buffer[i] = z[i]; break;
+ case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break;
+ case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break;
+ case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break;
+ case 5: line_buffer[i] = z[i]; break;
+ case 6: line_buffer[i] = z[i]; break;
+ }
+ }
+ switch (type) {
+ case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break;
+ case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break;
+ case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break;
+ case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break;
+ case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break;
+ case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break;
+ }
+}
+
+STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
+{
+ int force_filter = stbi_write_force_png_filter;
+ int ctype[5] = { -1, 0, 4, 2, 6 };
+ unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
+ unsigned char *out,*o, *filt, *zlib;
+ signed char *line_buffer;
+ int j,zlen;
+
+ if (stride_bytes == 0)
+ stride_bytes = x * n;
+
+ if (force_filter >= 5) {
+ force_filter = -1;
+ }
+
+ filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0;
+ line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; }
+ for (j=0; j < y; ++j) {
+ int filter_type;
+ if (force_filter > -1) {
+ filter_type = force_filter;
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer);
+ } else { // Estimate the best filter by running through all of them:
+ int best_filter = 0, best_filter_val = 0x7fffffff, est, i;
+ for (filter_type = 0; filter_type < 5; filter_type++) {
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer);
+
+ // Estimate the entropy of the line using this filter; the less, the better.
+ est = 0;
+ for (i = 0; i < x*n; ++i) {
+ est += abs((signed char) line_buffer[i]);
+ }
+ if (est < best_filter_val) {
+ best_filter_val = est;
+ best_filter = filter_type;
+ }
+ }
+ if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer);
+ filter_type = best_filter;
+ }
+ }
+ // when we get here, filter_type contains the filter type, and line_buffer contains the data
+ filt[j*(x*n+1)] = (unsigned char) filter_type;
+ STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n);
+ }
+ STBIW_FREE(line_buffer);
+ zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level);
+ STBIW_FREE(filt);
+ if (!zlib) return 0;
+
+ // each tag requires 12 bytes of overhead
+ out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12);
+ if (!out) return 0;
+ *out_len = 8 + 12+13 + 12+zlen + 12;
+
+ o=out;
+ STBIW_MEMMOVE(o,sig,8); o+= 8;
+ stbiw__wp32(o, 13); // header length
+ stbiw__wptag(o, "IHDR");
+ stbiw__wp32(o, x);
+ stbiw__wp32(o, y);
+ *o++ = 8;
+ *o++ = STBIW_UCHAR(ctype[n]);
+ *o++ = 0;
+ *o++ = 0;
+ *o++ = 0;
+ stbiw__wpcrc(&o,13);
+
+ stbiw__wp32(o, zlen);
+ stbiw__wptag(o, "IDAT");
+ STBIW_MEMMOVE(o, zlib, zlen);
+ o += zlen;
+ STBIW_FREE(zlib);
+ stbiw__wpcrc(&o, zlen);
+
+ stbiw__wp32(o,0);
+ stbiw__wptag(o, "IEND");
+ stbiw__wpcrc(&o,0);
+
+ STBIW_ASSERT(o == out + *out_len);
+
+ return out;
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
+{
+ FILE *f;
+ int len;
+ unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);
+ if (png == NULL) return 0;
+
+ f = stbiw__fopen(filename, "wb");
+ if (!f) { STBIW_FREE(png); return 0; }
+ fwrite(png, 1, len, f);
+ fclose(f);
+ STBIW_FREE(png);
+ return 1;
+}
+#endif
+
+STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes)
+{
+ int len;
+ unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);
+ if (png == NULL) return 0;
+ func(context, png, len);
+ STBIW_FREE(png);
+ return 1;
+}
+
+
+/* ***************************************************************************
+ *
+ * JPEG writer
+ *
+ * This is based on Jon Olick's jo_jpeg.cpp:
+ * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html
+ */
+
+static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,
+ 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 };
+
+static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) {
+ int bitBuf = *bitBufP, bitCnt = *bitCntP;
+ bitCnt += bs[1];
+ bitBuf |= bs[0] << (24 - bitCnt);
+ while(bitCnt >= 8) {
+ unsigned char c = (bitBuf >> 16) & 255;
+ stbiw__putc(s, c);
+ if(c == 255) {
+ stbiw__putc(s, 0);
+ }
+ bitBuf <<= 8;
+ bitCnt -= 8;
+ }
+ *bitBufP = bitBuf;
+ *bitCntP = bitCnt;
+}
+
+static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) {
+ float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p;
+ float z1, z2, z3, z4, z5, z11, z13;
+
+ float tmp0 = d0 + d7;
+ float tmp7 = d0 - d7;
+ float tmp1 = d1 + d6;
+ float tmp6 = d1 - d6;
+ float tmp2 = d2 + d5;
+ float tmp5 = d2 - d5;
+ float tmp3 = d3 + d4;
+ float tmp4 = d3 - d4;
+
+ // Even part
+ float tmp10 = tmp0 + tmp3; // phase 2
+ float tmp13 = tmp0 - tmp3;
+ float tmp11 = tmp1 + tmp2;
+ float tmp12 = tmp1 - tmp2;
+
+ d0 = tmp10 + tmp11; // phase 3
+ d4 = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * 0.707106781f; // c4
+ d2 = tmp13 + z1; // phase 5
+ d6 = tmp13 - z1;
+
+ // Odd part
+ tmp10 = tmp4 + tmp5; // phase 2
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ // The rotator is modified from fig 4-8 to avoid extra negations.
+ z5 = (tmp10 - tmp12) * 0.382683433f; // c6
+ z2 = tmp10 * 0.541196100f + z5; // c2-c6
+ z4 = tmp12 * 1.306562965f + z5; // c2+c6
+ z3 = tmp11 * 0.707106781f; // c4
+
+ z11 = tmp7 + z3; // phase 5
+ z13 = tmp7 - z3;
+
+ *d5p = z13 + z2; // phase 6
+ *d3p = z13 - z2;
+ *d1p = z11 + z4;
+ *d7p = z11 - z4;
+
+ *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6;
+}
+
+static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) {
+ int tmp1 = val < 0 ? -val : val;
+ val = val < 0 ? val-1 : val;
+ bits[1] = 1;
+ while(tmp1 >>= 1) {
+ ++bits[1];
+ }
+ bits[0] = val & ((1<<bits[1])-1);
+}
+
+static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt, float *CDU, int du_stride, float *fdtbl, int DC, const unsigned short HTDC[256][2], const unsigned short HTAC[256][2]) {
+ const unsigned short EOB[2] = { HTAC[0x00][0], HTAC[0x00][1] };
+ const unsigned short M16zeroes[2] = { HTAC[0xF0][0], HTAC[0xF0][1] };
+ int dataOff, i, j, n, diff, end0pos, x, y;
+ int DU[64];
+
+ // DCT rows
+ for(dataOff=0, n=du_stride*8; dataOff<n; dataOff+=du_stride) {
+ stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]);
+ }
+ // DCT columns
+ for(dataOff=0; dataOff<8; ++dataOff) {
+ stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+du_stride], &CDU[dataOff+du_stride*2], &CDU[dataOff+du_stride*3], &CDU[dataOff+du_stride*4],
+ &CDU[dataOff+du_stride*5], &CDU[dataOff+du_stride*6], &CDU[dataOff+du_stride*7]);
+ }
+ // Quantize/descale/zigzag the coefficients
+ for(y = 0, j=0; y < 8; ++y) {
+ for(x = 0; x < 8; ++x,++j) {
+ float v;
+ i = y*du_stride+x;
+ v = CDU[i]*fdtbl[j];
+ // DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f));
+ // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway?
+ DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? v - 0.5f : v + 0.5f);
+ }
+ }
+
+ // Encode DC
+ diff = DU[0] - DC;
+ if (diff == 0) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]);
+ } else {
+ unsigned short bits[2];
+ stbiw__jpg_calcBits(diff, bits);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
+ }
+ // Encode ACs
+ end0pos = 63;
+ for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) {
+ }
+ // end0pos = first element in reverse order !=0
+ if(end0pos == 0) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
+ return DU[0];
+ }
+ for(i = 1; i <= end0pos; ++i) {
+ int startpos = i;
+ int nrzeroes;
+ unsigned short bits[2];
+ for (; DU[i]==0 && i<=end0pos; ++i) {
+ }
+ nrzeroes = i-startpos;
+ if ( nrzeroes >= 16 ) {
+ int lng = nrzeroes>>4;
+ int nrmarker;
+ for (nrmarker=1; nrmarker <= lng; ++nrmarker)
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes);
+ nrzeroes &= 15;
+ }
+ stbiw__jpg_calcBits(DU[i], bits);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
+ }
+ if(end0pos != 63) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
+ }
+ return DU[0];
+}
+
+static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) {
+ // Constants that don't pollute global namespace
+ static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0};
+ static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};
+ static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d};
+ static const unsigned char std_ac_luminance_values[] = {
+ 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
+ 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
+ 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
+ 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
+ 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
+ 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
+ 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa
+ };
+ static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0};
+ static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};
+ static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77};
+ static const unsigned char std_ac_chrominance_values[] = {
+ 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
+ 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
+ 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
+ 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
+ 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
+ 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
+ 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa
+ };
+ // Huffman tables
+ static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}};
+ static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}};
+ static const unsigned short YAC_HT[256][2] = {
+ {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}
+ };
+ static const unsigned short UVAC_HT[256][2] = {
+ {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}
+ };
+ static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,
+ 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99};
+ static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,
+ 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};
+ static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f,
+ 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f };
+
+ int row, col, i, k, subsample;
+ float fdtbl_Y[64], fdtbl_UV[64];
+ unsigned char YTable[64], UVTable[64];
+
+ if(!data || !width || !height || comp > 4 || comp < 1) {
+ return 0;
+ }
+
+ quality = quality ? quality : 90;
+ subsample = quality <= 90 ? 1 : 0;
+ quality = quality < 1 ? 1 : quality > 100 ? 100 : quality;
+ quality = quality < 50 ? 5000 / quality : 200 - quality * 2;
+
+ for(i = 0; i < 64; ++i) {
+ int uvti, yti = (YQT[i]*quality+50)/100;
+ YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti);
+ uvti = (UVQT[i]*quality+50)/100;
+ UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti);
+ }
+
+ for(row = 0, k = 0; row < 8; ++row) {
+ for(col = 0; col < 8; ++col, ++k) {
+ fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
+ fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
+ }
+ }
+
+ // Write Headers
+ {
+ static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 };
+ static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 };
+ const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width),
+ 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 };
+ s->func(s->context, (void*)head0, sizeof(head0));
+ s->func(s->context, (void*)YTable, sizeof(YTable));
+ stbiw__putc(s, 1);
+ s->func(s->context, UVTable, sizeof(UVTable));
+ s->func(s->context, (void*)head1, sizeof(head1));
+ s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1);
+ s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values));
+ stbiw__putc(s, 0x10); // HTYACinfo
+ s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1);
+ s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values));
+ stbiw__putc(s, 1); // HTUDCinfo
+ s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1);
+ s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values));
+ stbiw__putc(s, 0x11); // HTUACinfo
+ s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1);
+ s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values));
+ s->func(s->context, (void*)head2, sizeof(head2));
+ }
+
+ // Encode 8x8 macroblocks
+ {
+ static const unsigned short fillBits[] = {0x7F, 7};
+ int DCY=0, DCU=0, DCV=0;
+ int bitBuf=0, bitCnt=0;
+ // comp == 2 is grey+alpha (alpha is ignored)
+ int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0;
+ const unsigned char *dataR = (const unsigned char *)data;
+ const unsigned char *dataG = dataR + ofsG;
+ const unsigned char *dataB = dataR + ofsB;
+ int x, y, pos;
+ if(subsample) {
+ for(y = 0; y < height; y += 16) {
+ for(x = 0; x < width; x += 16) {
+ float Y[256], U[256], V[256];
+ for(row = y, pos = 0; row < y+16; ++row) {
+ // row >= height => use last input row
+ int clamped_row = (row < height) ? row : height - 1;
+ int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;
+ for(col = x; col < x+16; ++col, ++pos) {
+ // if col >= width => use pixel from last input column
+ int p = base_p + ((col < width) ? col : (width-1))*comp;
+ float r = dataR[p], g = dataG[p], b = dataB[p];
+ Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;
+ U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;
+ V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;
+ }
+ }
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+
+ // subsample U,V
+ {
+ float subU[64], subV[64];
+ int yy, xx;
+ for(yy = 0, pos = 0; yy < 8; ++yy) {
+ for(xx = 0; xx < 8; ++xx, ++pos) {
+ int j = yy*32+xx*2;
+ subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f;
+ subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f;
+ }
+ }
+ DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
+ DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
+ }
+ }
+ }
+ } else {
+ for(y = 0; y < height; y += 8) {
+ for(x = 0; x < width; x += 8) {
+ float Y[64], U[64], V[64];
+ for(row = y, pos = 0; row < y+8; ++row) {
+ // row >= height => use last input row
+ int clamped_row = (row < height) ? row : height - 1;
+ int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;
+ for(col = x; col < x+8; ++col, ++pos) {
+ // if col >= width => use pixel from last input column
+ int p = base_p + ((col < width) ? col : (width-1))*comp;
+ float r = dataR[p], g = dataG[p], b = dataB[p];
+ Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;
+ U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;
+ V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;
+ }
+ }
+
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
+ DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
+ }
+ }
+ }
+
+ // Do the bit alignment of the EOI marker
+ stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits);
+ }
+
+ // EOI
+ stbiw__putc(s, 0xFF);
+ stbiw__putc(s, 0xD9);
+
+ return 1;
+}
+
+STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality);
+}
+
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_jpg_core(&s, x, y, comp, data, quality);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif
+
+#endif // STB_IMAGE_WRITE_IMPLEMENTATION
+
+/* Revision history
+ 1.16 (2021-07-11)
+ make Deflate code emit uncompressed blocks when it would otherwise expand
+ support writing BMPs with alpha channel
+ 1.15 (2020-07-13) unknown
+ 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels
+ 1.13
+ 1.12
+ 1.11 (2019-08-11)
+
+ 1.10 (2019-02-07)
+ support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 1.09 (2018-02-11)
+ fix typo in zlib quality API, improve STB_I_W_STATIC in C++
+ 1.08 (2018-01-29)
+ add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter
+ 1.07 (2017-07-24)
+ doc fix
+ 1.06 (2017-07-23)
+ writing JPEG (using Jon Olick's code)
+ 1.05 ???
+ 1.04 (2017-03-03)
+ monochrome BMP expansion
+ 1.03 ???
+ 1.02 (2016-04-02)
+ avoid allocating large structures on the stack
+ 1.01 (2016-01-16)
+ STBIW_REALLOC_SIZED: support allocators with no realloc support
+ avoid race-condition in crc initialization
+ minor compile issues
+ 1.00 (2015-09-14)
+ installable file IO function
+ 0.99 (2015-09-13)
+ warning fixes; TGA rle support
+ 0.98 (2015-04-08)
+ added STBIW_MALLOC, STBIW_ASSERT etc
+ 0.97 (2015-01-18)
+ fixed HDR asserts, rewrote HDR rle logic
+ 0.96 (2015-01-17)
+ add HDR output
+ fix monochrome BMP
+ 0.95 (2014-08-17)
+ add monochrome TGA output
+ 0.94 (2014-05-31)
+ rename private functions to avoid conflicts with stb_image.h
+ 0.93 (2014-05-27)
+ warning fixes
+ 0.92 (2010-08-01)
+ casts to unsigned char to fix warnings
+ 0.91 (2010-07-17)
+ first public release
+ 0.90 first internal release
+*/
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/third_party/ufbx/LICENSE b/third_party/ufbx/LICENSE
new file mode 100644
index 00000000..5db259b5
--- /dev/null
+++ b/third_party/ufbx/LICENSE
@@ -0,0 +1,39 @@
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2020 Samuli Raivio
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+----------------------------------------
diff --git a/third_party/ufbx/SOURCE.txt b/third_party/ufbx/SOURCE.txt
new file mode 100644
index 00000000..ae75dd13
--- /dev/null
+++ b/third_party/ufbx/SOURCE.txt
@@ -0,0 +1 @@
+ufbx.h, ufbx.c, LICENSE from https://github.com/ufbx/ufbx commit 5955c5c0b042ac2dc6f32955ab206aaec0620cfc (v0.23.1; MIT or public domain)
diff --git a/third_party/ufbx/ufbx.c b/third_party/ufbx/ufbx.c
new file mode 100644
index 00000000..f8b25bbd
--- /dev/null
+++ b/third_party/ufbx/ufbx.c
@@ -0,0 +1,33212 @@
+#ifndef UFBX_UFBX_C_INCLUDED
+#define UFBX_UFBX_C_INCLUDED
+
+#if defined(UFBX_HEADER_PATH)
+ #include UFBX_HEADER_PATH
+#else
+ #include "ufbx.h"
+#endif
+
+// -- User configuration
+
+// User configuration:
+// UFBX_REGRESSION Enable regression mode for development
+// UFBX_UBSAN Explicitly enable undefined behavior sanitizer workarounds
+// UFBX_NO_UNALIGNED_LOADS Do not use unaligned loads even when they are supported
+// UFBX_USE_UNALIGNED_LOADS Forcibly use unaligned loads on unknown platforms
+// UFBX_USE_SSE Explicitly enable SSE2 support (for x86)
+// UFBX_HAS_FTELLO Allow ufbx to use `ftello()` to measure file size
+// UFBX_WASM_32BIT Optimize WASM for 32-bit architectures
+// UFBX_TRACE Log calls of `ufbxi_check()` for tracing execution
+// UFBX_LITTLE_ENDIAN=0/1 Explicitly define little/big endian architecture
+// UFBX_PATH_SEPARATOR='' Specify default platform path separator
+// UFBX_NO_SSE Do not try to include SSE
+
+// Dependencies:
+// UFBX_NO_MALLOC Disable default malloc/realloc/free
+// UFBX_NO_STDIO Disable stdio FILE API
+// UFBX_EXTERNAL_MALLOC Link to external ufbx_malloc() interface
+// UFBX_EXTERNAL_STDIO Link to external ufbx_stdio_() interface
+// UFBX_EXTERNAL_MATH Link to external <math.h> interface
+// UFBX_EXTERNAL_STRING Link to external <string.h> interface
+
+// Freestanding:
+// UFBX_MATH_PREFIX='ufbx_' Prefix for external <math.h> functions used
+// UFBX_STRING_PREFIX='ufbx_' Prefix for external <string.h> functions used
+// UFBX_NO_LIBC Do not include libc (implies UFBX_EXTERNAL_MATH/STRING/MALLOC/STDIO by default)
+// UFBX_NO_LIBC_TYPES Do not include any libc headers, you must define all types in <stdint.h/stddef.h/etc>
+
+// Mostly internal for debugging:
+// UFBX_STATIC_ANALYSIS Enable static analysis augmentation
+// UFBX_DEBUG_BINARY_SEARCH Force using binary search for debugging
+// UFBX_EXTENSIVE_THREADING Use threads for small inputs
+// UFBX_MAXIMUM_ALIGNMENT Maximum alignment used for allocation
+
+#if defined(UFBX_CONFIG_SOURCE)
+ #include UFBX_CONFIG_SOURCE
+#endif
+
+// -- Configuration
+
+#define UFBXI_MAX_NON_ARRAY_VALUES 8
+#define UFBXI_MAX_NODE_DEPTH 32
+#define UFBXI_MAX_XML_DEPTH 32
+#define UFBXI_MAX_SKIP_SIZE 0x40000000
+#define UFBXI_MAP_MAX_SCAN 32
+#define UFBXI_KD_FAST_DEPTH 6
+#define UFBXI_HUGE_MAX_SCAN 16
+#define UFBXI_MIN_FILE_FORMAT_LOOKAHEAD 32
+#define UFBXI_FACE_GROUP_HASH_BITS 8
+#define UFBXI_MIN_THREADED_DEFLATE_BYTES 256
+#define UFBXI_MIN_THREADED_ASCII_VALUES 64
+#define UFBXI_GEOMETRY_CACHE_BUFFER_SIZE 512
+
+#ifndef UFBXI_MAX_NURBS_ORDER
+#define UFBXI_MAX_NURBS_ORDER 128
+#endif
+
+// By default enough to have squares be non-denormal
+#ifndef UFBX_EPSILON
+#define UFBX_EPSILON (sizeof(ufbx_real) == sizeof(float) ? \
+ (ufbx_real)1.0842021795674597e-19f : (ufbx_real)1.4916681462400413e-154)
+#endif
+
+// -- Feature exclusion
+
+#if !defined(UFBX_MINIMAL)
+ #if !defined(UFBX_NO_SUBDIVISION)
+ #define UFBXI_FEATURE_SUBDIVISION 1
+ #endif
+ #if !defined(UFBX_NO_TESSELLATION)
+ #define UFBXI_FEATURE_TESSELLATION 1
+ #endif
+ #if !defined(UFBX_NO_GEOMETRY_CACHE)
+ #define UFBXI_FEATURE_GEOMETRY_CACHE 1
+ #endif
+ #if !defined(UFBX_NO_SCENE_EVALUATION)
+ #define UFBXI_FEATURE_SCENE_EVALUATION 1
+ #endif
+ #if !defined(UFBX_NO_SKINNING_EVALUATION)
+ #define UFBXI_FEATURE_SKINNING_EVALUATION 1
+ #endif
+ #if !defined(UFBX_NO_ANIMATION_BAKING)
+ #define UFBXI_FEATURE_ANIMATION_BAKING 1
+ #endif
+ #if !defined(UFBX_NO_TRIANGULATION)
+ #define UFBXI_FEATURE_TRIANGULATION 1
+ #endif
+ #if !defined(UFBX_NO_INDEX_GENERATION)
+ #define UFBXI_FEATURE_INDEX_GENERATION 1
+ #endif
+ #if !defined(UFBX_NO_FORMAT_OBJ)
+ #define UFBXI_FEATURE_FORMAT_OBJ 1
+ #endif
+#endif
+
+#if defined(UFBX_DEV)
+ #if !defined(UFBX_NO_ERROR_STACK)
+ #define UFBXI_FEATURE_ERROR_STACK 1
+ #endif
+#endif
+
+#if !defined(UFBXI_FEATURE_SUBDIVISION) && defined(UFBX_ENABLE_SUBDIVISION)
+ #define UFBXI_FEATURE_SUBDIVISION 1
+#endif
+#if !defined(UFBXI_FEATURE_TESSELLATION) && defined(UFBX_ENABLE_TESSELLATION)
+ #define UFBXI_FEATURE_TESSELLATION 1
+#endif
+#if !defined(UFBXI_FEATURE_GEOMETRY_CACHE) && defined(UFBX_ENABLE_GEOMETRY_CACHE)
+ #define UFBXI_FEATURE_GEOMETRY_CACHE 1
+#endif
+#if !defined(UFBXI_FEATURE_SCENE_EVALUATION) && defined(UFBX_ENABLE_SCENE_EVALUATION)
+ #define UFBXI_FEATURE_SCENE_EVALUATION 1
+#endif
+#if !defined(UFBXI_FEATURE_SKINNING_EVALUATION) && defined(UFBX_ENABLE_SKINNING_EVALUATION)
+ #define UFBXI_FEATURE_SKINNING_EVALUATION 1
+#endif
+#if !defined(UFBXI_FEATURE_ANIMATION_BAKING) && defined(UFBX_ENABLE_ANIMATION_BAKING)
+ #define UFBXI_FEATURE_ANIMATION_BAKING 1
+#endif
+#if !defined(UFBXI_FEATURE_TRIANGULATION) && defined(UFBX_ENABLE_TRIANGULATION)
+ #define UFBXI_FEATURE_TRIANGULATION 1
+#endif
+#if !defined(UFBXI_FEATURE_INDEX_GENERATION) && defined(UFBX_ENABLE_INDEX_GENERATION)
+ #define UFBXI_FEATURE_INDEX_GENERATION 1
+#endif
+#if !defined(UFBXI_FEATURE_FORMAT_OBJ) && defined(UFBX_ENABLE_FORMAT_OBJ)
+ #define UFBXI_FEATURE_FORMAT_OBJ 1
+#endif
+#if !defined(UFBXI_FEATURE_ERROR_STACK) && defined(UFBX_ENABLE_ERROR_STACK)
+ #define UFBXI_FEATURE_ERROR_STACK 1
+#endif
+
+#if !defined(UFBXI_FEATURE_SUBDIVISION)
+ #define UFBXI_FEATURE_SUBDIVISION 0
+#endif
+#if !defined(UFBXI_FEATURE_TESSELLATION)
+ #define UFBXI_FEATURE_TESSELLATION 0
+#endif
+#if !defined(UFBXI_FEATURE_GEOMETRY_CACHE)
+ #define UFBXI_FEATURE_GEOMETRY_CACHE 0
+#endif
+#if !defined(UFBXI_FEATURE_SCENE_EVALUATION)
+ #define UFBXI_FEATURE_SCENE_EVALUATION 0
+#endif
+#if !defined(UFBXI_FEATURE_SKINNING_EVALUATION)
+ #define UFBXI_FEATURE_SKINNING_EVALUATION 0
+#endif
+#if !defined(UFBXI_FEATURE_ANIMATION_BAKING)
+ #define UFBXI_FEATURE_ANIMATION_BAKING 0
+#endif
+#if !defined(UFBXI_FEATURE_TRIANGULATION)
+ #define UFBXI_FEATURE_TRIANGULATION 0
+#endif
+#if !defined(UFBXI_FEATURE_INDEX_GENERATION)
+ #define UFBXI_FEATURE_INDEX_GENERATION 0
+#endif
+#if !defined(UFBXI_FEATURE_FORMAT_OBJ)
+ #define UFBXI_FEATURE_FORMAT_OBJ 0
+#endif
+#if !defined(UFBXI_FEATURE_ERROR_STACK)
+ #define UFBXI_FEATURE_ERROR_STACK 0
+#endif
+
+// Derived features
+
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ #define UFBXI_FEATURE_XML 1
+#else
+ #define UFBXI_FEATURE_XML 0
+#endif
+
+#if UFBXI_FEATURE_TRIANGULATION
+ #define UFBXI_FEATURE_KD 1
+#else
+ #define UFBXI_FEATURE_KD 0
+#endif
+
+#if !UFBXI_FEATURE_SUBDIVISION || !UFBXI_FEATURE_TESSELLATION || !UFBXI_FEATURE_GEOMETRY_CACHE || !UFBXI_FEATURE_SCENE_EVALUATION || !UFBXI_FEATURE_SKINNING_EVALUATION || !UFBXI_FEATURE_ANIMATION_BAKING || !UFBXI_FEATURE_TRIANGULATION || !UFBXI_FEATURE_INDEX_GENERATION || !UFBXI_FEATURE_XML || !UFBXI_FEATURE_KD || !UFBXI_FEATURE_FORMAT_OBJ
+ #define UFBXI_PARTIAL_FEATURES 1
+#endif
+
+// -- Headers
+
+// Legacy mapping
+#if !defined(UFBX_EXTERNAL_MATH) && defined(UFBX_NO_MATH_H)
+ #define UFBX_EXTERNAL_MATH
+#endif
+
+#if !defined(UFBX_NO_LIBC_TYPES)
+ #include <stdarg.h>
+#endif
+
+#if !defined(UFBX_NO_LIBC)
+ #if !defined(UFBX_NO_FLOAT_H)
+ #include <float.h>
+ #endif
+ #if !defined(UFBX_EXTERNAL_MATH)
+ #include <math.h>
+ #endif
+ #if !defined(UFBX_EXTERNAL_STRING)
+ #include <string.h>
+ #endif
+ #if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
+ #include <stdio.h>
+ #endif
+ #if !defined(UFBX_NO_MALLOC) && !defined(UFBX_EXTERNAL_MALLOC)
+ #include <stdlib.h>
+ #endif
+#else
+ #if !defined(UFBX_EXTERNAL_MATH) && !defined(UFBX_NO_EXTERNAL_MATH)
+ #define UFBX_EXTERNAL_MATH
+ #endif
+ #if !defined(UFBX_EXTERNAL_STRING) && !defined(UFBX_NO_EXTERNAL_STRING)
+ #define UFBX_EXTERNAL_STRING
+ #endif
+ #if !defined(UFBX_EXTERNAL_MALLOC) && !defined(UFBX_NO_EXTERNAL_MALLOC) && !defined(UFBX_NO_MALLOC)
+ #define UFBX_EXTERNAL_MALLOC
+ #endif
+ #if !defined(UFBX_EXTERNAL_STDIO) && !defined(UFBX_NO_EXTERNAL_STDIO) && !defined(UFBX_NO_STDIO)
+ #define UFBX_EXTERNAL_STDIO
+ #endif
+#endif
+
+#if defined(UFBX_EXTERNAL_STRING) && !defined(UFBX_STRING_PREFIX)
+ #define UFBX_STRING_PREFIX ufbx_
+#endif
+
+#if !defined(UFBX_EXTERNAL_MATH)
+ #if !defined(UFBX_MATH_PREFIX)
+ #define UFBX_MATH_PREFIX
+ #endif
+#endif
+
+#define ufbxi_pre_cat2(a, b) a##b
+#define ufbxi_pre_cat(a, b) ufbxi_pre_cat2(a, b)
+
+// -- External functions
+
+#ifndef ufbx_extern_abi
+ #if defined(UFBX_STATIC)
+ #define ufbx_extern_abi static
+ #else
+ #define ufbx_extern_abi
+ #endif
+#endif
+
+#if defined(UFBX_MATH_PREFIX)
+ #define ufbxi_math_fn(name) ufbxi_pre_cat(UFBX_MATH_PREFIX, name)
+ #define ufbx_sqrt ufbxi_math_fn(sqrt)
+ #define ufbx_fabs ufbxi_math_fn(fabs)
+ #define ufbx_pow ufbxi_math_fn(pow)
+ #define ufbx_sin ufbxi_math_fn(sin)
+ #define ufbx_cos ufbxi_math_fn(cos)
+ #define ufbx_tan ufbxi_math_fn(tan)
+ #define ufbx_asin ufbxi_math_fn(asin)
+ #define ufbx_acos ufbxi_math_fn(acos)
+ #define ufbx_atan ufbxi_math_fn(atan)
+ #define ufbx_atan2 ufbxi_math_fn(atan2)
+ #define ufbx_copysign ufbxi_math_fn(copysign)
+ #define ufbx_fmin ufbxi_math_fn(fmin)
+ #define ufbx_fmax ufbxi_math_fn(fmax)
+ #define ufbx_nextafter ufbxi_math_fn(nextafter)
+ #define ufbx_rint ufbxi_math_fn(rint)
+ #define ufbx_floor ufbxi_math_fn(floor)
+ #define ufbx_ceil ufbxi_math_fn(ceil)
+ #define ufbx_isnan ufbxi_math_fn(isnan)
+#endif
+
+#if !defined(UFBX_NO_EXTERNAL_DEFINES)
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#if defined(UFBX_EXTERNAL_MATH)
+ ufbx_extern_abi double ufbx_sqrt(double x);
+ ufbx_extern_abi double ufbx_sin(double x);
+ ufbx_extern_abi double ufbx_cos(double x);
+ ufbx_extern_abi double ufbx_tan(double x);
+ ufbx_extern_abi double ufbx_asin(double x);
+ ufbx_extern_abi double ufbx_acos(double x);
+ ufbx_extern_abi double ufbx_atan(double x);
+ ufbx_extern_abi double ufbx_atan2(double y, double x);
+ ufbx_extern_abi double ufbx_pow(double x, double y);
+ ufbx_extern_abi double ufbx_fmin(double a, double b);
+ ufbx_extern_abi double ufbx_fmax(double a, double b);
+ ufbx_extern_abi double ufbx_fabs(double x);
+ ufbx_extern_abi double ufbx_copysign(double x, double y);
+ ufbx_extern_abi double ufbx_nextafter(double x, double y);
+ ufbx_extern_abi double ufbx_rint(double x);
+ ufbx_extern_abi double ufbx_floor(double x);
+ ufbx_extern_abi double ufbx_ceil(double x);
+ ufbx_extern_abi int ufbx_isnan(double x);
+#endif
+
+#if defined(UFBX_EXTERNAL_STRING)
+ ufbx_extern_abi size_t ufbx_strlen(const char *str);
+ ufbx_extern_abi void *ufbx_memcpy(void *dst, const void *src, size_t count);
+ ufbx_extern_abi void *ufbx_memmove(void *dst, const void *src, size_t count);
+ ufbx_extern_abi void *ufbx_memset(void *dst, int ch, size_t count);
+ ufbx_extern_abi const void *ufbx_memchr(const void *ptr, int value, size_t count);
+ ufbx_extern_abi int ufbx_memcmp(const void *a, const void *b, size_t count);
+ ufbx_extern_abi int ufbx_strcmp(const char *a, const char *b);
+ ufbx_extern_abi int ufbx_strncmp(const char *a, const char *b, size_t count);
+#endif
+
+#if defined(UFBX_EXTERNAL_MALLOC)
+ ufbx_extern_abi void *ufbx_malloc(size_t size);
+ ufbx_extern_abi void *ufbx_realloc(void *ptr, size_t old_size, size_t new_size);
+ ufbx_extern_abi void ufbx_free(void *ptr, size_t old_size);
+#endif
+
+#if defined(UFBX_EXTERNAL_STDIO)
+ ufbx_extern_abi void *ufbx_stdio_open(const char *path, size_t path_len);
+ ufbx_extern_abi size_t ufbx_stdio_read(void *file, void *data, size_t size);
+ ufbx_extern_abi bool ufbx_stdio_skip(void *file, size_t size);
+ ufbx_extern_abi uint64_t ufbx_stdio_size(void *file);
+ ufbx_extern_abi void ufbx_stdio_close(void *file);
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+
+#if !defined(UFBX_INFINITY)
+ #if defined(INFINITY)
+ #define UFBX_INFINITY INFINITY
+ #else
+ #define UFBX_INFINITY (1e+300 * 1e+300)
+ #endif
+#endif
+#if !defined(UFBX_NAN)
+ #if defined(NAN)
+ #define UFBX_NAN NAN
+ #else
+ #define UFBX_NAN (UFBX_INFINITY * 0.0f)
+ #endif
+#endif
+#if !defined(UFBX_FLT_EPSILON)
+ #if defined(FLT_EPSILON)
+ #define UFBX_FLT_EPSILON FLT_EPSILON
+ #else
+ #define UFBX_FLT_EPSILON 1.192092896e-07f
+ #endif
+#endif
+#if !defined(UFBX_FLT_EVAL_METHOD)
+ #if defined(FLT_EVAL_METHOD)
+ #define UFBX_FLT_EVAL_METHOD FLT_EVAL_METHOD
+ #elif defined(__FLT_EVAL_METHOD__)
+ #define UFBX_FLT_EVAL_METHOD __FLT_EVAL_METHOD__
+ #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
+ #define UFBX_FLT_EVAL_METHOD 0
+ #else
+ #define UFBX_FLT_EVAL_METHOD -1
+ #endif
+#endif
+
+#if defined(ufbx_malloc) || defined(ufbx_realloc) || defined(ufbx_free)
+ // User provided allocators
+ #if !defined(ufbx_malloc) || !defined(ufbx_realloc) || !defined(ufbx_free)
+ #error Inconsistent custom global allocator
+ #endif
+#elif defined(UFBX_NO_MALLOC)
+ #define ufbx_malloc(size) ((void)(size), (void)NULL)
+ #define ufbx_realloc(ptr, old_size, new_size) ((void)(ptr), (void)(old_size), (void)(new_size), (void)NULL)
+ #define ufbx_free(ptr, old_size) ((void)(ptr), (void)(old_size))
+#elif defined(UFBX_EXTERNAL_MALLOC)
+ // Nop
+#else
+ #define ufbx_malloc(size) malloc((size))
+ #define ufbx_realloc(ptr, old_size, new_size) realloc((ptr), (new_size))
+ #define ufbx_free(ptr, old_size) free((ptr))
+#endif
+
+#if !defined(ufbx_panic_handler)
+ static void ufbxi_panic_handler(const char *message)
+ {
+ (void)message;
+ #if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
+ fprintf(stderr, "ufbx panic: %s\n", message);
+ #endif
+ ufbx_assert(false && "ufbx panic: See stderr for more information");
+ }
+ #define ufbx_panic_handler ufbxi_panic_handler
+#endif
+
+// -- Platform
+
+#if defined(_MSC_VER)
+ #define UFBXI_MSC_VER _MSC_VER
+#else
+ #define UFBXI_MSC_VER 0
+#endif
+
+#if defined(__GNUC__)
+ #define UFBXI_GNUC __GNUC__
+ #define UFBXI_GNUC_VERSION ufbx_pack_version(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
+#else
+ #define UFBXI_GNUC 0
+ #define UFBXI_GNUC_VERSION 0
+#endif
+
+#if !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ #define ufbxi_noinline __declspec(noinline)
+ #define ufbxi_forceinline __forceinline
+ #define ufbxi_restrict __restrict
+ #if defined(_Check_return_)
+ #define ufbxi_nodiscard _Check_return_
+ #else
+ #define ufbxi_nodiscard
+ #endif
+ #define ufbxi_unused
+ #define ufbxi_unlikely(cond) (cond)
+#elif !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__))
+ #define ufbxi_noinline __attribute__((noinline))
+ #define ufbxi_forceinline inline __attribute__((always_inline))
+ #define ufbxi_restrict __restrict
+ #define ufbxi_nodiscard __attribute__((warn_unused_result))
+ #define ufbxi_unused __attribute__((unused))
+ #define ufbxi_unlikely(cond) __builtin_expect((cond), 0)
+#else
+ #define ufbxi_noinline
+ #define ufbxi_forceinline
+ #define ufbxi_nodiscard
+ #define ufbxi_restrict
+ #define ufbxi_unused
+ #define ufbxi_unlikely(cond) (cond)
+#endif
+
+#if !defined(UFBX_STANDARD_C) && defined(__clang__)
+ #define ufbxi_nounroll _Pragma("clang loop unroll(disable)") _Pragma("clang loop vectorize(disable)")
+#elif !defined(UFBX_STANDARD_C) && UFBXI_GNUC >= 8
+ #define ufbxi_nounroll _Pragma("GCC unroll 0")
+#elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ #define ufbxi_nounroll __pragma(loop(no_vector))
+#else
+ #define ufbxi_nounroll
+#endif
+
+#if defined(__GNUC__) && !defined(__clang__)
+ #define ufbxi_ignore(cond) (void)!(cond)
+#else
+ #define ufbxi_ignore(cond) (void)(cond)
+#endif
+
+#if defined(_MSC_VER)
+ #pragma warning(push)
+ #pragma warning(disable: 4061) // enumerator 'ENUM' in switch of enum 'enum' is not explicitly handled by a case label
+ #pragma warning(disable: 4200) // nonstandard extension used: zero-sized array in struct/union
+ #pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union
+ #pragma warning(disable: 4210) // nonstandard extension used: function given file scope
+ #pragma warning(disable: 4127) // conditional expression is constant
+ #pragma warning(disable: 4706) // assignment within conditional expression
+ #pragma warning(disable: 4789) // buffer 'type_and_name' of size 8 bytes will be overrun; 16 bytes will be written starting at offset 0
+ #pragma warning(disable: 4820) // type': 'N' bytes padding added after data member 'member'
+ #if defined(UFBX_STANDARD_C)
+ #pragma warning(disable: 4996) // 'fopen': This function or variable may be unsafe. Consider using fopen_s instead.
+ #endif
+ #if defined(UFBXI_PARTIAL_FEATURES)
+ #pragma warning(disable: 4100) // 'name': unreferenced formal parameter
+ #pragma warning(disable: 4505) // 'func': unreferenced function with internal linkage has been removed
+ #endif
+#endif
+
+#if defined(__clang__)
+ #pragma clang diagnostic push
+ #pragma clang diagnostic ignored "-Wmissing-field-initializers"
+ #pragma clang diagnostic ignored "-Wmissing-braces"
+ #pragma clang diagnostic ignored "-Wdouble-promotion"
+ #pragma clang diagnostic ignored "-Wpedantic"
+ #pragma clang diagnostic ignored "-Wcast-qual"
+ #pragma clang diagnostic ignored "-Wcast-align"
+ #pragma clang diagnostic ignored "-Wcovered-switch-default"
+ #pragma clang diagnostic ignored "-Wpadded"
+ #pragma clang diagnostic ignored "-Wswitch-enum"
+ #pragma clang diagnostic ignored "-Wfloat-equal"
+ #pragma clang diagnostic ignored "-Wformat-nonliteral"
+ #if __has_warning("-Watomic-implicit-seq-cst")
+ #pragma clang diagnostic ignored "-Watomic-implicit-seq-cst"
+ #endif
+ #if defined(UFBX_STANDARD_C)
+ #pragma clang diagnostic ignored "-Wunused-function"
+ #endif
+ #if defined(UFBXI_PARTIAL_FEATURES)
+ #pragma clang diagnostic ignored "-Wunused-function"
+ #pragma clang diagnostic ignored "-Wunused-parameter"
+ #endif
+ #if defined(__cplusplus)
+ #pragma clang diagnostic ignored "-Wold-style-cast"
+ #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
+ #else
+ #pragma clang diagnostic ignored "-Wdeclaration-after-statement"
+ #pragma clang diagnostic ignored "-Wbad-function-cast"
+ #endif
+#endif
+
+#if defined(__GNUC__)
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
+ #pragma GCC diagnostic ignored "-Wmissing-braces"
+ #pragma GCC diagnostic ignored "-Wdouble-promotion"
+ #pragma GCC diagnostic ignored "-Wpedantic"
+ #pragma GCC diagnostic ignored "-Wcast-qual"
+ #pragma GCC diagnostic ignored "-Wcast-align"
+ #pragma GCC diagnostic ignored "-Wpadded"
+ #pragma GCC diagnostic ignored "-Wswitch-enum"
+ #pragma GCC diagnostic ignored "-Wfloat-equal"
+ #pragma GCC diagnostic ignored "-Wformat-nonliteral"
+ #pragma GCC diagnostic ignored "-Wlong-long"
+ #if defined(UFBX_STANDARD_C)
+ #pragma GCC diagnostic ignored "-Wunused-function"
+ #endif
+ #if defined(UFBXI_PARTIAL_FEATURES)
+ #pragma GCC diagnostic ignored "-Wunused-function"
+ #pragma GCC diagnostic ignored "-Wunused-parameter"
+ #endif
+ #if defined(__cplusplus)
+ #pragma GCC diagnostic ignored "-Wold-style-cast"
+ #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
+ #else
+ #pragma GCC diagnostic ignored "-Wdeclaration-after-statement"
+ #pragma GCC diagnostic ignored "-Wbad-function-cast"
+ #if __GNUC__ >= 5
+ #pragma GCC diagnostic ignored "-Wc90-c99-compat"
+ #pragma GCC diagnostic ignored "-Wc99-c11-compat"
+ #endif
+ #endif
+ // MSC isnan() definition triggers this error on MinGW GCC
+ #if defined(__MINGW32__)
+ #pragma GCC diagnostic ignored "-Wfloat-conversion"
+ #endif
+ // `-Warray-bounds` results in warnings if UBsan is enabled and pre-GCC-14 has no way of detecting it..
+ // The workaround for this uses an assert, but if the user has both UBsan and asserts disabled we need to silence the warning.
+ #if (UFBXI_GNUC_VERSION >= ufbx_pack_version(4, 3, 0) && UFBXI_GNUC_VERSION < ufbx_pack_version(14, 0, 0)) || defined(NDEBUG)
+ #pragma GCC diagnostic ignored "-Warray-bounds"
+ #endif
+#endif
+
+#if !defined(ufbx_static_assert)
+ #if defined(__cplusplus) && __cplusplus >= 201103
+ #define ufbx_static_assert(desc, cond) static_assert(cond, #desc ": " #cond)
+ #else
+ #define ufbx_static_assert(desc, cond) typedef char ufbxi_static_assert_##desc[(cond)?1:-1]
+ #endif
+#endif
+
+#if defined(__has_feature)
+ #if __has_feature(undefined_behavior_sanitizer) && !defined(UFBX_UBSAN)
+ #define UFBX_UBSAN 1
+ #endif
+#endif
+
+#if defined(__SANITIZE_UNDEFINED__) && !defined(UFBX_UBSAN)
+ #define UFBX_UBSAN 1
+#endif
+
+// Don't use unaligned loads with UB-sanitizer
+#if defined(UFBX_UBSAN) && !defined(UFBX_NO_UNALIGNED_LOADS)
+ #define UFBX_NO_UNALIGNED_LOADS
+#endif
+
+#if defined(__clang_analyzer__) && !defined(UFBX_STATIC_ANALYSIS)
+ #define UFBX_STATIC_ANALYSIS 1
+#endif
+
+#if defined(UFBX_STATIC_ANALYSIS)
+ bool ufbxi_analysis_opaque;
+ #define ufbxi_maybe_null(ptr) (ufbxi_analysis_opaque ? (ptr) : NULL)
+ #define ufbxi_analysis_assert(cond) ufbx_assert(cond)
+#else
+ #define ufbxi_maybe_null(ptr) (ptr)
+ #define ufbxi_analysis_assert(cond) (void)0
+#endif
+
+#if defined(UFBX_STATIC_ANALYSIS) || defined(UFBX_UBSAN)
+ #define ufbxi_maybe_uninit(cond, value, def) ((cond) ? (value) : (def))
+#else
+ #define ufbxi_maybe_uninit(cond, value, def) (value)
+#endif
+
+#if !defined(ufbxi_trace)
+ #if defined(UFBX_TRACE)
+ #define ufbxi_trace(desc) (fprintf(stderr, "ufbx trace: %s:%d: %s\n", __FILE__, __LINE__, #desc), fflush(stderr), desc)
+ #else
+ #define ufbxi_trace(desc) (desc)
+ #endif
+#endif
+
+#ifndef UFBX_PATH_SEPARATOR
+ #if defined(_WIN32)
+ #define UFBX_PATH_SEPARATOR '\\'
+ #else
+ #define UFBX_PATH_SEPARATOR '/'
+ #endif
+#endif
+
+#if !defined(UFBX_STANDARD_C) && defined(_POSIX_C_SOURCE)
+ #if _POSIX_C_SOURCE >= 200112l
+ #ifndef UFBX_HAS_FTELLO
+ #define UFBX_HAS_FTELLO
+ #endif
+ #endif
+#endif
+
+#if !defined(UFBX_STANDARD_C) && ((defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)) || ((defined(__GNUC__) || defined(__clang__)) && defined(__x86_64__)))
+ #define UFBXI_ARCH_X64 1
+#else
+ #define UFBXI_ARCH_X64 0
+#endif
+
+#if defined(UFBX_USE_SSE) || (!defined(UFBX_STANDARD_C) && !defined(UFBX_NO_SSE) && UFBXI_ARCH_X64)
+ #define UFBXI_HAS_SSE 1
+ #include <xmmintrin.h>
+ #include <emmintrin.h>
+#else
+ #define UFBXI_HAS_SSE 0
+#endif
+
+// -- Atomic counter
+
+#define UFBXI_THREAD_SAFE 1
+
+#if defined(__cplusplus)
+ #define ufbxi_extern_c extern "C"
+#else
+ #define ufbxi_extern_c
+#endif
+
+#if !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER))
+ typedef size_t ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_inc(ptr) __sync_fetch_and_add((ptr), 1)
+ #define ufbxi_atomic_counter_dec(ptr) __sync_fetch_and_sub((ptr), 1)
+ #define ufbxi_atomic_counter_load(ptr) __sync_fetch_and_add((ptr), 0) // TODO: Proper atomic load
+#elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ #if defined(_M_X64) || defined(_M_ARM64)
+ ufbxi_extern_c __int64 _InterlockedIncrement64(__int64 volatile * lpAddend);
+ ufbxi_extern_c __int64 _InterlockedDecrement64(__int64 volatile * lpAddend);
+ ufbxi_extern_c __int64 _InterlockedExchangeAdd64(__int64 volatile * lpAddend, __int64 Value);
+ typedef volatile __int64 ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_inc(ptr) ((size_t)_InterlockedIncrement64(ptr) - 1)
+ #define ufbxi_atomic_counter_dec(ptr) ((size_t)_InterlockedDecrement64(ptr) + 1)
+ #define ufbxi_atomic_counter_load(ptr) ((size_t)_InterlockedExchangeAdd64((ptr), 0))
+ #else
+ ufbxi_extern_c long __cdecl _InterlockedIncrement(long volatile * lpAddend);
+ ufbxi_extern_c long __cdecl _InterlockedDecrement(long volatile * lpAddend);
+ ufbxi_extern_c long __cdecl _InterlockedExchangeAdd(long volatile * lpAddend, long Value);
+ typedef volatile long ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_inc(ptr) ((size_t)_InterlockedIncrement(ptr) - 1)
+ #define ufbxi_atomic_counter_dec(ptr) ((size_t)_InterlockedDecrement(ptr) + 1)
+ #define ufbxi_atomic_counter_load(ptr) ((size_t)_InterlockedExchangeAdd((ptr), 0))
+ #endif
+#elif !defined(UFBX_STANDARD_C) && defined(__TINYC__)
+ #if defined(__x86_64__) || defined(_AMD64_)
+ static size_t ufbxi_tcc_atomic_add(volatile size_t *dst, size_t value) {
+ __asm__ __volatile__("lock; xaddq %0, %1;" : "+r" (value), "=m" (*dst) : "m" (dst));
+ return value;
+ }
+ #elif defined(__i386__) || defined(_X86_)
+ static size_t ufbxi_tcc_atomic_add(volatile size_t *dst, size_t value) {
+ __asm__ __volatile__("lock; xaddl %0, %1;" : "+r" (value), "=m" (*dst) : "m" (dst));
+ return value;
+ }
+ #else
+ #error Unexpected TCC architecture
+ #endif
+ typedef volatile size_t ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_inc(ptr) ufbxi_tcc_atomic_add((ptr), 1)
+ #define ufbxi_atomic_counter_dec(ptr) ufbxi_tcc_atomic_add((ptr), SIZE_MAX)
+ #define ufbxi_atomic_counter_load(ptr) ufbxi_tcc_atomic_add((ptr), 0)
+#elif defined(__cplusplus) && (__cplusplus >= 201103L)
+ #include <new>
+ #include <atomic>
+ typedef struct { alignas(std::atomic_size_t) char data[sizeof(std::atomic_size_t)]; } ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (new (&(ptr)->data) std::atomic_size_t(0))
+ #define ufbxi_atomic_counter_free(ptr) (((std::atomic_size_t*)(ptr)->data)->~atomic())
+ #define ufbxi_atomic_counter_inc(ptr) ((std::atomic_size_t*)(ptr)->data)->fetch_add(1)
+ #define ufbxi_atomic_counter_dec(ptr) ((std::atomic_size_t*)(ptr)->data)->fetch_sub(1)
+ #define ufbxi_atomic_counter_load(ptr) ((std::atomic_size_t*)(ptr)->data)->load(std::memory_order_acquire)
+#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__)
+ #include <stdatomic.h>
+ typedef volatile atomic_size_t ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) atomic_init(ptr, 0)
+ #define ufbxi_atomic_counter_free(ptr) (void)(ptr)
+ #define ufbxi_atomic_counter_inc(ptr) atomic_fetch_add((ptr), 1)
+ #define ufbxi_atomic_counter_dec(ptr) atomic_fetch_sub((ptr), 1)
+ #define ufbxi_atomic_counter_load(ptr) atomic_load_explicit((ptr), memory_order_acquire)
+#else
+ typedef volatile size_t ufbxi_atomic_counter;
+ #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
+ #define ufbxi_atomic_counter_inc(ptr) ((*(ptr))++)
+ #define ufbxi_atomic_counter_dec(ptr) ((*(ptr))--)
+ #define ufbxi_atomic_counter_load(ptr) (*(ptr))
+ #undef UFBXI_THREAD_SAFE
+ #define UFBXI_THREAD_SAFE 0
+#endif
+
+// ^^ No references to <string.h> before this point ^^
+// vv No more includes past this point vv
+
+#if defined(UFBX_STRING_PREFIX)
+ #define ufbxi_string_fn(name) ufbxi_pre_cat(UFBX_STRING_PREFIX, name)
+ #define strlen ufbxi_string_fn(strlen)
+ #define memcpy ufbxi_string_fn(memcpy)
+ #define memmove ufbxi_string_fn(memmove)
+ #define memset ufbxi_string_fn(memset)
+ #define memchr ufbxi_string_fn(memchr)
+ #define memcmp ufbxi_string_fn(memcmp)
+ #define strcmp ufbxi_string_fn(strcmp)
+ #define strncmp ufbxi_string_fn(strncmp)
+#endif
+
+#if !defined(UFBX_LITTLE_ENDIAN)
+ #if !defined(UFBX_STANDARD_C) && (defined(_M_IX86) || defined(__i386__) || defined(_M_X64) || defined(__x86_64__) || defined(_M_ARM64) || defined(__aarch64__) || defined(__wasm__) || defined(__EMSCRIPTEN__))
+ #define UFBX_LITTLE_ENDIAN 1
+ #else
+ #define UFBX_LITTLE_ENDIAN 0
+ #endif
+#endif
+
+// Unaligned little-endian load functions
+// On platforms that support unaligned access natively (x86, x64, ARM64) just use normal loads,
+// with unaligned attributes, otherwise do manual byte-wise load.
+
+#define ufbxi_read_u8(ptr) (*(const uint8_t*)(ptr))
+
+// Detect support for `__attribute__((aligned(1)))`
+#if !defined(UFBX_STANDARD_C) && (defined(__clang__) && defined(__APPLE__))
+ // Apple overrides Clang versioning, 5.0 here maps to 3.3
+ #if __clang_major__ >= 5
+ #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
+ #endif
+#elif !defined(UFBX_STANDARD_C) && defined(__clang__)
+ #if (__clang_major__ >= 4) || (__clang_major__ == 3 && __clang_minor__ >= 3)
+ #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
+ #endif
+#elif !defined(UFBX_STANDARD_C) && defined(__GNUC__)
+ #if __GNUC__ >= 5
+ #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
+ #endif
+#endif
+
+#if defined(UFBXI_HAS_ATTRIBUTE_ALIGNED)
+ #define UFBXI_HAS_UNALIGNED 1
+ #define UFBXI_HAS_ALIASING 1
+ #define ufbxi_unaligned
+ typedef uint16_t __attribute__((aligned(1))) ufbxi_unaligned_u16;
+ typedef uint32_t __attribute__((aligned(1))) ufbxi_unaligned_u32;
+ typedef uint64_t __attribute__((aligned(1))) ufbxi_unaligned_u64;
+ typedef float __attribute__((aligned(1))) ufbxi_unaligned_f32;
+ typedef double __attribute__((aligned(1))) ufbxi_unaligned_f64;
+ typedef uint32_t __attribute__((may_alias)) ufbxi_aliasing_u32;
+#elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ #define UFBXI_HAS_UNALIGNED 1
+ #if defined(_M_IX86)
+ // MSVC seems to assume all pointers are unaligned for x86
+ #define ufbxi_unaligned
+ #else
+ #define ufbxi_unaligned __unaligned
+ #endif
+ typedef uint16_t ufbxi_unaligned_u16;
+ typedef uint32_t ufbxi_unaligned_u32;
+ typedef uint64_t ufbxi_unaligned_u64;
+ typedef float ufbxi_unaligned_f32;
+ typedef double ufbxi_unaligned_f64;
+ // MSVC doesn't have aliasing types in theory, but it works in practice..
+ #define UFBXI_HAS_ALIASING 1
+ typedef uint32_t ufbxi_aliasing_u32;
+#endif
+
+#if (defined(UFBXI_HAS_UNALIGNED) && UFBX_LITTLE_ENDIAN && !defined(UFBX_NO_UNALIGNED_LOADS)) || defined(UFBX_USE_UNALIGNED_LOADS)
+ #define ufbxi_read_u16(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u16*)(ptr))
+ #define ufbxi_read_u32(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u32*)(ptr))
+ #define ufbxi_read_u64(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u64*)(ptr))
+ #define ufbxi_read_f32(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_f32*)(ptr))
+ #define ufbxi_read_f64(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_f64*)(ptr))
+#else
+ static ufbxi_forceinline uint16_t ufbxi_read_u16(const void *ptr) {
+ const char *p = (const char*)ptr;
+ return (uint16_t)(
+ (unsigned)(uint8_t)p[0] << 0u |
+ (unsigned)(uint8_t)p[1] << 8u );
+ }
+ static ufbxi_forceinline uint32_t ufbxi_read_u32(const void *ptr) {
+ const char *p = (const char*)ptr;
+ return (uint32_t)(
+ (unsigned)(uint8_t)p[0] << 0u |
+ (unsigned)(uint8_t)p[1] << 8u |
+ (unsigned)(uint8_t)p[2] << 16u |
+ (unsigned)(uint8_t)p[3] << 24u );
+ }
+ static ufbxi_forceinline uint64_t ufbxi_read_u64(const void *ptr) {
+ const char *p = (const char*)ptr;
+ return (uint64_t)(
+ (uint64_t)(uint8_t)p[0] << 0u |
+ (uint64_t)(uint8_t)p[1] << 8u |
+ (uint64_t)(uint8_t)p[2] << 16u |
+ (uint64_t)(uint8_t)p[3] << 24u |
+ (uint64_t)(uint8_t)p[4] << 32u |
+ (uint64_t)(uint8_t)p[5] << 40u |
+ (uint64_t)(uint8_t)p[6] << 48u |
+ (uint64_t)(uint8_t)p[7] << 56u );
+ }
+ static ufbxi_forceinline float ufbxi_read_f32(const void *ptr) {
+ uint32_t u = ufbxi_read_u32(ptr);
+ float f;
+ memcpy(&f, &u, 4);
+ return f;
+ }
+ static ufbxi_forceinline double ufbxi_read_f64(const void *ptr) {
+ uint64_t u = ufbxi_read_u64(ptr);
+ double f;
+ memcpy(&f, &u, 8);
+ return f;
+ }
+#endif
+
+#define ufbxi_read_i8(ptr) (int8_t)(ufbxi_read_u8(ptr))
+#define ufbxi_read_i16(ptr) (int16_t)(ufbxi_read_u16(ptr))
+#define ufbxi_read_i32(ptr) (int32_t)(ufbxi_read_u32(ptr))
+#define ufbxi_read_i64(ptr) (int64_t)(ufbxi_read_u64(ptr))
+
+ufbx_static_assert(sizeof_bool, sizeof(bool) == 1);
+ufbx_static_assert(sizeof_char, sizeof(char) == 1);
+ufbx_static_assert(sizeof_i8, sizeof(int8_t) == 1);
+ufbx_static_assert(sizeof_i16, sizeof(int16_t) == 2);
+ufbx_static_assert(sizeof_i32, sizeof(int32_t) == 4);
+ufbx_static_assert(sizeof_i64, sizeof(int64_t) == 8);
+ufbx_static_assert(sizeof_u8, sizeof(uint8_t) == 1);
+ufbx_static_assert(sizeof_u16, sizeof(uint16_t) == 2);
+ufbx_static_assert(sizeof_u32, sizeof(uint32_t) == 4);
+ufbx_static_assert(sizeof_u64, sizeof(uint64_t) == 8);
+ufbx_static_assert(sizeof_f32, sizeof(float) == 4);
+ufbx_static_assert(sizeof_f64, sizeof(double) == 8);
+
+// -- Alignment
+
+#ifndef UFBX_MAXIMUM_ALIGNMENT
+enum { UFBX_MAXIMUM_ALIGNMENT = sizeof(void*) > 8 ? sizeof(void*) : 8 };
+#endif
+
+#if !defined(UFBXI_UINTPTR_SIZE) && !defined(__CHERI__) // CHERI lies about UINTPTR_MAX
+ #if UINTPTR_MAX == UINT64_MAX
+ #define UFBXI_UINTPTR_SIZE 8
+ #elif UINTPTR_MAX == UINT32_MAX
+ #define UFBXI_UINTPTR_SIZE 4
+ #endif
+#endif
+#if defined(UFBXI_UINTPTR_SIZE)
+ ufbx_static_assert(pointer_size, UFBXI_UINTPTR_SIZE == sizeof(uintptr_t));
+#else
+ #define UFBXI_UINTPTR_SIZE 0
+#endif
+
+// -- Version
+
+#define UFBX_SOURCE_VERSION ufbx_pack_version(0, 23, 1)
+ufbx_abi_data_def const uint32_t ufbx_source_version = UFBX_SOURCE_VERSION;
+
+ufbx_static_assert(source_header_version, UFBX_SOURCE_VERSION/1000u == UFBX_HEADER_VERSION/1000u);
+
+// -- Fast copy
+
+#if UFBXI_HAS_SSE
+ #define ufbxi_copy_16_bytes(dst, src) _mm_storeu_si128((__m128i*)(dst), _mm_loadu_si128((const __m128i*)(src)))
+#elif defined(UFBXI_HAS_UNALIGNED)
+ #define ufbxi_copy_16_bytes(dst, src) do { \
+ ufbxi_unaligned ufbxi_unaligned_u64 *mi_dst = (ufbxi_unaligned ufbxi_unaligned_u64 *)(dst); \
+ const ufbxi_unaligned ufbxi_unaligned_u64 *mi_src = (const ufbxi_unaligned ufbxi_unaligned_u64 *)src; \
+ mi_dst[0] = mi_src[0]; \
+ mi_dst[1] = mi_src[1]; \
+ } while (0)
+#else
+ #define ufbxi_copy_16_bytes(dst, src) memcpy((dst), (src), 16)
+#endif
+
+
+// -- Large fast integer
+
+#if !defined(UFBX_STANDARD_C) && (defined(__wasm__) || defined(__EMSCRIPTEN__)) && !defined(UFBX_WASM_32BIT)
+ typedef uint64_t ufbxi_fast_uint;
+#else
+ typedef size_t ufbxi_fast_uint;
+#endif
+
+// -- Wrapping right shift
+
+#if !defined(UFBX_UBSAN) && UFBXI_ARCH_X64
+ #define ufbxi_wrap_shr64(a, b) ((a) >> (b))
+#else
+ #define ufbxi_wrap_shr64(a, b) ((a) >> ((b) & 63))
+#endif
+
+// -- Bit manipulation
+
+#if !defined(UFBX_STANDARD_C) && defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
+ ufbxi_extern_c unsigned char _BitScanReverse(unsigned long * _Index, unsigned long _Mask);
+ ufbxi_extern_c unsigned char _BitScanReverse64(unsigned long * _Index, unsigned __int64 _Mask);
+ static ufbxi_forceinline ufbxi_unused uint32_t ufbxi_lzcnt32(uint32_t v) {
+ unsigned long index;
+ _BitScanReverse(&index, (unsigned long)v);
+ return 31 - (uint32_t)index;
+ }
+ static ufbxi_forceinline ufbxi_unused uint32_t ufbxi_lzcnt64(uint64_t v) {
+ unsigned long index;
+ #if defined(_M_X64)
+ _BitScanReverse64(&index, (unsigned __int64)v);
+ #else
+ uint32_t hi = (uint32_t)(v >> 32u);
+ uint32_t hi_nonzero = hi != 0 ? 1 : 0;
+ uint32_t part = hi_nonzero ? hi : (uint32_t)v;
+ _BitScanReverse(&index, (unsigned long)part);
+ index += hi_nonzero * 32u;
+ #endif
+ return 63 - (uint32_t)index;
+ }
+#elif !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__))
+ #define ufbxi_lzcnt32(v) ((uint32_t)__builtin_clz((unsigned)(v)))
+ #define ufbxi_lzcnt64(v) ((uint32_t)__builtin_clzll((unsigned long long)(v)))
+#else
+ // DeBrujin table lookup
+ static const uint8_t ufbxi_lzcnt32_table[] = {
+ 31, 22, 30, 21, 18, 10, 29, 2, 20, 17, 15, 13, 9, 6, 28, 1, 23, 19, 11, 3, 16, 14, 7, 24, 12, 4, 8, 25, 5, 26, 27, 0,
+ };
+ static const uint8_t ufbxi_lzcnt64_table[] = {
+ 63, 16, 62, 7, 15, 36, 61, 3, 6, 14, 22, 26, 35, 47, 60, 2, 9, 5, 28, 11, 13, 21, 42,
+ 19, 25, 31, 34, 40, 46, 52, 59, 1, 17, 8, 37, 4, 23, 27, 48, 10, 29, 12, 43, 20, 32, 41,
+ 53, 18, 38, 24, 49, 30, 44, 33, 54, 39, 50, 45, 55, 51, 56, 57, 58, 0,
+ };
+ static ufbxi_noinline ufbxi_unused uint32_t ufbxi_lzcnt32(uint32_t v) {
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ return ufbxi_lzcnt32_table[(v * 0x07c4acddu) >> 27];
+ }
+ static ufbxi_noinline ufbxi_unused uint32_t ufbxi_lzcnt64(uint64_t v) {
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ v |= v >> 32;
+ return ufbxi_lzcnt64_table[(v * UINT64_C(0x03f79d71b4cb0a89)) >> 58];
+ }
+#endif
+
+// -- Bit conversion
+
+#if defined(__cplusplus)
+ #define ufbxi_bit_cast(m_dst_type, m_dst, m_src_type, m_src) memcpy(&(m_dst), &(m_src), sizeof(m_dst_type))
+#else
+ #define ufbxi_bit_cast(m_dst_type, m_dst, m_src_type, m_src) do { \
+ union { m_dst_type mi_dst; m_src_type mi_src; } mi_union; \
+ mi_union.mi_src = (m_src); (m_dst) = mi_union.mi_dst; } while (0)
+#endif
+
+// -- Pointer alignment
+
+#if !defined(UFBX_STANDARD_C) && defined(__GNUC__) && defined(__has_builtin)
+ #if __has_builtin(__builtin_is_aligned)
+ #define ufbxi_is_aligned(m_ptr, m_align) __builtin_is_aligned((m_ptr), (m_align))
+ #define ufbxi_is_aligned_mask(m_ptr, m_align) __builtin_is_aligned((m_ptr), (m_align) + 1)
+ #endif
+#endif
+#ifndef ufbxi_is_aligned
+ #define ufbxi_is_aligned(m_ptr, m_align) (((uintptr_t)(m_ptr) & ((m_align) - 1)) == 0)
+ #define ufbxi_is_aligned_mask(m_ptr, m_align) (((uintptr_t)(m_ptr) & (m_align)) == 0)
+#endif
+
+// -- Debug
+
+#if defined(UFBX_DEBUG_BINARY_SEARCH) || defined(UFBX_REGRESSION)
+ #define ufbxi_clamp_linear_threshold(v) (2)
+#else
+ #define ufbxi_clamp_linear_threshold(v) (v)
+#endif
+
+#if defined(UFBX_REGRESSION)
+ #undef UFBXI_MAX_SKIP_SIZE
+ #define UFBXI_MAX_SKIP_SIZE 128
+
+ #undef UFBXI_MAP_MAX_SCAN
+ #define UFBXI_MAP_MAX_SCAN 2
+
+ #undef UFBXI_KD_FAST_DEPTH
+ #define UFBXI_KD_FAST_DEPTH 2
+
+ #undef UFBXI_FACE_GROUP_HASH_BITS
+ #define UFBXI_FACE_GROUP_HASH_BITS 2
+#endif
+
+#if defined(UFBX_REGRESSION) || defined(UFBX_EXTENSIVE_THREADING)
+ #undef UFBXI_MIN_THREADED_DEFLATE_BYTES
+ #define UFBXI_MIN_THREADED_DEFLATE_BYTES 2
+
+ #undef UFBXI_MIN_THREADED_ASCII_VALUES
+ #define UFBXI_MIN_THREADED_ASCII_VALUES 2
+#endif
+
+#if defined(UFBX_REGRESSION)
+ #define ufbxi_regression_assert(cond) ufbx_assert(cond)
+#else
+ #define ufbxi_regression_assert(cond) (void)0
+#endif
+
+#if defined(UFBX_REGRESSION) || defined(UFBX_DEV) || defined(UFBX_UBSAN)
+ #define ufbxi_dev_assert(cond) ufbx_assert(cond)
+#else
+ #define ufbxi_dev_assert(cond) (void)0
+#endif
+
+#define ufbxi_unreachable(reason) do { ufbx_assert(0 && reason); } while (0)
+
+#if defined(UFBX_REGRESSION)
+ #define UFBXI_IS_REGRESSION 1
+#else
+ #define UFBXI_IS_REGRESSION 0
+#endif
+
+#if defined(_MSC_VER)
+ #define ufbxi_thread_local __declspec(thread)
+#elif defined(__GNUC__) || defined(__clang__)
+ #define ufbxi_thread_local __thread
+#elif UFBXI_HAS_CPP11
+ #define ufbxi_thread_local thread_local
+#elif UFBX_STDC >= 201112L
+ #define ufbxi_thread_local _Thread_local
+#endif
+
+#if defined(UFBXI_ANALYSIS_RECURSIVE)
+ #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params) UFBXI_RECURSIVE_FUNCTION(m_name, m_max_depth);
+ #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params) UFBXI_RECURSIVE_FUNCTION(m_name, m_max_depth);
+#elif UFBXI_IS_REGRESSION && defined(ufbxi_thread_local)
+ #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params) \
+ { \
+ m_ret m_name##_rec m_params; \
+ static ufbxi_thread_local unsigned ufbxi_recursion_depth; \
+ ufbx_assert(ufbxi_recursion_depth < m_max_depth); \
+ ++ufbxi_recursion_depth; \
+ m_ret ret = m_name##_rec m_args; \
+ --ufbxi_recursion_depth; \
+ return ret; \
+ } \
+ m_ret m_name##_rec m_params
+ #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params) \
+ { \
+ void m_name##_rec m_params; \
+ static ufbxi_thread_local unsigned ufbxi_recursion_depth; \
+ ufbx_assert(ufbxi_recursion_depth < m_max_depth); \
+ ++ufbxi_recursion_depth; \
+ m_name##_rec m_args; \
+ --ufbxi_recursion_depth; \
+ } \
+ void m_name##_rec m_params
+#else
+ #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params)
+ #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params)
+#endif
+
+// -- Utility
+
+#if defined(UFBX_UBSAN)
+ static void ufbxi_assert_zero(size_t offset) { (void)offset; ufbx_assert(offset == 0); }
+ #define ufbxi_add_ptr(ptr, offset) ((ptr) ? (ptr) + (offset) : (ufbxi_assert_zero((size_t)(offset)), (ptr)))
+ #define ufbxi_sub_ptr(ptr, offset) ((ptr) ? (ptr) - (offset) : (ufbxi_assert_zero((size_t)(offset)), (ptr)))
+#else
+ #define ufbxi_add_ptr(ptr, offset) ((ptr) + (offset))
+ #define ufbxi_sub_ptr(ptr, offset) ((ptr) - (offset))
+#endif
+
+#define ufbxi_arraycount(arr) (sizeof(arr) / sizeof(*(arr)))
+#define ufbxi_for(m_type, m_name, m_begin, m_num) for (m_type *m_name = m_begin, *m_name##_end = ufbxi_add_ptr(m_name, m_num); m_name != m_name##_end; m_name++)
+#define ufbxi_for_ptr(m_type, m_name, m_begin, m_num) for (m_type **m_name = m_begin, **m_name##_end = ufbxi_add_ptr(m_name, m_num); m_name != m_name##_end; m_name++)
+
+// WARNING: Evaluates `m_list` twice!
+#define ufbxi_for_list(m_type, m_name, m_list) for (m_type *m_name = (m_list).data, *m_name##_end = ufbxi_add_ptr(m_name, (m_list).count); m_name != m_name##_end; m_name++)
+#define ufbxi_for_ptr_list(m_type, m_name, m_list) for (m_type **m_name = (m_list).data, **m_name##_end = ufbxi_add_ptr(m_name, (m_list).count); m_name != m_name##_end; m_name++)
+
+#define ufbxi_string_literal(str) { str, sizeof(str) - 1 }
+
+static ufbxi_forceinline uint32_t ufbxi_min32(uint32_t a, uint32_t b) { return a < b ? a : b; }
+static ufbxi_forceinline uint32_t ufbxi_max32(uint32_t a, uint32_t b) { return a < b ? b : a; }
+static ufbxi_forceinline uint64_t ufbxi_min64(uint64_t a, uint64_t b) { return a < b ? a : b; }
+static ufbxi_forceinline uint64_t ufbxi_max64(uint64_t a, uint64_t b) { return a < b ? b : a; }
+static ufbxi_forceinline size_t ufbxi_min_sz(size_t a, size_t b) { return a < b ? a : b; }
+static ufbxi_forceinline size_t ufbxi_max_sz(size_t a, size_t b) { return a < b ? b : a; }
+static ufbxi_forceinline ufbx_real ufbxi_min_real(ufbx_real a, ufbx_real b) { return a < b ? a : b; }
+static ufbxi_forceinline ufbx_real ufbxi_max_real(ufbx_real a, ufbx_real b) { return a < b ? b : a; }
+
+static ufbxi_forceinline int32_t ufbxi_f64_to_i32(double value)
+{
+ if (ufbx_fabs(value) <= (double)INT32_MAX) {
+ return (int32_t)value;
+ } else {
+ return value >= 0.0 ? INT32_MAX : INT32_MIN;
+ }
+}
+
+static ufbxi_forceinline int64_t ufbxi_f64_to_i64(double value)
+{
+ if (ufbx_fabs(value) <= (double)INT64_MAX) {
+ return (int64_t)value;
+ } else {
+ return value >= 0.0 ? INT64_MAX : INT64_MIN;
+ }
+}
+
+#if defined(UFBX_REGRESSION)
+ static size_t ufbxi_to_size(ptrdiff_t delta) {
+ ufbx_assert(delta >= 0);
+ return (size_t)delta;
+ }
+#else
+ #define ufbxi_to_size(delta) ((size_t)(delta))
+#endif
+
+// Stable sort array `m_type m_data[m_size]` using the predicate `m_cmp_lambda(a, b)`
+// `m_linear_size` is a hint for how large blocks handle initially do with insertion sort
+// `m_tmp` must be a memory buffer with at least the same size and alignment as `m_data`
+#define ufbxi_macro_stable_sort(m_type, m_linear_size, m_data, m_tmp, m_size, m_cmp_lambda) do { \
+ typedef m_type mi_type; \
+ mi_type *mi_src = (mi_type*)(m_tmp); \
+ mi_type *mi_data = m_data, *mi_dst = mi_data; \
+ size_t mi_block_size = ufbxi_clamp_linear_threshold(m_linear_size), mi_size = m_size; \
+ /* Insertion sort in `m_linear_size` blocks */ \
+ for (size_t mi_base = 0; mi_base < mi_size; mi_base += mi_block_size) { \
+ size_t mi_i_end = mi_base + mi_block_size; \
+ if (mi_i_end > mi_size) mi_i_end = mi_size; \
+ for (size_t mi_i = mi_base + 1; mi_i < mi_i_end; mi_i++) { \
+ size_t mi_j = mi_i; \
+ mi_src[0] = mi_dst[mi_i]; \
+ for (; mi_j != mi_base; --mi_j) { \
+ mi_type *a = &mi_src[0], *b = &mi_dst[mi_j - 1]; \
+ if (!( m_cmp_lambda )) break; \
+ mi_dst[mi_j] = mi_dst[mi_j - 1]; \
+ } \
+ mi_dst[mi_j] = mi_src[0]; \
+ } \
+ } \
+ /* Merge sort ping-ponging between `m_data` and `m_tmp` */ \
+ for (; mi_block_size < mi_size; mi_block_size *= 2) { \
+ mi_type *mi_swap = mi_dst; mi_dst = mi_src; mi_src = mi_swap; \
+ for (size_t mi_base = 0; mi_base < mi_size; mi_base += mi_block_size * 2) { \
+ size_t mi_i = mi_base, mi_i_end = mi_base + mi_block_size; \
+ size_t mi_j = mi_i_end, mi_j_end = mi_j + mi_block_size; \
+ size_t mi_k = mi_base; \
+ if (mi_i_end > mi_size) mi_i_end = mi_size; \
+ if (mi_j_end > mi_size) mi_j_end = mi_size; \
+ while ((mi_i < mi_i_end) & (mi_j < mi_j_end)) { \
+ mi_type *a = &mi_src[mi_j], *b = &mi_src[mi_i]; \
+ if ( m_cmp_lambda ) { \
+ mi_dst[mi_k] = *a; mi_j++; \
+ } else { \
+ mi_dst[mi_k] = *b; mi_i++; \
+ } \
+ mi_k++; \
+ } \
+ while (mi_i < mi_i_end) mi_dst[mi_k++] = mi_src[mi_i++]; \
+ while (mi_j < mi_j_end) mi_dst[mi_k++] = mi_src[mi_j++]; \
+ } \
+ } \
+ /* Copy the result to `m_data` if we ended up in `m_tmp` */ \
+ if (mi_dst != mi_data) memcpy((void*)mi_data, mi_dst, sizeof(mi_type) * mi_size); \
+ } while (0)
+
+#define ufbxi_macro_lower_bound_eq(m_type, m_linear_size, m_result_ptr, m_data, m_begin, m_size, m_cmp_lambda, m_eq_lambda) do { \
+ typedef m_type mi_type; \
+ const mi_type *mi_data = (m_data); \
+ size_t mi_lo = m_begin, mi_hi = m_size, mi_linear_size = ufbxi_clamp_linear_threshold(m_linear_size); \
+ ufbx_assert(mi_linear_size > 1); \
+ /* Binary search until we get down to `m_linear_size` elements */ \
+ while (mi_hi - mi_lo > mi_linear_size) { \
+ size_t mi_mid = mi_lo + (mi_hi - mi_lo) / 2; \
+ const mi_type *a = &mi_data[mi_mid]; \
+ if ( m_cmp_lambda ) { mi_lo = mi_mid + 1; } else { mi_hi = mi_mid + 1; } \
+ } \
+ /* Linearly scan until we find the edge */ \
+ for (; mi_lo < mi_hi; mi_lo++) { \
+ const mi_type *a = &mi_data[mi_lo]; \
+ if ( m_eq_lambda ) { *(m_result_ptr) = mi_lo; break; } \
+ } \
+ } while (0)
+
+#define ufbxi_macro_upper_bound_eq(m_type, m_linear_size, m_result_ptr, m_data, m_begin, m_size, m_eq_lambda) do { \
+ typedef m_type mi_type; \
+ const mi_type *mi_data = (m_data); \
+ size_t mi_lo = m_begin, mi_hi = m_size, mi_linear_size = ufbxi_clamp_linear_threshold(m_linear_size); \
+ ufbx_assert(mi_linear_size > 1); \
+ /* Linearly scan with galloping */ \
+ for (size_t mi_step = 1; mi_step < 100 && mi_hi - mi_lo > mi_step; mi_step *= 2) { \
+ const mi_type *a = &mi_data[mi_lo + mi_step]; \
+ if (!( m_eq_lambda )) { mi_hi = mi_lo + mi_step; break; } \
+ mi_lo += mi_step; \
+ } \
+ /* Binary search until we get down to `m_linear_size` elements */ \
+ while (mi_hi - mi_lo > mi_linear_size) { \
+ size_t mi_mid = mi_lo + (mi_hi - mi_lo) / 2; \
+ const mi_type *a = &mi_data[mi_mid]; \
+ if ( m_eq_lambda ) { mi_lo = mi_mid + 1; } else { mi_hi = mi_mid + 1; } \
+ } \
+ /* Linearly scan until we find the edge */ \
+ for (; mi_lo < mi_hi; mi_lo++) { \
+ const mi_type *a = &mi_data[mi_lo]; \
+ if (!( m_eq_lambda )) break; \
+ } \
+ *(m_result_ptr) = mi_lo; \
+ } while (0)
+
+typedef bool ufbxi_less_fn(void *user, const void *a, const void *b);
+
+static ufbxi_noinline void ufbxi_stable_sort(size_t stride, size_t linear_size, void *in_data, void *in_tmp, size_t size, ufbxi_less_fn *less_fn, void *less_user)
+{
+ (void)linear_size;
+
+ char *src = (char*)in_tmp;
+ char *data = (char*)in_data, *dst = (char*)data;
+ size_t block_size = ufbxi_clamp_linear_threshold(linear_size);
+ /* Insertion sort in `linear_size` blocks */
+ for (size_t base = 0; base < size; base += block_size) {
+ size_t i_end = base + block_size;
+ if (i_end > size) i_end = size;
+ for (size_t i = base + 1; i < i_end; i++) {
+
+ {
+ char *a = dst + i * stride, *b = dst + (i - 1) * stride;
+ if (!less_fn(less_user, a, b)) continue;
+ }
+
+ size_t j = i - 1;
+ memcpy(src, dst + i * stride, stride);
+ memcpy(dst + i * stride, dst + j * stride, stride);
+ for (; j != base; --j) {
+ char *a = src, *b = dst + (j - 1) * stride;
+ if (!less_fn(less_user, a, b)) break;
+ memcpy(dst + j * stride, dst + (j - 1) * stride, stride);
+ }
+ memcpy(dst + j * stride, src, stride);
+ }
+ }
+ /* Merge sort ping-ponging between `data` and `tmp` */
+ for (; block_size < size; block_size *= 2) {
+ char *swap = dst; dst = src; src = swap;
+ for (size_t base = 0; base < size; base += block_size * 2) {
+ size_t i = base, i_end = base + block_size;
+ size_t j = i_end, j_end = j + block_size;
+ size_t k = base;
+ if (i_end > size) i_end = size;
+ if (j_end > size) j_end = size;
+ while ((i < i_end) & (j < j_end)) {
+ char *a = src + j * stride, *b = src + i * stride;
+ if (less_fn(less_user, a, b)) {
+ memcpy(dst + k * stride, a, stride);
+ j++;
+ } else {
+ memcpy(dst + k * stride, b, stride);
+ i++;
+ }
+ k++;
+ }
+
+ memcpy(dst + k * stride, src + i * stride, (i_end - i) * stride);
+ if (j < j_end) {
+ memcpy(dst + (k + (i_end - i)) * stride, src + j * stride, (j_end - j) * stride);
+ }
+ }
+ }
+ /* Copy the result to `data` if we ended up in `tmp` */
+ if (dst != data) memcpy((void*)data, dst, size * stride);
+}
+
+static ufbxi_forceinline void ufbxi_swap(void *a, void *b, size_t size)
+{
+#if UFBXI_HAS_ALIASING && !defined(__CHERI__) // CHERI needs to copy pointer metadata tag bits..
+ ufbxi_dev_assert(size % 4 == 0 && (uintptr_t)a % 4 == 0 && (uintptr_t)b % 4 == 0);
+ char *ca = (char*)a, *cb = (char*)b;
+ for (size_t i = 0; i < size; i += 4, ca += 4, cb += 4) {
+ ufbxi_aliasing_u32 *ua = (ufbxi_aliasing_u32*)ca, *ub = (ufbxi_aliasing_u32*)cb;
+ uint32_t va = *ua, vb = *ub;
+ *ua = vb;
+ *ub = va;
+ }
+#else
+ union {
+ void *align_ptr;
+ uintptr_t align_uptr;
+ uint64_t align_u64;
+ char data[256];
+ } tmp;
+ ufbxi_dev_assert(size <= sizeof(tmp));
+ memcpy(tmp.data, a, size);
+ memcpy(a, b, size);
+ memcpy(b, tmp.data, size);
+#endif
+}
+
+static ufbxi_noinline void ufbxi_unstable_sort(void *in_data, size_t size, size_t stride, ufbxi_less_fn *less_fn, void *less_user)
+{
+ if (size <= 1) return;
+
+ char *data = (char*)in_data;
+ size_t start = (size - 1) >> 1;
+ size_t end = size - 1;
+ for (;;) {
+ size_t root = start;
+ size_t child;
+ while ((child = root*2 + 1) <= end) {
+ size_t next = less_fn(less_user, data + child * stride, data + root * stride) ? root : child;
+ if (child + 1 <= end && less_fn(less_user, data + next * stride, data + (child + 1) * stride)) {
+ next = child + 1;
+ }
+ if (next == root) break;
+ ufbxi_swap(data + root * stride, data + next * stride, stride);
+ root = next;
+ }
+
+ if (start > 0) {
+ start--;
+ } else if (end > 0) {
+ ufbxi_swap(data + end * stride, data, stride);
+ end--;
+ } else {
+ break;
+ }
+ }
+}
+
+// -- Float parsing
+
+#define UFBXI_BIGINT_LIMB_BITS 32
+#define UFBXI_BIGINT_ACCUM_BITS (UFBXI_BIGINT_LIMB_BITS * 2)
+#define UFBXI_BIGINT_LIMB_MAX (ufbxi_bigint_limb)(((ufbxi_bigint_accum)1 << UFBXI_BIGINT_LIMB_BITS) - 1)
+typedef uint32_t ufbxi_bigint_limb;
+typedef uint64_t ufbxi_bigint_accum;
+
+typedef struct {
+ ufbxi_bigint_limb *limbs;
+ uint32_t capacity;
+ uint32_t length;
+} ufbxi_bigint;
+
+static ufbxi_bigint ufbxi_bigint_make(ufbxi_bigint_limb *limbs, size_t capacity)
+{
+ ufbxi_bigint bi = { limbs, (uint32_t)capacity };
+ return bi;
+}
+
+#define ufbxi_bigint_array(arr) ufbxi_bigint_make((arr), sizeof(arr) / sizeof(*(arr)))
+
+static const uint64_t ufbxi_pow5_tab[] = {
+ UINT64_C(0x1), UINT64_C(0x5), UINT64_C(0x19), UINT64_C(0x7d), UINT64_C(0x271), UINT64_C(0xc35), UINT64_C(0x3d09), UINT64_C(0x1312d), UINT64_C(0x5f5e1),
+ UINT64_C(0x1dcd65), UINT64_C(0x9502f9), UINT64_C(0x2e90edd), UINT64_C(0xe8d4a51), UINT64_C(0x48c27395), UINT64_C(0x16bcc41e9), UINT64_C(0x71afd498d),
+ UINT64_C(0x2386f26fc1), UINT64_C(0xb1a2bc2ec5), UINT64_C(0x3782dace9d9), UINT64_C(0x1158e460913d), UINT64_C(0x56bc75e2d631), UINT64_C(0x1b1ae4d6e2ef5),
+ UINT64_C(0x878678326eac9), UINT64_C(0x2a5a058fc295ed), UINT64_C(0xd3c21bcecceda1), UINT64_C(0x422ca8b0a00a425), UINT64_C(0x14adf4b7320334b9), UINT64_C(0x6765c793fa10079d),
+};
+
+static const double ufbxi_pow10_tab_f64[] = {
+ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
+};
+
+static ufbxi_noinline void ufbxi_bigint_mad(ufbxi_bigint *bigint, ufbxi_bigint_accum multiplicand, ufbxi_bigint_accum addend)
+{
+ ufbxi_dev_assert((multiplicand | addend) >> (UFBXI_BIGINT_ACCUM_BITS - 1) == 0);
+ ufbxi_bigint b = *bigint;
+ ufbxi_bigint_limb m_lo = (ufbxi_bigint_limb)multiplicand;
+ ufbxi_bigint_limb m_hi = (ufbxi_bigint_limb)(multiplicand >> UFBXI_BIGINT_LIMB_BITS);
+ ufbxi_bigint_accum carry = addend;
+ for (uint32_t i = 0; i < b.length; i++) {
+ ufbxi_bigint_accum limb = (ufbxi_bigint_accum)b.limbs[i];
+ ufbxi_bigint_accum lo = limb * m_lo + (carry & UFBXI_BIGINT_LIMB_MAX);
+ ufbxi_bigint_accum hi = limb * m_hi;
+ b.limbs[i] = (ufbxi_bigint_limb)lo;
+ carry = (carry >> 32u) + (lo >> 32u) + hi;
+ }
+ while (carry) {
+ b.limbs[b.length++] = (ufbxi_bigint_limb)carry;
+ ufbxi_dev_assert(b.length < b.capacity);
+ carry >>= 32u;
+ }
+ bigint->length = b.length;
+}
+
+static ufbxi_noinline bool ufbxi_bigint_div(ufbxi_bigint *q, ufbxi_bigint *u, ufbxi_bigint *v)
+{
+ int32_t n = (int32_t)v->length;
+ int32_t m = (int32_t)u->length - n;
+ ufbxi_bigint_limb v_hi = v->limbs[v->length - 1];
+ ufbxi_bigint_limb *un = u->limbs, *vn = v->limbs;
+ ufbxi_dev_assert(n >= 2 && m >= 1 && v_hi >> (UFBXI_BIGINT_LIMB_BITS - 1) != 0 && un[n+m - 1] >> (UFBXI_BIGINT_LIMB_BITS - 1) == 0);
+ un[n + m] = 0;
+ q->length = 0;
+ for (int32_t j = m - 1; j >= 0; j--) {
+ ufbxi_bigint_accum u_hi = ((ufbxi_bigint_accum)un[n+j] << UFBXI_BIGINT_LIMB_BITS) | un[n+j-1];
+ ufbxi_bigint_accum t, qhat = u_hi / v_hi, rhat = u_hi % v_hi;
+ while (qhat >> UFBXI_BIGINT_LIMB_BITS != 0 || qhat*vn[n-2] > ((rhat<<UFBXI_BIGINT_LIMB_BITS)|un[j+n-2])) {
+ qhat -= 1;
+ rhat += v_hi;
+ if (rhat >> UFBXI_BIGINT_LIMB_BITS != 0) break;
+ }
+ ufbxi_bigint_limb carry = 0;
+ for (int32_t i = 0; i < n; i++) {
+ ufbxi_bigint_accum p = qhat * vn[i];
+ t = (ufbxi_bigint_accum)un[i+j] - carry - (ufbxi_bigint_limb)p;
+ un[i+j] = (ufbxi_bigint_limb)t;
+ carry = (ufbxi_bigint_limb)((p >> UFBXI_BIGINT_LIMB_BITS) - (t >> UFBXI_BIGINT_LIMB_BITS));
+ }
+ t = (ufbxi_bigint_accum)un[j+n] - carry;
+ un[j+n] = (ufbxi_bigint_limb)t;
+ if (t >> UFBXI_BIGINT_LIMB_BITS != 0) {
+ qhat -= 1;
+ carry = 0;
+ for (int32_t i = 0; i < n; i++) {
+ t = (ufbxi_bigint_accum)un[i+j] + vn[i] + carry;
+ un[i+j] = (ufbxi_bigint_limb)t;
+ carry = (ufbxi_bigint_limb)(t >> UFBXI_BIGINT_LIMB_BITS);
+ }
+ un[j+n] += carry;
+ }
+ q->limbs[j] = (ufbxi_bigint_limb)qhat;
+ if (qhat && !q->length) {
+ ufbxi_dev_assert(j + 1 < (int32_t)q->capacity);
+ q->length = (uint32_t)(j + 1);
+ }
+ }
+ for (int32_t i = 0; i < n; i++) {
+ if (un[i]) return true;
+ }
+ return false;
+}
+
+static void ufbxi_bigint_mul_pow5(ufbxi_bigint *b, uint32_t power)
+{
+ for (; power > 27; power -= 27) {
+ ufbxi_bigint_mad(b, ufbxi_pow5_tab[27], 0);
+ }
+ ufbxi_bigint_mad(b, ufbxi_pow5_tab[power], 0);
+}
+
+static ufbxi_noinline void ufbxi_bigint_shift_left(ufbxi_bigint *bigint, uint32_t amount)
+{
+ uint32_t words = amount / UFBXI_BIGINT_LIMB_BITS, bits = amount % UFBXI_BIGINT_LIMB_BITS;
+ ufbxi_bigint b = *bigint;
+ ufbxi_dev_assert(b.length + words + 1 < b.capacity && b.capacity >= 4);
+ uint32_t bits_down = UFBXI_BIGINT_LIMB_BITS - bits - 1;
+ bigint->length += words + (b.limbs[b.length - 1] >> 1 >> bits_down != 0 ? 1 : 0);
+ b.limbs[b.length] = 0;
+ if (b.length <= 3 && words <= 3) {
+ ufbxi_bigint_limb l0 = b.limbs[0];
+ ufbxi_bigint_limb l1 = ufbxi_maybe_uninit(b.length >= 1, b.limbs[1], ~0u);
+ ufbxi_bigint_limb l2 = ufbxi_maybe_uninit(b.length >= 2, b.limbs[2], ~0u);
+ b.limbs[0] = 0;
+ b.limbs[1] = 0;
+ b.limbs[2] = 0;
+ b.limbs[words + 0] = l0 << bits;
+ b.limbs[words + 1] = (l1 << bits) | (l0 >> 1 >> bits_down);
+ b.limbs[words + 2] = (l2 << bits) | (l1 >> 1 >> bits_down);
+ b.limbs[words + 3] = (l2 >> 1 >> bits_down);
+ } else {
+ for (uint32_t i = b.length + 1; i-- > 1; ) {
+ b.limbs[i + words] = (b.limbs[i] << bits) | (b.limbs[i - 1] >> 1 >> bits_down);
+ }
+ b.limbs[words] = b.limbs[0] << bits;
+ for (uint32_t i = 0; i < words; i++) {
+ b.limbs[i] = 0;
+ }
+ }
+}
+
+static ufbxi_bigint_limb ufbxi_bigint_top_limb(const ufbxi_bigint b, uint32_t index) {
+ return index < b.length ? b.limbs[b.length - 1 - index] : 0;
+}
+
+static ufbxi_noinline uint64_t ufbxi_bigint_extract_high(const ufbxi_bigint b, int32_t *p_exponent, bool *p_tail)
+{
+ ufbxi_dev_assert(b.length != 0);
+ uint64_t result = 0;
+ const uint32_t limb_count = 64 / UFBXI_BIGINT_LIMB_BITS;
+ for (uint32_t i = 0; i < limb_count; i++) {
+ result = (result << UFBXI_BIGINT_LIMB_BITS) | ufbxi_bigint_top_limb(b, i);
+ }
+ uint32_t shift = ufbxi_lzcnt64(result);
+ result <<= shift;
+ ufbxi_bigint_limb lo = ufbxi_bigint_top_limb(b, limb_count);
+ if (shift > 0) {
+ result |= lo >> (UFBXI_BIGINT_LIMB_BITS - shift);
+ }
+ *p_tail |= (ufbxi_bigint_limb)(lo << shift) != 0;
+ for (uint32_t i = limb_count + 1; i < b.length; i++) {
+ *p_tail |= ufbxi_bigint_top_limb(b, i) != 0;
+ }
+ *p_exponent += (int32_t)(b.length * UFBXI_BIGINT_LIMB_BITS - shift - 1);
+ return result;
+}
+
+static uint64_t ufbxi_shift_right_round(uint64_t value, uint32_t shift, bool tail)
+{
+ if (shift == 0) return value;
+ if (shift > 64) return 0;
+ uint64_t result = value >> (shift - 1);
+ uint64_t tail_mask = (UINT64_C(1) << (shift - 1)) - 1;
+
+ bool r_odd = (result & 0x2) != 0;
+ bool r_round = (result & 0x1) != 0;
+ bool r_tail = tail || (value & tail_mask) != 0;
+ uint64_t round_bit = (r_round && (r_odd || r_tail)) ? 1u : 0u;
+
+ return (result >> 1u) + round_bit;
+}
+
+typedef enum {
+ UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH = 0x1,
+ UFBXI_PARSE_DOUBLE_AS_BINARY32 = 0x2,
+} ufbxi_parse_double_flag;
+
+static bool ufbxi_scan_ignorecase(const char *p, const char *end, const char *fmt)
+{
+ for (const char *f = fmt; *f; f++, p++) {
+ if (p >= end) return false;
+ if ((*p | 0x20) != *f) return false;
+ }
+ return true;
+}
+
+static ufbxi_noinline bool ufbxi_parse_inf_nan(double *p_result, const char *str, size_t max_length, char **p_end)
+{
+ bool negative = false;
+ const char *p = str, *end = p + max_length;
+ if (p != end && (*p == '+' || *p == '-')) {
+ negative = *p++ == '-';
+ }
+
+ uint32_t top_bits = 0;
+ if (end - p >= 3 && (p[0] >= '0' && p[0] <= '9') && p[1] == '.' && p[2] == '#') {
+ // Legacy MSVC 1.#NAN
+ p += 3;
+ if (ufbxi_scan_ignorecase(p, end, "inf")) {
+ p += 3;
+ top_bits = 0x7ff0;
+ } else if (ufbxi_scan_ignorecase(p, end, "nan") || ufbxi_scan_ignorecase(p, end, "ind")) {
+ p += 3;
+ top_bits = 0x7ff8;
+ } else {
+ return false;
+ }
+ while (p != end && *p >= '0' && *p <= '9') {
+ p++;
+ }
+ } else {
+ // Standard
+ if (ufbxi_scan_ignorecase(p, end, "nan")) {
+ p += 3;
+ top_bits = 0x7ff8;
+ if (p != end && *p == '(') {
+ p++;
+ while (p != end && *p != ')') {
+ char c = *p;
+ if (!((c>='0'&&c<='9') || (c>='a'&&c<='z') || (c>='A'&&c<='Z'))) {
+ return false;
+ }
+ p++;
+ }
+ if (p == end) return false;
+ p++;
+ }
+ } else if (ufbxi_scan_ignorecase(p, end, "inf")) {
+ p += ufbxi_scan_ignorecase(p + 3, end, "inity") ? 8 : 3;
+ top_bits = 0x7ff0;
+ }
+ }
+
+ *p_end = (char*)p;
+ top_bits |= negative ? 0x8000 : 0;
+ uint64_t bits = (uint64_t)top_bits << 48;
+ double result;
+ ufbxi_bit_cast(double, result, uint64_t, bits);
+ *p_result = result;
+ return true;
+}
+
+static ufbxi_noinline double ufbxi_parse_double(const char *str, size_t max_length, char **p_end, uint32_t flags)
+{
+ const uint32_t max_limbs = 14;
+
+ ufbxi_bigint_limb mantissa_limbs[42], divisor_limbs[42], quotient_limbs[42];
+ ufbxi_bigint big_mantissa = ufbxi_bigint_array(mantissa_limbs);
+ ufbxi_bigint big_quotient = ufbxi_bigint_array(quotient_limbs);
+ int32_t dec_exponent = 0, has_dot = 0;
+ bool negative = false, tail = false, digits_valid = true;
+ uint64_t digits = 0;
+ uint32_t num_digits = 0;
+
+ const char *p = str, *end = p + max_length;
+ if (p != end && (*p == '+' || *p == '-')) {
+ negative = *p++ == '-';
+ }
+ while (p != end) {
+ char c = *p;
+ if (c >= '0' && c <= '9') {
+ if (big_mantissa.length < max_limbs) {
+ digits = digits * 10 + (uint64_t)(c - '0');
+ num_digits++;
+ if (num_digits >= 18) {
+ ufbxi_dev_assert(num_digits < ufbxi_arraycount(ufbxi_pow5_tab));
+ ufbxi_bigint_mad(&big_mantissa, ufbxi_pow5_tab[num_digits] << num_digits, digits);
+ digits = 0;
+ num_digits = 0;
+ digits_valid = false;
+ }
+ dec_exponent -= has_dot;
+ } else {
+ dec_exponent += 1 - has_dot;
+ }
+ p++;
+ } else if (c == '.' && !has_dot) {
+ has_dot = true;
+ p++;
+ } else {
+ break;
+ }
+ }
+ if (p != end && (*p == 'e' || *p == 'E')) {
+ p++;
+ bool exp_negative = false;
+ if (p != end && (*p == '+' || *p == '-')) {
+ exp_negative = *p == '-';
+ p++;
+ }
+ int32_t exp = 0;
+ while (p != end) {
+ char c = *p;
+ if (c >= '0' && c <= '9') {
+ p++;
+ exp = exp * 10 + (c - '0');
+ if (exp >= 10000) break;
+ } else {
+ break;
+ }
+ }
+ dec_exponent += exp_negative ? -exp : exp;
+ }
+
+ if (p != end) {
+ char c = *p;
+ if (c == '#' || c == 'i' || c == 'I' || c == 'n' || c == 'N') {
+ double result;
+ if (ufbxi_parse_inf_nan(&result, str, max_length, p_end)) {
+ return result;
+ }
+ }
+ }
+
+ *p_end = (char*)p;
+
+ // Both power of 10 and integer are exactly representable as doubles
+ // Powers of 10 are factored as 2*5, and 2^N can be always exactly represented.
+ if ((flags & UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH) != 0 && big_mantissa.length == 0 && dec_exponent >= -22 && dec_exponent <= 22 && (digits >> 53) == 0) {
+ double value;
+ if (dec_exponent < 0) {
+ value = (double)digits / ufbxi_pow10_tab_f64[-dec_exponent];
+ } else {
+ value = (double)digits * ufbxi_pow10_tab_f64[dec_exponent];
+ }
+ return negative ? -value : value;
+ }
+
+ if (big_mantissa.length == 0) {
+ big_mantissa.limbs[0] = (ufbxi_bigint_limb)digits;
+ big_mantissa.limbs[1] = (ufbxi_bigint_limb)(digits >> 32u);
+ big_mantissa.length = (digits >> 32u) ? 2 : digits ? 1 : 0;
+ if (big_mantissa.length == 0) return negative ? -0.0 : 0.0;
+ } else {
+ ufbxi_dev_assert(num_digits < ufbxi_arraycount(ufbxi_pow5_tab));
+ ufbxi_bigint_mad(&big_mantissa, ufbxi_pow5_tab[num_digits] << num_digits, digits);
+ }
+
+ uint32_t enc_sign_shift = 63;
+ uint32_t enc_mantissa_bits = 53;
+ int32_t enc_max_exponent = 1023;
+ if (flags & UFBXI_PARSE_DOUBLE_AS_BINARY32) {
+ enc_sign_shift = 31;
+ enc_mantissa_bits = 24;
+ enc_max_exponent = 127;
+ }
+
+ int32_t exponent = 0;
+ if (dec_exponent < 0) {
+ if (dec_exponent + (int32_t)big_mantissa.length * 10 <= -325) return negative ? -0.0 : 0.0;
+
+ ufbxi_bigint big_divisor = ufbxi_bigint_array(divisor_limbs);
+ uint32_t pow5 = (uint32_t)-dec_exponent;
+ uint32_t initial_pow5 = pow5 <= 27 ? pow5 : 27;
+ uint64_t pow5_value = ufbxi_pow5_tab[initial_pow5];
+ pow5 -= initial_pow5;
+ exponent += dec_exponent;
+
+ if (pow5 == 0 && digits_valid && digits >> 63 == 0) {
+ uint32_t divisor_zeros = ufbxi_lzcnt64(pow5_value);
+ uint64_t mantissa_zeros = ufbxi_lzcnt64(digits) - 1;
+ uint64_t divisor_bits = pow5_value << divisor_zeros;
+ uint64_t mantissa_bits = digits << mantissa_zeros;
+ big_divisor.limbs[0] = (ufbxi_bigint_limb)divisor_bits;
+ big_divisor.limbs[1] = (ufbxi_bigint_limb)(divisor_bits >> 32u);
+ big_divisor.length = 2;
+ big_mantissa.limbs[0] = 0;
+ big_mantissa.limbs[1] = 0;
+ big_mantissa.limbs[2] = (ufbxi_bigint_limb)mantissa_bits;
+ big_mantissa.limbs[3] = (ufbxi_bigint_limb)(mantissa_bits >> 32u);
+ big_mantissa.length = 4;
+ exponent += (int32_t)divisor_zeros - (int32_t)mantissa_zeros - 64;
+ } else {
+ big_divisor.limbs[0] = (ufbxi_bigint_limb)pow5_value;
+ big_divisor.limbs[1] = (ufbxi_bigint_limb)(pow5_value >> 32u);
+ big_divisor.length = (pow5_value >> 32u) != 0 ? 2 : 1;
+ if (pow5 > 0) {
+ ufbxi_bigint_mul_pow5(&big_divisor, pow5);
+ }
+
+ uint32_t divisor_zeros = ufbxi_lzcnt32(big_divisor.limbs[big_divisor.length - 1]);
+ if (big_divisor.length == 1) divisor_zeros += UFBXI_BIGINT_LIMB_BITS;
+ ufbxi_bigint_shift_left(&big_divisor, divisor_zeros);
+ uint32_t divisor_bits = big_divisor.length * UFBXI_BIGINT_LIMB_BITS;
+
+ uint32_t mantissa_zeros = ufbxi_lzcnt32(big_mantissa.limbs[big_mantissa.length - 1]);
+ uint32_t mantissa_bits = big_mantissa.length * UFBXI_BIGINT_LIMB_BITS - mantissa_zeros;
+ uint32_t mantissa_min_bits = divisor_bits + enc_mantissa_bits + 2;
+ uint32_t mantissa_shift = mantissa_bits < mantissa_min_bits ? mantissa_min_bits - mantissa_bits : 0;
+ // Align mantissa to never have a high bit, this means we can skip the first digit during division.
+ mantissa_shift += ((mantissa_shift - mantissa_zeros) & (UFBXI_BIGINT_LIMB_BITS - 1)) == 0 ? 1 : 0;
+ if (mantissa_shift > 0) {
+ ufbxi_bigint_shift_left(&big_mantissa, mantissa_shift);
+ }
+ exponent += (int32_t)divisor_zeros - (int32_t)mantissa_shift;
+ }
+
+ tail = ufbxi_bigint_div(&big_quotient, &big_mantissa, &big_divisor);
+ big_mantissa = big_quotient;
+ } else if (dec_exponent > 0) {
+ if (dec_exponent + (int32_t)(big_mantissa.length - 1) * 9 >= 310) return negative ? -UFBX_INFINITY : UFBX_INFINITY;
+
+ exponent += dec_exponent;
+ ufbxi_bigint_mul_pow5(&big_mantissa, (uint32_t)dec_exponent);
+ }
+
+ uint64_t mantissa = ufbxi_bigint_extract_high(big_mantissa, &exponent, &tail);
+ uint64_t sign_bit = (uint64_t)(negative ? 1u : 0u) << enc_sign_shift;
+
+ uint32_t mantissa_shift = 64 - enc_mantissa_bits;
+ if (exponent > enc_max_exponent) {
+ return negative ? -UFBX_INFINITY : UFBX_INFINITY;
+ } else if (exponent <= -enc_max_exponent) {
+ mantissa_shift += (uint32_t)(-enc_max_exponent + 1 - exponent);
+ exponent = -enc_max_exponent + 1;
+ }
+
+ mantissa = ufbxi_shift_right_round(mantissa, mantissa_shift, tail);
+ if (mantissa == 0) return negative ? -0.0 : 0.0;
+
+ uint64_t bits = mantissa;
+ bits += (uint64_t)(exponent + enc_max_exponent - 1) << (enc_mantissa_bits - 1);
+ bits |= sign_bit;
+
+ if (flags & UFBXI_PARSE_DOUBLE_AS_BINARY32) {
+ uint32_t bits_lo = (uint32_t)bits;
+ float result;
+ ufbxi_bit_cast(float, result, uint32_t, bits_lo);
+ return result;
+ } else {
+ double result;
+ ufbxi_bit_cast(double, result, uint64_t, bits);
+ return result;
+ }
+}
+
+static ufbxi_noinline uint32_t ufbxi_parse_double_init_flags(void)
+{
+ // We require evaluation in double precision, either for doubles (0) or always (1)
+ // and rounding to nearest, which we can check for with `1 + eps == 1 - eps`.
+ #if UFBX_FLT_EVAL_METHOD == 0 || UFBX_FLT_EVAL_METHOD == 1
+ static volatile double ufbxi_volatile_eps = 2.2250738585072014e-308;
+ if (1.0 + ufbxi_volatile_eps == 1.0 - ufbxi_volatile_eps) return UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH;
+ #endif
+
+ return 0;
+}
+
+static ufbxi_forceinline int64_t ufbxi_parse_int64(const char *str, char **end)
+{
+ uint64_t abs_val = 0;
+ bool negative = *str == '-';
+ bool positive = *str == '+';
+
+ size_t init_len = (negative | positive) ? 1 : 0;
+ size_t len = init_len;
+ for (; len < 30; len++) {
+ char c = str[len];
+ if (!(c >= '0' && c <= '9')) break;
+ abs_val = 10 * abs_val + (uint64_t)(c - '0');
+ }
+ if (len == 30 || len == init_len) {
+ *end = NULL;
+ return 0;
+ }
+
+ // TODO: Wrap/clamp?
+ *end = (char*)str + len;
+ return negative ? (int64_t)(0 - abs_val) : (int64_t)abs_val;
+}
+
+static ufbxi_noinline uint32_t ufbxi_parse_uint32_radix(const char *str, uint32_t radix)
+{
+ uint32_t value = 0;
+ for (const char *p = str; ; p++) {
+ char c = *p;
+ if (c >= '0' && c <= '9') {
+ value = value * radix + (uint32_t)(c - '0');
+ } else if (radix == 16 && (c >= 'a' && c <= 'f')) {
+ value = value * radix + (uint32_t)(c + (10 - 'a'));
+ } else if (radix == 16 && (c >= 'A' && c <= 'F')) {
+ value = value * radix + (uint32_t)(c + (10 - 'A'));
+ } else {
+ break;
+ }
+ }
+ return value;
+}
+
+// -- DEFLATE implementation
+
+#if !defined(ufbx_inflate)
+
+// Lookup data: [0:5] extra bits [5:8] flags [16:32] base value
+// Generated by `misc/deflate_lut.py`
+static const uint32_t ufbxi_deflate_length_lut[] = {
+ 0x00000020, 0x00030040, 0x00040040, 0x00050040, 0x00060040, 0x00070040, 0x00080040, 0x00090040,
+ 0x000a0040, 0x000b0041, 0x000d0041, 0x000f0041, 0x00110041, 0x00130042, 0x00170042, 0x001b0042,
+ 0x001f0042, 0x00230043, 0x002b0043, 0x00330043, 0x003b0043, 0x00430044, 0x00530044, 0x00630044,
+ 0x00730044, 0x00830045, 0x00a30045, 0x00c30045, 0x00e30045, 0x01020040, 0x00010020, 0x00010020,
+};
+static const uint32_t ufbxi_deflate_dist_lut[] = {
+ 0x00010000, 0x00020000, 0x00030000, 0x00040000, 0x00050001, 0x00070001, 0x00090002, 0x000d0002,
+ 0x00110003, 0x00190003, 0x00210004, 0x00310004, 0x00410005, 0x00610005, 0x00810006, 0x00c10006,
+ 0x01010007, 0x01810007, 0x02010008, 0x03010008, 0x04010009, 0x06010009, 0x0801000a, 0x0c01000a,
+ 0x1001000b, 0x1801000b, 0x2001000c, 0x3001000c, 0x4001000d, 0x6001000d, 0x00010020, 0x00010020,
+};
+
+static const uint8_t ufbxi_deflate_code_length_permutation[] = {
+ 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,
+};
+
+#define UFBXI_INFLATE_FAST_MIN_IN 8
+#define UFBXI_INFLATE_FAST_MIN_OUT 2
+
+#define UFBXI_HUFF_MAX_BITS 16
+#define UFBXI_HUFF_MAX_VALUE 288
+#define UFBXI_HUFF_FAST_BITS 10
+#define UFBXI_HUFF_FAST_SIZE (1 << UFBXI_HUFF_FAST_BITS)
+#define UFBXI_HUFF_FAST_MASK (UFBXI_HUFF_FAST_SIZE - 1)
+#define UFBXI_HUFF_MAX_LONG_BITS 5
+#define UFBXI_HUFF_MAX_LONG_SYMS 380
+
+#define UFBXI_HUFF_CODELEN_FAST_BITS 8
+#define UFBXI_HUFF_CODELEN_FAST_MASK ((1<<UFBXI_HUFF_CODELEN_FAST_BITS)-1)
+
+#define UFBXI_HUFF_MAX_EXTRA_SYMS 32
+
+#define UFBXI_HUFF_CODELEN_SYMS 19
+#define UFBXI_HUFF_MAX_COMBINED_SYMS 320
+
+typedef struct {
+
+ // Number of bytes left to read from `read_fn()`
+ size_t input_left;
+
+ // User-supplied read callback
+ ufbx_read_fn *read_fn;
+ void *read_user;
+
+ // Buffer to read to from `read_fn()`, may point to `local_buffer` if user
+ // didn't supply a suitable buffer.
+ char *buffer;
+ size_t buffer_size;
+
+ // Current chunk of data to process, either the initial buffer of input
+ // or part of `buffer`.
+ const char *chunk_begin; // < Begin of the buffer
+ const char *chunk_ptr; // < Next bytes to read to `bits`
+ const char *chunk_yield; // < End of data before needing to call `ufbxi_bit_yield()`
+ const char *chunk_end; // < End of data before needing to call `ufbxi_bit_refill()`
+ const char *chunk_real_end; // < Actual end of the data buffer
+
+ // Amount of bytes read before the current chunk
+ size_t num_read_before_chunk;
+ uint64_t progress_bias;
+ uint64_t progress_total;
+ size_t progress_interval;
+
+ uint64_t bits; // < Buffered bits
+ size_t left; // < Number of valid low bits in `bits`
+
+ // Progress tracking, maybe `NULL` it not requested
+ ufbx_progress_cb progress_cb;
+
+ // When `progress_cb.fn()` returns `false`, set `nstop_error` to -28.
+ bool seen_end;
+
+ // If set, the decoding has been cancelled, or we read past EOF
+ int8_t stop_error;
+
+ char local_buffer[256];
+} ufbxi_bit_stream;
+
+// Packed symbol information:
+//
+// [0:5] total_bits // [fast=1] Number of bits in the symbol _including_ extra bits
+// [0:5] extra_mask // [fast=0] Mask of extra bits to use
+// [5] end // 1 if end/invalid symbol, always 0 if `fast` (*1)
+// [6] match // 1 if the symbol is a match length, always 0 in non `lit_length` trees (always 0 if `end`)
+// [7] fast // 1 if the symbol can be determined from the table bits and `end=0`
+// [8:16] lit_byte // [lit_length] Literal byte
+// [8:16] len_index // [lit_length, match=1] Match length index
+// [8:16] dist_index // [dist] Match distance index
+// [8:16] code_length // [code_length] Dynamic Huffman code length code
+// [8:16] long_offset // [fast_sym, fast=0, extra_mask>0] Base offset (halved) to `long_sym[]`
+// [8:16] code_prefix // [fast_sym, fast=0, extra_mask=0] First 8-bits of the code (reverse of the lookup)
+//
+// (*1) Not allowing `end` if `fast` serves a dual purpose: It allows us to omit a check for the end symbol in the
+// fast path and allows using the symbol as a 64-bit shift amount (x64/ARM64/WASM have native modulo 64 shifts).
+//
+// Valid bit patterns, all other patterns are forbidden (`sorted_to_sym[]` contains same patterns as `long_sym[]`):
+//
+// tree b e m f v
+//
+// lit_length.fast_sym[] N 0 0 1 L // Short N bit code (no extra allowed) for literal byte L
+// lit_length.fast_sym[] N 0 1 1 I // Short N bit code (huff+extra bits) for length index I
+// lit_length.fast_sym[] M 0 0 0 X // Long code at `lit_length.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
+// lit_length.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `lit_length.sorted_to_sym[]` to resolve (*1)
+// lit_length.fast_sym[] N 1 0 0 0 // Short N bit code for end-of-block (256) symbol
+// lit_length.fast_sym[] 0 1 0 0 1 // Invalid lit_length code
+//
+// lit_length.long_sym[] N 0 0 0 L // Long N bit code (no extra allowed) for literal byte L
+// lit_length.long_sym[] N 0 1 0 I // Long N bit code (huff+extra bits) for length index I
+// lit_length.long_sym[] N 1 0 0 0 // Long N bit code for end-of-block (256) symbol
+// lit_length.long_sym[] 0 1 0 0 1 // Invalid lit_length code
+//
+// dist.fast_sym[] N 0 0 1 L // Short N bit code (huff+extra bits) for distance index I
+// dist.fast_sym[] M 0 0 0 X // Long code at `dist.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
+// dist.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `dist.sorted_to_sym[]` to resolve (*1)
+// dist.fast_sym[] N 1 0 0 1 // Unused symbol 30-31 or invalid distance code
+//
+// dist.long_sym[] N 0 0 0 I // Long N bit code (huff+extra bits) for distance index I
+// dist.long_sym[] N 1 0 0 1 // Unused symbol 30-31 or invalid distance code
+//
+// code_length.fast_sym[] N 0 0 1 B // Short N bit code (huff only, extra handled explicitly) for symbol bit count B
+// code_length.fast_sym[] M 0 0 0 X // Long code at `dist.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
+// code_length.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `code_length.sorted_to_sym[]` to resolve (*1)
+//
+// code_length.long_sym[] N 0 0 0 B // Long N bit code (huff only, extra handled explicitly) for symbol bit count B
+//
+// (*1) Never necessary if `fast_bits >= 10` due to `long_sym[]` covering all possible codes,
+//
+typedef uint16_t ufbxi_huff_sym;
+
+#define ufbxi_huff_sym_total_bits(sym) ((uint32_t)(sym) & 0x1f)
+#define ufbxi_huff_sym_long_mask(sym) ((uint32_t)(sym) & 0x1f)
+#define ufbxi_huff_sym_long_offset(sym) ((uint32_t)(sym) >> 7u)
+#define ufbxi_huff_sym_value(sym) ((uint32_t)(sym) >> 8u)
+
+enum {
+ UFBXI_HUFF_SYM_END = 0x20,
+ UFBXI_HUFF_SYM_MATCH = 0x40,
+ UFBXI_HUFF_SYM_FAST = 0x80,
+};
+
+#define UFBXI_HUFF_ERROR_SYM ((ufbxi_huff_sym)0x0120) // Error symbol, END (value 1)
+#define UFBXI_HUFF_UNINITIALIZED_SYM ((ufbxi_huff_sym)0x0220) // Uninitialized symbol for regression, END (value 2)
+
+typedef struct {
+ ufbxi_huff_sym fast_sym[UFBXI_HUFF_FAST_SIZE]; // < Lookup from N bytes to symbol information
+ ufbxi_huff_sym long_sym[UFBXI_HUFF_MAX_LONG_SYMS]; // < Fast long symbol lookup
+ ufbxi_huff_sym sorted_to_sym[UFBXI_HUFF_MAX_VALUE]; // < Symbol information per sorted index
+
+ uint32_t extra_shift_base[UFBXI_HUFF_MAX_EXTRA_SYMS]; // < [0:6] shift [16:32] base value
+ uint16_t extra_mask[UFBXI_HUFF_MAX_EXTRA_SYMS]; // < Mask for extra bits
+
+ uint16_t past_max_code[UFBXI_HUFF_MAX_BITS]; // < One past maximum code value per bit length
+ int16_t code_to_sorted[UFBXI_HUFF_MAX_BITS]; // < Code to sorted symbol index per bit length
+ uint32_t num_symbols;
+
+ uint32_t end_of_block_bits;
+} ufbxi_huff_tree;
+
+typedef struct {
+ union {
+ struct {
+ ufbxi_huff_tree lit_length;
+ ufbxi_huff_tree dist;
+ };
+ ufbxi_huff_tree trees[2];
+ };
+ uint32_t fast_bits;
+} ufbxi_trees;
+
+typedef struct {
+ bool initialized;
+ ufbxi_trees static_trees;
+} ufbxi_inflate_retain_imp;
+
+ufbx_static_assert(inflate_retain_size, sizeof(ufbxi_inflate_retain_imp) <= sizeof(ufbx_inflate_retain));
+
+typedef struct {
+ ufbxi_bit_stream stream;
+ uint32_t fast_bits;
+
+ char *out_begin;
+ char *out_ptr;
+ char *out_end;
+} ufbxi_deflate_context;
+
+static ufbxi_forceinline uint32_t
+ufbxi_bit_reverse(uint32_t mask, uint32_t num_bits)
+{
+ ufbxi_dev_assert(num_bits <= 16);
+ uint32_t x = mask;
+ x = (((x & 0xaaaa) >> 1) | ((x & 0x5555) << 1));
+ x = (((x & 0xcccc) >> 2) | ((x & 0x3333) << 2));
+ x = (((x & 0xf0f0) >> 4) | ((x & 0x0f0f) << 4));
+ x = (((x & 0xff00) >> 8) | ((x & 0x00ff) << 8));
+ return x >> (16 - num_bits);
+}
+
+static ufbxi_noinline const char *
+ufbxi_bit_chunk_refill(ufbxi_bit_stream *s, const char *ptr)
+{
+ // Copy any left-over data to the beginning of `buffer`
+ size_t left = ufbxi_to_size(s->chunk_real_end - ptr);
+ ufbxi_dev_assert(left < 64);
+ if (left > 0) memmove(s->buffer, ptr, left);
+
+ s->num_read_before_chunk += ufbxi_to_size(ptr - s->chunk_begin);
+
+ // Read more user data if the user supplied a `read_fn()`, otherwise
+ // we assume the initial data chunk is the whole input buffer.
+ if (s->read_fn && s->stop_error == 0) {
+ size_t to_read = ufbxi_min_sz(s->input_left, s->buffer_size - left);
+ if (to_read > 0) {
+ size_t num_read = s->read_fn(s->read_user, s->buffer + left, to_read);
+ // TODO: IO error, should unify with (currently broken) cancel logic
+ if (num_read > to_read) num_read = 0;
+ ufbxi_dev_assert(s->input_left >= num_read);
+ s->input_left -= num_read;
+ left += num_read;
+ }
+ }
+
+ // Pad the rest with zeros, leaving at least 64 zeros of slack.
+ // If we end up here again after padding once, we're reading past EOF.
+ if (left < 64) {
+ if (s->seen_end) {
+ s->stop_error = -31;
+ }
+ s->seen_end = true;
+ memset(s->buffer + left, 0, 128 - left);
+ left = 128;
+ }
+
+ s->chunk_begin = s->buffer;
+ s->chunk_ptr = s->buffer;
+ s->chunk_end = s->buffer + left - 8;
+ s->chunk_real_end = s->buffer + left;
+ return s->buffer;
+}
+
+static ufbxi_noinline void ufbxi_bit_stream_init(ufbxi_bit_stream *s, const ufbx_inflate_input *input)
+{
+ size_t data_size = input->data_size;
+ if (data_size > input->total_size) {
+ data_size = input->total_size;
+ }
+
+ s->read_fn = input->read_fn;
+ s->read_user = input->read_user;
+ s->progress_cb = input->progress_cb;
+ s->chunk_begin = (const char*)input->data;
+ s->chunk_ptr = (const char*)input->data;
+ s->chunk_end = ufbxi_add_ptr((const char*)input->data, ufbxi_max_sz(8, data_size) - 8);
+ s->chunk_real_end = ufbxi_add_ptr((const char*)input->data, data_size);
+ s->input_left = input->total_size - data_size;
+
+ // Use the user buffer if it's large enough, otherwise `local_buffer`
+ if (input->buffer_size > sizeof(s->local_buffer)) {
+ s->buffer = (char*)input->buffer;
+ s->buffer_size = input->buffer_size;
+ } else {
+ s->buffer = s->local_buffer;
+ s->buffer_size = sizeof(s->local_buffer);
+ }
+ s->num_read_before_chunk = 0;
+ s->progress_bias = input->progress_size_before;
+ s->progress_total = input->total_size + input->progress_size_before + input->progress_size_after;
+ if (!s->progress_cb.fn || input->progress_interval_hint >= SIZE_MAX) {
+ s->progress_interval = SIZE_MAX;
+ } else if (input->progress_interval_hint > 0) {
+ s->progress_interval = (size_t)input->progress_interval_hint;
+ } else {
+ s->progress_interval = 0x4000;
+ }
+ s->seen_end = false;
+ s->stop_error = 0;
+
+ // Clear the initial bit buffer
+ s->bits = 0;
+ s->left = 0;
+
+ // If the initial data buffer is not large enough to be read directly
+ // from refill the chunk once.
+ if (data_size < 64) {
+ ufbxi_bit_chunk_refill(s, s->chunk_begin);
+ }
+
+ if (s->progress_cb.fn && ufbxi_to_size(s->chunk_end - s->chunk_ptr) > s->progress_interval + 8) {
+ s->chunk_yield = s->chunk_ptr + s->progress_interval;
+ } else {
+ s->chunk_yield = s->chunk_end;
+ }
+}
+
+static ufbxi_noinline const char *
+ufbxi_bit_yield(ufbxi_bit_stream *s, const char *ptr)
+{
+ if (ptr > s->chunk_end) {
+ ptr = ufbxi_bit_chunk_refill(s, ptr);
+ }
+
+ if (s->progress_cb.fn) {
+ size_t num_read = s->num_read_before_chunk + ufbxi_to_size(ptr - s->chunk_begin);
+
+ ufbx_progress progress = { s->progress_bias + num_read, s->progress_total };
+ uint32_t result = (uint32_t)s->progress_cb.fn(s->progress_cb.user, &progress);
+ ufbx_assert(result == UFBX_PROGRESS_CONTINUE || result == UFBX_PROGRESS_CANCEL);
+ if (result == UFBX_PROGRESS_CANCEL) {
+ s->stop_error = -28;
+ ptr = s->local_buffer;
+ s->buffer = s->local_buffer;
+ s->buffer_size = sizeof(s->local_buffer);
+ s->chunk_begin = ptr;
+ s->chunk_ptr = ptr;
+ s->chunk_end = ptr + sizeof(s->local_buffer) - 8;
+ s->chunk_real_end = ptr + sizeof(s->local_buffer);
+ memset(s->local_buffer, 0, sizeof(s->local_buffer));
+ }
+ }
+
+ if (s->progress_cb.fn && ufbxi_to_size(s->chunk_end - ptr) > s->progress_interval + 8) {
+ s->chunk_yield = ptr + s->progress_interval;
+ } else {
+ s->chunk_yield = s->chunk_end;
+ }
+
+ return ptr;
+}
+
+static ufbxi_forceinline void
+ufbxi_bit_refill(uint64_t *p_bits, size_t *p_left, const char **p_data, ufbxi_bit_stream *s)
+{
+ if (*p_data > s->chunk_yield) {
+ *p_data = ufbxi_bit_yield(s, *p_data);
+ }
+
+ // See https://fgiesen.wordpress.com/2018/02/20/reading-bits-in-far-too-many-ways-part-2/
+ // variant 4. This branchless refill guarantees [56,63] bits to be valid in `*p_bits`.
+ ufbxi_regression_assert(*p_left <= 64); \
+ *p_bits |= ufbxi_read_u64(*p_data) << *p_left;
+ *p_data += (63 - *p_left) >> 3;
+ *p_left |= 56;
+}
+
+// See `ufbxi_bit_refill()`
+#define ufbxi_macro_bit_refill_fast(m_bits, m_left, m_data, m_refill_bits) do { \
+ ufbxi_regression_assert(m_left <= 64); \
+ m_bits |= m_refill_bits << m_left; \
+ m_data += (63 - m_left) >> 3; \
+ m_left |= 56; \
+ } while (0)
+
+static ufbxi_noinline int
+ufbxi_bit_copy_bytes(void *dst, ufbxi_bit_stream *s, size_t len)
+{
+ ufbx_assert(s->left % 8 == 0);
+ char *ptr = (char*)dst;
+
+ // Copy the buffered bits first
+ while (len > 0 && s->left > 0) {
+ *ptr++ = (char)(uint8_t)s->bits;
+ len -= 1;
+ s->bits >>= 8;
+ s->left -= 8;
+ }
+
+ // Copied fully from buffer
+ if (len == 0) {
+ return 1;
+ }
+
+ // We need to clear the top bits as there may be data
+ // read ahead past `s->left` in some cases
+ s->bits = 0;
+
+ // Copy the current chunk
+ size_t chunk_left = ufbxi_to_size(s->chunk_real_end - s->chunk_ptr);
+ if (chunk_left >= len) {
+ memcpy(ptr, s->chunk_ptr, len);
+ s->chunk_ptr += len;
+ return 1;
+ } else {
+ memcpy(ptr, s->chunk_ptr, chunk_left);
+ s->chunk_ptr += chunk_left;
+ ptr += chunk_left;
+ len -= chunk_left;
+ }
+
+ // Read extra bytes from user
+ if (len > s->input_left) return 0;
+ size_t num_read = 0;
+ if (s->read_fn) {
+ num_read = s->read_fn(s->read_user, ptr, len);
+ s->input_left -= num_read;
+ }
+ return num_read == len;
+}
+
+// 0: Success
+// -1: Overfull
+// -2: Underfull
+static ufbxi_noinline ptrdiff_t
+ufbxi_huff_build_imp(ufbxi_huff_tree *tree, uint8_t *sym_bits, uint32_t sym_count, const uint32_t *sym_extra, uint32_t sym_extra_offset, uint32_t fast_bits, uint32_t *bits_counts)
+{
+ uint32_t fast_mask = (1u << fast_bits) - 1;
+
+ ufbx_assert(sym_count <= UFBXI_HUFF_MAX_VALUE);
+ tree->num_symbols = sym_count;
+
+ uint32_t nonzero_sym_count = sym_count - bits_counts[0];
+
+ uint32_t total_syms[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
+ uint32_t first_code[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
+
+ tree->code_to_sorted[0] = INT16_MAX;
+ tree->past_max_code[0] = 0;
+ total_syms[0] = 0;
+
+ // Clear to uninitialized symbols
+ #if defined(UFBX_REGRESSION)
+ {
+ for (size_t i = 0; i < UFBXI_HUFF_FAST_SIZE; i++) {
+ tree->fast_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
+ }
+ for (size_t i = 0; i < UFBXI_HUFF_MAX_VALUE; i++) {
+ tree->sorted_to_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
+ }
+ for (size_t i = 0; i < UFBXI_HUFF_MAX_LONG_SYMS; i++) {
+ tree->long_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
+ }
+ }
+ #endif
+
+ uint32_t last_valid_prefix = 0;
+
+ // Resolve the maximum code per bit length and ensure that the tree is not
+ // overfull or underfull.
+ {
+ int num_codes_left = 1;
+ uint32_t code = 0;
+ uint32_t prev_count = 0;
+ uint32_t long_offset = 0;
+ for (uint32_t bits = 1; bits < UFBXI_HUFF_MAX_BITS; bits++) {
+ uint32_t count = bits_counts[bits];
+ code = (code + prev_count) << 1;
+ first_code[bits] = code;
+ tree->past_max_code[bits] = (uint16_t)(code + count);
+
+ uint32_t prev_syms = total_syms[bits - 1];
+ total_syms[bits] = prev_syms + count;
+
+ // Each bit level doubles the amount of codes and potentially removes some
+ num_codes_left = (num_codes_left << 1) - (int32_t)count;
+ if (num_codes_left < 0) {
+ return -1;
+ }
+
+ if (count > 0 && bits > fast_bits && bits - fast_bits <= UFBXI_HUFF_MAX_LONG_BITS) {
+ uint32_t shift = bits - fast_bits;
+ uint32_t last_inclusive = num_codes_left == 0 ? (1u<<shift) - 1u : 0u;
+ uint32_t first_prefix = code >> shift;
+ uint32_t last_prefix = (code + count + last_inclusive) >> shift;
+ uint32_t mask = (1u << shift) - 1u;
+ uint32_t half_step = 1u << (shift - 1u);
+ for (uint32_t prefix = first_prefix; prefix < last_prefix; prefix++) {
+ uint32_t rev_prefix = ufbxi_bit_reverse(prefix, fast_bits);
+ tree->fast_sym[rev_prefix] = (ufbxi_huff_sym)(mask | (long_offset << 8));
+ long_offset += half_step;
+ }
+
+ last_valid_prefix = last_prefix;
+ }
+
+ if (count > 0) {
+ tree->code_to_sorted[bits] = (int16_t)((int)prev_syms - (int)code);
+ } else {
+ tree->code_to_sorted[bits] = INT16_MAX;
+ }
+ prev_count = count;
+ }
+
+ // All codes should be used if there's more than one symbol, if there's only one symbol there should be
+ // only a single 1-bit code.
+ if (nonzero_sym_count > 1 && num_codes_left != 0) {
+ return -2;
+ } else if (nonzero_sym_count == 1 && total_syms[1] != 1) {
+ return -2;
+ }
+
+ // We should always have enough space for long symbols as we support up to 5 (UFBXI_HUFF_MAX_LONG_BITS)
+ // bits and the largest tree has 286 symbols. For each bit we may waste at most 2^bits slots (conservative)
+ // and in the end we may waste 2^5 slots giving us `286+2+4+8+16+32+32 = 380` (UFBXI_HUFF_MAX_LONG_SYMS)
+ ufbx_assert(long_offset <= UFBXI_HUFF_MAX_LONG_SYMS);
+ }
+
+ tree->end_of_block_bits = 0;
+ uint32_t num_extra = 0;
+ tree->extra_shift_base[0] = 0;
+ tree->extra_mask[0] = 0;
+
+ // Fill `fast_sym[]` with error symbols if necessary, we don't need to do this if we have two or more symbols
+ // as the tree is guaranteed to be full, which means we will populate the whole `fast_sym[]`
+ if (nonzero_sym_count <= 1) {
+ for (uint32_t i = 0; i <= fast_mask; i++) {
+ tree->fast_sym[i] = UFBXI_HUFF_ERROR_SYM;
+ }
+ }
+
+ // Generate per-length sorted-to-symbol and fast lookup tables
+ uint32_t bits_index[UFBXI_HUFF_MAX_BITS] = { 0 };
+ for (uint32_t i = 0; i < sym_count; i++) {
+ uint32_t bits = sym_bits[i];
+ if (bits == 0) continue;
+
+ uint32_t sym = i << 8 | bits;
+ if (i >= sym_extra_offset) {
+ uint32_t extra = sym_extra[i - sym_extra_offset];
+ sym += extra;
+
+ // Store length/distance codes with extra values in a table.
+ // TODO: This is unnecessary for small values
+ if ((extra & 0xffff001f) != 0 && (extra & 0x20) == 0) {
+ uint32_t ix = ++num_extra;
+ tree->extra_shift_base[ix] = (extra & 0xffff0000) | bits;
+ tree->extra_mask[ix] = (uint16_t)((1u << (extra & 0x1f)) - 1);
+ sym = (sym & 0xff) | ix << 8;
+ }
+
+ }
+
+ uint32_t index = bits_index[bits]++;
+ uint32_t sorted = total_syms[bits - 1] + index;
+ tree->sorted_to_sym[sorted] = (ufbxi_huff_sym)sym;
+
+ // Reverse the code and fill all fast lookups with the reversed prefix
+ uint32_t code = first_code[bits] + index;
+ uint32_t rev_code = ufbxi_bit_reverse(code, bits);
+
+ if (bits <= fast_bits) {
+ uint32_t fast_sym = sym;
+ // The `end` and `fast` flags are mutually exclusive
+ if ((fast_sym & UFBXI_HUFF_SYM_END) == 0) {
+ fast_sym |= UFBXI_HUFF_SYM_FAST;
+ }
+ uint32_t hi_max = 1u << (fast_bits - bits);
+ for (uint32_t hi = 0; hi < hi_max; hi++) {
+ ufbxi_regression_assert(nonzero_sym_count <= 1 || tree->fast_sym[rev_code | hi << bits] == UFBXI_HUFF_UNINITIALIZED_SYM);
+ tree->fast_sym[rev_code | hi << bits] = (ufbxi_huff_sym)fast_sym;
+ }
+ } else if (bits <= fast_bits + UFBXI_HUFF_MAX_LONG_BITS && (code >> (bits - fast_bits)) < last_valid_prefix) {
+ uint32_t fast_sym = tree->fast_sym[rev_code & fast_mask];
+ ufbxi_regression_assert(fast_sym != UFBXI_HUFF_UNINITIALIZED_SYM);
+ uint32_t long_bits = 0;
+
+ uint32_t long_mask = fast_sym;
+ while (long_bits < UFBXI_HUFF_MAX_LONG_BITS && (long_mask & 1) != 0) {
+ long_mask >>= 1;
+ long_bits += 1;
+ }
+ ufbxi_dev_assert(long_bits >= 1);
+
+ uint32_t long_base = fast_sym >> 7u; // aka (fast_sym >> 8) * 2
+ uint32_t lo_bits = bits - fast_bits;
+ uint32_t hi_max = 1u << (long_bits - lo_bits);
+ uint32_t rev_suffix = rev_code >> fast_bits;
+ for (uint32_t hi = 0; hi < hi_max; hi++) {
+ ufbxi_regression_assert(tree->long_sym[long_base + (rev_suffix | hi << lo_bits)] == UFBXI_HUFF_UNINITIALIZED_SYM);
+ tree->long_sym[long_base + (rev_suffix | hi << lo_bits)] = (ufbxi_huff_sym)sym;
+ }
+ } else {
+ uint32_t fast_sym = (code >> (bits - fast_bits)) << 8;
+ ufbxi_regression_assert(
+ tree->fast_sym[rev_code & fast_mask] == UFBXI_HUFF_UNINITIALIZED_SYM ||
+ tree->fast_sym[rev_code & fast_mask] == (ufbxi_huff_sym)fast_sym);
+ tree->fast_sym[rev_code & fast_mask] = (ufbxi_huff_sym)fast_sym;
+ }
+
+ // Make sure the end-of-block symbol goes through the slow path
+ // Also store the end-of-block code so we can interrupt decoding
+ if (i == 256) {
+ tree->end_of_block_bits = rev_code;
+ }
+ }
+
+ // Make sure all `fast_sym[]` are filled with an initialized value.
+ #if defined(UFBX_REGRESSION)
+ {
+ for (size_t i = 0; i < UFBXI_HUFF_FAST_SIZE; i++) {
+ if (i <= fast_mask) {
+ ufbx_assert(tree->fast_sym[i] != UFBXI_HUFF_UNINITIALIZED_SYM);
+ } else {
+ ufbx_assert(tree->fast_sym[i] == UFBXI_HUFF_UNINITIALIZED_SYM);
+ }
+ }
+ for (size_t i = 0; i < nonzero_sym_count; i++) {
+ ufbx_assert(tree->sorted_to_sym[i] != UFBXI_HUFF_UNINITIALIZED_SYM);
+ }
+ }
+ #endif
+
+ return 0;
+}
+
+// 0: Success
+// -1: Overfull
+// -2: Underfull
+static ufbxi_noinline ptrdiff_t
+ufbxi_huff_build(ufbxi_huff_tree *tree, uint8_t *sym_bits, uint32_t sym_count, const uint32_t *sym_extra, uint32_t sym_extra_offset, uint32_t fast_bits)
+{
+ // Count the number of codes per bit length
+ // `bits_counts[0]` contains the number of non-used symbols
+ uint32_t bits_counts[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
+ memset(bits_counts, 0, sizeof(bits_counts));
+ for (uint32_t i = 0; i < sym_count; i++) {
+ uint32_t bits = sym_bits[i];
+ ufbx_assert(bits < UFBXI_HUFF_MAX_BITS);
+ bits_counts[bits]++;
+ }
+
+ return ufbxi_huff_build_imp(tree, sym_bits, sym_count, sym_extra, sym_extra_offset, fast_bits, bits_counts);
+}
+
+static ufbxi_forceinline ufbxi_huff_sym
+ufbxi_huff_decode_bits(const ufbxi_huff_tree *tree, uint64_t bits, uint32_t fast_bits, uint32_t fast_mask)
+{
+ ufbxi_huff_sym sym = tree->fast_sym[bits & fast_mask];
+ ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
+
+ if ((sym & (UFBXI_HUFF_SYM_FAST|UFBXI_HUFF_SYM_END)) != 0) {
+ return sym;
+ }
+
+ uint32_t tail = (uint32_t)(bits >> fast_bits);
+ uint32_t long_mask = ufbxi_huff_sym_long_mask(sym);
+ if (long_mask) {
+ sym = tree->long_sym[ufbxi_huff_sym_long_offset(sym) + (tail & long_mask)];
+ ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
+ return sym;
+ }
+
+ ufbxi_dev_assert(fast_bits <= 8);
+
+ uint32_t code = ufbxi_huff_sym_value(sym);
+ uint32_t num_bits = fast_bits;
+ for (;;) {
+ code = code << 1 | (tail & 1);
+ tail >>= 1;
+ num_bits++;
+
+ ufbxi_regression_assert(num_bits < UFBXI_HUFF_MAX_BITS);
+ if (code < tree->past_max_code[num_bits]) {
+ sym = tree->sorted_to_sym[(int32_t)code + (int32_t)tree->code_to_sorted[num_bits]];
+ ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
+ return sym;
+ }
+ }
+}
+
+static ufbxi_noinline void ufbxi_init_static_huff(ufbxi_trees *trees, const ufbx_inflate_input *input)
+{
+ ptrdiff_t err = 0;
+
+ // Override `fast_bits` if necessary, this must always be valid as it's checked in the beginning of `ufbx_inflate()`.
+ if (input && input->internal_fast_bits != 0) {
+ trees->fast_bits = (uint32_t)input->internal_fast_bits;
+ ufbx_assert(!(trees->fast_bits < 1 || trees->fast_bits == 9 || trees->fast_bits > 10));
+ } else {
+ trees->fast_bits = UFBXI_HUFF_FAST_BITS;
+ }
+
+ // 0-143: 8 bits, 144-255: 9 bits, 256-279: 7 bits, 280-287: 8 bits
+ uint8_t lit_length_bits[288]; // ufbxi_uninit
+ memset(lit_length_bits + 0, 8, 144 - 0);
+ memset(lit_length_bits + 144, 9, 256 - 144);
+ memset(lit_length_bits + 256, 7, 280 - 256);
+ memset(lit_length_bits + 280, 8, 288 - 280);
+ err |= ufbxi_huff_build(&trees->lit_length, lit_length_bits, sizeof(lit_length_bits), ufbxi_deflate_length_lut, 256, trees->fast_bits);
+
+ // "Distance codes 0-31 are represented by (fixed-length) 5-bit codes"
+ uint8_t dist_bits[32]; // ufbxi_uninit
+ memset(dist_bits + 0, 5, 32 - 0);
+ err |= ufbxi_huff_build(&trees->dist, dist_bits, sizeof(dist_bits), ufbxi_deflate_dist_lut, 0, trees->fast_bits);
+
+ // Building the static trees cannot fail as we use pre-defined code lengths.
+ ufbxi_ignore(err);
+ ufbx_assert(err == 0);
+}
+
+static ufbxi_noinline ptrdiff_t ufbxi_decode_dynamic_huff_bits(ufbxi_deflate_context *dc, const ufbxi_huff_tree *huff_code_length, uint8_t *code_lengths, uint32_t num_symbols)
+{
+ uint64_t bits = dc->stream.bits;
+ size_t left = dc->stream.left;
+ const char *data = dc->stream.chunk_ptr;
+
+ uint32_t symbol_index = 0;
+ uint8_t prev = 0;
+ while (symbol_index < num_symbols) {
+ ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
+ if (dc->stream.stop_error != 0) return dc->stream.stop_error;
+
+ ufbxi_huff_sym sym = ufbxi_huff_decode_bits(huff_code_length, bits, UFBXI_HUFF_CODELEN_FAST_BITS, UFBXI_HUFF_CODELEN_FAST_MASK);
+ ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
+ if (sym == UFBXI_HUFF_ERROR_SYM) return -21;
+
+ uint32_t inst = ufbxi_huff_sym_value(sym);
+ uint32_t sym_len = ufbxi_huff_sym_total_bits(sym);
+
+ bits >>= sym_len;
+ left -= sym_len;
+
+ if (inst <= 15) {
+ // "0 - 15: Represent code lengths of 0 - 15"
+ prev = (uint8_t)inst;
+ code_lengths[symbol_index++] = (uint8_t)inst;
+ } else if (inst == 16) {
+ // "16: Copy the previous code length 3 - 6 times. The next 2 bits indicate repeat length."
+ uint32_t num = 3 + ((uint32_t)bits & 0x3);
+ bits >>= 2;
+ left -= 2;
+ if (symbol_index + num > num_symbols) return -18;
+ memset(code_lengths + symbol_index, prev, num);
+ symbol_index += num;
+ } else if (inst == 17) {
+ // "17: Repeat a code length of 0 for 3 - 10 times. (3 bits of length)"
+ uint32_t num = 3 + ((uint32_t)bits & 0x7);
+ bits >>= 3;
+ left -= 3;
+ if (symbol_index + num > num_symbols) return -19;
+ memset(code_lengths + symbol_index, 0, num);
+ symbol_index += num;
+ prev = 0;
+ } else if (inst == 18) {
+ // "18: Repeat a code length of 0 for 11 - 138 times (7 bits of length)"
+ uint32_t num = 11 + ((uint32_t)bits & 0x7f);
+ bits >>= 7;
+ left -= 7;
+ if (symbol_index + num > num_symbols) return -20;
+ memset(code_lengths + symbol_index, 0, num);
+ symbol_index += num;
+ prev = 0;
+ } else {
+ return -6;
+ }
+ }
+
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+
+ return 0;
+}
+
+static ufbxi_noinline ptrdiff_t
+ufbxi_init_dynamic_huff(ufbxi_deflate_context *dc, ufbxi_trees *trees)
+{
+ uint64_t bits = dc->stream.bits;
+ size_t left = dc->stream.left;
+ const char *data = dc->stream.chunk_ptr;
+ ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
+ if (dc->stream.stop_error != 0) return dc->stream.stop_error;
+
+ trees->fast_bits = dc->fast_bits;
+
+ // The header contains the number of Huffman codes in each of the three trees.
+ uint32_t num_lit_lengths = 257 + (uint32_t)(bits & 0x1f);
+ uint32_t num_dists = 1 + (uint32_t)(bits >> 5 & 0x1f);
+ uint32_t num_code_lengths = 4 + (uint32_t)(bits >> 10 & 0xf);
+ bits >>= 14;
+ left -= 14;
+
+ uint8_t code_lengths[UFBXI_HUFF_MAX_COMBINED_SYMS]; // ufbxi_uninit
+
+ // Code lengths for the "code length" Huffman tree are represented literally
+ // 3 bits in order of: 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 up to
+ // `num_code_lengths`, rest of the code lengths are 0 (unused)
+ memset(code_lengths, 0, UFBXI_HUFF_CODELEN_SYMS);
+
+ for (size_t len_i = 0; len_i < num_code_lengths; len_i++) {
+ if (len_i == 14) {
+ ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
+ if (dc->stream.stop_error != 0) return dc->stream.stop_error;
+ }
+ code_lengths[ufbxi_deflate_code_length_permutation[len_i]] = (uint32_t)bits & 0x7;
+ bits >>= 3;
+ left -= 3;
+ }
+
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+
+ ufbxi_huff_tree huff_code_length; // ufbxi_uninit
+ ptrdiff_t err; // ufbxi_uninit
+
+ // Build the temporary "code length" Huffman tree used to encode the actual
+ // trees used to compress the data. Use that to build the literal/length and
+ // distance trees.
+ err = ufbxi_huff_build(&huff_code_length, code_lengths, UFBXI_HUFF_CODELEN_SYMS, NULL, INT32_MAX, UFBXI_HUFF_CODELEN_FAST_BITS);
+ if (err) return -14 + 1 + err;
+
+ err = ufbxi_decode_dynamic_huff_bits(dc, &huff_code_length, code_lengths, num_lit_lengths + num_dists);
+ if (err) return err;
+
+ err = ufbxi_huff_build(&trees->lit_length, code_lengths, num_lit_lengths, ufbxi_deflate_length_lut, 256, dc->fast_bits);
+ if (err) return err == -7 ? -28 : -16 + 1 + err;
+
+ err = ufbxi_huff_build(&trees->dist, code_lengths + num_lit_lengths, num_dists, ufbxi_deflate_dist_lut, 0, dc->fast_bits);
+ if (err) return err == -7 ? -28 : -22 + 1 + err;
+
+ return 0;
+}
+
+static ufbxi_noinline uint32_t ufbxi_adler32(const void *data, size_t size)
+{
+ ufbxi_fast_uint a = 1, b = 0;
+ const char *p = (const char*)data;
+
+ // Adler-32 consists of two running sums modulo 65521. As an optimization
+ // we can accumulate N sums before applying the modulo, where N depends on
+ // the size of the type holding the sum.
+ const ufbxi_fast_uint num_before_wrap = sizeof(ufbxi_fast_uint) == 8 ? 380368439u : 5552u;
+
+ ufbxi_fast_uint size_left = size;
+ while (size_left > 0) {
+ ufbxi_fast_uint num = size_left <= num_before_wrap ? size_left : num_before_wrap;
+ size_left -= num;
+ const char *end = p + num;
+
+ // Align to 16 bytes
+ while (p != end && !ufbxi_is_aligned(p, 16)) {
+ a += (ufbxi_fast_uint)(uint8_t)p[0]; b += a;
+ p++;
+ }
+
+#if UFBXI_HAS_SSE
+ static const uint16_t factors[2][8] = {
+ { 16, 15, 14, 13, 12, 11, 10, 9, },
+ { 8, 7, 6, 5, 4, 3, 2, 1, },
+ };
+
+ const __m128i zero = _mm_setzero_si128();
+ const __m128i factor_1 = _mm_set1_epi16(1);
+ const __m128i factor_16 = _mm_set1_epi16(16);
+ const __m128i factor_lo = _mm_loadu_si128((const __m128i*)factors[0]);
+ const __m128i factor_hi = _mm_loadu_si128((const __m128i*)factors[1]);
+
+ for (;;) {
+ size_t chunk_size = ufbxi_min_sz(ufbxi_to_size(end - p), 5803) & ~(size_t)0xff;
+ if (chunk_size == 0) break;
+ const char *chunk_end = p + chunk_size;
+
+ __m128i s1 = zero;
+ __m128i s2 = zero;
+
+ while (p != chunk_end) {
+ __m128i s1_lo = zero, s1_hi = zero;
+ __m128i tmp_lo = zero, tmp_hi = zero;
+
+ ufbxi_nounroll for (size_t i = 0; i < 256; i += 32) {
+ __m128i d0 = _mm_load_si128((const __m128i*)(p + i + 0));
+ __m128i d1 = _mm_load_si128((const __m128i*)(p + i + 16));
+
+ tmp_lo = _mm_add_epi16(tmp_lo, s1_lo);
+ tmp_hi = _mm_add_epi16(tmp_hi, s1_hi);
+ s1_lo = _mm_add_epi16(s1_lo, _mm_unpacklo_epi8(d0, zero));
+ s1_hi = _mm_add_epi16(s1_hi, _mm_unpackhi_epi8(d0, zero));
+
+ tmp_lo = _mm_add_epi16(tmp_lo, s1_lo);
+ tmp_hi = _mm_add_epi16(tmp_hi, s1_hi);
+ s1_lo = _mm_add_epi16(s1_lo, _mm_unpacklo_epi8(d1, zero));
+ s1_hi = _mm_add_epi16(s1_hi, _mm_unpackhi_epi8(d1, zero));
+ }
+
+ s2 = _mm_add_epi32(s2, _mm_slli_epi32(s1, 8));
+ s1 = _mm_add_epi32(s1, _mm_madd_epi16(s1_lo, factor_1));
+ s1 = _mm_add_epi32(s1, _mm_madd_epi16(s1_hi, factor_1));
+
+ s2 = _mm_add_epi32(s2, _mm_madd_epi16(tmp_lo, factor_16));
+ s2 = _mm_add_epi32(s2, _mm_madd_epi16(tmp_hi, factor_16));
+ s2 = _mm_add_epi32(s2, _mm_madd_epi16(s1_lo, factor_lo));
+ s2 = _mm_add_epi32(s2, _mm_madd_epi16(s1_hi, factor_hi));
+
+ p += 256;
+ }
+
+ s1 = _mm_add_epi32(s1, _mm_shuffle_epi32(s1, _MM_SHUFFLE(2,3,0,1)));
+ s2 = _mm_add_epi32(s2, _mm_shuffle_epi32(s2, _MM_SHUFFLE(2,3,0,1)));
+ s1 = _mm_add_epi32(s1, _mm_shuffle_epi32(s1, _MM_SHUFFLE(1,0,3,2)));
+ s2 = _mm_add_epi32(s2, _mm_shuffle_epi32(s2, _MM_SHUFFLE(1,0,3,2)));
+
+ b += chunk_size * a;
+ a += (uint32_t)_mm_cvtsi128_si32(s1);
+ b += (uint32_t)_mm_cvtsi128_si32(s2);
+ }
+#elif UFBX_LITTLE_ENDIAN
+ for (;;) {
+ size_t chunk_size = ufbxi_min_sz(ufbxi_to_size(end - p), 256*8/4) & ~(size_t)0xf;
+ if (chunk_size == 0) break;
+ const char *chunk_end = p + chunk_size;
+
+ uint64_t s1_lo = 0, s1_hi = 0;
+ uint64_t tmp, s2 = 0;
+ uint64_t mask8 = UINT64_C(0x00ff00ff00ff00ff);
+ uint64_t mask16 = UINT64_C(0x0000ffff0000ffff);
+
+ while (p != chunk_end) {
+ uint64_t d0 = *(const uint64_t*)p;
+ uint64_t d1 = *(const uint64_t*)(p + 8);
+
+ tmp = s1_lo + s1_hi;
+ s1_lo += d0 & mask8;
+ s1_hi += (d0 >> 8) & mask8;
+
+ tmp += s1_lo + s1_hi;
+ s1_lo += d1 & mask8;
+ s1_hi += (d1 >> 8) & mask8;
+
+ s2 += (tmp & mask16) + ((tmp >> 16) & mask16);
+ p += 16;
+ }
+
+ uint64_t s1 = s1_lo + s1_hi;
+ s1 = (s1 & mask16) + ((s1 >> 16u) & mask16);
+ ufbxi_fast_uint s1_sum = (ufbxi_fast_uint)(s1 + (s1 >> 32u));
+
+ ufbxi_fast_uint s2_sum = (ufbxi_fast_uint)(s2 + (s2 >> 32u)) * 8;
+ s2_sum += ((ufbxi_fast_uint)(s1_lo >> 0) & 0xffff) * 8;
+ s2_sum += ((ufbxi_fast_uint)(s1_hi >> 0) & 0xffff) * 7;
+ s2_sum += ((ufbxi_fast_uint)(s1_lo >> 16) & 0xffff) * 6;
+ s2_sum += ((ufbxi_fast_uint)(s1_hi >> 16) & 0xffff) * 5;
+ s2_sum += ((ufbxi_fast_uint)(s1_lo >> 32) & 0xffff) * 4;
+ s2_sum += ((ufbxi_fast_uint)(s1_hi >> 32) & 0xffff) * 3;
+ s2_sum += ((ufbxi_fast_uint)(s1_lo >> 48) & 0xffff) * 2;
+ s2_sum += ((ufbxi_fast_uint)(s1_hi >> 48) & 0xffff) * 1;
+
+ b += chunk_size * a;
+ a += s1_sum & 0xffffffffu;
+ b += s2_sum & 0xffffffffu;
+ }
+#endif
+
+ while (p != end) {
+ a += (size_t)(uint8_t)p[0]; b += a;
+ p++;
+ }
+
+ a %= 65521u;
+ b %= 65521u;
+ }
+
+ return (uint32_t)((b << 16) | (a & 0xffff));
+}
+
+static ufbxi_noinline int
+ufbxi_inflate_block_slow(ufbxi_deflate_context *dc, ufbxi_trees *trees, size_t max_symbols)
+{
+ char *out_ptr = dc->out_ptr;
+ char *const out_begin = dc->out_begin;
+ char *const out_end = dc->out_end;
+
+ uint32_t fast_bits = trees->fast_bits;
+ uint32_t fast_mask = (1u << fast_bits) - 1;
+
+ uint64_t bits = dc->stream.bits;
+ size_t left = dc->stream.left;
+ const char *data = dc->stream.chunk_ptr;
+
+ for (;;) {
+ if (max_symbols-- == 0) break;
+
+ ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
+ if (dc->stream.stop_error != 0) return dc->stream.stop_error;
+ uint64_t sym_bits = bits;
+
+ ufbxi_huff_sym sym0 = ufbxi_huff_decode_bits(&trees->lit_length, bits, fast_bits, fast_mask);
+ ufbxi_regression_assert(sym0 != UFBXI_HUFF_UNINITIALIZED_SYM);
+
+ uint32_t sym0_bits = ufbxi_huff_sym_total_bits(sym0);
+
+ bits >>= sym0_bits;
+ left -= sym0_bits;
+ if (sym0 & UFBXI_HUFF_SYM_END) {
+ if (ufbxi_huff_sym_value(sym0) != 0) return -13;
+
+ dc->out_ptr = out_ptr;
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+ return 0;
+ } else if ((sym0 & UFBXI_HUFF_SYM_MATCH) == 0) {
+ if (out_ptr == out_end) return -10;
+ *out_ptr++ = (char)ufbxi_huff_sym_value(sym0);
+ continue;
+ }
+
+ uint32_t sym0_value = ufbxi_huff_sym_value(sym0);
+ uint32_t len_shift_base = trees->lit_length.extra_shift_base[sym0_value];
+ uint16_t len_mask = trees->lit_length.extra_mask[sym0_value];
+ uint32_t length = (len_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym_bits, len_shift_base) & len_mask);
+
+ ufbxi_huff_sym sym1 = ufbxi_huff_decode_bits(&trees->dist, bits, fast_bits, fast_mask);
+ ufbxi_regression_assert(sym1 != UFBXI_HUFF_UNINITIALIZED_SYM);
+ if (sym1 & UFBXI_HUFF_SYM_END) return -11;
+
+ uint32_t sym1_bits = ufbxi_huff_sym_total_bits(sym1);
+
+ bits >>= sym1_bits;
+ left -= sym1_bits;
+
+ uint32_t sym1_value = ufbxi_huff_sym_value(sym1);
+ uint32_t dist_shift_base = trees->dist.extra_shift_base[sym1_value];
+ uint16_t dist_mask = trees->dist.extra_mask[sym1_value];
+ uint32_t distance = (dist_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym_bits, dist_shift_base + sym0) & dist_mask);
+
+ // Bounds checking
+ size_t out_space = ufbxi_to_size(out_end - out_ptr);
+ if ((ptrdiff_t)distance > out_ptr - out_begin || length > out_space) {
+ return -12;
+ }
+
+ // Copy the match
+ const char *src = out_ptr - distance;
+ char *dst = out_ptr;
+ char *end = dst + length;
+ out_ptr += length;
+
+ if (out_space >= length + 16) {
+ uint32_t min_dist = length < 16 ? length : 16;
+ if (distance >= min_dist) {
+ ufbxi_copy_16_bytes(dst, src);
+ while (length > 16) {
+ src += 16;
+ dst += 16;
+ length -= 16;
+ ufbxi_copy_16_bytes(dst, src);
+ }
+ } else {
+ while (dst != end) {
+ *dst++ = *src++;
+ }
+ }
+ } else {
+ while (dst != end) {
+ *dst++ = *src++;
+ }
+ }
+ }
+
+ dc->out_ptr = out_ptr;
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+ return 1;
+}
+
+ufbx_static_assert(inflate_huff_fast_bits, UFBXI_HUFF_FAST_BITS <= 11); // `fast lit, fast len, slow dist` in 56 bits
+ufbx_static_assert(inflate_huff_long_bits, UFBXI_HUFF_FAST_BITS + UFBXI_HUFF_MAX_LONG_BITS >= 15); // Largest code fits in a single long lookup
+
+// Optimized version of `ufbxi_inflate_block_slow()`.
+// Has a lot of assumptions (see asserts) and does not call _any_ (even forceinlined) functions.
+static ufbxi_noinline int
+ufbxi_inflate_block_fast(ufbxi_deflate_context *dc, ufbxi_trees *trees)
+{
+ ufbxi_dev_assert(dc->stream.stop_error == 0);
+ ufbxi_dev_assert(trees->fast_bits == UFBXI_HUFF_FAST_BITS);
+ ufbxi_dev_assert(dc->stream.chunk_yield - dc->stream.chunk_ptr >= UFBXI_INFLATE_FAST_MIN_IN);
+ ufbxi_dev_assert(dc->out_end - dc->out_ptr >= UFBXI_INFLATE_FAST_MIN_OUT);
+
+ char *out_ptr = dc->out_ptr;
+ char *const out_begin = dc->out_begin;
+ char *const out_end = dc->out_end - UFBXI_INFLATE_FAST_MIN_OUT;
+
+ const ufbxi_huff_tree *tree_lit_length = &trees->lit_length;
+ const ufbxi_huff_tree *tree_dist = &trees->dist;
+
+ uint64_t bits = dc->stream.bits;
+ size_t left = dc->stream.left;
+ const char *data = dc->stream.chunk_ptr;
+ const char *data_end = dc->stream.chunk_yield - UFBXI_INFLATE_FAST_MIN_IN;
+
+ uint64_t sym01_bits;
+ ufbxi_huff_sym sym0, sym1;
+ uint64_t refill_bits = ufbxi_read_u64(data);
+
+ #define ufbxi_fast_inflate_refill_and_decode() do { \
+ ufbxi_macro_bit_refill_fast(bits, left, data, refill_bits); \
+ sym01_bits = bits; \
+ sym0 = tree_lit_length->fast_sym[sym01_bits & UFBXI_HUFF_FAST_MASK]; \
+ sym1 = ((sym0 & UFBXI_HUFF_SYM_MATCH) ? tree_dist : tree_lit_length)->fast_sym[ufbxi_wrap_shr64(sym01_bits, sym0) & UFBXI_HUFF_FAST_MASK]; \
+ refill_bits = ufbxi_read_u64(data); \
+ } while (0)
+
+ #define ufbxi_fast_inflate_should_continue() \
+ (((data_end - data) | (out_end - out_ptr)) >= 0)
+
+ ufbxi_fast_inflate_refill_and_decode();
+
+ for (;;) {
+ if ((sym0 & sym1) & UFBXI_HUFF_SYM_FAST) {
+ bits = ufbxi_wrap_shr64(sym01_bits, sym0 + sym1);
+ left -= (sym0 + sym1) & 0x3f;
+
+ if (((sym0 | sym1) & UFBXI_HUFF_SYM_MATCH) == 0) {
+ // Literal, Literal
+ // -> Output the two literals and loop back to start.
+
+ out_ptr[0] = (char)ufbxi_huff_sym_value(sym0);
+ out_ptr[1] = (char)ufbxi_huff_sym_value(sym1);
+ out_ptr += 2;
+
+ ufbxi_fast_inflate_refill_and_decode();
+ if (ufbxi_fast_inflate_should_continue()) continue;
+ break;
+
+ } else if ((sym0 & UFBXI_HUFF_SYM_MATCH) == 0) {
+ // Literal, Match, (Distance)
+ // -> Output a single literal, decode the missing distance and fall through to match.
+
+ out_ptr[0] = (char)ufbxi_huff_sym_value(sym0);
+ out_ptr += 1;
+
+ sym01_bits = ufbxi_wrap_shr64(sym01_bits, sym0);
+
+ // This must fit as literals never have extra bits and the match length is fast so:
+ // 10 (lit) + 10 (len code) + 5 (len extra) + 15 (dist code) + 13 (dist extra) = 53 <= 56
+ sym0 = sym1;
+ sym1 = tree_dist->fast_sym[bits & UFBXI_HUFF_FAST_MASK];
+
+ if ((sym1 & UFBXI_HUFF_SYM_FAST) == 0) {
+ // Slow sym1
+ if (sym1 & UFBXI_HUFF_SYM_END) return -11;
+ uint32_t tail = (uint32_t)(bits >> UFBXI_HUFF_FAST_BITS);
+ uint32_t long_mask = ufbxi_huff_sym_long_mask(sym1);
+ sym1 = tree_dist->long_sym[ufbxi_huff_sym_long_offset(sym1) + (tail & long_mask)];
+ if (sym1 & UFBXI_HUFF_SYM_END) return -11;
+ }
+
+ bits = ufbxi_wrap_shr64(bits, sym1);
+ left -= sym1 & 0x3f;
+ } else {
+ // Match, Distance
+ // -> Fall through to match copy.
+ }
+
+ } else {
+ if ((sym0 & (UFBXI_HUFF_SYM_FAST|UFBXI_HUFF_SYM_END)) == 0) {
+ // Slow sym0
+ uint32_t tail = (uint32_t)(sym01_bits >> UFBXI_HUFF_FAST_BITS);
+ uint32_t long_mask = ufbxi_huff_sym_long_mask(sym0);
+ sym0 = tree_lit_length->long_sym[ufbxi_huff_sym_long_offset(sym0) + (tail & long_mask)];
+ }
+
+ uint32_t sym0_bits = ufbxi_huff_sym_total_bits(sym0);
+ bits >>= sym0_bits;
+ left -= sym0_bits;
+
+ if (sym0 & UFBXI_HUFF_SYM_END) {
+ if (ufbxi_huff_sym_value(sym0) != 0) return -13;
+ dc->out_ptr = out_ptr;
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+ return 0;
+ }
+
+ if (sym0 & UFBXI_HUFF_SYM_MATCH) {
+ sym1 = tree_dist->fast_sym[bits & UFBXI_HUFF_FAST_MASK];
+
+ if ((sym1 & UFBXI_HUFF_SYM_FAST) == 0) {
+ // Slow sym1
+ if (sym1 & UFBXI_HUFF_SYM_END) return -11;
+ uint32_t tail = (uint32_t)(bits >> UFBXI_HUFF_FAST_BITS);
+ uint32_t long_mask = ufbxi_huff_sym_long_mask(sym1);
+ sym1 = tree_dist->long_sym[ufbxi_huff_sym_long_offset(sym1) + (tail & long_mask)];
+ if (sym1 & UFBXI_HUFF_SYM_END) return -11;
+ }
+
+ bits = ufbxi_wrap_shr64(bits, sym1);
+ left -= sym1 & 0x3f;
+ } else {
+ *out_ptr++ = (char)ufbxi_huff_sym_value(sym0);
+
+ ufbxi_fast_inflate_refill_and_decode();
+ if (ufbxi_fast_inflate_should_continue()) continue;
+ break;
+ }
+ }
+
+ uint32_t sym0_value = ufbxi_huff_sym_value(sym0);
+ uint32_t len_shift_base = trees->lit_length.extra_shift_base[sym0_value];
+ uint16_t len_mask = trees->lit_length.extra_mask[sym0_value];
+ uint32_t length = (len_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym01_bits, len_shift_base) & len_mask);
+
+ uint32_t sym1_value = ufbxi_huff_sym_value(sym1);
+ uint32_t dist_shift_base = trees->dist.extra_shift_base[sym1_value];
+ uint16_t dist_mask = trees->dist.extra_mask[sym1_value];
+ uint32_t distance = (dist_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym01_bits, dist_shift_base + sym0) & dist_mask);
+
+ ufbxi_fast_inflate_refill_and_decode();
+
+ // Bounds checking: We don't actually handle the error here, just bail out to the slow implementation
+ ptrdiff_t dst_space = out_end - out_ptr - (ptrdiff_t)length + UFBXI_INFLATE_FAST_MIN_OUT;
+ ptrdiff_t src_space = out_ptr - out_begin - (ptrdiff_t)distance;
+ if ((dst_space | src_space) < 0) {
+ return -12;
+ }
+
+ const char *src = out_ptr - distance;
+ char *dst = out_ptr;
+ char *end = dst + length;
+ out_ptr += length;
+
+ // Copy the match
+
+ uint32_t min_dist = length < 16 ? length : 16;
+ if (distance >= min_dist && dst_space >= 16) {
+ ufbxi_copy_16_bytes(dst, src);
+ while (length > 16) {
+ src += 16;
+ dst += 16;
+ length -= 16;
+ ufbxi_copy_16_bytes(dst, src);
+ }
+ } else {
+ while (dst != end) {
+ *dst++ = *src++;
+ }
+ }
+
+ if (ufbxi_fast_inflate_should_continue()) continue;
+ break;
+ }
+
+ dc->out_ptr = out_ptr;
+ dc->stream.bits = bits;
+ dc->stream.left = left;
+ dc->stream.chunk_ptr = data;
+ return 1;
+
+ #undef ufbxi_fast_inflate_refill_and_decode
+ #undef ufbxi_fast_inflate_should_continue
+}
+
+static void ufbxi_inflate_init_retain(ufbx_inflate_retain *retain)
+{
+ ufbxi_inflate_retain_imp *ret_imp = (ufbxi_inflate_retain_imp*)retain;
+ if (!ret_imp->initialized) {
+ ufbxi_init_static_huff(&ret_imp->static_trees, NULL);
+ ret_imp->initialized = true;
+ }
+}
+
+// TODO: Error codes should have a quick test if the destination buffer overflowed
+// Returns actual number of decompressed bytes or negative error:
+// -1: Bad compression method (ZLIB header)
+// -2: Requires dictionary (ZLIB header)
+// -3: Bad FCHECK (ZLIB header)
+// -4: Bad NLEN (Uncompressed LEN != ~NLEN)
+// -5: Uncompressed source overflow
+// -6: Uncompressed destination overflow
+// -7: Bad block type
+// -8: Truncated checksum (deprecated, reported as -9)
+// -9: Checksum mismatch
+// -10: Literal destination overflow
+// -11: Bad distance code or distance of (30..31)
+// -12: Match out of bounds
+// -13: Bad lit/length code
+// -14: Codelen Huffman Overfull
+// -15: Codelen Huffman Underfull
+// -16: Litlen Huffman Overfull
+// -17: Litlen Huffman Underfull
+// -18: Repeat 16 overflow
+// -19: Repeat 17 overflow
+// -20: Repeat 18 overflow
+// -21: Bad codelen code
+// -22: Distance Huffman: Overfull
+// -23: Distance Huffman: Underfull
+// -28: Cancelled
+// -29: Invalid ufbx_inflate_input.internal_fast_bits value
+// -30: Bad window size (ZLIB header)
+// -31: Truncated stream
+ufbxi_extern_c ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain)
+{
+ ufbxi_inflate_retain_imp *ret_imp = (ufbxi_inflate_retain_imp*)retain;
+
+ ptrdiff_t err;
+ ufbxi_deflate_context dc;
+ ufbxi_bit_stream_init(&dc.stream, input);
+ dc.out_begin = (char*)dst;
+ dc.out_ptr = (char*)dst;
+ dc.out_end = (char*)dst + dst_size;
+ if (input->internal_fast_bits != 0) {
+ dc.fast_bits = (uint32_t)input->internal_fast_bits;
+ if (dc.fast_bits < 1 || dc.fast_bits == 9 || dc.fast_bits > 10) return -29;
+ } else {
+ // TODO: Profile this
+ dc.fast_bits = input->total_size > 2048 ? 10 : 8;
+ }
+
+ uint64_t bits = dc.stream.bits;
+ size_t left = dc.stream.left;
+ const char *data = dc.stream.chunk_ptr;
+
+ ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
+ if (dc.stream.stop_error != 0) return dc.stream.stop_error;
+
+ // Zlib header
+ if (!input->no_header) {
+ size_t cmf = (size_t)(bits & 0xff);
+ size_t flg = (size_t)(bits >> 8) & 0xff;
+ bits >>= 16;
+ left -= 16;
+
+ if ((cmf & 0xf) != 0x8) return -1;
+ if ((flg & 0x20) != 0) return -2;
+ if ((cmf << 8 | flg) % 31u != 0) return -3;
+ if ((cmf >> 4) > 7) return -30;
+ }
+
+ for (;;) {
+ ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
+ if (dc.stream.stop_error != 0) return dc.stream.stop_error;
+
+ // Block header: [0:1] BFINAL [1:3] BTYPE
+ size_t header = (size_t)bits & 0x7;
+ bits >>= 3;
+ left -= 3;
+
+ size_t type = header >> 1;
+ if (type == 0) {
+
+ // Round up to the next byte
+ size_t align_bits = left & 0x7;
+ bits >>= align_bits;
+ left -= align_bits;
+
+ size_t len = (size_t)(bits & 0xffff);
+ size_t nlen = (size_t)((bits >> 16) & 0xffff);
+ if ((len ^ nlen) != 0xffff) return -4;
+ if (dc.out_end - dc.out_ptr < (ptrdiff_t)len) return -6;
+ bits >>= 32;
+ left -= 32;
+
+ dc.stream.bits = bits;
+ dc.stream.left = left;
+ dc.stream.chunk_ptr = data;
+
+ // Copy `len` bytes of literal data
+ if (!ufbxi_bit_copy_bytes(dc.out_ptr, &dc.stream, len)) return -5;
+
+ dc.out_ptr += len;
+
+ } else if (type <= 2) {
+
+ dc.stream.bits = bits;
+ dc.stream.left = left;
+ dc.stream.chunk_ptr = data;
+
+ ufbxi_trees tree_data; // ufbxi_uninit
+ ufbxi_trees *trees; // ufbxi_uninit
+ if (type == 1) {
+ // Static Huffman: Initialize the trees once and cache them in `retain`.
+ if (!ret_imp->initialized) {
+ ufbxi_init_static_huff(&ret_imp->static_trees, input);
+ ret_imp->initialized = true;
+ }
+ trees = &ret_imp->static_trees;
+ } else {
+ // Dynamic Huffman
+ err = ufbxi_init_dynamic_huff(&dc, &tree_data);
+ if (err) return err;
+ trees = &tree_data;
+ }
+
+ for (;;) {
+ bool fast_viable = trees->fast_bits == UFBXI_HUFF_FAST_BITS && dc.out_end - dc.out_ptr >= UFBXI_INFLATE_FAST_MIN_OUT;
+
+ // `ufbxi_inflate_block_fast()` needs a bit more upfront setup, see asserts on top of the function
+ if (fast_viable && dc.stream.chunk_yield - dc.stream.chunk_ptr >= UFBXI_INFLATE_FAST_MIN_IN) {
+ err = ufbxi_inflate_block_fast(&dc, trees);
+ } else {
+ err = ufbxi_inflate_block_slow(&dc, trees, fast_viable ? 32 : SIZE_MAX);
+ }
+
+ if (err < 0) return err;
+
+ // `ufbxi_inflate_block()` returns normally on cancel so check it here
+ if (dc.stream.stop_error != 0) return dc.stream.stop_error;
+
+ if (err == 0) break;
+ }
+
+ } else {
+ // 0b11 - reserved (error)
+ return -7;
+ }
+
+ bits = dc.stream.bits;
+ left = dc.stream.left;
+ data = dc.stream.chunk_ptr;
+
+ // BFINAL: End of stream
+ if (header & 1) break;
+ }
+
+ // Check Adler-32
+ {
+ // Round up to the next byte
+ size_t align_bits = left & 0x7;
+ bits >>= align_bits;
+ left -= align_bits;
+ ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
+ if (dc.stream.stop_error != 0) return dc.stream.stop_error;
+
+ if (!input->no_checksum) {
+ uint32_t ref = (uint32_t)bits;
+ ref = (ref>>24) | ((ref>>8)&0xff00) | ((ref<<8)&0xff0000) | (ref<<24);
+
+ uint32_t checksum = ufbxi_adler32(dc.out_begin, ufbxi_to_size(dc.out_ptr - dc.out_begin));
+ if (ref != checksum) {
+ return -9;
+ }
+ }
+ }
+
+ return dc.out_ptr - dc.out_begin;
+}
+
+#endif // !defined(ufbx_inflate)
+
+// -- Printf
+
+typedef struct {
+ char *dst;
+ size_t length;
+ size_t pos;
+} ufbxi_print_buffer;
+
+#define UFBXI_PRINT_UNSIGNED 0x1
+#define UFBXI_PRINT_STRING 0x2
+#define UFBXI_PRINT_SIZE_T 0x10
+
+static void ufbxi_print_append(ufbxi_print_buffer *buf, size_t min_width, size_t max_width, const char *str)
+{
+ size_t width = 0;
+ for (width = 0; width < max_width; width++) {
+ if (!str[width]) break;
+ }
+ size_t pad = min_width > width ? min_width - width : 0;
+ for (size_t i = 0; i < pad; i++) {
+ if (buf->pos < buf->length) buf->dst[buf->pos++] = ' ';
+ }
+ for (size_t i = 0; i < width; i++) {
+ if (buf->pos < buf->length) buf->dst[buf->pos++] = str[i];
+ }
+}
+
+static char *ufbxi_print_format_int(char *buffer, uint64_t value)
+{
+ *--buffer = '\0';
+ do {
+ uint32_t digit = (uint32_t)(value % 10);
+ value = value / 10;
+ *--buffer = (char)('0' + digit);
+ } while (value > 0);
+ return buffer;
+}
+
+static void ufbxi_vprint(ufbxi_print_buffer *buf, const char *fmt, va_list args)
+{
+ char buffer[96]; // ufbxi_uninit
+ for (const char *p = fmt; *p;) {
+ if (*p == '%' && *++p != '%') {
+ size_t min_width = 0, max_width = SIZE_MAX;
+ if (*p == '*') {
+ p++;
+ min_width = (size_t)va_arg(args, int);
+ }
+ if (*p == '.') {
+ ufbxi_dev_assert(p[1] == '*');
+ p += 2;
+ max_width = (size_t)va_arg(args, int);
+ }
+ uint32_t flags = 0;
+ switch (*p) {
+ case 'z': p++; flags |= UFBXI_PRINT_SIZE_T; break;
+ default: break;
+ }
+ switch (*p++) {
+ case 'u': flags |= UFBXI_PRINT_UNSIGNED; break;
+ case 's': flags |= UFBXI_PRINT_STRING; break;
+ default: break;
+ }
+ if (flags & UFBXI_PRINT_STRING) {
+ const char *str = va_arg(args, const char*);
+ ufbxi_print_append(buf, min_width, max_width, str);
+ } else if (flags & UFBXI_PRINT_UNSIGNED) {
+ uint64_t value = (flags & UFBXI_PRINT_SIZE_T) != 0 ? (uint64_t)va_arg(args, size_t) : (uint64_t)va_arg(args, uint32_t);
+ char *str = ufbxi_print_format_int(buffer + sizeof(buffer), value);
+ ufbxi_print_append(buf, min_width, max_width, str);
+ } else {
+ ufbxi_unreachable("Bad printf format");
+ }
+ } else {
+ if (buf->pos < buf->length) buf->dst[buf->pos++] = *p;
+ p++;
+ }
+ }
+ if (buf->length && buf->dst) {
+ size_t end = buf->pos <= buf->length - 1 ? buf->pos : buf->length - 1;
+ buf->dst[end] = '\0';
+ }
+}
+
+// -- Errors
+
+static const char ufbxi_empty_char[1] = { '\0' };
+
+static ufbxi_noinline int ufbxi_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list args)
+{
+ ufbxi_print_buffer buffer = { buf, buf_size };
+ ufbxi_vprint(&buffer, fmt, args);
+ return (int)ufbxi_min_sz(buffer.pos, buf_size - 1);
+}
+
+static ufbxi_noinline int ufbxi_snprintf(char *buf, size_t buf_size, const char *fmt, ...)
+{
+ va_list args; // ufbxi_uninit
+ va_start(args, fmt);
+ int result = ufbxi_vsnprintf(buf, buf_size, fmt, args);
+ va_end(args);
+ return result;
+}
+
+static ufbxi_noinline void ufbxi_panicf_imp(ufbx_panic *panic, const char *fmt, ...)
+{
+ if (panic && panic->did_panic) return;
+
+ va_list args; // ufbxi_uninit
+
+ if (panic) {
+ va_start(args, fmt);
+ panic->did_panic = true;
+ panic->message_length = (size_t)ufbxi_vsnprintf(panic->message, sizeof(panic->message), fmt, args);
+ va_end(args);
+ } else {
+ va_start(args, fmt);
+ char message[UFBX_PANIC_MESSAGE_LENGTH];
+ ufbxi_vsnprintf(message, sizeof(message), fmt, args);
+ va_end(args);
+
+ ufbx_panic_handler(message);
+ }
+}
+
+#define ufbxi_panicf(panic, cond, ...) \
+ ((cond) ? false : (ufbxi_panicf_imp((panic), __VA_ARGS__), true))
+
+// Prefix the error condition with $Description\0 for a human readable description
+#define ufbxi_error_msg(cond, msg) "$" msg "\0" cond
+
+static ufbxi_noinline int ufbxi_fail_imp_err(ufbx_error *err, const char *cond, const char *func, uint32_t line)
+{
+ if (cond && cond[0] == '$') {
+ if (!err->description.data) {
+ err->description.data = cond + 1;
+ err->description.length = strlen(err->description.data);
+ }
+
+#if UFBXI_FEATURE_ERROR_STACK
+ // Skip the description part if adding to a stack
+ cond = cond + strlen(cond) + 1;
+#endif
+ }
+
+ // NOTE: This is the base function all fails boil down to, place a breakpoint here to
+ // break at the first error
+#if UFBXI_FEATURE_ERROR_STACK
+ ufbx_assert(cond);
+ ufbx_assert(func);
+ if (err->stack_size < UFBX_ERROR_STACK_MAX_DEPTH) {
+ ufbx_error_frame *frame = &err->stack[err->stack_size++];
+ frame->description.data = cond;
+ frame->description.length = strlen(cond);
+ frame->function.data = func;
+ frame->function.length = strlen(func);
+ frame->source_line = line;
+ }
+#else
+ ufbxi_ignore(func);
+ ufbxi_ignore(line);
+#endif
+
+ return 0;
+}
+
+ufbxi_nodiscard static ufbxi_noinline size_t ufbxi_utf8_valid_length(const char *str, size_t length)
+{
+ size_t index = 0;
+ while (index < length) {
+ uint8_t c = (uint8_t)str[index];
+ size_t left = length - index;
+
+ if ((c & 0x80) == 0) {
+ if (c != 0) {
+ index += 1;
+ continue;
+ }
+ } else if ((c & 0xe0) == 0xc0 && left >= 2) {
+ uint8_t t0 = (uint8_t)str[index + 1];
+ uint32_t code = (uint32_t)c << 8 | (uint32_t)t0;
+ if ((code & 0xc0) == 0x80 && code >= 0xc280) {
+ index += 2;
+ continue;
+ }
+ } else if ((c & 0xf0) == 0xe0 && left >= 3) {
+ uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2];
+ uint32_t code = (uint32_t)c << 16 | (uint32_t)t0 << 8 | (uint32_t)t1;
+ if ((code & 0xc0c0) == 0x8080 && code >= 0xe0a080 && (code < 0xeda080 || code >= 0xee8080)) {
+ index += 3;
+ continue;
+ }
+ } else if ((c & 0xf8) == 0xf0 && left >= 4) {
+ uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2], t2 = (uint8_t)str[index + 3];
+ uint32_t code = (uint32_t)c << 24 | (uint32_t)t0 << 16 | (uint32_t)t1 << 8 | (uint32_t)t2;
+ if ((code & 0xc0c0c0) == 0x808080 && code >= 0xf0908080u && code <= 0xf48fbfbfu) {
+ index += 4;
+ continue;
+ }
+ }
+
+ break;
+ }
+
+ ufbx_assert(index <= length);
+ return index;
+}
+
+static ufbxi_noinline void ufbxi_clean_string_utf8(char *str, size_t length)
+{
+ size_t pos = 0;
+ for (;;) {
+ pos += ufbxi_utf8_valid_length(str + pos, length - pos);
+ if (pos == length) break;
+ str[pos++] = '?';
+ }
+}
+
+static ufbxi_noinline void ufbxi_set_err_info(ufbx_error *err, const char *data, size_t length)
+{
+ if (!err) return;
+
+ if (length == SIZE_MAX) length = strlen(data);
+ size_t to_copy = ufbxi_min_sz(sizeof(err->info) - 1, length);
+ memcpy(err->info, data, to_copy);
+ err->info[to_copy] = '\0';
+ err->info_length = to_copy;
+ ufbxi_clean_string_utf8(err->info, err->info_length);
+}
+
+static ufbxi_noinline void ufbxi_fmt_err_info(ufbx_error *err, const char *fmt, ...)
+{
+ if (!err) return;
+
+ va_list args; // ufbxi_uninit
+ va_start(args, fmt);
+ err->info_length = (size_t)ufbxi_vsnprintf(err->info, sizeof(err->info), fmt, args);
+ va_end(args);
+ ufbxi_clean_string_utf8(err->info, err->info_length);
+}
+
+static ufbxi_noinline void ufbxi_clear_error(ufbx_error *err)
+{
+ if (!err) return;
+
+ err->type = UFBX_ERROR_NONE;
+ err->description.data = ufbxi_empty_char;
+ err->description.length = 0;
+ err->stack_size = 0;
+ err->info[0] = '\0';
+ err->info_length = 0;
+}
+
+#if UFBXI_FEATURE_ERROR_STACK
+ #define ufbxi_function __FUNCTION__
+ #define ufbxi_line __LINE__
+ #define ufbxi_cond_str(cond) #cond
+#else
+ #define ufbxi_function NULL
+ #define ufbxi_line 0
+ #define ufbxi_cond_str(cond) ""
+#endif
+
+#if UFBXI_FEATURE_ERROR_STACK
+ #define ufbxi_fail_err_no_msg(err, cond, func, line) ufbxi_fail_imp_err((err), (cond), (func), (line))
+#else
+ static ufbxi_noinline int ufbxi_fail_imp_err_no_stack(ufbx_error *err) { return ufbxi_fail_imp_err(err, NULL, NULL, 0); }
+ #define ufbxi_fail_err_no_msg(err, cond, func, line) ufbxi_fail_imp_err_no_stack((err))
+#endif
+
+#define ufbxi_check_err(err, cond) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_err_no_msg((err), ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return 0; } } while (0)
+#define ufbxi_check_return_err(err, cond, ret) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_err_no_msg((err), ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return ret; } } while (0)
+#define ufbxi_fail_err(err, desc) return ufbxi_fail_err_no_msg(err, desc, ufbxi_function, ufbxi_line)
+
+#define ufbxi_check_err_msg(err, cond, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp_err((err), ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return 0; } } while (0)
+#define ufbxi_check_return_err_msg(err, cond, ret, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp_err((err), ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return ret; } } while (0)
+#define ufbxi_fail_err_msg(err, desc, msg) return ufbxi_fail_imp_err(err, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
+#define ufbxi_report_err_msg(err, desc, msg) (void)ufbxi_fail_imp_err(err, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
+
+static ufbxi_noinline void ufbxi_fix_error_type(ufbx_error *error, const char *default_desc, ufbx_error *p_error)
+{
+ const char *desc = error->description.data;
+ if (!desc) desc = default_desc;
+ error->type = UFBX_ERROR_UNKNOWN;
+ if (!strcmp(desc, "Out of memory")) {
+ error->type = UFBX_ERROR_OUT_OF_MEMORY;
+ } else if (!strcmp(desc, "Memory limit exceeded")) {
+ error->type = UFBX_ERROR_MEMORY_LIMIT;
+ } else if (!strcmp(desc, "Allocation limit exceeded")) {
+ error->type = UFBX_ERROR_ALLOCATION_LIMIT;
+ } else if (!strcmp(desc, "Truncated file")) {
+ error->type = UFBX_ERROR_TRUNCATED_FILE;
+ } else if (!strcmp(desc, "IO error")) {
+ error->type = UFBX_ERROR_IO;
+ } else if (!strcmp(desc, "Cancelled")) {
+ error->type = UFBX_ERROR_CANCELLED;
+ } else if (!strcmp(desc, "Unrecognized file format")) {
+ error->type = UFBX_ERROR_UNRECOGNIZED_FILE_FORMAT;
+ } else if (!strcmp(desc, "File not found")) {
+ error->type = UFBX_ERROR_FILE_NOT_FOUND;
+ } else if (!strcmp(desc, "Empty file")) {
+ error->type = UFBX_ERROR_EMPTY_FILE;
+ } else if (!strcmp(desc, "External file not found")) {
+ error->type = UFBX_ERROR_EXTERNAL_FILE_NOT_FOUND;
+ } else if (!strcmp(desc, "Uninitialized options")) {
+ error->type = UFBX_ERROR_UNINITIALIZED_OPTIONS;
+ } else if (!strcmp(desc, "Zero vertex size")) {
+ error->type = UFBX_ERROR_ZERO_VERTEX_SIZE;
+ } else if (!strcmp(desc, "Truncated vertex stream")) {
+ error->type = UFBX_ERROR_TRUNCATED_VERTEX_STREAM;
+ } else if (!strcmp(desc, "Invalid UTF-8")) {
+ error->type = UFBX_ERROR_INVALID_UTF8;
+ } else if (!strcmp(desc, "Feature disabled")) {
+ error->type = UFBX_ERROR_FEATURE_DISABLED;
+ } else if (!strcmp(desc, "Bad NURBS geometry")) {
+ error->type = UFBX_ERROR_BAD_NURBS;
+ } else if (!strcmp(desc, "Bad index")) {
+ error->type = UFBX_ERROR_BAD_INDEX;
+ } else if (!strcmp(desc, "Node depth limit exceeded")) {
+ error->type = UFBX_ERROR_NODE_DEPTH_LIMIT;
+ } else if (!strcmp(desc, "Threaded ASCII parse error")) {
+ error->type = UFBX_ERROR_THREADED_ASCII_PARSE;
+ } else if (!strcmp(desc, "Unsafe options")) {
+ error->type = UFBX_ERROR_UNSAFE_OPTIONS;
+ } else if (!strcmp(desc, "Duplicate override")) {
+ error->type = UFBX_ERROR_DUPLICATE_OVERRIDE;
+ }
+ error->description.data = desc;
+ error->description.length = strlen(desc);
+ if (p_error) {
+ memcpy(p_error, error, sizeof(ufbx_error));
+ }
+}
+
+// -- Allocator
+
+// Returned for zero size allocations, place in the constant data
+// to catch writes to bad allocations.
+#if defined(UFBX_REGRESSION)
+static const char ufbxi_zero_size_buffer[4096] = { 0 };
+#else
+static const char ufbxi_zero_size_buffer[64] = { 0 };
+#endif
+
+static ufbxi_forceinline size_t ufbxi_align_to_mask(size_t value, size_t align_mask)
+{
+ return value + (((size_t)0 - value) & align_mask);
+}
+
+static ufbxi_forceinline size_t ufbxi_size_align_mask(size_t size)
+{
+ // Align to the all bits below the lowest set one in `size` up to the maximum alignment.
+ return ((size ^ (size - 1)) >> 1) & (UFBX_MAXIMUM_ALIGNMENT - 1);
+}
+
+typedef struct {
+ ufbx_error *error;
+ size_t current_size;
+ size_t max_size;
+ size_t num_allocs;
+ size_t max_allocs;
+ size_t huge_size;
+ size_t chunk_max;
+ ufbx_allocator_opts ator;
+ const char *name;
+} ufbxi_allocator;
+
+static ufbxi_forceinline bool ufbxi_does_overflow(size_t total, size_t a, size_t b)
+{
+ // If `a` and `b` have at most 4 bits per `size_t` byte, the product can't overflow.
+ if (((a | b) >> sizeof(size_t)*4) != 0) {
+ if (a != 0 && total / a != b) return true;
+ }
+ return false;
+}
+
+static ufbxi_noinline void *ufbxi_alloc_size(ufbxi_allocator *ator, size_t size, size_t n)
+{
+ // Always succeed with an empty non-NULL buffer for empty allocations
+ ufbx_assert(size > 0);
+ if (n == 0) return (void*)ufbxi_zero_size_buffer;
+
+ size_t total = size * n;
+ ufbxi_check_return_err(ator->error, !ufbxi_does_overflow(total, size, n), NULL);
+ ufbxi_check_return_err(ator->error, total <= SIZE_MAX / 2, NULL); // Make sure it's always safe to double allocations
+ if (!(total < ator->max_size - ator->current_size)) {
+ ufbxi_report_err_msg(ator->error, "total <= ator->max_size - ator->current_size", "Memory limit exceeded");
+ ufbxi_fmt_err_info(ator->error, "%s", ator->name);
+ return NULL;
+ }
+ if (!(ator->num_allocs < ator->max_allocs)) {
+ ufbxi_report_err_msg(ator->error, "ator->num_allocs < ator->max_allocs", "Allocation limit exceeded");
+ ufbxi_fmt_err_info(ator->error, "%s", ator->name);
+ return NULL;
+ }
+ ator->num_allocs++;
+
+ void *ptr;
+ if (ator->ator.allocator.alloc_fn) {
+ ptr = ator->ator.allocator.alloc_fn(ator->ator.allocator.user, total);
+ } else if (ator->ator.allocator.realloc_fn) {
+ ptr = ator->ator.allocator.realloc_fn(ator->ator.allocator.user, NULL, 0, total);
+ } else {
+ ptr = ufbx_malloc(total);
+ }
+
+ if (!ptr) {
+ ufbxi_report_err_msg(ator->error, "ptr", "Out of memory");
+ ufbxi_fmt_err_info(ator->error, "%s", ator->name);
+ return NULL;
+ }
+ ufbx_assert(ufbxi_is_aligned_mask(ptr, ufbxi_size_align_mask(total)));
+
+ ator->current_size += total;
+
+ return ptr;
+}
+
+static void ufbxi_free_size(ufbxi_allocator *ator, size_t size, void *ptr, size_t n);
+static ufbxi_noinline void *ufbxi_realloc_size(ufbxi_allocator *ator, size_t size, void *old_ptr, size_t old_n, size_t n)
+{
+ ufbx_assert(size > 0);
+ // realloc() with zero old/new size is equivalent to alloc()/free()
+ if (old_n == 0) return ufbxi_alloc_size(ator, size, n);
+ if (n == 0) { ufbxi_free_size(ator, size, old_ptr, old_n); return NULL; }
+
+ size_t old_total = size * old_n;
+ size_t total = size * n;
+
+ // The old values have been checked by a previous allocate call
+ ufbx_assert(!ufbxi_does_overflow(old_total, size, old_n));
+ ufbx_assert(old_total <= ator->current_size);
+
+ ufbxi_check_return_err(ator->error, !ufbxi_does_overflow(total, size, n), NULL);
+ ufbxi_check_return_err(ator->error, total <= SIZE_MAX / 2, NULL); // Make sure it's always safe to double allocations
+ ufbxi_check_return_err_msg(ator->error, total <= ator->max_size - ator->current_size, NULL, "Memory limit exceeded");
+ ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
+ ator->num_allocs++;
+
+ void *ptr;
+ if (ator->ator.allocator.realloc_fn) {
+ ptr = ator->ator.allocator.realloc_fn(ator->ator.allocator.user, old_ptr, old_total, total);
+ } else if (ator->ator.allocator.alloc_fn) {
+ // Use user-provided alloc_fn() and free_fn()
+ ptr = ator->ator.allocator.alloc_fn(ator->ator.allocator.user, total);
+ if (ptr) memcpy(ptr, old_ptr, old_total);
+ if (ator->ator.allocator.free_fn) {
+ ator->ator.allocator.free_fn(ator->ator.allocator.user, old_ptr, old_total);
+ }
+ } else {
+ ptr = ufbx_realloc(old_ptr, old_total, total);
+ }
+
+ ufbxi_check_return_err_msg(ator->error, ptr, NULL, "Out of memory");
+ ufbx_assert(ufbxi_is_aligned_mask(ptr, ufbxi_size_align_mask(total)));
+
+ ator->current_size += total;
+ ator->current_size -= old_total;
+
+ return ptr;
+}
+
+static ufbxi_noinline void ufbxi_free_size(ufbxi_allocator *ator, size_t size, void *ptr, size_t n)
+{
+ ufbx_assert(size > 0);
+ if (n == 0) return;
+ ufbx_assert(ptr);
+
+ size_t total = size * n;
+
+ // The old values have been checked by a previous allocate call
+ ufbx_assert(!ufbxi_does_overflow(total, size, n));
+ ufbx_assert(total <= ator->current_size);
+
+ ator->current_size -= total;
+
+ if (ator->ator.allocator.alloc_fn || ator->ator.allocator.realloc_fn) {
+ // Don't call default free() if there is an user-provided `alloc_fn()`
+ if (ator->ator.allocator.free_fn) {
+ ator->ator.allocator.free_fn(ator->ator.allocator.user, ptr, total);
+ } else if (ator->ator.allocator.realloc_fn) {
+ ator->ator.allocator.realloc_fn(ator->ator.allocator.user, ptr, total, 0);
+ }
+ } else {
+ ufbx_free(ptr, total);
+ }
+}
+
+ufbxi_noinline ufbxi_nodiscard static bool ufbxi_grow_array_size(ufbxi_allocator *ator, size_t size, void *p_ptr, size_t *p_cap, size_t n)
+{
+ #if defined(UFBX_REGRESSION)
+ {
+ ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, false, "Allocation limit exceeded");
+ ator->num_allocs++;
+ }
+ #endif
+
+ if (n <= *p_cap) return true;
+ void *ptr = *(void**)p_ptr;
+ size_t old_n = *p_cap;
+ if (old_n >= n) return true;
+ size_t new_n = ufbxi_max_sz(old_n * 2, n);
+ void *new_ptr = ufbxi_realloc_size(ator, size, ptr, old_n, new_n);
+ if (!new_ptr) return false;
+ *(void**)p_ptr = new_ptr;
+ *p_cap = new_n;
+ return true;
+}
+
+static ufbxi_noinline void ufbxi_free_ator(ufbxi_allocator *ator)
+{
+ ufbx_assert(ator->current_size == 0);
+
+ ufbx_free_allocator_fn *free_fn = ator->ator.allocator.free_allocator_fn;
+ if (free_fn) {
+ void *user = ator->ator.allocator.user;
+ free_fn(user);
+ }
+}
+
+#define ufbxi_alloc(ator, type, n) ufbxi_maybe_null((type*)ufbxi_alloc_size((ator), sizeof(type), (n)))
+#define ufbxi_alloc_zero(ator, type, n) ufbxi_maybe_null((type*)ufbxi_alloc_zero_size((ator), sizeof(type), (n)))
+#define ufbxi_realloc(ator, type, old_ptr, old_n, n) ufbxi_maybe_null((type*)ufbxi_realloc_size((ator), sizeof(type), (old_ptr), (old_n), (n)))
+#define ufbxi_realloc_zero(ator, type, old_ptr, old_n, n) ufbxi_maybe_null((type*)ufbxi_realloc_zero_size((ator), sizeof(type), (old_ptr), (old_n), (n)))
+#define ufbxi_free(ator, type, ptr, n) ufbxi_free_size((ator), sizeof(type), (ptr), (n))
+
+#define ufbxi_grow_array(ator, p_ptr, p_cap, n) ufbxi_grow_array_size((ator), sizeof(**(p_ptr)), (p_ptr), (p_cap), (n))
+
+#define UFBXI_SCENE_IMP_MAGIC 0x58424655
+#define UFBXI_MESH_IMP_MAGIC 0x48534d55
+#define UFBXI_LINE_CURVE_IMP_MAGIC 0x55434c55
+#define UFBXI_CACHE_IMP_MAGIC 0x48434355
+#define UFBXI_ANIM_IMP_MAGIC 0x494e4155
+#define UFBXI_BAKED_ANIM_IMP_MAGIC 0x4b414255
+#define UFBXI_REFCOUNT_IMP_MAGIC 0x46455255
+#define UFBXI_BUF_CHUNK_IMP_MAGIC 0x46554255
+
+// -- Memory buffer
+//
+// General purpose memory buffer that can be used either as a chunked linear memory
+// allocator or a non-contiguous stack. You can convert the contents of `ufbxi_buf`
+// to a contiguous range of memory by calling `ufbxi_make_array[_all]()`
+
+typedef struct ufbxi_buf_padding ufbxi_buf_padding;
+typedef struct ufbxi_buf_chunk ufbxi_buf_chunk;
+
+struct ufbxi_buf_padding {
+ size_t original_pos; // < Original position before aligning
+ size_t prev_padding; // < Starting offset of the previous `ufbxi_buf_padding`
+};
+
+struct ufbxi_buf_chunk {
+
+ // Linked list of nodes
+ ufbxi_buf_chunk *root;
+ ufbxi_buf_chunk *prev;
+ ufbxi_buf_chunk *next;
+
+ union {
+ size_t magic; // < Magic for debugging
+ void *align_0; // < Align to 4x pointer size (16/32 bytes)
+ };
+
+ size_t size; // < Size of the chunk `data`, excluding this header
+ size_t pushed_pos; // < Size of valid data when pushed to the list
+ size_t next_size; // < Next geometrically growing chunk size to allocate
+ size_t padding_pos; // < One past the offset of the most recent `ufbxi_buf_padding`
+
+ char data[]; // < Must be aligned to 8 bytes
+};
+
+ufbx_static_assert(buf_chunk_align, offsetof(ufbxi_buf_chunk, data) % 8 == 0);
+
+typedef struct {
+ ufbxi_allocator *ator;
+
+ // Current chunks for normal and huge allocations.
+ // Ordered buffers (`!ufbxi_buf.unordered`) never use `chunks[1]`
+ ufbxi_buf_chunk *chunks[2];
+
+ // Inline state for non-huge chunks
+ size_t pos; // < Next offset to allocate from
+ size_t size; // < Size of the current chunk ie. `chunks[0]->size` (or 0 if `chunks[0] == NULL`)
+
+ size_t num_items; // < Number of individual items pushed to the buffer
+
+ size_t pushed_size; // < Cumulative size of pushed chunks, not tracked across pops
+
+ bool unordered; // < Does not support popping from the buffer
+ bool clearable; // < Supports clearing the whole buffer even if `unordered`
+} ufbxi_buf;
+
+typedef struct {
+ ufbxi_buf_chunk *chunk;
+ size_t pos;
+ size_t num_items;
+} ufbxi_buf_state;
+
+static ufbxi_noinline void *ufbxi_push_size_new_block(ufbxi_buf *b, size_t size)
+{
+ bool huge = size >= b->ator->huge_size;
+
+ // Use the second chunk "list" for huge unordered chunks.
+ // The state of these chunks is not tracked by `ufbxi_buf.pos/size`.
+ uint32_t list_ix = ((uint32_t)b->unordered & (uint32_t)huge);
+
+ ufbxi_buf_chunk *chunk = b->chunks[list_ix];
+ if (chunk) {
+ if (list_ix == 0) {
+ // Store the final position for the retired chunk and scan free
+ // chunks in case we find one the allocation fits in.
+ b->pushed_size += b->pos;
+ chunk->pushed_pos = b->pos;
+ ufbxi_buf_chunk *next = chunk->next;
+ while (next != NULL) {
+ ufbx_assert(next->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ chunk = next;
+ ufbx_assert(b->unordered || chunk->pushed_pos == 0);
+ chunk->pushed_pos = 0;
+ if (size <= chunk->size) {
+ b->chunks[0] = chunk;
+ b->pos = (uint32_t)size;
+ b->size = chunk->size;
+ return chunk->data;
+ }
+ next = chunk->next;
+ }
+ } else if (b->clearable) {
+ // Keep track of the `UFBXI_HUGE_MAX_SCAN` largest chunks and
+ // retain them. Overflowing chunks are freed in `ufbxi_buf_clear()`
+ size_t align_mask = ufbxi_size_align_mask(size);
+ ufbxi_buf_chunk *next = chunk;
+
+ ufbxi_buf_chunk *best_chunk = NULL;
+ size_t best_space = SIZE_MAX;
+
+ // Clearable huge chunks are sorted by descending size. Check the first N
+ // chunks for reuse and find the place a new block should be inserted if
+ // no suitable space is found. Chunk ordering in the tail doesn't matter
+ // as those chunks are never reused.
+ // Unreachable chunks in the tail are freed in `ufbxi_buf_clear()`.
+ for (size_t i = 0; next && i < UFBXI_HUGE_MAX_SCAN; i++) {
+ ufbx_assert(next->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ if (next->size < size) break;
+ chunk = next;
+
+ // Try to reuse chunks using a best-fit strategy.
+ size_t pos = ufbxi_align_to_mask(chunk->pushed_pos, align_mask);
+ size_t space = chunk->size - pos;
+ if (size <= space) {
+ if (space < best_space) {
+ best_chunk = chunk;
+ best_space = space;
+ }
+ }
+
+ next = chunk->next;
+ }
+
+ // Early return if we found a slot.
+ if (best_chunk) {
+ size_t pos = ufbxi_align_to_mask(best_chunk->pushed_pos, align_mask);
+ best_chunk->pushed_pos = pos + size;
+ b->pushed_size += size;
+ return best_chunk->data + pos;
+ }
+ }
+ }
+
+ // Allocate a new chunk, grow `next_size` geometrically but don't double
+ // the current or previous user sizes if they are larger.
+ size_t chunk_size, next_size;
+
+ // If `size` is larger than `huge_size` don't grow `next_size` geometrically,
+ // but use a dedicated allocation.
+ if (huge) {
+ next_size = chunk ? chunk->next_size : 4096;
+ if (next_size > b->ator->chunk_max) next_size = b->ator->chunk_max;
+ chunk_size = size;
+ } else {
+ next_size = chunk ? chunk->next_size * 2 : 4096;
+ if (next_size > b->ator->chunk_max) next_size = b->ator->chunk_max;
+ chunk_size = next_size - sizeof(ufbxi_buf_chunk);
+ if (chunk_size < size) chunk_size = size;
+ }
+
+ // Align chunk sizes to 16 bytes
+ chunk_size = ufbxi_align_to_mask(chunk_size, 0xf);
+
+ ufbxi_buf_chunk *new_chunk = (ufbxi_buf_chunk*)ufbxi_alloc_size(b->ator, 1, sizeof(ufbxi_buf_chunk) + chunk_size);
+ if (!new_chunk) return NULL;
+
+ new_chunk->prev = chunk;
+ new_chunk->size = chunk_size;
+ new_chunk->next_size = next_size;
+ new_chunk->magic = UFBXI_BUF_CHUNK_IMP_MAGIC;
+ new_chunk->padding_pos = 0;
+ new_chunk->pushed_pos = 0;
+
+ // Link the chunk to the list and set it as the active one
+ if (chunk) {
+ ufbxi_buf_chunk *next = chunk->next;
+ if (next) next->prev = new_chunk;
+ new_chunk->next = next;
+ chunk->next = new_chunk;
+ new_chunk->root = chunk->root;
+ } else {
+ new_chunk->next = NULL;
+ new_chunk->root = new_chunk;
+ }
+
+ if (list_ix == 0) {
+ b->chunks[0] = new_chunk;
+ b->pos = size;
+ b->size = chunk_size;
+ } else {
+ ufbxi_buf_chunk *root = b->chunks[1];
+ b->pushed_size += size;
+ if (!root) {
+ b->chunks[1] = new_chunk;
+ } else if (root->size < chunk_size) {
+ // Swap root and self if necessary, we should have bailed out
+ // in the search loop in the first iteration so `new_chunk` should
+ // directly follow `root`.
+ // HACK: This ends up with `chunks[1]` entries having inconsistent
+ // `ufbxi_buf_chunk.root` pointers but other code only reads `chunks[1].root`
+ // TODO: Move roots out of the chunks?
+ ufbx_assert(root->next == new_chunk);
+ ufbx_assert(new_chunk->prev == root);
+ if (new_chunk->next) new_chunk->next->prev = root;
+ root->next = new_chunk->next;
+ new_chunk->next = root;
+ new_chunk->prev = NULL;
+ new_chunk->root = new_chunk;
+ b->chunks[1] = new_chunk;
+ }
+ new_chunk->pushed_pos = size;
+ }
+
+ return new_chunk->data;
+}
+
+static ufbxi_noinline void *ufbxi_push_size(ufbxi_buf *b, size_t size, size_t n)
+{
+ // Always succeed with an empty non-NULL buffer for empty allocations
+ ufbx_assert(size > 0);
+ if (n == 0) return (void*)ufbxi_zero_size_buffer;
+
+ size_t total = size * n;
+ if (ufbxi_does_overflow(total, size, n)) return NULL;
+
+ // Keep some slack to avoid overflows
+ if (total >= SIZE_MAX / 2) return NULL;
+
+ #if defined(UFBX_REGRESSION)
+ {
+ ufbxi_allocator *ator = b->ator;
+ ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
+ ator->num_allocs++;
+ }
+ #endif
+
+ b->num_items += n;
+
+ // Align to the natural alignment based on the size
+ size_t align_mask = ufbxi_size_align_mask(size);
+ size_t pos = ufbxi_align_to_mask(b->pos, align_mask);
+
+ if (!b->unordered && pos != b->pos) {
+ // Alignment mismatch in an unordered block. Align to 16 bytes to guarantee
+ // sufficient alignment for anything afterwards and mark the padding.
+ // If we overflow the current block we don't need to care as the block
+ // boundaries are not contiguous.
+ pos = ufbxi_align_to_mask(b->pos, 0xf);
+ if (total < SIZE_MAX - 16 && total + 16 <= b->size - pos) {
+ ufbxi_buf_chunk *chunk = b->chunks[0];
+ ufbxi_buf_padding *padding = (ufbxi_buf_padding*)(chunk->data + pos);
+ padding->original_pos = b->pos;
+ padding->prev_padding = chunk->padding_pos;
+ chunk->padding_pos = pos + 16 + 1;
+ b->pos = pos + 16 + total;
+ return (char*)padding + 16;
+ } else {
+ return ufbxi_push_size_new_block(b, total);
+ }
+ } else {
+ // Try to push to the current block. Allocate a new block
+ // if the aligned size doesn't fit.
+ if (total <= b->size - pos) {
+ b->pos = pos + total;
+ return b->chunks[0]->data + pos;
+ } else {
+ return ufbxi_push_size_new_block(b, total);
+ }
+ }
+}
+
+static ufbxi_forceinline void *ufbxi_push_size_fast(ufbxi_buf *b, size_t size, size_t n)
+{
+ // Always succeed with an empty non-NULL buffer for empty allocations
+ ufbxi_regression_assert(size > 0);
+ ufbxi_regression_assert(n > 0);
+
+ size_t total = size * n;
+ ufbxi_regression_assert(!ufbxi_does_overflow(total, size, n));
+
+ #if defined(UFBX_REGRESSION)
+ {
+ ufbxi_allocator *ator = b->ator;
+ ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
+ ator->num_allocs++;
+ }
+ #endif
+
+ b->num_items += n;
+
+ // Homogeneous arrays should always be aligned
+ size_t pos = b->pos;
+ ufbxi_regression_assert((pos & ufbxi_size_align_mask(size)) == 0);
+
+ // Try to push to the current block. Allocate a new block
+ // if the aligned size doesn't fit.
+ if (total <= b->size - pos) {
+ b->pos = pos + total;
+ return b->chunks[0]->data + pos;
+ } else {
+ return ufbxi_push_size_new_block(b, total);
+ }
+}
+
+static ufbxi_noinline void *ufbxi_push_size_zero(ufbxi_buf *b, size_t size, size_t n)
+{
+ void *ptr = ufbxi_push_size(b, size, n);
+ if (ptr) memset(ptr, 0, size * n);
+ return ptr;
+}
+
+ufbxi_nodiscard static ufbxi_noinline void *ufbxi_push_size_copy(ufbxi_buf *b, size_t size, size_t n, const void *data)
+{
+ // Always succeed with an empty non-NULL buffer for empty allocations, even if `data == NULL`
+ ufbx_assert(size > 0);
+ if (n == 0) return (void*)ufbxi_zero_size_buffer;
+
+ ufbx_assert(data);
+ void *ptr = ufbxi_push_size(b, size, n);
+ if (ptr) memcpy(ptr, data, size * n);
+ return ptr;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline void *ufbxi_push_size_copy_fast(ufbxi_buf *b, size_t size, size_t n, const void *data)
+{
+ // Always succeed with an empty non-NULL buffer for empty allocations, even if `data == NULL`
+ ufbx_assert(size > 0);
+ if (n == 0) return (void*)ufbxi_zero_size_buffer;
+
+ ufbx_assert(data);
+ void *ptr = ufbxi_push_size_fast(b, size, n);
+ if (ptr) memcpy(ptr, data, size * n);
+ return ptr;
+}
+
+static ufbxi_noinline void ufbxi_buf_free_unused(ufbxi_buf *b)
+{
+ ufbx_assert(!b->unordered);
+
+ ufbxi_buf_chunk *chunk = b->chunks[0];
+ if (!chunk) return;
+
+ ufbxi_buf_chunk *next = chunk->next;
+ while (next) {
+ ufbxi_buf_chunk *to_free = next;
+ next = next->next;
+ ufbx_assert(to_free->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ to_free->magic = 0;
+ ufbxi_free_size(b->ator, 1, to_free, sizeof(ufbxi_buf_chunk) + to_free->size);
+ }
+ chunk->next = NULL;
+
+ while (b->pos == 0 && chunk) {
+ ufbxi_buf_chunk *prev = chunk->prev;
+ ufbx_assert(chunk->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ chunk->magic = 0;
+ ufbxi_free_size(b->ator, 1, chunk, sizeof(ufbxi_buf_chunk) + chunk->size);
+ chunk = prev;
+ b->chunks[0] = prev;
+ if (prev) {
+ prev->next = NULL;
+ b->pos = prev->pushed_pos;
+ b->size = prev->size;
+ } else {
+ b->pos = 0;
+ b->size = 0;
+ }
+ }
+}
+
+static ufbxi_noinline void ufbxi_pop_size(ufbxi_buf *b, size_t size, size_t n, void *dst, bool peek)
+{
+ ufbx_assert(!b->unordered);
+ ufbx_assert(size > 0);
+ ufbx_assert(b->num_items >= n);
+ if (!peek) b->num_items -= n;
+
+ char *ptr = (char*)dst;
+ size_t bytes_left = size * n;
+
+ // We've already pushed this, it better not overflow
+ ufbx_assert(!ufbxi_does_overflow(bytes_left, size, n));
+
+ if (ptr) {
+ ptr += bytes_left;
+ size_t pos = b->pos;
+ ufbxi_buf_chunk *chunk = b->chunks[0];
+ for (;;) {
+ if (bytes_left <= pos) {
+ // Rest of the data is in this single chunk
+ pos -= bytes_left;
+ if (!peek) b->pos = pos;
+ ptr -= bytes_left;
+ if (bytes_left > 0) {
+ memcpy(ptr, chunk->data + pos, bytes_left);
+ }
+ break;
+ } else {
+ // Pop the whole chunk
+ ptr -= pos;
+ bytes_left -= pos;
+ memcpy(ptr, chunk->data, pos);
+ if (!peek) {
+ chunk->pushed_pos = 0;
+ chunk = chunk->prev;
+ b->chunks[0] = chunk;
+ b->size = chunk->size;
+ } else {
+ chunk = chunk->prev;
+ }
+ pos = chunk->pushed_pos;
+ }
+ }
+ } else {
+ size_t pos = b->pos;
+ ufbxi_buf_chunk *chunk = b->chunks[0];
+ for (;;) {
+ if (bytes_left <= pos) {
+ // Rest of the data is in this single chunk
+ pos -= bytes_left;
+ if (!peek) b->pos = pos;
+ break;
+ } else {
+ // Pop the whole chunk
+ bytes_left -= pos;
+ if (!peek) {
+ chunk->pushed_pos = 0;
+ chunk = chunk->prev;
+ b->chunks[0] = chunk;
+ b->size = chunk->size;
+ } else {
+ chunk = chunk->prev;
+ }
+ pos = chunk->pushed_pos;
+ }
+ }
+ }
+
+ if (!peek) {
+ // Check if we need to rewind past some alignment padding
+ ufbxi_buf_chunk *chunk = b->chunks[0];
+ if (chunk) {
+ size_t pos = b->pos, padding_pos = chunk->padding_pos;
+ if (pos < padding_pos) {
+ ufbx_assert(pos + 1 == padding_pos);
+ ufbxi_buf_padding *padding = (ufbxi_buf_padding*)(chunk->data + padding_pos - 1 - 16);
+ b->pos = padding->original_pos;
+ chunk->padding_pos = padding->prev_padding;
+ }
+ }
+
+ // Immediately free popped items if all the allocations are huge
+ // as it means we want to have dedicated allocations for each push.
+ if (b->ator->huge_size <= 1) {
+ ufbxi_buf_free_unused(b);
+ }
+ }
+}
+
+static ufbxi_noinline void *ufbxi_push_pop_size(ufbxi_buf *dst, ufbxi_buf *src, size_t size, size_t n)
+{
+ void *data = ufbxi_push_size(dst, size, n);
+ if (!data) return NULL;
+ ufbxi_pop_size(src, size, n, data, false);
+ return data;
+}
+
+static ufbxi_noinline void *ufbxi_push_peek_size(ufbxi_buf *dst, ufbxi_buf *src, size_t size, size_t n)
+{
+ void *data = ufbxi_push_size(dst, size, n);
+ if (!data) return NULL;
+ ufbxi_pop_size(src, size, n, data, true);
+ return data;
+}
+
+static ufbxi_noinline void ufbxi_buf_free(ufbxi_buf *buf)
+{
+ ufbxi_nounroll for (size_t i = 0; i < 2; i++) {
+ ufbxi_buf_chunk *chunk = buf->chunks[i];
+ if (chunk) {
+ chunk = chunk->root;
+ while (chunk) {
+ ufbxi_buf_chunk *next = chunk->next;
+ ufbx_assert(chunk->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ chunk->magic = 0;
+ ufbxi_free_size(buf->ator, 1, chunk, sizeof(ufbxi_buf_chunk) + chunk->size);
+ chunk = next;
+ }
+ }
+ buf->chunks[i] = NULL;
+ }
+ buf->pos = 0;
+ buf->size = 0;
+ buf->num_items = 0;
+}
+
+static ufbxi_noinline void ufbxi_buf_clear(ufbxi_buf *buf)
+{
+ // Only unordered or clearable buffers can be cleared
+ ufbx_assert(!buf->unordered || buf->clearable);
+
+ // Free the memory if using ASAN
+ if (buf->ator->huge_size <= 1) {
+ ufbxi_buf_free(buf);
+ return;
+ }
+
+ // Reset the non-huge chunks as `chunk->next` is always free.
+ ufbxi_buf_chunk *chunk = buf->chunks[0];
+ if (chunk) {
+ ufbxi_buf_chunk *root = chunk->root;
+ buf->chunks[0] = root;
+ buf->pos = 0;
+ buf->size = root->size;
+ }
+ buf->num_items = 0;
+ buf->pushed_size = 0;
+
+ // Huge chunks are always sorted by descending size and
+ // `chunks[1]` points to the largest one.
+ ufbxi_buf_chunk *huge = buf->chunks[1];
+ if (huge) {
+ // Reset the first N ones that are tracked.
+ for (size_t i = 0; huge && i < UFBXI_HUGE_MAX_SCAN; i++) {
+ huge->pushed_pos = 0;
+ huge = huge->next;
+ }
+
+ // Got unreachable tail that should be freed: Unlink from the last
+ // tracked chunk and free the rest.
+ if (huge) {
+ huge->prev->next = NULL;
+ while (huge) {
+ ufbxi_buf_chunk *next = huge->next;
+ ufbx_assert(huge->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
+ huge->magic = 0;
+ ufbxi_free_size(buf->ator, 1, huge, sizeof(ufbxi_buf_chunk) + huge->size);
+ huge = next;
+ }
+ }
+ }
+}
+
+#define ufbxi_push(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size((b), sizeof(type), (n)))
+#define ufbxi_push_zero(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size_zero((b), sizeof(type), (n)))
+#define ufbxi_push_copy(b, type, n, data) ufbxi_maybe_null((type*)ufbxi_push_size_copy((b), sizeof(type), (n), (data)))
+#define ufbxi_push_copy_fast(b, type, n, data) ufbxi_maybe_null((type*)ufbxi_push_size_copy_fast((b), sizeof(type), (n), (data)))
+#define ufbxi_push_fast(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size_fast((b), sizeof(type), (n)))
+#define ufbxi_pop(b, type, n, dst) ufbxi_pop_size((b), sizeof(type), (n), (dst), false)
+#define ufbxi_peek(b, type, n, dst) ufbxi_pop_size((b), sizeof(type), (n), (dst), true)
+#define ufbxi_push_pop(dst, src, type, n) ufbxi_maybe_null((type*)ufbxi_push_pop_size((dst), (src), sizeof(type), (n)))
+#define ufbxi_push_peek(dst, src, type, n) ufbxi_maybe_null((type*)ufbxi_push_peek_size((dst), (src), sizeof(type), (n)))
+
+// -- Hash map
+//
+// The actual element comparison is left to the user of `ufbxi_map`, see usage below.
+//
+// NOTES:
+// ufbxi_map_insert() does not support duplicate values, use find first if duplicates are possible!
+// Inserting duplicate elements fails with an assertion if `UFBX_REGRESSION` is enabled.
+
+typedef struct ufbxi_aa_node ufbxi_aa_node;
+
+typedef int ufbxi_cmp_fn(void *user, const void *a, const void *b);
+
+struct ufbxi_aa_node {
+ ufbxi_aa_node *left, *right;
+ uint32_t level;
+ uint32_t index;
+};
+
+typedef struct {
+ ufbxi_allocator *ator;
+ size_t data_size;
+
+ void *items;
+ uint64_t *entries;
+ uint32_t mask;
+
+ uint32_t capacity;
+ uint32_t size;
+
+ ufbxi_cmp_fn *cmp_fn;
+ void *cmp_user;
+
+ ufbxi_buf aa_buf;
+ ufbxi_aa_node *aa_root;
+
+} ufbxi_map;
+
+static ufbxi_noinline void ufbxi_map_init(ufbxi_map *map, ufbxi_allocator *ator, ufbxi_cmp_fn *cmp_fn, void *cmp_user)
+{
+ map->ator = ator;
+#if defined(UFBX_REGRESSION)
+ // HACK: Maps contain pointers that are not stable between runs, in regression
+ // mode this causes instability in allocation patterns due to different AA trees
+ // being built, which is a problem in fuzz checks that need to have deterministic
+ // allocation counts. We can work around this using a local allocator that doesn't
+ // count the allocations.
+ {
+ ufbxi_allocator *regression_ator = (ufbxi_allocator*)ufbx_malloc(sizeof(ufbxi_allocator));
+ ufbx_assert(regression_ator);
+ memset(regression_ator, 0, sizeof(ufbxi_allocator));
+ regression_ator->name = "regression";
+ regression_ator->error = ator->error;
+ regression_ator->huge_size = ator->huge_size;
+ regression_ator->max_size = SIZE_MAX;
+ regression_ator->max_allocs = SIZE_MAX;
+ regression_ator->chunk_max = 0x1000000;
+ map->aa_buf.ator = regression_ator;
+ }
+#else
+ map->aa_buf.ator = ator;
+#endif
+ map->cmp_fn = cmp_fn;
+ map->cmp_user = cmp_user;
+}
+
+static ufbxi_noinline void ufbxi_map_free(ufbxi_map *map)
+{
+#if defined(UFBX_REGRESSION)
+ ufbxi_allocator *regression_ator = map->aa_buf.ator;
+#endif
+
+ ufbxi_buf_free(&map->aa_buf);
+ ufbxi_free(map->ator, char, map->entries, map->data_size);
+ map->entries = NULL;
+ map->items = NULL;
+ map->aa_root = NULL;
+ map->mask = map->capacity = map->size = 0;
+
+#if defined(UFBX_REGRESSION)
+ if (regression_ator) {
+ ufbxi_free_ator(regression_ator);
+ ufbx_free(regression_ator, sizeof(ufbxi_allocator));
+ }
+#endif
+}
+
+// Recursion limit: log2(2^64 / sizeof(ufbxi_aa_node))
+static ufbxi_noinline ufbxi_aa_node *ufbxi_aa_tree_insert(ufbxi_map *map, ufbxi_aa_node *node, const void *value, uint32_t index, size_t item_size)
+ ufbxi_recursive_function(ufbxi_aa_node *, ufbxi_aa_tree_insert, (map, node, value, index, item_size), 59,
+ (ufbxi_map *map, ufbxi_aa_node *node, const void *value, uint32_t index, size_t item_size))
+{
+ if (!node) {
+ ufbxi_aa_node *new_node = ufbxi_push(&map->aa_buf, ufbxi_aa_node, 1);
+ if (!new_node) return NULL;
+ new_node->left = NULL;
+ new_node->right = NULL;
+ new_node->level = 1;
+ new_node->index = index;
+ return new_node;
+ }
+
+ void *entry = (char*)map->items + node->index * item_size;
+ int cmp = map->cmp_fn(map->cmp_user, value, entry);
+ if (cmp < 0) {
+ node->left = ufbxi_aa_tree_insert(map, node->left, value, index, item_size);
+ } else if (cmp >= 0) {
+ node->right = ufbxi_aa_tree_insert(map, node->right, value, index, item_size);
+ }
+
+ if (node->left && node->left->level == node->level) {
+ ufbxi_aa_node *left = node->left;
+ node->left = left->right;
+ left->right = node;
+ node = left;
+ }
+
+ if (node->right && node->right->right && node->right->right->level == node->level) {
+ ufbxi_aa_node *right = node->right;
+ node->right = right->left;
+ right->left = node;
+ right->level += 1;
+ node = right;
+ }
+
+ return node;
+}
+
+static ufbxi_noinline void *ufbxi_aa_tree_find(ufbxi_map *map, const void *value, size_t item_size)
+{
+ ufbxi_aa_node *node = map->aa_root;
+ while (node) {
+ void *entry = (char*)map->items + node->index * item_size;
+ int cmp = map->cmp_fn(map->cmp_user, value, entry);
+ if (cmp < 0) {
+ node = node->left;
+ } else if (cmp > 0) {
+ node = node->right;
+ } else {
+ return entry;
+ }
+ }
+ return NULL;
+}
+
+static ufbxi_noinline bool ufbxi_map_grow_size_imp(ufbxi_map *map, size_t item_size, size_t min_size)
+{
+ ufbx_assert(min_size > 0);
+ const double load_factor = 0.7;
+
+ // Find the lowest power of two size that fits `min_size` within `load_factor`
+ size_t num_entries = map->mask + 1;
+ size_t new_size = (size_t)((double)num_entries * load_factor);
+ if (min_size < map->capacity + 1) min_size = map->capacity + 1;
+ while (new_size < min_size) {
+ num_entries *= 2;
+ new_size = (size_t)((double)num_entries * load_factor);
+ }
+
+ // Check for overflow
+ ufbxi_check_return_err(map->ator->error, SIZE_MAX / num_entries > sizeof(uint64_t), false);
+ size_t alloc_size = num_entries * sizeof(uint64_t);
+
+ // Allocate a combined entry/item memory block
+ ufbxi_check_return_err(map->ator->error, (SIZE_MAX - alloc_size) / new_size > item_size, false);
+ size_t data_size = alloc_size + new_size * item_size;
+
+ char *data = ufbxi_alloc(map->ator, char, data_size);
+ ufbxi_check_return_err(map->ator->error, data, false);
+
+ // Copy the previous user items over
+ uint64_t *old_entries = map->entries;
+ uint64_t *new_entries = (uint64_t*)data;
+ void *new_items = data + alloc_size;
+ if (map->size > 0) {
+ memcpy(new_items, map->items, item_size * map->size);
+ }
+
+ // Re-hash the entries
+ uint32_t old_mask = map->mask;
+ uint32_t new_mask = (uint32_t)(num_entries) - 1;
+ memset(new_entries, 0, sizeof(uint64_t) * num_entries);
+ if (old_mask) {
+ for (uint32_t i = 0; i <= old_mask; i++) {
+ uint64_t entry, new_entry = old_entries[i];
+ if (!new_entry) continue;
+
+ // Reconstruct the hash of the old entry at `i`
+ uint32_t old_scan = (uint32_t)(new_entry & old_mask) - 1;
+ uint32_t hash = ((uint32_t)new_entry & ~old_mask) | ((i - old_scan) & old_mask);
+ uint32_t slot = hash & new_mask;
+ new_entry &= ~(uint64_t)new_mask;
+
+ // Scan forward until we find an empty slot, potentially swapping
+ // `new_element` if it has a shorter scan distance (Robin Hood).
+ uint32_t scan = 1;
+ while ((entry = new_entries[slot]) != 0) {
+ uint32_t entry_scan = (uint32_t)(entry & new_mask);
+ if (entry_scan < scan) {
+ new_entries[slot] = new_entry + scan;
+ new_entry = (entry & ~(uint64_t)new_mask);
+ scan = entry_scan;
+ }
+ scan += 1;
+ slot = (slot + 1) & new_mask;
+ }
+ new_entries[slot] = new_entry + scan;
+ }
+ }
+
+ // And finally free the previous allocation
+ ufbxi_free(map->ator, char, (char*)old_entries, map->data_size);
+ map->items = new_items;
+ map->data_size = data_size;
+ map->entries = new_entries;
+ map->mask = new_mask;
+ map->capacity = (uint32_t)new_size;
+
+ return true;
+}
+
+static ufbxi_forceinline bool ufbxi_map_grow_size(ufbxi_map *map, size_t size, size_t min_size)
+{
+ #if defined(UFBX_REGRESSION)
+ {
+ ufbxi_allocator *ator = map->ator;
+ ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, false, "Allocation limit exceeded");
+ ator->num_allocs++;
+ }
+ #endif
+
+ if (map->size < map->capacity && map->capacity >= min_size) return true;
+ return ufbxi_map_grow_size_imp(map, size, min_size);
+}
+
+static ufbxi_noinline void *ufbxi_map_find_size(ufbxi_map *map, size_t size, uint32_t hash, const void *value)
+{
+ uint64_t *entries = map->entries;
+ uint32_t mask = map->mask, scan = 0;
+
+ uint32_t ref = hash & ~mask;
+ if (!mask || scan == UINT32_MAX) return 0;
+
+ // Scan entries until we find an exact match of the hash or until we hit
+ // an element that has lower scan distance than our search (Robin Hood).
+ // The encoding guarantees that zero slots also terminate with the same test.
+ for (;;) {
+ uint64_t entry = entries[(hash + scan) & mask];
+ scan += 1;
+ if ((uint32_t)entry == ref + scan) {
+ uint32_t index = (uint32_t)(entry >> 32u);
+ void *data = (char*)map->items + size * index;
+ int cmp = map->cmp_fn(map->cmp_user, value, data);
+ if (cmp == 0) return data;
+ } else if ((entry & mask) < scan) {
+ if (map->aa_root) {
+ return ufbxi_aa_tree_find(map, value, size);
+ } else {
+ return NULL;
+ }
+ }
+ }
+}
+
+static ufbxi_noinline void *ufbxi_map_insert_size(ufbxi_map *map, size_t size, uint32_t hash, const void *value)
+{
+ if (!ufbxi_map_grow_size(map, size, 64)) return NULL;
+
+ ufbxi_regression_assert(ufbxi_map_find_size(map, size, hash, value) == NULL);
+
+ uint32_t index = map->size++;
+
+ uint64_t *entries = map->entries;
+ uint32_t mask = map->mask;
+
+ // Scan forward until we find an empty slot, potentially swapping
+ // `new_element` if it has a shorter scan distance (Robin Hood).
+ uint32_t slot = hash & mask;
+ uint64_t entry, new_entry = (uint64_t)index << 32u | (hash & ~mask);
+ uint32_t scan = 1;
+ while ((entry = entries[slot]) != 0) {
+ uint32_t entry_scan = (uint32_t)(entry & mask);
+ if (entry_scan < scan) {
+ entries[slot] = new_entry + scan;
+ new_entry = (entry & ~(uint64_t)mask);
+ scan = entry_scan;
+ }
+ scan += 1;
+ slot = (slot + 1) & mask;
+
+ if (scan > UFBXI_MAP_MAX_SCAN) {
+ uint32_t new_index = (uint32_t)(new_entry >> 32u);
+ const void *new_value = new_index == index ? value : (const void*)((char*)map->items + size * new_index);
+ map->aa_root = ufbxi_aa_tree_insert(map, map->aa_root, new_value, new_index, size);
+ return (char*)map->items + size * index;
+ }
+ }
+ entries[slot] = new_entry + scan;
+
+ return (char*)map->items + size * index;
+}
+
+#define ufbxi_map_grow(map, type, min_size) ufbxi_map_grow_size((map), sizeof(type), (min_size))
+#define ufbxi_map_find(map, type, hash, value) ufbxi_maybe_null((type*)ufbxi_map_find_size((map), sizeof(type), (hash), (value)))
+#define ufbxi_map_insert(map, type, hash, value) ufbxi_maybe_null((type*)ufbxi_map_insert_size((map), sizeof(type), (hash), (value)))
+
+static int ufbxi_map_cmp_uint64(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ uint64_t a = *(const uint64_t*)va, b = *(const uint64_t*)vb;
+ if (a < b) return -1;
+ if (a > b) return +1;
+ return 0;
+}
+
+static int ufbxi_map_cmp_const_char_ptr(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const char *a = *(const char **)va, *b = *(const char **)vb;
+ if (a < b) return -1;
+ if (a > b) return +1;
+ return 0;
+}
+
+static int ufbxi_map_cmp_uintptr(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ uintptr_t a = *(const uintptr_t*)va, b = *(const uintptr_t*)vb;
+ if (a < b) return -1;
+ if (a > b) return +1;
+ return 0;
+}
+
+typedef struct {
+ uintptr_t ptr;
+ uint64_t id;
+} ufbxi_ptr_id;
+
+static int ufbxi_map_cmp_ptr_id(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ ufbxi_ptr_id a = *(const ufbxi_ptr_id*)va, b = *(const ufbxi_ptr_id*)vb;
+ if (a.id != b.id) return a.id < b.id ? -1 : +1;
+ if (a.ptr != b.ptr) return a.ptr < b.ptr ? -1 : +1;
+ return 0;
+}
+
+// -- Hash functions
+
+static ufbxi_noinline uint32_t ufbxi_hash_string(const char *str, size_t length)
+{
+ uint32_t hash = (uint32_t)length;
+ uint32_t seed = UINT32_C(0x9e3779b9);
+ if (length >= 4) {
+ do {
+ uint32_t word = ufbxi_read_u32(str);
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ str += 4;
+ length -= 4;
+ } while (length >= 4);
+
+ uint32_t word = ufbxi_read_u32(str + length - 4);
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ } else {
+ uint32_t word = 0;
+ if (length >= 1) word |= (uint32_t)(uint8_t)str[0] << 0;
+ if (length >= 2) word |= (uint32_t)(uint8_t)str[1] << 8;
+ if (length >= 3) word |= (uint32_t)(uint8_t)str[2] << 16;
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ }
+ hash ^= hash >> 16;
+ hash *= UINT32_C(0x7feb352d);
+ hash ^= hash >> 15;
+ return hash;
+}
+
+// NOTE: _Must_ match `ufbxi_hash_string()`
+static ufbxi_noinline uint32_t ufbxi_hash_string_check_ascii(const char *str, size_t length, bool *p_non_ascii)
+{
+ uint32_t ascii_mask = 0;
+ uint32_t zero_mask = 0;
+
+ ufbx_assert(length > 0);
+
+ uint32_t hash = (uint32_t)length;
+ uint32_t seed = UINT32_C(0x9e3779b9);
+ if (length >= 4) {
+ do {
+ uint32_t word = ufbxi_read_u32(str);
+ ascii_mask |= word;
+ zero_mask |= UINT32_C(0x80808080) - word;
+
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ str += 4;
+ length -= 4;
+ } while (length >= 4);
+
+ uint32_t word = ufbxi_read_u32(str + length - 4);
+ ascii_mask |= word;
+ zero_mask |= UINT32_C(0x80808080) - word;
+
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ } else {
+ uint32_t word = 0;
+ if (length >= 1) word |= (uint32_t)(uint8_t)str[0] << 0;
+ if (length >= 2) word |= (uint32_t)(uint8_t)str[1] << 8;
+ if (length >= 3) word |= (uint32_t)(uint8_t)str[2] << 16;
+
+ ascii_mask |= word;
+ zero_mask |= (UINT32_C(0x80808080) >> ((4u - length) * 8u)) - word;
+
+ hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
+ }
+
+ // If any character has high bit set or is zero we're not ASCII
+ if (((ascii_mask | zero_mask) & 0x80808080u) != 0) {
+ *p_non_ascii = true;
+ }
+
+ hash ^= hash >> 16;
+ hash *= UINT32_C(0x7feb352d);
+ hash ^= hash >> 15;
+
+ return hash;
+}
+
+static ufbxi_unused ufbxi_forceinline uint32_t ufbxi_hash32(uint32_t x)
+{
+ x ^= x >> 16;
+ x *= UINT32_C(0x7feb352d);
+ x ^= x >> 15;
+ x *= UINT32_C(0x846ca68b);
+ x ^= x >> 16;
+ return x;
+}
+
+static ufbxi_unused ufbxi_forceinline uint32_t ufbxi_hash64(uint64_t x)
+{
+ x ^= x >> 32;
+ x *= UINT64_C(0xd6e8feb86659fd93);
+ x ^= x >> 32;
+ x *= UINT64_C(0xd6e8feb86659fd93);
+ x ^= x >> 32;
+ return (uint32_t)x;
+}
+
+static ufbxi_forceinline uint32_t ufbxi_hash_uptr(uintptr_t ptr)
+{
+#if UFBXI_UINTPTR_SIZE == 8
+ return ufbxi_hash64((uint64_t)ptr);
+#elif UFBXI_UINTPTR_SIZE == 4
+ return ufbxi_hash32((uint32_t)ptr);
+#else
+ if (sizeof(ptr) == 8) return ufbxi_hash64((uint64_t)ptr);
+ else if (sizeof(ptr) == 4) return ufbxi_hash32((uint32_t)ptr);
+ else return ufbxi_hash_string((const char*)&ptr, sizeof(uintptr_t));
+#endif
+}
+
+static ufbxi_forceinline uint32_t ufbxi_hash_ptr_id(ufbxi_ptr_id id)
+{
+ // Trivial reduction is fine: Only `ptr` or `id` is defined.
+ return ufbxi_hash_uptr(id.ptr) ^ ufbxi_hash64(id.id);
+}
+
+#define ufbxi_hash_ptr(ptr) ufbxi_hash_uptr((uintptr_t)(ptr))
+
+// -- Warnings
+
+typedef struct {
+ ufbx_error *error;
+ ufbxi_buf *result;
+ ufbxi_buf tmp_stack;
+ uint32_t deferred_element_id_plus_one;
+ // Separate lists for specific and non-specific warnings
+ ufbx_warning *prev_warnings[UFBX_WARNING_TYPE_COUNT][2];
+} ufbxi_warnings;
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_vwarnf_imp(ufbxi_warnings *ws, ufbx_warning_type type, uint32_t element_id, const char *fmt, va_list args)
+{
+ if (!ws) return 1;
+
+ // HACK(warning-element): Encode potential deferred element ID into `ufbx_warning.element_id`,
+ // `ws->element_id_index_plus_one` contains index to `uc->tmp_element_id`.
+ // Tag deferred indices with the high bit.
+ if (element_id == ~0u && ws->deferred_element_id_plus_one > 0) {
+ element_id = (ws->deferred_element_id_plus_one - 1) | 0x80000000u;
+ }
+
+ uint32_t has_element_id = element_id != ~0u;
+ if (type >= UFBX_WARNING_TYPE_FIRST_DEDUPLICATED) {
+ ufbx_warning *prev = ws->prev_warnings[type][has_element_id];
+ if (prev && prev->element_id == element_id) {
+ prev->count++;
+ return 1;
+ }
+ }
+
+ char desc[256];
+ size_t desc_len = (size_t)ufbxi_vsnprintf(desc, sizeof(desc), fmt, args);
+
+ ufbxi_clean_string_utf8(desc, desc_len);
+
+ char *desc_copy = ufbxi_push_copy(ws->result, char, desc_len + 1, desc);
+ ufbxi_check_err(ws->error, desc_copy);
+
+ ufbx_warning *warning = ufbxi_push(&ws->tmp_stack, ufbx_warning, 1);
+ ufbxi_check_err(ws->error, warning);
+
+ warning->type = type;
+ warning->description.data = desc_copy;
+ warning->description.length = desc_len;
+ warning->element_id = element_id;
+ warning->count = 1;
+ ws->prev_warnings[type][has_element_id] = warning;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_warnf_imp(ufbxi_warnings *ws, ufbx_warning_type type, uint32_t element_id, const char *fmt, ...)
+{
+ // NOTE: `ws` may be `NULL` here, handled by `ufbxi_vwarnf()`
+ va_list args; // ufbxi_uninit
+ va_start(args, fmt);
+ int ok = ufbxi_vwarnf_imp(ws, type, element_id, fmt, args);
+ va_end(args);
+ return ok;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_pop_warnings(ufbxi_warnings *ws, ufbx_warning_list *warnings, bool *p_has_warning)
+{
+ warnings->count = ws->tmp_stack.num_items;
+ warnings->data = ufbxi_push_pop(ws->result, &ws->tmp_stack, ufbx_warning, warnings->count);
+ ufbxi_check_err(ws->error, warnings->data);
+ ufbxi_for_list(ufbx_warning, warning, *warnings) {
+ p_has_warning[warning->type] = true;
+ }
+ return 1;
+}
+
+// -- String pool
+
+// All strings found in FBX files are interned for deduplication and fast
+// comparison. Our fixed internal strings (`ufbxi_String`) are considered the
+// canonical pointers for said strings so we can compare them by address.
+
+typedef struct {
+ ufbx_error *error;
+ ufbxi_buf buf; // < Buffer for the actual string data
+ ufbxi_map map; // < Map of `ufbxi_string`
+ size_t initial_size; // < Number of initial entries
+ char *temp_str; // < Temporary string buffer of `temp_cap`
+ size_t temp_cap; // < Capacity of the temporary buffer
+ ufbx_unicode_error_handling error_handling;
+ ufbxi_warnings *warnings;
+} ufbxi_string_pool;
+
+typedef struct {
+ const char *raw_data; // < Original non-sanitized string
+ const char *utf8_data; // < Sanitized UTF-8 string, may alias to `raw_data` or be `NULL`
+ uint32_t raw_length; // < Length of the non-sanitized original string
+ uint32_t utf8_length; // < Length of sanitized UTF-8 string
+} ufbxi_sanitized_string;
+
+static ufbxi_forceinline bool ufbxi_str_equal(ufbx_string a, ufbx_string b)
+{
+ return a.length == b.length && !memcmp(a.data, b.data, a.length);
+}
+
+static ufbxi_forceinline bool ufbxi_str_less(ufbx_string a, ufbx_string b)
+{
+ size_t len = ufbxi_min_sz(a.length, b.length);
+ int cmp = memcmp(a.data, b.data, len);
+ if (cmp != 0) return cmp < 0;
+ return a.length < b.length;
+}
+
+static ufbxi_forceinline int ufbxi_str_cmp(ufbx_string a, ufbx_string b)
+{
+ size_t len = ufbxi_min_sz(a.length, b.length);
+ int cmp = memcmp(a.data, b.data, len);
+ if (cmp != 0) return cmp;
+ if (a.length != b.length) return a.length < b.length ? -1 : 1;
+ return 0;
+}
+
+static ufbxi_forceinline ufbx_string ufbxi_str_c(const char *str)
+{
+ ufbx_string s = { str, strlen(str) };
+ return s;
+}
+
+static ufbxi_noinline uint32_t ufbxi_get_concat_key(const ufbx_string *parts, size_t num_parts)
+{
+ uint32_t key = 0, shift = 32;
+ ufbxi_for(const ufbx_string, part, parts, num_parts) {
+ size_t length = part->length != SIZE_MAX ? part->length : strlen(part->data);
+ for (size_t i = 0; i < length; i++) {
+ shift -= 8;
+ key |= (uint32_t)(uint8_t)part->data[i] << shift;
+ if (shift == 0) return key;
+ }
+ }
+ return key;
+}
+
+static ufbxi_noinline int ufbxi_concat_str_cmp(const ufbx_string *ref, const ufbx_string *parts, size_t num_parts)
+{
+ const char *ptr = ref->data, *end = ptr + ref->length;
+ ufbxi_for(const ufbx_string, part, parts, num_parts) {
+ size_t length = part->length != SIZE_MAX ? part->length : strlen(part->data);
+ size_t to_cmp = ufbxi_min_sz(ufbxi_to_size(end - ptr), length);
+ int cmp = to_cmp > 0 ? memcmp(ptr, part->data, to_cmp) : 0;
+ if (cmp != 0) return cmp;
+ if (to_cmp != length) return -1;
+ ptr += length;
+ }
+ return ptr == end ? 0 : +1;
+}
+
+static ufbxi_forceinline bool ufbxi_starts_with(ufbx_string str, ufbx_string prefix)
+{
+ return str.length >= prefix.length && !memcmp(str.data, prefix.data, prefix.length);
+}
+
+static ufbxi_forceinline bool ufbxi_ends_with(ufbx_string str, ufbx_string suffix)
+{
+ return str.length >= suffix.length && !memcmp(str.data + str.length - suffix.length, suffix.data, suffix.length);
+}
+
+static ufbxi_noinline bool ufbxi_remove_prefix_len(ufbx_string *str, const char *prefix, size_t prefix_len)
+{
+ ufbx_string prefix_str = { prefix, prefix_len };
+ if (ufbxi_starts_with(*str, prefix_str)) {
+ str->data += prefix_len;
+ str->length -= prefix_len;
+ return true;
+ }
+ return false;
+}
+
+static ufbxi_noinline bool ufbxi_remove_suffix_len(ufbx_string *str, const char *suffix, size_t suffix_len)
+{
+ ufbx_string suffix_str = { suffix, suffix_len };
+ if (ufbxi_ends_with(*str, suffix_str)) {
+ str->length -= suffix_len;
+ return true;
+ }
+ return false;
+}
+
+static ufbxi_forceinline bool ufbxi_remove_prefix_str(ufbx_string *str, ufbx_string prefix)
+{
+ return ufbxi_remove_prefix_len(str, prefix.data, prefix.length);
+}
+
+static ufbxi_forceinline bool ufbxi_remove_suffix_c(ufbx_string *str, const char *suffix)
+{
+ return ufbxi_remove_suffix_len(str, suffix, strlen(suffix));
+}
+
+static int ufbxi_map_cmp_string(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_string *a = (const ufbx_string*)va, *b = (const ufbx_string*)vb;
+ return ufbxi_str_cmp(*a, *b);
+}
+
+static ufbxi_forceinline ufbx_string ufbxi_safe_string(const char *data, size_t length)
+{
+ ufbx_string str = { length > 0 ? data : ufbxi_empty_char, length };
+ return str;
+}
+
+static void ufbxi_string_pool_temp_free(ufbxi_string_pool *pool)
+{
+ ufbxi_free(pool->map.ator, char, pool->temp_str, pool->temp_cap);
+ ufbxi_map_free(&pool->map);
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_string_entry(ufbxi_string_pool *pool, const char **p_data, size_t length, uint32_t hash, bool copy)
+{
+ if (length == 0) {
+ *p_data = ufbxi_empty_char;
+ return 1;
+ }
+
+ ufbx_string ref = { *p_data, length };
+ ufbxi_check_err(pool->error, ufbxi_map_grow(&pool->map, ufbx_string, pool->initial_size));
+ ufbx_string *entry = ufbxi_map_find(&pool->map, ufbx_string, hash, &ref);
+ if (!entry) {
+ entry = ufbxi_map_insert(&pool->map, ufbx_string, hash, &ref);
+ ufbxi_check_err(pool->error, entry);
+ entry->length = length;
+ if (copy) {
+ char *dst = ufbxi_push(&pool->buf, char, length + 1);
+ ufbxi_check_err(pool->error, dst);
+ memcpy(dst, ref.data, length);
+ dst[length] = '\0';
+ entry->data = dst;
+ } else {
+ entry->data = ref.data;
+ }
+ }
+
+ *p_data = entry->data;
+ return 1;
+}
+
+ufbxi_nodiscard static size_t ufbxi_add_replacement_char(ufbxi_string_pool *pool, char *dst, char c)
+{
+ switch (pool->error_handling) {
+
+ case UFBX_UNICODE_ERROR_HANDLING_REPLACEMENT_CHARACTER:
+ dst[0] = (char)(uint8_t)0xefu;
+ dst[1] = (char)(uint8_t)0xbfu;
+ dst[2] = (char)(uint8_t)0xbdu;
+ return 3;
+
+ case UFBX_UNICODE_ERROR_HANDLING_UNDERSCORE:
+ dst[0] = '_';
+ return 1;
+
+ case UFBX_UNICODE_ERROR_HANDLING_QUESTION_MARK:
+ dst[0] = '?';
+ return 1;
+
+ case UFBX_UNICODE_ERROR_HANDLING_REMOVE:
+ return 0;
+
+ case UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE:
+ dst[0] = c;
+ return 1;
+
+ default:
+ return 0;
+
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_sanitized_string_entry(ufbxi_string_pool *pool, ufbx_string *sanitized, const char *str, size_t length, size_t valid_length)
+{
+ // Handle only invalid cases here
+ ufbx_assert(valid_length < length);
+ ufbxi_check_err_msg(pool->error, pool->error_handling != UFBX_UNICODE_ERROR_HANDLING_ABORT_LOADING, "Invalid UTF-8");
+ ufbxi_check_err(pool->error, ufbxi_warnf_imp(pool->warnings, UFBX_WARNING_BAD_UNICODE, ~0u, "Bad UTF-8 string"));
+
+ size_t index = valid_length;
+ size_t dst_len = index;
+
+ // Copy the initial valid part
+ ufbxi_check_err(pool->error, length <= SIZE_MAX - 64);
+ ufbxi_check_err(pool->error, ufbxi_grow_array(pool->map.ator, &pool->temp_str, &pool->temp_cap, length + 64));
+ memcpy(pool->temp_str, str, index);
+
+ char *dst = pool->temp_str;
+ while (index < length) {
+ uint8_t c = (uint8_t)str[index];
+ size_t left = length - index;
+
+ // Not optimal but not the worst thing ever
+ if (pool->temp_cap - dst_len < 16) {
+ ufbxi_check_err(pool->error, ufbxi_grow_array(pool->map.ator, &pool->temp_str, &pool->temp_cap, dst_len + 16));
+ dst = pool->temp_str;
+ }
+
+ if ((c & 0x80) == 0) {
+ if (c != 0) {
+ dst[dst_len] = (char)c;
+ dst_len += 1;
+ index += 1;
+ continue;
+ }
+ } else if ((c & 0xe0) == 0xc0 && left >= 2) {
+ uint8_t t0 = (uint8_t)str[index + 1];
+ uint32_t code = (uint32_t)c << 8 | (uint32_t)t0 << 0;
+ if ((code & 0xc0) == 0x80 && code >= 0xc280) {
+ dst[dst_len + 0] = (char)c;
+ dst[dst_len + 1] = (char)t0;
+ dst_len += 2;
+ index += 2;
+ continue;
+ }
+ } else if ((c & 0xf0) == 0xe0 && left >= 3) {
+ uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2];
+ uint32_t code = (uint32_t)c << 16 | (uint32_t)t0 << 8 | (uint32_t)t1;
+ if ((code & 0xc0c0) == 0x8080 && code >= 0xe0a080 && (code < 0xeda080 || code >= 0xee8080)) {
+ dst[dst_len + 0] = (char)c;
+ dst[dst_len + 1] = (char)t0;
+ dst[dst_len + 2] = (char)t1;
+ dst_len += 3;
+ index += 3;
+ continue;
+ }
+ } else if ((c & 0xf8) == 0xf0 && left >= 4) {
+ uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2], t2 = (uint8_t)str[index + 3];
+ uint32_t code = (uint32_t)c << 24 | (uint32_t)t0 << 16 | (uint32_t)t1 << 8 | (uint32_t)t2;
+ if ((code & 0xc0c0c0) == 0x808080 && code >= 0xf0908080u && code <= 0xf48fbfbfu) {
+ dst[dst_len + 0] = (char)c;
+ dst[dst_len + 1] = (char)t0;
+ dst[dst_len + 2] = (char)t1;
+ dst[dst_len + 3] = (char)t2;
+ dst_len += 4;
+ index += 4;
+ continue;
+ }
+ }
+
+ dst_len += ufbxi_add_replacement_char(pool, dst + dst_len, (char)c);
+ index++;
+ }
+
+ sanitized->data = pool->temp_str;
+ sanitized->length = dst_len;
+ uint32_t hash = ufbxi_hash_string(sanitized->data, sanitized->length);
+ ufbxi_check_err(pool->error, ufbxi_push_string_entry(pool, &sanitized->data, sanitized->length, hash, true));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_sanitized_string(ufbxi_string_pool *pool, ufbxi_sanitized_string *sanitized, const char *str, size_t length, uint32_t hash, bool non_ascii, bool raw)
+{
+ ufbxi_regression_assert(hash == ufbxi_hash_string(str, length));
+
+ ufbxi_check_err(pool->error, length <= UINT32_MAX);
+
+ sanitized->raw_data = str;
+ sanitized->raw_length = (uint32_t)length;
+
+ ufbxi_check_err(pool->error, ufbxi_push_string_entry(pool, &sanitized->raw_data, sanitized->raw_length, hash, true));
+
+ if (raw) {
+ sanitized->utf8_data = NULL;
+ sanitized->utf8_length = 0;
+ } else if (!non_ascii) {
+ sanitized->utf8_data = sanitized->raw_data;
+ sanitized->utf8_length = sanitized->raw_length;
+ } else {
+ size_t valid_length = ufbxi_utf8_valid_length(str, length);
+ if (valid_length != length) {
+ ufbx_string utf8;
+ ufbxi_check_err(pool->error, ufbxi_push_sanitized_string_entry(pool, &utf8, str, length, valid_length));
+ ufbxi_check_err(pool->error, utf8.length <= UINT32_MAX);
+ sanitized->utf8_data = utf8.data;
+ sanitized->utf8_length = (uint32_t)utf8.length;
+ } else {
+ sanitized->utf8_data = sanitized->raw_data;
+ sanitized->utf8_length = sanitized->raw_length;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_push_string_imp(ufbxi_string_pool *pool, const char *str, size_t length, size_t *p_out_length, bool copy, bool raw)
+{
+ if (length == 0) return ufbxi_empty_char;
+
+ uint32_t hash;
+ if (raw) {
+ hash = ufbxi_hash_string(str, length);
+ } else {
+ bool non_ascii = false;
+ hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
+ if (non_ascii) {
+ size_t valid_length = ufbxi_utf8_valid_length(str, length);
+ if (valid_length < length) {
+ ufbx_string sanitized;
+ ufbxi_check_return_err(pool->error, ufbxi_push_sanitized_string_entry(pool, &sanitized, str, length, valid_length), NULL);
+ *p_out_length = sanitized.length;
+ return sanitized.data;
+ }
+ }
+ }
+
+ ufbxi_check_return_err(pool->error, ufbxi_push_string_entry(pool, &str, length, hash, copy), NULL);
+ return str;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline const char *ufbxi_push_string(ufbxi_string_pool *pool, const char *str, size_t length, size_t *p_out_length, bool raw)
+{
+ return ufbxi_push_string_imp(pool, str, length, p_out_length, true, raw);
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_push_string_place(ufbxi_string_pool *pool, const char **p_str, size_t *p_length, bool raw)
+{
+ const char *str = *p_str;
+ size_t length = *p_length;
+ ufbxi_check_err(pool->error, str || length == 0);
+ str = ufbxi_push_string(pool, str, length, p_length, raw);
+ ufbxi_check_err(pool->error, str);
+ *p_str = str;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_string_place_str(ufbxi_string_pool *pool, ufbx_string *p_str, bool raw)
+{
+ ufbxi_check_err(pool->error, p_str);
+ return ufbxi_push_string_place(pool, &p_str->data, &p_str->length, raw);
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_string_place_blob(ufbxi_string_pool *pool, ufbx_blob *p_blob, bool raw)
+{
+ if (p_blob->size == 0) {
+ p_blob->data = NULL;
+ return 1;
+ }
+ p_blob->data = ufbxi_push_string(pool, (const char*)p_blob->data, p_blob->size, &p_blob->size, raw);
+ ufbxi_check_err(pool->error, p_blob->data);
+ return 1;
+}
+
+// -- String constants
+//
+// All strings in FBX files are pooled so by having canonical string constant
+// addresses we can compare strings to these constants by comparing pointers.
+// Keep the list alphabetically sorted!
+
+static const char ufbxi_AllSame[] = "AllSame";
+static const char ufbxi_Alphas[] = "Alphas";
+static const char ufbxi_AmbientColor[] = "AmbientColor";
+static const char ufbxi_AnimationCurveNode[] = "AnimationCurveNode";
+static const char ufbxi_AnimationCurve[] = "AnimationCurve";
+static const char ufbxi_AnimationLayer[] = "AnimationLayer";
+static const char ufbxi_AnimationStack[] = "AnimationStack";
+static const char ufbxi_ApertureFormat[] = "ApertureFormat";
+static const char ufbxi_ApertureMode[] = "ApertureMode";
+static const char ufbxi_AreaLightShape[] = "AreaLightShape";
+static const char ufbxi_AspectH[] = "AspectH";
+static const char ufbxi_AspectHeight[] = "AspectHeight";
+static const char ufbxi_AspectRatioMode[] = "AspectRatioMode";
+static const char ufbxi_AspectW[] = "AspectW";
+static const char ufbxi_AspectWidth[] = "AspectWidth";
+static const char ufbxi_Audio[] = "Audio";
+static const char ufbxi_AudioLayer[] = "AudioLayer";
+static const char ufbxi_BaseLayer[] = "BaseLayer";
+static const char ufbxi_BinaryData[] = "BinaryData";
+static const char ufbxi_BindPose[] = "BindPose";
+static const char ufbxi_BindingTable[] = "BindingTable";
+static const char ufbxi_Binormals[] = "Binormals";
+static const char ufbxi_BinormalsIndex[] = "BinormalsIndex";
+static const char ufbxi_BinormalsW[] = "BinormalsW";
+static const char ufbxi_BlendMode[] = "BlendMode";
+static const char ufbxi_BlendModes[] = "BlendModes";
+static const char ufbxi_BlendShapeChannel[] = "BlendShapeChannel";
+static const char ufbxi_BlendShape[] = "BlendShape";
+static const char ufbxi_BlendWeights[] = "BlendWeights";
+static const char ufbxi_BoundaryRule[] = "BoundaryRule";
+static const char ufbxi_Boundary[] = "Boundary";
+static const char ufbxi_ByEdge[] = "ByEdge";
+static const char ufbxi_ByPolygonVertex[] = "ByPolygonVertex";
+static const char ufbxi_ByPolygon[] = "ByPolygon";
+static const char ufbxi_ByVertex[] = "ByVertex";
+static const char ufbxi_ByVertice[] = "ByVertice";
+static const char ufbxi_Cache[] = "Cache";
+static const char ufbxi_CameraProjectionType[] = "CameraProjectionType";
+static const char ufbxi_CameraStereo[] = "CameraStereo";
+static const char ufbxi_CameraSwitcher[] = "CameraSwitcher";
+static const char ufbxi_Camera[] = "Camera";
+static const char ufbxi_CastLight[] = "CastLight";
+static const char ufbxi_CastShadows[] = "CastShadows";
+static const char ufbxi_Channel[] = "Channel";
+static const char ufbxi_Character[] = "Character";
+static const char ufbxi_Children[] = "Children";
+static const char ufbxi_Cluster[] = "Cluster";
+static const char ufbxi_CollectionExclusive[] = "CollectionExclusive";
+static const char ufbxi_Collection[] = "Collection";
+static const char ufbxi_ColorIndex[] = "ColorIndex";
+static const char ufbxi_Color[] = "Color";
+static const char ufbxi_Colors[] = "Colors";
+static const char ufbxi_Cone_angle[] = "Cone angle";
+static const char ufbxi_ConeAngle[] = "ConeAngle";
+static const char ufbxi_Connections[] = "Connections";
+static const char ufbxi_Constraint[] = "Constraint";
+static const char ufbxi_Content[] = "Content";
+static const char ufbxi_CoordAxisSign[] = "CoordAxisSign";
+static const char ufbxi_CoordAxis[] = "CoordAxis";
+static const char ufbxi_Count[] = "Count";
+static const char ufbxi_Creator[] = "Creator";
+static const char ufbxi_CurrentTextureBlendMode[] = "CurrentTextureBlendMode";
+static const char ufbxi_CurrentTimeMarker[] = "CurrentTimeMarker";
+static const char ufbxi_CustomFrameRate[] = "CustomFrameRate";
+static const char ufbxi_DecayType[] = "DecayType";
+static const char ufbxi_DefaultCamera[] = "DefaultCamera";
+static const char ufbxi_Default[] = "Default";
+static const char ufbxi_Definitions[] = "Definitions";
+static const char ufbxi_DeformPercent[] = "DeformPercent";
+static const char ufbxi_Deformer[] = "Deformer";
+static const char ufbxi_DiffuseColor[] = "DiffuseColor";
+static const char ufbxi_Dimension[] = "Dimension";
+static const char ufbxi_Dimensions[] = "Dimensions";
+static const char ufbxi_DisplayLayer[] = "DisplayLayer";
+static const char ufbxi_Document[] = "Document";
+static const char ufbxi_Documents[] = "Documents";
+static const char ufbxi_EdgeCrease[] = "EdgeCrease";
+static const char ufbxi_EdgeIndexArray[] = "EdgeIndexArray";
+static const char ufbxi_Edges[] = "Edges";
+static const char ufbxi_EmissiveColor[] = "EmissiveColor";
+static const char ufbxi_Entry[] = "Entry";
+static const char ufbxi_FBXHeaderExtension[] = "FBXHeaderExtension";
+static const char ufbxi_FBXHeaderVersion[] = "FBXHeaderVersion";
+static const char ufbxi_FBXVersion[] = "FBXVersion";
+static const char ufbxi_FKEffector[] = "FKEffector";
+static const char ufbxi_FarPlane[] = "FarPlane";
+static const char ufbxi_FbxPropertyEntry[] = "FbxPropertyEntry";
+static const char ufbxi_FbxSemanticEntry[] = "FbxSemanticEntry";
+static const char ufbxi_FieldOfViewX[] = "FieldOfViewX";
+static const char ufbxi_FieldOfViewY[] = "FieldOfViewY";
+static const char ufbxi_FieldOfView[] = "FieldOfView";
+static const char ufbxi_FileName[] = "FileName";
+static const char ufbxi_Filename[] = "Filename";
+static const char ufbxi_FilmHeight[] = "FilmHeight";
+static const char ufbxi_FilmSqueezeRatio[] = "FilmSqueezeRatio";
+static const char ufbxi_FilmWidth[] = "FilmWidth";
+static const char ufbxi_FlipNormals[] = "FlipNormals";
+static const char ufbxi_FocalLength[] = "FocalLength";
+static const char ufbxi_Form[] = "Form";
+static const char ufbxi_Freeze[] = "Freeze";
+static const char ufbxi_FrontAxisSign[] = "FrontAxisSign";
+static const char ufbxi_FrontAxis[] = "FrontAxis";
+static const char ufbxi_FullWeights[] = "FullWeights";
+static const char ufbxi_GateFit[] = "GateFit";
+static const char ufbxi_GeometricRotation[] = "GeometricRotation";
+static const char ufbxi_GeometricScaling[] = "GeometricScaling";
+static const char ufbxi_GeometricTranslation[] = "GeometricTranslation";
+static const char ufbxi_GeometryUVInfo[] = "GeometryUVInfo";
+static const char ufbxi_Geometry[] = "Geometry";
+static const char ufbxi_GlobalSettings[] = "GlobalSettings";
+static const char ufbxi_Hole[] = "Hole";
+static const char ufbxi_HotSpot[] = "HotSpot";
+static const char ufbxi_IKEffector[] = "IKEffector";
+static const char ufbxi_ImageData[] = "ImageData";
+static const char ufbxi_Implementation[] = "Implementation";
+static const char ufbxi_Indexes[] = "Indexes";
+static const char ufbxi_InheritType[] = "InheritType";
+static const char ufbxi_InnerAngle[] = "InnerAngle";
+static const char ufbxi_Intensity[] = "Intensity";
+static const char ufbxi_IsTheNodeInSet[] = "IsTheNodeInSet";
+static const char ufbxi_KeyAttrDataFloat[] = "KeyAttrDataFloat";
+static const char ufbxi_KeyAttrFlags[] = "KeyAttrFlags";
+static const char ufbxi_KeyAttrRefCount[] = "KeyAttrRefCount";
+static const char ufbxi_KeyCount[] = "KeyCount";
+static const char ufbxi_KeyTime[] = "KeyTime";
+static const char ufbxi_KeyValueFloat[] = "KeyValueFloat";
+static const char ufbxi_KeyVer[] = "KeyVer";
+static const char ufbxi_Key[] = "Key";
+static const char ufbxi_KnotVectorU[] = "KnotVectorU";
+static const char ufbxi_KnotVectorV[] = "KnotVectorV";
+static const char ufbxi_KnotVector[] = "KnotVector";
+static const char ufbxi_LayerElementBinormal[] = "LayerElementBinormal";
+static const char ufbxi_LayerElementColor[] = "LayerElementColor";
+static const char ufbxi_LayerElementEdgeCrease[] = "LayerElementEdgeCrease";
+static const char ufbxi_LayerElementHole[] = "LayerElementHole";
+static const char ufbxi_LayerElementMaterial[] = "LayerElementMaterial";
+static const char ufbxi_LayerElementNormal[] = "LayerElementNormal";
+static const char ufbxi_LayerElementPolygonGroup[] = "LayerElementPolygonGroup";
+static const char ufbxi_LayerElementSmoothing[] = "LayerElementSmoothing";
+static const char ufbxi_LayerElementTangent[] = "LayerElementTangent";
+static const char ufbxi_LayerElementUV[] = "LayerElementUV";
+static const char ufbxi_LayerElementVertexCrease[] = "LayerElementVertexCrease";
+static const char ufbxi_LayerElementVisibility[] = "LayerElementVisibility";
+static const char ufbxi_LayerElement[] = "LayerElement";
+static const char ufbxi_Layer[] = "Layer";
+static const char ufbxi_LayeredTexture[] = "LayeredTexture";
+static const char ufbxi_Lcl_Rotation[] = "Lcl Rotation";
+static const char ufbxi_Lcl_Scaling[] = "Lcl Scaling";
+static const char ufbxi_Lcl_Translation[] = "Lcl Translation";
+static const char ufbxi_LeftCamera[] = "LeftCamera";
+static const char ufbxi_LightType[] = "LightType";
+static const char ufbxi_Light[] = "Light";
+static const char ufbxi_LimbLength[] = "LimbLength";
+static const char ufbxi_LimbNode[] = "LimbNode";
+static const char ufbxi_Limb[] = "Limb";
+static const char ufbxi_Line[] = "Line";
+static const char ufbxi_Link[] = "Link";
+static const char ufbxi_LocalStart[] = "LocalStart";
+static const char ufbxi_LocalStop[] = "LocalStop";
+static const char ufbxi_LocalTime[] = "LocalTime";
+static const char ufbxi_LodGroup[] = "LodGroup";
+static const char ufbxi_MappingInformationType[] = "MappingInformationType";
+static const char ufbxi_Marker[] = "Marker";
+static const char ufbxi_MaterialAssignation[] = "MaterialAssignation";
+static const char ufbxi_Material[] = "Material";
+static const char ufbxi_Materials[] = "Materials";
+static const char ufbxi_Matrix[] = "Matrix";
+static const char ufbxi_Media[] = "Media";
+static const char ufbxi_Mesh[] = "Mesh";
+static const char ufbxi_Model[] = "Model";
+static const char ufbxi_Name[] = "Name";
+static const char ufbxi_NearPlane[] = "NearPlane";
+static const char ufbxi_NodeAttributeName[] = "NodeAttributeName";
+static const char ufbxi_NodeAttribute[] = "NodeAttribute";
+static const char ufbxi_Node[] = "Node";
+static const char ufbxi_Normals[] = "Normals";
+static const char ufbxi_NormalsIndex[] = "NormalsIndex";
+static const char ufbxi_NormalsW[] = "NormalsW";
+static const char ufbxi_Null[] = "Null";
+static const char ufbxi_NurbsCurve[] = "NurbsCurve";
+static const char ufbxi_NurbsSurfaceOrder[] = "NurbsSurfaceOrder";
+static const char ufbxi_NurbsSurface[] = "NurbsSurface";
+static const char ufbxi_Nurbs[] = "Nurbs";
+static const char ufbxi_OO[] = "OO\0";
+static const char ufbxi_OP[] = "OP\0";
+static const char ufbxi_ObjectMetaData[] = "ObjectMetaData";
+static const char ufbxi_ObjectType[] = "ObjectType";
+static const char ufbxi_Objects[] = "Objects";
+static const char ufbxi_Order[] = "Order";
+static const char ufbxi_OriginalUnitScaleFactor[] = "OriginalUnitScaleFactor";
+static const char ufbxi_OriginalUpAxis[] = "OriginalUpAxis";
+static const char ufbxi_OriginalUpAxisSign[] = "OriginalUpAxisSign";
+static const char ufbxi_OrthoZoom[] = "OrthoZoom";
+static const char ufbxi_OtherFlags[] = "OtherFlags";
+static const char ufbxi_OuterAngle[] = "OuterAngle";
+static const char ufbxi_PO[] = "PO\0";
+static const char ufbxi_PP[] = "PP\0";
+static const char ufbxi_PointsIndex[] = "PointsIndex";
+static const char ufbxi_Points[] = "Points";
+static const char ufbxi_PolygonGroup[] = "PolygonGroup";
+static const char ufbxi_PolygonIndexArray[] = "PolygonIndexArray";
+static const char ufbxi_PolygonVertexIndex[] = "PolygonVertexIndex";
+static const char ufbxi_PoseNode[] = "PoseNode";
+static const char ufbxi_Pose[] = "Pose";
+static const char ufbxi_Post_Extrapolation[] = "Post-Extrapolation";
+static const char ufbxi_PostRotation[] = "PostRotation";
+static const char ufbxi_Pre_Extrapolation[] = "Pre-Extrapolation";
+static const char ufbxi_PreRotation[] = "PreRotation";
+static const char ufbxi_PreviewDivisionLevels[] = "PreviewDivisionLevels";
+static const char ufbxi_Properties60[] = "Properties60";
+static const char ufbxi_Properties70[] = "Properties70";
+static const char ufbxi_PropertyTemplate[] = "PropertyTemplate";
+static const char ufbxi_R[] = "R\0\0";
+static const char ufbxi_ReferenceStart[] = "ReferenceStart";
+static const char ufbxi_ReferenceStop[] = "ReferenceStop";
+static const char ufbxi_ReferenceTime[] = "ReferenceTime";
+static const char ufbxi_RelativeFileName[] = "RelativeFileName";
+static const char ufbxi_RelativeFilename[] = "RelativeFilename";
+static const char ufbxi_RenderDivisionLevels[] = "RenderDivisionLevels";
+static const char ufbxi_Repetition[] = "Repetition";
+static const char ufbxi_RightCamera[] = "RightCamera";
+static const char ufbxi_RootNode[] = "RootNode";
+static const char ufbxi_Root[] = "Root";
+static const char ufbxi_RotationAccumulationMode[] = "RotationAccumulationMode";
+static const char ufbxi_RotationActive[] = "RotationActive";
+static const char ufbxi_RotationOffset[] = "RotationOffset";
+static const char ufbxi_RotationOrder[] = "RotationOrder";
+static const char ufbxi_RotationPivot[] = "RotationPivot";
+static const char ufbxi_RotationSpaceForLimitOnly[] = "RotationSpaceForLimitOnly";
+static const char ufbxi_Rotation[] = "Rotation";
+static const char ufbxi_S[] = "S\0\0";
+static const char ufbxi_ScaleAccumulationMode[] = "ScaleAccumulationMode";
+static const char ufbxi_ScalingOffset[] = "ScalingOffset";
+static const char ufbxi_ScalingPivot[] = "ScalingPivot";
+static const char ufbxi_Scaling[] = "Scaling";
+static const char ufbxi_SceneInfo[] = "SceneInfo";
+static const char ufbxi_SelectionNode[] = "SelectionNode";
+static const char ufbxi_SelectionSet[] = "SelectionSet";
+static const char ufbxi_ShadingModel[] = "ShadingModel";
+static const char ufbxi_Shape[] = "Shape";
+static const char ufbxi_Shininess[] = "Shininess";
+static const char ufbxi_Show[] = "Show";
+static const char ufbxi_Size[] = "Size";
+static const char ufbxi_Skin[] = "Skin";
+static const char ufbxi_SkinningType[] = "SkinningType";
+static const char ufbxi_Smoothing[] = "Smoothing";
+static const char ufbxi_Smoothness[] = "Smoothness";
+static const char ufbxi_SnapOnFrameMode[] = "SnapOnFrameMode";
+static const char ufbxi_SpecularColor[] = "SpecularColor";
+static const char ufbxi_Step[] = "Step";
+static const char ufbxi_SubDeformer[] = "SubDeformer";
+static const char ufbxi_T[] = "T\0\0";
+static const char ufbxi_TCDefinition[] = "TCDefinition";
+static const char ufbxi_Take[] = "Take";
+static const char ufbxi_Takes[] = "Takes";
+static const char ufbxi_Tangents[] = "Tangents";
+static const char ufbxi_TangentsIndex[] = "TangentsIndex";
+static const char ufbxi_TangentsW[] = "TangentsW";
+static const char ufbxi_Texture[] = "Texture";
+static const char ufbxi_Texture_alpha[] = "Texture alpha";
+static const char ufbxi_TextureId[] = "TextureId";
+static const char ufbxi_TextureRotationPivot[] = "TextureRotationPivot";
+static const char ufbxi_TextureScalingPivot[] = "TextureScalingPivot";
+static const char ufbxi_TextureUV[] = "TextureUV";
+static const char ufbxi_TextureUVVerticeIndex[] = "TextureUVVerticeIndex";
+static const char ufbxi_Thumbnail[] = "Thumbnail";
+static const char ufbxi_TimeMarker[] = "TimeMarker";
+static const char ufbxi_TimeMode[] = "TimeMode";
+static const char ufbxi_TimeProtocol[] = "TimeProtocol";
+static const char ufbxi_TimeSpanStart[] = "TimeSpanStart";
+static const char ufbxi_TimeSpanStop[] = "TimeSpanStop";
+static const char ufbxi_TransformLink[] = "TransformLink";
+static const char ufbxi_Transform[] = "Transform";
+static const char ufbxi_Translation[] = "Translation";
+static const char ufbxi_TrimNurbsSurface[] = "TrimNurbsSurface";
+static const char ufbxi_Type[] = "Type";
+static const char ufbxi_TypedIndex[] = "TypedIndex";
+static const char ufbxi_UVIndex[] = "UVIndex";
+static const char ufbxi_UVSet[] = "UVSet";
+static const char ufbxi_UVSwap[] = "UVSwap";
+static const char ufbxi_UV[] = "UV\0";
+static const char ufbxi_UnitScaleFactor[] = "UnitScaleFactor";
+static const char ufbxi_UpAxisSign[] = "UpAxisSign";
+static const char ufbxi_UpAxis[] = "UpAxis";
+static const char ufbxi_Version5[] = "Version5";
+static const char ufbxi_VertexCacheDeformer[] = "VertexCacheDeformer";
+static const char ufbxi_VertexCrease[] = "VertexCrease";
+static const char ufbxi_VertexCreaseIndex[] = "VertexCreaseIndex";
+static const char ufbxi_VertexIndexArray[] = "VertexIndexArray";
+static const char ufbxi_Vertices[] = "Vertices";
+static const char ufbxi_Video[] = "Video";
+static const char ufbxi_Visibility[] = "Visibility";
+static const char ufbxi_Weight[] = "Weight";
+static const char ufbxi_Weights[] = "Weights";
+static const char ufbxi_WrapModeU[] = "WrapModeU";
+static const char ufbxi_WrapModeV[] = "WrapModeV";
+static const char ufbxi_X[] = "X\0\0";
+static const char ufbxi_Y[] = "Y\0\0";
+static const char ufbxi_Z[] = "Z\0\0";
+static const char ufbxi_d_X[] = "d|X";
+static const char ufbxi_d_Y[] = "d|Y";
+static const char ufbxi_d_Z[] = "d|Z";
+
+static const ufbx_string ufbxi_strings[] = {
+ { ufbxi_AllSame, 7 },
+ { ufbxi_Alphas, 6 },
+ { ufbxi_AmbientColor, 12 },
+ { ufbxi_AnimationCurve, 14 },
+ { ufbxi_AnimationCurveNode, 18 },
+ { ufbxi_AnimationLayer, 14 },
+ { ufbxi_AnimationStack, 14 },
+ { ufbxi_ApertureFormat, 14 },
+ { ufbxi_ApertureMode, 12 },
+ { ufbxi_AreaLightShape, 14 },
+ { ufbxi_AspectH, 7 },
+ { ufbxi_AspectHeight, 12 },
+ { ufbxi_AspectRatioMode, 15 },
+ { ufbxi_AspectW, 7 },
+ { ufbxi_AspectWidth, 11 },
+ { ufbxi_Audio, 5 },
+ { ufbxi_AudioLayer, 10 },
+ { ufbxi_BaseLayer, 9 },
+ { ufbxi_BinaryData, 10 },
+ { ufbxi_BindPose, 8 },
+ { ufbxi_BindingTable, 12 },
+ { ufbxi_Binormals, 9 },
+ { ufbxi_BinormalsIndex, 14 },
+ { ufbxi_BinormalsW, 10 },
+ { ufbxi_BlendMode, 9 },
+ { ufbxi_BlendModes, 10 },
+ { ufbxi_BlendShape, 10 },
+ { ufbxi_BlendShapeChannel, 17 },
+ { ufbxi_BlendWeights, 12 },
+ { ufbxi_Boundary, 8 },
+ { ufbxi_BoundaryRule, 12 },
+ { ufbxi_ByEdge, 6 },
+ { ufbxi_ByPolygon, 9 },
+ { ufbxi_ByPolygonVertex, 15 },
+ { ufbxi_ByVertex, 8 },
+ { ufbxi_ByVertice, 9 },
+ { ufbxi_Cache, 5 },
+ { ufbxi_Camera, 6 },
+ { ufbxi_CameraProjectionType, 20 },
+ { ufbxi_CameraStereo, 12 },
+ { ufbxi_CameraSwitcher, 14 },
+ { ufbxi_CastLight, 9 },
+ { ufbxi_CastShadows, 11 },
+ { ufbxi_Channel, 7 },
+ { ufbxi_Character, sizeof(ufbxi_Character) - 1 },
+ { ufbxi_Children, 8 },
+ { ufbxi_Cluster, 7 },
+ { ufbxi_Collection, 10 },
+ { ufbxi_CollectionExclusive, 19 },
+ { ufbxi_Color, 5 },
+ { ufbxi_ColorIndex, 10 },
+ { ufbxi_Colors, 6 },
+ { ufbxi_Cone_angle, 10 },
+ { ufbxi_ConeAngle, 9 },
+ { ufbxi_Connections, 11 },
+ { ufbxi_Constraint, sizeof(ufbxi_Constraint) - 1 },
+ { ufbxi_Content, 7 },
+ { ufbxi_CoordAxis, 9 },
+ { ufbxi_CoordAxisSign, 13 },
+ { ufbxi_Count, 5 },
+ { ufbxi_Creator, 7 },
+ { ufbxi_CurrentTextureBlendMode, 23 },
+ { ufbxi_CurrentTimeMarker, 17 },
+ { ufbxi_CustomFrameRate, 15 },
+ { ufbxi_DecayType, 9 },
+ { ufbxi_Default, 7 },
+ { ufbxi_DefaultCamera, 13 },
+ { ufbxi_Definitions, 11 },
+ { ufbxi_DeformPercent, 13 },
+ { ufbxi_Deformer, 8 },
+ { ufbxi_DiffuseColor, 12 },
+ { ufbxi_Dimension, 9 },
+ { ufbxi_Dimensions, 10 },
+ { ufbxi_DisplayLayer, 12 },
+ { ufbxi_Document, 8 },
+ { ufbxi_Documents, 9 },
+ { ufbxi_EdgeCrease, 10 },
+ { ufbxi_EdgeIndexArray, 14 },
+ { ufbxi_Edges, 5 },
+ { ufbxi_EmissiveColor, 13 },
+ { ufbxi_Entry, 5 },
+ { ufbxi_FBXHeaderExtension, 18 },
+ { ufbxi_FBXHeaderVersion, 16 },
+ { ufbxi_FBXVersion, 10 },
+ { ufbxi_FKEffector, 10 },
+ { ufbxi_FarPlane, 8 },
+ { ufbxi_FbxPropertyEntry, 16 },
+ { ufbxi_FbxSemanticEntry, 16 },
+ { ufbxi_FieldOfView, 11 },
+ { ufbxi_FieldOfViewX, 12 },
+ { ufbxi_FieldOfViewY, 12 },
+ { ufbxi_FileName, 8 },
+ { ufbxi_Filename, 8 },
+ { ufbxi_FilmHeight, 10 },
+ { ufbxi_FilmSqueezeRatio, 16 },
+ { ufbxi_FilmWidth, 9 },
+ { ufbxi_FlipNormals, 11 },
+ { ufbxi_FocalLength, 11 },
+ { ufbxi_Form, 4 },
+ { ufbxi_Freeze, 6 },
+ { ufbxi_FrontAxis, 9 },
+ { ufbxi_FrontAxisSign, 13 },
+ { ufbxi_FullWeights, 11 },
+ { ufbxi_GateFit, 7 },
+ { ufbxi_GeometricRotation, 17 },
+ { ufbxi_GeometricScaling, 16 },
+ { ufbxi_GeometricTranslation, 20 },
+ { ufbxi_Geometry, 8 },
+ { ufbxi_GeometryUVInfo, 14 },
+ { ufbxi_GlobalSettings, 14 },
+ { ufbxi_Hole, 4 },
+ { ufbxi_HotSpot, 7 },
+ { ufbxi_IKEffector, 10 },
+ { ufbxi_ImageData, 9 },
+ { ufbxi_Implementation, 14 },
+ { ufbxi_Indexes, 7 },
+ { ufbxi_InheritType, 11 },
+ { ufbxi_InnerAngle, 10 },
+ { ufbxi_Intensity, 9 },
+ { ufbxi_IsTheNodeInSet, 14 },
+ { ufbxi_Key, 3 },
+ { ufbxi_KeyAttrDataFloat, 16 },
+ { ufbxi_KeyAttrFlags, 12 },
+ { ufbxi_KeyAttrRefCount, 15 },
+ { ufbxi_KeyCount, 8 },
+ { ufbxi_KeyTime, 7 },
+ { ufbxi_KeyValueFloat, 13 },
+ { ufbxi_KeyVer, 6 },
+ { ufbxi_KnotVector, 10 },
+ { ufbxi_KnotVectorU, 11 },
+ { ufbxi_KnotVectorV, 11 },
+ { ufbxi_Layer, 5 },
+ { ufbxi_LayerElement, 12 },
+ { ufbxi_LayerElementBinormal, 20 },
+ { ufbxi_LayerElementColor, 17 },
+ { ufbxi_LayerElementEdgeCrease, 22 },
+ { ufbxi_LayerElementHole, 16 },
+ { ufbxi_LayerElementMaterial, 20 },
+ { ufbxi_LayerElementNormal, 18 },
+ { ufbxi_LayerElementPolygonGroup, 24 },
+ { ufbxi_LayerElementSmoothing, 21 },
+ { ufbxi_LayerElementTangent, 19 },
+ { ufbxi_LayerElementUV, 14 },
+ { ufbxi_LayerElementVertexCrease, 24 },
+ { ufbxi_LayerElementVisibility, 22 },
+ { ufbxi_LayeredTexture, 14 },
+ { ufbxi_Lcl_Rotation, 12 },
+ { ufbxi_Lcl_Scaling, 11 },
+ { ufbxi_Lcl_Translation, 15 },
+ { ufbxi_LeftCamera, 10 },
+ { ufbxi_Light, 5 },
+ { ufbxi_LightType, 9 },
+ { ufbxi_Limb, 4 },
+ { ufbxi_LimbLength, 10 },
+ { ufbxi_LimbNode, 8 },
+ { ufbxi_Line, 4 },
+ { ufbxi_Link, 4 },
+ { ufbxi_LocalStart, 10 },
+ { ufbxi_LocalStop, 9 },
+ { ufbxi_LocalTime, 9 },
+ { ufbxi_LodGroup, 8 },
+ { ufbxi_MappingInformationType, 22 },
+ { ufbxi_Marker, 6 },
+ { ufbxi_Material, 8 },
+ { ufbxi_MaterialAssignation, 19 },
+ { ufbxi_Materials, 9 },
+ { ufbxi_Matrix, 6 },
+ { ufbxi_Media, 5 },
+ { ufbxi_Mesh, 4 },
+ { ufbxi_Model, 5 },
+ { ufbxi_Name, 4 },
+ { ufbxi_NearPlane, 9 },
+ { ufbxi_Node, 4 },
+ { ufbxi_NodeAttribute, 13 },
+ { ufbxi_NodeAttributeName, 17 },
+ { ufbxi_Normals, 7 },
+ { ufbxi_NormalsIndex, 12 },
+ { ufbxi_NormalsW, 8 },
+ { ufbxi_Null, 4 },
+ { ufbxi_Nurbs, 5 },
+ { ufbxi_NurbsCurve, 10 },
+ { ufbxi_NurbsSurface, 12 },
+ { ufbxi_NurbsSurfaceOrder, 17 },
+ { ufbxi_OO, 2 },
+ { ufbxi_OP, 2 },
+ { ufbxi_ObjectMetaData, 14 },
+ { ufbxi_ObjectType, 10 },
+ { ufbxi_Objects, 7 },
+ { ufbxi_Order, 5 },
+ { ufbxi_OriginalUnitScaleFactor, 23 },
+ { ufbxi_OriginalUpAxis, 14 },
+ { ufbxi_OriginalUpAxisSign, 18 },
+ { ufbxi_OrthoZoom, 9 },
+ { ufbxi_OtherFlags, 10 },
+ { ufbxi_OuterAngle, 10 },
+ { ufbxi_PO, 2 },
+ { ufbxi_PP, 2 },
+ { ufbxi_Points, 6 },
+ { ufbxi_PointsIndex, 11 },
+ { ufbxi_PolygonGroup, 12 },
+ { ufbxi_PolygonIndexArray, 17 },
+ { ufbxi_PolygonVertexIndex, 18 },
+ { ufbxi_Pose, 4 },
+ { ufbxi_PoseNode, 8 },
+ { ufbxi_Post_Extrapolation, 18 },
+ { ufbxi_PostRotation, 12 },
+ { ufbxi_Pre_Extrapolation, 17 },
+ { ufbxi_PreRotation, 11 },
+ { ufbxi_PreviewDivisionLevels, 21 },
+ { ufbxi_Properties60, 12 },
+ { ufbxi_Properties70, 12 },
+ { ufbxi_PropertyTemplate, 16 },
+ { ufbxi_R, 1 },
+ { ufbxi_ReferenceStart, 14 },
+ { ufbxi_ReferenceStop, 13 },
+ { ufbxi_ReferenceTime, 13 },
+ { ufbxi_RelativeFileName, 16 },
+ { ufbxi_RelativeFilename, 16 },
+ { ufbxi_RenderDivisionLevels, 20 },
+ { ufbxi_Repetition, 10 },
+ { ufbxi_RightCamera, 11 },
+ { ufbxi_Root, 4 },
+ { ufbxi_RootNode, 8 },
+ { ufbxi_Rotation, 8 },
+ { ufbxi_RotationAccumulationMode, 24 },
+ { ufbxi_RotationActive, 14 },
+ { ufbxi_RotationOffset, 14 },
+ { ufbxi_RotationOrder, 13 },
+ { ufbxi_RotationPivot, 13 },
+ { ufbxi_RotationSpaceForLimitOnly, 25 },
+ { ufbxi_S, 1 },
+ { ufbxi_ScaleAccumulationMode, 21 },
+ { ufbxi_Scaling, 7 },
+ { ufbxi_ScalingOffset, 13 },
+ { ufbxi_ScalingPivot, 12 },
+ { ufbxi_SceneInfo, 9 },
+ { ufbxi_SelectionNode, 13 },
+ { ufbxi_SelectionSet, 12 },
+ { ufbxi_ShadingModel, 12 },
+ { ufbxi_Shape, 5 },
+ { ufbxi_Shininess, 9 },
+ { ufbxi_Show, 4 },
+ { ufbxi_Size, 4 },
+ { ufbxi_Skin, 4 },
+ { ufbxi_SkinningType, 12 },
+ { ufbxi_Smoothing, 9 },
+ { ufbxi_Smoothness, 10 },
+ { ufbxi_SnapOnFrameMode, 15 },
+ { ufbxi_SpecularColor, 13 },
+ { ufbxi_Step, 4 },
+ { ufbxi_SubDeformer, 11 },
+ { ufbxi_T, 1 },
+ { ufbxi_TCDefinition, 12 },
+ { ufbxi_Take, 4 },
+ { ufbxi_Takes, 5 },
+ { ufbxi_Tangents, 8 },
+ { ufbxi_TangentsIndex, 13 },
+ { ufbxi_TangentsW, 9 },
+ { ufbxi_Texture, 7 },
+ { ufbxi_Texture_alpha, 13 },
+ { ufbxi_TextureId, 9 },
+ { ufbxi_TextureRotationPivot, 20 },
+ { ufbxi_TextureScalingPivot, 19 },
+ { ufbxi_TextureUV, 9 },
+ { ufbxi_TextureUVVerticeIndex, 21 },
+ { ufbxi_Thumbnail, 9 },
+ { ufbxi_TimeMarker, 10 },
+ { ufbxi_TimeMode, 8 },
+ { ufbxi_TimeProtocol, 12 },
+ { ufbxi_TimeSpanStart, 13 },
+ { ufbxi_TimeSpanStop, 12 },
+ { ufbxi_Transform, 9 },
+ { ufbxi_TransformLink, 13 },
+ { ufbxi_Translation, 11 },
+ { ufbxi_TrimNurbsSurface, 16 },
+ { ufbxi_Type, 4 },
+ { ufbxi_TypedIndex, 10 },
+ { ufbxi_UV, 2 },
+ { ufbxi_UVIndex, 7 },
+ { ufbxi_UVSet, 5 },
+ { ufbxi_UVSwap, 6 },
+ { ufbxi_UnitScaleFactor, 15 },
+ { ufbxi_UpAxis, 6 },
+ { ufbxi_UpAxisSign, 10 },
+ { ufbxi_Version5, 8 },
+ { ufbxi_VertexCacheDeformer, 19 },
+ { ufbxi_VertexCrease, 12 },
+ { ufbxi_VertexCreaseIndex, 17 },
+ { ufbxi_VertexIndexArray, 16 },
+ { ufbxi_Vertices, 8 },
+ { ufbxi_Video, 5 },
+ { ufbxi_Visibility, 10 },
+ { ufbxi_Weight, 6 },
+ { ufbxi_Weights, 7 },
+ { ufbxi_WrapModeU, 9 },
+ { ufbxi_WrapModeV, 9 },
+ { ufbxi_X, 1 },
+ { ufbxi_Y, 1 },
+ { ufbxi_Z, 1 },
+ { ufbxi_d_X, 3 },
+ { ufbxi_d_Y, 3 },
+ { ufbxi_d_Z, 3 },
+};
+
+static const ufbx_vec3 ufbxi_one_vec3 = { 1.0f, 1.0f, 1.0f };
+
+#define UFBXI_PI ((ufbx_real)3.14159265358979323846)
+#define UFBXI_DPI (3.14159265358979323846)
+#define UFBXI_DEG_TO_RAD ((ufbx_real)(UFBXI_PI / 180.0))
+#define UFBXI_RAD_TO_DEG ((ufbx_real)(180.0 / UFBXI_PI))
+#define UFBXI_DEG_TO_RAD_DOUBLE (UFBXI_DPI / 180.0)
+#define UFBXI_RAD_TO_DEG_DOUBLE (180.0 / UFBXI_DPI)
+#define UFBXI_MM_TO_INCH ((ufbx_real)0.0393700787)
+
+ufbx_inline ufbx_vec3 ufbxi_add3(ufbx_vec3 a, ufbx_vec3 b) {
+ ufbx_vec3 v = { a.x + b.x, a.y + b.y, a.z + b.z };
+ return v;
+}
+
+ufbx_inline ufbx_vec3 ufbxi_sub3(ufbx_vec3 a, ufbx_vec3 b) {
+ ufbx_vec3 v = { a.x - b.x, a.y - b.y, a.z - b.z };
+ return v;
+}
+
+ufbx_inline ufbx_vec3 ufbxi_mul3(ufbx_vec3 a, ufbx_real b) {
+ ufbx_vec3 v = { a.x * b, a.y * b, a.z * b };
+ return v;
+}
+
+ufbx_inline ufbx_vec3 ufbxi_lerp3(ufbx_vec3 a, ufbx_vec3 b, ufbx_real t) {
+ ufbx_real u = 1.0f - t;
+ ufbx_vec3 v = { a.x*u + b.x*t, a.y*u + b.y*t, a.z*u + b.z*t };
+ return v;
+}
+
+ufbx_inline ufbx_real ufbxi_dot3(ufbx_vec3 a, ufbx_vec3 b) {
+ return a.x*b.x + a.y*b.y + a.z*b.z;
+}
+
+ufbx_inline ufbx_real ufbxi_length3(ufbx_vec3 v)
+{
+ return (ufbx_real)ufbx_sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
+}
+
+ufbx_inline ufbx_real ufbxi_min3(ufbx_vec3 v)
+{
+ return ufbxi_min_real(ufbxi_min_real(v.x, v.y), v.z);
+}
+
+ufbx_inline ufbx_vec3 ufbxi_cross3(ufbx_vec3 a, ufbx_vec3 b) {
+ ufbx_vec3 v = { a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x };
+ return v;
+}
+
+ufbx_inline ufbx_vec3 ufbxi_normalize3(ufbx_vec3 a) {
+ ufbx_real len = (ufbx_real)ufbx_sqrt(ufbxi_dot3(a, a));
+ if (len > UFBX_EPSILON) {
+ return ufbxi_mul3(a, (ufbx_real)1.0 / len);
+ } else {
+ ufbx_vec3 zero = { (ufbx_real)0 };
+ return zero;
+ }
+}
+
+ufbx_inline ufbx_vec3 ufbxi_neg3(ufbx_vec3 a) {
+ ufbx_vec3 v = { -a.x, -a.y, -a.z };
+ return v;
+}
+
+ufbx_inline ufbx_real ufbxi_distsq2(ufbx_vec2 a, ufbx_vec2 b) {
+ ufbx_real dx = a.x - b.x, dy = a.y - b.y;
+ return dx*dx + dy*dy;
+}
+
+static ufbxi_noinline ufbx_vec3 ufbxi_slow_normalize3(const ufbx_vec3 *a) {
+ return ufbxi_normalize3(*a);
+}
+
+static ufbxi_noinline ufbx_vec3 ufbxi_slow_normalized_cross3(const ufbx_vec3 *a, const ufbx_vec3 *b) {
+ return ufbxi_normalize3(ufbxi_cross3(*a, *b));
+}
+
+// -- Threading
+
+typedef struct ufbxi_task ufbxi_task;
+typedef struct ufbxi_thread_pool ufbxi_thread_pool;
+
+typedef bool ufbxi_task_fn(ufbxi_task *task);
+
+struct ufbxi_task {
+ void *data;
+ const char *error;
+};
+
+typedef struct {
+ ufbxi_task task;
+ ufbxi_task_fn *fn;
+} ufbxi_task_imp;
+
+typedef struct {
+ uint32_t max_index;
+ uint32_t wait_index;
+} ufbxi_task_group;
+
+struct ufbxi_thread_pool {
+ ufbx_thread_opts opts;
+ ufbxi_allocator *ator;
+ ufbx_error *error;
+ void *user_ptr;
+
+ bool enabled;
+ bool failed;
+ const char *error_desc;
+
+ uint32_t start_index;
+ uint32_t execute_index;
+ uint32_t wait_index;
+
+ ufbxi_task_group groups[UFBX_THREAD_GROUP_COUNT];
+ uint32_t group;
+
+ uint32_t num_tasks;
+ ufbxi_task_imp *tasks;
+};
+
+static void ufbxi_thread_pool_execute(ufbxi_thread_pool *pool, uint32_t index)
+{
+ ufbxi_task_imp *imp = &pool->tasks[index % pool->num_tasks];
+ if (imp->fn(&imp->task)) {
+ imp->task.error = NULL;
+ } else if (!imp->task.error) {
+ imp->task.error = "";
+ }
+}
+
+ufbxi_noinline static void ufbxi_thread_pool_update_finished(ufbxi_thread_pool *pool, uint32_t max_index)
+{
+ while (pool->wait_index < max_index) {
+ ufbxi_task_imp *task = &pool->tasks[pool->wait_index % pool->num_tasks];
+ if (!pool->failed && task->task.error) {
+ pool->failed = true;
+ pool->error_desc = task->task.error;
+ }
+ pool->wait_index += 1;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_imp(ufbxi_thread_pool *pool, uint32_t group, bool can_fail)
+{
+ uint32_t max_index = pool->groups[group].max_index;
+
+ if (pool->groups[group].wait_index < max_index) {
+ pool->opts.pool.wait_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, group, max_index);
+ pool->groups[group].wait_index = max_index;
+ }
+ ufbxi_thread_pool_update_finished(pool, max_index);
+
+ if (pool->failed && can_fail) {
+ ufbx_error *error = pool->error;
+ if (pool->error_desc) {
+ error->description.data = pool->error_desc;
+ error->description.length = strlen(pool->error_desc);
+ }
+ ufbxi_fail_err(error, "Task failed");
+ }
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_group(ufbxi_thread_pool *pool)
+{
+ ufbxi_check_err(pool->error, ufbxi_thread_pool_wait_imp(pool, pool->group, true));
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_all(ufbxi_thread_pool *pool)
+{
+ for (uint32_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
+ ufbxi_check_err(pool->error, ufbxi_thread_pool_wait_imp(pool, pool->group, true));
+ pool->group = (pool->group + 1) % UFBX_THREAD_GROUP_COUNT;
+ }
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_init(ufbxi_thread_pool *pool, ufbx_error *error, ufbxi_allocator *ator, const ufbx_thread_opts *opts)
+{
+ if (!(opts->pool.run_fn && opts->pool.wait_fn)) return 1;
+ pool->enabled = true;
+
+ uint32_t num_tasks = (uint32_t)ufbxi_min_sz(opts->num_tasks, INT32_MAX);
+ if (num_tasks == 0) {
+ num_tasks = 2048;
+ }
+
+ pool->opts = *opts;
+ if (pool->opts.pool.init_fn) {
+ ufbx_thread_pool_info info; // ufbxi_uninit
+ info.max_concurrent_tasks = num_tasks;
+ ufbxi_check_err(error, pool->opts.pool.init_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, &info));
+ }
+ pool->ator = ator;
+ pool->error = error;
+
+ pool->num_tasks = num_tasks;
+ pool->tasks = ufbxi_alloc(ator, ufbxi_task_imp, num_tasks);
+ ufbxi_check_err(error, pool->tasks);
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_thread_pool_free(ufbxi_thread_pool *pool)
+{
+ if (!pool->enabled) return;
+
+ // Wait for all pending tasks
+ for (uint32_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
+ pool->group = (pool->group + 1) % UFBX_THREAD_GROUP_COUNT;
+ ufbxi_ignore(ufbxi_thread_pool_wait_imp(pool, pool->group, false));
+ }
+
+ if (pool->opts.pool.free_fn) {
+ pool->opts.pool.free_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool);
+ }
+
+ ufbxi_free(pool->ator, ufbxi_task_imp, pool->tasks, pool->num_tasks);
+}
+
+ufbxi_nodiscard ufbxi_noinline static uint32_t ufbxi_thread_pool_available_tasks(ufbxi_thread_pool *pool)
+{
+ return pool->num_tasks - (pool->start_index - pool->wait_index);
+}
+
+ufbxi_noinline static void ufbxi_thread_pool_flush_group(ufbxi_thread_pool *pool)
+{
+ uint32_t group = pool->group;
+ uint32_t start_index = pool->execute_index;
+ uint32_t count = pool->start_index - start_index;
+ if (count > 0) {
+ if (pool->opts.pool.run_fn) {
+ pool->opts.pool.run_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, group, start_index, count);
+ }
+ pool->groups[group].max_index = start_index + count;
+ pool->execute_index = start_index + count;
+ }
+ pool->group = (group + 1) % UFBX_THREAD_GROUP_COUNT;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbxi_task *ufbxi_thread_pool_create_task(ufbxi_thread_pool *pool, ufbxi_task_fn *fn)
+{
+ uint32_t index = pool->start_index;
+ if (index - pool->wait_index >= pool->num_tasks) {
+ if (index - pool->wait_index >= pool->num_tasks) {
+ // No space left
+ return NULL;
+ }
+ } else if (index == INT32_MAX) {
+ // TODO: Expand to 64 bits if possible?
+ return NULL;
+ }
+
+ ufbxi_task_imp *imp = &pool->tasks[index % pool->num_tasks];
+ if (index < pool->num_tasks) {
+ memset(imp, 0, sizeof(ufbxi_task_imp));
+ }
+
+ imp->fn = fn;
+
+ return &imp->task;
+}
+
+static void ufbxi_thread_pool_run_task(ufbxi_thread_pool *pool, ufbxi_task *task)
+{
+ (void)task;
+ uint32_t index = pool->start_index;
+ ufbx_assert(task == &pool->tasks[index % pool->num_tasks].task);
+ pool->start_index = index + 1;
+}
+
+// -- Type definitions
+
+typedef struct ufbxi_node ufbxi_node;
+
+typedef enum {
+ UFBXI_VALUE_NONE,
+ UFBXI_VALUE_NUMBER,
+ UFBXI_VALUE_STRING,
+ UFBXI_VALUE_ARRAY,
+} ufbxi_value_type;
+
+typedef union {
+ struct { double f; int64_t i; }; // < if `UFBXI_PROP_NUMBER`
+ ufbxi_sanitized_string s; // < if `UFBXI_PROP_STRING`
+} ufbxi_value;
+
+typedef struct {
+ void *data; // < Pointer to `size` bool/int32_t/int64_t/float/double elements
+ size_t size; // < Number of elements
+ char type; // < FBX type code: b/i/l/f/d
+} ufbxi_value_array;
+
+struct ufbxi_node {
+ const char *name; // < Name of the node (pooled, compare with == to ufbxi_* strings)
+ uint32_t num_children; // < Number of child nodes
+ uint8_t name_len; // < Length of `name` in bytes
+
+ // If `value_type_mask == UFBXI_PROP_ARRAY` then the node is an array
+ // (`array` field is valid) otherwise the node has N values in `vals`
+ // where the type of each value is stored in 2 bits per value from LSB.
+ // ie. `vals[ix]` type is `(value_type_mask >> (ix*2)) & 0x3`
+ uint16_t value_type_mask;
+
+ ufbxi_node *children;
+ union {
+ ufbxi_value_array *array; // if `prop_type_mask == UFBXI_PROP_ARRAY`
+ ufbxi_value *vals; // otherwise
+ };
+};
+
+typedef struct ufbxi_refcount ufbxi_refcount;
+
+struct ufbxi_refcount {
+ ufbxi_refcount *parent;
+ void *align_0;
+ uint32_t self_magic;
+ uint32_t type_magic;
+ ufbxi_buf buf;
+ ufbxi_allocator ator;
+ uint64_t zero_pad_pre[8];
+ ufbxi_atomic_counter refcount;
+ uint64_t zero_pad_post[8];
+};
+
+static ufbxi_noinline void ufbxi_init_ref(ufbxi_refcount *refcount, uint32_t magic, ufbxi_refcount *parent);
+static ufbxi_noinline void ufbxi_retain_ref(ufbxi_refcount *refcount);
+
+#define ufbxi_get_imp(type, ptr) ((type*)((char*)ptr - sizeof(ufbxi_refcount)))
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_scene scene;
+ uint32_t magic;
+
+ ufbxi_buf string_buf;
+} ufbxi_scene_imp;
+
+ufbx_static_assert(scene_imp_offset, offsetof(ufbxi_scene_imp, scene) == sizeof(ufbxi_refcount));
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_mesh mesh;
+ uint32_t magic;
+} ufbxi_mesh_imp;
+
+ufbx_static_assert(mesh_imp_offset, offsetof(ufbxi_mesh_imp, mesh) == sizeof(ufbxi_refcount));
+
+typedef struct {
+ // Semantic string data and length eg. for a string token
+ // this string doesn't include the quotes.
+ char *str_data;
+ size_t str_len;
+ size_t str_cap;
+
+ // Type of the token, either single character such as '{' or ':'
+ // or one of UFBXI_ASCII_* defines.
+ char type;
+
+ // Sign for integer if negative.
+ bool negative;
+
+ // Parsed semantic value
+ union {
+ double f64;
+ int64_t i64;
+ size_t name_len;
+ } value;
+} ufbxi_ascii_token;
+
+typedef struct {
+ size_t max_token_length;
+
+ const char *src;
+ const char *src_yield;
+ const char *src_end;
+
+ bool read_first_comment;
+ bool found_version;
+ bool parse_as_f32;
+ bool src_is_retained;
+
+ ufbxi_buf *retain_buf;
+ ufbxi_buf *src_buf;
+
+ ufbxi_ascii_token prev_token;
+ ufbxi_ascii_token token;
+} ufbxi_ascii;
+
+typedef struct {
+ const char *type;
+ ufbx_string sub_type;
+ ufbx_props props;
+} ufbxi_template;
+
+typedef struct {
+ uint64_t fbx_id;
+ uint32_t element_id;
+ uint32_t user_id;
+} ufbxi_fbx_id_entry;
+
+typedef struct {
+ ufbxi_ptr_id ptr_id;
+ uint64_t fbx_id;
+} ufbxi_ptr_fbx_id_entry;
+
+typedef struct {
+ uint64_t node_fbx_id;
+ uint64_t attr_fbx_id;
+} ufbxi_fbx_attr_entry;
+
+// Temporary connection before we resolve the element pointers
+typedef struct {
+ uint64_t src, dst;
+ ufbx_string src_prop;
+ ufbx_string dst_prop;
+} ufbxi_tmp_connection;
+
+typedef struct {
+ uint64_t fbx_id;
+ ufbx_string name;
+ ufbx_props props;
+ ufbx_dom_node *dom_node;
+} ufbxi_element_info;
+
+typedef struct {
+ uint64_t bone_fbx_id;
+ ufbx_matrix bone_to_world;
+} ufbxi_tmp_bone_pose;
+
+typedef struct {
+ ufbx_string prop_name;
+ uint32_t *face_texture;
+ size_t num_faces;
+ bool all_same;
+} ufbxi_tmp_mesh_texture;
+
+typedef struct {
+ ufbxi_tmp_mesh_texture *texture_arr;
+ size_t texture_count;
+} ufbxi_mesh_extra;
+
+typedef struct {
+ int32_t material_id;
+ int32_t texture_id;
+ ufbx_string prop_name;
+} ufbxi_tmp_material_texture;
+
+typedef struct {
+ int32_t *blend_modes;
+ size_t num_blend_modes;
+
+ ufbx_real *alphas;
+ size_t num_alphas;
+} ufbxi_texture_extra;
+
+typedef enum {
+ UFBXI_OBJ_ATTRIB_POSITION,
+ UFBXI_OBJ_ATTRIB_UV,
+ UFBXI_OBJ_ATTRIB_NORMAL,
+ UFBXI_OBJ_ATTRIB_COLOR,
+} ufbxi_obj_attrib;
+
+#define UFBXI_OBJ_NUM_ATTRIBS 3
+#define UFBXI_OBJ_NUM_ATTRIBS_EXT 4
+
+typedef struct {
+ uint64_t min_ix, max_ix;
+} ufbxi_obj_index_range;
+
+typedef struct {
+ size_t num_faces;
+ size_t num_indices;
+ ufbxi_obj_index_range vertex_range[UFBXI_OBJ_NUM_ATTRIBS];
+
+ ufbx_node *fbx_node;
+ ufbx_mesh *fbx_mesh;
+
+ uint64_t fbx_node_id;
+ uint64_t fbx_mesh_id;
+
+ uint32_t usemtl_base;
+
+ uint32_t num_groups;
+} ufbxi_obj_mesh;
+
+typedef struct {
+ const char *name;
+ uint32_t local_id;
+ uint32_t mesh_id;
+} ufbxi_obj_group_entry;
+
+typedef struct {
+ uint64_t *indices;
+ size_t num_left;
+} ufbxi_obj_fast_indices;
+
+// Temporary pointer to a `ufbx_anim_stack` by name used to patch start/stop
+// time from "Takes" if necessary.
+typedef struct {
+ const char *name;
+ ufbx_anim_stack *stack;
+} ufbxi_tmp_anim_stack;
+
+typedef struct {
+ ufbx_string absolute_filename;
+ ufbx_blob content;
+} ufbxi_file_content;
+
+typedef struct {
+
+ // Current line and tokens.
+ // NOTE: `line` and `tokens` are not NULL-terminated nor UTF-8!
+ // `line` is guaranteed to be terminated by a `\n`
+ ufbx_string line;
+ ufbx_string *tokens;
+ size_t tokens_cap;
+ size_t num_tokens;
+
+ ufbxi_obj_fast_indices fast_indices[UFBXI_OBJ_NUM_ATTRIBS];
+
+ size_t vertex_count[UFBXI_OBJ_NUM_ATTRIBS_EXT];
+ ufbxi_buf tmp_vertices[UFBXI_OBJ_NUM_ATTRIBS_EXT];
+ ufbxi_buf tmp_indices[UFBXI_OBJ_NUM_ATTRIBS_EXT];
+ ufbxi_buf tmp_color_valid;
+ ufbxi_buf tmp_faces;
+ ufbxi_buf tmp_face_smoothing;
+ ufbxi_buf tmp_face_group;
+ ufbxi_buf tmp_face_group_infos;
+ ufbxi_buf tmp_face_material;
+ ufbxi_buf tmp_meshes;
+ ufbxi_buf tmp_props;
+
+ ufbxi_map group_map;
+
+ size_t read_progress;
+
+ ufbxi_obj_mesh *mesh;
+
+ uint64_t usemtl_fbx_id;
+ uint32_t usemtl_index;
+
+ uint32_t face_material;
+
+ uint32_t face_group;
+ bool has_face_group;
+
+ bool face_smoothing;
+ bool has_face_smoothing;
+
+ bool has_vertex_color;
+ size_t mrgb_vertex_count;
+
+ bool eof;
+ bool initialized;
+
+ ufbx_blob mtllib_relative_path;
+
+ ufbx_material **tmp_materials;
+ size_t tmp_materials_cap;
+
+ ufbx_string object;
+ ufbx_string group;
+ bool material_dirty;
+ bool object_dirty;
+ bool group_dirty;
+ bool face_group_dirty;
+
+} ufbxi_obj_context;
+
+typedef struct {
+
+ ufbx_error error;
+ uint32_t version;
+ ufbx_exporter exporter;
+ uint32_t exporter_version;
+ bool from_ascii;
+ bool local_big_endian;
+ bool file_big_endian;
+ bool sure_fbx;
+ bool retain_mesh_parts;
+ bool read_legacy_settings;
+ uint32_t double_parse_flags;
+
+ ufbx_load_opts opts;
+
+ // IO
+ uint64_t data_offset;
+ ufbx_read_fn *read_fn;
+ ufbx_skip_fn *skip_fn;
+ void *read_user;
+
+ char *read_buffer;
+ size_t read_buffer_size;
+
+ const char *data_begin;
+ const char *data;
+ size_t yield_size;
+ size_t data_size;
+
+ // Allocators
+ ufbxi_allocator ator_result;
+ ufbxi_allocator ator_tmp;
+
+ // Temporary maps
+ ufbxi_map prop_type_map; // < `ufbxi_prop_type_name` Property type to enum
+ ufbxi_map fbx_id_map; // < `ufbxi_fbx_id_entry` FBX ID to local ID
+ ufbxi_map ptr_fbx_id_map; // < `ufbxi_ptr_fbx_id_entry` Pointer/negative ID to FBX ID
+ ufbxi_map texture_file_map; // < `ufbxi_texture_file_entry` absolute raw filename to element ID
+ ufbxi_map anim_stack_map; // < `ufbxi_tmp_anim_stack` anim stacks by name before finalization
+
+ // 6x00 specific maps
+ ufbxi_map fbx_attr_map; // < `ufbxi_fbx_attr_entry` Node ID to attrib ID
+ ufbxi_map node_prop_set; // < `const char*` Node property names
+
+ // DOM nodes
+ ufbxi_map dom_node_map; // < `const char*` Node property names
+
+ // Temporary array
+ char *tmp_arr;
+ size_t tmp_arr_size;
+ char *swap_arr;
+ size_t swap_arr_size;
+
+ // Generated index buffers
+ size_t max_zero_indices;
+ size_t max_consecutive_indices;
+
+ // Temporary buffers
+ ufbxi_buf tmp;
+ ufbxi_buf tmp_parse;
+ ufbxi_buf tmp_stack;
+ ufbxi_buf tmp_connections;
+ ufbxi_buf tmp_node_ids;
+ ufbxi_buf tmp_elements;
+ ufbxi_buf tmp_element_offsets;
+ ufbxi_buf tmp_element_fbx_ids;
+ ufbxi_buf tmp_element_ptrs;
+ ufbxi_buf tmp_typed_element_offsets[UFBX_ELEMENT_TYPE_COUNT];
+ ufbxi_buf tmp_mesh_textures;
+ ufbxi_buf tmp_full_weights;
+ ufbxi_buf tmp_dom_nodes;
+ ufbxi_buf tmp_element_id;
+ ufbxi_buf tmp_ascii_spans;
+ ufbxi_buf tmp_thread_parse[UFBX_THREAD_GROUP_COUNT];
+ size_t tmp_element_byte_offset;
+
+ ufbxi_template *templates;
+ size_t num_templates;
+
+ ufbx_dom_node *dom_parse_toplevel;
+ size_t dom_parse_num_children;
+
+ uint32_t *p_element_id;
+
+ // String pool
+ ufbxi_string_pool string_pool;
+
+ // Result buffers, these are retained in `ufbx_scene` returned to user.
+ ufbxi_buf result;
+
+ // Top-level state
+ ufbxi_node *top_nodes;
+ size_t top_nodes_len, top_nodes_cap;
+ bool parsed_to_end;
+
+ // "Focused" top-level node and child index, if `top_child_index == SIZE_MAX`
+ // the children are parsed on demand.
+ ufbxi_node *top_node;
+ size_t top_child_index;
+ ufbxi_node top_child;
+ bool has_next_child;
+
+ // Shared consecutive and all-zero index buffers
+ uint32_t *zero_indices;
+ uint32_t *consecutive_indices;
+
+ // Call progress function periodically
+ ptrdiff_t progress_timer;
+ uint64_t progress_bytes_total;
+ uint64_t latest_progress_bytes;
+ size_t progress_interval;
+
+ // Extra data on the side of elements
+ void **element_extra_arr;
+ size_t element_extra_cap;
+
+ // Temporary per-element flags
+ uint8_t *tmp_element_flag;
+
+ // IO (cold)
+ ufbx_close_fn *close_fn;
+ ufbx_size_fn *size_fn;
+
+ ufbxi_ascii ascii;
+
+ uint64_t synthetic_id_counter;
+
+ bool has_geometry_transform_nodes;
+ bool has_scale_helper_nodes;
+ bool retain_vertex_w;
+ bool blender_full_weights;
+
+ ufbx_mirror_axis mirror_axis;
+
+ ufbxi_node root;
+
+ ufbx_scene scene;
+ ufbxi_scene_imp *scene_imp;
+
+ ufbx_inflate_retain *inflate_retain;
+
+ // Per-mesh consecutive indices used by `ufbxi_flip_winding()`.
+ uint32_t *tmp_mesh_consecutive_indices;
+
+ uint64_t root_id;
+ uint32_t num_elements;
+
+ ufbxi_node legacy_node;
+ uint64_t legacy_implicit_anim_layer_id;
+
+ ufbxi_file_content *file_content;
+ size_t num_file_content;
+
+ int64_t ktime_sec;
+ double ktime_sec_double;
+
+ bool eof;
+ ufbxi_obj_context obj;
+
+ ufbx_matrix axis_matrix;
+ ufbx_real unit_scale;
+
+ ufbxi_warnings warnings;
+
+ bool deferred_failure;
+ bool deferred_load;
+
+ const char *load_filename;
+ size_t load_filename_len;
+
+ bool parse_threaded;
+ ufbxi_thread_pool thread_pool;
+
+ uint8_t *base64_table;
+
+} ufbxi_context;
+
+static ufbxi_noinline int ufbxi_fail_imp(ufbxi_context *uc, const char *cond, const char *func, uint32_t line)
+{
+ return ufbxi_fail_imp_err(&uc->error, cond, func, line);
+}
+
+#if UFBXI_FEATURE_ERROR_STACK
+ #define ufbxi_fail_no_msg(uc, cond, func, line) ufbxi_fail_imp((uc), (cond), (func), (line))
+#else
+ static ufbxi_noinline int ufbxi_fail_imp_no_stack(ufbxi_context *uc) { return ufbxi_fail_imp_err(&uc->error, NULL, NULL, 0); }
+ #define ufbxi_fail_no_msg(uc, cond, func, line) ufbxi_fail_imp_no_stack((uc))
+#endif
+
+#define ufbxi_check(cond) if (ufbxi_unlikely(!ufbxi_trace(cond))) return ufbxi_fail_no_msg(uc, ufbxi_cond_str(cond), ufbxi_function, ufbxi_line)
+#define ufbxi_check_return(cond, ret) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_no_msg(uc, ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return ret; } } while (0)
+#define ufbxi_fail(desc) return ufbxi_fail_no_msg(uc, desc, ufbxi_function, ufbxi_line)
+#define ufbxi_fail_return(desc, ret) do { ufbxi_fail_no_msg(uc, desc, ufbxi_function, ufbxi_line); return ret; } while (0)
+
+#define ufbxi_check_msg(cond, msg) if (ufbxi_unlikely(!ufbxi_trace(cond))) return ufbxi_fail_imp(uc, ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line)
+#define ufbxi_check_return_msg(cond, ret, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp(uc, ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return ret; } } while (0)
+#define ufbxi_fail_msg(desc, msg) return ufbxi_fail_imp(uc, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
+
+#define ufbxi_warnf(type, ...) ufbxi_warnf_imp(&uc->warnings, type, ~0u, __VA_ARGS__)
+#define ufbxi_warnf_tag(type, element_id, ...) ufbxi_warnf_imp(&uc->warnings, type, (element_id), __VA_ARGS__)
+
+// -- Progress
+
+static ufbxi_forceinline uint64_t ufbxi_get_read_offset(ufbxi_context *uc)
+{
+ return uc->data_offset + ufbxi_to_size(uc->data - uc->data_begin);
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_report_progress(ufbxi_context *uc)
+{
+ if (!uc->opts.progress_cb.fn) return 1;
+
+ uint64_t read_offset = ufbxi_get_read_offset(uc);
+ uc->latest_progress_bytes = read_offset;
+
+ ufbx_progress progress = { 0 };
+ progress.bytes_read = read_offset;
+ progress.bytes_total = uc->progress_bytes_total;
+ if (progress.bytes_total < progress.bytes_read) {
+ progress.bytes_total = progress.bytes_read;
+ }
+
+ uc->progress_timer = 1024;
+ uint32_t result = (uint32_t)uc->opts.progress_cb.fn(uc->opts.progress_cb.user, &progress);
+ ufbx_assert(result == UFBX_PROGRESS_CONTINUE || result == UFBX_PROGRESS_CANCEL);
+ ufbxi_check_msg(result != UFBX_PROGRESS_CANCEL, "Cancelled");
+ return 1;
+}
+
+// TODO: Remove `ufbxi_unused` when it's not needed anymore
+ufbxi_unused ufbxi_nodiscard static ufbxi_forceinline int ufbxi_progress(ufbxi_context *uc, size_t work_units)
+{
+ if (!uc->opts.progress_cb.fn) return 1;
+ ptrdiff_t left = uc->progress_timer - (ptrdiff_t)work_units;
+ uc->progress_timer = left;
+ if (left > 0) return 1;
+ return ufbxi_report_progress(uc);
+}
+
+// -- IO
+
+static ufbxi_noinline const char *ufbxi_refill(ufbxi_context *uc, size_t size, bool require_size)
+{
+ ufbx_assert(uc->data_size < size);
+ ufbxi_check_return(!uc->eof, NULL);
+ if (require_size) {
+ ufbxi_check_return_msg(uc->read_fn || uc->data_size > 0, NULL, "Empty file");
+ ufbxi_check_return_msg(uc->read_fn, NULL, "Truncated file");
+ } else if (!uc->read_fn) {
+ uc->eof = true;
+ return uc->data;
+ }
+
+ void *data_to_free = NULL;
+ size_t size_to_free = 0;
+
+ // Grow the read buffer if necessary, data is copied over below with the
+ // usual path so the free is deferred (`size_to_free`, `data_to_free`)
+ if (size > uc->read_buffer_size) {
+ size_t new_size = ufbxi_max_sz(size, uc->opts.read_buffer_size);
+ new_size = ufbxi_max_sz(new_size, uc->read_buffer_size * 2);
+ size_to_free = uc->read_buffer_size;
+ data_to_free = uc->read_buffer;
+ char *new_buffer = ufbxi_alloc(&uc->ator_tmp, char, new_size);
+ ufbxi_check_return(new_buffer, NULL);
+ uc->read_buffer = new_buffer;
+ uc->read_buffer_size = new_size;
+ }
+
+ // Copy the remains of the previous buffer to the beginning of the new one
+ size_t data_size = uc->data_size;
+ if (data_size > 0) {
+ ufbx_assert(uc->read_buffer != NULL && uc->data != NULL);
+ memmove(uc->read_buffer, uc->data, data_size);
+ }
+
+ if (size_to_free) {
+ ufbxi_free(&uc->ator_tmp, char, data_to_free, size_to_free);
+ }
+
+ // Fill the rest of the buffer with user data
+ size_t data_capacity = uc->read_buffer_size;
+ while (data_size < data_capacity) {
+ size_t to_read = data_capacity - data_size;
+ size_t read_result = uc->read_fn(uc->read_user, uc->read_buffer + data_size, to_read);
+ ufbxi_check_return_msg(read_result != SIZE_MAX, NULL, "IO error");
+ ufbxi_check_return(read_result <= to_read, NULL);
+ data_size += read_result;
+ if (read_result == 0) {
+ uc->eof = true;
+ break;
+ }
+ }
+
+ if (require_size) {
+ if (uc->data_offset == 0) {
+ ufbxi_check_return_msg(data_size > 0, NULL, "Empty file");
+ }
+ ufbxi_check_return_msg(data_size >= size, NULL, "Truncated file");
+ }
+
+ uc->data_offset += ufbxi_to_size(uc->data - uc->data_begin);
+ uc->data_begin = uc->data = uc->read_buffer;
+ uc->data_size = data_size;
+
+ return uc->read_buffer;
+}
+
+static ufbxi_forceinline void ufbxi_pause_progress(ufbxi_context *uc)
+{
+ uc->data_size += uc->yield_size;
+ uc->yield_size = 0;
+}
+
+static ufbxi_noinline int ufbxi_resume_progress(ufbxi_context *uc)
+{
+ uc->yield_size = ufbxi_min_sz(uc->data_size, uc->progress_interval);
+ uc->data_size -= uc->yield_size;
+
+ if (ufbxi_get_read_offset(uc) - uc->latest_progress_bytes >= uc->progress_interval) {
+ ufbxi_check(ufbxi_report_progress(uc));
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline const char *ufbxi_yield(ufbxi_context *uc, size_t size)
+{
+ const char *ret;
+ uc->data_size += uc->yield_size;
+ if (uc->data_size >= size) {
+ ret = uc->data;
+ } else {
+ ret = ufbxi_refill(uc, size, true);
+ }
+ uc->yield_size = ufbxi_min_sz(uc->data_size, ufbxi_max_sz(size, uc->progress_interval));
+ uc->data_size -= uc->yield_size;
+
+ ufbxi_check_return(ufbxi_report_progress(uc), NULL);
+ return ret;
+}
+
+static ufbxi_forceinline const char *ufbxi_peek_bytes(ufbxi_context *uc, size_t size)
+{
+ if (uc->yield_size >= size) {
+ return uc->data;
+ } else {
+ return ufbxi_yield(uc, size);
+ }
+}
+
+static ufbxi_forceinline const char *ufbxi_read_bytes(ufbxi_context *uc, size_t size)
+{
+ // Refill the current buffer if necessary
+ const char *ret;
+ if (uc->yield_size >= size) {
+ ret = uc->data;
+ } else {
+ ret = ufbxi_yield(uc, size);
+ if (!ret) return NULL;
+ }
+
+ // Advance the read position inside the current buffer
+ uc->yield_size -= size;
+ uc->data = ret + size;
+ return ret;
+}
+
+static ufbxi_forceinline void ufbxi_consume_bytes(ufbxi_context *uc, size_t size)
+{
+ // Bytes must have been checked first with `ufbxi_peek_bytes()`
+ ufbx_assert(size <= uc->yield_size);
+ uc->yield_size -= size;
+ uc->data += size;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_skip_bytes(ufbxi_context *uc, uint64_t size)
+{
+ if (uc->skip_fn) {
+ ufbxi_pause_progress(uc);
+
+ if (size > uc->data_size) {
+ size -= uc->data_size;
+ uc->data += uc->data_size;
+ uc->data_size = 0;
+
+ uc->data_offset += size;
+ while (size >= UFBXI_MAX_SKIP_SIZE) {
+ size -= UFBXI_MAX_SKIP_SIZE;
+ ufbxi_check_msg(uc->skip_fn(uc->read_user, UFBXI_MAX_SKIP_SIZE - 1), "Truncated file");
+
+ // Check that we can read at least one byte in case the file is broken
+ // and causes us to seek indefinitely forwards as `fseek()` does not
+ // report if we hit EOF...
+ char single_byte[1]; // ufbxi_uninit
+ size_t num_read = uc->read_fn(uc->read_user, single_byte, 1);
+ ufbxi_check_msg(num_read <= 1, "IO error");
+ ufbxi_check_msg(num_read == 1, "Truncated file");
+ }
+
+ if (size > 0) {
+ ufbxi_check_msg(uc->skip_fn(uc->read_user, (size_t)size), "Truncated file");
+ }
+
+ } else {
+ uc->data += (size_t)size;
+ uc->data_size -= (size_t)size;
+ }
+
+ ufbxi_check(ufbxi_resume_progress(uc));
+ } else {
+ // Read and discard bytes in reasonable chunks
+ uint64_t skip_size = ufbxi_max64(uc->read_buffer_size, uc->opts.read_buffer_size);
+ while (size > 0) {
+ uint64_t to_skip = ufbxi_min64(size, skip_size);
+ ufbxi_check(ufbxi_read_bytes(uc, (size_t)to_skip));
+ size -= to_skip;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_to(ufbxi_context *uc, void *dst, size_t size)
+{
+ char *ptr = (char*)dst;
+
+ ufbxi_pause_progress(uc);
+
+ // Copy data from the current buffer first
+ size_t len = ufbxi_min_sz(uc->data_size, size);
+ memcpy(ptr, uc->data, len);
+ uc->data += len;
+ uc->data_size -= len;
+ ptr += len;
+ size -= len;
+
+ // If there's data left to copy try to read from user IO
+ if (size > 0) {
+ uc->data_offset += ufbxi_to_size(uc->data - uc->data_begin);
+
+ uc->data_begin = uc->data = NULL;
+ uc->data_size = 0;
+ ufbxi_check(uc->read_fn);
+
+ while (size > 0) {
+ size_t read_result = uc->read_fn(uc->read_user, ptr, size);
+ ufbxi_check_msg(read_result != SIZE_MAX, "IO error");
+ ufbxi_check(read_result != 0);
+
+ ptr += read_result;
+ size -= read_result;
+ uc->data_offset += read_result;
+ }
+ }
+
+ ufbxi_check(ufbxi_resume_progress(uc));
+
+ return 1;
+}
+
+static ufbxi_noinline void ufbxi_init_ator(ufbx_error *error, ufbxi_allocator *ator, const ufbx_allocator_opts *opts, const char *name)
+{
+ ufbx_allocator_opts zero_opts;
+ if (!opts) {
+ memset(&zero_opts, 0, sizeof(zero_opts));
+ opts = &zero_opts;
+ }
+
+ // `opts` is either passed in or `zero_opts`.
+ // cppcheck-suppress uninitvar
+ ator->ator = *opts;
+ ator->error = error;
+ ator->max_size = opts->memory_limit ? opts->memory_limit : SIZE_MAX;
+ ator->max_allocs = opts->allocation_limit ? opts->allocation_limit : SIZE_MAX;
+ ator->huge_size = opts->huge_threshold ? opts->huge_threshold : 0x100000;
+ ator->chunk_max = opts->max_chunk_size ? opts->max_chunk_size : 0x1000000;
+ ator->name = name;
+}
+
+typedef struct {
+ ufbx_error error;
+
+ ufbxi_allocator *parent_ator;
+ ufbxi_allocator ator;
+} ufbxi_file_context;
+
+static ufbxi_noinline void ufbxi_begin_file_context(ufbxi_file_context *fc, ufbx_open_file_context ctx, const ufbx_allocator_opts *ator_opts)
+{
+ memset(fc, 0, sizeof(ufbxi_file_context));
+ if (ctx) {
+ fc->parent_ator = (ufbxi_allocator*)ctx;
+ fc->ator = *fc->parent_ator;
+ fc->ator.error = &fc->error;
+ } else {
+ ufbxi_init_ator(&fc->error, &fc->ator, ator_opts, "file");
+ }
+}
+
+static ufbxi_noinline void ufbxi_end_file_context(ufbxi_file_context *fc, ufbx_error *error, bool ok)
+{
+ if (fc->parent_ator) {
+ fc->ator.error = fc->parent_ator->error;
+ *fc->parent_ator = fc->ator;
+ } else {
+ ufbxi_free_ator(&fc->ator);
+ }
+ if (error) {
+ if (!ok) {
+ ufbxi_fix_error_type(&fc->error, "Failed to open file", error);
+ } else {
+ ufbxi_clear_error(error);
+ }
+ }
+}
+
+// -- File IO
+
+#if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
+
+static ufbxi_noinline FILE *ufbxi_fopen(ufbxi_file_context *fc, const char *path, size_t path_len, bool null_terminated)
+{
+ FILE *file = NULL;
+#if !defined(UFBX_STANDARD_C) && defined(_WIN32)
+ (void)null_terminated;
+ wchar_t wpath_buf[256], *wpath = NULL; // ufbxi_uninit
+ if (path_len < ufbxi_arraycount(wpath_buf) - 1) {
+ wpath = wpath_buf;
+ } else {
+ wpath = ufbxi_alloc(&fc->ator, wchar_t, path_len + 1);
+ if (!wpath) return NULL;
+ }
+
+ // Convert UTF-8 to UTF-16 but allow stray surrogate pairs as the Windows
+ // file system encoding allows them as well..
+ size_t wlen = 0;
+ for (size_t i = 0; i < path_len; ) {
+ uint32_t code = UINT32_MAX;
+ char c = path[i++];
+ if ((c & 0x80) == 0) {
+ code = (uint32_t)c;
+ } else if ((c & 0xe0) == 0xc0) {
+ code = (uint32_t)(c & 0x1f);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ } else if ((c & 0xf0) == 0xe0) {
+ code = (uint32_t)(c & 0x0f);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ } else if ((c & 0xf8) == 0xf0) {
+ code = (uint32_t)(c & 0x07);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
+ } else {
+ // Bad UTF-8 character, fail early.
+ if (wpath != wpath_buf) {
+ ufbxi_free(&fc->ator, wchar_t, wpath, path_len + 1);
+ }
+ ufbxi_report_err_msg(&fc->error, "file", "Invalid UTF-8");
+ return NULL;
+ }
+
+ if (code < 0x10000) {
+ wpath[wlen++] = (wchar_t)code;
+ } else {
+ code -= 0x10000;
+ wpath[wlen++] = (wchar_t)(0xd800 + (code >> 10));
+ wpath[wlen++] = (wchar_t)(0xdc00 + (code & 0x3ff));
+ }
+ }
+ wpath[wlen] = 0;
+
+ #if UFBXI_MSC_VER >= 1400
+ if (_wfopen_s(&file, wpath, L"rb") != 0) file = NULL;
+ #else
+ file = _wfopen(wpath, L"rb");
+ #endif
+ if (wpath != wpath_buf) {
+ ufbxi_free(&fc->ator, wchar_t, wpath, path_len + 1);
+ }
+#else
+ char copy_buf[256], *copy = NULL; // ufbxi_uninit
+ if (null_terminated) {
+ copy = (char*)path;
+ } else {
+ if (path_len < ufbxi_arraycount(copy_buf) - 1) {
+ copy = copy_buf;
+ } else {
+ copy = ufbxi_alloc(&fc->ator, char, path_len + 1);
+ if (!copy) return NULL;
+ }
+ memcpy(copy, path, path_len);
+ copy[path_len] = '\0';
+ }
+ file = fopen(copy, "rb");
+ if (!null_terminated && copy != copy_buf) {
+ ufbxi_free(&fc->ator, char, copy, path_len + 1);
+ }
+#endif
+ if (!file) {
+ ufbxi_set_err_info(&fc->error, path, path_len);
+ ufbxi_report_err_msg(&fc->error, "file", "File not found");
+ }
+ return file;
+}
+
+static uint64_t ufbxi_ftell(FILE *file)
+{
+#if !defined(UFBX_STANDARD_C) && defined(UFBX_HAS_FTELLO)
+ off_t result = ftello(file);
+ if (result >= 0) return (uint64_t)result;
+#elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ int64_t result = _ftelli64(file);
+ if (result >= 0) return (uint64_t)result;
+#else
+ int64_t result = ftell(file);
+ if (result >= 0) return (uint64_t)result;
+#endif
+ return UINT64_MAX;
+}
+
+static size_t ufbxi_stdio_read(void *user, void *data, size_t max_size)
+{
+ FILE *file = (FILE*)user;
+ if (ferror(file)) return SIZE_MAX;
+ return fread(data, 1, max_size, file);
+}
+
+static bool ufbxi_stdio_skip(void *user, size_t size)
+{
+ FILE *file = (FILE*)user;
+ ufbx_assert(size <= UFBXI_MAX_SKIP_SIZE);
+ if (fseek(file, (long)size, SEEK_CUR) != 0) return false;
+ if (ferror(file)) return false;
+ return true;
+}
+
+static uint64_t ufbxi_stdio_size(void *user)
+{
+ FILE *file = (FILE*)user;
+ uint64_t result = 0;
+ uint64_t begin = ufbxi_ftell(file);
+ if (begin < UINT64_MAX) {
+ fpos_t pos; // ufbxi_uninit
+ if (fgetpos(file, &pos) == 0) {
+ if (fseek(file, 0, SEEK_END) == 0) {
+ uint64_t end = ufbxi_ftell(file);
+ if (end != UINT64_MAX && begin < end) {
+ result = end - begin;
+ }
+ // Both `rewind()` and `fsetpos()` to reset error and EOF
+ rewind(file);
+ fsetpos(file, &pos);
+ }
+ }
+ }
+ return result;
+}
+
+static void ufbxi_stdio_close(void *user)
+{
+ FILE *file = (FILE*)user;
+ fclose(file);
+}
+
+static ufbxi_noinline void ufbxi_stdio_init(ufbx_stream *stream, void *file, bool close)
+{
+ stream->read_fn = &ufbxi_stdio_read;
+ stream->skip_fn = &ufbxi_stdio_skip;
+ stream->size_fn = &ufbxi_stdio_size;
+ stream->close_fn = close ? &ufbxi_stdio_close : NULL;
+ stream->user = file;
+}
+
+static ufbxi_noinline bool ufbxi_stdio_open(ufbxi_file_context *fc, ufbx_stream *stream, const char *path, size_t path_len, bool null_terminated)
+{
+ FILE *file = ufbxi_fopen(fc, path, path_len, null_terminated);
+ if (!file) return false;
+ ufbxi_stdio_init(stream, file, true);
+ return true;
+}
+
+#elif defined(UFBX_EXTERNAL_STDIO)
+
+static ufbxi_noinline void ufbxi_stdio_init(ufbx_stream *stream, void *file, bool close)
+{
+ stream->read_fn = &ufbx_stdio_read;
+ stream->skip_fn = &ufbx_stdio_skip;
+ stream->size_fn = &ufbx_stdio_size;
+ stream->close_fn = close ? &ufbx_stdio_close : NULL;
+ stream->user = file;
+}
+
+static ufbxi_noinline bool ufbxi_stdio_open(ufbxi_file_context *fc, ufbx_stream *stream, const char *path, size_t path_len, bool null_terminated)
+{
+ char copy_buf[256], *copy = NULL; // ufbxi_uninit
+ if (null_terminated) {
+ copy = (char*)path;
+ } else {
+ if (path_len < ufbxi_arraycount(copy_buf) - 1) {
+ copy = copy_buf;
+ } else {
+ copy = ufbxi_alloc(&fc->ator, char, path_len + 1);
+ if (!copy) return false;
+ }
+ memcpy(copy, path, path_len);
+ copy[path_len] = '\0';
+ }
+ void *file = ufbx_stdio_open(copy, path_len);
+ if (!null_terminated && copy != copy_buf) {
+ ufbxi_free(&fc->ator, char, copy, path_len + 1);
+ }
+ if (!file) {
+ ufbxi_set_err_info(&fc->error, path, path_len);
+ ufbxi_report_err_msg(&fc->error, "file", "File not found");
+ return false;
+ }
+ ufbxi_stdio_init(stream, file, true);
+ return true;
+}
+
+#endif
+
+// -- Memory IO
+
+typedef struct {
+ const void *data;
+ size_t size;
+ size_t position;
+ ufbx_close_memory_cb close_cb;
+
+ // Own allocation information
+ size_t self_size;
+ ufbxi_allocator *parent_ator;
+ ufbxi_allocator local_ator;
+ ufbx_error error;
+ char data_copy[];
+} ufbxi_memory_stream;
+
+static size_t ufbxi_memory_read(void *user, void *data, size_t max_size)
+{
+ ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
+ size_t to_read = ufbxi_min_sz(stream->size - stream->position, max_size);
+ memcpy(data, (const char*)stream->data + stream->position, to_read);
+ stream->position += to_read;
+ return to_read;
+}
+
+static bool ufbxi_memory_skip(void *user, size_t size)
+{
+ ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
+ if (stream->size - stream->position < size) return false;
+ stream->position += size;
+ return true;
+}
+
+static uint64_t ufbxi_memory_size(void *user)
+{
+ ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
+ return stream->size;
+}
+
+static void ufbxi_memory_close(void *user)
+{
+ ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
+ if (stream->close_cb.fn) {
+ stream->close_cb.fn(stream->close_cb.user, (void*)stream->data, stream->size);
+ }
+
+ if (stream->parent_ator) {
+ ufbxi_free(stream->parent_ator, char, stream, stream->self_size);
+ } else {
+ ufbxi_allocator ator = stream->local_ator;
+ ufbxi_free(&ator, char, stream, stream->self_size);
+ ufbxi_free_ator(&ator);
+ }
+}
+
+// -- XML
+
+#if UFBXI_FEATURE_XML
+
+typedef struct ufbxi_xml_tag ufbxi_xml_tag;
+typedef struct ufbxi_xml_attrib ufbxi_xml_attrib;
+typedef struct ufbxi_xml_document ufbxi_xml_document;
+
+struct ufbxi_xml_attrib {
+ ufbx_string name;
+ ufbx_string value;
+};
+
+struct ufbxi_xml_tag {
+ ufbx_string name;
+ ufbx_string text;
+
+ ufbxi_xml_attrib *attribs;
+ size_t num_attribs;
+
+ ufbxi_xml_tag *children;
+ size_t num_children;
+};
+
+struct ufbxi_xml_document {
+ ufbxi_xml_tag *root;
+ ufbxi_buf buf;
+};
+
+typedef struct {
+ ufbx_error error;
+
+ ufbxi_allocator *ator;
+
+ ufbxi_buf tmp_stack;
+ ufbxi_buf result;
+
+ ufbxi_xml_document *doc;
+
+ ufbx_read_fn *read_fn;
+ void *read_user;
+
+ char *tok;
+ size_t tok_cap;
+ size_t tok_len;
+
+ const char *pos, *pos_end;
+ char data[4096];
+
+ bool io_error;
+} ufbxi_xml_context;
+
+enum {
+ UFBXI_XML_CTYPE_WHITESPACE = 0x1,
+ UFBXI_XML_CTYPE_SINGLE_QUOTE = 0x2,
+ UFBXI_XML_CTYPE_DOUBLE_QUOTE = 0x4,
+ UFBXI_XML_CTYPE_NAME_END = 0x8,
+ UFBXI_XML_CTYPE_TAG_START = 0x10,
+ UFBXI_XML_CTYPE_END_OF_FILE = 0x20,
+};
+
+// Generated by `misc/gen_xml_ctype.py`
+static const uint8_t ufbxi_xml_ctype[256] = {
+ 32,0,0,0,0,0,0,0,0,9,9,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 9,0,12,0,0,0,0,10,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,16,8,8,8,
+};
+
+static ufbxi_noinline void ufbxi_xml_refill(ufbxi_xml_context *xc)
+{
+ size_t num = xc->read_fn(xc->read_user, xc->data, sizeof(xc->data));
+ if (num == SIZE_MAX || num < sizeof(xc->data)) xc->io_error = true;
+ if (num < sizeof(xc->data)) {
+ xc->data[num++] = '\0';
+ }
+ xc->pos = xc->data;
+ xc->pos_end = xc->data + num;
+}
+
+static ufbxi_forceinline void ufbxi_xml_advance(ufbxi_xml_context *xc)
+{
+ if (++xc->pos == xc->pos_end) ufbxi_xml_refill(xc);
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_xml_push_token_char(ufbxi_xml_context *xc, char c)
+{
+ if (xc->tok_len == xc->tok_cap || UFBXI_IS_REGRESSION) {
+ ufbxi_check_err(&xc->error, ufbxi_grow_array(xc->ator, &xc->tok, &xc->tok_cap, xc->tok_len + 1));
+ }
+ xc->tok[xc->tok_len++] = c;
+ return 1;
+}
+
+static ufbxi_noinline int ufbxi_xml_accept(ufbxi_xml_context *xc, char ch)
+{
+ if (*xc->pos == ch) {
+ ufbxi_xml_advance(xc);
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+static ufbxi_noinline void ufbxi_xml_skip_while(ufbxi_xml_context *xc, uint32_t ctypes)
+{
+ while (ufbxi_xml_ctype[(uint8_t)*xc->pos] & ctypes) {
+ ufbxi_xml_advance(xc);
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_xml_skip_until_string(ufbxi_xml_context *xc, ufbx_string *dst, const char *suffix)
+{
+ xc->tok_len = 0;
+ size_t match_len = 0, ix = 0, suffix_len = strlen(suffix);
+ char buf[16] = { 0 };
+ size_t wrap_mask = sizeof(buf) - 1;
+ ufbx_assert(suffix_len < sizeof(buf));
+ for (;;) {
+ char c = *xc->pos;
+ ufbxi_check_err_msg(&xc->error, c != 0, "Truncated file");
+ ufbxi_xml_advance(xc);
+ if (ix >= suffix_len) {
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, buf[(ix - suffix_len) & wrap_mask]));
+ }
+
+ buf[ix++ & wrap_mask] = c;
+ for (match_len = 0; match_len < suffix_len; match_len++) {
+ if (buf[(ix - suffix_len + match_len) & wrap_mask] != suffix[match_len]) {
+ break;
+ }
+ }
+ if (match_len == suffix_len) break;
+ }
+
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
+ if (dst) {
+ dst->length = xc->tok_len - 1;
+ dst->data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
+ ufbxi_check_err(&xc->error, dst->data);
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline int ufbxi_xml_read_until(ufbxi_xml_context *xc, ufbx_string *dst, uint32_t ctypes)
+{
+ xc->tok_len = 0;
+ for (;;) {
+ char c = *xc->pos;
+
+ if (c == '&') {
+ size_t entity_begin = xc->tok_len;
+ for (;;) {
+ ufbxi_xml_advance(xc);
+ c = *xc->pos;
+ ufbxi_check_err(&xc->error, c != '\0');
+ if (c == ';') break;
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, c));
+ }
+ ufbxi_xml_advance(xc);
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
+
+ char *entity = xc->tok + entity_begin;
+ xc->tok_len = entity_begin;
+
+ if (entity[0] == '#') {
+ unsigned long code = 0;
+ if (entity[1] == 'x') {
+ code = ufbxi_parse_uint32_radix(entity + 2, 16);
+ } else {
+ code = ufbxi_parse_uint32_radix(entity + 1, 10);
+ }
+
+ char bytes[5] = { 0 };
+ if (code < 0x80) {
+ bytes[0] = (char)code;
+ } else if (code < 0x800) {
+ bytes[0] = (char)(0xc0 | (code>>6));
+ bytes[1] = (char)(0x80 | (code & 0x3f));
+ } else if (code < 0x10000) {
+ bytes[0] = (char)(0xe0 | (code>>12));
+ bytes[1] = (char)(0x80 | ((code>>6) & 0x3f));
+ bytes[2] = (char)(0x80 | (code & 0x3f));
+ } else {
+ bytes[0] = (char)(0xf0 | (code>>18));
+ bytes[1] = (char)(0x80 | ((code>>12) & 0x3f));
+ bytes[2] = (char)(0x80 | ((code>>6) & 0x3f));
+ bytes[3] = (char)(0x80 | (code & 0x3f));
+ }
+ for (char *b = bytes; *b; b++) {
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, *b));
+ }
+ } else {
+ char ch = '\0';
+ if (!strcmp(entity, "lt")) ch = '<';
+ else if (!strcmp(entity, "quot")) ch = '"';
+ else if (!strcmp(entity, "amp")) ch = '&';
+ else if (!strcmp(entity, "apos")) ch = '\'';
+ else if (!strcmp(entity, "gt")) ch = '>';
+ if (ch) {
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, ch));
+ }
+ }
+ } else {
+ if ((ufbxi_xml_ctype[(uint8_t)c] & ctypes) != 0) break;
+ ufbxi_check_err_msg(&xc->error, c != 0, "Truncated file");
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, c));
+ ufbxi_xml_advance(xc);
+ }
+ }
+
+ ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
+ if (dst) {
+ dst->length = xc->tok_len - 1;
+ dst->data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
+ ufbxi_check_err(&xc->error, dst->data);
+ }
+
+ return 1;
+}
+
+// Recursion limited by check at the start
+static ufbxi_noinline int ufbxi_xml_parse_tag(ufbxi_xml_context *xc, size_t depth, bool *p_closing, const char *opening)
+ ufbxi_recursive_function(int, ufbxi_xml_parse_tag, (xc, depth, p_closing, opening), UFBXI_MAX_XML_DEPTH + 1,
+ (ufbxi_xml_context *xc, size_t depth, bool *p_closing, const char *opening))
+{
+ ufbxi_check_err(&xc->error, depth < UFBXI_MAX_XML_DEPTH);
+
+ if (!ufbxi_xml_accept(xc, '<')) {
+ if (*xc->pos == '\0') {
+ *p_closing = true;
+ } else {
+ ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, NULL, UFBXI_XML_CTYPE_TAG_START | UFBXI_XML_CTYPE_END_OF_FILE));
+ bool has_text = false;
+ for (size_t i = 0; i < xc->tok_len; i++) {
+ if ((ufbxi_xml_ctype[(uint8_t)xc->tok[i]] & UFBXI_XML_CTYPE_WHITESPACE) == 0) {
+ has_text = true;
+ break;
+ }
+ }
+
+ if (has_text) {
+ ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
+ ufbxi_check_err(&xc->error, tag);
+ tag->name.data = ufbxi_empty_char;
+
+ tag->text.length = xc->tok_len - 1;
+ tag->text.data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
+ ufbxi_check_err(&xc->error, tag->text.data);
+ }
+ }
+ return 1;
+ }
+
+ if (ufbxi_xml_accept(xc, '/')) {
+ ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, NULL, UFBXI_XML_CTYPE_NAME_END));
+ ufbxi_check_err(&xc->error, opening && !strcmp(xc->tok, opening));
+ ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
+ if (!ufbxi_xml_accept(xc, '>')) return 0;
+ *p_closing = true;
+ return 1;
+ } else if (ufbxi_xml_accept(xc, '!')) {
+ if (ufbxi_xml_accept(xc, '[')) {
+ for (const char *ch = "CDATA["; *ch; ch++) {
+ if (!ufbxi_xml_accept(xc, *ch)) return 0;
+ }
+
+ ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
+ ufbxi_check_err(&xc->error, tag);
+ ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, &tag->text, "]]>"));
+ tag->name.data = ufbxi_empty_char;
+
+ } else if (ufbxi_xml_accept(xc, '-')) {
+ if (!ufbxi_xml_accept(xc, '-')) return 0;
+ ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, "-->"));
+ } else {
+ // TODO: !DOCTYPE
+ ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, ">"));
+ }
+ return 1;
+ } else if (ufbxi_xml_accept(xc, '?')) {
+ ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, "?>"));
+ return 1;
+ }
+
+ ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
+ ufbxi_check_err(&xc->error, tag);
+ ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &tag->name, UFBXI_XML_CTYPE_NAME_END));
+ tag->text.data = ufbxi_empty_char;
+
+ bool has_children = false;
+
+ size_t num_attribs = 0;
+ for (;;) {
+ ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
+ if (ufbxi_xml_accept(xc, '/')) {
+ if (!ufbxi_xml_accept(xc, '>')) return 0;
+ break;
+ } else if (ufbxi_xml_accept(xc, '>')) {
+ has_children = true;
+ break;
+ } else {
+ ufbxi_xml_attrib *attrib = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_attrib, 1);
+ ufbxi_check_err(&xc->error, attrib);
+ ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &attrib->name, UFBXI_XML_CTYPE_NAME_END));
+ ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
+ if (!ufbxi_xml_accept(xc, '=')) return 0;
+ ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
+ uint32_t quote_ctype = 0;
+ if (ufbxi_xml_accept(xc, '"')) {
+ quote_ctype = UFBXI_XML_CTYPE_DOUBLE_QUOTE;
+ } else if (ufbxi_xml_accept(xc, '\'')) {
+ quote_ctype = UFBXI_XML_CTYPE_SINGLE_QUOTE;
+ } else {
+ ufbxi_fail_err(&xc->error, "Bad attrib value");
+ }
+ ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &attrib->value, quote_ctype));
+ ufbxi_xml_advance(xc);
+ num_attribs++;
+ }
+ }
+
+ tag->num_attribs = num_attribs;
+ tag->attribs = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_attrib, num_attribs);
+ ufbxi_check_err(&xc->error, tag->attribs);
+
+ if (has_children) {
+ size_t children_begin = xc->tmp_stack.num_items;
+ for (;;) {
+ bool closing = false;
+ ufbxi_check_err(&xc->error, ufbxi_xml_parse_tag(xc, depth + 1, &closing, tag->name.data));
+ if (closing) break;
+ }
+
+ tag->num_children = xc->tmp_stack.num_items - children_begin;
+ tag->children = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_tag, tag->num_children);
+ ufbxi_check_err(&xc->error, tag->children);
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline int ufbxi_xml_parse_root(ufbxi_xml_context *xc)
+{
+ ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->result, ufbxi_xml_tag, 1);
+ ufbxi_check_err(&xc->error, tag);
+ tag->name.data = ufbxi_empty_char;
+ tag->text.data = ufbxi_empty_char;
+
+ for (;;) {
+ bool closing = false;
+ ufbxi_check_err(&xc->error, ufbxi_xml_parse_tag(xc, 0, &closing, NULL));
+ if (closing) break;
+ }
+
+ tag->num_children = xc->tmp_stack.num_items;
+ tag->children = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_tag, tag->num_children);
+ ufbxi_check_err(&xc->error, tag->children);
+
+ xc->doc = ufbxi_push(&xc->result, ufbxi_xml_document, 1);
+ ufbxi_check_err(&xc->error, xc->doc);
+
+ xc->doc->root = tag;
+ xc->doc->buf = xc->result;
+
+ return 1;
+}
+
+typedef struct {
+ ufbxi_allocator *ator;
+ ufbx_read_fn *read_fn;
+ void *read_user;
+ const char *prefix;
+ size_t prefix_length;
+} ufbxi_xml_load_opts;
+
+static ufbxi_noinline ufbxi_xml_document *ufbxi_load_xml(ufbxi_xml_load_opts *opts, ufbx_error *error)
+{
+ ufbxi_xml_context xc = { UFBX_ERROR_NONE };
+ xc.ator = opts->ator;
+ xc.read_fn = opts->read_fn;
+ xc.read_user = opts->read_user;
+
+ xc.tmp_stack.ator = xc.ator;
+ xc.result.ator = xc.ator;
+
+ xc.result.unordered = true;
+
+ if (opts->prefix_length > 0) {
+ xc.pos = opts->prefix;
+ xc.pos_end = opts->prefix + opts->prefix_length;
+ } else {
+ ufbxi_xml_refill(&xc);
+ }
+
+ int ok = ufbxi_xml_parse_root(&xc);
+
+ ufbxi_buf_free(&xc.tmp_stack);
+ ufbxi_free(xc.ator, char, xc.tok, xc.tok_cap);
+
+ if (ok) {
+ return xc.doc;
+ } else {
+ ufbxi_buf_free(&xc.result);
+ if (error) {
+ *error = xc.error;
+ }
+
+ return NULL;
+ }
+}
+
+static ufbxi_noinline void ufbxi_free_xml(ufbxi_xml_document *doc)
+{
+ ufbxi_buf buf = doc->buf;
+ ufbxi_buf_free(&buf);
+}
+
+static ufbxi_noinline ufbxi_xml_tag *ufbxi_xml_find_child(ufbxi_xml_tag *tag, const char *name)
+{
+ ufbxi_for(ufbxi_xml_tag, child, tag->children, tag->num_children) {
+ if (!strcmp(child->name.data, name)) {
+ return child;
+ }
+ }
+ return NULL;
+}
+
+static ufbxi_noinline ufbxi_xml_attrib *ufbxi_xml_find_attrib(ufbxi_xml_tag *tag, const char *name)
+{
+ ufbxi_for(ufbxi_xml_attrib, attrib, tag->attribs, tag->num_attribs) {
+ if (!strcmp(attrib->name.data, name)) {
+ return attrib;
+ }
+ }
+ return NULL;
+}
+
+#endif
+
+// -- FBX value type information
+
+static char ufbxi_normalize_array_type(char type, char bool_type) {
+ switch (type) {
+ case 'r': return sizeof(ufbx_real) == sizeof(float) ? 'f' : 'd';
+ case 'b': return bool_type;
+ default: return type;
+ }
+}
+
+static ufbxi_noinline size_t ufbxi_array_type_size(char type)
+{
+ switch (type) {
+ case 'r': return sizeof(ufbx_real);
+ case 'b': return sizeof(bool);
+ case 'c': return sizeof(uint8_t);
+ case 'i': return sizeof(int32_t);
+ case 'l': return sizeof(int64_t);
+ case 'f': return sizeof(float);
+ case 'd': return sizeof(double);
+ case 's': return sizeof(ufbx_string);
+ case 'S': return sizeof(ufbx_string);
+ case 'C': return sizeof(ufbx_string);
+ default: return 1;
+ }
+}
+
+// -- Node operations
+
+static ufbxi_noinline ufbxi_node *ufbxi_find_child(ufbxi_node *node, const char *name)
+{
+ ufbxi_for(ufbxi_node, c, node->children, node->num_children) {
+ if (c->name == name) return c;
+ }
+ return NULL;
+}
+
+// Retrieve the type of a given value
+ufbxi_forceinline static ufbxi_value_type ufbxi_get_val_type(ufbxi_node *node, size_t ix)
+{
+ return (ufbxi_value_type)((node->value_type_mask >> (ix*2)) & 0x3);
+}
+
+// Retrieve values from nodes with type codes:
+// Any: '_' (ignore)
+// NUMBER: 'I' int32_t 'L' int64_t 'F' float 'D' double 'R' ufbxi_real 'B' bool 'Z' size_t
+// STRING: 'S' ufbx_string 'C' const char* (checked) 's' ufbx_string 'c' const char * (unchecked) 'b' ufbx_blob
+ufbxi_nodiscard ufbxi_forceinline static int ufbxi_get_val_at(ufbxi_node *node, size_t ix, char fmt, void *v)
+{
+ ufbxi_dev_assert(ix < UFBXI_MAX_NON_ARRAY_VALUES);
+ ufbxi_value_type type = (ufbxi_value_type)((node->value_type_mask >> (ix*2)) & 0x3);
+ switch (fmt) {
+ case '_': return 1;
+ case 'I': if (type == UFBXI_VALUE_NUMBER) { *(int32_t*)v = (int32_t)node->vals[ix].i; return 1; } else return 0;
+ case 'L': if (type == UFBXI_VALUE_NUMBER) { *(int64_t*)v = (int64_t)node->vals[ix].i; return 1; } else return 0;
+ case 'F': if (type == UFBXI_VALUE_NUMBER) { *(float*)v = (float)node->vals[ix].f; return 1; } else return 0;
+ case 'D': if (type == UFBXI_VALUE_NUMBER) { *(double*)v = (double)node->vals[ix].f; return 1; } else return 0;
+ case 'R': if (type == UFBXI_VALUE_NUMBER) { *(ufbx_real*)v = (ufbx_real)node->vals[ix].f; return 1; } else return 0;
+ case 'B': if (type == UFBXI_VALUE_NUMBER) { *(bool*)v = node->vals[ix].i != 0; return 1; } else return 0;
+ case 'Z': if (type == UFBXI_VALUE_NUMBER) {
+ if (node->vals[ix].i < 0) return 0;
+ #if SIZE_MAX < INT64_MAX
+ if (node->vals[ix].i > SIZE_MAX) return 0;
+ #endif
+ *(size_t*)v = (size_t)node->vals[ix].i;
+ return 1;
+ } else return 0;
+ case 'S': if (type == UFBXI_VALUE_STRING) {
+ ufbxi_sanitized_string src = node->vals[ix].s;
+ ufbx_string *dst = (ufbx_string*)v;
+ if (!src.utf8_data) return 0;
+ dst->data = src.utf8_data;
+ dst->length = src.utf8_length;
+ return 1;
+ } else return 0;
+ case 's': if (type == UFBXI_VALUE_STRING) {
+ ufbxi_sanitized_string src = node->vals[ix].s;
+ ufbx_string *dst = (ufbx_string*)v;
+ dst->data = src.raw_data;
+ dst->length = src.raw_length;
+ return 1;
+ } else return 0;
+ case 'C': if (type == UFBXI_VALUE_STRING) {
+ ufbxi_sanitized_string src = node->vals[ix].s;
+ const char **dst = (const char **)v;
+ if (!src.utf8_data) return 0;
+ *dst = src.utf8_data;
+ return 1;
+ } else return 0;
+ case 'c': if (type == UFBXI_VALUE_STRING) {
+ ufbxi_sanitized_string src = node->vals[ix].s;
+ const char **dst = (const char **)v;
+ *dst = src.raw_data;
+ return 1;
+ } else return 0;
+ case 'b': if (type == UFBXI_VALUE_STRING) {
+ ufbxi_sanitized_string src = node->vals[ix].s;
+ ufbx_blob *dst = (ufbx_blob*)v;
+ dst->data = src.raw_data;
+ dst->size = src.raw_length;
+ return 1;
+ } else return 0;
+ default:
+ ufbxi_unreachable("Bad format char");
+ return 0;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbxi_value_array *ufbxi_get_array(ufbxi_node *node, char fmt)
+{
+ if (node->value_type_mask != UFBXI_VALUE_ARRAY) return NULL;
+ ufbxi_value_array *array = node->array;
+ if (fmt != '?') {
+ fmt = ufbxi_normalize_array_type(fmt, 'b');
+ if (array->type != fmt) return NULL;
+ }
+ return array;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val1(ufbxi_node *node, const char *fmt, void *v0)
+{
+ if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val2(ufbxi_node *node, const char *fmt, void *v0, void *v1)
+{
+ if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
+ if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val3(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2)
+{
+ if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
+ if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
+ if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val4(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2, void *v3)
+{
+ if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
+ if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
+ if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
+ if (!ufbxi_get_val_at(node, 3, fmt[3], v3)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val5(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2, void *v3, void *v4)
+{
+ if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
+ if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
+ if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
+ if (!ufbxi_get_val_at(node, 3, fmt[3], v3)) return 0;
+ if (!ufbxi_get_val_at(node, 4, fmt[4], v4)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_find_val1(ufbxi_node *node, const char *name, const char *fmt, void *v0)
+{
+ ufbxi_node *child = ufbxi_find_child(node, name);
+ if (!child) return 0;
+ if (!ufbxi_get_val_at(child, 0, fmt[0], v0)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_find_val2(ufbxi_node *node, const char *name, const char *fmt, void *v0, void *v1)
+{
+ ufbxi_node *child = ufbxi_find_child(node, name);
+ if (!child) return 0;
+ if (!ufbxi_get_val_at(child, 0, fmt[0], v0)) return 0;
+ if (!ufbxi_get_val_at(child, 1, fmt[1], v1)) return 0;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline ufbxi_value_array *ufbxi_find_array(ufbxi_node *node, const char *name, char fmt)
+{
+ ufbxi_node *child = ufbxi_find_child(node, name);
+ if (!child) return NULL;
+ return ufbxi_get_array(child, fmt);
+}
+
+static ufbxi_node *ufbxi_find_child_strcmp(ufbxi_node *node, const char *name)
+{
+ char leading = name[0];
+ ufbxi_for(ufbxi_node, c, node->children, node->num_children) {
+ if (c->name[0] != leading) continue;
+ if (!strcmp(c->name, name)) return c;
+ }
+ return NULL;
+}
+
+// -- Element extra data allocation
+
+ufbxi_nodiscard static ufbxi_noinline void *ufbxi_push_element_extra_size(ufbxi_context *uc, uint32_t id, size_t size)
+{
+ if (uc->element_extra_cap <= id) {
+ size_t old_cap = uc->element_extra_cap;
+ ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->element_extra_arr, &uc->element_extra_cap, id + 1), NULL);
+ memset(uc->element_extra_arr + old_cap, 0, (uc->element_extra_cap - old_cap) * sizeof(void*));
+ }
+
+ if (uc->element_extra_arr[id]) return uc->element_extra_arr[id];
+
+ void *extra = ufbxi_push_size_zero(&uc->tmp, size, 1);
+ ufbxi_check_return(extra, NULL);
+ uc->element_extra_arr[id] = extra;
+
+ return extra;
+}
+
+static ufbxi_noinline void *ufbxi_get_element_extra(ufbxi_context *uc, uint32_t id)
+{
+ if (id < uc->element_extra_cap) {
+ return uc->element_extra_arr[id];
+ } else {
+ return NULL;
+ }
+}
+
+#define ufbxi_push_element_extra(uc, id, type) (type*)ufbxi_push_element_extra_size((uc), (id), sizeof(type))
+
+// -- Parsing state machine
+//
+// When reading the file we maintain a coarse representation of the structure so
+// that we can resolve array info (type, included in result, etc). Using this info
+// we can often read/decompress the contents directly into the right memory area.
+
+typedef enum {
+ UFBXI_PARSE_ROOT,
+ UFBXI_PARSE_FBX_HEADER_EXTENSION,
+ UFBXI_PARSE_SCENE_INFO,
+ UFBXI_PARSE_THUMBNAIL,
+ UFBXI_PARSE_DEFINITIONS,
+ UFBXI_PARSE_OBJECTS,
+ UFBXI_PARSE_CONNECTIONS,
+ UFBXI_PARSE_RELATIONS,
+ UFBXI_PARSE_TAKES,
+ UFBXI_PARSE_FBX_VERSION,
+ UFBXI_PARSE_MODEL,
+ UFBXI_PARSE_GEOMETRY,
+ UFBXI_PARSE_NODE_ATTRIBUTE,
+ UFBXI_PARSE_LEGACY_MODEL,
+ UFBXI_PARSE_LEGACY_MEDIA,
+ UFBXI_PARSE_LEGACY_VIDEO,
+ UFBXI_PARSE_LEGACY_SWITCHER,
+ UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE,
+ UFBXI_PARSE_REFERENCES,
+ UFBXI_PARSE_REFERENCE,
+ UFBXI_PARSE_ANIMATION_CURVE,
+ UFBXI_PARSE_DEFORMER,
+ UFBXI_PARSE_ASSOCIATE_MODEL,
+ UFBXI_PARSE_LEGACY_LINK,
+ UFBXI_PARSE_POSE,
+ UFBXI_PARSE_POSE_NODE,
+ UFBXI_PARSE_TEXTURE,
+ UFBXI_PARSE_VIDEO,
+ UFBXI_PARSE_LAYERED_TEXTURE,
+ UFBXI_PARSE_SELECTION_NODE,
+ UFBXI_PARSE_COLLECTION,
+ UFBXI_PARSE_AUDIO,
+ UFBXI_PARSE_UNKNOWN_OBJECT,
+ UFBXI_PARSE_LAYER_ELEMENT_NORMAL,
+ UFBXI_PARSE_LAYER_ELEMENT_BINORMAL,
+ UFBXI_PARSE_LAYER_ELEMENT_TANGENT,
+ UFBXI_PARSE_LAYER_ELEMENT_UV,
+ UFBXI_PARSE_LAYER_ELEMENT_COLOR,
+ UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE,
+ UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE,
+ UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING,
+ UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY,
+ UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP,
+ UFBXI_PARSE_LAYER_ELEMENT_HOLE,
+ UFBXI_PARSE_LAYER_ELEMENT_MATERIAL,
+ UFBXI_PARSE_LAYER_ELEMENT_OTHER,
+ UFBXI_PARSE_GEOMETRY_UV_INFO,
+ UFBXI_PARSE_SHAPE,
+ UFBXI_PARSE_TAKE,
+ UFBXI_PARSE_TAKE_OBJECT,
+ UFBXI_PARSE_CHANNEL,
+ UFBXI_PARSE_UNKNOWN,
+} ufbxi_parse_state;
+
+typedef enum {
+ UFBXI_ARRAY_FLAG_RESULT = 0x1, // < Allocate the array from the result buffer
+ UFBXI_ARRAY_FLAG_TMP_BUF = 0x2, // < Allocate the array from the long-term temporary buffer
+ UFBXI_ARRAY_FLAG_PAD_BEGIN = 0x4, // < Pad the begin of the array with 4 zero elements to guard from invalid -1 index accesses
+ UFBXI_ARRAY_FLAG_ACCURATE_F32 = 0x8, // < Must be parsed as bit-accurate 32-bit floats
+} ufbxi_array_flags;
+
+typedef struct {
+ char type; // < FBX type code of the array: b,i,l,f,d (or 'r' meaning ufbx_real '-' ignore, 's'/'S' for strings, 'C' for content)
+ uint8_t flags; // < Combination of `ufbxi_array_flags`
+} ufbxi_array_info;
+
+static ufbxi_noinline ufbxi_parse_state ufbxi_update_parse_state(ufbxi_parse_state parent, const char *name)
+{
+ switch (parent) {
+
+ case UFBXI_PARSE_ROOT:
+ if (name == ufbxi_FBXHeaderExtension) return UFBXI_PARSE_FBX_HEADER_EXTENSION;
+ if (name == ufbxi_Definitions) return UFBXI_PARSE_DEFINITIONS;
+ if (name == ufbxi_Objects) return UFBXI_PARSE_OBJECTS;
+ if (name == ufbxi_Connections) return UFBXI_PARSE_CONNECTIONS;
+ if (name == ufbxi_Takes) return UFBXI_PARSE_TAKES;
+ if (name == ufbxi_Model) return UFBXI_PARSE_LEGACY_MODEL;
+ if (!strcmp(name, "References")) return UFBXI_PARSE_REFERENCES;
+ if (!strcmp(name, "Relations")) return UFBXI_PARSE_RELATIONS;
+ if (name == ufbxi_Media) return UFBXI_PARSE_LEGACY_MEDIA;
+ if (!strcmp(name, "Switcher")) return UFBXI_PARSE_LEGACY_SWITCHER;
+ if (!strcmp(name, "SceneGenericPersistence")) return UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE;
+ break;
+
+ case UFBXI_PARSE_FBX_HEADER_EXTENSION:
+ if (name == ufbxi_FBXVersion) return UFBXI_PARSE_FBX_VERSION;
+ if (name == ufbxi_SceneInfo) return UFBXI_PARSE_SCENE_INFO;
+ break;
+
+ case UFBXI_PARSE_SCENE_INFO:
+ if (name == ufbxi_Thumbnail) return UFBXI_PARSE_THUMBNAIL;
+ break;
+
+ case UFBXI_PARSE_OBJECTS:
+ if (name == ufbxi_Model) return UFBXI_PARSE_MODEL;
+ if (name == ufbxi_Geometry) return UFBXI_PARSE_GEOMETRY;
+ if (name == ufbxi_NodeAttribute) return UFBXI_PARSE_NODE_ATTRIBUTE;
+ if (name == ufbxi_AnimationCurve) return UFBXI_PARSE_ANIMATION_CURVE;
+ if (name == ufbxi_Deformer) return UFBXI_PARSE_DEFORMER;
+ if (name == ufbxi_Pose) return UFBXI_PARSE_POSE;
+ if (name == ufbxi_Texture) return UFBXI_PARSE_TEXTURE;
+ if (name == ufbxi_Video) return UFBXI_PARSE_VIDEO;
+ if (name == ufbxi_LayeredTexture) return UFBXI_PARSE_LAYERED_TEXTURE;
+ if (name == ufbxi_SelectionNode) return UFBXI_PARSE_SELECTION_NODE;
+ if (name == ufbxi_Collection) return UFBXI_PARSE_COLLECTION;
+ if (name == ufbxi_Audio) return UFBXI_PARSE_AUDIO;
+ return UFBXI_PARSE_UNKNOWN_OBJECT;
+
+ case UFBXI_PARSE_MODEL:
+ case UFBXI_PARSE_GEOMETRY:
+ if (name[0] == 'L') {
+ if (name == ufbxi_LayerElementNormal) return UFBXI_PARSE_LAYER_ELEMENT_NORMAL;
+ if (name == ufbxi_LayerElementBinormal) return UFBXI_PARSE_LAYER_ELEMENT_BINORMAL;
+ if (name == ufbxi_LayerElementTangent) return UFBXI_PARSE_LAYER_ELEMENT_TANGENT;
+ if (name == ufbxi_LayerElementUV) return UFBXI_PARSE_LAYER_ELEMENT_UV;
+ if (name == ufbxi_LayerElementColor) return UFBXI_PARSE_LAYER_ELEMENT_COLOR;
+ if (name == ufbxi_LayerElementVertexCrease) return UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE;
+ if (name == ufbxi_LayerElementEdgeCrease) return UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE;
+ if (name == ufbxi_LayerElementSmoothing) return UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING;
+ if (name == ufbxi_LayerElementVisibility) return UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY;
+ if (name == ufbxi_LayerElementPolygonGroup) return UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP;
+ if (name == ufbxi_LayerElementHole) return UFBXI_PARSE_LAYER_ELEMENT_HOLE;
+ if (name == ufbxi_LayerElementMaterial) return UFBXI_PARSE_LAYER_ELEMENT_MATERIAL;
+ if (!strncmp(name, "LayerElement", 12)) return UFBXI_PARSE_LAYER_ELEMENT_OTHER;
+ }
+ if (name == ufbxi_Shape) return UFBXI_PARSE_SHAPE;
+ break;
+
+ case UFBXI_PARSE_DEFORMER:
+ if (!strcmp(name, "AssociateModel")) return UFBXI_PARSE_ASSOCIATE_MODEL;
+ break;
+
+ case UFBXI_PARSE_LEGACY_MEDIA:
+ if (name == ufbxi_Video) return UFBXI_PARSE_LEGACY_VIDEO;
+ break;
+
+ case UFBXI_PARSE_LEGACY_VIDEO:
+ return UFBXI_PARSE_VIDEO;
+
+ case UFBXI_PARSE_LEGACY_MODEL:
+ if (name == ufbxi_GeometryUVInfo) return UFBXI_PARSE_GEOMETRY_UV_INFO;
+ if (name == ufbxi_Link) return UFBXI_PARSE_LEGACY_LINK;
+ if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
+ if (name == ufbxi_Shape) return UFBXI_PARSE_SHAPE;
+ break;
+
+ case UFBXI_PARSE_POSE:
+ if (name == ufbxi_PoseNode) return UFBXI_PARSE_POSE_NODE;
+ break;
+
+ case UFBXI_PARSE_TAKES:
+ if (name == ufbxi_Take) return UFBXI_PARSE_TAKE;
+ break;
+
+ case UFBXI_PARSE_TAKE:
+ return UFBXI_PARSE_TAKE_OBJECT;
+
+ case UFBXI_PARSE_TAKE_OBJECT:
+ if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
+ break;
+
+ case UFBXI_PARSE_CHANNEL:
+ if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
+ break;
+
+ case UFBXI_PARSE_REFERENCES:
+ return UFBXI_PARSE_REFERENCE;
+
+ default:
+ break;
+
+ }
+
+ return UFBXI_PARSE_UNKNOWN;
+}
+
+static bool ufbxi_is_array_node(ufbxi_context *uc, ufbxi_parse_state parent, const char *name, ufbxi_array_info *info)
+{
+ info->flags = 0;
+
+ // Retain all arrays if user wants the DOM representation
+ if (uc->opts.retain_dom) {
+ info->flags |= UFBXI_ARRAY_FLAG_RESULT;
+ }
+
+ switch (parent) {
+
+ case UFBXI_PARSE_THUMBNAIL:
+ if (name == ufbxi_ImageData) {
+ info->type = 'c';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_GEOMETRY:
+ case UFBXI_PARSE_MODEL:
+ if (name == ufbxi_Vertices) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_PolygonVertexIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Edges) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ return true;
+ } else if (name == ufbxi_Indexes) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Points) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_KnotVector) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_KnotVectorU) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_KnotVectorV) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_PointsIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Normals) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LEGACY_MODEL:
+ if (name == ufbxi_Vertices) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_Normals) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_Materials) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_PolygonVertexIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Children) {
+ info->type = 's';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_ANIMATION_CURVE:
+ if (name == ufbxi_KeyTime) {
+ info->type = uc->opts.ignore_animation ? '-' : 'l';
+ return true;
+ } else if (name == ufbxi_KeyValueFloat) {
+ info->type = uc->opts.ignore_animation ? '-' : 'r';
+ return true;
+ } else if (name == ufbxi_KeyAttrFlags) {
+ info->type = uc->opts.ignore_animation ? '-' : 'i';
+ return true;
+ } else if (name == ufbxi_KeyAttrDataFloat) {
+ // The float data in a keyframe attribute array is represented as integers
+ // in versions >= 7200 as some of the elements aren't actually floats (!)
+ info->type = uc->from_ascii && uc->version >= 7200 ? 'i' : 'f';
+ if (uc->opts.ignore_animation) info->type = '-';
+ if (uc->from_ascii && uc->version < 7200) {
+ info->flags |= UFBXI_ARRAY_FLAG_ACCURATE_F32;
+ }
+ return true;
+ } else if (name == ufbxi_KeyAttrRefCount) {
+ info->type = uc->opts.ignore_animation ? '-' : 'i';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_TEXTURE:
+ if (!strcmp(name, "ModelUVTranslation") || !strcmp(name, "ModelUVScaling") || !strcmp(name, "Cropping")) {
+ info->type = uc->opts.retain_dom ? 'r' : '-';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_VIDEO:
+ if (name == ufbxi_Content) {
+ info->type = uc->opts.ignore_embedded ? '-' : 'C';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYERED_TEXTURE:
+ if (name == ufbxi_BlendModes) {
+ info->type = 'i';
+ info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
+ return true;
+ } else if (name == ufbxi_Alphas) {
+ info->type = 'r';
+ info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_SELECTION_NODE:
+ if (name == ufbxi_VertexIndexArray) {
+ info->type = 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_EdgeIndexArray) {
+ info->type = 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_PolygonIndexArray) {
+ info->type = 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_NORMAL:
+ if (name == ufbxi_Normals) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_NormalsIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_NormalsW) {
+ info->type = uc->retain_vertex_w ? 'r' : '-';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_BINORMAL:
+ if (name == ufbxi_Binormals) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_BinormalsIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_BinormalsW) {
+ info->type = uc->retain_vertex_w ? 'r' : '-';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_TANGENT:
+ if (name == ufbxi_Tangents) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_TangentsIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_TangentsW) {
+ info->type = uc->retain_vertex_w ? 'r' : '-';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_UV:
+ if (name == ufbxi_UV) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_UVIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_COLOR:
+ if (name == ufbxi_Colors) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_ColorIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE:
+ if (name == ufbxi_VertexCrease) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_VertexCreaseIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE:
+ if (name == ufbxi_EdgeCrease) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING:
+ if (name == ufbxi_Smoothing) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'b';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY:
+ if (name == ufbxi_Visibility) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'b';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP:
+ if (name == ufbxi_PolygonGroup) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_HOLE:
+ if (name == ufbxi_Hole) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'b';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_MATERIAL:
+ if (name == ufbxi_Materials) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LAYER_ELEMENT_OTHER:
+ if (name == ufbxi_TextureId) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
+ return true;
+ } else if (name == ufbxi_UV) {
+ info->type = uc->opts.retain_dom ? 'r' : '-';
+ return true;
+ } else if (name == ufbxi_UVIndex) {
+ info->type = uc->opts.retain_dom ? 'i' : '-';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_GEOMETRY_UV_INFO:
+ if (name == ufbxi_TextureUV) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ } else if (name == ufbxi_TextureUVVerticeIndex) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_SHAPE:
+ if (name == ufbxi_Indexes) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ if (name == ufbxi_Vertices) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ if (name == ufbxi_Normals) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_DEFORMER:
+ if (name == ufbxi_Transform) {
+ info->type = 'r';
+ return true;
+ } else if (name == ufbxi_TransformLink) {
+ info->type = 'r';
+ return true;
+ } else if (name == ufbxi_Indexes) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Weights) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_BlendWeights) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_FullWeights) {
+ info->type = 'r';
+ info->flags = (uint8_t)(info->flags | (uc->blender_full_weights ? UFBXI_ARRAY_FLAG_RESULT : UFBXI_ARRAY_FLAG_TMP_BUF));
+ return true;
+ } else if (!strcmp(name, "TransformAssociateModel")) {
+ info->type = uc->opts.retain_dom ? 'r' : '-';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_ASSOCIATE_MODEL:
+ if (name == ufbxi_Transform) {
+ info->type = uc->opts.retain_dom ? 'r' : '-';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_LEGACY_LINK:
+ if (name == ufbxi_Transform) {
+ info->type = 'r';
+ return true;
+ } else if (name == ufbxi_TransformLink) {
+ info->type = 'r';
+ return true;
+ } else if (name == ufbxi_Indexes) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'i';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ } else if (name == ufbxi_Weights) {
+ info->type = uc->opts.ignore_geometry ? '-' : 'r';
+ info->flags = UFBXI_ARRAY_FLAG_RESULT;
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_POSE_NODE:
+ if (name == ufbxi_Matrix) {
+ info->type = 'r';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_CHANNEL:
+ if (name == ufbxi_Key) {
+ info->type = uc->opts.ignore_animation ? '-' : 'd';
+ return true;
+ }
+ break;
+
+ case UFBXI_PARSE_AUDIO:
+ if (name == ufbxi_Content) {
+ info->type = uc->opts.ignore_embedded ? '-' : 'C';
+ return true;
+ }
+ break;
+
+ default:
+ if (name == ufbxi_BinaryData) {
+ info->type = uc->opts.ignore_embedded ? '-' : 'C';
+ return true;
+ }
+ break;
+
+ }
+
+ return false;
+}
+
+static ufbxi_noinline bool ufbxi_is_raw_string(ufbxi_context *uc, ufbxi_parse_state parent, const char *name, size_t index)
+{
+ (void)index;
+
+ switch (parent) {
+
+ case UFBXI_PARSE_ROOT:
+ if (name == ufbxi_Model) return true;
+ if (!strcmp(name, "FileId")) return true;
+ break;
+
+ case UFBXI_PARSE_FBX_HEADER_EXTENSION:
+ if (name == ufbxi_SceneInfo) return true;
+ break;
+
+ case UFBXI_PARSE_OBJECTS:
+ return true;
+
+ case UFBXI_PARSE_CONNECTIONS:
+ case UFBXI_PARSE_RELATIONS:
+ // Pre-7000 needs raw strings for "Name\x00\x01Type" pairs, post-7000 uses it only
+ // for properties that are non-raw by default.
+ return uc->version < 7000;
+
+ case UFBXI_PARSE_MODEL:
+ if (name == ufbxi_NodeAttributeName) return true;
+ if (name == ufbxi_Name) return true;
+ break;
+
+ case UFBXI_PARSE_VIDEO:
+ if (name == ufbxi_Content) return true;
+ break;
+
+ case UFBXI_PARSE_TEXTURE:
+ if (!strcmp(name, "TextureName")) return true;
+ if (name == ufbxi_Media) return true;
+ break;
+
+ case UFBXI_PARSE_GEOMETRY:
+ if (name == ufbxi_NodeAttributeName) return true;
+ if (name == ufbxi_Name) return true;
+ break;
+
+ case UFBXI_PARSE_NODE_ATTRIBUTE:
+ if (name == ufbxi_NodeAttributeName) return true;
+ if (name == ufbxi_Name) return true;
+ break;
+
+ case UFBXI_PARSE_POSE_NODE:
+ if (name == ufbxi_Node) return true;
+ break;
+
+ case UFBXI_PARSE_SELECTION_NODE:
+ if (name == ufbxi_Node) return true;
+ break;
+
+ case UFBXI_PARSE_UNKNOWN_OBJECT:
+ if (name == ufbxi_NodeAttributeName) return true;
+ if (name == ufbxi_Name) return true;
+ break;
+
+ case UFBXI_PARSE_COLLECTION:
+ if (!strcmp(name, "Member")) return true;
+ break;
+
+ case UFBXI_PARSE_AUDIO:
+ if (name == ufbxi_Content) return true;
+ break;
+
+ case UFBXI_PARSE_LEGACY_MODEL:
+ if (name == ufbxi_Material) return true;
+ if (name == ufbxi_Link) return true;
+ if (name == ufbxi_Name) return true;
+ break;
+
+ case UFBXI_PARSE_LEGACY_SWITCHER:
+ if (!strcmp(name, "CameraIndexName")) return true;
+ break;
+
+ case UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE:
+ if (name == ufbxi_SceneInfo) return true;
+ break;
+
+ case UFBXI_PARSE_REFERENCE:
+ if (!strcmp(name, "Object")) return true;
+ break;
+
+ case UFBXI_PARSE_TAKE:
+ if (name == ufbxi_Model) return true;
+ break;
+
+ default:
+ break;
+
+ }
+
+ return false;
+}
+
+// -- Binary parsing
+
+ufbxi_nodiscard static ufbxi_noinline char *ufbxi_swap_endian(ufbxi_context *uc, const void *src, size_t count, size_t elem_size)
+{
+ ufbxi_dev_assert(elem_size > 1);
+ size_t total_size = count * elem_size;
+ ufbxi_check_return(!ufbxi_does_overflow(total_size, count, elem_size), NULL);
+ if (uc->swap_arr_size < total_size) {
+ ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->swap_arr, &uc->swap_arr_size, total_size), NULL);
+ }
+ char *dst = uc->swap_arr, *d = dst;
+
+ const char *s = (const char*)src;
+ switch (elem_size) {
+ case 2:
+ ufbxi_nounroll for (size_t i = 0; i < count; i++) {
+ d[0] = s[1]; d[1] = s[0];
+ d += 2; s += 2;
+ }
+ break;
+ case 4:
+ ufbxi_nounroll for (size_t i = 0; i < count; i++) {
+ d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0];
+ d += 4; s += 4;
+ }
+ break;
+ case 8:
+ ufbxi_nounroll for (size_t i = 0; i < count; i++) {
+ d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4];
+ d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0];
+ d += 8; s += 8;
+ }
+ break;
+ default:
+ ufbxi_unreachable("Bad endian swap size");
+ }
+
+ return dst;
+}
+
+// Swap the endianness of an array typed with a lowercase letter
+ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_swap_endian_array(ufbxi_context *uc, const void *src, size_t count, char type)
+{
+ switch (type) {
+ case 'i': case 'f': return ufbxi_swap_endian(uc, src, count, 4);
+ case 'l': case 'd': return ufbxi_swap_endian(uc, src, count, 8);
+ default: return (const char*)src;
+ }
+}
+
+// Swap the endianness of a single value (shallow, swaps string/array header words)
+ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_swap_endian_value(ufbxi_context *uc, const void *src, char type)
+{
+ switch (type) {
+ case 'Y': return ufbxi_swap_endian(uc, src, 1, 2);
+ case 'I': case 'F': return ufbxi_swap_endian(uc, src, 1, 4);
+ case 'L': case 'D': return ufbxi_swap_endian(uc, src, 1, 8);
+ case 'S': case 'R': return ufbxi_swap_endian(uc, src, 1, 4);
+ case 'i': case 'l': case 'f': case 'd': case 'b': return ufbxi_swap_endian(uc, src, 3, 4);
+ default: return (const char*)src;
+ }
+}
+
+// Read and convert a post-7000 FBX data array into a different format. `src_type` may be equal to `dst_type`
+// if the platform is not binary compatible with the FBX data representation.
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_binary_convert_array(ufbxi_context *maybe_uc, char src_type, char dst_type, const void *src, void *dst, size_t size)
+{
+ // TODO: We might want to use the slow path if the machine float/double doesn't match IEEE 754!
+ // Convert commented out lines under some `#if UFBX_NON_IEE754` define or something.
+ if (src_type == dst_type) {
+ ufbx_assert(maybe_uc && maybe_uc->file_big_endian != maybe_uc->local_big_endian);
+ src = ufbxi_swap_endian_array(maybe_uc, src, size, src_type);
+ ufbxi_check_err(&maybe_uc->error, src);
+ memcpy(dst, src, size * ufbxi_array_type_size(dst_type));
+ return 1;
+ }
+
+ if (maybe_uc && maybe_uc->file_big_endian) {
+ src = ufbxi_swap_endian_array(maybe_uc, src, size, src_type);
+ ufbxi_check_err(&maybe_uc->error, src);
+ }
+
+ switch (dst_type)
+ {
+
+ #define ufbxi_convert_loop_fast(m_dst, m_cast, m_size, m_expr) do { \
+ const char *val = (const char*)src, *val_end = val + size*m_size; \
+ m_dst *d = (m_dst*)dst; \
+ while (val != val_end) { *d++ = m_cast(m_expr); val += m_size; } \
+ } while (0)
+
+ #define ufbxi_convert_loop_slow(m_dst, m_cast, m_size, m_expr) do { \
+ const char *val = (const char*)src, *val_end = val + size*m_size; \
+ m_dst *d = (m_dst*)dst; \
+ ufbxi_nounroll while (val != val_end) { *d++ = m_cast(m_expr); val += m_size; } \
+ } while (0)
+
+ case 'c':
+ switch (src_type) {
+ // case 'c': ufbxi_convert_loop_fast(char, (char), 1, *val != 0); break;
+ case 'i': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 4, (uint8_t)ufbxi_read_i32(val)); break;
+ case 'l': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 8, (uint8_t)ufbxi_read_i64(val)); break;
+ case 'f': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 4, (uint8_t)ufbxi_read_f32(val)); break;
+ case 'd': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 8, (uint8_t)ufbxi_read_f64(val)); break;
+ default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
+ }
+ break;
+
+ case 'i':
+ switch (src_type) {
+ case 'c': ufbxi_convert_loop_slow(int32_t, (int32_t), 1, *val); break;
+ // case 'i': ufbxi_convert_loop_slow(int32_t, (int32_t), 4, ufbxi_read_i32(val)); break;
+ case 'l': ufbxi_convert_loop_slow(int32_t, (int32_t), 8, ufbxi_read_i64(val)); break;
+ case 'f': ufbxi_convert_loop_slow(int32_t, ufbxi_f64_to_i32, 4, ufbxi_read_f32(val)); break;
+ case 'd': ufbxi_convert_loop_slow(int32_t, ufbxi_f64_to_i32, 8, ufbxi_read_f64(val)); break;
+ default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
+ }
+ break;
+
+ case 'l':
+ switch (src_type) {
+ case 'c': ufbxi_convert_loop_slow(int64_t, (int64_t), 1, *val); break;
+ case 'i': ufbxi_convert_loop_slow(int64_t, (int64_t), 4, ufbxi_read_i32(val)); break;
+ // case 'l': ufbxi_convert_loop_slow(int64_t, (int64_t), 8, ufbxi_read_i64(val)); break;
+ case 'f': ufbxi_convert_loop_slow(int64_t, ufbxi_f64_to_i64, 4, ufbxi_read_f32(val)); break;
+ case 'd': ufbxi_convert_loop_slow(int64_t, ufbxi_f64_to_i64, 8, ufbxi_read_f64(val)); break;
+ default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
+ }
+ break;
+
+ case 'f':
+ switch (src_type) {
+ case 'c': ufbxi_convert_loop_slow(float, (float), 1, *val); break;
+ case 'i': ufbxi_convert_loop_slow(float, (float), 4, ufbxi_read_i32(val)); break;
+ case 'l': ufbxi_convert_loop_slow(float, (float), 8, ufbxi_read_i64(val)); break;
+ // case 'f': ufbxi_convert_loop_slow(float, (float), 4, ufbxi_read_f32(val)); break;
+ case 'd': ufbxi_convert_loop_fast(float, (float), 8, ufbxi_read_f64(val)); break;
+ default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
+ }
+ break;
+
+ case 'd':
+ switch (src_type) {
+ case 'c': ufbxi_convert_loop_slow(double, (double), 1, *val); break;
+ case 'i': ufbxi_convert_loop_slow(double, (double), 4, ufbxi_read_i32(val)); break;
+ case 'l': ufbxi_convert_loop_slow(double, (double), 8, ufbxi_read_i64(val)); break;
+ case 'f': ufbxi_convert_loop_fast(double, (double), 4, ufbxi_read_f32(val)); break;
+ // case 'd': ufbxi_convert_loop_slow(double, (double), 8, ufbxi_read_f64(val)); break;
+ default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
+ }
+ break;
+
+ default: return 0;
+
+ }
+
+ return 1;
+}
+
+// Read pre-7000 separate properties as an array.
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_binary_parse_multivalue_array(ufbxi_context *uc, char dst_type, void *dst, size_t size, ufbxi_buf *tmp_buf)
+{
+ if (size == 0) return 1;
+ const char *val;
+ size_t val_size;
+
+ bool file_big_endian = uc->file_big_endian;
+
+ #define ufbxi_convert_parse_fast(m_dst, m_type, m_expr) do { \
+ m_dst *d = (m_dst*)dst; \
+ for (; base < size; base++) { \
+ val = ufbxi_peek_bytes(uc, 13); \
+ ufbxi_check(val); \
+ if (*val != m_type) break; \
+ val++; \
+ *d++ = (m_dst)(m_expr); \
+ ufbxi_consume_bytes(uc, 1 + sizeof(m_dst)); \
+ } \
+ } while (0)
+
+ // String array special case
+ if (dst_type == 's' || dst_type == 'S' || dst_type == 'C') {
+ bool raw = dst_type == 's';
+ ufbx_string *d = (ufbx_string*)dst;
+ for (size_t i = 0; i < size; i++) {
+ val = ufbxi_peek_bytes(uc, 13);
+ ufbxi_check(val);
+ char type = *val++;
+ ufbxi_check(type == 'S' || type == 'R');
+ if (file_big_endian) {
+ val = ufbxi_swap_endian_value(uc, val, type);
+ ufbxi_check(val);
+ }
+ size_t len = ufbxi_read_u32(val);
+ ufbxi_consume_bytes(uc, 5);
+ d->data = ufbxi_read_bytes(uc, len);
+ d->length = len;
+ ufbxi_check(d->data);
+ if (dst_type == 'C') {
+ ufbxi_buf *buf = size == 1 || uc->opts.retain_dom ? &uc->result : tmp_buf;
+ d->data = ufbxi_push_copy(buf, char, len, d->data);
+ ufbxi_check(d->data);
+ } else {
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, d, raw));
+ }
+ d++;
+ }
+ return 1;
+ }
+
+ // Optimize a couple of common cases
+ size_t base = 0;
+ if (!file_big_endian) {
+ switch (dst_type) {
+ case 'i': ufbxi_convert_parse_fast(int32_t, 'I', ufbxi_read_i32(val)); break;
+ case 'l': ufbxi_convert_parse_fast(int64_t, 'L', ufbxi_read_i64(val)); break;
+ case 'f': ufbxi_convert_parse_fast(float, 'F', ufbxi_read_f32(val)); break;
+ case 'd': ufbxi_convert_parse_fast(double, 'D', ufbxi_read_f64(val)); break;
+ default: break; // Fallthrough to rest
+ }
+
+ // Early return if we handled everything
+ if (base == size) return 1;
+ }
+
+ switch (dst_type)
+ {
+
+ #define ufbxi_convert_parse(m_cast, m_size, m_expr) \
+ *d++ = m_cast(m_expr); val_size = m_size + 1; \
+
+ #define ufbxi_convert_parse_switch(m_dst, m_cast_int, m_cast_float) do { \
+ m_dst *d = (m_dst*)dst + base; \
+ for (size_t i = base; i < size; i++) { \
+ val = ufbxi_peek_bytes(uc, 13); \
+ ufbxi_check(val); \
+ char type = *val++; \
+ if (file_big_endian) { \
+ val = ufbxi_swap_endian_value(uc, val, type); \
+ ufbxi_check(val); \
+ } \
+ switch (type) { \
+ case 'C': \
+ case 'B': ufbxi_convert_parse(m_cast_int, 1, *val); break; \
+ case 'Y': ufbxi_convert_parse(m_cast_int, 2, ufbxi_read_i16(val)); break; \
+ case 'I': ufbxi_convert_parse(m_cast_int, 4, ufbxi_read_i32(val)); break; \
+ case 'L': ufbxi_convert_parse(m_cast_int, 8, ufbxi_read_i64(val)); break; \
+ case 'F': ufbxi_convert_parse(m_cast_float, 4, ufbxi_read_f32(val)); break; \
+ case 'D': ufbxi_convert_parse(m_cast_float, 8, ufbxi_read_f64(val)); break; \
+ default: ufbxi_fail("Bad multivalue array type"); \
+ } \
+ ufbxi_consume_bytes(uc, val_size); \
+ } \
+ } while (0)
+
+ case 'c': ufbxi_convert_parse_switch(uint8_t, (uint8_t), (uint8_t)); break;
+ case 'i': ufbxi_convert_parse_switch(int32_t, (int32_t), ufbxi_f64_to_i32); break;
+ case 'l': ufbxi_convert_parse_switch(int64_t, (int64_t), ufbxi_f64_to_i64); break;
+ case 'f': ufbxi_convert_parse_switch(float, (float), (float)); break;
+ case 'd': ufbxi_convert_parse_switch(double, (double), (double)); break;
+
+ default: return 0;
+
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static void *ufbxi_push_array_data(ufbxi_context *uc, const ufbxi_array_info *info, size_t size, ufbxi_buf *tmp_buf)
+{
+ size_t elem_size = ufbxi_array_type_size(info->type);
+ uint32_t flags = info->flags;
+ if (flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) {
+ ufbxi_check_return(size <= SIZE_MAX - 4, NULL);
+ size += 4;
+ }
+
+ // The array may be pushed either to the result or temporary buffer depending
+ // if it's already in the right format
+ ufbxi_buf *arr_buf = tmp_buf;
+ if (flags & UFBXI_ARRAY_FLAG_RESULT) arr_buf = &uc->result;
+ else if (flags & UFBXI_ARRAY_FLAG_TMP_BUF) arr_buf = &uc->tmp;
+ char *data = (char*)ufbxi_push_size(arr_buf, elem_size, size);
+ ufbxi_check_return(data, NULL);
+
+ if (flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) {
+ memset(data, 0, elem_size * 4);
+ data += elem_size * 4;
+ }
+
+ return data;
+}
+
+ufbxi_noinline static void ufbxi_postprocess_bool_array(char *data, size_t size)
+{
+ ufbxi_for(char, b, (char*)data, size) {
+ *b = (char)(*b != 0);
+ }
+}
+
+typedef struct {
+ size_t encoded_size;
+ size_t src_elem_size;
+ size_t array_size;
+ char src_type;
+ char dst_type;
+ char arr_type;
+ const void *encoded_data;
+ void *decoded_data;
+ void *dst_data;
+ ufbx_inflate_retain *inflate_retain;
+} ufbxi_deflate_task;
+
+static bool ufbxi_deflate_task_fn(ufbxi_task *task)
+{
+ ufbxi_deflate_task *t = (ufbxi_deflate_task*)task->data;
+
+ ufbx_inflate_input input; // ufbxi_uninit
+ input.total_size = t->encoded_size;
+ input.data = t->encoded_data;
+ input.data_size = t->encoded_size;
+ input.no_header = false;
+ input.no_checksum = false;
+ input.internal_fast_bits = 0;
+ input.progress_cb.fn = NULL;
+ input.progress_cb.user = NULL;
+ input.progress_size_before = 0;
+ input.progress_size_after = 0;
+ input.progress_interval_hint = 0;
+ input.buffer = NULL;
+ input.buffer_size = 0;
+ input.read_fn = NULL;
+ input.read_user = NULL;
+
+ size_t decoded_data_size = t->src_elem_size * t->array_size;
+ ptrdiff_t res = ufbx_inflate(t->decoded_data, decoded_data_size, &input, t->inflate_retain);
+ if (res == -28) {
+ task->error = "Cancelled";
+ return false;
+ } else if (res != (ptrdiff_t)decoded_data_size) {
+ task->error = "Bad DEFLATE data";
+ return false;
+ }
+
+ if (t->decoded_data != t->dst_data) {
+ int ok = ufbxi_binary_convert_array(NULL, t->src_type, t->dst_type, t->decoded_data, t->dst_data, t->array_size);
+ if (!ok) {
+ task->error = "Failed to convert array";
+ return false;
+ }
+ }
+
+ if (t->arr_type == 'b') {
+ ufbxi_postprocess_bool_array((char*)t->dst_data, t->array_size);
+ }
+
+ return true;
+}
+
+// Recursion limited by check at the start
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_binary_parse_node(ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive)
+ ufbxi_recursive_function(int, ufbxi_binary_parse_node, (uc, depth, parent_state, p_end, tmp_buf, recursive), UFBXI_MAX_NODE_DEPTH + 1,
+ (ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive))
+{
+ // https://code.blender.org/2013/08/fbx-binary-file-format-specification
+ // Parse an FBX document node in the binary format
+ ufbxi_check(depth < UFBXI_MAX_NODE_DEPTH);
+
+ // Parse the node header, post-7500 versions use 64-bit values for most
+ // header fields.
+ uint64_t end_offset, num_values64, values_len;
+ uint8_t name_len;
+ size_t header_size = (uc->version >= 7500) ? 25 : 13;
+ const char *header = ufbxi_read_bytes(uc, header_size), *header_words = header;
+ ufbxi_check(header);
+ if (uc->version >= 7500) {
+ if (uc->file_big_endian) {
+ header_words = ufbxi_swap_endian(uc, header_words, 3, 8);
+ ufbxi_check(header_words);
+ }
+ end_offset = ufbxi_read_u64(header_words + 0);
+ num_values64 = ufbxi_read_u64(header_words + 8);
+ values_len = ufbxi_read_u64(header_words + 16);
+ name_len = ufbxi_read_u8(header + 24);
+ } else {
+ if (uc->file_big_endian) {
+ header_words = ufbxi_swap_endian(uc, header_words, 3, 4);
+ ufbxi_check(header_words);
+ }
+ end_offset = ufbxi_read_u32(header_words + 0);
+ num_values64 = ufbxi_read_u32(header_words + 4);
+ values_len = ufbxi_read_u32(header_words + 8);
+ name_len = ufbxi_read_u8(header + 12);
+ }
+
+ ufbxi_check(num_values64 <= UINT32_MAX);
+ uint32_t num_values = (uint32_t)num_values64;
+
+ // If `end_offset` and `name_len` is zero we treat as the node as a NULL-sentinel
+ // that terminates a node list.
+ if (end_offset == 0 && name_len == 0) {
+ *p_end = true;
+ return 1;
+ }
+
+ // Update estimated end offset if possible
+ if (end_offset > uc->progress_bytes_total) {
+ uc->progress_bytes_total = end_offset;
+ }
+
+ // Push the parsed node into the `tmp_stack` buffer, the nodes will be popped by
+ // calling code after its done parsing all of it's children.
+ ufbxi_node *node = ufbxi_push_zero(&uc->tmp_stack, ufbxi_node, 1);
+ ufbxi_check(node);
+
+ // Parse and intern the name to the string pool.
+ const char *name = ufbxi_read_bytes(uc, name_len);
+ ufbxi_check(name);
+ name = ufbxi_push_string(&uc->string_pool, name, name_len, NULL, true);
+ ufbxi_check(name);
+ node->name_len = name_len;
+ node->name = name;
+
+ uint64_t values_end_offset = ufbxi_get_read_offset(uc) + values_len;
+
+ // Check if the values of the node we're parsing currently should be
+ // treated as an array.
+ ufbxi_array_info arr_info;
+ if (ufbxi_is_array_node(uc, parent_state, name, &arr_info)) {
+
+ // Normalize the array type (eg. 'r' to 'f'/'d' depending on the build)
+ // and get the per-element size of the array.
+ // Boolean arrays 'b' are normalized to 'c' as they are postprocessed
+ // below based on `arr_info.type`.
+ char dst_type = ufbxi_normalize_array_type(arr_info.type, 'c');
+
+ ufbxi_value_array *arr = ufbxi_push(tmp_buf, ufbxi_value_array, 1);
+ ufbxi_check(arr);
+
+ node->value_type_mask = UFBXI_VALUE_ARRAY;
+ node->array = arr;
+ arr->type = ufbxi_normalize_array_type(arr_info.type, 'b');
+
+ // Peek the first bytes of the array. We can always look at least 13 bytes
+ // ahead safely as valid FBX files must end in a 13/25 byte NULL record.
+ const char *data = ufbxi_peek_bytes(uc, 13);
+ ufbxi_check(data);
+
+ // Check if the data type is one of the explicit array types (post-7000).
+ // Otherwise we form the array by concatenating all the normal values of the
+ // node (pre-7000)
+ char c = data[0];
+
+ // HACK: Override the "type" if either the array is empty or we want to
+ // specifically ignore the contents.
+ if (num_values == 0) c = '0';
+ if (dst_type == '-') c = '-';
+
+ bool deferred = false;
+
+ if (c=='c' || c=='b' || c=='i' || c=='l' || c =='f' || c=='d') {
+
+ const char *arr_words = data + 1;
+ if (uc->file_big_endian) {
+ arr_words = ufbxi_swap_endian(uc, arr_words, 3, 4);
+ ufbxi_check(arr_words);
+ }
+
+ // Parse the array header from the prefix we already peeked above.
+ char src_type = data[0];
+ uint32_t size = ufbxi_read_u32(arr_words + 0);
+ uint32_t encoding = ufbxi_read_u32(arr_words + 4);
+ uint32_t encoded_size = ufbxi_read_u32(arr_words + 8);
+ ufbxi_consume_bytes(uc, 13);
+
+ // Normalize the source type as well, but don't convert UFBX-specific
+ // 'r' to 'f'/'d', but fail later instead.
+ if (src_type != 'r') src_type = ufbxi_normalize_array_type(src_type, 'c');
+ size_t src_elem_size = ufbxi_array_type_size(src_type);
+ size_t decoded_data_size = src_elem_size * size;
+ ufbxi_check(!ufbxi_does_overflow(decoded_data_size, src_elem_size, size));
+
+ // Allocate `size` elements for the array.
+ char *arr_data = (char*)ufbxi_push_array_data(uc, &arr_info, size, tmp_buf);
+ ufbxi_check(arr_data);
+
+ uint64_t arr_begin = ufbxi_get_read_offset(uc);
+ ufbxi_check(UINT64_MAX - encoded_size > arr_begin);
+ uint64_t arr_end = arr_begin + encoded_size;
+ if (arr_end > uc->progress_bytes_total) {
+ uc->progress_bytes_total = arr_end;
+ }
+
+ // Threading
+ if (uc->parse_threaded && encoding == 1 && encoded_size >= UFBXI_MIN_THREADED_DEFLATE_BYTES && !uc->file_big_endian && !uc->local_big_endian) {
+ ufbxi_task *task = ufbxi_thread_pool_create_task(&uc->thread_pool, &ufbxi_deflate_task_fn);
+ if (task) {
+ ufbxi_deflate_task *t = ufbxi_push_zero(tmp_buf, ufbxi_deflate_task, 1);
+ ufbxi_check(t);
+
+ ufbxi_inflate_init_retain(uc->inflate_retain);
+
+ t->src_elem_size = src_elem_size;
+ t->encoded_size = encoded_size;
+ t->array_size = size;
+ t->src_type = src_type;
+ t->dst_type = dst_type;
+ t->arr_type = arr->type;
+ t->dst_data = arr_data;
+ t->inflate_retain = uc->inflate_retain;
+
+ if (!uc->read_fn) {
+ // From memory, no need to copy
+ t->encoded_data = uc->data;
+ ufbxi_check(ufbxi_skip_bytes(uc, encoded_size));
+ } else {
+ void *encoded_data = ufbxi_push(tmp_buf, char, encoded_size);
+ ufbxi_check(encoded_data);
+ ufbxi_check(ufbxi_read_to(uc, encoded_data, encoded_size));
+ t->encoded_data = encoded_data;
+ }
+
+ if (src_type != dst_type) {
+ t->decoded_data = ufbxi_push_size(tmp_buf, src_elem_size, size);
+ ufbxi_check(t->decoded_data);
+ } else {
+ t->decoded_data = arr_data;
+ }
+
+ task->data = t;
+ ufbxi_thread_pool_run_task(&uc->thread_pool, task);
+ deferred = true;
+ }
+ }
+
+ // If the source and destination types are equal and our build is binary-compatible
+ // with the FBX format we can read the decoded data directly into the array buffer.
+ // Otherwise we need a temporary buffer to decode the array into before conversion.
+ void *decoded_data = arr_data;
+ if (!deferred && (src_type != dst_type || uc->local_big_endian != uc->file_big_endian)) {
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, decoded_data_size));
+ decoded_data = uc->tmp_arr;
+ }
+
+ if (deferred) {
+ // Nop
+ } else if (encoding == 0) {
+ // Encoding 0: Plain binary data.
+ ufbxi_check(encoded_size == decoded_data_size);
+
+ // If the array is contained in the current read buffer and we need to convert
+ // the data anyway we can use the read buffer as the decoded array source, otherwise
+ // do a plain byte copy to the array/conversion buffer.
+ if (uc->yield_size + uc->data_size >= encoded_size && decoded_data != arr_data) {
+ // Yield right after this if we crossed the yield threshold
+ if (encoded_size > uc->yield_size) {
+ uc->data_size += uc->yield_size;
+ uc->yield_size = encoded_size;
+ uc->data_size -= uc->yield_size;
+ }
+
+ decoded_data = (void*)uc->data;
+ ufbxi_consume_bytes(uc, encoded_size);
+ } else {
+ ufbxi_check(ufbxi_read_to(uc, decoded_data, encoded_size));
+ }
+ } else if (encoding == 1) {
+ // Encoding 1: DEFLATE
+
+ ufbxi_pause_progress(uc);
+
+ // Inflate the data from the user-provided IO buffer / read callbacks
+ ufbx_inflate_input input;
+ input.total_size = encoded_size;
+ input.data = uc->data;
+ input.data_size = uc->data_size;
+ input.no_header = false;
+ input.no_checksum = false;
+ input.internal_fast_bits = 0;
+
+ if (uc->opts.progress_cb.fn) {
+ input.progress_cb = uc->opts.progress_cb;
+ input.progress_size_before = arr_begin;
+ input.progress_size_after = uc->progress_bytes_total - arr_end;
+ input.progress_interval_hint = uc->progress_interval;
+ } else {
+ input.progress_cb.fn = NULL;
+ input.progress_cb.user = NULL;
+ input.progress_size_before = 0;
+ input.progress_size_after = 0;
+ input.progress_interval_hint = 0;
+ }
+
+ // If the encoded array is larger than the data we have currently buffered
+ // we need to allow `ufbx_inflate()` to read from the IO callback. We can
+ // let `ufbx_inflate()` freely clobber our `read_buffer` as all the data
+ // in the buffer will be consumed. `ufbx_inflate()` always reads exactly
+ // the amount of bytes needed so we can continue reading from `read_fn` as
+ // usual (given that we clear the `uc->data/_size` buffer below).
+ // NOTE: We _cannot_ share `read_buffer` if we plan to read later from it
+ // as `ufbx_inflate()` overwrites parts of it with zeroes.
+ if (encoded_size > input.data_size) {
+ input.buffer = uc->read_buffer;
+ input.buffer_size = uc->read_buffer_size;
+ input.read_fn = uc->read_fn;
+ input.read_user = uc->read_user;
+ uc->data_offset += encoded_size - input.data_size;
+ uc->data += input.data_size;
+ uc->data_size = 0;
+ } else {
+ input.buffer = NULL;
+ input.buffer_size = 0;
+ input.read_fn = NULL;
+ input.read_user = NULL;
+ uc->data += encoded_size;
+ uc->data_size -= encoded_size;
+ ufbxi_check(ufbxi_resume_progress(uc));
+ }
+
+ ptrdiff_t res = ufbx_inflate(decoded_data, decoded_data_size, &input, uc->inflate_retain);
+ ufbxi_check_msg(res != -28, "Cancelled");
+ ufbxi_check_msg(res == (ptrdiff_t)decoded_data_size, "Bad DEFLATE data");
+
+ } else {
+ ufbxi_fail("Bad array encoding");
+ }
+
+ // Convert the decoded array if necessary.
+ if (!deferred && decoded_data != arr_data) {
+ ufbxi_check(ufbxi_binary_convert_array(uc, src_type, dst_type, decoded_data, arr_data, size));
+ }
+
+ arr->data = arr_data;
+ arr->size = size;
+
+ } else if (c == '0' || c == '-') {
+ // Ignore the array
+ arr->type = c == '-' ? '-' : dst_type;
+ arr->data = (char*)ufbxi_zero_size_buffer + 32;
+ arr->size = 0;
+ } else {
+ // Allocate `num_values` elements for the array and parse single values into it.
+ char *arr_data = (char*)ufbxi_push_array_data(uc, &arr_info, num_values, tmp_buf);
+ ufbxi_check(arr_data);
+ ufbxi_check(ufbxi_binary_parse_multivalue_array(uc, dst_type, arr_data, num_values, tmp_buf));
+ arr->data = arr_data;
+ arr->size = num_values;
+ }
+
+ // Post-process boolean arrays
+ if (!deferred && arr_info.type == 'b') {
+ ufbxi_postprocess_bool_array((char*)arr->data, arr->size);
+ }
+
+ } else {
+ // Parse up to UFBXI_MAX_NON_ARRAY_VALUES as plain values
+ num_values = ufbxi_min32(num_values, UFBXI_MAX_NON_ARRAY_VALUES);
+ ufbxi_value *vals = ufbxi_push(tmp_buf, ufbxi_value, num_values);
+ ufbxi_check(vals);
+ node->vals = vals;
+
+ uint32_t type_mask = 0;
+ for (size_t i = 0; i < (size_t)num_values; i++) {
+ // The file must end in a 13/25 byte NULL record, so we can peek
+ // up to 13 bytes safely here.
+ const char *data = ufbxi_peek_bytes(uc, 13);
+ ufbxi_check(data);
+
+ const char *value = data + 1;
+
+ char type = data[0];
+ if (uc->file_big_endian) {
+ value = ufbxi_swap_endian_value(uc, value, type);
+ ufbxi_check(value);
+ }
+
+ switch (type) {
+
+ case 'C': case 'B': case 'Z':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].f = (double)(vals[i].i = (int64_t)(uint8_t)value[0]);
+ ufbxi_consume_bytes(uc, 2);
+ break;
+
+ case 'Y':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].f = (double)(vals[i].i = ufbxi_read_i16(value));
+ ufbxi_consume_bytes(uc, 3);
+ break;
+
+ case 'I':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].f = (double)(vals[i].i = ufbxi_read_i32(value));
+ ufbxi_consume_bytes(uc, 5);
+ break;
+
+ case 'L':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].f = (double)(vals[i].i = ufbxi_read_i64(value));
+ ufbxi_consume_bytes(uc, 9);
+ break;
+
+ case 'F':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].i = ufbxi_f64_to_i64(vals[i].f = ufbxi_read_f32(value));
+ ufbxi_consume_bytes(uc, 5);
+ break;
+
+ case 'D':
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
+ vals[i].i = ufbxi_f64_to_i64(vals[i].f = ufbxi_read_f64(value));
+ ufbxi_consume_bytes(uc, 9);
+ break;
+
+ case 'S': case 'R':
+ {
+ uint32_t length = ufbxi_read_u32(value);
+ ufbxi_consume_bytes(uc, 5);
+ const char *str = ufbxi_read_bytes(uc, length);
+ ufbxi_check(str);
+
+ if (length == 0) {
+ vals[i].s.raw_data = ufbxi_empty_char;
+ vals[i].s.utf8_data = ufbxi_empty_char;
+ vals[i].s.raw_length = 0;
+ vals[i].s.utf8_length = 0;
+ } else {
+ bool non_ascii = false;
+ uint32_t hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
+ bool raw = ufbxi_is_raw_string(uc, parent_state, name, i);
+ ufbxi_check(ufbxi_push_sanitized_string(&uc->string_pool, &vals[i].s, str, length, hash, non_ascii, raw));
+ }
+
+ type_mask |= (uint32_t)UFBXI_VALUE_STRING << (i*2);
+ }
+ break;
+
+ // Treat arrays as non-values and skip them
+ case 'c': case 'b': case 'i': case 'l': case 'f': case 'd':
+ {
+ uint32_t encoded_size = ufbxi_read_u32(value + 8);
+ ufbxi_consume_bytes(uc, 13);
+ ufbxi_check(ufbxi_skip_bytes(uc, encoded_size));
+ }
+ break;
+
+ default:
+ ufbxi_fail("Bad value type");
+
+ }
+ }
+
+ node->value_type_mask = (uint16_t)type_mask;
+ }
+
+ // Skip over remaining values if necessary if we for example truncated
+ // the list of values or if there are values after an array
+ uint64_t offset = ufbxi_get_read_offset(uc);
+ ufbxi_check(offset <= values_end_offset);
+ if (offset < values_end_offset) {
+ ufbxi_check(ufbxi_skip_bytes(uc, values_end_offset - offset));
+ }
+
+ if (recursive) {
+ // Recursively parse the children of this node. Update the parse state
+ // to provide context for child node parsing.
+ ufbxi_parse_state parse_state = ufbxi_update_parse_state(parent_state, node->name);
+ uint32_t num_children = 0;
+ for (;;) {
+ // Stop at end offset
+ uint64_t current_offset = ufbxi_get_read_offset(uc);
+ if (current_offset >= end_offset) {
+ ufbxi_check(current_offset == end_offset || end_offset == 0);
+ break;
+ }
+
+ bool end = false;
+ ufbxi_check(ufbxi_binary_parse_node(uc, depth + 1, parse_state, &end, tmp_buf, true));
+ if (end) break;
+ num_children++;
+ }
+
+ // Pop children from `tmp_stack` to a contiguous array
+ node->num_children = num_children;
+ if (num_children > 0) {
+ node->children = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node, num_children);
+ ufbxi_check(node->children);
+ }
+ } else {
+ uint64_t current_offset = ufbxi_get_read_offset(uc);
+ uc->has_next_child = (current_offset < end_offset);
+ }
+
+ return 1;
+}
+
+#define UFBXI_BINARY_MAGIC_SIZE 22
+#define UFBXI_BINARY_HEADER_SIZE 27
+static const char ufbxi_binary_magic[] = "Kaydara FBX Binary \x00\x1a";
+
+// -- ASCII parsing
+
+#define UFBXI_ASCII_END '\0'
+#define UFBXI_ASCII_NAME 'N'
+#define UFBXI_ASCII_BARE_WORD 'B'
+#define UFBXI_ASCII_INT 'I'
+#define UFBXI_ASCII_FLOAT 'F'
+#define UFBXI_ASCII_STRING 'S'
+
+static ufbxi_noinline char ufbxi_ascii_refill(ufbxi_context *uc)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+ uc->data_offset += ufbxi_to_size(ua->src - uc->data_begin);
+ if (uc->read_fn) {
+ char *dst_buffer = NULL;
+ size_t dst_size = 0;
+
+ if (ua->retain_buf != NULL) {
+ dst_size = uc->opts.read_buffer_size;
+ dst_buffer = ufbxi_push(ua->retain_buf, char, dst_size);
+ ufbxi_check_return(dst_buffer, '\0');
+ ua->src_is_retained = true;
+ ua->src_buf = ua->retain_buf;
+ } else {
+ // Grow the read buffer if necessary
+ if (uc->read_buffer_size < uc->opts.read_buffer_size) {
+ size_t new_size = uc->opts.read_buffer_size;
+ ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->read_buffer, &uc->read_buffer_size, new_size), '\0');
+ }
+ dst_buffer = uc->read_buffer;
+ dst_size = uc->read_buffer_size;
+ ua->src_is_retained = false;
+ ua->src_buf = NULL;
+ }
+
+ // Read user data, return '\0' on EOF
+ // TODO: Very unoptimal for non-full-size reads in some cases
+ size_t num_read = uc->read_fn(uc->read_user, dst_buffer, dst_size);
+ ufbxi_check_return_msg(num_read != SIZE_MAX, '\0', "IO error");
+ ufbxi_check_return(num_read <= dst_size, '\0');
+ if (num_read == 0) return '\0';
+
+ uc->data = uc->data_begin = ua->src = dst_buffer;
+ ua->src_end = dst_buffer + num_read;
+ return *ua->src;
+ } else {
+ // If the user didn't specify a `read_fn()` treat anything
+ // past the initial data buffer as EOF.
+ uc->data = uc->data_begin = ua->src = "";
+ ua->src_end = ua->src + 1;
+ return '\0';
+ }
+}
+
+static ufbxi_noinline char ufbxi_ascii_yield(ufbxi_context *uc)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ char ret;
+ if (ua->src == ua->src_end) {
+ ret = ufbxi_ascii_refill(uc);
+ } else {
+ ret = *ua->src;
+ }
+
+ if (ufbxi_to_size(ua->src_end - ua->src) < uc->progress_interval) {
+ ua->src_yield = ua->src_end;
+ } else {
+ ua->src_yield = ua->src + uc->progress_interval;
+ }
+
+ // TODO: Unify these properly
+ uc->data = ua->src;
+ ufbxi_check_return(ufbxi_report_progress(uc), '\0');
+ return ret;
+}
+
+static ufbxi_forceinline char ufbxi_ascii_peek(ufbxi_context *uc)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+ if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
+ return *ua->src;
+}
+
+static ufbxi_forceinline char ufbxi_ascii_next(ufbxi_context *uc)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+ if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
+ ua->src++;
+ if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
+ return *ua->src;
+}
+
+static ufbxi_noinline uint32_t ufbxi_ascii_parse_version(ufbxi_context *uc)
+{
+ uint8_t digits[3];
+ uint32_t num_digits = 0;
+
+ char c = ufbxi_ascii_next(uc);
+
+ const char fmt[] = " FBX ?.?.?";
+ uint32_t ix = 0;
+ while (num_digits < 3) {
+ char ref = fmt[ix++];
+ switch (ref) {
+
+ // Digit
+ case '?':
+ if (c < '0' || c > '9') return 0;
+ digits[num_digits++] = (uint8_t)(c - '0');
+ c = ufbxi_ascii_next(uc);
+ break;
+
+ // Whitespace
+ case ' ':
+ while (c == ' ' || c == '\t') {
+ c = ufbxi_ascii_next(uc);
+ }
+ break;
+
+ // Literal character
+ default:
+ if (c != ref) return 0;
+ c = ufbxi_ascii_next(uc);
+ break;
+ }
+ }
+
+ if (num_digits != 3) return 0;
+ return 1000u*(uint32_t)digits[0] + 100u*(uint32_t)digits[1] + 10u*(uint32_t)digits[2];
+}
+
+static const uint32_t ufbxi_space_mask =
+ (1u << ((uint32_t)' ' - 1)) |
+ (1u << ((uint32_t)'\t' - 1)) |
+ (1u << ((uint32_t)'\r' - 1)) |
+ (1u << ((uint32_t)'\n' - 1)) ;
+
+ufbx_static_assert(space_codepoint,
+ (uint32_t)' ' <= 32u && (uint32_t)'\t' <= 32u &&
+ (uint32_t)'\r' <= 32u && (uint32_t)'\n' <= 32u);
+
+static ufbxi_forceinline bool ufbxi_is_space(char c)
+{
+ uint32_t v = (uint32_t)(uint8_t)c - 1;
+ return v < 32 && ((ufbxi_space_mask >> v) & 0x1) != 0;
+}
+
+static ufbxi_noinline char ufbxi_ascii_skip_whitespace(ufbxi_context *uc)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ // Ignore whitespace
+ char c = ufbxi_ascii_peek(uc);
+ for (;;) {
+ while (ufbxi_is_space(c)) {
+ c = ufbxi_ascii_next(uc);
+ }
+
+ // Line comment
+ if (c == ';') {
+
+ bool read_magic = false;
+ // FBX ASCII files begin with a magic comment of form "; FBX 7.7.0 project file"
+ // Try to extract the version number from the magic comment
+ if (!ua->read_first_comment) {
+ ua->read_first_comment = true;
+ uint32_t version = ufbxi_ascii_parse_version(uc);
+ if (version) {
+ uc->version = version;
+ ua->found_version = true;
+ read_magic = true;
+ }
+ }
+
+ c = ufbxi_ascii_next(uc);
+ while (c != '\n' && c != '\0') {
+ c = ufbxi_ascii_next(uc);
+ }
+ c = ufbxi_ascii_next(uc);
+
+ // Try to determine if this is a Blender 6100 ASCII file
+ if (read_magic) {
+ if (c == ';') {
+ char line[32];
+ size_t line_len = 0;
+
+ c = ufbxi_ascii_next(uc);
+ while (c != '\n' && c != '\0') {
+ if (line_len < sizeof(line)) {
+ line[line_len++] = c;
+ }
+ c = ufbxi_ascii_next(uc);
+ }
+
+ if (line_len >= 19 && !memcmp(line, " Created by Blender", 19)) {
+ uc->exporter = UFBX_EXPORTER_BLENDER_ASCII;
+ }
+ }
+ }
+
+ } else {
+ break;
+ }
+ }
+ return c;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_ascii_push_token_char(ufbxi_context *uc, ufbxi_ascii_token *token, char c)
+{
+ // Grow the string data buffer if necessary
+ if (token->str_len == token->str_cap) {
+ size_t len = ufbxi_max_sz(token->str_len + 1, 256);
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &token->str_data, &token->str_cap, len));
+ }
+
+ token->str_data[token->str_len++] = c;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_ascii_push_token_string(ufbxi_context *uc, ufbxi_ascii_token *token, const char *data, size_t length)
+{
+ // Grow the string data buffer if necessary
+ if (token->str_len + length >= token->str_cap) {
+ size_t len = ufbxi_max_sz(token->str_len + length, 256);
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &token->str_data, &token->str_cap, len));
+ }
+
+ memcpy(token->str_data + token->str_len, data, length);
+ token->str_len += length;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_skip_until(ufbxi_context *uc, char dst)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ for (;;) {
+ size_t buffered = ufbxi_to_size(ua->src_yield - ua->src);
+ const char *match = (const char*)memchr(ua->src, dst, buffered);
+ if (match) {
+ ua->src = match;
+ break;
+ } else {
+ ua->src += buffered;
+ }
+ if (buffered == 0) {
+ char c = ufbxi_ascii_yield(uc);
+ ufbxi_check(c != '\0');
+ }
+ }
+
+ return 1;
+}
+
+typedef struct {
+ const char *source;
+ size_t length;
+} ufbxi_ascii_span;
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_store_array(ufbxi_context *uc, ufbxi_buf *tmp_buf)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ ua->retain_buf = tmp_buf;
+
+ for (;;) {
+ size_t buffered = ufbxi_to_size(ua->src_yield - ua->src);
+ if (buffered == 0) {
+ char c = ufbxi_ascii_yield(uc);
+ ufbxi_check(c != '\0');
+ continue;
+ }
+
+ const char *begin = ua->src, *end;
+ const char *match = (const char*)memchr(begin, '}', buffered);
+ if (match) {
+ end = match;
+ } else {
+ end = begin + buffered;
+ }
+ ua->src = end;
+
+ size_t length = ufbxi_to_size(end - begin);
+ ufbxi_ascii_span *span = ufbxi_push(&uc->tmp_ascii_spans, ufbxi_ascii_span, 1);
+ ufbxi_check(span);
+ // Store the trailing '}' for parsing
+ if (match) length += 1;
+ span->length = length;
+ if (ua->src_is_retained || !uc->read_fn) {
+ span->source = begin;
+ } else {
+ span->source = ufbxi_push_copy(tmp_buf, char, length, begin);
+ ufbxi_check(span->source);
+ }
+
+ if (match) break;
+ }
+
+ ua->retain_buf = NULL;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_try_ignore_string(ufbxi_context *uc, ufbxi_ascii_token *token)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ char c = ufbxi_ascii_skip_whitespace(uc);
+ token->str_len = 0;
+
+ if (c == '"') {
+ // Replace `prev_token` with `token` but swap the buffers so `token` uses
+ // the now-unused string buffer of the old `prev_token`.
+ char *swap_data = ua->prev_token.str_data;
+ size_t swap_cap = ua->prev_token.str_cap;
+ ua->prev_token = ua->token;
+ ua->token.str_data = swap_data;
+ ua->token.str_cap = swap_cap;
+
+ token->type = UFBXI_ASCII_STRING;
+ // Skip opening quote
+ ufbxi_ascii_next(uc);
+ ufbxi_check(ufbxi_ascii_skip_until(uc, '"'));
+ // Skip closing quote
+ ufbxi_ascii_next(uc);
+ return true;
+ }
+
+ return false;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_next_token(ufbxi_context *uc, ufbxi_ascii_token *token)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ // Replace `prev_token` with `token` but swap the buffers so `token` uses
+ // the now-unused string buffer of the old `prev_token`.
+ char *swap_data = ua->prev_token.str_data;
+ size_t swap_cap = ua->prev_token.str_cap;
+ ua->prev_token = ua->token;
+ ua->token.str_data = swap_data;
+ ua->token.str_cap = swap_cap;
+
+ char c = ufbxi_ascii_skip_whitespace(uc);
+ token->str_len = 0;
+
+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') {
+ token->type = UFBXI_ASCII_BARE_WORD;
+ while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
+ || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '(' || c == ')') {
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
+ c = ufbxi_ascii_next(uc);
+ }
+
+ // Skip whitespace to find if there's a following ':'
+ c = ufbxi_ascii_skip_whitespace(uc);
+ if (c == ':') {
+ token->value.name_len = token->str_len;
+ token->type = UFBXI_ASCII_NAME;
+ ufbxi_ascii_next(uc);
+ }
+ } else if ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.') {
+ token->type = UFBXI_ASCII_INT;
+
+ token->negative = c == '-';
+ while ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E') {
+ if (c == '.' || c == 'e' || c == 'E') {
+ token->type = UFBXI_ASCII_FLOAT;
+ }
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
+ c = ufbxi_ascii_next(uc);
+ }
+
+ bool nan_like = false;
+ while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '#' || c == '(' || c == ')') {
+ nan_like = true;
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
+ c = ufbxi_ascii_next(uc);
+ }
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, '\0'));
+ if (nan_like) {
+ token->type = UFBXI_ASCII_FLOAT;
+ }
+
+ char *end;
+ if (token->type == UFBXI_ASCII_INT) {
+ token->value.i64 = ufbxi_parse_int64(token->str_data, &end);
+ ufbxi_check(end == token->str_data + token->str_len - 1);
+ } else if (token->type == UFBXI_ASCII_FLOAT) {
+ uint32_t flags = uc->double_parse_flags;
+ if (ua->parse_as_f32) flags = UFBXI_PARSE_DOUBLE_AS_BINARY32;
+ token->value.f64 = ufbxi_parse_double(token->str_data, token->str_len, &end, flags);
+ ufbxi_check(end == token->str_data + token->str_len - 1);
+ }
+ } else if (c == '"') {
+ token->type = UFBXI_ASCII_STRING;
+ c = ufbxi_ascii_next(uc);
+ while (c != '"') {
+
+ // Optimized string parsing for non-special characters
+ if (ua->src + 1 < ua->src_yield) {
+ const char *begin = ua->src;
+ const char *end = ua->src_yield;
+ const char *quot = (const char*)memchr(begin, '"', ufbxi_to_size(end - begin));
+ if (quot) end = quot;
+ const char *esc = (const char*)memchr(begin, '&', ufbxi_to_size(end - begin));
+ if (esc) end = esc;
+
+ if (begin < end) {
+ ufbxi_check(ufbxi_ascii_push_token_string(uc, token, begin, ufbxi_to_size(end - begin)));
+ ua->src = end;
+ c = ufbxi_ascii_peek(uc);
+ continue;
+ }
+ }
+
+ // Escape XML-like elements, funny enough there is no way to escape '&' itself, there is no `&amp`.
+ // '&quot;' -> '"'
+ // '&cr;' -> '\r'
+ // '&lf;' -> '\n'
+ if (c == '&') {
+ const char *entity = NULL;
+ char replacement = '\0';
+
+ c = ufbxi_ascii_next(uc);
+ switch (c) {
+ case 'q':
+ entity = "&quot;";
+ replacement = '"';
+ break;
+ case 'c':
+ entity = "&cr;";
+ replacement = '\r';
+ break;
+ case 'l':
+ entity = "&lf;";
+ replacement = '\n';
+ break;
+ default:
+ // As '&' is not escaped in any way just map '&' -> '&'
+ entity = "&";
+ replacement = '&';
+ break;
+ }
+
+ size_t step = 1;
+
+ ufbxi_dev_assert(entity && *entity);
+ // `entity` is a NULL terminated string longer than a single character
+ // cppcheck-suppress arrayIndexOutOfBounds
+ for (; entity[step]; step++) {
+ if (c != entity[step]) break;
+ c = ufbxi_ascii_next(uc);
+ }
+
+ if (entity[step] == '\0') {
+ // Full match: Push the replacement character
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, replacement));
+ } else {
+ // Partial match: Push the prefix we have skipped already
+ for (size_t i = 0; i < step; i++) {
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, entity[i]));
+ }
+ }
+ continue;
+ }
+
+ ufbxi_check(c != '\0');
+ ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
+ c = ufbxi_ascii_next(uc);
+ }
+ // Skip closing quote
+ char next = ufbxi_ascii_next(uc);
+
+ // Check if the next character is ':', in some legacy FBX files we have names with
+ // spaces, like `"Transport Tool Settings": { ... }`
+ if (next == ':') {
+ token->value.name_len = token->str_len;
+ token->type = UFBXI_ASCII_NAME;
+ ufbxi_ascii_next(uc);
+ }
+
+ } else {
+ // Single character token
+ token->type = c;
+ ufbxi_ascii_next(uc);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static int ufbxi_ascii_accept(ufbxi_context *uc, char type)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ if (ua->token.type == type) {
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_ascii_read_int_array(ufbxi_context *uc, char type, size_t *p_num_read)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+ if (ua->parse_as_f32) return 1;
+ size_t initial_items = uc->tmp_stack.num_items;
+
+ int64_t val;
+ if (ua->token.type == UFBXI_ASCII_INT) {
+ val = ua->token.value.i64;
+ } else {
+ return 1;
+ }
+
+ const char *src = ua->src;
+ const char *end = ua->src_yield;
+ const char *src_scan = src;
+
+ for (;;) {
+
+ // Skip '\s*,\s*' between array elements. If we don't find a comma after an element
+ // don't push it as we can't be 100% certain whether it's a part of the array.
+ while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
+ if (src_scan == end || *src_scan != ',') break;
+ src_scan++;
+ while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
+
+ // Found comma, commit to the position and push the previous value to the array
+ src = src_scan;
+ if (type == 'i') {
+ int32_t *v = ufbxi_push_fast(&uc->tmp_stack, int32_t, 1);
+ ufbxi_check(v);
+ *v = (int32_t)val;
+ } else if (type == 'l') {
+ int64_t *v = ufbxi_push_fast(&uc->tmp_stack, int64_t, 1);
+ ufbxi_check(v);
+ *v = (int64_t)val;
+ }
+
+ // Try to parse the next value, we don't commit this until we find a comma after it above.
+ size_t left = ufbxi_to_size(end - src_scan);
+ if (left < 32) break;
+
+ val = ufbxi_parse_int64(src_scan, (char**)&src_scan);
+ if (!src_scan) break;
+ }
+
+ // Resume conventional parsing if we moved `src`.
+ if (src != ua->src) {
+ ua->src = src;
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ }
+
+ *p_num_read = uc->tmp_stack.num_items - initial_items;
+ return 1;
+}
+
+typedef struct {
+ void *arr_data;
+ char arr_type;
+ size_t arr_size;
+ const ufbxi_ascii_span *spans;
+ size_t num_spans;
+ size_t offset;
+} ufbxi_ascii_array_task;
+
+ufbxi_noinline static const char *ufbxi_ascii_array_task_parse_floats(ufbxi_ascii_array_task *t, const char *src, const char *src_end, uint32_t parse_flags)
+{
+ size_t offset = t->offset;
+ float *dst_float = t->arr_type == 'f' ? (float*)t->arr_data + offset : NULL;
+ double *dst_double = t->arr_type == 'd' ? (double*)t->arr_data + offset : NULL;
+ ufbx_assert(dst_float || dst_double);
+ const char *src_begin = src;
+
+ while (src != src_end) {
+ while (ufbxi_is_space(*src)) src++;
+
+ // Try to parse the next value, we don't commit this until we find a comma after it above.
+ char *num_end = NULL;
+ double val = ufbxi_parse_double(src, ufbxi_to_size(src_end - src), &num_end, parse_flags);
+ if (!num_end) return src_begin;
+ src = num_end;
+
+ while (ufbxi_is_space(*src)) src++;
+ if (*src != ',') break;
+ src++;
+ src_begin = src;
+
+ if (offset >= t->arr_size) return NULL;
+ if (dst_double) {
+ *dst_double++ = val;
+ } else {
+ *dst_float++ = (float)val;
+ }
+ offset++;
+ }
+
+ t->offset = offset;
+ return src_begin;
+}
+
+ufbxi_noinline static const char *ufbxi_ascii_array_task_parse_ints(ufbxi_ascii_array_task *t, const char *src, const char *src_end)
+{
+ size_t offset = t->offset;
+ int32_t *dst32 = t->arr_type == 'i' ? (int32_t*)t->arr_data + offset : NULL;
+ int64_t *dst64 = t->arr_type == 'l' ? (int64_t*)t->arr_data + offset : NULL;
+ ufbx_assert(dst32 || dst64);
+ const char *src_begin = src;
+
+ while (src != src_end) {
+ while (ufbxi_is_space(*src)) src++;
+
+ int64_t val = ufbxi_parse_int64(src, (char**)&src);
+ if (!src) return NULL;
+
+ while (ufbxi_is_space(*src)) src++;
+ if (*src != ',') break;
+ src++;
+ src_begin = src;
+
+ if (offset >= t->arr_size) return NULL;
+ if (dst32) {
+ *dst32++ = (int32_t)val;
+ } else {
+ *dst64++ = val;
+ }
+ offset++;
+ }
+
+ t->offset = offset;
+ return src_begin;
+}
+
+ufbxi_noinline static const char *ufbxi_ascii_array_task_parse(ufbxi_ascii_array_task *t, const char *src, const char *src_end)
+{
+ if (t->arr_type == 'f' || t->arr_type == 'd') {
+ uint32_t flags = ufbxi_parse_double_init_flags();
+ return ufbxi_ascii_array_task_parse_floats(t, src, src_end, flags);
+ } else {
+ return ufbxi_ascii_array_task_parse_ints(t, src, src_end);
+ }
+}
+
+typedef enum {
+ UFBXI_ASCII_SCAN_STATE_VALUE,
+ UFBXI_ASCII_SCAN_STATE_WHITESPACE,
+ UFBXI_ASCII_SCAN_STATE_COMMENT,
+ UFBXI_ASCII_SCAN_STATE_COMMA,
+} ufbxi_ascii_scan_state;
+
+ufbxi_noinline static bool ufbxi_ascii_array_task_imp(ufbxi_ascii_array_task *t)
+{
+ // Temporary buffer for parsing between spans
+ char buffer[128]; // ufbxi_uninit
+ size_t buffer_len = 0;
+ bool buffer_value = false;
+
+ ufbxi_ascii_scan_state state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
+ ufbxi_for(const ufbxi_ascii_span, span, t->spans, t->num_spans) {
+ const char *src = span->source;
+ const char *end = src + span->length;
+
+ while (src != end) {
+
+ // State machine for skipping whitespace and comments, potentially
+ // between multiple spans.
+ while (src != end) {
+ char c = *src;
+ if (state == UFBXI_ASCII_SCAN_STATE_VALUE) {
+ if (buffer_len >= sizeof(buffer) - 1) return false;
+ if (c == '"') {
+ return false;
+ } else if (c == ';' || ufbxi_is_space(c)) {
+ state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
+ buffer[buffer_len] = ' ';
+ buffer_len++;
+ } else if (c == ',' || c == '}') {
+ state = UFBXI_ASCII_SCAN_STATE_COMMA;
+ buffer[buffer_len] = ',';
+ buffer_len++;
+ src++;
+ break;
+ } else {
+ buffer_value = true;
+ buffer[buffer_len] = c;
+ buffer_len++;
+ src++;
+ }
+ } else if (state == UFBXI_ASCII_SCAN_STATE_WHITESPACE) {
+ if (c == ';') {
+ state = UFBXI_ASCII_SCAN_STATE_COMMENT;
+ } else if (ufbxi_is_space(c)) {
+ src++;
+ } else {
+ state = UFBXI_ASCII_SCAN_STATE_VALUE;
+ }
+ } else if (state == UFBXI_ASCII_SCAN_STATE_COMMENT) {
+ if (c == '\n') {
+ state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
+ } else {
+ src++;
+ }
+ } else if (state == UFBXI_ASCII_SCAN_STATE_COMMA) {
+ state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
+ }
+ }
+
+ if (state == UFBXI_ASCII_SCAN_STATE_COMMA) {
+ // Parse a value from the buffer
+ if (buffer_value) {
+ const char *buffer_end = ufbxi_ascii_array_task_parse(t, buffer, buffer + buffer_len);
+ if (buffer_end == NULL || buffer_end == buffer) {
+ return false;
+ }
+ }
+
+ // If not at end, we are past the last comma, so try to find a
+ // safe range to parse.
+ if (src != end) {
+ const char *parse_end = end;
+ while (parse_end > src) {
+ if (parse_end[-1] == ',') break;
+ parse_end--;
+ }
+ if (src < parse_end) {
+ src = ufbxi_ascii_array_task_parse(t, src, parse_end);
+ if (src == NULL) return false;
+ }
+ }
+
+ buffer_len = 0;
+ buffer_value = false;
+ }
+ }
+ }
+
+ if (t->offset != t->arr_size) return false;
+
+ return true;
+}
+
+ufbxi_noinline static bool ufbxi_ascii_array_task_fn(ufbxi_task *task)
+{
+ ufbxi_ascii_array_task *t = (ufbxi_ascii_array_task *)task->data;
+ if (!ufbxi_ascii_array_task_imp(t)) {
+ task->error = "Threaded ASCII parse error";
+ return false;
+ }
+ return true;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_ascii_read_float_array(ufbxi_context *uc, char type, size_t *p_num_read)
+{
+ ufbxi_ascii *ua = &uc->ascii;
+ if (ua->parse_as_f32) return 1;
+
+ double val;
+ if (ua->token.type == UFBXI_ASCII_FLOAT) {
+ val = ua->token.value.f64;
+ } else if (ua->token.type == UFBXI_ASCII_INT) {
+ double fsign = !ua->token.value.i64 && ua->token.negative ? -1.0 : 1.0;
+ val = (double)ua->token.value.i64 * fsign;
+ } else {
+ return 1;
+ }
+
+ const char *src = ua->src;
+ const char *end = ua->src_yield;
+
+ uint32_t parse_flags = uc->double_parse_flags;
+
+ size_t initial_items = uc->tmp_stack.num_items;
+ const char *src_scan = src;
+ for (;;) {
+
+ // Skip '\s*,\s*' between array elements. If we don't find a comma after an element
+ // don't push it as we can't be 100% certain whether it's a part of the array.
+ while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
+ if (src_scan == end || *src_scan != ',') break;
+ src_scan++;
+ while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
+
+ // Found comma, commit to the position and push the previous value to the array
+ src = src_scan;
+ if (type == 'd') {
+ double *v = ufbxi_push_fast(&uc->tmp_stack, double, 1);
+ ufbxi_check(v);
+ *v = (double)val;
+ } else if (type == 'f') {
+ float *v = ufbxi_push_fast(&uc->tmp_stack, float, 1);
+ ufbxi_check(v);
+ *v = (float)val;
+ }
+
+ // Try to parse the next value, we don't commit this until we find a comma after it above.
+ char *num_end = NULL;
+ size_t left = ufbxi_to_size(end - src_scan);
+ val = ufbxi_parse_double(src_scan, left, &num_end, parse_flags);
+ if (!num_end || num_end == src_scan || num_end >= end) {
+ break;
+ }
+
+ src_scan = num_end;
+ }
+
+ // Resume conventional parsing if we moved `src`.
+ if (src != ua->src) {
+ ua->src = src;
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ }
+
+ *p_num_read = uc->tmp_stack.num_items - initial_items;
+ return 1;
+}
+
+ufbxi_noinline static int ufbxi_setup_base64(ufbxi_context *uc)
+{
+ uint8_t *table = ufbxi_push(&uc->tmp, uint8_t, 256);
+ ufbxi_check(table);
+ uc->base64_table = table;
+
+ memset(table, 0x80, 256);
+ ufbxi_nounroll for (char c = 'A'; c <= 'Z'; c++) table[(size_t)c] = (uint8_t)(c - 'A');
+ ufbxi_nounroll for (char c = 'a'; c <= 'z'; c++) table[(size_t)c] = (uint8_t)(26 + (c - 'a'));
+ ufbxi_nounroll for (char c = '0'; c <= '9'; c++) table[(size_t)c] = (uint8_t)(52 + (c - '0'));
+ table[(size_t)'+'] = 62;
+ table[(size_t)'/'] = 63;
+ table[(size_t)'='] = 0x40;
+
+ return 1;
+}
+
+ufbxi_noinline static int ufbxi_decode_base64(ufbxi_context *uc, ufbx_string *p_result, const char *src, size_t src_length, bool *p_failed)
+{
+ if (!uc->base64_table) ufbxi_check(ufbxi_setup_base64(uc));
+
+ uint8_t *table = uc->base64_table;
+ uint32_t error_mask = 0, pad_error = 0;
+
+ char *p = (char*)p_result->data;
+ for (size_t i = 0; i + 4 <= src_length; i += 4) {
+ uint32_t a = table[(size_t)(uint8_t)src[i + 0]];
+ uint32_t b = table[(size_t)(uint8_t)src[i + 1]];
+ uint32_t c = table[(size_t)(uint8_t)src[i + 2]];
+ uint32_t d = table[(size_t)(uint8_t)src[i + 3]];
+ pad_error = error_mask;
+ error_mask |= a | b | c | d;
+
+ p[0] = (char)(uint8_t)(a << 2 | b >> 4);
+ p[1] = (char)(uint8_t)(b << 4 | c >> 2);
+ p[2] = (char)(uint8_t)(c << 6 | d);
+ p += 3;
+ }
+
+ if (src_length >= 4) {
+ const char *end = src + src_length - 4;
+ uint32_t padding = 0;
+ padding |= end[0] == '=' ? 0x8 : 0x0;
+ padding |= end[1] == '=' ? 0x4 : 0x0;
+ padding |= end[2] == '=' ? 0x2 : 0x0;
+ padding |= end[3] == '=' ? 0x1 : 0x0;
+ if (padding <= 0x1) p -= padding; // "xxx=" or "xxxx"
+ else if (padding == 0x3) p -= 2; // "xx=="
+ else pad_error |= 0x40; // anything else
+ }
+
+ if (((error_mask & 0x80) != 0 || (pad_error & 0x40) != 0 || src_length % 4 != 0) && !*p_failed) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_BAD_BASE64_CONTENT, "Ignored bad base64 embedded content"));
+ *p_failed = true;
+ }
+
+ p_result->length = ufbxi_to_size(p - p_result->data);
+ return 1;
+}
+
+// Recursion limited by check at the start
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_parse_node(ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive)
+ ufbxi_recursive_function(int, ufbxi_ascii_parse_node, (uc, depth, parent_state, p_end, tmp_buf, recursive), UFBXI_MAX_NODE_DEPTH + 1,
+ (ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive))
+{
+ ufbxi_ascii *ua = &uc->ascii;
+
+ if (ua->token.type == '}') {
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ *p_end = true;
+ return 1;
+ }
+
+ if (ua->token.type == UFBXI_ASCII_END) {
+ ufbxi_check_msg(depth == 0, "Truncated file");
+ *p_end = true;
+ return 1;
+ }
+
+ // Parse the name eg. "Node:" token and intern the name
+ ufbxi_check(depth < UFBXI_MAX_NODE_DEPTH);
+ if (!uc->sure_fbx && depth == 0 && ua->token.type != UFBXI_ASCII_NAME) {
+ ufbxi_fail_msg("Expected a 'Name:' token", "Not an FBX file");
+ }
+ ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_NAME));
+ size_t name_len = ua->prev_token.value.name_len;
+ ufbxi_check(name_len <= 0xff);
+ const char *name = ufbxi_push_string(&uc->string_pool, ua->prev_token.str_data, ua->prev_token.str_len, NULL, true);
+ ufbxi_check(name);
+
+ // Push the parsed node into the `tmp_stack` buffer, the nodes will be popped by
+ // calling code after its done parsing all of it's children.
+ ufbxi_node *node = ufbxi_push_zero(&uc->tmp_stack, ufbxi_node, 1);
+ ufbxi_check(node);
+ node->name = name;
+ node->name_len = (uint8_t)name_len;
+
+ bool in_ascii_array = false;
+
+ uint32_t num_values = 0;
+ uint32_t type_mask = 0;
+
+ int arr_type = 0;
+ ufbxi_buf *arr_buf = NULL;
+ size_t arr_elem_size = 0;
+ bool arr_error = false;
+
+ // Check if the values of the node we're parsing currently should be
+ // treated as an array.
+ ufbxi_array_info arr_info;
+ if (ufbxi_is_array_node(uc, parent_state, name, &arr_info)) {
+ uint32_t flags = arr_info.flags;
+ arr_type = ufbxi_normalize_array_type(arr_info.type, 'b');
+ arr_buf = tmp_buf;
+ if (flags & UFBXI_ARRAY_FLAG_RESULT) arr_buf = &uc->result;
+ else if (flags & UFBXI_ARRAY_FLAG_TMP_BUF) arr_buf = &uc->tmp;
+
+ ufbxi_value_array *arr = ufbxi_push(tmp_buf, ufbxi_value_array, 1);
+ ufbxi_check(arr);
+ node->value_type_mask = UFBXI_VALUE_ARRAY;
+ node->array = arr;
+ arr->type = (char)arr_type;
+
+ // Parse array values using strtof() if the array destination is 32-bit float
+ // since KeyAttrDataFloat packs integer data (!) into floating point values so we
+ // should try to be as exact as possible.
+ if (arr_info.flags & UFBXI_ARRAY_FLAG_ACCURATE_F32) {
+ ua->parse_as_f32 = true;
+ }
+
+ arr_elem_size = ufbxi_array_type_size((char)arr_type);
+
+ if (arr_type != '-') {
+ // Force alignment for array contents: This allows us to use `ufbxi_push_fast()`
+ // in fast parsing functions.
+ ufbxi_check(ufbxi_push_size_zero(&uc->tmp_stack, 8, 1));
+
+ // Pad with 4 zero elements to make indexing with `-1` safe.
+ if ((flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) != 0) {
+ ufbxi_check(ufbxi_push_size_zero(&uc->tmp_stack, arr_elem_size, 4));
+ num_values += 4;
+ }
+ }
+ }
+
+ // Some fields in ASCII may have leading commas eg. `Content: , "base64-string"`
+ if (ua->token.type == ',') {
+ // HACK: If we are parsing an "array" that should be ignored, ie. `Content` when
+ // `opts.ignore_embedded == true` try to skip the next token string if possible.
+ if (arr_type == '-') {
+ if (!ufbxi_ascii_try_ignore_string(uc, &ua->token)) {
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ }
+ } else {
+ ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
+ }
+ }
+
+ ufbxi_parse_state parse_state = ufbxi_update_parse_state(parent_state, node->name);
+ ufbxi_value vals[UFBXI_MAX_NON_ARRAY_VALUES];
+
+ uint32_t deferred_size = 0;
+
+ // NOTE: Infinite loop to allow skipping the comma parsing via `continue`.
+ for (;;) {
+ ufbxi_ascii_token *tok = &ua->prev_token;
+
+ if (arr_type) {
+ size_t num_read = 0;
+ if (arr_type == 'f' || arr_type == 'd') {
+ ufbxi_check(ufbxi_ascii_read_float_array(uc, (char)arr_type, &num_read));
+ } else if (arr_type == 'i' || arr_type == 'l') {
+ ufbxi_check(ufbxi_ascii_read_int_array(uc, (char)arr_type, &num_read));
+ }
+ ufbxi_check(UINT32_MAX - num_values > num_read);
+ num_values += (uint32_t)num_read;
+ }
+
+ if (ufbxi_ascii_accept(uc, UFBXI_ASCII_STRING)) {
+
+ if (arr_type) {
+
+ if (arr_type == 's' || arr_type == 'S' || arr_type == 'C') {
+ bool raw = arr_type == 's';
+ ufbx_string *v = ufbxi_push(&uc->tmp_stack, ufbx_string, 1);
+ ufbxi_check(v);
+ if (arr_type == 'C') {
+ ufbxi_buf *buf = uc->opts.retain_dom ? &uc->result : tmp_buf;
+ size_t capacity = tok->str_len / 4 * 3 + 3;
+ v->data = ufbxi_push(buf, char, capacity);
+ ufbxi_check(v->data);
+ ufbxi_check(ufbxi_decode_base64(uc, v, tok->str_data, tok->str_len, &arr_error));
+ ufbx_assert(v->length <= capacity);
+ } else {
+ v->data = tok->str_data;
+ v->length = tok->str_len;
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, v, raw));
+ }
+ } else {
+ // Ignore strings in non-string arrays, decrement `num_values` as it will be
+ // incremented after the loop iteration is done to ignore it.
+ num_values--;
+ }
+
+ } else if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
+ type_mask |= (uint32_t)UFBXI_VALUE_STRING << (num_values*2);
+ ufbxi_value *v = &vals[num_values];
+
+ const char *str = tok->str_data;
+ size_t length = tok->str_len;
+ ufbxi_check(str);
+
+ if (length == 0) {
+ v->s.raw_data = ufbxi_empty_char;
+ v->s.utf8_data = ufbxi_empty_char;
+ v->s.raw_length = 0;
+ v->s.utf8_length = 0;
+ } else {
+ bool non_ascii = false;
+ uint32_t hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
+ bool raw = ufbxi_is_raw_string(uc, parent_state, name, num_values);
+ ufbxi_check(ufbxi_push_sanitized_string(&uc->string_pool, &v->s, str, length, hash, non_ascii, raw));
+ }
+ }
+
+ } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_INT)) {
+ int64_t val = tok->value.i64;
+ ufbx_real fsign = !val && tok->negative ? (ufbx_real)-1.0f : (ufbx_real)1.0f;
+
+ switch (arr_type) {
+
+ case 0:
+ // Parse version from comment if there was no magic comment
+ if (!ua->found_version && parse_state == UFBXI_PARSE_FBX_VERSION && num_values == 0) {
+ if (val >= 6000 && val <= 10000) {
+ ua->found_version = true;
+ uc->version = (uint32_t)val;
+ }
+ }
+
+ if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
+ ufbxi_value *v = &vals[num_values];
+ // False positive: `v->f` and `v->i` do not overlap in the union.
+ // cppcheck-suppress overlappingWriteUnion
+ v->f = (double)(v->i = val) * (double)fsign;
+ }
+ break;
+
+ case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
+ case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
+ case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = (int32_t)val; } break;
+ case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = (int64_t)val; } break;
+ case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val * (float)fsign; } break;
+ case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val * (double)fsign; } break;
+ case '-': num_values--; break;
+
+ default:
+ ufbxi_fail("Bad array dst type");
+
+ }
+
+ } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_FLOAT)) {
+ double val = tok->value.f64;
+
+ switch (arr_type) {
+
+ case 0:
+ if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
+ ufbxi_value *v = &vals[num_values];
+ // False positive: `v->f` and `v->i` do not overlap in the union.
+ // cppcheck-suppress overlappingWriteUnion
+ v->i = ufbxi_f64_to_i64(v->f = val);
+ }
+ break;
+
+ case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
+ case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
+ case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = ufbxi_f64_to_i32(val); } break;
+ case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = ufbxi_f64_to_i64(val); } break;
+ case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val; } break;
+ case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val; } break;
+ case '-': num_values--; break;
+
+ default:
+ ufbxi_fail("Bad array dst type");
+
+ }
+
+ } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_BARE_WORD)) {
+
+ int64_t val = 0;
+ double val_f = 0.0;
+ if (tok->str_len >= 1) {
+ val = (int64_t)tok->str_data[0];
+ val_f = (double)val;
+ if (tok->str_len > 1 && tok->str_len < 64) {
+ // Try to parse the bare word as NAN/INF
+ char str_data[64]; // ufbxi_uninit
+ size_t str_len = tok->str_len;
+ memcpy(str_data, tok->str_data, str_len);
+ str_data[str_len] = '\0';
+ double inf_nan;
+ char *end = NULL;
+ if (ufbxi_parse_inf_nan(&inf_nan, str_data, str_len, &end) && end == str_data + str_len) {
+ val = 0;
+ val_f = inf_nan;
+ }
+ }
+ }
+
+ switch (arr_type) {
+
+ case 0:
+ if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
+ type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
+ ufbxi_value *v = &vals[num_values];
+ // False positive: `v->f` and `v->i` do not overlap in the union.
+ // cppcheck-suppress overlappingWriteUnion
+ v->i = val;
+ v->f = val_f;
+ }
+ break;
+
+ case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
+ case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
+ case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = (int32_t)val; } break;
+ case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = (int64_t)val; } break;
+ case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val_f; } break;
+ case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val_f; } break;
+ case '-': num_values--; break;
+
+ default:
+ ufbxi_fail("Bad array dst type");
+ }
+
+ } else if (ufbxi_ascii_accept(uc, '*')) {
+ // Parse a post-7000 ASCII array eg. "*3 { 1,2,3 }"
+ ufbxi_check(!in_ascii_array);
+ ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_INT));
+ int64_t count = ua->prev_token.value.i64;
+
+ if (ufbxi_ascii_accept(uc, '{')) {
+ ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_NAME));
+ in_ascii_array = true;
+
+ // Optimized array skipping and threaded parsing
+ if (arr_type == '-') {
+ ufbxi_check(ufbxi_ascii_skip_until(uc, '}'));
+ } else if (uc->parse_threaded && !uc->opts.force_single_thread_ascii_parsing
+ && !ua->parse_as_f32
+ && (arr_type == 'i' || arr_type == 'l' || arr_type == 'f' || arr_type == 'd')) {
+ // Don't bother with small arrays due to fixed overhead
+ if (count >= UFBXI_MIN_THREADED_ASCII_VALUES && count <= UINT32_MAX) {
+ deferred_size = (uint32_t)count - 1;
+ ufbxi_check(ufbxi_ascii_store_array(uc, tmp_buf));
+ }
+ }
+ }
+
+ // NOTE: This `continue` skips incrementing `num_values` and parsing
+ // a comma, continuing to parse the values in the array.
+ continue;
+ } else {
+ break;
+ }
+
+ // Add value and keep parsing if there's a comma. This part may be
+ // skipped if we enter an array block.
+ num_values++;
+ ufbxi_check(num_values < UINT32_MAX);
+ if (!ufbxi_ascii_accept(uc, ',')) break;
+ }
+
+ // Close the ASCII array if we are in one
+ if (in_ascii_array) {
+ ufbxi_check(ufbxi_ascii_accept(uc, '}'));
+ }
+
+ ua->parse_as_f32 = false;
+
+ if (arr_type) {
+ if (arr_type == '-') {
+ node->array->data = NULL;
+ node->array->size = 0;
+ } else {
+ void *arr_data = NULL;
+
+ if (deferred_size > 0) {
+ ufbxi_check(deferred_size < UINT32_MAX - num_values);
+ arr_data = ufbxi_push_size(arr_buf, arr_elem_size, num_values + deferred_size);
+ // Pop any previously pushed values
+ if (num_values > 0) {
+ ufbxi_pop_size(&uc->tmp_stack, arr_elem_size, num_values, arr_data, false);
+ }
+ } else if (arr_error) {
+ ufbxi_pop_size(&uc->tmp_stack, arr_elem_size, num_values, NULL, false);
+ num_values = 0;
+ arr_data = (void*)ufbxi_zero_size_buffer;
+ } else {
+ arr_data = ufbxi_push_pop_size(arr_buf, &uc->tmp_stack, arr_elem_size, num_values);
+ }
+ ufbxi_check(arr_data);
+ if (arr_info.flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) {
+ node->array->data = (char*)arr_data + 4*arr_elem_size;
+ node->array->size = num_values + deferred_size - 4;
+ } else {
+ node->array->data = arr_data;
+ node->array->size = num_values + deferred_size;
+ }
+
+ // Pop alignment helper
+ ufbxi_pop_size(&uc->tmp_stack, 8, 1, NULL, false);
+
+ // Deferred parsing
+ if (deferred_size > 0) {
+ size_t num_spans = uc->tmp_ascii_spans.num_items;
+ ufbxi_ascii_span *spans = ufbxi_push_pop(tmp_buf, &uc->tmp_ascii_spans, ufbxi_ascii_span, num_spans);
+ ufbxi_check(spans);
+
+ ufbxi_ascii_array_task t; // ufbxi_uninit
+ t.arr_data = (char*)arr_data + num_values * arr_elem_size;
+ t.arr_type = (char)arr_type;
+ t.arr_size = deferred_size;
+ t.num_spans = num_spans;
+ t.spans = spans;
+ t.offset = 0;
+
+ // TODO: Split these further
+ ufbxi_task *task = ufbxi_thread_pool_create_task(&uc->thread_pool, &ufbxi_ascii_array_task_fn);
+ if (task) {
+ task->data = ufbxi_push_copy(tmp_buf, ufbxi_ascii_array_task, 1, &t);
+ ufbxi_check(task->data);
+ ufbxi_thread_pool_run_task(&uc->thread_pool, task);
+ } else {
+ ufbxi_check_msg(ufbxi_ascii_array_task_imp(&t), "Threaded ASCII parse error");
+ }
+ }
+ }
+ } else {
+ num_values = ufbxi_min32(num_values, UFBXI_MAX_NON_ARRAY_VALUES);
+ node->value_type_mask = (uint16_t)type_mask;
+ node->vals = ufbxi_push_copy(tmp_buf, ufbxi_value, num_values, vals);
+ ufbxi_check(node->vals);
+ }
+
+ // Recursively parse the children of this node. Update the parse state
+ // to provide context for child node parsing.
+ if (ufbxi_ascii_accept(uc, '{')) {
+ if (recursive) {
+ size_t num_children = 0;
+ for (;;) {
+ bool end = false;
+ ufbxi_check(ufbxi_ascii_parse_node(uc, depth + 1, parse_state, &end, tmp_buf, recursive));
+ if (end) break;
+ num_children++;
+ }
+
+ // Pop children from `tmp_stack` to a contiguous array
+ node->children = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node, num_children);
+ ufbxi_check(node->children);
+ node->num_children = (uint32_t)num_children;
+ }
+
+ uc->has_next_child = true;
+ } else {
+ uc->has_next_child = false;
+ }
+
+ return 1;
+}
+
+// -- DOM retention
+
+typedef struct {
+ uintptr_t node_ptr;
+ ufbx_dom_node *dom_node;
+} ufbxi_dom_mapping;
+
+ufbxi_nodiscard static ufbxi_noinline ufbx_dom_node *ufbxi_get_dom_node_imp(ufbxi_context *uc, ufbxi_node *node)
+{
+ if (!node) return NULL;
+ ufbxi_dom_mapping mapping = { (uintptr_t)node, NULL };
+ uint32_t hash = ufbxi_hash_uptr(mapping.node_ptr);
+ ufbxi_dom_mapping *result = ufbxi_map_find(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
+ return result ? result->dom_node : NULL;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline ufbx_dom_node *ufbxi_get_dom_node(ufbxi_context *uc, ufbxi_node *node)
+{
+ if (!uc->opts.retain_dom) return NULL;
+ return ufbxi_get_dom_node_imp(uc, node);
+}
+
+// Recursion limited by check in ufbxi_[binary/ascii]_parse_node()
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_dom_node(ufbxi_context *uc, ufbxi_node *node, ufbx_dom_node **p_dom_node)
+ ufbxi_recursive_function(int, ufbxi_retain_dom_node, (uc, node, p_dom_node), UFBXI_MAX_NODE_DEPTH + 1,
+ (ufbxi_context *uc, ufbxi_node *node, ufbx_dom_node **p_dom_node))
+{
+ ufbx_dom_node *dst = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
+ ufbxi_check(dst);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_dom_nodes, ufbx_dom_node*, 1, &dst));
+
+ if (p_dom_node) {
+ *p_dom_node = dst;
+ }
+
+ dst->name.data = node->name;
+ dst->name.length = node->name_len;
+
+ {
+ ufbxi_dom_mapping mapping = { (uintptr_t)node, NULL };
+ uint32_t hash = ufbxi_hash_uptr(mapping.node_ptr);
+ ufbxi_dom_mapping *result = ufbxi_map_find(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
+ if (!result) {
+ result = ufbxi_map_insert(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
+ ufbxi_check(result);
+ }
+ result->node_ptr = (uintptr_t)node;
+ result->dom_node = dst;
+ }
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst->name, false));
+
+ if (node->value_type_mask == UFBXI_VALUE_ARRAY) {
+ ufbxi_value_array *arr = node->array;
+ ufbx_dom_value *val = ufbxi_push_zero(&uc->result, ufbx_dom_value, 1);
+ ufbxi_check(val);
+
+ dst->values.data = val;
+ dst->values.count = 1;
+
+ size_t elem_size = ufbxi_array_type_size(arr->type);
+ val->value_str.data = ufbxi_empty_char;
+ val->value_blob.data = arr->data;
+ val->value_blob.size = arr->size * elem_size;
+ val->value_float = (double)(val->value_int = (int64_t)arr->size);
+
+ switch (arr->type) {
+ case 'c': val->type = UFBX_DOM_VALUE_BLOB; break;
+ case 'b': val->type = UFBX_DOM_VALUE_BLOB; break;
+ case 'i': val->type = UFBX_DOM_VALUE_ARRAY_I32; break;
+ case 'l': val->type = UFBX_DOM_VALUE_ARRAY_I64; break;
+ case 'f': val->type = UFBX_DOM_VALUE_ARRAY_F32; break;
+ case 'd': val->type = UFBX_DOM_VALUE_ARRAY_F64; break;
+ case 's': val->type = UFBX_DOM_VALUE_ARRAY_BLOB; break;
+ case 'C': val->type = UFBX_DOM_VALUE_ARRAY_BLOB; break;
+ case '-': val->type = UFBX_DOM_VALUE_ARRAY_IGNORED; break;
+ default: ufbxi_fail("Bad array type");
+ }
+ } else {
+ size_t ix;
+ for (ix = 0; ix < UFBXI_MAX_NON_ARRAY_VALUES; ix++) {
+ uint32_t mask = (node->value_type_mask >> (2*ix)) & 0x3;
+ if (!mask) break;
+ ufbx_dom_value *val = ufbxi_push_zero(&uc->tmp_stack, ufbx_dom_value, 1);
+ ufbxi_check(val);
+ val->value_str.data = ufbxi_empty_char;
+
+ if (mask == UFBXI_VALUE_STRING) {
+ val->type = UFBX_DOM_VALUE_STRING;
+ ufbxi_ignore(ufbxi_get_val_at(node, ix, 'S', &val->value_str));
+ ufbxi_ignore(ufbxi_get_val_at(node, ix, 'b', &val->value_blob));
+ } else {
+ ufbx_assert(mask == UFBXI_VALUE_NUMBER);
+ val->type = UFBX_DOM_VALUE_NUMBER;
+ val->value_int = node->vals[ix].i;
+ val->value_float = node->vals[ix].f;
+ }
+ }
+
+ dst->values.count = ix;
+ dst->values.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_dom_value, ix);
+ ufbxi_check(dst->values.data);
+ }
+
+ if (node->num_children > 0) {
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ ufbxi_check(ufbxi_retain_dom_node(uc, child, NULL));
+ }
+
+ dst->children.count = node->num_children;
+ dst->children.data = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, node->num_children);
+ ufbxi_check(dst->children.data);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_toplevel(ufbxi_context *uc, ufbxi_node *node)
+{
+ if (uc->dom_parse_num_children > 0) {
+ ufbx_dom_node **children = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, uc->dom_parse_num_children);
+ ufbxi_check(children);
+ uc->dom_parse_toplevel->children.data = children;
+ uc->dom_parse_toplevel->children.count = uc->dom_parse_num_children;
+ uc->dom_parse_num_children = 0;
+ }
+
+ if (node) {
+ ufbxi_check(ufbxi_retain_dom_node(uc, node, &uc->dom_parse_toplevel));
+ } else {
+ uc->dom_parse_toplevel = NULL;
+
+ // Called with NULL argument to finish retaining DOM, collect the final nodes to `ufbx_scene`.
+ size_t num_top_nodes = uc->tmp_dom_nodes.num_items;
+ ufbx_dom_node **nodes = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, num_top_nodes);
+ ufbxi_check(nodes);
+
+ ufbx_dom_node *dom_root = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
+ ufbxi_check(dom_root);
+
+ dom_root->name.data = ufbxi_empty_char;
+ dom_root->children.data = nodes;
+ dom_root->children.count = num_top_nodes;
+
+ uc->scene.dom_root = dom_root;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_toplevel_child(ufbxi_context *uc, ufbxi_node *child)
+{
+ ufbx_assert(uc->dom_parse_toplevel);
+ ufbxi_check(ufbxi_retain_dom_node(uc, child, NULL));
+ uc->dom_parse_num_children++;
+
+ return 1;
+}
+
+// -- General parsing
+
+static ufbxi_noinline bool ufbxi_next_line(ufbx_string *line, ufbx_string *buf, bool skip_space)
+{
+ if (buf->length == 0) return false;
+ const char *newline = (const char*)memchr(buf->data, '\n', buf->length);
+ size_t length = newline ? ufbxi_to_size(newline - buf->data) + 1 : buf->length;
+
+ line->data = buf->data;
+ line->length = length;
+ buf->data += length;
+ buf->length -= length;
+
+ if (skip_space) {
+ while (line->length > 0 && ufbxi_is_space(line->data[0])) {
+ line->data++;
+ line->length--;
+ }
+ while (line->length > 0 && ufbxi_is_space(line->data[line->length - 1])) {
+ line->length--;
+ }
+ }
+
+ return true;
+}
+
+// Recursion limited by compile time patterns
+static ufbxi_noinline const char *ufbxi_match_skip(const char *fmt, bool alternation)
+ ufbxi_recursive_function(const char *, ufbxi_match_skip, (fmt, alternation), 4,
+ (const char *fmt, bool alternation))
+{
+ for (;;) {
+ char c = *fmt++;
+ switch (c) {
+ case '(':
+ fmt = ufbxi_match_skip(fmt, false) + 1;
+ break;
+ case '\\':
+ fmt++;
+ break;
+ case '[':
+ c = *fmt;
+ while (c != ']') {
+ c = *fmt++;
+ if (c == '\\') {
+ c = *fmt++;
+ }
+ }
+ fmt++;
+ break;
+ case '|':
+ if (alternation) return fmt - 1;
+ break;
+ case ')':
+ case '\0':
+ return fmt - 1;
+ default: break;
+ }
+ }
+}
+
+// Recursion limited by compile time patterns
+static ufbxi_noinline bool ufbxi_match_imp(const char **p_str, const char *end, const char **p_fmt)
+ ufbxi_recursive_function(bool, ufbxi_match_imp, (p_str, end, p_fmt), 4,
+ (const char **p_str, const char *end, const char **p_fmt))
+{
+ const char *str_original_begin = *p_str;
+ const char *str = str_original_begin;
+ const char *fmt_begin = *p_fmt;
+ const char *fmt = fmt_begin;
+ bool case_insensitive = false;
+
+ size_t count = 0;
+ for (;;) {
+ char c = *fmt++;
+ if (!c) {
+ *p_str = str;
+ *p_fmt = fmt - 1;
+ return true;
+ }
+
+ const char *str_begin = str;
+ char ref = str != end ? *str : '\0';
+
+ if (case_insensitive) {
+ if (ref >= 'A' && ref <= 'Z') {
+ ref = (char)((int)(ref - 'A') + 'a');
+ }
+ }
+
+ bool ok = false;
+ switch (c) {
+
+ case '\\': {
+ const char *macro = NULL;
+ c = *fmt++;
+ switch (c) {
+ case 'd':
+ macro = "[0-9]";
+ break;
+ case 'F':
+ macro = "[\\-+]?[0-9]+(\\.[0-9]+)?([eE][\\-+]?[0-9]+)?";
+ break;
+ case 's':
+ if (ufbxi_is_space(ref)) {
+ ok = true;
+ str++;
+ }
+ break;
+ case 'S':
+ if (!ufbxi_is_space(ref)) {
+ ok = true;
+ str++;
+ }
+ break;
+ case 'c':
+ case 'C':
+ case_insensitive = c == 'c';
+ ok = true;
+ break;
+ default:
+ if (ref == c) {
+ ok = true;
+ str++;
+ }
+ break;
+ }
+ if (macro) {
+ ok = ufbxi_match_imp(&str, end, &macro);
+ }
+ } break;
+
+ case '[': {
+ while (fmt[0] != ']') {
+ if (fmt[0] == '\\') {
+ if (ref == fmt[1]) ok = true;
+ fmt += 2;
+ } else if (fmt[1] == '-') {
+ if (ref >= fmt[0] && ref <= fmt[2]) {
+ ok = true;
+ }
+ fmt += 3;
+ } else {
+ if (ref == fmt[0]) ok = true;
+ fmt += 1;
+ }
+ }
+ fmt++;
+ if (ok) str++;
+ } break;
+
+ case '(':
+ if (ufbxi_match_imp(&str, end, &fmt)) {
+ ok = true;
+ }
+ break;
+
+ case '|':
+ fmt = ufbxi_match_skip(fmt, false);
+ ok = true;
+ break;
+
+ case ')':
+ *p_str = str;
+ *p_fmt = fmt;
+ return true;
+
+ case '.':
+ if (ref != '\0') {
+ ok = true;
+ str++;
+ }
+ break;
+
+ default:
+ if (c == ref) {
+ str++;
+ ok = true;
+ }
+ break;
+ }
+
+ bool did_fail = false;
+ c = *fmt;
+ switch (c) {
+ case '*':
+ fmt++;
+ if (ok) {
+ fmt = fmt_begin;
+ count++;
+ continue;
+ }
+ break;
+ case '+':
+ fmt++;
+ if (ok) {
+ fmt = fmt_begin;
+ count++;
+ continue;
+ } else if (count == 0) {
+ did_fail = true;
+ }
+ break;
+ case '?':
+ fmt++;
+ break;
+ default:
+ did_fail = !ok;
+ break;
+ }
+
+ if (did_fail) {
+ fmt = ufbxi_match_skip(fmt, true);
+ if (*fmt == '|') {
+ fmt++;
+ str = str_original_begin;
+ } else {
+ *p_fmt = ufbxi_match_skip(fmt, false) + 1;
+ return false;
+ }
+ } else {
+ if (!ok) {
+ str = str_begin;
+ }
+ }
+
+ fmt_begin = fmt;
+ count = 0;
+ }
+}
+
+static ufbxi_noinline bool ufbxi_match(const ufbx_string *str, const char *fmt)
+{
+ const char *ptr = str->data, *end = str->data + str->length;
+ if (ufbxi_match_imp(&ptr, end, &fmt)) {
+ return ptr == end;
+ } else {
+ return false;
+ }
+}
+
+static ufbxi_noinline bool ufbxi_is_format(const char *data, size_t size, ufbx_file_format format)
+{
+ ufbx_string line, buf = { data, size };
+
+ if (format == UFBX_FILE_FORMAT_FBX) {
+ if (size >= UFBXI_BINARY_MAGIC_SIZE && !memcmp(data, ufbxi_binary_magic, UFBXI_BINARY_MAGIC_SIZE)) {
+ return true;
+ }
+
+ while (ufbxi_next_line(&line, &buf, true)) {
+ if (ufbxi_match(&line, ";\\s*FBX\\s*\\d+\\.\\d+\\.\\d+\\s*project\\s+file")) return true;
+ if (ufbxi_match(&line, "FBXHeaderExtension:.*")) return true;
+ }
+ } else if (format == UFBX_FILE_FORMAT_OBJ) {
+ while (ufbxi_next_line(&line, &buf, true)) {
+ const char *pattern =
+ "(vn?\\s+\\F|vt)\\s+\\F\\s+\\F.*" "|"
+ "f\\s+[\\-/0-9]+\\s+[\\-/0-9]+\\s*[\\-/0-9]+.*" "|"
+ "(usemtl|mtllib)\\s+\\S.*";
+ if (ufbxi_match(&line, pattern)) return true;
+ }
+ } else if (format == UFBX_FILE_FORMAT_MTL) {
+ while (ufbxi_next_line(&line, &buf, true)) {
+ const char *pattern =
+ "newmtl\\s+\\S.*";
+ if (ufbxi_match(&line, pattern)) return true;
+ }
+ } else {
+ ufbxi_unreachable("Unhandled format");
+ }
+
+ return false;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_determine_format(ufbxi_context *uc)
+{
+ ufbx_file_format format = uc->opts.file_format;
+
+ if (format == UFBX_FILE_FORMAT_UNKNOWN && !uc->opts.no_format_from_content) {
+ ufbxi_pause_progress(uc);
+
+ size_t lookahead = UFBXI_MIN_FILE_FORMAT_LOOKAHEAD;
+ while (format == UFBX_FILE_FORMAT_UNKNOWN && lookahead <= uc->opts.file_format_lookahead) {
+ if (lookahead > uc->data_size) {
+ if (uc->eof) break;
+ ufbxi_check(ufbxi_refill(uc, lookahead, false));
+ }
+
+ size_t data_size = ufbxi_min_sz(lookahead, uc->data_size);
+ ufbxi_check_msg(data_size > 0, "Empty file");
+
+ for (uint32_t fmt = UFBX_FILE_FORMAT_FBX; fmt < UFBX_FILE_FORMAT_COUNT; fmt++) {
+ if (ufbxi_is_format(uc->data, data_size, (ufbx_file_format)fmt)) {
+ format = (ufbx_file_format)fmt;
+ break;
+ }
+ }
+
+ if (lookahead >= uc->opts.file_format_lookahead) {
+ break;
+ } else if (lookahead < SIZE_MAX / 2) {
+ lookahead = ufbxi_min_sz(lookahead * 2, uc->opts.file_format_lookahead);
+ } else {
+ lookahead = SIZE_MAX;
+ }
+ }
+
+ ufbxi_check(ufbxi_resume_progress(uc));
+ }
+
+ if (format == UFBX_FILE_FORMAT_UNKNOWN && !uc->opts.no_format_from_extension) {
+ if (uc->opts.filename.length > 0) {
+ ufbx_string extension = uc->opts.filename;
+ for (size_t i = extension.length; i > 0; i--) {
+ if (extension.data[i - 1] == '.') {
+ extension.data += i - 1;
+ extension.length -= i - 1;
+ break;
+ }
+ }
+
+ if (ufbxi_match(&extension, "\\c\\.fbx")) {
+ format = UFBX_FILE_FORMAT_FBX;
+ } else if (ufbxi_match(&extension, "\\c\\.obj")) {
+ format = UFBX_FILE_FORMAT_OBJ;
+ } else if (ufbxi_match(&extension, "\\c\\.mtl")) {
+ format = UFBX_FILE_FORMAT_MTL;
+ }
+ }
+ }
+
+ ufbxi_check_msg(format != UFBX_FILE_FORMAT_UNKNOWN, "Unrecognized file format");
+ uc->scene.metadata.file_format = format;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_begin_parse(ufbxi_context *uc)
+{
+ const char *header = ufbxi_peek_bytes(uc, UFBXI_BINARY_HEADER_SIZE);
+ ufbxi_check(header);
+
+ // If the file starts with the binary magic parse it as binary, otherwise
+ // treat it as an ASCII file.
+ if (!memcmp(header, ufbxi_binary_magic, UFBXI_BINARY_MAGIC_SIZE)) {
+
+ // The byte after the magic indicates endianness
+ char endian = header[UFBXI_BINARY_MAGIC_SIZE + 0];
+ uc->file_big_endian = endian != 0;
+
+ // Read the version directly from the header
+ const char *version_word = header + UFBXI_BINARY_MAGIC_SIZE + 1;
+ if (uc->file_big_endian) {
+ version_word = ufbxi_swap_endian(uc, version_word, 1, 4);
+ ufbxi_check(version_word);
+ }
+ uc->version = ufbxi_read_u32(version_word);
+
+ // This is quite probably an FBX file..
+ uc->sure_fbx = true;
+ ufbxi_consume_bytes(uc, UFBXI_BINARY_HEADER_SIZE);
+
+ } else {
+ uc->from_ascii = true;
+
+ // Use the current read buffer as the initial parse buffer
+ memset(&uc->ascii, 0, sizeof(uc->ascii));
+ uc->ascii.src = uc->data;
+ uc->ascii.src_yield = uc->data + uc->yield_size;
+ uc->ascii.src_end = uc->data + uc->data_size + uc->yield_size;
+
+ // Initialize the first token
+ ufbxi_check(ufbxi_ascii_next_token(uc, &uc->ascii.token));
+
+ // Default to version 7400 if not found in header
+ if (uc->version > 0) {
+ uc->sure_fbx = true;
+ } else {
+ if (!uc->opts.strict) uc->version = 7400;
+ ufbxi_check_msg(uc->version > 0, "Not an FBX file");
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static int ufbxi_parse_toplevel_child_imp(ufbxi_context *uc, ufbxi_parse_state state, ufbxi_buf *buf, bool *p_end)
+{
+ if (uc->from_ascii) {
+ ufbxi_check(ufbxi_ascii_parse_node(uc, 0, state, p_end, buf, true));
+ } else {
+ ufbxi_check(ufbxi_binary_parse_node(uc, 0, state, p_end, buf, true));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_toplevel(ufbxi_context *uc, const char *name)
+{
+ ufbxi_for(ufbxi_node, node, uc->top_nodes, uc->top_nodes_len) {
+ if (node->name == name) {
+ uc->top_node = node;
+ uc->top_child_index = 0;
+ return 1;
+ }
+ }
+
+ // Reached end and not found in cache
+ if (uc->parsed_to_end) {
+ uc->top_node = NULL;
+ uc->top_child_index = 0;
+ return 1;
+ }
+
+ for (;;) {
+ // Parse the next top-level node
+ bool end = false;
+ if (uc->from_ascii) {
+ ufbxi_check(ufbxi_ascii_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, false));
+ } else {
+ ufbxi_check(ufbxi_binary_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, false));
+ }
+
+ // Top-level node not found
+ if (end) {
+ uc->top_node = NULL;
+ uc->top_child_index = 0;
+ uc->parsed_to_end = true;
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_retain_toplevel(uc, NULL));
+ }
+
+ // Not needed anymore
+ ufbxi_buf_free(&uc->tmp_parse);
+
+ return 1;
+ }
+
+ uc->top_nodes_len++;
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->top_nodes, &uc->top_nodes_cap, uc->top_nodes_len));
+ ufbxi_node *node = &uc->top_nodes[uc->top_nodes_len - 1];
+ ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, node);
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_retain_toplevel(uc, node));
+ }
+
+ // Return if we parsed the right one
+ if (node->name == name) {
+ uc->top_node = node;
+ uc->top_child_index = SIZE_MAX;
+ return 1;
+ }
+
+ // If not we need to parse all the children of the node for later
+ uint32_t num_children = 0;
+ ufbxi_parse_state state = ufbxi_update_parse_state(UFBXI_PARSE_ROOT, node->name);
+ if (uc->has_next_child) {
+ for (;;) {
+ ufbxi_check(ufbxi_parse_toplevel_child_imp(uc, state, &uc->tmp, &end));
+ if (end) break;
+ num_children++;
+ }
+ }
+
+ node->num_children = num_children;
+ node->children = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_node, num_children);
+ ufbxi_check(node->children);
+
+ if (uc->opts.retain_dom) {
+ for (size_t i = 0; i < num_children; i++) {
+ ufbxi_check(ufbxi_retain_toplevel_child(uc, &node->children[i]));
+ }
+ }
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_toplevel_child(ufbxi_context *uc, ufbxi_node **p_node, ufbxi_buf *tmp_buf)
+{
+ // Top-level node not found
+ if (!uc->top_node) {
+ *p_node = NULL;
+ return 1;
+ }
+
+ if (uc->top_child_index == SIZE_MAX) {
+ // Parse children on demand
+ if (!tmp_buf) {
+ ufbxi_buf_clear(&uc->tmp_parse);
+ }
+ bool end = false;
+ ufbxi_parse_state state = ufbxi_update_parse_state(UFBXI_PARSE_ROOT, uc->top_node->name);
+ ufbxi_check(ufbxi_parse_toplevel_child_imp(uc, state, tmp_buf ? tmp_buf : &uc->tmp_parse, &end));
+ if (end) {
+ *p_node = NULL;
+ } else {
+ // Parse to either reused `uc->top_child` or push if retaining to `tmp_buf`.
+ ufbxi_node *dst = &uc->top_child;
+ if (tmp_buf) {
+ dst = ufbxi_push_zero(tmp_buf, ufbxi_node, 1);
+ ufbxi_check(dst);
+ }
+
+ ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, dst);
+ *p_node = dst;
+
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_retain_toplevel_child(uc, dst));
+ }
+ }
+ } else {
+ // Iterate already parsed nodes
+ size_t child_index = uc->top_child_index;
+ if (child_index == uc->top_node->num_children) {
+ *p_node = NULL;
+ } else {
+ uc->top_child_index++;
+ *p_node = &uc->top_node->children[child_index];
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_legacy_toplevel(ufbxi_context *uc)
+{
+ ufbx_assert(uc->top_nodes_len == 0);
+
+ bool end = false;
+ if (uc->from_ascii) {
+ ufbxi_check(ufbxi_ascii_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, true));
+ } else {
+ ufbxi_check(ufbxi_binary_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, true));
+ }
+
+ // Top-level node not found
+ if (end) {
+ uc->top_node = NULL;
+ uc->top_child_index = 0;
+ uc->parsed_to_end = true;
+ return 1;
+ }
+
+ ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, &uc->legacy_node);
+ uc->top_child_index = 0;
+ uc->top_node = &uc->legacy_node;
+
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_retain_toplevel(uc, &uc->legacy_node));
+ }
+
+ return 1;
+}
+
+// -- Setup
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_strings(ufbxi_context *uc)
+{
+#if defined(UFBX_REGRESSION)
+ ufbx_string reg_prev = ufbx_empty_string;
+#endif
+
+ // Push all the global 'ufbxi_*' strings into the pool without copying them
+ // This allows us to compare name pointers to the global values
+ ufbxi_for(const ufbx_string, str, ufbxi_strings, ufbxi_arraycount(ufbxi_strings)) {
+#if defined(UFBX_REGRESSION)
+ ufbx_assert(strlen(str->data) == str->length);
+ ufbx_assert(ufbxi_str_less(reg_prev, *str));
+ reg_prev = *str;
+#endif
+ ufbxi_check(ufbxi_push_string_imp(&uc->string_pool, str->data, str->length, NULL, false, true));
+ }
+
+ return 1;
+}
+
+typedef struct {
+ const char *name;
+ ufbx_prop_type type;
+} ufbxi_prop_type_name;
+
+static const ufbxi_prop_type_name ufbxi_prop_type_names[] = {
+ { "Boolean", UFBX_PROP_BOOLEAN },
+ { "bool", UFBX_PROP_BOOLEAN },
+ { "Bool", UFBX_PROP_BOOLEAN },
+ { "Integer", UFBX_PROP_INTEGER },
+ { "int", UFBX_PROP_INTEGER },
+ { "enum", UFBX_PROP_INTEGER },
+ { "Enum", UFBX_PROP_INTEGER },
+ { "Visibility", UFBX_PROP_INTEGER },
+ { "Visibility Inheritance", UFBX_PROP_INTEGER },
+ { "KTime", UFBX_PROP_INTEGER },
+ { "Number", UFBX_PROP_NUMBER },
+ { "double", UFBX_PROP_NUMBER },
+ { "Real", UFBX_PROP_NUMBER },
+ { "Float", UFBX_PROP_NUMBER },
+ { "Intensity", UFBX_PROP_NUMBER },
+ { "Vector", UFBX_PROP_VECTOR },
+ { "Vector3D", UFBX_PROP_VECTOR },
+ { "Color", UFBX_PROP_COLOR },
+ { "ColorAndAlpha", UFBX_PROP_COLOR_WITH_ALPHA },
+ { "ColorRGB", UFBX_PROP_COLOR },
+ { "String", UFBX_PROP_STRING },
+ { "KString", UFBX_PROP_STRING },
+ { "object", UFBX_PROP_STRING },
+ { "DateTime", UFBX_PROP_DATE_TIME },
+ { "Lcl Translation", UFBX_PROP_TRANSLATION },
+ { "Lcl Rotation", UFBX_PROP_ROTATION },
+ { "Lcl Scaling", UFBX_PROP_SCALING },
+ { "Distance", UFBX_PROP_DISTANCE },
+ { "Compound", UFBX_PROP_COMPOUND },
+ { "Blob", UFBX_PROP_BLOB },
+ { "Reference", UFBX_PROP_REFERENCE },
+};
+
+static ufbx_prop_type ufbxi_get_prop_type(ufbxi_context *uc, const char *name)
+{
+ uint32_t hash = ufbxi_hash_ptr(name);
+ ufbxi_prop_type_name *entry = ufbxi_map_find(&uc->prop_type_map, ufbxi_prop_type_name, hash, &name);
+ if (entry) {
+ return entry->type;
+ }
+ return UFBX_PROP_UNKNOWN;
+}
+
+static ufbxi_noinline ufbx_prop *ufbxi_find_prop_with_key(const ufbx_props *props, const char *name, uint32_t key)
+{
+ do {
+ ufbx_prop *prop_data = props->props.data;
+ size_t begin = 0;
+ size_t end = props->props.count;
+ while (end - begin >= 16) {
+ size_t mid = (begin + end) >> 1;
+ const ufbx_prop *p = &prop_data[mid];
+ if (p->_internal_key < key) {
+ begin = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ end = props->props.count;
+ for (; begin < end; begin++) {
+ const ufbx_prop *p = &prop_data[begin];
+ if (p->_internal_key > key) break;
+ if (p->name.data == name && (p->flags & UFBX_PROP_FLAG_NO_VALUE) == 0) {
+ return (ufbx_prop*)p;
+ }
+ }
+
+ props = props->defaults;
+ } while (props);
+
+ return NULL;
+}
+
+typedef struct {
+ const char *key;
+ ufbx_texture_file *file;
+} ufbxi_texture_file_entry;
+
+#define ufbxi_find_prop(props, name) ufbxi_find_prop_with_key((props), (name), \
+ ((uint32_t)(uint8_t)name[0] << 24u) | ((uint32_t)(uint8_t)name[1] << 16u) | \
+ ((uint32_t)(uint8_t)name[2] << 8u) | (uint32_t)(uint8_t)name[3])
+
+static ufbxi_forceinline ufbx_real ufbxi_find_real(const ufbx_props *props, const char *name, ufbx_real def)
+{
+ ufbx_prop *prop = ufbxi_find_prop(props, name);
+ if (prop) {
+ return prop->value_real;
+ } else {
+ return def;
+ }
+}
+
+static ufbxi_forceinline ufbx_vec3 ufbxi_find_vec3(const ufbx_props *props, const char *name, ufbx_real def_x, ufbx_real def_y, ufbx_real def_z)
+{
+ ufbx_prop *prop = ufbxi_find_prop(props, name);
+ if (prop) {
+ return prop->value_vec3;
+ } else {
+ ufbx_vec3 def = { def_x, def_y, def_z };
+ return def;
+ }
+}
+
+static ufbxi_forceinline int64_t ufbxi_find_int(const ufbx_props *props, const char *name, int64_t def)
+{
+ ufbx_prop *prop = ufbxi_find_prop(props, name);
+ if (prop) {
+ return prop->value_int;
+ } else {
+ return def;
+ }
+}
+
+static ufbxi_forceinline int64_t ufbxi_find_enum(const ufbx_props *props, const char *name, int64_t def, int64_t max_value)
+{
+ ufbx_prop *prop = ufbxi_find_prop(props, name);
+ if (prop) {
+ int64_t value = prop->value_int;
+ if (value >= 0 && value <= max_value) {
+ return value;
+ } else {
+ return def;
+ }
+ } else {
+ return def;
+ }
+}
+
+ufbxi_noinline static bool ufbxi_matrix_all_zero(const ufbx_matrix *matrix)
+{
+ for (size_t i = 0; i < 12; i++) {
+ if (matrix->v[i] != 0.0f) return false;
+ }
+ return true;
+}
+
+static ufbxi_forceinline bool ufbxi_is_vec3_zero(ufbx_vec3 v)
+{
+ return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0);
+}
+
+static ufbxi_forceinline bool ufbxi_is_vec4_zero(ufbx_vec4 v)
+{
+ return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0);
+}
+
+static ufbxi_forceinline bool ufbxi_is_vec3_one(ufbx_vec3 v)
+{
+ return (v.x == 1.0) & (v.y == 1.0) & (v.z == 1.0);
+}
+
+static ufbxi_forceinline bool ufbxi_is_quat_identity(ufbx_quat v)
+{
+ return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0) & (v.w == 1.0);
+}
+
+static ufbxi_unused ufbxi_forceinline bool ufbxi_is_vec3_equal(ufbx_vec3 a, ufbx_vec3 b)
+{
+ return (a.x == b.x) & (a.y == b.y) & (a.z == b.z);
+}
+
+static ufbxi_unused ufbxi_forceinline bool ufbxi_is_quat_equal(ufbx_quat a, ufbx_quat b)
+{
+ return (a.x == b.x) & (a.y == b.y) & (a.z == b.z) & (a.w == b.w);
+}
+
+static ufbxi_noinline bool ufbxi_is_transform_identity(const ufbx_transform *t)
+{
+ return (bool)((int)ufbxi_is_vec3_zero(t->translation) & (int)ufbxi_is_quat_identity(t->rotation) & (int)ufbxi_is_vec3_one(t->scale));
+}
+
+static ufbxi_forceinline uint32_t ufbxi_get_name_key(const char *name, size_t len)
+{
+ uint32_t key = 0;
+ if (len >= 4) {
+ key = (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16
+ | (uint32_t)(uint8_t)name[2]<<8 | (uint32_t)(uint8_t)name[3];
+ } else {
+ for (size_t i = 0; i < 4; i++) {
+ key <<= 8;
+ if (i < len) key |= (uint8_t)name[i];
+ }
+ }
+ return key;
+}
+
+static ufbxi_forceinline uint32_t ufbxi_get_name_key_c(const char *name)
+{
+ if (name[0] == '\0') return 0;
+ if (name[1] == '\0') return (uint32_t)(uint8_t)name[0]<<24;
+ if (name[2] == '\0') return (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16;
+ return (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16
+ | (uint32_t)(uint8_t)name[2]<<8 | (uint32_t)(uint8_t)name[3];
+}
+
+static ufbxi_forceinline bool ufbxi_name_key_less(ufbx_prop *prop, const char *data, size_t name_len, uint32_t key)
+{
+ if (prop->_internal_key < key) return true;
+ if (prop->_internal_key > key) return false;
+
+ size_t prop_len = prop->name.length;
+ size_t len = ufbxi_min_sz(prop_len, name_len);
+ int cmp = memcmp(prop->name.data, data, len);
+ if (cmp != 0) return cmp < 0;
+ return prop_len < name_len;
+}
+
+static const char *const ufbxi_node_prop_names[] = {
+ "AxisLen",
+ "DefaultAttributeIndex",
+ "Freeze",
+ "GeometricRotation",
+ "GeometricScaling",
+ "GeometricTranslation",
+ "InheritType",
+ "LODBox",
+ "Lcl Rotation",
+ "Lcl Scaling",
+ "Lcl Translation",
+ "LookAtProperty",
+ "MaxDampRangeX",
+ "MaxDampRangeY",
+ "MaxDampRangeZ",
+ "MaxDampStrengthX",
+ "MaxDampStrengthY",
+ "MaxDampStrengthZ",
+ "MinDampRangeX",
+ "MinDampRangeY",
+ "MinDampRangeZ",
+ "MinDampStrengthX",
+ "MinDampStrengthY",
+ "MinDampStrengthZ",
+ "NegativePercentShapeSupport",
+ "PostRotation",
+ "PreRotation",
+ "PreferedAngleX",
+ "PreferedAngleY",
+ "PreferedAngleZ",
+ "QuaternionInterpolate",
+ "RotationActive",
+ "RotationMax",
+ "RotationMaxX",
+ "RotationMaxY",
+ "RotationMaxZ",
+ "RotationMin",
+ "RotationMinX",
+ "RotationMinY",
+ "RotationMinZ",
+ "RotationOffset",
+ "RotationOrder",
+ "RotationPivot",
+ "RotationSpaceForLimitOnly",
+ "RotationStiffnessX",
+ "RotationStiffnessY",
+ "RotationStiffnessZ",
+ "ScalingActive",
+ "ScalingMax",
+ "ScalingMaxX",
+ "ScalingMaxY",
+ "ScalingMaxZ",
+ "ScalingMin",
+ "ScalingMinX",
+ "ScalingMinY",
+ "ScalingMinZ",
+ "ScalingOffset",
+ "ScalingPivot",
+ "Show",
+ "TranslationActive",
+ "TranslationMax",
+ "TranslationMaxX",
+ "TranslationMaxY",
+ "TranslationMaxZ",
+ "TranslationMin",
+ "TranslationMinX",
+ "TranslationMinY",
+ "TranslationMinZ",
+ "UpVectorProperty",
+ "Visibility Inheritance",
+ "Visibility",
+ "notes",
+};
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_init_node_prop_names(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_map_grow(&uc->node_prop_set, const char*, ufbxi_arraycount(ufbxi_node_prop_names)));
+ for (size_t i = 0; i < ufbxi_arraycount(ufbxi_node_prop_names); i++) {
+ const char *name = ufbxi_node_prop_names[i];
+ const char *pooled = ufbxi_push_string_imp(&uc->string_pool, name, strlen(name), NULL, false, true);
+ ufbxi_check(pooled);
+ uint32_t hash = ufbxi_hash_ptr(pooled);
+ const char **entry = ufbxi_map_insert(&uc->node_prop_set, const char*, hash, &pooled);
+ ufbxi_check(entry);
+ *entry = pooled;
+ }
+
+ return 1;
+}
+
+static bool ufbxi_is_node_property_name(ufbxi_context *uc, const char *name)
+{
+ // You need to call `ufbxi_init_node_prop_names()` before calling this
+ ufbx_assert(uc->node_prop_set.size > 0);
+
+ uint32_t hash = ufbxi_hash_ptr(name);
+ const char **entry = ufbxi_map_find(&uc->node_prop_set, const char*, hash, &name);
+ return entry != NULL;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_maps(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_map_grow(&uc->prop_type_map, ufbxi_prop_type_name, ufbxi_arraycount(ufbxi_prop_type_names)));
+ ufbxi_for(const ufbxi_prop_type_name, name, ufbxi_prop_type_names, ufbxi_arraycount(ufbxi_prop_type_names)) {
+ const char *pooled = ufbxi_push_string_imp(&uc->string_pool, name->name, strlen(name->name), NULL, false, true);
+ ufbxi_check(pooled);
+ uint32_t hash = ufbxi_hash_ptr(pooled);
+ ufbxi_prop_type_name *entry = ufbxi_map_insert(&uc->prop_type_map, ufbxi_prop_type_name, hash, &pooled);
+ ufbxi_check(entry);
+ entry->type = name->type;
+ entry->name = pooled;
+ }
+
+ return 1;
+}
+
+// -- Reading the parsed data
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_embedded_blob(ufbxi_context *uc, ufbx_blob *dst_blob, ufbxi_node *node)
+{
+ if (!node) return 1;
+
+ ufbxi_value_array *content_arr = ufbxi_get_array(node, 'C');
+ if (content_arr && content_arr->size > 0) {
+ ufbx_string content;
+ size_t num_parts = content_arr->size;
+ ufbx_string *parts = (ufbx_string*)content_arr->data;
+
+ if (num_parts == 1 && !uc->from_ascii) {
+ content = parts[0];
+ } else {
+ size_t total_size = 0;
+ ufbxi_for(ufbx_string, part, parts, num_parts) {
+ total_size += part->length;
+ }
+ char *dst = ufbxi_push(&uc->result, char, total_size);
+ ufbxi_check(dst);
+ content.data = dst;
+ content.length = total_size;
+ ufbxi_for(ufbx_string, part, parts, num_parts) {
+ memcpy(dst, part->data, part->length);
+ dst += part->length;
+ }
+ }
+
+ dst_blob->data = content.data;
+ dst_blob->size = content.length;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_property(ufbxi_context *uc, ufbxi_node *node, ufbx_prop *prop, int version)
+{
+ const char *type_str = NULL, *subtype_str = NULL;
+ ufbxi_check(ufbxi_get_val2(node, "SC", &prop->name, (char**)&type_str));
+ uint32_t val_ix = 2;
+ if (version == 70) {
+ ufbxi_check(ufbxi_get_val_at(node, val_ix++, 'C', (char**)&subtype_str));
+ }
+
+ uint32_t flags = 0;
+ prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
+
+ ufbx_string flags_str;
+ if (ufbxi_get_val_at(node, val_ix++, 'S', &flags_str)) {
+ for (size_t i = 0; i < flags_str.length; i++) {
+ char next = i + 1 < flags_str.length ? flags_str.data[i + 1] : '0';
+ switch (flags_str.data[i]) {
+ case 'A': flags |= UFBX_PROP_FLAG_ANIMATABLE; break;
+ case 'U': flags |= UFBX_PROP_FLAG_USER_DEFINED; break;
+ case 'H': flags |= UFBX_PROP_FLAG_HIDDEN; break;
+ case 'L': flags |= ((uint32_t)(next - '0') & 0xf) << 4; break; // UFBX_PROP_FLAG_LOCK_*
+ case 'M': flags |= ((uint32_t)(next - '0') & 0xf) << 8; break; // UFBX_PROP_FLAG_MUTE_*
+ default: break; // Ignore unknown flags
+ }
+ }
+ }
+
+ prop->type = ufbxi_get_prop_type(uc, type_str);
+ if (prop->type == UFBX_PROP_UNKNOWN && subtype_str) {
+ prop->type = ufbxi_get_prop_type(uc, subtype_str);
+ }
+
+ if (ufbxi_get_val_at(node, val_ix, 'L', &prop->value_int)) {
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_INT;
+ }
+
+ size_t real_ix;
+ for (real_ix = 0; real_ix < 4; real_ix++) {
+ if (!ufbxi_get_val_at(node, val_ix + real_ix, 'R', &prop->value_real_arr[real_ix])) break;
+ }
+ if (real_ix > 0) {
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << (real_ix - 1);
+ }
+
+ // Skip one value forward in case the current value is not a string, as some properties
+ // contain mixed numbers and strings. Currenltly known cases:
+ // Lod Distance: P: "Thresholds|Level0", "Distance", "", "",64, "cm"
+ // User Enum: P: "User_Enum", "Enum", "", "A+U",1, "ValueA~ValueB~ValueC"
+ if (ufbxi_get_val_type(node, val_ix) != UFBXI_VALUE_STRING) {
+ val_ix++;
+ }
+
+ if (ufbxi_get_val_at(node, val_ix, 'S', &prop->value_str)) {
+ // `vals[val_ix]` is known to be a string, fetch non-sanitized blob directly
+ prop->value_blob.data = node->vals[val_ix].s.raw_data;
+ prop->value_blob.size = node->vals[val_ix].s.raw_length;
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_STR;
+ } else {
+ prop->value_str = ufbx_empty_string;
+ }
+
+ // Very unlikely, seems to only exist in some "non standard" FBX files
+ if (node->num_children > 0) {
+ ufbxi_node *binary = ufbxi_find_child(node, ufbxi_BinaryData);
+ ufbxi_check(ufbxi_read_embedded_blob(uc, &prop->value_blob, binary));
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_BLOB;
+ }
+
+ prop->flags = (ufbx_prop_flags)flags;
+
+ return 1;
+}
+
+static ufbxi_forceinline bool ufbxi_prop_less(ufbx_prop *a, ufbx_prop *b)
+{
+ if (a->_internal_key < b->_internal_key) return true;
+ if (a->_internal_key > b->_internal_key) return false;
+ return strcmp(a->name.data, b->name.data) < 0;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_properties(ufbxi_context *uc, ufbx_prop *props, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_prop)));
+ ufbxi_macro_stable_sort(ufbx_prop, 32, props, uc->tmp_arr, count, ( ufbxi_prop_less(a, b) ));
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_deduplicate_properties(ufbx_prop_list *list)
+{
+ if (list->count >= 2) {
+ ufbx_prop *ps = list->data;
+ size_t dst = 0, src = 0, end = list->count;
+ while (src < end) {
+ if (src + 1 < end && ps[src].name.data == ps[src + 1].name.data) {
+ src++;
+ } else if (dst != src) {
+ ps[dst++] = ps[src++];
+ } else {
+ dst++; src++;
+ }
+ }
+ list->count = dst;
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_properties(ufbxi_context *uc, ufbxi_node *parent, ufbx_props *props)
+{
+ props->defaults = NULL;
+
+ int version = 70;
+ ufbxi_node *node = ufbxi_find_child(parent, ufbxi_Properties70);
+ if (!node) {
+ node = ufbxi_find_child(parent, ufbxi_Properties60);
+ if (!node) {
+ // No properties found, not an error
+ props->props.data = NULL;
+ props->props.count = 0;
+ return 1;
+ }
+ version = 60;
+ }
+
+ props->props.data = ufbxi_push_zero(&uc->result, ufbx_prop, node->num_children);
+ props->props.count = node->num_children;
+ ufbxi_check(props->props.data);
+
+ for (size_t i = 0; i < props->props.count; i++) {
+ ufbxi_check(ufbxi_read_property(uc, &node->children[i], &props->props.data[i], version));
+ }
+
+ ufbxi_check(ufbxi_sort_properties(uc, props->props.data, props->props.count));
+ ufbxi_deduplicate_properties(&props->props);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_thumbnail(ufbxi_context *uc, ufbxi_node *node, ufbx_thumbnail *thumbnail)
+{
+ ufbxi_check(ufbxi_read_properties(uc, node, &thumbnail->props));
+
+ int64_t custom_width = ufbx_find_int(&thumbnail->props, "CustomWidth", 0);
+ int64_t custom_height = ufbx_find_int(&thumbnail->props, "CustomHeight", 0);
+
+ int32_t format;
+ ufbxi_node *format_node = ufbxi_find_child_strcmp(node, "Format");
+ if (format_node && ufbxi_get_val1(format_node, "I", &format)) {
+ if (format >= 0 && format + 1 < UFBX_THUMBNAIL_FORMAT_COUNT) {
+ thumbnail->format = (ufbx_thumbnail_format)(format + 1);
+ }
+ }
+
+ int32_t size;
+ if (ufbxi_find_val1(node, ufbxi_Size, "I", &size)) {
+ if (size > 0) {
+ thumbnail->width = (uint32_t)size;
+ thumbnail->height = (uint32_t)size;
+ } else if (size < 0 && custom_width > 0 && custom_height > 0) {
+ thumbnail->width = (uint32_t)custom_width;
+ thumbnail->height = (uint32_t)custom_height;
+ }
+ }
+
+ ufbxi_value_array *data_arr = ufbxi_find_array(node, ufbxi_ImageData, 'c');
+ if (data_arr) {
+ thumbnail->data.data = data_arr->data;
+ thumbnail->data.size = data_arr->size;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_scene_info(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbxi_check(ufbxi_read_properties(uc, node, &uc->scene.metadata.scene_props));
+
+ ufbxi_node *thumbnail = ufbxi_find_child(node, ufbxi_Thumbnail);
+ if (thumbnail) {
+ ufbxi_check(ufbxi_read_thumbnail(uc, thumbnail, &uc->scene.metadata.thumbnail));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_header_extension(ufbxi_context *uc)
+{
+ bool has_tc_definition = false;
+ int32_t tc_definition = 0;
+ int32_t header_version = 0;
+
+ for (;;) {
+ ufbxi_node *child;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &child, NULL));
+ if (!child) break;
+
+ if (child->name == ufbxi_Creator) {
+ ufbxi_ignore(ufbxi_get_val1(child, "S", &uc->scene.metadata.creator));
+ }
+
+ if (uc->version < 6000 && child->name == ufbxi_FBXVersion) {
+ int32_t version;
+ if (ufbxi_get_val1(child, "I", &version)) {
+ if (version > 0 && version < 6000 && (uint32_t)version > uc->version) {
+ uc->version = (uint32_t)version;
+ }
+ }
+ }
+
+ if (child->name == ufbxi_FBXHeaderVersion) {
+ ufbxi_ignore(ufbxi_get_val1(child, "I", &header_version));
+ }
+
+ if (child->name == ufbxi_OtherFlags) {
+ if (ufbxi_find_val1(child, ufbxi_TCDefinition, "I", &tc_definition)) {
+ has_tc_definition = true;
+ }
+ }
+
+ if (child->name == ufbxi_SceneInfo) {
+ ufbxi_check(ufbxi_read_scene_info(uc, child));
+ }
+
+ }
+
+ // FBX 8000 will change the KTime units and the new units are opt-in currently via `TCDefinition`.
+ // `TCDefinition` seems be accounted in all versions, as long as `FBXHeaderVersion >= 1004`.
+ // The old KTime units are specified as the value `127` and all other values seem to use the new definition.
+ bool use_v7_ktime = uc->version < 8000;
+ if (header_version >= 1004 && has_tc_definition) {
+ use_v7_ktime = tc_definition == 127;
+ }
+
+ uc->ktime_sec = use_v7_ktime ? 46186158000 : 141120000;
+ uc->ktime_sec_double = (double)uc->ktime_sec;
+
+ return 1;
+}
+
+static bool ufbxi_match_version_string(const char *fmt, ufbx_string str, uint32_t *p_version)
+{
+ size_t num_ix = 0;
+ size_t pos = 0;
+ while (*fmt) {
+ char c = *fmt++;
+ if (c >= 'a' && c <= 'z') {
+ if (pos >= str.length) return false;
+ char s = str.data[pos];
+ if (s != c && (int)s + (int)('a' - 'A') != (int)c) return false;
+ pos++;
+ } else if (c == ' ') {
+ while (pos < str.length) {
+ char s = str.data[pos];
+ if (s != ' ' && s != '\t') break;
+ pos++;
+ }
+ } else if (c == '-') {
+ while (pos < str.length) {
+ char s = str.data[pos];
+ if (s == '-') break;
+ pos++;
+ }
+ if (pos >= str.length) return false;
+ pos++;
+ } else if (c == '/' || c == '.' || c == '(' || c == ')' || c == '_') {
+ if (pos >= str.length) return false;
+ if (str.data[pos] != c) return false;
+ pos++;
+ } else if (c == '?') {
+ uint32_t num = 0;
+ size_t len = 0;
+ while (pos < str.length) {
+ char s = str.data[pos];
+ if (!(s >= '0' && s <= '9')) break;
+ num = num*10 + (uint32_t)(s - '0');
+ pos++;
+ len++;
+ }
+ if (len == 0) return false;
+ p_version[num_ix++] = num;
+ } else {
+ ufbxi_unreachable("Unhandled match character");
+ }
+ }
+
+ return true;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_match_exporter(ufbxi_context *uc)
+{
+ ufbx_string creator = uc->scene.metadata.creator;
+ uint32_t version[3] = { 0 };
+ if (ufbxi_match_version_string("blender-- ?.?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_BLENDER_BINARY;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], version[2]);
+ } else if (ufbxi_match_version_string("blender- ?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_BLENDER_BINARY;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
+ } else if (ufbxi_match_version_string("blender version ?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_BLENDER_ASCII;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
+ } else if (ufbxi_match_version_string("fbx sdk/fbx plugins version ?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_FBX_SDK;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
+ } else if (ufbxi_match_version_string("fbx sdk/fbx plugins build ?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_FBX_SDK;
+ uc->exporter_version = ufbx_pack_version(version[0]/10000u, version[0]/100u%100u, version[0]%100u);
+ } else if (ufbxi_match_version_string("motionbuilder version ?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_MOTION_BUILDER;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
+ } else if (ufbxi_match_version_string("motionbuilder/mocap/online version ?.?", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_MOTION_BUILDER;
+ uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
+ } else if (ufbxi_match_version_string("ufbx_write", creator, version)) {
+ uc->exporter = UFBX_EXPORTER_UFBX_WRITE;
+ uc->exporter_version = ufbx_pack_version(0, 0, 1);
+ }
+
+ uc->scene.metadata.exporter = uc->exporter;
+ uc->scene.metadata.exporter_version = uc->exporter_version;
+
+ // Un-detect the exporter in `ufbxi_context` to disable special cases
+ if (uc->opts.disable_quirks) {
+ uc->exporter = UFBX_EXPORTER_UNKNOWN;
+ uc->exporter_version = 0;
+ }
+
+ if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
+ uc->blender_full_weights = true;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_document(ufbxi_context *uc)
+{
+ bool found_root_id = 0;
+
+ for (;;) {
+ ufbxi_node *child;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &child, NULL));
+ if (!child) break;
+
+ if (child->name == ufbxi_Document && !found_root_id) {
+ // Post-7000: Try to find the first document node and root ID.
+ // TODO: Multiple documents / roots?
+ if (ufbxi_find_val1(child, ufbxi_RootNode, "L", &uc->root_id)) {
+ found_root_id = true;
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_definitions(ufbxi_context *uc)
+{
+ for (;;) {
+ ufbxi_node *object;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &object, NULL));
+ if (!object) break;
+
+ if (object->name != ufbxi_ObjectType) continue;
+
+ ufbxi_template *tmpl = ufbxi_push_zero(&uc->tmp_stack, ufbxi_template, 1);
+ uc->num_templates++;
+ ufbxi_check(tmpl);
+ ufbxi_check(ufbxi_get_val1(object, "C", (char**)&tmpl->type));
+
+ // Pre-7000 FBX versions don't have property templates, they just have
+ // the object counts by themselves.
+ ufbxi_node *props = ufbxi_find_child(object, ufbxi_PropertyTemplate);
+ if (props) {
+ ufbxi_check(ufbxi_get_val1(props, "S", &tmpl->sub_type));
+
+ // Remove the "Fbx" prefix from sub-types, remember to re-intern!
+ if (tmpl->sub_type.length > 3 && !strncmp(tmpl->sub_type.data, "Fbx", 3)) {
+ tmpl->sub_type.data += 3;
+ tmpl->sub_type.length -= 3;
+
+ // HACK: LOD groups use LODGroup for Template, LodGroup for Object?
+ if (tmpl->sub_type.length == 8 && !memcmp(tmpl->sub_type.data, "LODGroup", 8)) {
+ tmpl->sub_type.data = "LodGroup";
+ }
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &tmpl->sub_type, false));
+ }
+
+ ufbxi_check(ufbxi_read_properties(uc, props, &tmpl->props));
+ }
+ }
+
+ // TODO: Preserve only the `props` part of the templates
+ uc->templates = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbxi_template, uc->num_templates);
+ ufbxi_check(uc->templates);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbx_props *ufbxi_find_template(ufbxi_context *uc, const char *name, const char *sub_type)
+{
+ // TODO: Binary search
+ ufbxi_for(ufbxi_template, tmpl, uc->templates, uc->num_templates) {
+ if (tmpl->type == name) {
+
+ // Check that sub_type matches unless the type is Material, Model, AnimationStack, AnimationLayer.
+ // Those match to all sub-types.
+ if (tmpl->type != ufbxi_Material && tmpl->type != ufbxi_Model
+ && tmpl->type != ufbxi_AnimationStack && tmpl->type != ufbxi_AnimationLayer) {
+ if (tmpl->sub_type.data != sub_type) {
+ return NULL;
+ }
+ }
+
+ if (tmpl->props.props.count > 0) {
+ return &tmpl->props;
+ } else {
+ return NULL;
+ }
+ }
+ }
+ return NULL;
+}
+
+// Name ID categories
+#if defined(UFBX_REGRESSION)
+ #define UFBXI_MAXIMUM_FAST_POINTER_ID UINT64_C(0x100)
+#else
+ #define UFBXI_MAXIMUM_FAST_POINTER_ID UINT64_C(0x4000000000000000)
+#endif
+#define UFBXI_POINTER_ID_START UINT64_C(0x8000000000000000)
+#define UFBXI_SYNTHETIC_ID_START (UFBXI_POINTER_ID_START + UFBXI_MAXIMUM_FAST_POINTER_ID)
+
+static ufbxi_forceinline uint64_t ufbxi_push_synthetic_id(ufbxi_context *uc)
+{
+ return ++uc->synthetic_id_counter;
+}
+
+static ufbxi_noinline uint64_t ufbxi_synthetic_id_from_ptr_id(ufbxi_context *uc, uintptr_t ptr, uint64_t id)
+{
+ ufbxi_ptr_id ptr_id = { ptr, id };
+ uint32_t hash = ufbxi_hash_ptr_id(ptr_id);
+ ufbxi_ptr_fbx_id_entry *entry = ufbxi_map_find(&uc->ptr_fbx_id_map, ufbxi_ptr_fbx_id_entry, hash, &ptr_id);
+
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->ptr_fbx_id_map, ufbxi_ptr_fbx_id_entry, hash, &ptr_id);
+ ufbxi_check_return(entry, 0);
+ entry->ptr_id = ptr_id;
+ entry->fbx_id = ufbxi_push_synthetic_id(uc);
+ }
+
+ return entry->fbx_id;
+}
+
+static ufbxi_forceinline uint64_t ufbxi_synthetic_id_from_string(ufbxi_context *uc, const char *str)
+{
+ uintptr_t uptr = (uintptr_t)str;
+ if (uptr < (UINTPTR_MAX < UFBXI_MAXIMUM_FAST_POINTER_ID ? UINTPTR_MAX : UFBXI_MAXIMUM_FAST_POINTER_ID)) {
+ return (uint64_t)uptr;
+ } else {
+ return ufbxi_synthetic_id_from_ptr_id(uc, uptr, 0);
+ }
+}
+
+ufbxi_nodiscard ufbxi_forceinline static int ufbxi_validate_fbx_id(ufbxi_context *uc, uint64_t *p_fbx_id)
+{
+ uint64_t fbx_id = *p_fbx_id;
+ if (fbx_id >= UFBXI_POINTER_ID_START) {
+ fbx_id = ufbxi_synthetic_id_from_ptr_id(uc, 0, fbx_id);
+ ufbxi_check(fbx_id);
+ *p_fbx_id = fbx_id;
+ }
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_split_type_and_name(ufbxi_context *uc, ufbx_string type_and_name, ufbx_string *type, ufbx_string *name)
+{
+ // Name and type are packed in a single property as Type::Name (in ASCII)
+ // or Name\x00\x01Type (in binary)
+ const char *sep = uc->from_ascii ? "::" : "\x00\x01";
+ size_t type_end = 2;
+ for (; type_end <= type_and_name.length; type_end++) {
+ const char *ch = type_and_name.data + type_end - 2;
+ if (ch[0] == sep[0] && ch[1] == sep[1]) break;
+ }
+
+ // ???: ASCII and binary store type and name in different order
+ if (type_end <= type_and_name.length) {
+ if (uc->from_ascii) {
+ name->data = type_and_name.data + type_end;
+ name->length = type_and_name.length - type_end;
+ type->data = type_and_name.data;
+ type->length = type_end - 2;
+ } else {
+ name->data = type_and_name.data;
+ name->length = type_end - 2;
+ type->data = type_and_name.data + type_end;
+ type->length = type_and_name.length - type_end;
+ }
+ } else {
+ *name = type_and_name;
+ type->data = ufbxi_empty_char;
+ type->length = 0;
+ }
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, type, false));
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, name, false));
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_fbx_id(ufbxi_context *uc, uint64_t fbx_id, uint32_t element_id)
+{
+ uint32_t hash = ufbxi_hash64(fbx_id);
+ ufbxi_fbx_id_entry *entry = ufbxi_map_find(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
+
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
+ ufbxi_check(entry);
+ entry->fbx_id = fbx_id;
+ entry->element_id = element_id;
+ entry->user_id = 0;
+ } else {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_DUPLICATE_OBJECT_ID, "Duplicate object ID"));
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline ufbxi_fbx_id_entry *ufbxi_find_fbx_id(ufbxi_context *uc, uint64_t fbx_id)
+{
+ uint32_t hash = ufbxi_hash64(fbx_id);
+ return ufbxi_map_find(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
+}
+
+static ufbxi_forceinline bool ufbxi_fbx_id_exists(ufbxi_context *uc, uint64_t fbx_id)
+{
+ return ufbxi_find_fbx_id(uc, fbx_id) != NULL;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_fbx_attr(ufbxi_context *uc, uint64_t fbx_id, uint64_t attrib_fbx_id)
+{
+ uint32_t hash = ufbxi_hash64(fbx_id);
+ ufbxi_fbx_attr_entry *entry = ufbxi_map_find(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &fbx_id);
+ // TODO: Strict / warn about duplicate objects
+
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &fbx_id);
+ ufbxi_check(entry);
+ entry->node_fbx_id = fbx_id;
+ entry->attr_fbx_id = attrib_fbx_id;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_push_element_size(ufbxi_context *uc, ufbxi_element_info *info, size_t size, ufbx_element_type type)
+{
+ size_t aligned_size = (size + 7u) & ~0x7u;
+
+ uint32_t typed_id = (uint32_t)uc->tmp_typed_element_offsets[type].num_items;
+ uint32_t element_id = uc->num_elements++;
+
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_typed_element_offsets[type], size_t, 1, &uc->tmp_element_byte_offset), NULL);
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_offsets, size_t, 1, &uc->tmp_element_byte_offset), NULL);
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_fbx_ids, uint64_t, 1, &info->fbx_id), NULL);
+ uc->tmp_element_byte_offset += aligned_size;
+
+ ufbx_element *elem = (ufbx_element*)ufbxi_push_zero(&uc->tmp_elements, uint64_t, aligned_size/8);
+ ufbxi_check_return(elem, NULL);
+ elem->type = type;
+ elem->element_id = element_id;
+ elem->typed_id = typed_id;
+ elem->name = info->name;
+ elem->props = info->props;
+ elem->dom_node = info->dom_node;
+
+ if (uc->p_element_id) {
+ *uc->p_element_id = element_id;
+ }
+
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_ptrs, ufbx_element*, 1, &elem), NULL);
+
+ ufbxi_check_return(ufbxi_insert_fbx_id(uc, info->fbx_id, element_id), NULL);
+
+ return elem;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_push_synthetic_element_size(ufbxi_context *uc, uint64_t *p_fbx_id, ufbxi_node *node, const char *name, size_t size, ufbx_element_type type)
+{
+ size_t aligned_size = (size + 7u) & ~0x7u;
+
+ uint32_t typed_id = (uint32_t)uc->tmp_typed_element_offsets[type].num_items;
+ uint32_t element_id = uc->num_elements++;
+
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_typed_element_offsets[type], size_t, 1, &uc->tmp_element_byte_offset), NULL);
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_offsets, size_t, 1, &uc->tmp_element_byte_offset), NULL);
+ uc->tmp_element_byte_offset += aligned_size;
+
+ ufbx_element *elem = (ufbx_element*)ufbxi_push_zero(&uc->tmp_elements, uint64_t, aligned_size/8);
+ ufbxi_check_return(elem, NULL);
+ elem->type = type;
+ elem->element_id = element_id;
+ elem->typed_id = typed_id;
+ elem->dom_node = ufbxi_get_dom_node(uc, node);
+ if (name) {
+ elem->name.data = name;
+ elem->name.length = strlen(name);
+ }
+
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_ptrs, ufbx_element*, 1, &elem), NULL);
+
+ *p_fbx_id = ufbxi_push_synthetic_id(uc);
+
+ ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_fbx_ids, uint64_t, 1, p_fbx_id), NULL);
+ ufbxi_check_return(ufbxi_insert_fbx_id(uc, *p_fbx_id, element_id), NULL);
+
+ return elem;
+}
+
+#define ufbxi_push_element(uc, info, type_name, type_enum) ufbxi_maybe_null((type_name*)ufbxi_push_element_size((uc), (info), sizeof(type_name), (type_enum)))
+#define ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, type_name, type_enum) ufbxi_maybe_null((type_name*)ufbxi_push_synthetic_element_size((uc), (p_fbx_id), (node), (name), sizeof(type_name), (type_enum)))
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_oo(ufbxi_context *uc, uint64_t src, uint64_t dst)
+{
+ ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
+ ufbxi_check(conn);
+ conn->src = src;
+ conn->dst = dst;
+ conn->src_prop = conn->dst_prop = ufbx_empty_string;
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_op(ufbxi_context *uc, uint64_t src, uint64_t dst, ufbx_string prop)
+{
+ ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
+ ufbxi_check(conn);
+ conn->src = src;
+ conn->dst = dst;
+ conn->src_prop = ufbx_empty_string;
+ conn->dst_prop = prop;
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_pp(ufbxi_context *uc, uint64_t src, uint64_t dst, ufbx_string src_prop, ufbx_string dst_prop)
+{
+ ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
+ ufbxi_check(conn);
+ conn->src = src;
+ conn->dst = dst;
+ conn->src_prop = src_prop;
+ conn->dst_prop = dst_prop;
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_init_synthetic_int_prop(ufbx_prop *dst, const char *name, int64_t value, ufbx_prop_type type)
+{
+ dst->type = type;
+ dst->name.data = name;
+ dst->name.length = strlen(name);
+ dst->value_real = (ufbx_real)value;
+ dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_REAL|UFBX_PROP_FLAG_VALUE_INT);
+ dst->value_int = value;
+ dst->value_str.data = ufbxi_empty_char;
+
+ ufbxi_dev_assert(dst->name.length >= 4);
+ dst->_internal_key = ufbxi_get_name_key(name, 4);
+}
+
+ufbxi_noinline static void ufbxi_init_synthetic_real_prop(ufbx_prop *dst, const char *name, ufbx_real value, ufbx_prop_type type)
+{
+ dst->type = type;
+ dst->name.data = name;
+ dst->name.length = strlen(name);
+ dst->value_real = value;
+ dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_REAL);
+ dst->value_int = (int64_t)value;
+ dst->value_str.data = ufbxi_empty_char;
+
+ ufbxi_dev_assert(dst->name.length >= 4);
+ dst->_internal_key = ufbxi_get_name_key(name, 4);
+}
+
+ufbxi_noinline static void ufbxi_init_synthetic_vec3_prop(ufbx_prop *dst, const char *name, const ufbx_vec3 *value, ufbx_prop_type type)
+{
+ dst->type = type;
+ dst->name.data = name;
+ dst->name.length = strlen(name);
+ dst->value_vec3 = *value;
+ dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_VEC3);
+ dst->value_int = ufbxi_f64_to_i64(dst->value_real);
+ dst->value_str.data = ufbxi_empty_char;
+
+ ufbxi_dev_assert(dst->name.length >= 4);
+ dst->_internal_key = ufbxi_get_name_key(name, 4);
+}
+
+ufbxi_noinline static void ufbxi_set_own_prop_vec3_uniform(ufbx_props *props, const char *name, ufbx_real value)
+{
+ ufbx_props local_props = *props;
+ local_props.defaults = NULL;
+ ufbx_prop *prop = ufbx_find_prop(&local_props, name);
+ if (prop) {
+ prop->value_vec4.x = value;
+ prop->value_vec4.y = value;
+ prop->value_vec4.z = value;
+ prop->value_vec4.w = 0.0f;
+ prop->value_int = (int64_t)value;
+ }
+}
+
+typedef struct {
+ uint32_t geometry_helper_id;
+ uint32_t scale_helper_id;
+} ufbxi_node_extra;
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_setup_geometry_transform_helper(ufbxi_context *uc, ufbx_node *node, uint64_t node_fbx_id)
+{
+ ufbx_vec3 geo_translation = ufbxi_find_vec3(&node->props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 geo_rotation = ufbxi_find_vec3(&node->props, ufbxi_GeometricRotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 geo_scaling = ufbxi_find_vec3(&node->props, ufbxi_GeometricScaling, 1.0f, 1.0f, 1.0f);
+ if (!ufbxi_is_vec3_zero(geo_translation) || !ufbxi_is_vec3_zero(geo_rotation) || !ufbxi_is_vec3_one(geo_scaling)) {
+
+ uint64_t geo_fbx_id;
+ ufbx_node *geo_node = ufbxi_push_synthetic_element(uc, &geo_fbx_id, NULL, uc->opts.geometry_transform_helper_name.data, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(geo_node);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &geo_node->element.element_id));
+ geo_node->element.dom_node = node->element.dom_node;
+
+ ufbx_prop *props = ufbxi_push_zero(&uc->result, ufbx_prop, 3);
+ ufbxi_check(props);
+ ufbxi_init_synthetic_vec3_prop(&props[0], ufbxi_Lcl_Rotation, &geo_rotation, UFBX_PROP_ROTATION);
+ ufbxi_init_synthetic_vec3_prop(&props[1], ufbxi_Lcl_Scaling, &geo_scaling, UFBX_PROP_SCALING);
+ ufbxi_init_synthetic_vec3_prop(&props[2], ufbxi_Lcl_Translation, &geo_translation, UFBX_PROP_TRANSLATION);
+
+ geo_node->props.props.data = props;
+ geo_node->props.props.count = 3;
+
+ node->has_geometry_transform = true;
+ geo_node->is_geometry_transform_helper = true;
+
+ ufbxi_check(ufbxi_connect_oo(uc, geo_fbx_id, node_fbx_id));
+ uc->has_geometry_transform_nodes = true;
+
+ ufbxi_node_extra *extra = ufbxi_push_element_extra(uc, node->element_id, ufbxi_node_extra);
+ ufbxi_check(extra);
+ extra->geometry_helper_id = geo_node->element_id;
+ }
+
+ return 1;
+}
+
+typedef struct {
+ const char *name;
+ ufbx_vec3 default_value;
+} ufbxi_scale_helper_prop;
+
+static const ufbxi_scale_helper_prop ufbxi_scale_helper_props[] = {
+ { ufbxi_GeometricRotation, { 0.0f, 0.0f, 0.0f } },
+ { ufbxi_GeometricScaling, { 1.0f, 1.0f, 1.0f } },
+ { ufbxi_GeometricTranslation, { 0.0f, 0.0f, 0.0f } },
+ { ufbxi_Lcl_Scaling, { 1.0f, 1.0f, 1.0f } },
+};
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_setup_scale_helper(ufbxi_context *uc, ufbx_node *node, uint64_t node_fbx_id)
+{
+ uint64_t scale_fbx_id;
+ ufbx_node *scale_node = ufbxi_push_synthetic_element(uc, &scale_fbx_id, NULL, uc->opts.scale_helper_name.data, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(scale_node);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &scale_node->element.element_id));
+ scale_node->element.dom_node = node->element.dom_node;
+
+ node->scale_helper = scale_node;
+ scale_node->is_scale_helper = true;
+
+ ufbxi_check(ufbxi_connect_oo(uc, scale_fbx_id, node_fbx_id));
+ uc->has_scale_helper_nodes = true;
+
+ ufbxi_node_extra *extra = ufbxi_push_element_extra(uc, node->element.element_id, ufbxi_node_extra);
+ ufbxi_check(extra);
+ extra->scale_helper_id = scale_node->element_id;
+
+ size_t max_props = ufbxi_arraycount(ufbxi_scale_helper_props);
+ ufbx_prop *helper_props = ufbxi_push(&uc->result, ufbx_prop, max_props);
+ ufbxi_check(helper_props);
+
+ size_t num_props = 0;
+ ufbx_props props_copy = node->props;
+ props_copy.defaults = NULL;
+ for (size_t i = 0; i < max_props; i++) {
+ const ufbxi_scale_helper_prop *hp = &ufbxi_scale_helper_props[i];
+ ufbx_prop *src_prop = ufbxi_find_prop(&props_copy, hp->name);
+ if (!src_prop) continue;
+
+ helper_props[num_props++] = *src_prop;
+ src_prop->value_vec3 = hp->default_value;
+ src_prop->value_int = (int64_t)src_prop->value_vec3.x;
+ }
+
+ scale_node->props.props.data = helper_props;
+ scale_node->props.props.count = num_props;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_model(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ (void)node;
+ ufbx_node *elem_node = ufbxi_push_element(uc, info, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(elem_node);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &elem_node->element.element_id));
+
+ int64_t inherit_type = ufbxi_find_int(&elem_node->props, ufbxi_InheritType, -1);
+ switch (inherit_type) {
+ case 0: // RrSs
+ elem_node->original_inherit_mode = UFBX_INHERIT_MODE_COMPONENTWISE_SCALE;
+ break;
+ case 2: // Rrs
+ elem_node->original_inherit_mode = UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE;
+ break;
+ default: break;
+ }
+
+ if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
+ elem_node->inherit_mode = elem_node->original_inherit_mode;
+ } else if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_IGNORE) {
+ elem_node->original_inherit_mode = UFBX_INHERIT_MODE_NORMAL;
+ elem_node->inherit_mode = UFBX_INHERIT_MODE_NORMAL;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_element(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, size_t size, ufbx_element_type type)
+{
+ (void)node;
+ ufbx_element *elem = ufbxi_push_element_size(uc, info, size, type);
+ ufbxi_check(elem);
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_unknown(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *element, ufbx_string type, ufbx_string sub_type, const char *node_name)
+{
+ (void)node;
+ ufbx_unknown *unknown = ufbxi_push_element(uc, element, ufbx_unknown, UFBX_ELEMENT_UNKNOWN);
+ ufbxi_check(unknown);
+ unknown->type = type;
+ unknown->sub_type = sub_type;
+ unknown->super_type.data = node_name;
+ unknown->super_type.length = strlen(node_name);
+
+ // `type`, `sub_type` and `node_name` are raw strings so they may need to be sanitized.
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->type, false));
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->sub_type, false));
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->super_type, false));
+
+ return 1;
+}
+
+typedef struct {
+ ufbx_vertex_vec3 elem;
+ uint32_t index;
+} ufbxi_tangent_layer;
+
+static ufbx_real ufbxi_zero_element[8] = { 0 };
+
+// Sentinel pointers used for zero/sequential index buffers
+static const uint32_t ufbxi_sentinel_index_zero[1] = { 100000000 };
+static const uint32_t ufbxi_sentinel_index_consecutive[1] = { 123456789 };
+
+ufbxi_noinline static int ufbxi_fix_index(ufbxi_context *uc, uint32_t *p_dst, uint32_t index, size_t one_past_max_val)
+{
+ switch (uc->opts.index_error_handling) {
+ case UFBX_INDEX_ERROR_HANDLING_CLAMP:
+ ufbxi_check(one_past_max_val > 0);
+ ufbxi_check(one_past_max_val <= UINT32_MAX);
+ *p_dst = (uint32_t)one_past_max_val - 1;
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_INDEX_CLAMPED, "Clamped index"));
+ break;
+ case UFBX_INDEX_ERROR_HANDLING_NO_INDEX:
+ *p_dst = UFBX_NO_INDEX;
+ break;
+ case UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING:
+ ufbxi_fmt_err_info(&uc->error, "%u (max %u)", index, one_past_max_val ? (one_past_max_val - 1) : 0);
+ ufbxi_fail_msg("UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING", "Bad index");
+ case UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE:
+ *p_dst = index;
+ break;
+ default:
+ ufbxi_unreachable("Unhandled index_error_handling");
+ return 0;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_check_indices(ufbxi_context *uc, uint32_t **p_dst, uint32_t *indices, bool owns_indices, size_t num_indices, size_t num_indexers, size_t num_elems)
+{
+ // If the indices are truncated extend them with `UFBX_NO_INDEX`, the following normalization pass
+ // will handle them the same way as other out-of-bounds indices.
+ if (num_indices < num_indexers) {
+ uint32_t *new_indices = ufbxi_push(&uc->result, uint32_t, num_indexers);
+ ufbxi_check(new_indices);
+
+ memcpy(new_indices, indices, sizeof(uint32_t) * num_indices);
+ for (size_t i = num_indices; i < num_indexers; i++) {
+ new_indices[i] = UFBX_NO_INDEX;
+ }
+
+ indices = new_indices;
+ num_indices = num_indexers;
+ owns_indices = true;
+ }
+
+ // Normalize out-of-bounds indices to `invalid_index`
+ for (size_t i = 0; i < num_indices; i++) {
+ uint32_t ix = indices[i];
+ if (ix >= num_elems) {
+ // If the indices refer to an external buffer we need to
+ // allocate a separate buffer for them
+ if (!owns_indices) {
+ indices = ufbxi_push_copy(&uc->result, uint32_t, num_indices, indices);
+ ufbxi_check(indices);
+ owns_indices = true;
+ }
+ ufbxi_check(ufbxi_fix_index(uc, &indices[i], ix, num_elems));
+ }
+ }
+
+ *p_dst = indices;
+
+ return 1;
+}
+
+ufbx_static_assert(vertex_real_size, sizeof(ufbx_vertex_real) == sizeof(ufbx_vertex_attrib));
+ufbx_static_assert(vertex_vec2_size, sizeof(ufbx_vertex_vec2) == sizeof(ufbx_vertex_attrib));
+ufbx_static_assert(vertex_vec3_size, sizeof(ufbx_vertex_vec3) == sizeof(ufbx_vertex_attrib));
+ufbx_static_assert(vertex_vec4_size, sizeof(ufbx_vertex_vec4) == sizeof(ufbx_vertex_attrib));
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_warn_polygon_mapping(ufbxi_context *uc, const char *data_name, const char *mapping)
+{
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_POLYGON_MAPPING, "Ignoring geometry '%s' with bad mapping mode '%s'", data_name, mapping));
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_vertex_element(ufbxi_context *uc, ufbx_mesh *mesh, ufbxi_node *node,
+ ufbx_vertex_attrib *attrib, const char *data_name, const char *index_name, const char *w_name, char data_type, size_t num_components)
+{
+ ufbx_real **p_dst_data = (ufbx_real**)&attrib->values.data;
+
+ ufbxi_value_array *data = ufbxi_find_array(node, data_name, data_type);
+ ufbxi_value_array *indices = ufbxi_find_array(node, index_name, 'i');
+
+ if (!uc->opts.strict) {
+ if (!data) return 1;
+ }
+
+ ufbxi_check(data);
+ ufbxi_check(data->size % num_components == 0);
+
+ size_t num_elems = data->size / num_components;
+
+ // HACK: If there's no elements at all keep the attribute as NULL
+ // TODO: Strict mode for this?
+ if (num_elems == 0) {
+ return 1;
+ }
+
+ ufbxi_check(num_elems > 0 && num_elems < INT32_MAX);
+
+ attrib->exists = true;
+ attrib->indices.count = mesh->num_indices;
+
+ const char *mapping = "";
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_MappingInformationType, "C", (char**)&mapping));
+
+ attrib->values.count = num_elems ? num_elems : 1;
+
+ // Data array is always used as-is, if empty set the data to a global
+ // zero buffer so invalid zero index can point to some valid data.
+ // The zero data is offset by 4 elements to accommodate for invalid index (-1)
+ if (num_elems > 0) {
+ *p_dst_data = (ufbx_real*)data->data;
+ } else {
+ *p_dst_data = ufbxi_zero_element + 4;
+ }
+
+ // HACK: Some old exporters seem to use ByPolygon to mean ByPolygonVertex,
+ // it should be quite safe to remap this
+ if (mapping == ufbxi_ByPolygon) {
+ size_t num_indices = indices ? indices->size : num_elems;
+ if (num_indices == mesh->num_indices) {
+ mapping = ufbxi_ByPolygonVertex;
+ }
+ }
+
+ if (indices) {
+ size_t num_indices = indices->size;
+ uint32_t *index_data = (uint32_t*)indices->data;
+
+ if (mapping == ufbxi_ByPolygonVertex) {
+
+ // Indexed by polygon vertex: We can use the provided indices directly.
+ ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, index_data, true, num_indices, mesh->num_indices, num_elems));
+
+ } else if (mapping == ufbxi_ByVertex || mapping == ufbxi_ByVertice) {
+
+ // Indexed by vertex: Follow through the position index mapping to get the final indices.
+ uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
+ ufbxi_check(new_index_data);
+
+ uint32_t *vert_ix = mesh->vertex_indices.data;
+ for (size_t i = 0; i < mesh->num_indices; i++) {
+ uint32_t ix = vert_ix[i];
+ if (ix < num_indices) {
+ new_index_data[i] = index_data[ix];
+ } else {
+ ufbxi_check(ufbxi_fix_index(uc, &new_index_data[i], ix, num_elems));
+ }
+ }
+
+ ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, new_index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
+ attrib->unique_per_vertex = true;
+
+ } else if (mapping == ufbxi_ByPolygon) {
+
+ // Indexed by polygon: Generate new indices based on polygons
+ uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
+ ufbxi_check(new_index_data);
+
+ size_t num_faces = mesh->num_faces;
+ for (size_t face_ix = 0; face_ix < num_faces; face_ix++) {
+ ufbx_face face = mesh->faces.data[face_ix];
+ uint32_t index = UFBX_NO_INDEX;
+ if (face_ix < num_indices) {
+ index = index_data[face_ix];
+ }
+ if (index >= num_elems) {
+ ufbxi_check(ufbxi_fix_index(uc, &index, index, num_elems));
+ }
+ for (size_t i = 0; i < face.num_indices; i++) {
+ new_index_data[face.index_begin + i] = index;
+ }
+ }
+
+ attrib->indices.data = new_index_data;
+
+ } else if (mapping == ufbxi_AllSame) {
+
+ // Indexed by all same: ??? This could be possibly used for making
+ // holes with invalid indices, but that seems really fringe.
+ // Just use the shared zero index buffer for this.
+ uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_indices);
+ attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ attrib->unique_per_vertex = true;
+
+ } else {
+ memset(attrib, 0, sizeof(ufbx_vertex_attrib));
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, data_name, mapping));
+ return 1;
+ }
+
+ } else {
+
+ if (mapping == ufbxi_ByPolygonVertex) {
+
+ // Direct by polygon index: Use shared consecutive array if there's enough
+ // elements, otherwise use a unique truncated consecutive index array.
+ if (num_elems >= mesh->num_indices) {
+ uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_indices);
+ attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
+ } else {
+ uint32_t *index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
+ ufbxi_check(index_data);
+ for (size_t i = 0; i < mesh->num_indices; i++) {
+ index_data[i] = (uint32_t)i;
+ }
+ ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
+ }
+
+ } else if (mapping == ufbxi_ByVertex || mapping == ufbxi_ByVertice) {
+
+ // Direct by vertex: We can re-use the position indices..
+ ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, mesh->vertex_position.indices.data, false, mesh->num_indices, mesh->num_indices, num_elems));
+ attrib->unique_per_vertex = true;
+
+ } else if (mapping == ufbxi_ByPolygon) {
+
+ // Direct by polygon: Generate new indices based on polygons
+ uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
+ ufbxi_check(new_index_data);
+
+ uint32_t num_faces = (uint32_t)mesh->num_faces;
+ for (uint32_t face_ix = 0; face_ix < num_faces; face_ix++) {
+ ufbx_face face = mesh->faces.data[face_ix];
+ for (size_t i = 0; i < face.num_indices; i++) {
+ new_index_data[face.index_begin + i] = face_ix;
+ }
+ }
+
+ ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, new_index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
+
+ } else if (mapping == ufbxi_AllSame) {
+
+ // Direct by all same: This cannot fail as the index list is just zero.
+ uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_indices);
+ attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ attrib->unique_per_vertex = true;
+
+ } else {
+ memset(attrib, 0, sizeof(ufbx_vertex_attrib));
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, data_name, mapping));
+ return 1;
+ }
+ }
+
+ if (uc->opts.retain_vertex_attrib_w && w_name) {
+ ufbxi_value_array *w_data = ufbxi_find_array(node, w_name, 'r');
+ if (w_data) {
+ if (w_data->size == num_elems) {
+ attrib->values_w.count = w_data->size;
+ attrib->values_w.data = (ufbx_real*)w_data->data;
+ } else {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_BAD_VERTEX_W_ATTRIBUTE, "Bad W array size %s=%zu, %s=%zu",
+ w_name, w_data->size, data_name, num_elems));
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_truncated_array(ufbxi_context *uc, void *p_data, size_t *p_count, ufbxi_node *node, const char *name, char fmt, size_t size)
+{
+ ufbxi_value_array *arr = ufbxi_find_array(node, name, fmt);
+ if (!arr) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_GEOMETRY_DATA, "Missing geometry data: %s", name));
+ return 1;
+ }
+
+ *p_count = size;
+
+ void *data = arr->data;
+ if (arr->size < size) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_TRUNCATED_ARRAY, "Truncated array: %s", name));
+
+ size_t elem_size = ufbxi_array_type_size(fmt);
+ void *new_data = ufbxi_push_size(&uc->result, elem_size, size);
+ ufbxi_check(new_data);
+ memcpy(new_data, data, arr->size * elem_size);
+ // Extend the array with the last element if possible
+ if (arr->size > 0) {
+ char *first_elem = (char*)data + (arr->size - 1) * elem_size;
+ for (size_t i = arr->size; i < size; i++) {
+ memcpy((char*)new_data + i * elem_size, first_elem, elem_size);
+ }
+ } else {
+ memset(new_data, 0, size * elem_size);
+ }
+ data = new_data;
+ }
+
+ *(void**)p_data = data;
+ return 1;
+}
+
+ufbxi_noinline static bool ufbxi_uv_set_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_uv_set *a = (const ufbx_uv_set *)va, *b = (const ufbx_uv_set *)vb;
+ return a->index < b->index;
+}
+
+ufbxi_noinline static bool ufbxi_color_set_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_color_set *a = (const ufbx_color_set *)va, *b = (const ufbx_color_set *)vb;
+ return a->index < b->index;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_uv_sets(ufbxi_context *uc, ufbx_uv_set *sets, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_uv_set)));
+ ufbxi_stable_sort(sizeof(ufbx_uv_set), 32, sets, uc->tmp_arr, count, &ufbxi_uv_set_less, NULL);
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_color_sets(ufbxi_context *uc, ufbx_color_set *sets, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_color_set)));
+ ufbxi_stable_sort(sizeof(ufbx_color_set), 32, sets, uc->tmp_arr, count, &ufbxi_color_set_less, NULL);
+ return 1;
+}
+
+typedef struct ufbxi_blend_offset {
+ uint32_t vertex;
+ ufbx_vec3 position_offset;
+ ufbx_vec3 normal_offset;
+} ufbxi_blend_offset;
+
+static ufbxi_noinline bool ufbxi_blend_offset_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_blend_offset *a = (const ufbxi_blend_offset*)va, *b = (const ufbxi_blend_offset*)vb;
+ return a->vertex < b->vertex;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_blend_offsets(ufbxi_context *uc, ufbxi_blend_offset *offsets, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_blend_offset)));
+ ufbxi_stable_sort(sizeof(ufbxi_blend_offset), 16, offsets, uc->tmp_arr, count, &ufbxi_blend_offset_less, NULL);
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_shape(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
+ ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_Indexes);
+ ufbxi_node *node_normals = ufbxi_find_child(node, ufbxi_Normals);
+ if (!node_vertices || !node_indices) return 1;
+
+ ufbx_blend_shape *shape = ufbxi_push_element(uc, info, ufbx_blend_shape, UFBX_ELEMENT_BLEND_SHAPE);
+ ufbxi_check(shape);
+
+ if (uc->opts.ignore_geometry) return 1;
+
+ ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
+ ufbxi_value_array *indices = ufbxi_get_array(node_indices, 'i');
+
+ ufbxi_check(vertices && indices);
+ ufbxi_check(vertices->size % 3 == 0);
+ ufbxi_check(indices->size == vertices->size / 3);
+
+ size_t num_offsets = indices->size;
+ uint32_t *vertex_indices = (uint32_t*)indices->data;
+
+ shape->num_offsets = num_offsets;
+ shape->position_offsets.data = (ufbx_vec3*)vertices->data;
+ shape->offset_vertices.data = vertex_indices;
+ shape->position_offsets.count = num_offsets;
+ shape->offset_vertices.count = num_offsets;
+
+ if (node_normals) {
+ ufbxi_value_array *normals = ufbxi_get_array(node_normals, 'r');
+ ufbxi_check(normals && normals->size == vertices->size);
+ shape->normal_offsets.data = (ufbx_vec3*)normals->data;
+ shape->normal_offsets.count = num_offsets;
+ }
+
+ // Sort the blend shape vertices only if absolutely necessary
+ bool sorted = true;
+ for (size_t i = 1; i < num_offsets; i++) {
+ if (vertex_indices[i - 1] > vertex_indices[i]) {
+ sorted = false;
+ break;
+ }
+ }
+
+ if (!sorted) {
+ ufbxi_blend_offset *offsets = ufbxi_push(&uc->tmp_stack, ufbxi_blend_offset, num_offsets);
+ ufbxi_check(offsets);
+
+ for (size_t i = 0; i < num_offsets; i++) {
+ offsets[i].vertex = shape->offset_vertices.data[i];
+ offsets[i].position_offset = shape->position_offsets.data[i];
+ if (node_normals) offsets[i].normal_offset = shape->normal_offsets.data[i];
+ }
+
+ ufbxi_check(ufbxi_sort_blend_offsets(uc, offsets, num_offsets));
+
+ for (size_t i = 0; i < num_offsets; i++) {
+ shape->offset_vertices.data[i] = offsets[i].vertex;
+ shape->position_offsets.data[i] = offsets[i].position_offset;
+ if (node_normals) shape->normal_offsets.data[i] = offsets[i].normal_offset;
+ }
+ ufbxi_pop(&uc->tmp_stack, ufbxi_blend_offset, num_offsets, NULL);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_synthetic_blend_shapes(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_blend_deformer *deformer = NULL;
+ uint64_t deformer_fbx_id = 0;
+
+ ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
+ if (n->name != ufbxi_Shape) continue;
+
+ ufbx_string name;
+ ufbxi_check(ufbxi_get_val1(n, "S", &name));
+
+ if (deformer == NULL) {
+ deformer = ufbxi_push_synthetic_element(uc, &deformer_fbx_id, n, name.data, ufbx_blend_deformer, UFBX_ELEMENT_BLEND_DEFORMER);
+ ufbxi_check(deformer);
+ ufbxi_check(ufbxi_connect_oo(uc, deformer_fbx_id, info->fbx_id));
+ }
+
+ uint64_t channel_fbx_id = 0;
+ ufbx_blend_channel *channel = ufbxi_push_synthetic_element(uc, &channel_fbx_id, n, name.data, ufbx_blend_channel, UFBX_ELEMENT_BLEND_CHANNEL);
+ ufbxi_check(channel);
+
+ ufbx_real_list weight_list = { NULL, 0 };
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_full_weights, ufbx_real_list, 1, &weight_list));
+
+ size_t num_shape_props = 1;
+ ufbx_prop *shape_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_shape_props);
+ ufbxi_check(shape_props);
+ shape_props[0].name.data = ufbxi_DeformPercent;
+ shape_props[0].name.length = sizeof(ufbxi_DeformPercent) - 1;
+ shape_props[0]._internal_key = ufbxi_get_name_key_c(ufbxi_DeformPercent);
+ shape_props[0].type = UFBX_PROP_NUMBER;
+ shape_props[0].value_real = (ufbx_real)0.0;
+ shape_props[0].value_str = ufbx_empty_string;
+ shape_props[0].value_blob = ufbx_empty_blob;
+
+ ufbx_prop *self_prop = ufbx_find_prop_len(&info->props, name.data, name.length);
+ if (self_prop && (self_prop->type == UFBX_PROP_NUMBER || self_prop->type == UFBX_PROP_INTEGER)) {
+ shape_props[0].value_real = self_prop->value_real;
+ ufbxi_check(ufbxi_connect_pp(uc, info->fbx_id, channel_fbx_id, name, shape_props[0].name));
+ } else if (uc->version < 6000) {
+ ufbxi_check(ufbxi_connect_pp(uc, info->fbx_id, channel_fbx_id, name, shape_props[0].name));
+ }
+
+ channel->name = name;
+ channel->props.props.data = shape_props;
+ channel->props.props.count = num_shape_props;
+
+ ufbxi_element_info shape_info = { 0 };
+
+ shape_info.fbx_id = ufbxi_push_synthetic_id(uc);
+ shape_info.name = name;
+ shape_info.dom_node = ufbxi_get_dom_node(uc, n);
+
+ ufbxi_check(ufbxi_read_shape(uc, n, &shape_info));
+
+ ufbxi_check(ufbxi_connect_oo(uc, channel_fbx_id, deformer_fbx_id));
+ ufbxi_check(ufbxi_connect_oo(uc, shape_info.fbx_id, channel_fbx_id));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_process_indices(ufbxi_context *uc, ufbx_mesh *mesh, uint32_t *index_data)
+{
+ // Count the number of faces and allocate the index list
+ // Indices less than zero (~actual_index) ends a polygon
+ size_t num_total_faces = 0;
+ ufbxi_for (uint32_t, p_ix, index_data, mesh->num_indices) {
+ num_total_faces += ((int32_t)*p_ix < 0) ? 1u : 0u;
+ }
+ mesh->faces.data = ufbxi_push(&uc->result, ufbx_face, num_total_faces);
+ ufbxi_check(mesh->faces.data);
+
+ size_t num_triangles = 0;
+ size_t max_face_triangles = 0;
+ size_t num_bad_faces[3] = { 0 };
+
+ ufbx_face *dst_face = mesh->faces.data;
+ uint32_t *p_face_begin = index_data;
+ ufbxi_for (uint32_t, p_ix, index_data, mesh->num_indices) {
+ uint32_t ix = *p_ix;
+ // Un-negate final indices of polygons
+ if ((int32_t)ix < 0) {
+ ix = ~ix;
+ *p_ix = ix;
+ uint32_t num_indices = (uint32_t)((p_ix - p_face_begin) + 1);
+ dst_face->index_begin = (uint32_t)(p_face_begin - index_data);
+ dst_face->num_indices = num_indices;
+ if (num_indices >= 3) {
+ num_triangles += num_indices - 2;
+ max_face_triangles = ufbxi_max_sz(max_face_triangles, num_indices - 2);
+ } else {
+ num_bad_faces[num_indices]++;
+ }
+ dst_face++;
+ p_face_begin = p_ix + 1;
+ }
+ ufbxi_check((size_t)ix < mesh->num_vertices);
+ }
+
+ mesh->vertex_position.indices.data = index_data;
+ mesh->num_faces = ufbxi_to_size(dst_face - mesh->faces.data);
+ mesh->faces.count = mesh->num_faces;
+ mesh->num_triangles = num_triangles;
+ mesh->max_face_triangles = max_face_triangles;
+ mesh->num_empty_faces = num_bad_faces[0];
+ mesh->num_point_faces = num_bad_faces[1];
+ mesh->num_line_faces = num_bad_faces[2];
+
+ mesh->vertex_first_index.count = mesh->num_vertices;
+ mesh->vertex_first_index.data = ufbxi_push(&uc->result, uint32_t, mesh->num_vertices);
+ ufbxi_check(mesh->vertex_first_index.data);
+
+ ufbxi_for_list(uint32_t, p_vx_ix, mesh->vertex_first_index) {
+ *p_vx_ix = UFBX_NO_INDEX;
+ }
+
+ {
+ size_t num_indices = mesh->num_indices;
+ size_t num_vertices = mesh->num_vertices;
+ uint32_t *vertex_indices = mesh->vertex_indices.data;
+ uint32_t *vertex_first_index = mesh->vertex_first_index.data;
+ for (size_t ix = 0; ix < num_indices; ix++) {
+ uint32_t vx = vertex_indices[ix];
+ if (vx < num_vertices) {
+ if (vertex_first_index[vx] == UFBX_NO_INDEX) {
+ vertex_first_index[vx] = (uint32_t)ix;
+ }
+ } else {
+ ufbxi_check(ufbxi_fix_index(uc, &vertex_indices[ix], vx, mesh->num_vertices));
+ }
+ }
+ }
+
+ // HACK(consecutive-faces): Prepare for finalize to re-use a consecutive/zero
+ // index buffer for face materials..
+ uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_faces);
+ uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_faces);
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_patch_mesh_reals(ufbx_mesh *mesh)
+{
+ mesh->vertex_position.value_reals = 3;
+ mesh->vertex_normal.value_reals = 3;
+ mesh->vertex_uv.value_reals = 2;
+ mesh->vertex_tangent.value_reals = 3;
+ mesh->vertex_bitangent.value_reals = 3;
+ mesh->vertex_color.value_reals = 4;
+ mesh->vertex_crease.value_reals = 1;
+ mesh->skinned_position.value_reals = 3;
+ mesh->skinned_normal.value_reals = 3;
+
+ ufbxi_nounroll ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ set->vertex_uv.value_reals = 2;
+ set->vertex_tangent.value_reals = 3;
+ set->vertex_bitangent.value_reals = 3;
+ }
+
+ ufbxi_nounroll ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
+ set->vertex_color.value_reals = 4;
+ }
+}
+
+typedef struct {
+ uint32_t id, index;
+} ufbxi_id_group;
+
+static bool ufbxi_less_int32(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const int32_t a = *(const int32_t*)va, b = *(const int32_t*)vb;
+ return a < b;
+}
+
+ufbx_static_assert(mesh_mat_point_faces, offsetof(ufbx_mesh_part, num_point_faces) - offsetof(ufbx_mesh_part, num_empty_faces) == 1 * sizeof(size_t));
+ufbx_static_assert(mesh_mat_line_faces, offsetof(ufbx_mesh_part, num_line_faces) - offsetof(ufbx_mesh_part, num_empty_faces) == 2 * sizeof(size_t));
+static ufbxi_forceinline void ufbxi_mesh_part_add_face(ufbx_mesh_part *part, uint32_t num_indices)
+{
+ part->num_faces++;
+ if (num_indices >= 3) {
+ part->num_triangles += num_indices - 2;
+ } else {
+ // `num_empty/point/line_faces` are consecutive, see static asserts above.
+ // cppcheck-suppress objectIndex
+ (&part->num_empty_faces)[num_indices]++;
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_assign_face_groups(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh, size_t *p_consecutive_indices, bool retain_parts)
+{
+ size_t num_faces = mesh->num_faces;
+ ufbxi_check_err(error, num_faces > 0);
+ ufbxi_check_err(error, num_faces < UINT32_MAX);
+ ufbxi_check_err(error, mesh->face_group.count == num_faces);
+
+ uint32_t *ids = ufbxi_push(buf, uint32_t, num_faces);
+ ufbxi_check_err(error, ids);
+
+ uint32_t num_ids = 0;
+
+ ufbxi_id_group seen_ids[1 << UFBXI_FACE_GROUP_HASH_BITS];
+ memset(seen_ids, 0, sizeof(seen_ids));
+
+ uint32_t seed = 2654435769u;
+ uint32_t rehash_threshold = 256;
+
+ // Loosely deduplicate group IDs
+ ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
+ uint32_t id = *p_id;
+ uint32_t id_hash = (id * seed) >> (32u - UFBXI_FACE_GROUP_HASH_BITS);
+ if (seen_ids[id_hash].id != id || seen_ids[id_hash].index == 0) {
+ seen_ids[id_hash].id = id;
+ if (++seen_ids[id_hash].index > rehash_threshold) {
+ seed *= seed;
+ rehash_threshold *= 2;
+ }
+ ids[num_ids++] = id;
+ }
+ }
+
+ // Sort and deduplicate remaining IDs
+ ufbxi_unstable_sort(ids, num_ids, sizeof(uint32_t), &ufbxi_less_int32, NULL);
+
+ size_t num_groups = 0;
+ for (size_t i = 0; i < num_ids; ) {
+ uint32_t id = ids[i];
+ ids[num_groups++] = id;
+ do { i++; } while (i < num_ids && ids[i] == id);
+ }
+
+ // Allocate group info structs
+ ufbx_face_group *groups = ufbxi_push_zero(buf, ufbx_face_group, num_groups);
+ ufbxi_check_err(error, groups);
+ for (size_t i = 0; i < num_groups; i++) {
+ groups[i].id = (int32_t)ids[i];
+ groups[i].name.data = ufbxi_empty_char;
+ }
+
+ mesh->face_groups.data = groups;
+ mesh->face_groups.count = num_groups;
+
+ ufbx_mesh_part *parts = NULL;
+ if (retain_parts) {
+ parts = ufbxi_push_zero(buf, ufbx_mesh_part, num_groups);
+ ufbxi_check_err(error, parts);
+ mesh->face_group_parts.data = parts;
+ mesh->face_group_parts.count = num_groups;
+ }
+
+ // Optimization: Use `consecutive_indices` for a single group
+ if (p_consecutive_indices && num_groups == 1) {
+ memset(mesh->face_group.data, 0, sizeof(uint32_t) * num_faces);
+
+ if (parts) {
+ parts[0].face_indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
+ parts[0].face_indices.count = num_faces;
+ parts[0].num_empty_faces = mesh->num_empty_faces;
+ parts[0].num_point_faces = mesh->num_point_faces;
+ parts[0].num_line_faces = mesh->num_line_faces;
+ parts[0].num_faces = num_faces;
+ parts[0].num_triangles = mesh->num_triangles;
+ }
+
+ *p_consecutive_indices = ufbxi_max_sz(*p_consecutive_indices, num_faces);
+ return 1;
+ }
+
+ memset(seen_ids, 0, sizeof(seen_ids));
+
+ // Count faces and triangles per group and reassign IDs
+ const ufbx_face *p_face = mesh->faces.data;
+ ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
+ uint32_t id = *p_id;
+ uint32_t id_hash = (id * seed) >> (32u - UFBXI_FACE_GROUP_HASH_BITS);
+
+ uint32_t num_indices = p_face->num_indices;
+
+ size_t index;
+ if (seen_ids[id_hash].id == id && seen_ids[id_hash].index > 0) {
+ index = seen_ids[id_hash].index - 1;
+ *p_id = (uint32_t)index;
+ } else {
+ int32_t signed_id = (int32_t)id;
+ index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_face_group, 8, &index, groups, 0, num_groups, ( a->id < signed_id ), ( a->id == signed_id ));
+ ufbx_assert(index < num_groups);
+ seen_ids[id_hash].id = id;
+ seen_ids[id_hash].index = (uint32_t)index + 1;
+ }
+
+ if (parts) {
+ ufbxi_mesh_part_add_face(&parts[index], num_indices);
+ }
+
+ *p_id = (uint32_t)index;
+ p_face++;
+ }
+
+ if (!parts) return 1;
+
+ // Subdivide `ids` for per-group `face_indices`
+ uint32_t *face_indices = ids;
+ uint32_t part_index = 0;
+ ufbxi_for(ufbx_mesh_part, part, parts, num_groups) {
+ part->index = part_index++;
+ part->face_indices.data = face_indices;
+ face_indices += part->num_faces;
+ }
+ ufbx_assert(face_indices == ids + num_faces);
+
+ // Collect per-group faces
+ uint32_t face_index = 0;
+ ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
+ ufbx_mesh_part *part = &parts[*p_id];
+ part->face_indices.data[part->face_indices.count++] = face_index++;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_update_face_groups(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh, bool need_copy)
+{
+ size_t num_faces = mesh->faces.count;
+ size_t num_groups = mesh->face_group_parts.count;
+ if (num_groups == 0) return 1;
+
+ if (need_copy) {
+ mesh->face_group_parts.data = ufbxi_push_zero(buf, ufbx_mesh_part, num_groups);
+ ufbxi_check_err(error, mesh->face_group_parts.data);
+ }
+
+ uint32_t *face_indices = ufbxi_push(buf, uint32_t, num_faces);
+ ufbxi_check_err(error, face_indices);
+
+ ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
+ ufbx_mesh_part *part = &mesh->face_group_parts.data[mesh->face_group.data[i]];
+ ufbxi_mesh_part_add_face(part, mesh->faces.data[i].num_indices);
+ }
+
+ uint32_t part_index = 0;
+ ufbxi_for_list(ufbx_mesh_part, part, mesh->face_group_parts) {
+ part->index = part_index++;
+ part->face_indices.data = face_indices;
+ part->face_indices.count = 0;
+ face_indices += part->num_faces;
+ }
+
+ ufbxi_nounroll for (uint32_t i = 0; i < num_faces; i++) {
+ ufbx_mesh_part *part = &mesh->face_group_parts.data[mesh->face_group.data[i]];
+ part->face_indices.data[part->face_indices.count++] = i;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_mesh(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_mesh *ufbxi_restrict mesh = ufbxi_push_element(uc, info, ufbx_mesh, UFBX_ELEMENT_MESH);
+ ufbxi_check(mesh);
+
+ // In up to version 7100 FBX files blend shapes are contained within the same geometry node
+ if (uc->version <= 7100) {
+ ufbxi_check(ufbxi_read_synthetic_blend_shapes(uc, node, info));
+ }
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ // Sometimes there are empty meshes in FBX files?
+ // TODO: Should these be included in output? option? strict mode?
+ ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
+ ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_PolygonVertexIndex);
+ if (!node_vertices) return 1;
+
+ if (uc->opts.ignore_geometry) return 1;
+
+ ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
+ ufbxi_value_array *indices = node_indices ? ufbxi_get_array(node_indices, 'i') : NULL;
+ ufbxi_value_array *edge_indices = ufbxi_find_array(node, ufbxi_Edges, 'i');
+ ufbxi_check(vertices);
+ ufbxi_check(!node_indices || indices); // If node_indices exists, it must be an array
+ ufbxi_check(vertices->size % 3 == 0);
+
+ mesh->num_vertices = vertices->size / 3;
+ mesh->num_indices = indices ? indices->size : 0;
+
+ uint32_t *index_data = indices ? (uint32_t*)indices->data : NULL;
+
+ // Duplicate `index_data` for modification if we retain DOM
+ if (uc->opts.retain_dom) {
+ index_data = ufbxi_push_copy(&uc->result, uint32_t, mesh->num_indices, index_data);
+ ufbxi_check(index_data);
+ }
+
+ mesh->vertices.data = (ufbx_vec3*)vertices->data;
+ mesh->vertices.count = mesh->num_vertices;
+ mesh->vertex_indices.data = index_data;
+ mesh->vertex_indices.count = mesh->num_indices;
+
+ mesh->vertex_position.exists = true;
+ mesh->vertex_position.values.data = (ufbx_vec3*)vertices->data;
+ mesh->vertex_position.values.count = mesh->num_vertices;
+ mesh->vertex_position.indices.data = index_data;
+ mesh->vertex_position.indices.count = mesh->num_indices;
+ mesh->vertex_position.unique_per_vertex = true;
+
+ // Check/make sure that the last index is negated (last of polygon)
+ if (mesh->num_indices > 0) {
+ if ((int32_t)index_data[mesh->num_indices - 1] >= 0) {
+ if (uc->opts.strict) ufbxi_fail("Non-negated last index");
+ index_data[mesh->num_indices - 1] = ~index_data[mesh->num_indices - 1];
+ }
+ }
+
+ // Read edges before un-negating the indices
+ if (edge_indices) {
+ size_t num_edges = edge_indices->size;
+ ufbx_edge *edges = ufbxi_push(&uc->result, ufbx_edge, num_edges);
+ ufbxi_check(edges);
+
+ size_t dst_ix = 0;
+
+ // Edges are represented using a single index into PolygonVertexIndex.
+ // The edge is between two consecutive vertices in the polygon.
+ uint32_t *edge_data = (uint32_t*)edge_indices->data;
+ for (size_t i = 0; i < num_edges; i++) {
+ uint32_t index_ix = edge_data[i];
+ if (index_ix >= mesh->num_indices) {
+ if (uc->opts.strict) ufbxi_fail("Edge index out of bounds");
+ continue;
+ }
+ edges[dst_ix].a = index_ix;
+ if ((int32_t)index_data[index_ix] < 0) {
+ // Previous index is the last one of this polygon, rewind to first index.
+ while (index_ix > 0 && (int32_t)index_data[index_ix - 1] >= 0) {
+ index_ix--;
+ }
+ } else {
+ // Connect to the next index in the same polygon
+ index_ix++;
+ }
+ ufbxi_check(index_ix < mesh->num_indices);
+ edges[dst_ix].b = index_ix;
+ dst_ix++;
+ }
+
+ mesh->edges.data = edges;
+ mesh->edges.count = dst_ix;
+ mesh->num_edges = mesh->edges.count;
+ }
+
+ ufbxi_check(ufbxi_process_indices(uc, mesh, index_data));
+
+ // Count the number of UV/color sets
+ size_t num_uv = 0, num_color = 0, num_bitangents = 0, num_tangents = 0;
+ ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
+ if (n->name == ufbxi_LayerElementUV) num_uv++;
+ if (n->name == ufbxi_LayerElementColor) num_color++;
+ if (n->name == ufbxi_LayerElementBinormal) num_bitangents++;
+ if (n->name == ufbxi_LayerElementTangent) num_tangents++;
+ }
+
+ size_t num_textures = 0;
+
+ ufbxi_tangent_layer *bitangents = ufbxi_push_zero(&uc->tmp_stack, ufbxi_tangent_layer, num_bitangents);
+ ufbxi_tangent_layer *tangents = ufbxi_push_zero(&uc->tmp_stack, ufbxi_tangent_layer, num_tangents);
+ ufbxi_check(bitangents);
+ ufbxi_check(tangents);
+
+ mesh->uv_sets.data = ufbxi_push_zero(&uc->result, ufbx_uv_set, num_uv);
+ mesh->color_sets.data = ufbxi_push_zero(&uc->result, ufbx_color_set, num_color);
+ ufbxi_check(mesh->uv_sets.data);
+ ufbxi_check(mesh->color_sets.data);
+
+ size_t num_bitangents_read = 0, num_tangents_read = 0;
+ ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
+ if (n->name[0] != 'L') continue; // All names start with 'LayerElement*'
+
+ if (n->name == ufbxi_LayerElementNormal) {
+ if (mesh->vertex_normal.exists) continue;
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&mesh->vertex_normal,
+ ufbxi_Normals, ufbxi_NormalsIndex, ufbxi_NormalsW, 'r', 3));
+ } else if (n->name == ufbxi_LayerElementBinormal) {
+ ufbxi_tangent_layer *layer = &bitangents[num_bitangents_read++];
+
+ ufbxi_ignore(ufbxi_get_val1(n, "I", &layer->index));
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&layer->elem,
+ ufbxi_Binormals, ufbxi_BinormalsIndex, ufbxi_BinormalsW, 'r', 3));
+ if (!layer->elem.exists) num_bitangents_read--;
+
+ } else if (n->name == ufbxi_LayerElementTangent) {
+ ufbxi_tangent_layer *layer = &tangents[num_tangents_read++];
+
+ ufbxi_ignore(ufbxi_get_val1(n, "I", &layer->index));
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&layer->elem,
+ ufbxi_Tangents, ufbxi_TangentsIndex, ufbxi_TangentsW, 'r', 3));
+ if (!layer->elem.exists) num_tangents_read--;
+
+ } else if (n->name == ufbxi_LayerElementUV) {
+ ufbx_uv_set *set = &mesh->uv_sets.data[mesh->uv_sets.count++];
+
+ ufbxi_ignore(ufbxi_get_val1(n, "I", &set->index));
+ if (!ufbxi_find_val1(n, ufbxi_Name, "S", &set->name)) {
+ set->name = ufbx_empty_string;
+ }
+
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&set->vertex_uv,
+ ufbxi_UV, ufbxi_UVIndex, NULL, 'r', 2));
+ if (!set->vertex_uv.exists) mesh->uv_sets.count--;
+
+ } else if (n->name == ufbxi_LayerElementColor) {
+ ufbx_color_set *set = &mesh->color_sets.data[mesh->color_sets.count++];
+
+ ufbxi_ignore(ufbxi_get_val1(n, "I", &set->index));
+ if (!ufbxi_find_val1(n, ufbxi_Name, "S", &set->name)) {
+ set->name = ufbx_empty_string;
+ }
+
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&set->vertex_color,
+ ufbxi_Colors, ufbxi_ColorIndex, NULL, 'r', 4));
+ if (!set->vertex_color.exists) mesh->color_sets.count--;
+
+ } else if (n->name == ufbxi_LayerElementVertexCrease) {
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&mesh->vertex_crease,
+ ufbxi_VertexCrease, ufbxi_VertexCreaseIndex, NULL, 'r', 1));
+ } else if (n->name == ufbxi_LayerElementEdgeCrease) {
+ const char *mapping = "";
+ ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByEdge) {
+ if (mesh->edge_crease.count) continue;
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_crease.data, &mesh->edge_crease.count, n, ufbxi_EdgeCrease, 'r', mesh->num_edges));
+ } else {
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_EdgeCrease, mapping));
+ }
+ } else if (n->name == ufbxi_LayerElementSmoothing) {
+ const char *mapping = "";
+ ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByEdge) {
+ if (mesh->edge_smoothing.count) continue;
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_smoothing.data, &mesh->edge_smoothing.count, n, ufbxi_Smoothing, 'b', mesh->num_edges));
+ } else if (mapping == ufbxi_ByPolygon) {
+ if (mesh->face_smoothing.count) continue;
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_smoothing.data, &mesh->face_smoothing.count, n, ufbxi_Smoothing, 'b', mesh->num_faces));
+ } else {
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Smoothing, mapping));
+ }
+ } else if (n->name == ufbxi_LayerElementVisibility) {
+ const char *mapping = "";
+ ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByEdge) {
+ if (mesh->edge_visibility.count) continue;
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_visibility.data, &mesh->edge_visibility.count, n, ufbxi_Visibility, 'b', mesh->num_edges));
+ } else {
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Visibility, mapping));
+ }
+ } else if (n->name == ufbxi_LayerElementMaterial) {
+ if (mesh->face_material.count) continue;
+ const char *mapping = "";
+ ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByPolygon) {
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_material.data, &mesh->face_material.count, n, ufbxi_Materials, 'i', mesh->num_faces));
+ } else if (mapping == ufbxi_AllSame) {
+ ufbxi_value_array *arr = ufbxi_find_array(n, ufbxi_Materials, 'i');
+ ufbxi_check(arr && arr->size >= 1);
+ uint32_t material = *(uint32_t*)arr->data;
+ mesh->face_material.count = mesh->num_faces;
+ if (material == 0) {
+ mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ } else {
+ mesh->face_material.data = ufbxi_push(&uc->result, uint32_t, mesh->num_faces);
+ ufbxi_check(mesh->face_material.data);
+ ufbxi_for_list(uint32_t, p_mat, mesh->face_material) {
+ *p_mat = material;
+ }
+ }
+ } else {
+ ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Materials, mapping));
+ }
+ } else if (n->name == ufbxi_LayerElementPolygonGroup) {
+ if (mesh->face_group.count) continue;
+ const char *mapping = NULL;
+ ufbxi_check(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByPolygon) {
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_group.data, &mesh->face_group.count, n, ufbxi_PolygonGroup, 'i', mesh->num_faces));
+ }
+ } else if (n->name == ufbxi_LayerElementHole) {
+ if (mesh->face_group.count) continue;
+ const char *mapping = NULL;
+ ufbxi_check(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
+ if (mapping == ufbxi_ByPolygon) {
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_hole.data, &mesh->face_hole.count, n, ufbxi_Hole, 'b', mesh->num_faces));
+ }
+ } else if (!strncmp(n->name, "LayerElement", 12)) {
+
+ // Make sure the name has no internal zero bytes
+ ufbxi_check(!memchr(n->name, '\0', n->name_len));
+
+ // What?! 6x00 stores textures in mesh geometry, eg. "LayerElementTexture",
+ // "LayerElementDiffuseFactorTextures", "LayerElementEmissive_Textures"...
+ ufbx_string prop_name = ufbx_empty_string;
+ if (n->name_len > 20 && !strcmp(n->name + n->name_len - 8, "Textures")) {
+ prop_name.data = n->name + 12;
+ prop_name.length = (size_t)n->name_len - 20;
+ if (prop_name.data[prop_name.length - 1] == '_') {
+ prop_name.length -= 1;
+ }
+ } else if (!strcmp(n->name, "LayerElementTexture")) {
+ prop_name.data = "Diffuse";
+ prop_name.length = 7;
+ }
+
+ if (prop_name.length > 0) {
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop_name, false));
+ const char *mapping = NULL;
+ if (ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping)) {
+ ufbxi_value_array *arr = ufbxi_find_array(n, ufbxi_TextureId, 'i');
+
+ ufbxi_tmp_mesh_texture *tex = ufbxi_push_zero(&uc->tmp_mesh_textures, ufbxi_tmp_mesh_texture, 1);
+ ufbxi_check(tex);
+ if (arr) {
+ tex->face_texture = (uint32_t*)arr->data;
+ tex->num_faces = arr->size;
+ }
+ tex->prop_name = prop_name;
+ tex->all_same = (mapping == ufbxi_AllSame);
+ num_textures++;
+ }
+ }
+ }
+ }
+
+ // Always use a default zero material, this will be removed if no materials are found
+ if (!mesh->face_material.count) {
+ uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_faces);
+ mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ mesh->face_material.count = mesh->num_faces;
+ }
+
+ if (uc->opts.strict) {
+ ufbxi_check(mesh->uv_sets.count == num_uv);
+ ufbxi_check(mesh->color_sets.count == num_color);
+ ufbxi_check(num_bitangents_read == num_bitangents);
+ ufbxi_check(num_tangents_read == num_tangents);
+ }
+
+ // Connect bitangents/tangents to UV sets
+ ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
+ if (n->name != ufbxi_Layer) continue;
+ ufbx_uv_set *uv_set = NULL;
+ ufbxi_tangent_layer *bitangent_layer = NULL;
+ ufbxi_tangent_layer *tangent_layer = NULL;
+
+ ufbxi_for (ufbxi_node, c, n->children, n->num_children) {
+ uint32_t index;
+ const char *type;
+ if (c->name != ufbxi_LayerElement) continue;
+ if (!ufbxi_find_val1(c, ufbxi_TypedIndex, "I", &index)) continue;
+ if (!ufbxi_find_val1(c, ufbxi_Type, "C", (char**)&type)) continue;
+
+ if (type == ufbxi_LayerElementUV) {
+ ufbxi_for(ufbx_uv_set, set, mesh->uv_sets.data, mesh->uv_sets.count) {
+ if (set->index == index) {
+ uv_set = set;
+ break;
+ }
+ }
+ } else if (type == ufbxi_LayerElementBinormal) {
+ ufbxi_for(ufbxi_tangent_layer, layer, bitangents, num_bitangents_read) {
+ if (layer->index == index) {
+ bitangent_layer = layer;
+ break;
+ }
+ }
+ } else if (type == ufbxi_LayerElementTangent) {
+ ufbxi_for(ufbxi_tangent_layer, layer, tangents, num_tangents_read) {
+ if (layer->index == index) {
+ tangent_layer = layer;
+ break;
+ }
+ }
+ }
+ }
+
+ if (uv_set) {
+ if (bitangent_layer) {
+ uv_set->vertex_bitangent = bitangent_layer->elem;
+ }
+ if (tangent_layer) {
+ uv_set->vertex_tangent = tangent_layer->elem;
+ }
+ }
+ }
+
+ mesh->skinned_is_local = true;
+ mesh->skinned_position = mesh->vertex_position;
+ mesh->skinned_normal = mesh->vertex_normal;
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ if (mesh->face_group.count > 0 && mesh->face_groups.count == 0) {
+ ufbxi_check(ufbxi_assign_face_groups(&uc->result, &uc->error, mesh, &uc->max_consecutive_indices, uc->retain_mesh_parts));
+ }
+
+ // Sort UV and color sets by set index
+ ufbxi_check(ufbxi_sort_uv_sets(uc, mesh->uv_sets.data, mesh->uv_sets.count));
+ ufbxi_check(ufbxi_sort_color_sets(uc, mesh->color_sets.data, mesh->color_sets.count));
+
+ if (num_textures > 0) {
+ ufbxi_mesh_extra *extra = ufbxi_push_element_extra(uc, mesh->element.element_id, ufbxi_mesh_extra);
+ ufbxi_check(extra);
+ extra->texture_count = num_textures;
+ extra->texture_arr = ufbxi_push_pop(&uc->tmp, &uc->tmp_mesh_textures, ufbxi_tmp_mesh_texture, num_textures);
+ ufbxi_check(extra->texture_arr);
+ }
+
+ // Subdivision
+
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_PreviewDivisionLevels, "I", &mesh->subdivision_preview_levels));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RenderDivisionLevels, "I", &mesh->subdivision_render_levels));
+
+ int32_t smoothness, boundary;
+ if (ufbxi_find_val1(node, ufbxi_Smoothness, "I", &smoothness)) {
+ if (smoothness >= 0 && smoothness <= UFBX_SUBDIVISION_DISPLAY_SMOOTH) {
+ mesh->subdivision_display_mode = (ufbx_subdivision_display_mode)smoothness;
+ }
+ }
+ if (ufbxi_find_val1(node, ufbxi_BoundaryRule, "I", &boundary)) {
+ if (boundary >= 0 && boundary <= UFBX_SUBDIVISION_BOUNDARY_SHARP_CORNERS - 1) {
+ mesh->subdivision_boundary = (ufbx_subdivision_boundary)(boundary + 1);
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_noinline static ufbx_nurbs_topology ufbxi_read_nurbs_topology(const char *form)
+{
+ if (!strcmp(form, "Open")) {
+ return UFBX_NURBS_TOPOLOGY_OPEN;
+ } else if (!strcmp(form, "Closed")) {
+ return UFBX_NURBS_TOPOLOGY_CLOSED;
+ } else if (!strcmp(form, "Periodic")) {
+ return UFBX_NURBS_TOPOLOGY_PERIODIC;
+ }
+ return UFBX_NURBS_TOPOLOGY_OPEN;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_nurbs_curve(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_nurbs_curve *nurbs = ufbxi_push_element(uc, info, ufbx_nurbs_curve, UFBX_ELEMENT_NURBS_CURVE);
+ ufbxi_check(nurbs);
+
+ int32_t dimension = 3;
+
+ const char *form = NULL;
+ ufbxi_check(ufbxi_find_val1(node, ufbxi_Order, "I", &nurbs->basis.order));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Dimension, "I", &dimension));
+ ufbxi_check(ufbxi_find_val1(node, ufbxi_Form, "C", (char**)&form));
+ nurbs->basis.topology = ufbxi_read_nurbs_topology(form);
+ nurbs->basis.is_2d = dimension == 2;
+
+ if (!uc->opts.ignore_geometry) {
+ ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
+ ufbxi_value_array *knot = ufbxi_find_array(node, ufbxi_KnotVector, 'r');
+ ufbxi_check(points);
+ ufbxi_check(knot);
+ ufbxi_check(points->size % 4 == 0);
+
+ nurbs->control_points.count = points->size / 4;
+ nurbs->control_points.data = (ufbx_vec4*)points->data;
+ nurbs->basis.knot_vector.data = (ufbx_real*)knot->data;
+ nurbs->basis.knot_vector.count = knot->size;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_nurbs_surface(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_nurbs_surface *nurbs = ufbxi_push_element(uc, info, ufbx_nurbs_surface, UFBX_ELEMENT_NURBS_SURFACE);
+ ufbxi_check(nurbs);
+
+ const char *form_u = NULL, *form_v = NULL;
+ size_t dimension_u = 0, dimension_v = 0;
+ int32_t step_u = 0, step_v = 0;
+ ufbxi_check(ufbxi_find_val2(node, ufbxi_NurbsSurfaceOrder, "II", &nurbs->basis_u.order, &nurbs->basis_v.order));
+ ufbxi_check(ufbxi_find_val2(node, ufbxi_Dimensions, "ZZ", &dimension_u, &dimension_v));
+ ufbxi_check(ufbxi_find_val2(node, ufbxi_Step, "II", &step_u, &step_v));
+ ufbxi_check(ufbxi_find_val2(node, ufbxi_Form, "CC", (char**)&form_u, (char**)&form_v));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FlipNormals, "B", &nurbs->flip_normals));
+
+ // Support control point area up to 2^32, as a larger control point array cannot be represented in binary FBX.
+ // This guards against users doing `dimension_u * dimension_v`, causing a 32-bit overflow.
+ if (dimension_u > 0) {
+ ufbxi_check(dimension_v <= UINT32_MAX / dimension_u);
+ }
+
+ nurbs->basis_u.topology = ufbxi_read_nurbs_topology(form_u);
+ nurbs->basis_v.topology = ufbxi_read_nurbs_topology(form_v);
+ nurbs->num_control_points_u = dimension_u;
+ nurbs->num_control_points_v = dimension_v;
+ nurbs->span_subdivision_u = step_u > 0 ? (uint32_t)step_u : 4u;
+ nurbs->span_subdivision_v = step_v > 0 ? (uint32_t)step_v : 4u;
+
+ if (!uc->opts.ignore_geometry) {
+ ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
+ ufbxi_value_array *knot_u = ufbxi_find_array(node, ufbxi_KnotVectorU, 'r');
+ ufbxi_value_array *knot_v = ufbxi_find_array(node, ufbxi_KnotVectorV, 'r');
+ ufbxi_check(points);
+ ufbxi_check(knot_u);
+ ufbxi_check(knot_v);
+ ufbxi_check(points->size % 4 == 0);
+ ufbxi_check(points->size / 4 == (size_t)dimension_u * (size_t)dimension_v);
+
+ nurbs->control_points.count = points->size / 4;
+ nurbs->control_points.data = (ufbx_vec4*)points->data;
+ nurbs->basis_u.knot_vector.data = (ufbx_real*)knot_u->data;
+ nurbs->basis_u.knot_vector.count = knot_u->size;
+ nurbs->basis_v.knot_vector.data = (ufbx_real*)knot_v->data;
+ nurbs->basis_v.knot_vector.count = knot_v->size;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_line(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_line_curve *line = ufbxi_push_element(uc, info, ufbx_line_curve, UFBX_ELEMENT_LINE_CURVE);
+ ufbxi_check(line);
+
+ if (!uc->opts.ignore_geometry) {
+ ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
+ ufbxi_value_array *points_index = ufbxi_find_array(node, ufbxi_PointsIndex, 'i');
+ ufbxi_check(points);
+ ufbxi_check(points_index);
+ ufbxi_check(points->size % 3 == 0);
+
+ if (points->size > 0) {
+ line->control_points.count = points->size / 3;
+ line->control_points.data = (ufbx_vec3*)points->data;
+ line->point_indices.count = points_index->size;
+ line->point_indices.data = (uint32_t*)points_index->data;
+
+ ufbxi_check(line->control_points.count < INT32_MAX);
+
+ // Count end points
+ size_t num_segments = 1;
+ if (line->point_indices.count > 0) {
+ for (size_t i = 0; i < line->point_indices.count - 1; i++) {
+ uint32_t ix = line->point_indices.data[i];
+ num_segments += (int32_t)ix < 0 ? 1u : 0u;
+ }
+ }
+
+ size_t prev_end = 0;
+ line->segments.data = ufbxi_push(&uc->result, ufbx_line_segment, num_segments);
+ ufbxi_check(line->segments.data);
+ for (size_t i = 0; i < line->point_indices.count; i++) {
+ uint32_t ix = line->point_indices.data[i];
+ if ((int32_t)ix < 0) {
+ ix = ~ix;
+ if (i + 1 < line->point_indices.count) {
+ ufbx_line_segment *segment = &line->segments.data[line->segments.count++];
+ segment->index_begin = (uint32_t)prev_end;
+ segment->num_indices = (uint32_t)(i - prev_end);
+ prev_end = i;
+ }
+ }
+
+ if (ix < line->control_points.count) {
+ line->point_indices.data[i] = ix;
+ } else {
+ ufbxi_check(ufbxi_fix_index(uc, &line->point_indices.data[i], ix, line->control_points.count));
+ }
+ }
+
+ ufbx_line_segment *segment = &line->segments.data[line->segments.count++];
+ segment->index_begin = (uint32_t)prev_end;
+ segment->num_indices = (uint32_t)ufbxi_to_size(line->point_indices.count - prev_end);
+ ufbx_assert(line->segments.count == num_segments);
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_read_transform_matrix(ufbx_matrix *m, ufbx_real *data)
+{
+ m->m00 = data[ 0]; m->m10 = data[ 1]; m->m20 = data[ 2];
+ m->m01 = data[ 4]; m->m11 = data[ 5]; m->m21 = data[ 6];
+ m->m02 = data[ 8]; m->m12 = data[ 9]; m->m22 = data[10];
+ m->m03 = data[12]; m->m13 = data[13]; m->m23 = data[14];
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_bone(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type)
+{
+ (void)node;
+
+ ufbx_bone *bone = ufbxi_push_element(uc, info, ufbx_bone, UFBX_ELEMENT_BONE);
+ ufbxi_check(bone);
+
+ if (sub_type == ufbxi_Root) {
+ bone->is_root = true;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_marker(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type, ufbx_marker_type type)
+{
+ (void)node;
+ (void)sub_type;
+
+ ufbx_marker *marker = ufbxi_push_element(uc, info, ufbx_marker, UFBX_ELEMENT_MARKER);
+ ufbxi_check(marker);
+
+ marker->type = type;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_skin(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_skin_deformer *skin = ufbxi_push_element(uc, info, ufbx_skin_deformer, UFBX_ELEMENT_SKIN_DEFORMER);
+ ufbxi_check(skin);
+
+ const char *skinning_type = NULL;
+ if (ufbxi_find_val1(node, ufbxi_SkinningType, "C", (char**)&skinning_type)) {
+ if (!strcmp(skinning_type, "Rigid")) {
+ skin->skinning_method = UFBX_SKINNING_METHOD_RIGID;
+ } else if (!strcmp(skinning_type, "Linear")) {
+ skin->skinning_method = UFBX_SKINNING_METHOD_LINEAR;
+ } else if (!strcmp(skinning_type, "DualQuaternion")) {
+ skin->skinning_method = UFBX_SKINNING_METHOD_DUAL_QUATERNION;
+ } else if (!strcmp(skinning_type, "Blend")) {
+ skin->skinning_method = UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR;
+ }
+ }
+
+ ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
+ ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_BlendWeights, 'r');
+ if (indices && weights) {
+ // TODO strict: ufbxi_check(indices->size == weights->size);
+ skin->num_dq_weights = ufbxi_min_sz(indices->size, weights->size);
+ skin->dq_vertices.data = (uint32_t*)indices->data;
+ skin->dq_weights.data = (ufbx_real*)weights->data;
+ skin->dq_vertices.count = skin->num_dq_weights;
+ skin->dq_weights.count = skin->num_dq_weights;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_skin_cluster(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_skin_cluster *cluster = ufbxi_push_element(uc, info, ufbx_skin_cluster, UFBX_ELEMENT_SKIN_CLUSTER);
+ ufbxi_check(cluster);
+
+ ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
+ ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_Weights, 'r');
+
+ if (indices && weights) {
+ ufbxi_check(indices->size == weights->size);
+ cluster->num_weights = indices->size;
+ cluster->vertices.data = (uint32_t*)indices->data;
+ cluster->weights.data = (ufbx_real*)weights->data;
+ cluster->vertices.count = cluster->num_weights;
+ cluster->weights.count = cluster->num_weights;
+ }
+
+ ufbxi_value_array *transform = ufbxi_find_array(node, ufbxi_Transform, 'r');
+ ufbxi_value_array *transform_link = ufbxi_find_array(node, ufbxi_TransformLink, 'r');
+ if (transform && transform_link) {
+ ufbxi_check(transform->size >= 16);
+ ufbxi_check(transform_link->size >= 16);
+
+ ufbxi_read_transform_matrix(&cluster->mesh_node_to_bone, (ufbx_real*)transform->data);
+ ufbxi_read_transform_matrix(&cluster->bind_to_world, (ufbx_real*)transform_link->data);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_blend_channel(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_blend_channel *channel = ufbxi_push_element(uc, info, ufbx_blend_channel, UFBX_ELEMENT_BLEND_CHANNEL);
+ ufbxi_check(channel);
+
+ ufbx_real_list list = { NULL, 0 };
+ ufbxi_value_array *full_weights = ufbxi_find_array(node, ufbxi_FullWeights, 'r');
+ if (full_weights) {
+ list.data = (ufbx_real*)full_weights->data;
+ list.count = full_weights->size;
+ }
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_full_weights, ufbx_real_list, 1, &list));
+
+ // Blender saves blend shapes with DeformPercent as a field, not a property.
+ // However, the animations are mapped to the DeformPercent property.
+ ufbxi_node *deform_percent = ufbxi_find_child(node, ufbxi_DeformPercent);
+ if (channel->props.props.count == 0 && deform_percent) {
+ size_t num_shape_props = 1;
+ ufbx_prop *shape_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_shape_props);
+ ufbxi_check(shape_props);
+ shape_props[0].name.data = ufbxi_DeformPercent;
+ shape_props[0].name.length = sizeof(ufbxi_DeformPercent) - 1;
+ shape_props[0]._internal_key = ufbxi_get_name_key_c(ufbxi_DeformPercent);
+ shape_props[0].type = UFBX_PROP_NUMBER;
+ shape_props[0].value_str = ufbx_empty_string;
+ shape_props[0].value_real = 100.0f;
+ ufbxi_ignore(ufbxi_get_val1(deform_percent, "R", &shape_props[0].value_real));
+ channel->props.props.data = shape_props;
+ channel->props.props.count = num_shape_props;
+ }
+
+ return 1;
+}
+
+typedef enum {
+ UFBXI_KEY_INTERPOLATION_CONSTANT = 0x2,
+ UFBXI_KEY_INTERPOLATION_LINEAR = 0x4,
+ UFBXI_KEY_INTERPOLATION_CUBIC = 0x8,
+ UFBXI_KEY_TANGENT_AUTO = 0x100,
+ UFBXI_KEY_TANGENT_TCB = 0x200,
+ UFBXI_KEY_TANGENT_USER = 0x400,
+ UFBXI_KEY_TANGENT_BROKEN = 0x800,
+ UFBXI_KEY_CONSTANT_NEXT = 0x100,
+ UFBXI_KEY_CLAMP = 0x1000,
+ UFBXI_KEY_TIME_INDEPENDENT = 0x2000,
+ UFBXI_KEY_CLAMP_PROGRESSIVE = 0x4000,
+ UFBXI_KEY_WEIGHTED_RIGHT = 0x1000000,
+ UFBXI_KEY_WEIGHTED_NEXT_LEFT = 0x2000000,
+ UFBXI_KEY_VELOCITY_RIGHT = 0x10000000,
+ UFBXI_KEY_VELOCITY_NEXT_LEFT = 0x20000000,
+} ufbxi_key_flags;
+
+static ufbxi_noinline float ufbxi_solve_auto_tangent(ufbxi_context *uc, double prev_time, double time, double next_time, ufbx_real prev_value, ufbx_real value, ufbx_real next_value, float weight_left, float weight_right, float auto_bias, uint32_t flags)
+{
+ // Clamp tangent to zero if near either left or right key
+ if (flags & UFBXI_KEY_CLAMP) {
+ if (ufbx_fmin(ufbx_fabs(prev_value - value), ufbx_fabs(next_value - value)) <= uc->opts.key_clamp_threshold) {
+ return 0.0f;
+ }
+ }
+
+ // Time-independent: Set the initial slope to be the difference between the two keyframes.
+ double slope = (next_value - prev_value) / (next_time - prev_time);
+
+ // Non-time-independent tangents seem to blend between left/right tangent and the total difference.
+ if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
+ double slope_left = (value - prev_value) / (time - prev_time);
+ double slope_right = (next_value - value) / (next_time - time);
+ double delta = (time - prev_time) / (next_time - prev_time);
+ slope = slope * 0.5 + (slope_left * (1.0 - delta) + slope_right * delta) * 0.5;
+
+ double bias_weight = ufbx_fabs(auto_bias) / 100.0;
+ if (bias_weight > 0.0001) {
+ double bias_target = auto_bias > 0.0 ? slope_right : slope_left;
+ double bias_delta = bias_target - slope;
+ slope = slope * (1.0 - bias_weight) + bias_target * bias_weight;
+
+ // Auto bias larger than 500 (positive or negative) adds an absolute
+ // value to the slope, determined by `((bias-500) / 100)^2 * 40`.
+ double abs_bias_weight = bias_weight - 5.0;
+ if (abs_bias_weight > 0.0) {
+ double bias_sign = ufbx_fabs(bias_delta) > 0.00001 ? bias_delta : auto_bias;
+ bias_sign = bias_sign > 0.0 ? 1.0 : -1.0;
+ slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
+ }
+ }
+ }
+
+ // Prevent overshooting by clamping the slope in case either
+ // tangent goes above/below the endpoints.
+ if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) {
+ // Split the slope to sign and a non-negative absolute value
+ double slope_sign = slope >= 0.0 ? 1.0 : -1.0;
+ double abs_slope = slope_sign * slope;
+
+ // Find limits for the absolute value of the slope
+ double range_left = weight_left * (time - prev_time);
+ double range_right = weight_right * (next_time - time);
+ double max_left = range_left > 0.0 ? slope_sign * (value - prev_value) / range_left : 0.0;
+ double max_right = range_right > 0.0 ? slope_sign * (next_value - value) / range_right : 0.0;
+
+ // Clamp negative values and NaNs to zero
+ if (!(max_left > 0.0)) max_left = 0.0;
+ if (!(max_right > 0.0)) max_right = 0.0;
+
+ // Clamp the absolute slope from both sides
+ if (abs_slope > max_left) abs_slope = max_left;
+ if (abs_slope > max_right) abs_slope = max_right;
+
+ slope = (slope_sign * abs_slope);
+ }
+
+ return (float)slope;
+}
+
+static float ufbxi_solve_auto_tangent_left(ufbxi_context *uc, double prev_time, double time, ufbx_real prev_value, ufbx_real value, float weight_left, float auto_bias, uint32_t flags)
+{
+ (void)weight_left;
+ if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) return 0.0f;
+ if (flags & UFBXI_KEY_CLAMP) {
+ if (ufbx_fabs(prev_value - value) <= uc->opts.key_clamp_threshold) {
+ return 0.0f;
+ }
+ }
+
+ double slope = (value - prev_value) / (time - prev_time);
+
+ if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
+ double abs_bias_weight = ufbx_fabs(auto_bias) / 100.0 - 5.0;
+ if (abs_bias_weight > 0.0) {
+ double bias_sign = auto_bias > 0.0 ? 1.0 : -1.0;
+ slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
+ }
+ }
+
+ return (float)slope;
+}
+
+static float ufbxi_solve_auto_tangent_right(ufbxi_context *uc, double time, double next_time, ufbx_real value, ufbx_real next_value, float weight_right, float auto_bias, uint32_t flags)
+{
+ (void)weight_right;
+ if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) return 0.0f;
+ if (flags & UFBXI_KEY_CLAMP) {
+ if (ufbx_fabs(next_value - value) <= uc->opts.key_clamp_threshold) {
+ return 0.0f;
+ }
+ }
+
+ double slope = (next_value - value) / (next_time - time);
+
+ if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
+ double abs_bias_weight = ufbx_fabs(auto_bias) / 100.0 - 5.0;
+ if (abs_bias_weight > 0.0) {
+ double bias_sign = auto_bias > 0.0 ? 1.0 : -1.0;
+ slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
+ }
+ }
+
+ return (float)slope;
+}
+
+static void ufbxi_solve_tcb(float *p_slope_left, float *p_slope_right, double tension, double continuity, double bias, double slope_left, double slope_right, bool edge)
+{
+ double factor = edge ? 1.0 : 0.5;
+ double d00 = factor * (1.0 - tension) * (1.0 + bias) * (1.0 - continuity);
+ double d01 = factor * (1.0 - tension) * (1.0 - bias) * (1.0 + continuity);
+ double d10 = factor * (1.0 - tension) * (1.0 + bias) * (1.0 + continuity);
+ double d11 = factor * (1.0 - tension) * (1.0 - bias) * (1.0 - continuity);
+
+ *p_slope_left = (float)(d00 * slope_left + d01 * slope_right);
+ *p_slope_right = (float)(d10 * slope_left + d11 * slope_right);
+}
+
+ufbxi_noinline static void ufbxi_read_extrapolation(ufbx_extrapolation *p_extrapolation, ufbxi_node *node, const char *name)
+{
+ ufbxi_node *child = ufbxi_find_child(node, name);
+ ufbx_extrapolation_mode mode = UFBX_EXTRAPOLATION_CONSTANT;
+ int32_t repeat_count = -1;
+
+ if (child) {
+ int32_t mode_ch;
+ if (ufbxi_find_val1(child, ufbxi_Type, "I", &mode_ch)) {
+
+ switch (mode_ch) {
+ case 'A': mode = UFBX_EXTRAPOLATION_REPEAT_RELATIVE; break;
+ case 'C': mode = UFBX_EXTRAPOLATION_CONSTANT; break;
+ case 'K': mode = UFBX_EXTRAPOLATION_SLOPE; break;
+ case 'M': mode = UFBX_EXTRAPOLATION_MIRROR; break;
+ case 'R': mode = UFBX_EXTRAPOLATION_REPEAT; break;
+ default: /* Unknown */ break;
+ }
+ if (ufbxi_find_val1(child, ufbxi_Repetition, "I", &repeat_count)) {
+ if (repeat_count < 0) {
+ repeat_count = -1;
+ }
+ }
+ }
+ }
+
+ p_extrapolation->mode = mode;
+ p_extrapolation->repeat_count = repeat_count;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_animation_curve(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_anim_curve *curve = ufbxi_push_element(uc, info, ufbx_anim_curve, UFBX_ELEMENT_ANIM_CURVE);
+ ufbxi_check(curve);
+
+ ufbxi_read_extrapolation(&curve->pre_extrapolation, node, ufbxi_Pre_Extrapolation);
+ ufbxi_read_extrapolation(&curve->post_extrapolation, node, ufbxi_Post_Extrapolation);
+
+ if (uc->opts.ignore_animation) return 1;
+
+ ufbxi_value_array *times, *values, *attr_flags, *attrs, *refs;
+ ufbxi_check(times = ufbxi_find_array(node, ufbxi_KeyTime, 'l'));
+ ufbxi_check(values = ufbxi_find_array(node, ufbxi_KeyValueFloat, 'r'));
+ ufbxi_check(attr_flags = ufbxi_find_array(node, ufbxi_KeyAttrFlags, 'i'));
+ ufbxi_check(attrs = ufbxi_find_array(node, ufbxi_KeyAttrDataFloat, '?'));
+ ufbxi_check(refs = ufbxi_find_array(node, ufbxi_KeyAttrRefCount, 'i'));
+
+ // Time and value arrays that define the keyframes should be parallel
+ ufbxi_check(times->size == values->size);
+
+ // Flags and attributes are run-length encoded where KeyAttrRefCount (refs)
+ // is an array that describes how many times to repeat a given flag/attribute.
+ // Attributes consist of 4 32-bit floating point values per key.
+ ufbxi_check(attr_flags->size == refs->size);
+ ufbxi_check(attrs->size == refs->size * 4u);
+
+ size_t num_keys = times->size;
+ ufbx_keyframe *keys = ufbxi_push(&uc->result, ufbx_keyframe, num_keys);
+ ufbxi_check(keys);
+
+ curve->keyframes.data = keys;
+ curve->keyframes.count = num_keys;
+
+ int64_t *p_time = (int64_t*)times->data;
+ ufbx_real *p_value = (ufbx_real*)values->data;
+ int32_t *p_flag = (int32_t*)attr_flags->data;
+ float *p_attr = (float*)attrs->data;
+ int32_t *p_ref = (int32_t*)refs->data, *p_ref_end = p_ref + refs->size;
+
+ // The previous key defines the weight/slope of the left tangent
+ float slope_left = 0.0f;
+ float weight_left = 0.333333f;
+ // float velocity_left = 0.0f;
+
+ double prev_time = 0.0;
+ double next_time = 0.0;
+
+ int32_t refs_left = 0;
+ if (num_keys > 0) {
+ next_time = (double)p_time[0] / uc->ktime_sec_double;
+ if (p_ref < p_ref_end) refs_left = *p_ref;
+ }
+
+ for (size_t i = 0; i < num_keys; i++) {
+ ufbx_keyframe *key = &keys[i];
+ ufbxi_check(refs_left > 0);
+
+ ufbx_real value = *p_value;
+ if (i == 0) {
+ curve->min_value = value;
+ curve->max_value = value;
+ } else {
+ curve->min_value = ufbxi_min_real(curve->min_value, value);
+ curve->max_value = ufbxi_max_real(curve->max_value, value);
+ }
+
+ key->time = next_time;
+ key->value = value;
+
+ if (i + 1 < num_keys) {
+ next_time = (double)p_time[1] / uc->ktime_sec_double;
+ }
+
+ uint32_t flags = (uint32_t)*p_flag;
+
+ float slope_right = p_attr[0];
+ float weight_right = 0.333333f;
+ //float velocity_right = 0.0f;
+ float next_slope_left = p_attr[1];
+ float next_weight_left = 0.333333f;
+ // float next_velocity_left = 0.0f;
+
+ if ((flags & (UFBXI_KEY_WEIGHTED_RIGHT|UFBXI_KEY_WEIGHTED_NEXT_LEFT)) != 0) {
+ // At least one of the tangents is weighted. The weights are encoded as
+ // two 0.4 _decimal_ fixed point values that are packed into 32 bits and
+ // interpreted as a 32-bit float.
+ uint32_t packed_weights;
+ memcpy(&packed_weights, &p_attr[2], sizeof(uint32_t));
+
+ if (flags & UFBXI_KEY_WEIGHTED_RIGHT) {
+ // Right tangent is weighted
+ weight_right = (float)(packed_weights & 0xffff) * 0.0001f;
+ }
+
+ if (flags & UFBXI_KEY_WEIGHTED_NEXT_LEFT) {
+ // Next left tangent is weighted
+ next_weight_left = (float)(packed_weights >> 16) * 0.0001f;
+ }
+ }
+#if 0
+ if ((flags & (UFBXI_KEY_VELOCITY_RIGHT|UFBXI_KEY_VELOCITY_NEXT_LEFT)) != 0) {
+ // Velocities are encoded in the same way as weights, see above.
+ uint32_t packed_velocities;
+ memcpy(&packed_velocities, &p_attr[3], sizeof(uint32_t));
+
+ if (flags & UFBXI_KEY_VELOCITY_RIGHT) {
+ // Right tangent has velocity
+ velocity_right = (float)(int16_t)(packed_velocities & 0xffff) * 0.0001f;
+ }
+
+ if (flags & UFBXI_KEY_VELOCITY_NEXT_LEFT) {
+ // Next left tangent has velocity
+ next_velocity_left = (float)(int16_t)(packed_velocities >> 16) * 0.0001f;
+ }
+ }
+#endif
+
+ if (flags & UFBXI_KEY_INTERPOLATION_CONSTANT) {
+ // Constant interpolation: Set cubic tangents to flat.
+
+ if (flags & UFBXI_KEY_CONSTANT_NEXT) {
+ // Take constant value from next key
+ key->interpolation = UFBX_INTERPOLATION_CONSTANT_NEXT;
+
+ } else {
+ // Take constant value from the previous key
+ key->interpolation = UFBX_INTERPOLATION_CONSTANT_PREV;
+ }
+
+ weight_right = next_weight_left = 0.333333f;
+ slope_right = next_slope_left = 0.0f;
+
+ } else if (flags & UFBXI_KEY_INTERPOLATION_CUBIC) {
+ // Cubic interpolation
+ key->interpolation = UFBX_INTERPOLATION_CUBIC;
+
+ if (flags & UFBXI_KEY_TANGENT_TCB) {
+ double tcb_slope_left = 0.0;
+ double tcb_slope_right = 0.0;
+ bool tcb_edge = false;
+ if (i > 0 && key->time > prev_time) {
+ tcb_slope_left = (key->value - p_value[-1]) / (key->time - prev_time);
+ } else {
+ tcb_edge = true;
+ }
+ if (i + 1 < num_keys && next_time > key->time) {
+ tcb_slope_right = (p_value[1] - key->value) / (next_time - key->time);
+ } else {
+ tcb_edge = true;
+ }
+
+ ufbxi_solve_tcb(&slope_left, &slope_right, p_attr[0], p_attr[1], p_attr[2], tcb_slope_left, tcb_slope_right, tcb_edge);
+
+ // TODO: How to handle these?
+ next_slope_left = 0.0f;
+ next_weight_left = 0.333333f;
+ // next_velocity_left = 0.0f;
+ } else if (flags & UFBXI_KEY_TANGENT_USER) {
+ // User tangents
+
+ if (flags & UFBXI_KEY_TANGENT_BROKEN) {
+ // Broken tangents: No need to modify slopes
+ } else {
+ // Unified tangents: Use right slope for both sides
+ // TODO: ??? slope_left = slope_right;
+ }
+
+ } else {
+ // TODO: Auto break (0x800)
+
+ if (i > 0 && i + 1 < num_keys && key->time > prev_time && next_time > key->time) {
+ if (ufbx_fabs(slope_left + slope_right) <= 0.0001f) {
+ slope_left = slope_right = ufbxi_solve_auto_tangent(uc,
+ prev_time, key->time, next_time,
+ p_value[-1], key->value, p_value[1],
+ weight_left, weight_right, slope_right, flags);
+ } else {
+ slope_left = ufbxi_solve_auto_tangent(uc,
+ prev_time, key->time, next_time,
+ p_value[-1], key->value, p_value[1],
+ weight_left, weight_right, -slope_left, flags);
+ slope_right = ufbxi_solve_auto_tangent(uc,
+ prev_time, key->time, next_time,
+ p_value[-1], key->value, p_value[1],
+ weight_left, weight_right, slope_right, flags);
+ }
+ } else if (i > 0 && key->time > prev_time) {
+ slope_left = slope_right = ufbxi_solve_auto_tangent_left(uc,
+ prev_time, key->time,
+ p_value[-1], key->value,
+ weight_left, -slope_left, flags);
+ } else if (i + 1 < num_keys && next_time > key->time) {
+ slope_left = slope_right = ufbxi_solve_auto_tangent_right(uc,
+ key->time, next_time,
+ key->value, p_value[1],
+ weight_right, slope_right, flags);
+ } else {
+ // Only / invalid keyframe: Set both slopes to zero
+ slope_left = slope_right = 0.0f;
+ }
+
+
+ // ??? Looks like at least MotionBuilder adjusts weight and auto bias to
+ // implement velocity and the velocity information in the file is purely
+ // for UI (?) If auto bias is not accounted for the velocity computation
+ // below results in the correct tangents, but with auto bias the velocity
+ // seems to be accounted for twice resulting in incorrect values...
+#if 0
+ if (weight_left >= UFBX_EPSILON) {
+ slope_left *= (float)(1.0 - ufbx_fmin(velocity_left / weight_left, 1.0));
+ }
+ if (weight_right >= UFBX_EPSILON) {
+ slope_right *= (float)(1.0 - ufbx_fmin(velocity_right / weight_right, 1.0));
+ }
+#endif
+ }
+
+ } else {
+ // Linear or unknown interpolation: Set cubic tangents to match
+ // the linear interpolation with weights of 1/3.
+ key->interpolation = UFBX_INTERPOLATION_LINEAR;
+
+ weight_right = 0.333333f;
+ next_weight_left = 0.333333f;
+
+ if (next_time > key->time) {
+ double delta_time = next_time - key->time;
+ if (delta_time > 0.0) {
+ double slope = (p_value[1] - key->value) / delta_time;
+ slope_right = next_slope_left = (float)slope;
+ } else {
+ slope_right = next_slope_left = 0.0f;
+ }
+ } else {
+ slope_right = next_slope_left = 0.0f;
+ }
+ }
+
+ // Set the tangents based on weights (dx relative to the time difference
+ // between the previous/next key) and slope (simply d = slope * dx)
+ if (key->time > prev_time) {
+ double delta = key->time - prev_time;
+ key->left.dx = (float)(weight_left * delta);
+ key->left.dy = key->left.dx * slope_left;
+ } else {
+ key->left.dx = 0.0f;
+ key->left.dy = 0.0f;
+ }
+
+ if (next_time > key->time) {
+ double delta = next_time - key->time;
+ key->right.dx = (float)(weight_right * delta);
+ key->right.dy = key->right.dx * slope_right;
+ } else {
+ key->right.dx = 0.0f;
+ key->right.dy = 0.0f;
+ }
+
+ slope_left = next_slope_left;
+ weight_left = next_weight_left;
+ // velocity_left = next_velocity_left;
+ prev_time = key->time;
+
+ // Decrement attribute refcount and potentially move to the next one.
+ if (--refs_left == 0) {
+ p_flag++;
+ p_attr += 4;
+ p_ref++;
+ if (p_ref < p_ref_end) refs_left = *p_ref;
+ }
+ p_time++;
+ p_value++;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_material(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_material *material = ufbxi_push_element(uc, info, ufbx_material, UFBX_ELEMENT_MATERIAL);
+ ufbxi_check(material);
+
+ if (!ufbxi_find_val1(node, ufbxi_ShadingModel, "S", &material->shading_model_name)) {
+ material->shading_model_name = ufbx_empty_string;
+ }
+
+ material->shader_prop_prefix = ufbx_empty_string;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_texture(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_texture *texture = ufbxi_push_element(uc, info, ufbx_texture, UFBX_ELEMENT_TEXTURE);
+ ufbxi_check(texture);
+
+ texture->type = UFBX_TEXTURE_FILE;
+
+ texture->filename = ufbx_empty_string;
+ texture->absolute_filename = ufbx_empty_string;
+ texture->relative_filename = ufbx_empty_string;
+
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "S", &texture->absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "S", &texture->absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "S", &texture->relative_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "S", &texture->relative_filename));
+
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "b", &texture->raw_absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "b", &texture->raw_absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "b", &texture->raw_relative_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "b", &texture->raw_relative_filename));
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_layered_texture(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_texture *texture = ufbxi_push_element(uc, info, ufbx_texture, UFBX_ELEMENT_TEXTURE);
+ ufbxi_check(texture);
+
+ texture->type = UFBX_TEXTURE_LAYERED;
+
+ texture->filename = ufbx_empty_string;
+ texture->absolute_filename = ufbx_empty_string;
+ texture->relative_filename = ufbx_empty_string;
+
+ ufbxi_texture_extra *extra = ufbxi_push_element_extra(uc, texture->element.element_id, ufbxi_texture_extra);
+ ufbxi_check(extra);
+
+ ufbxi_value_array *alphas = ufbxi_find_array(node, ufbxi_Alphas, 'r');
+ if (alphas) {
+ extra->alphas = (ufbx_real*)alphas->data;
+ extra->num_alphas = alphas->size;
+ }
+
+ ufbxi_value_array *blend_modes = ufbxi_find_array(node, ufbxi_BlendModes, 'i');
+ if (blend_modes) {
+ extra->blend_modes = (int32_t*)blend_modes->data;
+ extra->num_blend_modes = blend_modes->size;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_video(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_video *video = ufbxi_push_element(uc, info, ufbx_video, UFBX_ELEMENT_VIDEO);
+ ufbxi_check(video);
+
+ video->filename = ufbx_empty_string;
+ video->absolute_filename = ufbx_empty_string;
+ video->relative_filename = ufbx_empty_string;
+
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "S", &video->absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "S", &video->absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "S", &video->relative_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "S", &video->relative_filename));
+
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "b", &video->raw_absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "b", &video->raw_absolute_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "b", &video->raw_relative_filename));
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "b", &video->raw_relative_filename));
+
+ ufbxi_node *content_node = ufbxi_find_child(node, ufbxi_Content);
+ ufbxi_check(ufbxi_read_embedded_blob(uc, &video->content, content_node));
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_anim_stack(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ (void)node;
+
+ ufbx_anim_stack *stack = ufbxi_push_element(uc, info, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
+ ufbxi_check(stack);
+
+ uint32_t hash = ufbxi_hash_ptr(info->name.data);
+ ufbxi_tmp_anim_stack *entry = ufbxi_map_find(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &info->name.data);
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &info->name.data);
+ ufbxi_check(entry);
+ entry->name = info->name.data;
+ entry->stack = stack;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_pose(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type)
+{
+ ufbx_pose *pose = ufbxi_push_element(uc, info, ufbx_pose, UFBX_ELEMENT_POSE);
+ ufbxi_check(pose);
+
+ // TODO: What are the actual other types?
+ pose->is_bind_pose = sub_type == ufbxi_BindPose;
+
+ size_t num_bones = 0;
+ ufbxi_for(ufbxi_node, n, node->children, node->num_children) {
+ if (n->name != ufbxi_PoseNode) continue;
+
+ // Bones are linked with FBX names/IDs bypassing the connection system (!?)
+ uint64_t fbx_id = 0;
+ if (uc->version < 7000) {
+ char *name = NULL;
+ if (!ufbxi_find_val1(n, ufbxi_Node, "c", &name)) continue;
+ fbx_id = ufbxi_synthetic_id_from_string(uc, name);
+ ufbxi_check(fbx_id);
+ } else {
+ if (!ufbxi_find_val1(n, ufbxi_Node, "L", &fbx_id)) continue;
+ ufbxi_check(ufbxi_validate_fbx_id(uc, &fbx_id));
+ }
+
+ ufbxi_value_array *matrix = ufbxi_find_array(n, ufbxi_Matrix, 'r');
+ if (!matrix) continue;
+ ufbxi_check(matrix->size >= 16);
+
+ ufbxi_tmp_bone_pose *tmp_pose = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_bone_pose, 1);
+ ufbxi_check(tmp_pose);
+
+ num_bones++;
+ tmp_pose->bone_fbx_id = fbx_id;
+ ufbxi_read_transform_matrix(&tmp_pose->bone_to_world, (ufbx_real*)matrix->data);
+ }
+
+ // HACK: Transport `ufbxi_tmp_bone_pose` array through the `ufbx_bone_pose` pointer
+ pose->bone_poses.count = num_bones;
+ pose->bone_poses.data = (ufbx_bone_pose*)ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_tmp_bone_pose, num_bones);
+ ufbxi_check(pose->bone_poses.data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_shader_prop_bindings(ufbxi_context *uc, ufbx_shader_prop_binding *bindings, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_shader_prop_binding)));
+ ufbxi_macro_stable_sort(ufbx_shader_prop_binding, 32, bindings, uc->tmp_arr, count,
+ ( ufbxi_str_less(a->shader_prop, b->shader_prop) ) );
+ return 1;
+}
+
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_binding_table(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_shader_binding *bindings = ufbxi_push_element(uc, info, ufbx_shader_binding, UFBX_ELEMENT_SHADER_BINDING);
+ ufbxi_check(bindings);
+
+ size_t num_entries = 0;
+ ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
+ if (n->name != ufbxi_Entry) continue;
+
+ ufbx_string src, dst;
+ const char *src_type = NULL, *dst_type = NULL;
+ if (!ufbxi_get_val4(n, "SCSC", &src, (char**)&src_type, &dst, (char**)&dst_type)) {
+ continue;
+ }
+
+ if (src_type == ufbxi_FbxPropertyEntry && dst_type == ufbxi_FbxSemanticEntry) {
+ ufbx_shader_prop_binding *bind = ufbxi_push(&uc->tmp_stack, ufbx_shader_prop_binding, 1);
+ ufbxi_check(bind);
+ bind->material_prop = src;
+ bind->shader_prop = dst;
+ num_entries++;
+ } else if (src_type == ufbxi_FbxSemanticEntry && dst_type == ufbxi_FbxPropertyEntry) {
+ ufbx_shader_prop_binding *bind = ufbxi_push(&uc->tmp_stack, ufbx_shader_prop_binding, 1);
+ ufbxi_check(bind);
+ bind->material_prop = dst;
+ bind->shader_prop = src;
+ num_entries++;
+ }
+ }
+
+ bindings->prop_bindings.count = num_entries;
+ bindings->prop_bindings.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_shader_prop_binding, num_entries);
+ ufbxi_check(bindings->prop_bindings.data);
+
+ ufbxi_check(ufbxi_sort_shader_prop_bindings(uc, bindings->prop_bindings.data, bindings->prop_bindings.count));
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_selection_set(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ (void)node;
+
+ ufbx_selection_set *set = ufbxi_push_element(uc, info, ufbx_selection_set, UFBX_ELEMENT_SELECTION_SET);
+ ufbxi_check(set);
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_find_uint32_list(ufbx_uint32_list *dst, ufbxi_node *node, const char *name)
+{
+ ufbxi_value_array *arr = ufbxi_find_array(node, name, 'i');
+ if (arr) {
+ dst->data = (uint32_t*)arr->data;
+ dst->count = arr->size;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_selection_node(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_selection_node *sel = ufbxi_push_element(uc, info, ufbx_selection_node, UFBX_ELEMENT_SELECTION_NODE);
+ ufbxi_check(sel);
+
+ int32_t in_set = 0;
+ if (ufbxi_find_val1(node, ufbxi_IsTheNodeInSet, "I", &in_set) && in_set) {
+ sel->include_node = true;
+ }
+
+ ufbxi_find_uint32_list(&sel->vertices, node, ufbxi_VertexIndexArray);
+ ufbxi_find_uint32_list(&sel->edges, node, ufbxi_EdgeIndexArray);
+ ufbxi_find_uint32_list(&sel->faces, node, ufbxi_PolygonIndexArray);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_character(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ (void)node;
+
+ ufbx_character *character = ufbxi_push_element(uc, info, ufbx_character, UFBX_ELEMENT_CHARACTER);
+ ufbxi_check(character);
+
+ // TODO: There's some extremely cursed all-caps data in characters
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_audio_clip(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_audio_clip *audio = ufbxi_push_element(uc, info, ufbx_audio_clip, UFBX_ELEMENT_AUDIO_CLIP);
+ ufbxi_check(audio);
+
+ audio->filename = ufbx_empty_string;
+ audio->absolute_filename = ufbx_empty_string;
+ audio->relative_filename = ufbx_empty_string;
+
+ ufbxi_node *content_node = ufbxi_find_child(node, ufbxi_Content);
+ ufbxi_check(ufbxi_read_embedded_blob(uc, &audio->content, content_node));
+
+ return 1;
+}
+
+typedef struct {
+ ufbx_constraint_type type;
+ const char *name;
+} ufbxi_constraint_type;
+
+static const ufbxi_constraint_type ufbxi_constraint_types[] = {
+ { UFBX_CONSTRAINT_AIM, "Aim" },
+ { UFBX_CONSTRAINT_PARENT, "Parent-Child" },
+ { UFBX_CONSTRAINT_POSITION, "Position From Positions" },
+ { UFBX_CONSTRAINT_ROTATION, "Rotation From Rotations" },
+ { UFBX_CONSTRAINT_SCALE, "Scale From Scales" },
+ { UFBX_CONSTRAINT_SINGLE_CHAIN_IK, "Single Chain IK" },
+};
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_constraint(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ (void)node;
+
+ ufbx_constraint *constraint = ufbxi_push_element(uc, info, ufbx_constraint, UFBX_ELEMENT_CONSTRAINT);
+ ufbxi_check(constraint);
+
+ if (!ufbxi_find_val1(node, ufbxi_Type, "S", &constraint->type_name)) {
+ constraint->type_name = ufbx_empty_string;
+ }
+
+ ufbxi_for(const ufbxi_constraint_type, ctype, ufbxi_constraint_types, ufbxi_arraycount(ufbxi_constraint_types)) {
+ if (!strcmp(constraint->type_name.data, ctype->name)) {
+ constraint->type = ctype->type;
+ break;
+ }
+ }
+
+ // TODO: There's some extremely cursed all-caps data in characters
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_synthetic_attribute(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, ufbx_string type_str, const char *sub_type, const char *super_type)
+{
+ // Some legacy (version 6000) files store mesh nodes without any `sub_type`
+ // There seems to be no robust indicator, so detect it from `Vertices` and `PolygonVertexIndex`
+ if (sub_type == ufbxi_empty_char) {
+ ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
+ ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_PolygonVertexIndex);
+ if (node_vertices && node_indices) {
+ sub_type = ufbxi_Mesh;
+ }
+ }
+
+ if ((sub_type == ufbxi_empty_char || sub_type == ufbxi_Model) && type_str.data == ufbxi_Model) {
+ // Plain model
+ return 1;
+ }
+
+ ufbxi_element_info attrib_info = *info;
+
+ attrib_info.fbx_id = ufbxi_push_synthetic_id(uc);
+
+ // Use type and name from NodeAttributeName if it exists *uniquely*
+ ufbx_string type_and_name;
+ if (ufbxi_find_val1(node, ufbxi_NodeAttributeName, "s", &type_and_name)) {
+ ufbx_string attrib_type_str, attrib_name_str;
+ ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &attrib_type_str, &attrib_name_str));
+ if (attrib_name_str.length > 0) {
+ attrib_info.name = attrib_name_str;
+ uint64_t attrib_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
+ ufbxi_check(attrib_id);
+ if (info->fbx_id != attrib_id && !ufbxi_fbx_id_exists(uc, attrib_id)) {
+ attrib_info.fbx_id = attrib_id;
+ }
+ }
+ }
+
+ // 6x00: Link the node to the node attribute so property connections can be
+ // redirected from connections if necessary.
+ ufbxi_check(ufbxi_insert_fbx_attr(uc, info->fbx_id, attrib_info.fbx_id));
+
+ // Split properties between the node and the attribute.
+ // Consider all user properties as node properties.
+ ufbx_prop *ps = info->props.props.data;
+ size_t dst = 0, src = 0, end = info->props.props.count;
+ while (src < end) {
+ if (!ufbxi_is_node_property_name(uc, ps[src].name.data) && (ps[src].flags & UFBX_PROP_FLAG_USER_DEFINED) == 0) {
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, 1, &ps[src]));
+ src++;
+ } else if (dst != src) {
+ ps[dst++] = ps[src++];
+ } else {
+ dst++; src++;
+ }
+ }
+ attrib_info.props.props.count = end - dst;
+ attrib_info.props.props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_prop, attrib_info.props.props.count);
+ ufbxi_check(attrib_info.props.props.data);
+ info->props.props.count = dst;
+
+ if (sub_type == ufbxi_Mesh) {
+ ufbxi_check(ufbxi_read_mesh(uc, node, &attrib_info));
+ } else if (sub_type == ufbxi_Light) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_light), UFBX_ELEMENT_LIGHT));
+ } else if (sub_type == ufbxi_Camera) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_camera), UFBX_ELEMENT_CAMERA));
+ } else if (sub_type == ufbxi_LimbNode || sub_type == ufbxi_Limb || sub_type == ufbxi_Root) {
+ ufbxi_check(ufbxi_read_bone(uc, node, &attrib_info, sub_type));
+ } else if (sub_type == ufbxi_Null || sub_type == ufbxi_Marker) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_empty), UFBX_ELEMENT_EMPTY));
+ } else if (sub_type == ufbxi_NurbsCurve) {
+ if (!ufbxi_find_child(node, ufbxi_KnotVector)) return 1;
+ ufbxi_check(ufbxi_read_nurbs_curve(uc, node, &attrib_info));
+ } else if (sub_type == ufbxi_NurbsSurface) {
+ if (!ufbxi_find_child(node, ufbxi_KnotVectorU)) return 1;
+ if (!ufbxi_find_child(node, ufbxi_KnotVectorV)) return 1;
+ ufbxi_check(ufbxi_read_nurbs_surface(uc, node, &attrib_info));
+ } else if (sub_type == ufbxi_Line) {
+ if (!ufbxi_find_child(node, ufbxi_Points)) return 1;
+ if (!ufbxi_find_child(node, ufbxi_PointsIndex)) return 1;
+ ufbxi_check(ufbxi_read_line(uc, node, &attrib_info));
+ } else if (sub_type == ufbxi_TrimNurbsSurface) {
+ if (!ufbxi_find_child(node, ufbxi_Layer)) return 1;
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_nurbs_trim_surface), UFBX_ELEMENT_NURBS_TRIM_SURFACE));
+ } else if (sub_type == ufbxi_Boundary) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_nurbs_trim_boundary), UFBX_ELEMENT_NURBS_TRIM_BOUNDARY));
+ } else if (sub_type == ufbxi_CameraStereo) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_stereo_camera), UFBX_ELEMENT_STEREO_CAMERA));
+ } else if (sub_type == ufbxi_CameraSwitcher) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_camera_switcher), UFBX_ELEMENT_CAMERA_SWITCHER));
+ } else if (sub_type == ufbxi_FKEffector) {
+ ufbxi_check(ufbxi_read_marker(uc, node, &attrib_info, sub_type, UFBX_MARKER_FK_EFFECTOR));
+ } else if (sub_type == ufbxi_IKEffector) {
+ ufbxi_check(ufbxi_read_marker(uc, node, &attrib_info, sub_type, UFBX_MARKER_IK_EFFECTOR));
+ } else if (sub_type == ufbxi_LodGroup) {
+ ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_lod_group), UFBX_ELEMENT_LOD_GROUP));
+ } else {
+ ufbx_string sub_type_str = { sub_type, strlen(sub_type) };
+ ufbxi_check(ufbxi_read_unknown(uc, node, &attrib_info, type_str, sub_type_str, super_type));
+ }
+
+ ufbxi_check(ufbxi_connect_oo(uc, attrib_info.fbx_id, info->fbx_id));
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_global_settings(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbxi_check(ufbxi_read_properties(uc, node, &uc->scene.settings.props));
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_object(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbxi_element_info info = { 0 };
+ info.dom_node = ufbxi_get_dom_node(uc, node);
+
+ if (node->name == ufbxi_GlobalSettings) {
+ ufbxi_check(ufbxi_read_global_settings(uc, node));
+ return 1;
+ }
+
+ ufbx_string type_and_name, sub_type_str;
+
+ // Failing to parse the object properties is not an error since
+ // there's some weird objects mixed in every now and then.
+ // FBX version 7000 and up uses 64-bit unique IDs per object,
+ // older FBX versions just use name/type pairs, which we can
+ // use as IDs since all strings are interned into a string pool.
+ if (uc->version >= 7000) {
+ if (!ufbxi_get_val3(node, "Lss", &info.fbx_id, &type_and_name, &sub_type_str)) return 1;
+ ufbxi_check(ufbxi_validate_fbx_id(uc, &info.fbx_id));
+ } else {
+ if (!ufbxi_get_val2(node, "ss", &type_and_name, &sub_type_str)) return 1;
+ info.fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
+ ufbxi_check(info.fbx_id);
+ }
+
+ // Remove the "Fbx" prefix from sub-types, remember to re-intern!
+ if (sub_type_str.length > 3 && !memcmp(sub_type_str.data, "Fbx", 3)) {
+ sub_type_str.data += 3;
+ sub_type_str.length -= 3;
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &sub_type_str, false));
+ }
+
+ ufbx_string type_str;
+ ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type_str, &info.name));
+
+ const char *name = node->name, *sub_type = sub_type_str.data;
+ ufbxi_check(ufbxi_read_properties(uc, node, &info.props));
+ info.props.defaults = ufbxi_find_template(uc, name, sub_type);
+
+ if (name == ufbxi_Model) {
+ if (uc->version < 7000) {
+ ufbxi_check(ufbxi_read_synthetic_attribute(uc, node, &info, type_str, sub_type, name));
+ }
+ ufbxi_check(ufbxi_read_model(uc, node, &info));
+ } else if (name == ufbxi_NodeAttribute) {
+ if (sub_type == ufbxi_Light) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_light), UFBX_ELEMENT_LIGHT));
+ } else if (sub_type == ufbxi_Camera) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_camera), UFBX_ELEMENT_CAMERA));
+ } else if (sub_type == ufbxi_LimbNode || sub_type == ufbxi_Limb || sub_type == ufbxi_Root) {
+ ufbxi_check(ufbxi_read_bone(uc, node, &info, sub_type));
+ } else if (sub_type == ufbxi_Null || sub_type == ufbxi_Marker) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_empty), UFBX_ELEMENT_EMPTY));
+ } else if (sub_type == ufbxi_CameraStereo) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_stereo_camera), UFBX_ELEMENT_STEREO_CAMERA));
+ } else if (sub_type == ufbxi_CameraSwitcher) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_camera_switcher), UFBX_ELEMENT_CAMERA_SWITCHER));
+ } else if (sub_type == ufbxi_FKEffector) {
+ ufbxi_check(ufbxi_read_marker(uc, node, &info, sub_type, UFBX_MARKER_FK_EFFECTOR));
+ } else if (sub_type == ufbxi_IKEffector) {
+ ufbxi_check(ufbxi_read_marker(uc, node, &info, sub_type, UFBX_MARKER_IK_EFFECTOR));
+ } else if (sub_type == ufbxi_LodGroup) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_lod_group), UFBX_ELEMENT_LOD_GROUP));
+ } else {
+ ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
+ }
+ } else if (name == ufbxi_Geometry) {
+ if (sub_type == ufbxi_Mesh) {
+ ufbxi_check(ufbxi_read_mesh(uc, node, &info));
+ } else if (sub_type == ufbxi_Shape) {
+ ufbxi_check(ufbxi_read_shape(uc, node, &info));
+ } else if (sub_type == ufbxi_NurbsCurve) {
+ ufbxi_check(ufbxi_read_nurbs_curve(uc, node, &info));
+ } else if (sub_type == ufbxi_NurbsSurface) {
+ ufbxi_check(ufbxi_read_nurbs_surface(uc, node, &info));
+ } else if (sub_type == ufbxi_Line) {
+ ufbxi_check(ufbxi_read_line(uc, node, &info));
+ } else if (sub_type == ufbxi_TrimNurbsSurface) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_nurbs_trim_surface), UFBX_ELEMENT_NURBS_TRIM_SURFACE));
+ } else if (sub_type == ufbxi_Boundary) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_nurbs_trim_boundary), UFBX_ELEMENT_NURBS_TRIM_BOUNDARY));
+ } else {
+ ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
+ }
+ } else if (name == ufbxi_Deformer) {
+ if (sub_type == ufbxi_Skin) {
+ ufbxi_check(ufbxi_read_skin(uc, node, &info));
+ } else if (sub_type == ufbxi_Cluster) {
+ ufbxi_check(ufbxi_read_skin_cluster(uc, node, &info));
+ } else if (sub_type == ufbxi_BlendShape) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_blend_deformer), UFBX_ELEMENT_BLEND_DEFORMER));
+ } else if (sub_type == ufbxi_BlendShapeChannel) {
+ ufbxi_check(ufbxi_read_blend_channel(uc, node, &info));
+ } else if (sub_type == ufbxi_VertexCacheDeformer) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_cache_deformer), UFBX_ELEMENT_CACHE_DEFORMER));
+ } else {
+ ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
+ }
+ } else if (name == ufbxi_Material) {
+ ufbxi_check(ufbxi_read_material(uc, node, &info));
+ } else if (name == ufbxi_Texture) {
+ ufbxi_check(ufbxi_read_texture(uc, node, &info));
+ } else if (name == ufbxi_LayeredTexture) {
+ ufbxi_check(ufbxi_read_layered_texture(uc, node, &info));
+ } else if (name == ufbxi_Video) {
+ ufbxi_check(ufbxi_read_video(uc, node, &info));
+ } else if (name == ufbxi_AnimationStack) {
+ ufbxi_check(ufbxi_read_anim_stack(uc, node, &info));
+ } else if (name == ufbxi_AnimationLayer) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_anim_layer), UFBX_ELEMENT_ANIM_LAYER));
+ } else if (name == ufbxi_AnimationCurveNode) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_anim_value), UFBX_ELEMENT_ANIM_VALUE));
+ } else if (name == ufbxi_AnimationCurve) {
+ ufbxi_check(ufbxi_read_animation_curve(uc, node, &info));
+ } else if (name == ufbxi_Pose) {
+ ufbxi_check(ufbxi_read_pose(uc, node, &info, sub_type));
+ } else if (name == ufbxi_Implementation) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_shader), UFBX_ELEMENT_SHADER));
+ } else if (name == ufbxi_BindingTable) {
+ ufbxi_check(ufbxi_read_binding_table(uc, node, &info));
+ } else if (name == ufbxi_Collection) {
+ if (sub_type == ufbxi_SelectionSet) {
+ ufbxi_check(ufbxi_read_selection_set(uc, node, &info));
+ }
+ } else if (name == ufbxi_CollectionExclusive) {
+ if (sub_type == ufbxi_DisplayLayer) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_display_layer), UFBX_ELEMENT_DISPLAY_LAYER));
+ }
+ } else if (name == ufbxi_SelectionNode) {
+ ufbxi_check(ufbxi_read_selection_node(uc, node, &info));
+ } else if (name == ufbxi_Constraint) {
+ if (sub_type == ufbxi_Character) {
+ ufbxi_check(ufbxi_read_character(uc, node, &info));
+ } else {
+ ufbxi_check(ufbxi_read_constraint(uc, node, &info));
+ }
+ } else if (name == ufbxi_SceneInfo) {
+ ufbxi_check(ufbxi_read_scene_info(uc, node));
+ } else if (name == ufbxi_Cache) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_cache_file), UFBX_ELEMENT_CACHE_FILE));
+ } else if (name == ufbxi_ObjectMetaData) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_metadata_object), UFBX_ELEMENT_METADATA_OBJECT));
+ } else if (name == ufbxi_AudioLayer) {
+ ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_audio_layer), UFBX_ELEMENT_AUDIO_LAYER));
+ } else if (name == ufbxi_Audio) {
+ ufbxi_check(ufbxi_read_audio_clip(uc, node, &info));
+ } else {
+ ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_objects(ufbxi_context *uc)
+{
+ for (;;) {
+ // Push a deferred element ID for tagging warnings
+ uc->p_element_id = ufbxi_push(&uc->tmp_element_id, uint32_t, 1);
+ ufbxi_check(uc->p_element_id);
+ *uc->p_element_id = UFBX_NO_INDEX;
+ uc->warnings.deferred_element_id_plus_one = (uint32_t)uc->tmp_element_id.num_items;
+
+ ufbxi_node *node;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
+ if (!node) break;
+
+ ufbxi_check(ufbxi_read_object(uc, node));
+
+ uc->warnings.deferred_element_id_plus_one = 0;
+ uc->p_element_id = NULL;
+ }
+
+ return 1;
+}
+
+typedef struct {
+ ufbxi_node **nodes;
+ size_t num_nodes;
+ uint32_t task_index;
+} ufbxi_object_batch;
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_objects_threaded(ufbxi_context *uc)
+{
+ uc->parse_threaded = true;
+
+ bool parsed_to_end = false;
+ ufbxi_object_batch batches[UFBX_THREAD_GROUP_COUNT]; // ufbxi_uninit
+ memset(batches, 0, sizeof(batches));
+
+ size_t empty_count = 0;
+ size_t batch_index = 0;
+ while (empty_count < UFBX_THREAD_GROUP_COUNT) {
+ ufbxi_object_batch *batch = &batches[batch_index];
+
+ ufbxi_check(ufbxi_thread_pool_wait_group(&uc->thread_pool));
+
+ if (batch->num_nodes > 0) {
+ ufbxi_for_ptr(ufbxi_node, p_node, batch->nodes, batch->num_nodes) {
+ ufbxi_buf_clear(&uc->tmp_parse);
+
+ // Push a deferred element ID for tagging warnings
+ uc->p_element_id = ufbxi_push(&uc->tmp_element_id, uint32_t, 1);
+ ufbxi_check(uc->p_element_id);
+ *uc->p_element_id = UFBX_NO_INDEX;
+ uc->warnings.deferred_element_id_plus_one = (uint32_t)uc->tmp_element_id.num_items;
+
+ ufbxi_check(ufbxi_read_object(uc, *p_node));
+
+ uc->warnings.deferred_element_id_plus_one = 0;
+ uc->p_element_id = NULL;
+ }
+ batch->num_nodes = 0;
+ }
+
+ ufbxi_buf *tmp_buf = &uc->tmp_thread_parse[batch_index];
+
+ // ASCII data may be in `tmp_buf`, so copy it to safety in case
+ if (uc->ascii.src_buf == tmp_buf) {
+ ufbxi_ascii *ua = &uc->ascii;
+ size_t size = ufbxi_to_size(ua->src_end - ua->src);
+ if (uc->read_buffer_size < size) {
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->read_buffer, &uc->read_buffer_size, size));
+ }
+ memcpy(uc->read_buffer, ua->src, size);
+ uc->data = uc->data_begin = ua->src = uc->read_buffer;
+ ua->src_end = uc->read_buffer + size;
+ ua->src_is_retained = false;
+ ua->src_buf = NULL;
+ if (ufbxi_to_size(ua->src_end - ua->src) < uc->progress_interval) {
+ ua->src_yield = ua->src_end;
+ } else {
+ ua->src_yield = ua->src + uc->progress_interval;
+ }
+ uc->data = ua->src;
+ }
+
+ ufbxi_buf_clear(tmp_buf);
+
+ if (!parsed_to_end) {
+ size_t num_nodes = 0;
+ uint32_t task_start = uc->thread_pool.start_index;
+ uint32_t max_tasks = uc->thread_pool.num_tasks / UFBX_THREAD_GROUP_COUNT;
+ max_tasks = ufbxi_min32(max_tasks, ufbxi_thread_pool_available_tasks(&uc->thread_pool));
+ size_t max_memory = uc->opts.thread_opts.memory_limit / UFBX_THREAD_GROUP_COUNT;
+
+ for (;;) {
+ ufbxi_node *node = NULL;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, tmp_buf));
+ if (!node) {
+ parsed_to_end = true;
+ break;
+ }
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbxi_node*, 1, &node));
+ num_nodes++;
+
+ uint32_t num_tasks = uc->thread_pool.start_index - task_start;
+ if (num_tasks >= max_tasks) break;
+
+ size_t memory_used = tmp_buf->pushed_size + tmp_buf->pos;
+ if (memory_used >= max_memory) break;
+ }
+
+ batch->num_nodes = num_nodes;
+ batch->nodes = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node*, num_nodes);
+ ufbxi_check(batch->nodes);
+ batch->task_index = uc->thread_pool.start_index;
+
+ }
+
+ // Not safe to refer to this buffer anymore
+ uc->ascii.src_is_retained = false;
+
+ ufbxi_thread_pool_flush_group(&uc->thread_pool);
+
+ if (batch->num_nodes == 0) {
+ empty_count += 1;
+ }
+
+ batch_index = (batch_index + 1) % UFBX_THREAD_GROUP_COUNT;
+ }
+
+ ufbxi_check(ufbxi_thread_pool_wait_all(&uc->thread_pool));
+
+ uc->parse_threaded = false;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_connections(ufbxi_context *uc)
+{
+ // Read the connections to the list first
+ for (;;) {
+ ufbxi_node *node;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
+ if (!node) break;
+
+ char *type;
+
+ uint64_t src_id = 0, dst_id = 0;
+ ufbx_string src_prop = ufbx_empty_string, dst_prop = ufbx_empty_string;
+
+ if (uc->version < 7000) {
+ char *src_name = NULL, *dst_name = NULL;
+ // Pre-7000 versions use Type::Name pairs as identifiers
+
+ if (!ufbxi_get_val1(node, "c", &type)) continue;
+
+ if (type == ufbxi_OO) {
+ if (!ufbxi_get_val3(node, "_cc", NULL, &src_name, &dst_name)) continue;
+ } else if (type == ufbxi_OP) {
+ if (!ufbxi_get_val4(node, "_ccs", NULL, &src_name, &dst_name, &dst_prop)) continue;
+ } else if (type == ufbxi_PO) {
+ if (!ufbxi_get_val4(node, "_csc", NULL, &src_name, &src_prop, &dst_name)) continue;
+ } else if (type == ufbxi_PP) {
+ if (!ufbxi_get_val5(node, "_cscs", NULL, &src_name, &src_prop, &dst_name, &dst_prop)) continue;
+ } else {
+ // TODO: Strict mode?
+ continue;
+ }
+
+ if (src_prop.length > 0) {
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &src_prop, false));
+ }
+ if (dst_prop.length > 0) {
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst_prop, false));
+ }
+
+ src_id = ufbxi_synthetic_id_from_string(uc, src_name);
+ dst_id = ufbxi_synthetic_id_from_string(uc, dst_name);
+ ufbxi_check(src_id && dst_id);
+
+ } else {
+ // Post-7000 versions use proper unique 64-bit IDs
+
+ if (!ufbxi_get_val1(node, "C", &type)) continue;
+
+ if (type == ufbxi_OO) {
+ if (!ufbxi_get_val3(node, "_LL", NULL, &src_id, &dst_id)) continue;
+ } else if (type == ufbxi_OP) {
+ if (!ufbxi_get_val4(node, "_LLS", NULL, &src_id, &dst_id, &dst_prop)) continue;
+ } else if (type == ufbxi_PO) {
+ if (!ufbxi_get_val4(node, "_LSL", NULL, &src_id, &src_prop, &dst_id)) continue;
+ } else if (type == ufbxi_PP) {
+ if (!ufbxi_get_val5(node, "_LSLS", NULL, &src_id, &src_prop, &dst_id, &dst_prop)) continue;
+ } else {
+ // TODO: Strict mode?
+ continue;
+ }
+
+ ufbxi_check(ufbxi_validate_fbx_id(uc, &src_id));
+ ufbxi_check(ufbxi_validate_fbx_id(uc, &dst_id));
+ }
+
+ ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
+ ufbxi_check(conn);
+ conn->src = src_id;
+ conn->dst = dst_id;
+ conn->src_prop = src_prop;
+ conn->dst_prop = dst_prop;
+ }
+
+ return 1;
+}
+
+// -- Pre-7000 "Take" based animation
+
+ufbxi_forceinline static char ufbxi_double_to_char(double value)
+{
+ if (value >= 0.0 && value <= 127.0) {
+ return (char)(int)value;
+ } else {
+ return 0;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_anim_channel(ufbxi_context *uc, ufbxi_node *node, uint64_t value_fbx_id, const char *name, ufbx_real *p_default)
+{
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Default, "R", p_default));
+
+ // Find the key array, early return with success if not found as we may have only a default
+ ufbxi_value_array *keys = ufbxi_find_array(node, ufbxi_Key, 'd');
+ if (!keys) return 1;
+
+ uint64_t curve_fbx_id = 0;
+ ufbx_anim_curve *curve = ufbxi_push_synthetic_element(uc, &curve_fbx_id, node, name, ufbx_anim_curve, UFBX_ELEMENT_ANIM_CURVE);
+ ufbxi_check(curve);
+
+ ufbxi_check(ufbxi_connect_op(uc, curve_fbx_id, value_fbx_id, curve->name));
+
+ ufbxi_read_extrapolation(&curve->pre_extrapolation, node, ufbxi_Pre_Extrapolation);
+ ufbxi_read_extrapolation(&curve->post_extrapolation, node, ufbxi_Post_Extrapolation);
+
+ if (uc->opts.ignore_animation) return 1;
+
+ int32_t key_ver = 0;
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_KeyVer, "I", &key_ver));
+ if (key_ver <= 0) {
+ if (uc->version < 5000) {
+ key_ver = 4003;
+ } else if (uc->version < 6000) {
+ key_ver = 4004;
+ } else {
+ key_ver = 4005;
+ }
+ }
+
+ size_t num_keys = 0;
+ ufbxi_check(ufbxi_find_val1(node, ufbxi_KeyCount, "Z", &num_keys));
+ curve->keyframes.data = ufbxi_push(&uc->result, ufbx_keyframe, num_keys);
+ curve->keyframes.count = num_keys;
+ ufbxi_check(curve->keyframes.data);
+
+ float slope_left = 0.0f;
+ float weight_left = 0.333333f;
+
+ double next_time = 0.0;
+ double next_value = 0.0;
+ double prev_time = 0.0;
+
+ // The pre-7000 keyframe data is stored as a _heterogenous_ array containing 64-bit integers,
+ // floating point values, and _bare characters_. We cast all values to double and interpret them.
+ double *data = (double*)keys->data, *data_end = data + keys->size;
+
+ if (num_keys > 0) {
+ ufbxi_check(data_end - data >= 2);
+ next_time = data[0] / uc->ktime_sec_double;
+ next_value = data[1];
+ }
+
+ for (size_t i = 0; i < num_keys; i++) {
+ ufbx_keyframe *key = &curve->keyframes.data[i];
+
+ if (i == 0) {
+ curve->min_value = (ufbx_real)next_value;
+ curve->max_value = (ufbx_real)next_value;
+ } else {
+ curve->min_value = ufbxi_min_real(curve->min_value, (ufbx_real)next_value);
+ curve->max_value = ufbxi_max_real(curve->max_value, (ufbx_real)next_value);
+ }
+
+ // First three values: Time, Value, InterpolationMode
+ ufbxi_check(data_end - data >= 3);
+ key->time = next_time;
+ key->value = (ufbx_real)next_value;
+ char mode = ufbxi_double_to_char(data[2]);
+ data += 3;
+
+ float slope_right = 0.0f;
+ float weight_right = 0.333333f;
+ float next_slope_left = 0.0f;
+ float next_weight_left = 0.333333f;
+ bool auto_slope = false;
+
+ if (mode == 'U') {
+ // Cubic interpolation
+ key->interpolation = UFBX_INTERPOLATION_CUBIC;
+
+ ufbxi_check(data_end - data >= 1);
+ char slope_mode = ufbxi_double_to_char(data[0]);
+ data += 1;
+
+ size_t num_weights = 1;
+ if (slope_mode == 's' || slope_mode == 'b') {
+ // Slope mode 's'/'b' (standard? broken?) always have two explicit slopes
+ // TODO: `b` might actually be some kind of TCB curve
+ ufbxi_check(data_end - data >= 2);
+ slope_right = (float)data[0];
+ next_slope_left = (float)data[1];
+ data += 2;
+ // TODO: This looks very suspicious, but we have observed files with
+ // KeyVer=4002 -> followed by 'n', then next key
+ // KeyVer=4003 -> no weight mode, directly followed by key
+ // KeyVer=4004 -> followed by 'n', then next key
+ if (key_ver == 4003) {
+ num_weights = 0;
+ }
+ } else if (slope_mode == 'a') {
+ // Parameterless slope mode 'a' seems to appear in baked animations. Let's just assume
+ // automatic tangents for now as they're the least likely to break with
+ // objectionable artifacts. We need to defer the automatic tangent resolve
+ // until we have read the next time/value.
+ // TODO: Solve what this is more thoroughly, using auto slope for now to reduce artifacts
+ auto_slope = true;
+ if (key_ver <= 4004) {
+ num_weights = 0;
+ }
+ } else if (slope_mode == 'p') {
+ // TODO: What is this mode? It seems to have negative values sometimes?
+ // Also it seems to have _two_ trailing weights values, currently observed:
+ // `n,n` and `a,X,Y,n`...
+ // Ignore unknown values for now
+ // TODO: Solve what this is more thoroughly, using auto slope for now to reduce artifacts
+ auto_slope = true;
+ ufbxi_check(data_end - data >= 2);
+ data += 2;
+ if (key_ver <= 4004) {
+ num_weights = 1;
+ } else {
+ num_weights = 2;
+ }
+ } else if (slope_mode == 'q') {
+ // TODO: What is this mode? It seems to have negative values sometimes?
+ // Also it seems to have _two_ trailing weights values, currently observed:
+ // `d,d` and `n`...
+ // Ignore unknown values for now
+ // TODO: This has only been observed with KeyVer=4003/4005, it might have two weights in 4004
+ // TODO: Solve what this is more thoroughly, using auto slope for now to reduce artifacts
+ auto_slope = true;
+ ufbxi_check(data_end - data >= 2);
+ data += 2;
+ if (key_ver <= 4004) {
+ num_weights = 1;
+ } else {
+ num_weights = 2;
+ }
+ } else if (slope_mode == 't') {
+ // TODO: What is this mode? It seems that it does not have any weights and the
+ // third value seems _tiny_ (around 1e-30?)
+ // TODO: This looks like simple TCB parameters, currently falling back to auto.
+ auto_slope = true;
+ ufbxi_check(data_end - data >= 3);
+ data += 3;
+ num_weights = 0;
+ } else if (slope_mode == 'd') {
+ // TODO: What is this mode? It has a single parameter (currently observed `0`)
+ // and a single weight.
+ // TODO: Solve what this is more thoroughly, using auto slope for now to reduce artifacts
+ auto_slope = true;
+ ufbxi_check(data_end - data >= 1);
+ data += 1;
+ } else {
+ ufbxi_fail("Unknown slope mode");
+ }
+
+ for (; num_weights > 0; num_weights--) {
+ ufbxi_check(data_end - data >= 1);
+ char weight_mode = ufbxi_double_to_char(data[0]);
+ data += 1;
+
+ if (weight_mode == 'n') {
+ // Automatic weights (0.3333...)
+ } else if (weight_mode == 'a') {
+ // Manual weights: RightWeight, NextLeftWeight
+ ufbxi_check(data_end - data >= 2);
+ weight_right = (float)data[0];
+ next_weight_left = (float)data[1];
+ data += 2;
+ } else if (weight_mode == 'l') {
+ // Next left tangent is weighted
+ ufbxi_check(data_end - data >= 1);
+ next_weight_left = (float)data[0];
+ data += 1;
+ } else if (weight_mode == 'r') {
+ // Right tangent is weighted
+ ufbxi_check(data_end - data >= 1);
+ weight_right = (float)data[0];
+ data += 1;
+ } else if (weight_mode == 'c') {
+ // TODO: What is this mode? At least it has no parameters so let's
+ // just assume automatic weights for the time being (0.3333...)
+ } else {
+ ufbxi_fail("Unknown weight mode");
+ }
+ }
+
+ } else if (mode == 'L') {
+ // Linear interpolation: No parameters
+ key->interpolation = UFBX_INTERPOLATION_LINEAR;
+ } else if (mode == 'C') {
+ // Constant interpolation: Single parameter (use prev/next)
+ if (key_ver >= 4004) {
+ ufbxi_check(data_end - data >= 1);
+ key->interpolation = ufbxi_double_to_char(data[0]) == 'n' ? UFBX_INTERPOLATION_CONSTANT_NEXT : UFBX_INTERPOLATION_CONSTANT_PREV;
+ data += 1;
+ } else {
+ key->interpolation = UFBX_INTERPOLATION_CONSTANT_PREV;
+ }
+ } else {
+ ufbxi_fail("Unknown key mode");
+ }
+
+ // Retrieve next key and value
+ if (i + 1 < num_keys) {
+ ufbxi_check(data_end - data >= 2);
+ next_time = data[0] / uc->ktime_sec_double;
+ next_value = data[1];
+ }
+
+ if (auto_slope) {
+ if (i > 0) {
+ slope_left = slope_right = ufbxi_solve_auto_tangent(uc,
+ prev_time, key->time, next_time,
+ key[-1].value, key->value, (ufbx_real)next_value,
+ weight_left, weight_right, 0.0f, UFBXI_KEY_CLAMP_PROGRESSIVE|UFBXI_KEY_TIME_INDEPENDENT);
+ } else {
+ slope_left = slope_right = 0.0f;
+ }
+ }
+
+ // Set up linear cubic tangents if necessary
+ if (key->interpolation == UFBX_INTERPOLATION_LINEAR) {
+ if (next_time > key->time) {
+ double slope = (next_value - key->value) / (next_time - key->time);
+ slope_right = next_slope_left = (float)slope;
+ } else {
+ slope_right = next_slope_left = 0.0f;
+ }
+ }
+
+ if (key->time > prev_time) {
+ double delta = key->time - prev_time;
+ key->left.dx = (float)(weight_left * delta);
+ key->left.dy = key->left.dx * slope_left;
+ } else {
+ key->left.dx = 0.0f;
+ key->left.dy = 0.0f;
+ }
+
+ if (next_time > key->time) {
+ double delta = next_time - key->time;
+ key->right.dx = (float)(weight_right * delta);
+ key->right.dy = key->right.dx * slope_right;
+ } else {
+ key->right.dx = 0.0f;
+ key->right.dy = 0.0f;
+ }
+
+ slope_left = next_slope_left;
+ weight_left = next_weight_left;
+ prev_time = key->time;
+ }
+
+ ufbxi_check(data == data_end);
+
+ return 1;
+}
+
+// Recursion limited as it is further called only for `name="T"/"R"/"S"` and
+// cannot enter the `name=="Transform"` branch.
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_prop_channel(ufbxi_context *uc, ufbxi_node *node, uint64_t target_fbx_id, uint64_t layer_fbx_id, ufbx_string name)
+ ufbxi_recursive_function(int, ufbxi_read_take_prop_channel, (uc, node, target_fbx_id, layer_fbx_id, name), 2,
+ (ufbxi_context *uc, ufbxi_node *node, uint64_t target_fbx_id, uint64_t layer_fbx_id, ufbx_string name))
+{
+ if (name.data == ufbxi_Transform) {
+ // Pre-7000 have transform keyframes in a deeply nested structure,
+ // flatten it to make it resemble post-7000 structure a bit closer:
+ // old: Model: { Channel: "Transform" { Channel: "T" { Channel "X": { ... } } } }
+ // new: Model: { Channel: "Lcl Translation" { Channel "X": { ... } } }
+
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ if (child->name != ufbxi_Channel) continue;
+
+ const char *old_name = NULL;
+ ufbxi_check(ufbxi_get_val1(child, "C", (char**)&old_name));
+
+ ufbx_string new_name;
+ if (old_name == ufbxi_T) { new_name.data = ufbxi_Lcl_Translation; new_name.length = sizeof(ufbxi_Lcl_Translation) - 1; }
+ else if (old_name == ufbxi_R) { new_name.data = ufbxi_Lcl_Rotation; new_name.length = sizeof(ufbxi_Lcl_Rotation) - 1; }
+ else if (old_name == ufbxi_S) { new_name.data = ufbxi_Lcl_Scaling; new_name.length = sizeof(ufbxi_Lcl_Scaling) - 1; }
+ else {
+ continue;
+ }
+
+ // Read child as a top-level property channel
+ ufbxi_check(ufbxi_read_take_prop_channel(uc, child, target_fbx_id, layer_fbx_id, new_name));
+ }
+
+ } else {
+
+ // Pre-6000 FBX files store blend shape keys with a " (Shape)" suffix
+ if (uc->version < 6000) {
+ const char *const suffix = " (Shape)";
+ size_t suffix_len = strlen(suffix);
+ if (name.length > suffix_len && !memcmp(name.data + name.length - suffix_len, suffix, suffix_len)) {
+ name.length -= suffix_len;
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &name, false));
+ }
+ }
+
+ // Find 1-3 channel nodes that contain a `Key:` node
+ ufbxi_node *channel_nodes[3] = { 0 };
+ const char *channel_names[3] = { 0 };
+ size_t num_channel_nodes = 0;
+
+ if (ufbxi_find_child(node, ufbxi_Key) || ufbxi_find_child(node, ufbxi_Default)) {
+ // Channel has only a single curve
+ channel_nodes[0] = node;
+ channel_names[0] = name.data;
+ num_channel_nodes = 1;
+ } else {
+ // Channel is a compound of multiple curves
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ if (child->name != ufbxi_Channel) continue;
+ if (!ufbxi_find_child(child, ufbxi_Key) && !ufbxi_find_child(child, ufbxi_Default)) continue;
+ if (!ufbxi_get_val1(child, "C", (char**)&channel_names[num_channel_nodes])) continue;
+ channel_nodes[num_channel_nodes] = child;
+ if (++num_channel_nodes == 3) break;
+ }
+ }
+
+ // Early return: No valid channels found, not an error
+ if (num_channel_nodes == 0) return 1;
+
+ uint64_t value_fbx_id = 0;
+ ufbx_anim_value *value = ufbxi_push_synthetic_element(uc, &value_fbx_id, node, name.data, ufbx_anim_value, UFBX_ELEMENT_ANIM_VALUE);
+
+ // Add a "virtual" connection between the animated property and the layer/target
+ ufbxi_check(ufbxi_connect_oo(uc, value_fbx_id, layer_fbx_id));
+ ufbxi_check(ufbxi_connect_op(uc, value_fbx_id, target_fbx_id, name));
+
+ for (size_t i = 0; i < num_channel_nodes; i++) {
+ ufbxi_check(ufbxi_read_take_anim_channel(uc, channel_nodes[i], value_fbx_id, channel_names[i], &value->default_value.v[i]));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_object(ufbxi_context *uc, ufbxi_node *node, uint64_t layer_fbx_id)
+{
+ // Takes are used only in pre-7000 FBX versions so objects are identified
+ // by their unique Type::Name pair that we use as unique IDs through the
+ // pooled interned string pointers.
+ const char *type_and_name = NULL;
+ ufbxi_check(ufbxi_get_val1(node, "c", (char**)&type_and_name));
+ uint64_t target_fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name);
+ ufbxi_check(target_fbx_id);
+
+ // Add all suitable Channels as animated properties
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ ufbx_string name;
+ if (child->name != ufbxi_Channel) continue;
+ if (!ufbxi_get_val1(child, "S", &name)) continue;
+
+ ufbxi_check(ufbxi_read_take_prop_channel(uc, child, target_fbx_id, layer_fbx_id, name));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbx_prop tmp_props[4];
+ uint32_t num_props = 0;
+ memset(tmp_props, 0, sizeof(tmp_props));
+
+ int64_t start = 0, stop = 0;
+ if (ufbxi_find_val2(node, ufbxi_LocalTime, "LL", &start, &stop)) {
+ ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_LocalStart, start, UFBX_PROP_INTEGER);
+ ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_LocalStop, stop, UFBX_PROP_INTEGER);
+ }
+ if (ufbxi_find_val2(node, ufbxi_ReferenceTime, "LL", &start, &stop)) {
+ ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_ReferenceStart, start, UFBX_PROP_INTEGER);
+ ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_ReferenceStop, stop, UFBX_PROP_INTEGER);
+ }
+
+ const char *name;
+ ufbxi_check(ufbxi_get_val1(node, "C", (char**)&name));
+
+ // Hack: For post-7000 files we are only interested in the animation times
+ // for fallback in case the information is missing in the stacks.
+ if (uc->version >= 7000) {
+ uint32_t hash = ufbxi_hash_ptr(name);
+ ufbxi_tmp_anim_stack *entry = ufbxi_map_find(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &name);
+
+ if (entry) {
+ ufbx_anim_stack *stack = entry->stack;
+ if (stack->props.props.count == 0) {
+ stack->props.props.count = num_props;
+ stack->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(stack->props.props.data);
+ }
+ }
+
+ return 1;
+ }
+
+ uint64_t stack_fbx_id = 0, layer_fbx_id = 0;
+
+ // Treat the Take as a post-7000 version animation stack and layer.
+ ufbx_anim_stack *stack = ufbxi_push_synthetic_element(uc, &stack_fbx_id, node, name, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
+ ufbxi_check(stack);
+
+ stack->props.props.count = num_props;
+ stack->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(stack->props.props.data);
+
+ ufbx_anim_layer *layer = ufbxi_push_synthetic_element(uc, &layer_fbx_id, node, ufbxi_BaseLayer, ufbx_anim_layer, UFBX_ELEMENT_ANIM_LAYER);
+ ufbxi_check(layer);
+
+ ufbxi_check(ufbxi_connect_oo(uc, layer_fbx_id, stack_fbx_id));
+
+ // Read all properties of objects included in the take
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ // TODO: Do some object types have another name?
+ if (child->name != ufbxi_Model) continue;
+
+ ufbxi_check(ufbxi_read_take_object(uc, child, layer_fbx_id));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_takes(ufbxi_context *uc)
+{
+ for (;;) {
+ ufbxi_node *node;
+ ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
+ if (!node) break;
+
+ if (node->name == ufbxi_Take) {
+ ufbxi_check(ufbxi_read_take(uc, node));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_settings(ufbxi_context *uc, ufbxi_node *node)
+{
+ if (uc->read_legacy_settings) return 1;
+ uc->read_legacy_settings = true;
+
+ ufbx_prop tmp_props[2];
+ uint32_t num_props = 0;
+ memset(tmp_props, 0, sizeof(tmp_props));
+
+ ufbxi_node *frame_rate = ufbxi_find_child_strcmp(node, "FrameRate");
+ if (frame_rate) {
+ double fps = 0.0;
+ if (!ufbxi_get_val1(frame_rate, "D", &fps)) {
+ ufbx_string str;
+ if (ufbxi_get_val1(frame_rate, "S", &str)) {
+ char *end;
+ double val = ufbxi_parse_double(str.data, str.length, &end, uc->double_parse_flags);
+ if (end == str.data + str.length) {
+ fps = val;
+ }
+ }
+ }
+ if (fps > 0.0) {
+ ufbxi_init_synthetic_real_prop(&tmp_props[num_props++], ufbxi_CustomFrameRate, (ufbx_real)fps, UFBX_PROP_NUMBER);
+ ufbxi_init_synthetic_real_prop(&tmp_props[num_props++], ufbxi_TimeMode, UFBX_TIME_MODE_CUSTOM, UFBX_PROP_INTEGER);
+ }
+ }
+
+ if (num_props > 0) {
+ ufbx_props *props = &uc->scene.settings.props;
+ size_t num_existing = props->props.count;
+
+ size_t new_count = num_props + num_existing;
+ ufbx_prop *new_props = ufbxi_push(&uc->result, ufbx_prop, new_count);
+ ufbxi_check(new_props);
+
+ memcpy(new_props, tmp_props, num_props * sizeof(ufbx_prop));
+ if (num_existing > 0) {
+ memcpy(new_props + num_props, props->props.data, num_existing * sizeof(ufbx_prop));
+ }
+
+ ufbxi_check(ufbxi_sort_properties(uc, new_props, new_count));
+ props->props.data = new_props;
+ props->props.count = new_count;
+ ufbxi_deduplicate_properties(&props->props);
+
+ ufbxi_check(uc->scene.settings.props.props.data);
+ }
+
+ return 1;
+}
+
+ufbxi_noinline static ufbx_matrix ufbxi_unscaled_transform_to_matrix(const ufbx_transform *t)
+{
+ ufbx_transform transform = *t;
+ transform.scale.x = 1.0f;
+ transform.scale.y = 1.0f;
+ transform.scale.z = 1.0f;
+ return ufbx_transform_to_matrix(&transform);
+}
+
+ufbxi_noinline static void ufbxi_setup_root_node(ufbxi_context *uc, ufbx_node *root)
+{
+ if (uc->opts.use_root_transform) {
+ root->local_transform = uc->opts.root_transform;
+ root->node_to_parent = ufbx_transform_to_matrix(&uc->opts.root_transform);
+ } else {
+ root->local_transform = ufbx_identity_transform;
+ root->node_to_parent = ufbx_identity_matrix;
+ }
+ root->is_root = true;
+}
+
+static ufbxi_forceinline bool ufbxi_supports_version(uint32_t version)
+{
+ return version >= 3000 && version <= 7700;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_root(ufbxi_context *uc)
+{
+ // FBXHeaderExtension: Some metadata (optional)
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_FBXHeaderExtension));
+ ufbxi_check(ufbxi_read_header_extension(uc));
+
+ // The ASCII exporter version is stored in top-level
+ if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Creator));
+ if (uc->top_node) {
+ ufbxi_ignore(ufbxi_get_val1(uc->top_node, "S", &uc->scene.metadata.creator));
+ }
+ }
+
+ // Resolve the exporter before continuing
+ ufbxi_check(ufbxi_match_exporter(uc));
+ if (uc->version < 7000) {
+ ufbxi_check(ufbxi_init_node_prop_names(uc));
+ }
+ // Don't allow changing version from this point onwards
+ uc->ascii.found_version = true;
+
+ // Document: Read root ID
+ if (uc->version >= 7000) {
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Documents));
+ ufbxi_check(ufbxi_read_document(uc));
+ } else {
+ // Pre-7000: Root node has a specific type-name pair "Model::Scene"
+ // (or reversed in binary). Use the interned name as ID as usual.
+ const char *root_name = uc->from_ascii ? "Model::Scene" : "Scene\x00\x01Model";
+ root_name = ufbxi_push_string_imp(&uc->string_pool, root_name, 12, NULL, false, true);
+ ufbxi_check(root_name);
+ uc->root_id = ufbxi_synthetic_id_from_string(uc, root_name);
+ ufbxi_check(uc->root_id);
+ }
+
+ // Add a nameless root node with the root ID
+ {
+ ufbxi_element_info root_info = { uc->root_id };
+ root_info.name = ufbx_empty_string;
+ ufbx_node *root = ufbxi_push_element(uc, &root_info, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(root);
+ ufbxi_setup_root_node(uc, root);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
+ }
+
+ // Definitions: Object type counts and property templates (optional)
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Definitions));
+ ufbxi_check(ufbxi_read_definitions(uc));
+
+ // Objects: Actual scene data
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Objects));
+ if (!uc->sure_fbx) {
+ // If the file is a bit iffy about being a real FBX file reject it if
+ // even the objects are not found.
+ ufbxi_check_msg(uc->top_node, "Not an FBX file");
+ }
+ if (uc->thread_pool.enabled) {
+ ufbxi_check(ufbxi_read_objects_threaded(uc));
+ } else {
+ ufbxi_check(ufbxi_read_objects(uc));
+ }
+
+ // Connections: Relationships between nodes
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Connections));
+ ufbxi_check(ufbxi_read_connections(uc));
+
+ // Takes: Pre-7000 animation data
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Takes));
+ ufbxi_check(ufbxi_read_takes(uc));
+
+ // Check if there's a top-level GlobalSettings that we skimmed over
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_GlobalSettings));
+ if (uc->top_node) {
+ ufbxi_check(ufbxi_read_global_settings(uc, uc->top_node));
+ }
+
+ // Version5: Pre-6000 settings
+ ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Version5));
+ if (uc->top_node) {
+ ufbxi_node *settings = ufbxi_find_child_strcmp(uc->top_node, "Settings");
+ if (settings) {
+ ufbxi_check(ufbxi_read_legacy_settings(uc, settings));
+ }
+ }
+
+ // Force parsing all the nodes by parsing a toplevel that cannot be found
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_parse_toplevel(uc, NULL));
+ }
+
+ return 1;
+}
+
+typedef struct {
+ const char *prop_name;
+ ufbx_prop_type prop_type;
+ const char *node_name;
+ const char *node_fmt;
+} ufbxi_legacy_prop;
+
+// Must be alphabetically sorted!
+static const ufbxi_legacy_prop ufbxi_legacy_light_props[] = {
+ { ufbxi_CastLight, UFBX_PROP_BOOLEAN, ufbxi_CastLight, "L" },
+ { ufbxi_CastShadows, UFBX_PROP_BOOLEAN, ufbxi_CastShadows, "L" },
+ { ufbxi_Color, UFBX_PROP_COLOR, ufbxi_Color, "RRR" },
+ { ufbxi_ConeAngle, UFBX_PROP_NUMBER, ufbxi_ConeAngle, "R" },
+ { ufbxi_HotSpot, UFBX_PROP_NUMBER, ufbxi_HotSpot, "R" },
+ { ufbxi_Intensity, UFBX_PROP_NUMBER, ufbxi_Intensity, "R" },
+ { ufbxi_LightType, UFBX_PROP_INTEGER, ufbxi_LightType, "L" },
+};
+
+// Must be alphabetically sorted!
+static const ufbxi_legacy_prop ufbxi_legacy_camera_props[] = {
+ { ufbxi_ApertureMode, UFBX_PROP_INTEGER, ufbxi_ApertureMode, "L" },
+ { ufbxi_AspectH, UFBX_PROP_NUMBER, ufbxi_AspectH, "R" },
+ { ufbxi_AspectRatioMode, UFBX_PROP_INTEGER, "AspectType", "L" },
+ { ufbxi_AspectW, UFBX_PROP_NUMBER, ufbxi_AspectW, "R" },
+ { ufbxi_FieldOfView, UFBX_PROP_NUMBER, "Aperture", "R" },
+ { ufbxi_FieldOfViewX, UFBX_PROP_NUMBER, "FieldOfViewXProperty", "R" },
+ { ufbxi_FieldOfViewY, UFBX_PROP_NUMBER, "FieldOfViewYProperty", "R" },
+ { ufbxi_FilmHeight, UFBX_PROP_NUMBER, "CameraAperture", "_R" },
+ { ufbxi_FilmSqueezeRatio, UFBX_PROP_NUMBER, "SqueezeRatio", "R" },
+ { ufbxi_FilmWidth, UFBX_PROP_NUMBER, "CameraAperture", "R_" },
+ { ufbxi_FocalLength, UFBX_PROP_NUMBER, ufbxi_FocalLength, "R" },
+};
+
+// Must be alphabetically sorted!
+static const ufbxi_legacy_prop ufbxi_legacy_bone_props[] = {
+ { ufbxi_Size, UFBX_PROP_NUMBER, ufbxi_Size, "R" },
+};
+
+// Must be alphabetically sorted!
+static const ufbxi_legacy_prop ufbxi_legacy_material_props[] = {
+ { ufbxi_AmbientColor, UFBX_PROP_COLOR, "Ambient", "RRR" },
+ { ufbxi_DiffuseColor, UFBX_PROP_COLOR, "Diffuse", "RRR" },
+ { ufbxi_EmissiveColor, UFBX_PROP_COLOR, "Emissive", "RRR" },
+ { ufbxi_ShadingModel, UFBX_PROP_COLOR, ufbxi_ShadingModel, "S" },
+ { ufbxi_Shininess, UFBX_PROP_NUMBER, "Shininess", "R" },
+ { ufbxi_SpecularColor, UFBX_PROP_COLOR, "Specular", "RRR" },
+};
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_prop(ufbxi_node *node, ufbx_prop *prop, const ufbxi_legacy_prop *legacy_prop)
+{
+ size_t value_ix = 0;
+ uint32_t flags = 0;
+
+ const char *fmt = legacy_prop->node_fmt;
+ for (size_t fmt_ix = 0; fmt[fmt_ix]; fmt_ix++) {
+ char c = fmt[fmt_ix];
+ switch (c) {
+ case 'L':
+ ufbx_assert(value_ix == 0);
+ if (!ufbxi_get_val_at(node, fmt_ix, 'L', &prop->value_int)) return 0;
+ prop->value_real = (ufbx_real)prop->value_int;
+ prop->value_real_arr[1] = 0.0f;
+ prop->value_real_arr[2] = 0.0f;
+ prop->value_real_arr[3] = 0.0f;
+ prop->value_str = ufbx_empty_string;
+ prop->value_blob = ufbx_empty_blob;
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_INT;
+ value_ix++;
+ break;
+ case 'R':
+ ufbx_assert(value_ix < 4);
+ if (!ufbxi_get_val_at(node, fmt_ix, 'R', &prop->value_real_arr[value_ix])) return 0;
+ if (value_ix == 0) {
+ prop->value_int = ufbxi_f64_to_i64(prop->value_real);
+ prop->value_real_arr[1] = 0.0f;
+ prop->value_real_arr[2] = 0.0f;
+ prop->value_real_arr[3] = 0.0f;
+ prop->value_str = ufbx_empty_string;
+ prop->value_blob = ufbx_empty_blob;
+ }
+ flags &= ~(uint32_t)(UFBX_PROP_FLAG_VALUE_REAL|UFBX_PROP_FLAG_VALUE_VEC2|UFBX_PROP_FLAG_VALUE_VEC3|UFBX_PROP_FLAG_VALUE_VEC4);
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << value_ix;
+ value_ix++;
+ break;
+ case 'S':
+ ufbx_assert(value_ix == 0);
+ if (!ufbxi_get_val_at(node, fmt_ix, 'S', &prop->value_str)) return 0;
+ // `vals[fmt_ix]` is known to be a string, fetch non-sanitized blob directly
+ prop->value_blob.data = node->vals[fmt_ix].s.raw_data;
+ prop->value_blob.size = node->vals[fmt_ix].s.raw_length;
+ prop->value_real = 0.0f;
+ prop->value_real_arr[1] = 0.0f;
+ prop->value_real_arr[2] = 0.0f;
+ prop->value_real_arr[3] = 0.0f;
+ prop->value_int = 0;
+ flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_STR;
+ value_ix++;
+ break;
+ case '_':
+ break;
+ default:
+ ufbxi_unreachable("Unhandled legacy fmt");
+ }
+ }
+
+ prop->flags = (ufbx_prop_flags)flags;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static size_t ufbxi_read_legacy_props(ufbxi_node *node, ufbx_prop *props, const ufbxi_legacy_prop *legacy_props, size_t num_legacy)
+{
+ size_t num_props = 0;
+ for (size_t legacy_ix = 0; legacy_ix < num_legacy; legacy_ix++) {
+ const ufbxi_legacy_prop *legacy_prop = &legacy_props[legacy_ix];
+ ufbx_prop *prop = &props[num_props];
+
+ ufbxi_node *n = ufbxi_find_child_strcmp(node, legacy_prop->node_name);
+ if (!n) continue;
+ if (!ufbxi_read_legacy_prop(n, prop, legacy_prop)) continue;
+
+ prop->name.data = legacy_prop->prop_name;
+ prop->name.length = strlen(legacy_prop->prop_name);
+ prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
+ prop->flags = (ufbx_prop_flags)0;
+ prop->type = legacy_prop->prop_type;
+ num_props++;
+ }
+
+ return num_props;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_material(ufbxi_context *uc, ufbxi_node *node, uint64_t *p_fbx_id, const char *name)
+{
+ ufbx_material *ufbxi_restrict material = ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, ufbx_material, UFBX_ELEMENT_MATERIAL);
+ ufbxi_check(material);
+
+ ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_material_props)];
+ size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_material_props, ufbxi_arraycount(ufbxi_legacy_material_props));
+
+ material->shading_model_name = ufbx_empty_string;
+ material->props.props.count = num_props;
+ material->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(material->props.props.data);
+
+ material->shader_prop_prefix = ufbx_empty_string;
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_link(ufbxi_context *uc, ufbxi_node *node, uint64_t *p_fbx_id, const char *name)
+{
+ ufbx_skin_cluster *ufbxi_restrict cluster = ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, ufbx_skin_cluster, UFBX_ELEMENT_SKIN_CLUSTER);
+ ufbxi_check(cluster);
+
+ // TODO: Merge with ufbxi_read_skin_cluster(), at least partially?
+ ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
+ ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_Weights, 'r');
+
+ if (indices && weights) {
+ ufbxi_check(indices->size == weights->size);
+ cluster->num_weights = indices->size;
+ cluster->vertices.data = (uint32_t*)indices->data;
+ cluster->weights.data = (ufbx_real*)weights->data;
+ cluster->vertices.count = cluster->num_weights;
+ cluster->weights.count = cluster->num_weights;
+ }
+
+ ufbxi_value_array *transform = ufbxi_find_array(node, ufbxi_Transform, 'r');
+ ufbxi_value_array *transform_link = ufbxi_find_array(node, ufbxi_TransformLink, 'r');
+ if (transform && transform_link) {
+ ufbxi_check(transform->size >= 16);
+ ufbxi_check(transform_link->size >= 16);
+
+ ufbxi_read_transform_matrix(&cluster->mesh_node_to_bone, (ufbx_real*)transform->data);
+ ufbxi_read_transform_matrix(&cluster->bind_to_world, (ufbx_real*)transform_link->data);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_light(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_light *ufbxi_restrict light = ufbxi_push_element(uc, info, ufbx_light, UFBX_ELEMENT_LIGHT);
+ ufbxi_check(light);
+
+ ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_light_props)];
+ size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_light_props, ufbxi_arraycount(ufbxi_legacy_light_props));
+
+ light->props.props.count = num_props;
+ light->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(light->props.props.data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_camera(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_camera *ufbxi_restrict camera = ufbxi_push_element(uc, info, ufbx_camera, UFBX_ELEMENT_CAMERA);
+ ufbxi_check(camera);
+
+ ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_camera_props)];
+ size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_camera_props, ufbxi_arraycount(ufbxi_legacy_camera_props));
+
+ camera->props.props.count = num_props;
+ camera->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(camera->props.props.data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_limb_node(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ ufbx_bone *ufbxi_restrict bone = ufbxi_push_element(uc, info, ufbx_bone, UFBX_ELEMENT_BONE);
+ ufbxi_check(bone);
+
+ ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_bone_props)];
+ size_t num_props = 0;
+
+ ufbxi_node *prop_node = ufbxi_find_child_strcmp(node, "Properties");
+ if (prop_node) {
+ num_props = ufbxi_read_legacy_props(prop_node, tmp_props, ufbxi_legacy_bone_props, ufbxi_arraycount(ufbxi_legacy_bone_props));
+ }
+
+ bone->props.props.count = num_props;
+ bone->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
+ ufbxi_check(bone->props.props.data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_mesh(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
+{
+ // Only read polygon meshes, ignore eg. NURBS without error
+ ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
+ ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_PolygonVertexIndex);
+ if (!node_vertices || !node_indices) return 1;
+
+ ufbx_mesh *ufbxi_restrict mesh = ufbxi_push_element(uc, info, ufbx_mesh, UFBX_ELEMENT_MESH);
+ ufbxi_check(mesh);
+
+ ufbxi_check(ufbxi_read_synthetic_blend_shapes(uc, node, info));
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ if (uc->opts.ignore_geometry) return 1;
+
+ ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
+ ufbxi_value_array *indices = ufbxi_get_array(node_indices, 'i');
+ ufbxi_check(vertices && indices);
+ ufbxi_check(vertices->size % 3 == 0);
+
+ mesh->num_vertices = vertices->size / 3;
+ mesh->num_indices = indices->size;
+
+ uint32_t *index_data = (uint32_t*)indices->data;
+
+ // Duplicate `index_data` for modification if we retain DOM
+ if (uc->opts.retain_dom) {
+ index_data = ufbxi_push_copy(&uc->result, uint32_t, indices->size, index_data);
+ ufbxi_check(index_data);
+ }
+
+ mesh->vertices.data = (ufbx_vec3*)vertices->data;
+ mesh->vertex_indices.data = index_data;
+ mesh->vertices.count = mesh->num_vertices;
+ mesh->vertex_indices.count = mesh->num_indices;
+
+ mesh->vertex_position.exists = true;
+ mesh->vertex_position.values.data = (ufbx_vec3*)vertices->data;
+ mesh->vertex_position.values.count = mesh->num_vertices;
+ mesh->vertex_position.indices.data = index_data;
+ mesh->vertex_position.indices.count = mesh->num_indices;
+ mesh->vertex_position.unique_per_vertex = true;
+
+ // Check/make sure that the last index is negated (last of polygon)
+ if (mesh->num_indices > 0) {
+ if ((int32_t)index_data[mesh->num_indices - 1] >= 0) {
+ if (uc->opts.strict) ufbxi_fail("Non-negated last index");
+ index_data[mesh->num_indices - 1] = ~index_data[mesh->num_indices - 1];
+ }
+ }
+
+ ufbxi_check(ufbxi_process_indices(uc, mesh, index_data));
+
+ // Normals are either per-vertex or per-index in legacy FBX files?
+ // If the version is 5000 prefer per-vertex, otherwise per-index...
+ ufbxi_value_array *normals = ufbxi_find_array(node, ufbxi_Normals, 'r');
+ if (normals) {
+ size_t num_normals = normals->size / 3;
+ bool per_vertex = num_normals == mesh->num_vertices;
+ bool per_index = num_normals == mesh->num_indices;
+ if (per_vertex && (!per_index || uc->version == 5000)) {
+ mesh->vertex_normal.exists = true;
+ mesh->vertex_normal.values.count = num_normals;
+ mesh->vertex_normal.indices.count = mesh->num_indices;
+ mesh->vertex_normal.unique_per_vertex = true;
+ mesh->vertex_normal.values.data = (ufbx_vec3*)normals->data;
+ mesh->vertex_normal.indices.data = mesh->vertex_indices.data;
+ } else if (per_index) {
+ uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_indices);
+ mesh->vertex_normal.exists = true;
+ mesh->vertex_normal.values.count = num_normals;
+ mesh->vertex_normal.indices.count = mesh->num_indices;
+ mesh->vertex_normal.unique_per_vertex = false;
+ mesh->vertex_normal.values.data = (ufbx_vec3*)normals->data;
+ mesh->vertex_normal.indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
+ }
+ }
+
+ // Optional UV values are stored pretty much like a modern vertex element
+ ufbxi_node *uv_info = ufbxi_find_child(node, ufbxi_GeometryUVInfo);
+ if (uv_info) {
+ ufbx_uv_set *set = ufbxi_push_zero(&uc->result, ufbx_uv_set, 1);
+ ufbxi_check(set);
+ set->index = 0;
+ set->name.data = ufbxi_empty_char;
+ ufbxi_check(ufbxi_read_vertex_element(uc, mesh, uv_info, (ufbx_vertex_attrib*)&set->vertex_uv,
+ ufbxi_TextureUV, ufbxi_TextureUVVerticeIndex, NULL, 'r', 2));
+
+ mesh->uv_sets.data = set;
+ mesh->uv_sets.count = 1;
+ mesh->vertex_uv = set->vertex_uv;
+ }
+
+ // Material indices
+ {
+ const char *mapping = NULL;
+ ufbxi_check(ufbxi_find_val1(node, ufbxi_MaterialAssignation, "C", (char**)&mapping));
+ if (mapping == ufbxi_ByPolygon) {
+ ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_material.data, &mesh->face_material.count, node, ufbxi_Materials, 'i', mesh->num_faces));
+ } else if (mapping == ufbxi_AllSame) {
+ ufbxi_value_array *arr = ufbxi_find_array(node, ufbxi_Materials, 'i');
+ uint32_t material = 0;
+ if (arr && arr->size >= 1) {
+ material = ((uint32_t*)arr->data)[0];
+ }
+
+ mesh->face_material.count = mesh->num_faces;
+ if (material == 0) {
+ mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ } else {
+ mesh->face_material.data = ufbxi_push(&uc->result, uint32_t, mesh->num_faces);
+ ufbxi_check(mesh->face_material.data);
+ ufbxi_for_list(uint32_t, p_mat, mesh->face_material) {
+ *p_mat = material;
+ }
+ }
+ }
+ }
+
+ uint64_t skin_fbx_id = 0;
+ ufbx_skin_deformer *skin = NULL;
+
+ // Materials, Skin Clusters
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ if (child->name == ufbxi_Material) {
+ uint64_t fbx_id = 0;
+ ufbx_string type_and_name, type, name;
+ ufbxi_check(ufbxi_get_val1(child, "s", &type_and_name));
+ ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
+ ufbxi_check(ufbxi_read_legacy_material(uc, child, &fbx_id, name.data));
+ ufbxi_check(ufbxi_connect_oo(uc, fbx_id, info->fbx_id));
+ } else if (child->name == ufbxi_Link) {
+ uint64_t fbx_id = 0;
+ ufbx_string type_and_name, type, name;
+ ufbxi_check(ufbxi_get_val1(child, "s", &type_and_name));
+ ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
+ ufbxi_check(ufbxi_read_legacy_link(uc, child, &fbx_id, name.data));
+
+ uint64_t node_fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
+ ufbxi_check(node_fbx_id);
+ ufbxi_check(ufbxi_connect_oo(uc, node_fbx_id, fbx_id));
+ if (!skin) {
+ skin = ufbxi_push_synthetic_element(uc, &skin_fbx_id, NULL, info->name.data, ufbx_skin_deformer, UFBX_ELEMENT_SKIN_DEFORMER);
+ ufbxi_check(skin);
+ ufbxi_check(ufbxi_connect_oo(uc, skin_fbx_id, info->fbx_id));
+ }
+ ufbxi_check(ufbxi_connect_oo(uc, fbx_id, skin_fbx_id));
+ }
+ }
+
+ mesh->skinned_is_local = true;
+ mesh->skinned_position = mesh->vertex_position;
+ mesh->skinned_normal = mesh->vertex_normal;
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_media(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbxi_node *videos = ufbxi_find_child(node, ufbxi_Video);
+ if (videos) {
+ ufbxi_for(ufbxi_node, child, videos->children, videos->num_children) {
+ ufbxi_element_info video_info = { 0 };
+ ufbxi_check(ufbxi_get_val1(child, "S", &video_info.name));
+ video_info.fbx_id = ufbxi_push_synthetic_id(uc);
+ video_info.dom_node = ufbxi_get_dom_node(uc, node);
+
+ ufbxi_check(ufbxi_read_video(uc, child, &video_info));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_model(ufbxi_context *uc, ufbxi_node *node)
+{
+ ufbx_string type_and_name, type, name;
+ ufbxi_check(ufbxi_get_val1(node, "s", &type_and_name));
+ ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
+
+ ufbxi_element_info info = { 0 };
+ info.fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
+ ufbxi_check(info.fbx_id);
+ info.name = name;
+ info.dom_node = ufbxi_get_dom_node(uc, node);
+
+ ufbx_node *elem_node = ufbxi_push_element(uc, &info, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(elem_node);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &elem_node->element.element_id));
+
+ ufbxi_element_info attrib_info = { 0 };
+ attrib_info.fbx_id = ufbxi_push_synthetic_id(uc);
+ attrib_info.name = name;
+ attrib_info.dom_node = info.dom_node;
+
+ // If we make unused connections it doesn't matter..
+ ufbxi_check(ufbxi_connect_oo(uc, attrib_info.fbx_id, info.fbx_id));
+
+ const char *attrib_type = ufbxi_empty_char;
+ ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Type, "C", (char**)&attrib_type));
+
+ bool has_attrib = true;
+ if (attrib_type == ufbxi_Light) {
+ ufbxi_check(ufbxi_read_legacy_light(uc, node, &attrib_info));
+ } else if (attrib_type == ufbxi_Camera) {
+ ufbxi_check(ufbxi_read_legacy_camera(uc, node, &attrib_info));
+ } else if (attrib_type == ufbxi_LimbNode) {
+ ufbxi_check(ufbxi_read_legacy_limb_node(uc, node, &attrib_info));
+ } else if (ufbxi_find_child(node, ufbxi_Vertices)) {
+ ufbxi_check(ufbxi_read_legacy_mesh(uc, node, &attrib_info));
+ } else {
+ has_attrib = false;
+ }
+
+ // Mark the node as having an attribute so property connections can be forwarded
+ if (has_attrib) {
+ ufbxi_check(ufbxi_insert_fbx_attr(uc, info.fbx_id, attrib_info.fbx_id));
+ }
+
+ // Children are represented as an array of strings
+ ufbxi_value_array *children = ufbxi_find_array(node, ufbxi_Children, 's');
+ if (children) {
+ ufbx_string *names = (ufbx_string*)children->data;
+ for (size_t i = 0; i < children->size; i++) {
+ uint64_t child_fbx_id = ufbxi_synthetic_id_from_string(uc, names[i].data);
+ ufbxi_check(child_fbx_id);
+ ufbxi_check(ufbxi_connect_oo(uc, child_fbx_id, info.fbx_id));
+ }
+ }
+
+ // Non-take animation channels
+ ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
+ if (child->name == ufbxi_Channel) {
+ ufbx_string channel_name;
+ if (ufbxi_get_val1(child, "S", &channel_name)) {
+ if (uc->legacy_implicit_anim_layer_id == 0) {
+ // Defer creation so we won't be the first animation stack..
+ uc->legacy_implicit_anim_layer_id = ufbxi_push_synthetic_id(uc);
+ }
+ ufbxi_check(ufbxi_read_take_prop_channel(uc, child, info.fbx_id, uc->legacy_implicit_anim_layer_id, channel_name));
+ }
+ }
+ }
+
+ return 1;
+}
+
+// Read a pre-6000 FBX file where everything is stored at the root level
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_legacy_root(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_init_node_prop_names(uc));
+
+ // Some legacy FBX files have an `Fbx_Root` node that could be used as the
+ // root node. However no other formats have root node with transforms so it
+ // might be better to leave it as-is and create an empty one.
+ {
+ ufbx_node *root = ufbxi_push_synthetic_element(uc, &uc->root_id, NULL, ufbxi_empty_char, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(root);
+ ufbxi_setup_root_node(uc, root);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
+ }
+
+ // NOTE: `ufbxi_read_header_extension()` is optional so use default KTime definition
+ uc->ktime_sec = 46186158000;
+ uc->ktime_sec_double = (double)uc->ktime_sec;
+
+ for (;;) {
+ ufbxi_check(ufbxi_parse_legacy_toplevel(uc));
+ if (!uc->top_node) break;
+
+ ufbxi_node *node = uc->top_node;
+ if (node->name == ufbxi_FBXHeaderExtension) {
+ ufbxi_check(ufbxi_read_header_extension(uc));
+ } else if (node->name == ufbxi_Media) {
+ ufbxi_check(ufbxi_read_legacy_media(uc, node));
+ } else if (node->name == ufbxi_Takes) {
+ ufbxi_check(ufbxi_read_takes(uc));
+ } else if (node->name == ufbxi_Model) {
+ ufbxi_check(ufbxi_read_legacy_model(uc, node));
+ } else if (!strcmp(node->name, "Settings")) {
+ ufbxi_check(ufbxi_read_legacy_settings(uc, node));
+ }
+ }
+
+ if (uc->opts.retain_dom) {
+ ufbxi_check(ufbxi_retain_toplevel(uc, NULL));
+ }
+
+ // Create the implicit animation stack if necessary
+ if (uc->legacy_implicit_anim_layer_id) {
+ ufbxi_element_info layer_info = { 0 };
+ layer_info.fbx_id = uc->legacy_implicit_anim_layer_id;
+ layer_info.name.data = "(internal)";
+ layer_info.name.length = strlen(layer_info.name.data);
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &layer_info.name, true));
+ ufbx_anim_layer *layer = ufbxi_push_element(uc, &layer_info, ufbx_anim_layer, UFBX_ELEMENT_ANIM_LAYER);
+ ufbxi_check(layer);
+
+ ufbxi_element_info stack_info = layer_info;
+ stack_info.fbx_id = ufbxi_push_synthetic_id(uc);
+ ufbx_anim_stack *stack = ufbxi_push_element(uc, &stack_info, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
+ ufbxi_check(stack);
+
+ ufbxi_check(ufbxi_connect_oo(uc, layer_info.fbx_id, stack_info.fbx_id));
+ }
+
+ return 1;
+}
+
+// Filename manipulation
+
+ufbxi_nodiscard ufbxi_noinline static size_t ufbxi_trim_delimiters(ufbxi_context *uc, const char *data, size_t length)
+{
+ for (; length > 0; length--) {
+ char c = data[length - 1];
+ bool is_separator = c == '/' || c == uc->opts.path_separator;
+ if (is_separator) {
+ length--;
+ break;
+ }
+ }
+ return length;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_init_file_paths(ufbxi_context *uc)
+{
+ if (uc->opts.filename.length > 0) {
+ uc->scene.metadata.filename = uc->opts.filename;
+ } else if (uc->opts.raw_filename.size > 0) {
+ uc->scene.metadata.filename.data = (const char*)uc->opts.raw_filename.data;
+ uc->scene.metadata.filename.length = uc->opts.raw_filename.size;
+ }
+
+ if (uc->opts.raw_filename.size > 0) {
+ uc->scene.metadata.raw_filename = uc->opts.raw_filename;
+ } else if (uc->opts.filename.length > 0) {
+ uc->scene.metadata.raw_filename.data = uc->opts.filename.data;
+ uc->scene.metadata.raw_filename.size = uc->opts.filename.length;
+ }
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->scene.metadata.filename, false));
+ ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &uc->scene.metadata.raw_filename, true));
+
+ uc->scene.metadata.relative_root.data = uc->scene.metadata.filename.data;
+ uc->scene.metadata.relative_root.length = ufbxi_trim_delimiters(uc, uc->scene.metadata.filename.data, uc->scene.metadata.filename.length);
+
+ uc->scene.metadata.raw_relative_root.data = uc->scene.metadata.raw_filename.data;
+ uc->scene.metadata.raw_relative_root.size = ufbxi_trim_delimiters(uc, (const char*)uc->scene.metadata.raw_filename.data, uc->scene.metadata.raw_filename.size);
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->scene.metadata.relative_root, false));
+ ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &uc->scene.metadata.raw_relative_root, true));
+
+ return 1;
+}
+
+typedef union {
+ ufbx_string str;
+ ufbx_blob blob;
+} ufbxi_strblob;
+
+static ufbxi_noinline void ufbxi_strblob_set(ufbxi_strblob *dst, const char *data, size_t length, bool raw)
+{
+ if (raw) {
+ dst->blob.data = data;
+ dst->blob.size = length;
+ } else {
+ dst->str.data = length == 0 ? ufbxi_empty_char : data;
+ dst->str.length = length;
+ }
+}
+
+static ufbxi_forceinline const char *ufbxi_strblob_data(const ufbxi_strblob *strblob, bool raw)
+{
+ return raw ? (const char*)strblob->blob.data : strblob->str.data;
+}
+
+static ufbxi_forceinline size_t ufbxi_strblob_length(const ufbxi_strblob *strblob, bool raw)
+{
+ return raw ? strblob->blob.size : strblob->str.length;
+}
+
+ufbxi_nodiscard ufbxi_noinline static bool ufbxi_is_absolute_path(const char *path, size_t length)
+{
+ if (length > 0 && (path[0] == '/' || path[0] == '\\')) {
+ return true;
+ } else if (length > 2 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
+ return true;
+ }
+ return false;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_relative_filename(ufbxi_context *uc, ufbxi_strblob *p_dst, const ufbxi_strblob *p_src, bool raw)
+{
+ const char *src = ufbxi_strblob_data(p_src, raw);
+ size_t src_length = ufbxi_strblob_length(p_src, raw);
+
+ // Skip leading directory separators and early return if the relative path is empty
+ while (src_length > 0 && (src[0] == '/' || src[0] == '\\')) {
+ src++;
+ src_length--;
+ }
+ if (src_length == 0) {
+ ufbxi_strblob_set(p_dst, NULL, 0, raw);
+ return 1;
+ }
+
+ const char *prefix_data;
+ size_t prefix_length;
+ if (raw) {
+ prefix_data = (const char*)uc->scene.metadata.raw_relative_root.data;
+ prefix_length = uc->scene.metadata.raw_relative_root.size;
+ } else {
+ prefix_data = (const char*)uc->scene.metadata.relative_root.data;
+ prefix_length = uc->scene.metadata.relative_root.length;
+ }
+
+ // Retain absolute paths
+ if (ufbxi_is_absolute_path(src, src_length)) {
+ prefix_length = 0;
+ }
+
+ // Undo directories from `prefix` for every `..`
+ while (prefix_length > 0 && src_length >= 3 && src[0] == '.' && src[1] == '.' && (src[2] == '/' || src[2] == '\\')) {
+ size_t part_start = prefix_length;
+ while (part_start > 0 && !(prefix_data[part_start - 1] == '/' || prefix_data[part_start - 1] == '\\')) {
+ part_start--;
+ }
+ size_t part_len = prefix_length - part_start;
+
+ if (part_len == 2 && prefix_data[part_start] == '.' && prefix_data[part_start + 1] == '.') {
+ // Prefix itself ends in `..`, cannot cancel out a leading `../`
+ break;
+ }
+
+ // Eat the leading '/' before the part segment
+ prefix_length = part_start > 0 ? part_start - 1 : 0;
+
+ if (part_len == 1 && prefix_data[part_start] == '.') {
+ // Single '.' -> remove and continue without cancelling out a leading `../`
+ continue;
+ }
+
+ src += 3;
+ src_length -= 3;
+ }
+
+ size_t result_cap = prefix_length + src_length + 1;
+ char *result = ufbxi_push(&uc->tmp_stack, char, result_cap);
+ ufbxi_check(result);
+ char *ptr = result;
+
+ // Copy prefix and suffix converting separators in the process
+ if (prefix_length > 0) {
+ memcpy(ptr, prefix_data, prefix_length);
+ ptr[prefix_length] = uc->opts.path_separator;
+ ptr += prefix_length + 1;
+ }
+ for (size_t i = 0; i < src_length; i++) {
+ char c = src[i];
+ if (c == '/' || c == '\\') {
+ c = uc->opts.path_separator;
+ }
+ *ptr++ = c;
+ }
+
+ // Intern the string and pop the temporary buffer
+ ufbx_string dst = { result, ufbxi_to_size(ptr - result) };
+ ufbx_assert(dst.length <= result_cap);
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst, raw));
+ ufbxi_pop(&uc->tmp_stack, char, result_cap, NULL);
+
+ ufbxi_strblob_set(p_dst, dst.data, dst.length, raw);
+
+ return 1;
+}
+
+// Open file utility
+
+static ufbxi_noinline bool ufbxi_open_file(const ufbx_open_file_cb *cb, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_blob *original_filename, ufbxi_allocator *ator, ufbx_open_file_type type)
+{
+ if (!cb || !cb->fn) return false;
+
+ ufbx_open_file_info info; // ufbxi_uninit
+ info.context = (uintptr_t)ator;
+ if (original_filename) {
+ info.original_filename = *original_filename;
+ } else {
+ info.original_filename.data = path;
+ info.original_filename.size = path_len;
+ }
+ info.type = type;
+
+ return cb->fn(cb->user, stream, path, path_len, &info);
+}
+
+#define ufbxi_patch_zero(dst, src) do { \
+ ufbx_assert((dst) == 0 || (dst) == (src)); \
+ (dst) = (src); \
+ } while (0)
+
+static void ufbxi_update_vertex_first_index(ufbx_mesh *mesh)
+{
+ ufbxi_for_list(uint32_t, p_vx_ix, mesh->vertex_first_index) {
+ *p_vx_ix = UFBX_NO_INDEX;
+ }
+
+ uint32_t num_vertices = (uint32_t)mesh->num_vertices;
+ for (size_t ix = 0; ix < mesh->num_indices; ix++) {
+ uint32_t vx = mesh->vertex_indices.data[ix];
+ if (vx < num_vertices && mesh->vertex_first_index.data[vx] == UFBX_NO_INDEX) {
+ mesh->vertex_first_index.data[vx] = (uint32_t)ix;
+ }
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_mesh(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh)
+{
+ if (mesh->vertices.count == 0) {
+ mesh->vertices = mesh->vertex_position.values;
+ }
+ if (mesh->vertex_indices.count == 0) {
+ mesh->vertex_indices = mesh->vertex_position.indices;
+ }
+
+ ufbxi_patch_zero(mesh->num_vertices, mesh->vertices.count);
+ ufbxi_patch_zero(mesh->num_indices, mesh->vertex_indices.count);
+ ufbxi_patch_zero(mesh->num_faces, mesh->faces.count);
+
+ if (mesh->num_triangles == 0 || mesh->max_face_triangles == 0) {
+ size_t num_triangles = 0;
+ size_t max_face_triangles = 0;
+ size_t num_bad_faces[3] = { 0 };
+ ufbxi_nounroll ufbxi_for_list(ufbx_face, face, mesh->faces) {
+ if (face->num_indices >= 3) {
+ size_t tris = face->num_indices - 2;
+ num_triangles += tris;
+ max_face_triangles = ufbxi_max_sz(max_face_triangles, tris);
+ } else {
+ num_bad_faces[face->num_indices]++;
+ }
+ }
+
+ ufbxi_patch_zero(mesh->num_triangles, num_triangles);
+ ufbxi_patch_zero(mesh->max_face_triangles, max_face_triangles);
+ ufbxi_patch_zero(mesh->num_empty_faces, num_bad_faces[0]);
+ ufbxi_patch_zero(mesh->num_point_faces, num_bad_faces[1]);
+ ufbxi_patch_zero(mesh->num_line_faces, num_bad_faces[2]);
+ }
+
+ if (!mesh->skinned_position.exists) {
+ mesh->skinned_is_local = true;
+ mesh->skinned_position = mesh->vertex_position;
+ mesh->skinned_normal = mesh->vertex_normal;
+ }
+
+ if (mesh->vertex_first_index.count == 0) {
+ mesh->vertex_first_index.count = mesh->num_vertices;
+ mesh->vertex_first_index.data = ufbxi_push(buf, uint32_t, mesh->num_vertices);
+ ufbxi_check_err(error, mesh->vertex_first_index.data);
+ ufbxi_update_vertex_first_index(mesh);
+ }
+
+ if (mesh->uv_sets.count == 0 && mesh->vertex_uv.exists) {
+ ufbx_uv_set *uv_set = ufbxi_push_zero(buf, ufbx_uv_set, 1);
+ ufbxi_check_err(error, uv_set);
+
+ uv_set->name.data = ufbxi_empty_char;
+ uv_set->vertex_uv = mesh->vertex_uv;
+ uv_set->vertex_tangent = mesh->vertex_tangent;
+ uv_set->vertex_bitangent = mesh->vertex_bitangent;
+
+ mesh->uv_sets.data = uv_set;
+ mesh->uv_sets.count = 1;
+ }
+
+ if (mesh->color_sets.count == 0 && mesh->vertex_color.exists) {
+ ufbx_color_set *color_set = ufbxi_push_zero(buf, ufbx_color_set, 1);
+ ufbxi_check_err(error, color_set);
+
+ color_set->name.data = ufbxi_empty_char;
+ color_set->vertex_color = mesh->vertex_color;
+
+ mesh->color_sets.data = color_set;
+ mesh->color_sets.count = 1;
+ }
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ return 1;
+}
+
+// -- .obj file
+
+#if UFBXI_FEATURE_FORMAT_OBJ
+
+static const uint8_t ufbxi_obj_attrib_stride[] = {
+ 3, 2, 3, 4,
+};
+
+ufbx_static_assert(obj_attrib_strides, ufbxi_arraycount(ufbxi_obj_attrib_stride) == UFBXI_OBJ_NUM_ATTRIBS_EXT);
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_props(ufbxi_context *uc, ufbx_prop_list *dst, size_t count)
+{
+ ufbx_prop_list props; // ufbxi_uninit
+ props.count = count;
+ props.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_props, ufbx_prop, count);
+ ufbxi_check(props.data);
+
+ ufbxi_for_list(ufbx_prop, prop, props) {
+ prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
+ if (prop->value_str.length == 0) {
+ prop->value_str.data = ufbxi_empty_char;
+ }
+ if (!prop->value_int) {
+ prop->value_int = ufbxi_f64_to_i64(prop->value_real);
+ }
+ if (prop->value_blob.size == 0 && prop->value_str.length > 0) {
+ prop->value_blob.data = prop->value_str.data;
+ prop->value_blob.size = prop->value_str.length;
+ }
+ }
+
+ if (props.count > 1) {
+ ufbxi_check(ufbxi_sort_properties(uc, props.data, props.count));
+ ufbxi_deduplicate_properties(&props);
+ }
+
+ *dst = props;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_push_mesh(ufbxi_context *uc)
+{
+ ufbxi_obj_mesh *mesh = ufbxi_push_zero(&uc->obj.tmp_meshes, ufbxi_obj_mesh, 1);
+ ufbxi_check(mesh);
+ uc->obj.mesh = mesh;
+
+ ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS; i++) {
+ mesh->vertex_range[i].min_ix = UINT64_MAX;
+ }
+
+ const char *name = "";
+ if (uc->opts.obj_split_groups && uc->obj.group.length > 0) {
+ name = uc->obj.group.data;
+ } else if (!uc->opts.obj_merge_objects && uc->obj.object.length > 0) {
+ name = uc->obj.object.data;
+ } else if (!uc->opts.obj_merge_groups && uc->obj.group.length > 0) {
+ name = uc->obj.group.data;
+ }
+
+ mesh->fbx_node = ufbxi_push_synthetic_element(uc, &mesh->fbx_node_id, NULL, name, ufbx_node, UFBX_ELEMENT_NODE);
+ mesh->fbx_mesh = ufbxi_push_synthetic_element(uc, &mesh->fbx_mesh_id, NULL, name, ufbx_mesh, UFBX_ELEMENT_MESH);
+ ufbxi_check(mesh->fbx_node && mesh->fbx_mesh);
+
+ mesh->fbx_mesh->vertex_position.unique_per_vertex = true;
+
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &mesh->fbx_node->element_id));
+
+ uc->obj.face_material = UFBX_NO_INDEX;
+ uc->obj.face_group = 0;
+ uc->obj.face_group_dirty = true;
+ uc->obj.material_dirty = true;
+
+ ufbxi_check(ufbxi_connect_oo(uc, mesh->fbx_mesh_id, mesh->fbx_node_id));
+ ufbxi_check(ufbxi_connect_oo(uc, mesh->fbx_node_id, 0));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_flush_mesh(ufbxi_context *uc)
+{
+ if (!uc->obj.mesh) return 1;
+
+ size_t num_props = uc->obj.tmp_props.num_items;
+ ufbxi_check(ufbxi_obj_pop_props(uc, &uc->obj.mesh->fbx_mesh->props.props, num_props));
+
+ size_t num_groups = uc->obj.tmp_face_group_infos.num_items;
+ ufbx_face_group *groups = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_group_infos, ufbx_face_group, num_groups);
+ ufbxi_check(groups);
+
+ uc->obj.mesh->fbx_mesh->face_groups.data = groups;
+ uc->obj.mesh->fbx_mesh->face_groups.count = num_groups;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_init(ufbxi_context *uc)
+{
+ uc->from_ascii = true;
+ uc->obj.initialized = true;
+
+
+ ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS_EXT; i++) {
+ uc->obj.tmp_vertices[i].ator = &uc->ator_tmp;
+ uc->obj.tmp_indices[i].ator = &uc->ator_tmp;
+ }
+ uc->obj.tmp_color_valid.ator = &uc->ator_tmp;
+ uc->obj.tmp_faces.ator = &uc->ator_tmp;
+ uc->obj.tmp_face_material.ator = &uc->ator_tmp;
+ uc->obj.tmp_face_smoothing.ator = &uc->ator_tmp;
+ uc->obj.tmp_face_group.ator = &uc->ator_tmp;
+ uc->obj.tmp_face_group_infos.ator = &uc->ator_tmp;
+ uc->obj.tmp_meshes.ator = &uc->ator_tmp;
+ uc->obj.tmp_props.ator = &uc->ator_tmp;
+
+ // .obj parsing does its own yield logic
+ uc->data_size += uc->yield_size;
+
+ uc->obj.object.data = ufbxi_empty_char;
+ uc->obj.group.data = ufbxi_empty_char;
+
+ ufbxi_map_init(&uc->obj.group_map, &uc->ator_tmp, ufbxi_map_cmp_const_char_ptr, NULL);
+
+ // Add a nameless root node with the root ID
+ {
+ ufbxi_element_info root_info = { uc->root_id };
+ root_info.name = ufbx_empty_string;
+ ufbx_node *root = ufbxi_push_element(uc, &root_info, ufbx_node, UFBX_ELEMENT_NODE);
+ ufbxi_check(root);
+ ufbxi_setup_root_node(uc, root);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline void ufbxi_obj_free(ufbxi_context *uc)
+{
+ if (!uc->obj.initialized) return;
+
+ ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS_EXT; i++) {
+ ufbxi_buf_free(&uc->obj.tmp_vertices[i]);
+ ufbxi_buf_free(&uc->obj.tmp_indices[i]);
+ }
+ ufbxi_buf_free(&uc->obj.tmp_color_valid);
+ ufbxi_buf_free(&uc->obj.tmp_faces);
+ ufbxi_buf_free(&uc->obj.tmp_face_material);
+ ufbxi_buf_free(&uc->obj.tmp_face_smoothing);
+ ufbxi_buf_free(&uc->obj.tmp_face_group);
+ ufbxi_buf_free(&uc->obj.tmp_face_group_infos);
+ ufbxi_buf_free(&uc->obj.tmp_meshes);
+ ufbxi_buf_free(&uc->obj.tmp_props);
+
+ ufbxi_map_free(&uc->obj.group_map);
+
+ ufbxi_free(&uc->ator_tmp, ufbx_string, uc->obj.tokens, uc->obj.tokens_cap);
+ ufbxi_free(&uc->ator_tmp, ufbx_material*, uc->obj.tmp_materials, uc->obj.tmp_materials_cap);
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_read_line(ufbxi_context *uc)
+{
+ ufbxi_dev_assert(!uc->obj.eof);
+
+ size_t offset = 0;
+
+ for (;;) {
+ const char *begin = ufbxi_add_ptr(uc->data, offset);
+ const char *end = begin ? (const char*)memchr(begin, '\n', uc->data_size - offset) : NULL;
+ if (!end) {
+ if (uc->eof) {
+ offset = uc->data_size;
+ uc->obj.eof = true;
+ break;
+ } else {
+ size_t new_cap = ufbxi_max_sz(1, uc->data_size * 2);
+ ufbxi_check(ufbxi_refill(uc, new_cap, false));
+ continue;
+ }
+ }
+
+ offset += ufbxi_to_size(end - begin) + 1;
+
+ // Handle line continuations
+ const char *esc = end;
+ if (esc > begin && esc[-1] == '\r') esc--;
+ if (esc > begin && esc[-1] == '\\') {
+ continue;
+ }
+
+ break;
+ }
+
+ size_t line_len = offset;
+
+ uc->obj.line.data = uc->data;
+ uc->obj.line.length = line_len;
+ uc->data += line_len;
+ uc->data_size -= line_len;
+
+ uc->obj.read_progress += line_len;
+ if (uc->obj.read_progress >= uc->progress_interval) {
+ ufbxi_check(ufbxi_report_progress(uc));
+ uc->obj.read_progress %= uc->progress_interval;
+ }
+
+ if (uc->obj.eof) {
+ char *new_data = ufbxi_push(&uc->tmp, char, line_len + 1);
+ ufbxi_check(new_data);
+ memcpy(new_data, uc->obj.line.data, line_len);
+ new_data[line_len] = '\n';
+ uc->obj.line.data = new_data;
+ uc->obj.line.length++;
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline ufbx_string ufbxi_obj_span_token(ufbxi_context *uc, size_t start_token, size_t end_token)
+{
+ ufbx_assert(start_token < uc->obj.num_tokens);
+ end_token = ufbxi_min_sz(end_token, uc->obj.num_tokens - 1);
+
+ ufbx_assert(start_token <= end_token);
+ ufbx_string start = uc->obj.tokens[start_token];
+ ufbx_string end = uc->obj.tokens[end_token];
+ size_t num_between = ufbxi_to_size(end.data - start.data);
+
+ ufbx_string result;
+ result.data = start.data;
+ result.length = num_between + end.length;
+ return result;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_tokenize(ufbxi_context *uc)
+{
+ const char *ptr = uc->obj.line.data, *end = ptr + uc->obj.line.length;
+ uc->obj.num_tokens = 0;
+
+ for (;;) {
+ char c;
+
+ // Skip whitespace
+ for (;;) {
+ c = *ptr;
+ if (c == ' ' || c == '\t' || c == '\r') {
+ ptr++;
+ continue;
+ }
+
+ // Treat line continuations as whitespace
+ if (c == '\\') {
+ const char *p = ptr + 1;
+ if (*p == '\r') p++;
+ if (*p == '\n' && p < end - 1) {
+ ptr = p + 1;
+ continue;
+ }
+ }
+
+ break;
+ }
+
+ c = *ptr;
+ if (c == '\n') break;
+ if (c == '#' && uc->obj.num_tokens > 0) break;
+
+ size_t index = uc->obj.num_tokens++;
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->obj.tokens, &uc->obj.tokens_cap, index + 1));
+
+ ufbx_string *tok = &uc->obj.tokens[index];
+ tok->data = ptr;
+
+ // Treat comment start as a single token
+ if (c == '#') {
+ ptr++;
+ tok->length = 1;
+ continue;
+ }
+
+ for (;;) {
+ c = *++ptr;
+
+ if (ufbxi_is_space(c)) {
+ break;
+ }
+
+ if (c == '\\') {
+ const char *p = ptr + 1;
+ if (*p == '\r') p++;
+ if (*p == '\n' && p < end - 1) {
+ break;
+ }
+ }
+ }
+
+ tok->length = ufbxi_to_size(ptr - tok->data);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_tokenize_line(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_obj_read_line(uc));
+ ufbxi_check(ufbxi_obj_tokenize(uc));
+ return 1;
+}
+
+static ufbxi_noinline int ufbxi_obj_parse_vertex(ufbxi_context *uc, ufbxi_obj_attrib attrib, size_t offset)
+{
+ if (uc->opts.ignore_geometry) return 1;
+
+ ufbxi_buf *dst = &uc->obj.tmp_vertices[attrib];
+ size_t num_values = ufbxi_obj_attrib_stride[attrib];
+ uc->obj.vertex_count[attrib]++;
+
+ size_t read_values = num_values;
+ if (attrib == UFBXI_OBJ_ATTRIB_COLOR) {
+ if (offset + read_values > uc->obj.num_tokens) {
+ read_values = 3;
+ }
+ }
+ ufbxi_check(offset + read_values <= uc->obj.num_tokens);
+
+ uint32_t parse_flags = uc->double_parse_flags;
+ ufbx_real *vals = ufbxi_push_fast(dst, ufbx_real, num_values);
+ ufbxi_check(vals);
+ for (size_t i = 0; i < read_values; i++) {
+ ufbx_string str = uc->obj.tokens[offset + i];
+ char *end; // ufbxi_uninit
+ double val = ufbxi_parse_double(str.data, str.length, &end, parse_flags);
+ ufbxi_check(end == str.data + str.length);
+ vals[i] = (ufbx_real)val;
+ }
+
+ if (read_values < num_values) {
+ ufbx_assert(read_values + 1 == num_values);
+ ufbx_assert(attrib == UFBXI_OBJ_ATTRIB_COLOR);
+ vals[read_values] = 1.0f;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_index(ufbxi_context *uc, ufbx_string *s, uint32_t attrib)
+{
+ const char *ptr = s->data, *end = ptr + s->length;
+
+ bool negative = false;
+ if (*ptr == '-') {
+ negative = true;
+ ptr++;
+ }
+
+ // As .obj indices are never zero we can detect missing indices
+ // by simply not writing to it.
+ uint64_t index = 0;
+ for (; ptr != end; ptr++) {
+ char c = *ptr;
+ if (c >= '0' && c <= '9') {
+ ufbxi_check(index < UINT64_MAX / 10 - 10);
+ index = index * 10 + (uint64_t)(c - '0');
+ } else if (c == '/') {
+ ptr++;
+ break;
+ }
+ }
+
+ if (negative) {
+ size_t count = uc->obj.vertex_count[attrib];
+ index = index <= count ? count - index : UINT64_MAX;
+ } else {
+ // Corrects to zero based indices and wraps 0 to UINT64_MAX (missing)
+ index -= 1;
+ }
+
+ ufbxi_obj_fast_indices *fast_indices = &uc->obj.fast_indices[attrib];
+ if (fast_indices->num_left == 0) {
+ size_t num_push = 128;
+ uint64_t *dst = ufbxi_push(&uc->obj.tmp_indices[attrib], uint64_t, num_push);
+ ufbxi_check(dst);
+ uc->obj.fast_indices[attrib].indices = dst;
+ uc->obj.fast_indices[attrib].num_left = num_push;
+ }
+
+ *fast_indices->indices++ = index;
+ fast_indices->num_left--;
+
+ ufbxi_obj_mesh *mesh = uc->obj.mesh;
+
+ if (index != UINT64_MAX) {
+ ufbxi_obj_index_range *range = &mesh->vertex_range[attrib];
+ range->min_ix = ufbxi_min64(range->min_ix, index);
+ range->max_ix = ufbxi_max64(range->max_ix, index);
+ }
+
+ s->data = ptr;
+ s->length = ufbxi_to_size(end - ptr);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_indices(ufbxi_context *uc, size_t token_begin, size_t num_tokens)
+{
+ bool flush_mesh = false;
+ if (uc->obj.object_dirty) {
+ if (!uc->opts.obj_merge_objects) {
+ flush_mesh = true;
+ }
+ uc->obj.object_dirty = false;
+ }
+
+ if (uc->obj.group_dirty) {
+ if (((uc->obj.object.length == 0 || uc->opts.obj_merge_objects) && !uc->opts.obj_merge_groups) || uc->opts.obj_split_groups) {
+ flush_mesh = true;
+ }
+ uc->obj.group_dirty = false;
+ uc->obj.face_group_dirty = true;
+ }
+
+ if (!uc->obj.mesh || flush_mesh) {
+ ufbxi_check(ufbxi_obj_flush_mesh(uc));
+ ufbxi_check(ufbxi_obj_push_mesh(uc));
+ }
+ ufbxi_obj_mesh *mesh = uc->obj.mesh;
+
+ if (uc->obj.material_dirty) {
+ if (uc->obj.usemtl_fbx_id != 0) {
+ ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, uc->obj.usemtl_fbx_id);
+ ufbx_assert(entry);
+ if (mesh->usemtl_base == 0 || entry->user_id < mesh->usemtl_base) {
+ ufbxi_check(ufbxi_connect_oo(uc, uc->obj.usemtl_fbx_id, mesh->fbx_node_id));
+
+ uint32_t index = ++uc->obj.usemtl_index;
+ ufbxi_check(index < UINT32_MAX);
+ entry->user_id = index;
+
+ if (mesh->usemtl_base == 0) {
+ mesh->usemtl_base = index;
+ }
+ uc->obj.face_material = index - mesh->usemtl_base;
+ }
+ uc->obj.face_material = entry->user_id - mesh->usemtl_base;
+ } else {
+ uc->obj.face_material = UFBX_NO_INDEX;
+ }
+ }
+
+ // EARLY RETURN: Rest of the function should only be related to geometry!
+ if (uc->opts.ignore_geometry) return 1;
+
+ if (num_tokens == 0 && !uc->opts.allow_empty_faces) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_EMPTY_FACE_REMOVED, "Empty face has been removed"));
+ return 1;
+ }
+
+ if (uc->obj.face_group_dirty) {
+ ufbx_string name = ufbx_empty_string;
+ if (uc->obj.group.length > 0 && (uc->obj.object.length > 0 || uc->opts.obj_merge_groups) && !uc->opts.obj_split_groups) {
+ name = uc->obj.group;
+ }
+
+ uint32_t hash = ufbxi_hash_ptr(name.data);
+ ufbxi_obj_group_entry *entry = ufbxi_map_find(&uc->obj.group_map, ufbxi_obj_group_entry, hash, &name.data);
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->obj.group_map, ufbxi_obj_group_entry, hash, &name.data);
+ ufbxi_check(entry);
+ entry->name = name.data;
+ entry->mesh_id = 0;
+ entry->local_id = 0;
+ }
+
+ uint32_t mesh_id = mesh->fbx_mesh->element_id;
+ if (entry->mesh_id != mesh_id) {
+ uint32_t id = mesh->num_groups++;
+ entry->mesh_id = mesh_id;
+ entry->local_id = id;
+
+ ufbx_face_group *group = ufbxi_push_zero(&uc->obj.tmp_face_group_infos, ufbx_face_group, 1);
+ ufbxi_check(group);
+ group->id = 0;
+ group->name = name;
+ }
+
+ uc->obj.face_group = entry->local_id;
+
+ if (!uc->obj.has_face_group) {
+ uc->obj.has_face_group = true;
+ ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_face_group, uint32_t, uc->obj.tmp_faces.num_items));
+ }
+
+ uc->obj.face_group_dirty = false;
+ }
+
+ size_t num_indices = num_tokens;
+ ufbxi_check(UINT32_MAX - mesh->num_indices >= num_indices);
+
+ ufbx_face *face = ufbxi_push_fast(&uc->obj.tmp_faces, ufbx_face, 1);
+ ufbxi_check(face);
+
+ face->index_begin = (uint32_t)mesh->num_indices;
+ face->num_indices = (uint32_t)num_indices;
+
+ mesh->num_faces++;
+ mesh->num_indices += num_indices;
+
+ uint32_t *p_face_mat = ufbxi_push_fast(&uc->obj.tmp_face_material, uint32_t, 1);
+ ufbxi_check(p_face_mat);
+ *p_face_mat = uc->obj.face_material;
+
+ if (uc->obj.has_face_smoothing) {
+ bool *p_face_smooth = ufbxi_push_fast(&uc->obj.tmp_face_smoothing, bool, 1);
+ ufbxi_check(p_face_smooth);
+ *p_face_smooth = uc->obj.face_smoothing;
+ }
+
+ if (uc->obj.has_face_group) {
+ uint32_t *p_face_group = ufbxi_push_fast(&uc->obj.tmp_face_group, uint32_t, 1);
+ ufbxi_check(p_face_group);
+ *p_face_group = uc->obj.face_group;
+ }
+
+ for (size_t ix = 0; ix < num_indices; ix++) {
+ ufbx_string tok = uc->obj.tokens[token_begin + ix];
+ for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
+ ufbxi_check(ufbxi_obj_parse_index(uc, &tok, attrib));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_multi_indices(ufbxi_context *uc, size_t window)
+{
+ for (size_t begin = 1; begin + window <= uc->obj.num_tokens; begin++) {
+ ufbxi_check(ufbxi_obj_parse_indices(uc, begin, window));
+ }
+ return 1;
+}
+
+static ufbxi_noinline uint32_t ufbxi_parse_hex(const char *digits, size_t length)
+{
+ uint32_t value = 0;
+
+ for (size_t i = 0; i < length; i++) {
+ char c = digits[i];
+ uint32_t v = 0;
+ if (c >= '0' && c <= '9') {
+ v = (uint32_t)(c - '0');
+ } else if (c >= 'A' && c <= 'F') {
+ v = (uint32_t)(c - 'A') + 10;
+ } else if (c >= 'a' && c <= 'f') {
+ v = (uint32_t)(c - 'a') + 10;
+ }
+ value = (value << 4) | v;
+ }
+
+ return value;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_comment(ufbxi_context *uc)
+{
+ if (uc->obj.num_tokens >= 3 && ufbxi_str_equal(uc->obj.tokens[1], ufbxi_str_c("MRGB"))) {
+ size_t num_color = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR];
+
+ // Pop standard vertex colors and replace them with MRGB colors
+ if (num_color > uc->obj.mrgb_vertex_count) {
+ size_t num_pop = num_color - uc->obj.mrgb_vertex_count;
+ ufbxi_pop(&uc->obj.tmp_color_valid, bool, num_pop, NULL);
+ ufbxi_pop(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, num_pop * 4, NULL);
+ uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] -= num_pop;
+ }
+
+ ufbx_string mrgb = uc->obj.tokens[2];
+ for (size_t i = 0; i + 8 <= mrgb.length; i += 8) {
+ ufbx_real *p_rgba = ufbxi_push(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, 4);
+ bool *p_valid = ufbxi_push(&uc->obj.tmp_color_valid, bool, 1);
+ ufbxi_check(p_rgba && p_valid);
+ *p_valid = true;
+
+ uint32_t hex = ufbxi_parse_hex(mrgb.data + i, 8);
+ p_rgba[0] = (ufbx_real)((hex >> 16u) & 0xff) / 255.0f;
+ p_rgba[1] = (ufbx_real)((hex >> 8u) & 0xff) / 255.0f;
+ p_rgba[2] = (ufbx_real)((hex >> 0u) & 0xff) / 255.0f;
+ p_rgba[3] = (ufbx_real)((hex >> 24u) & 0xff) / 255.0f;
+ }
+
+ uc->obj.has_vertex_color = true;
+ }
+
+ if (!uc->opts.disable_quirks) {
+ if (ufbxi_match(&uc->obj.line, "\\s*#\\s*File exported by ZBrush.*")) {
+ if (!uc->obj.mesh) {
+ uc->opts.obj_merge_groups = true;
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_material(ufbxi_context *uc)
+{
+ uc->obj.material_dirty = true;
+
+ // Allow empty `usemtl` lines to specify "no material".
+ if (uc->obj.num_tokens < 2) {
+ uc->obj.usemtl_fbx_id = 0;
+ return 1;
+ }
+
+ ufbx_string name = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &name, false));
+
+ uint64_t fbx_id = ufbxi_synthetic_id_from_string(uc, name.data);
+ ufbxi_check(fbx_id);
+
+ ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, fbx_id);
+
+ uc->obj.usemtl_fbx_id = fbx_id;
+
+ if (!entry) {
+ ufbxi_element_info info = { 0 };
+ info.fbx_id = fbx_id;
+ info.name = name;
+
+ ufbx_material *material = ufbxi_push_element(uc, &info, ufbx_material, UFBX_ELEMENT_MATERIAL);
+ ufbxi_check(material);
+
+ material->shader_type = UFBX_SHADER_WAVEFRONT_MTL;
+ material->shading_model_name.data = ufbxi_empty_char;
+ material->shader_prop_prefix.data = ufbxi_empty_char;
+
+ size_t id = material->element_id;
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->obj.tmp_materials, &uc->obj.tmp_materials_cap, id + 1));
+ uc->obj.tmp_materials[id] = material;
+ }
+
+ return 1;
+}
+
+#define ufbxi_obj_cmd1(a) ((uint32_t)(a)<<24u)
+#define ufbxi_obj_cmd2(a,b) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16)
+#define ufbxi_obj_cmd3(a,b,c) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16 | (uint32_t)(c)<<8u)
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_vertices(ufbxi_context *uc, ufbx_real_list *dst, uint32_t attrib, uint64_t min_index)
+{
+ size_t stride = ufbxi_obj_attrib_stride[attrib];
+ ufbxi_check(min_index < uc->obj.tmp_vertices[attrib].num_items / stride);
+
+ size_t count = uc->obj.tmp_vertices[attrib].num_items - (size_t)min_index * stride;
+ ufbx_real *data = ufbxi_push(&uc->result, ufbx_real, count + 4);
+ ufbxi_check(data);
+
+ data[0] = 0.0f;
+ data[1] = 0.0f;
+ data[2] = 0.0f;
+ data[3] = 0.0f;
+ data += 4;
+
+ ufbxi_pop(&uc->obj.tmp_vertices[attrib], ufbx_real, count, data);
+
+ dst->data = data;
+ dst->count = count;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_setup_attrib(ufbxi_context *uc, ufbxi_obj_mesh *mesh, uint64_t *tmp_indices,
+ ufbx_vertex_attrib *dst, const ufbx_real_list *p_data, uint32_t attrib, bool non_disjoint, bool required)
+{
+ ufbx_real_list data = *p_data;
+
+ size_t num_indices = mesh->num_indices;
+ size_t stride = ufbxi_obj_attrib_stride[attrib];
+ size_t num_values = data.count / stride;
+
+ uint64_t mesh_min_ix = mesh->vertex_range[attrib].min_ix;
+ if (num_indices == 0 || num_values == 0 || mesh_min_ix == UINT64_MAX) {
+ ufbxi_check(num_indices == 0 || !required);
+
+ // Pop indices without copying if the attribute is not used
+ ufbxi_pop(&uc->obj.tmp_indices[attrib], uint64_t, num_indices, NULL);
+ return 1;
+ }
+
+ uint64_t min_index = non_disjoint ? 0 : mesh_min_ix;
+
+ ufbxi_pop(&uc->obj.tmp_indices[attrib], uint64_t, num_indices, tmp_indices);
+
+ uint32_t *dst_indices = ufbxi_push(&uc->result, uint32_t, num_indices);
+ ufbxi_check(dst_indices);
+
+ dst->exists = true;
+
+ dst->values.data = data.data;
+ dst->values.count = num_values;
+
+ dst->indices.data = dst_indices;
+ dst->indices.count = num_indices;
+
+ ufbxi_nounroll for (size_t i = 0; i < num_indices; i++) {
+ uint64_t ix = tmp_indices[i];
+ if (ix != UINT64_MAX) {
+ ix -= min_index;
+ ufbxi_check(ix < UINT32_MAX);
+ }
+ if (ix < num_values) {
+ dst_indices[i] = (uint32_t)ix;
+ } else {
+ ufbxi_check(ufbxi_fix_index(uc, &dst_indices[i], (uint32_t)ix, num_values));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pad_colors(ufbxi_context *uc, size_t num_vertices)
+{
+ if (uc->opts.ignore_geometry) return 1;
+
+ size_t num_colors = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR];
+ if (num_vertices > num_colors) {
+ size_t num_pad = num_vertices - num_colors;
+ ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, num_pad * 4));
+ ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_color_valid, bool, num_pad));
+ uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] += num_pad;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_meshes(ufbxi_context *uc)
+{
+ size_t num_meshes = uc->obj.tmp_meshes.num_items;
+ ufbxi_obj_mesh *meshes = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_meshes, ufbxi_obj_mesh, num_meshes);
+ ufbxi_check(meshes);
+
+ if (uc->obj.has_vertex_color) {
+ ufbxi_check(ufbxi_obj_pad_colors(uc, uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_POSITION]));
+ }
+
+ // Pop unused fast indices
+ for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS; i++) {
+ ufbxi_pop(&uc->obj.tmp_indices[i], uint64_t, uc->obj.fast_indices[i].num_left, NULL);
+ }
+
+ // Check if the file has disjoint vertices
+ bool non_disjoint[UFBXI_OBJ_NUM_ATTRIBS] = { 0 };
+ uint64_t next_min[UFBXI_OBJ_NUM_ATTRIBS] = { 0 };
+ ufbx_real_list vertices[UFBXI_OBJ_NUM_ATTRIBS_EXT] = { 0 };
+ bool *color_valid = NULL;
+
+ size_t max_indices = 0;
+
+ for (size_t i = 0; i < num_meshes; i++) {
+ ufbxi_obj_mesh *mesh = &meshes[i];
+ max_indices = ufbxi_max_sz(max_indices, mesh->num_indices);
+ ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
+ ufbxi_obj_index_range range = mesh->vertex_range[attrib];
+ if (range.min_ix > range.max_ix) continue;
+ if (range.min_ix < next_min[attrib]) {
+ non_disjoint[attrib] = true;
+ }
+ next_min[attrib] = range.max_ix + 1;
+ }
+ }
+
+ uint64_t *tmp_indices = ufbxi_push(&uc->tmp, uint64_t, max_indices);
+ ufbxi_check(tmp_indices);
+
+ ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
+ if (!non_disjoint[attrib]) continue;
+ ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[attrib], attrib, 0));
+ }
+ if (uc->obj.has_vertex_color && non_disjoint[UFBXI_OBJ_ATTRIB_POSITION]) {
+ ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[UFBXI_OBJ_ATTRIB_COLOR], UFBXI_OBJ_ATTRIB_COLOR, 0));
+ color_valid = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_color_valid, bool, vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4);
+ ufbxi_check(color_valid);
+ }
+
+ for (size_t i = num_meshes; i > 0; i--) {
+ ufbxi_obj_mesh *mesh = &meshes[i - 1];
+
+ ufbx_mesh *fbx_mesh = mesh->fbx_mesh;
+
+ size_t num_faces = mesh->num_faces;
+
+ if (!uc->opts.ignore_geometry) {
+ ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
+ if (non_disjoint[attrib]) continue;
+ uint64_t min_ix = mesh->vertex_range[attrib].min_ix;
+ if (min_ix < UINT64_MAX) {
+ ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[attrib], attrib, min_ix));
+ }
+ }
+ if (uc->obj.has_vertex_color && !non_disjoint[UFBXI_OBJ_ATTRIB_POSITION]) {
+ uint64_t min_ix = mesh->vertex_range[UFBXI_OBJ_ATTRIB_POSITION].min_ix;
+ ufbxi_check(min_ix < UINT64_MAX);
+ ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[UFBXI_OBJ_ATTRIB_COLOR], UFBXI_OBJ_ATTRIB_COLOR, min_ix));
+ color_valid = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_color_valid, bool, vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4);
+ ufbxi_check(color_valid);
+ }
+
+ fbx_mesh->faces.count = num_faces;
+ fbx_mesh->face_material.count = num_faces;
+
+ fbx_mesh->faces.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_faces, ufbx_face, num_faces);
+ fbx_mesh->face_material.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_material, uint32_t, num_faces);
+
+ ufbxi_check(fbx_mesh->faces.data);
+ ufbxi_check(fbx_mesh->face_material.data);
+
+ if (uc->obj.has_face_smoothing) {
+ fbx_mesh->face_smoothing.count = num_faces;
+ fbx_mesh->face_smoothing.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_smoothing, bool, num_faces);
+ ufbxi_check(fbx_mesh->face_smoothing.data);
+ }
+
+ if (uc->obj.has_face_group) {
+ if (mesh->num_groups > 1) {
+ fbx_mesh->face_group.count = num_faces;
+ fbx_mesh->face_group.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_group, uint32_t, num_faces);
+ ufbxi_check(fbx_mesh->face_group.data);
+ } else {
+ ufbxi_pop(&uc->obj.tmp_face_group, uint32_t, num_faces, NULL);
+ }
+ }
+
+ ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_position,
+ &vertices[UFBXI_OBJ_ATTRIB_POSITION], UFBXI_OBJ_ATTRIB_POSITION, non_disjoint[UFBXI_OBJ_ATTRIB_POSITION], true));
+
+ ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_uv,
+ &vertices[UFBXI_OBJ_ATTRIB_UV], UFBXI_OBJ_ATTRIB_UV, non_disjoint[UFBXI_OBJ_ATTRIB_UV], false));
+
+ ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_normal,
+ &vertices[UFBXI_OBJ_ATTRIB_NORMAL], UFBXI_OBJ_ATTRIB_NORMAL, non_disjoint[UFBXI_OBJ_ATTRIB_NORMAL], false));
+
+ if (uc->obj.has_vertex_color) {
+ ufbx_assert(color_valid);
+ bool has_color = false;
+ bool all_valid = true;
+ size_t max_index = fbx_mesh->vertex_position.values.count;
+ ufbxi_for_list(uint32_t, p_ix, fbx_mesh->vertex_position.indices) {
+ if (*p_ix < max_index) {
+ if (color_valid[*p_ix]) {
+ has_color = true;
+ } else {
+ all_valid = false;
+ }
+ }
+ }
+
+ if (has_color) {
+ fbx_mesh->vertex_color.exists = true;
+ fbx_mesh->vertex_color.values.data = (ufbx_vec4*)vertices[UFBXI_OBJ_ATTRIB_COLOR].data;
+ fbx_mesh->vertex_color.values.count = vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4;
+ fbx_mesh->vertex_color.indices = fbx_mesh->vertex_position.indices;
+ fbx_mesh->vertex_color.unique_per_vertex = true;
+
+ if (!all_valid) {
+ uint32_t *indices = fbx_mesh->vertex_color.indices.data;
+ indices = ufbxi_push_copy(&uc->result, uint32_t, mesh->num_indices, indices);
+ ufbxi_check(indices);
+
+ size_t num_values = fbx_mesh->vertex_color.values.count;
+ ufbxi_for(uint32_t, p_ix, indices, mesh->num_indices) {
+ if (*p_ix >= num_values || !color_valid[*p_ix]) {
+ ufbxi_check(ufbxi_fix_index(uc, p_ix, *p_ix, num_values));
+ }
+ }
+
+ fbx_mesh->vertex_color.indices.data = indices;
+ }
+ }
+ }
+ }
+
+ ufbxi_check(ufbxi_finalize_mesh(&uc->result, &uc->error, fbx_mesh));
+
+ if (uc->retain_mesh_parts) {
+ fbx_mesh->face_group_parts.count = mesh->num_groups;
+ fbx_mesh->face_group_parts.data = ufbxi_push_zero(&uc->result, ufbx_mesh_part, mesh->num_groups);
+ ufbxi_check(fbx_mesh->face_group_parts.data);
+ }
+
+ if (mesh->num_groups > 1) {
+ ufbxi_check(ufbxi_update_face_groups(&uc->result, &uc->error, fbx_mesh, false));
+ } else if (mesh->num_groups == 1) {
+ fbx_mesh->face_group.data = (uint32_t*)ufbxi_sentinel_index_zero;
+ fbx_mesh->face_group.count = num_faces;
+ // NOTE: Consecutive and zero indices are always allocated so we can skip doing it here,
+ // see HACK(consecutiv-faces)..
+ if (fbx_mesh->face_group_parts.count > 0) {
+ ufbx_mesh_part *part = &fbx_mesh->face_group_parts.data[0];
+ part->num_faces = fbx_mesh->num_faces;
+ part->num_faces = num_faces;
+ part->num_empty_faces = fbx_mesh->num_empty_faces;
+ part->num_point_faces = fbx_mesh->num_point_faces;
+ part->num_line_faces = fbx_mesh->num_line_faces;
+ part->num_triangles = fbx_mesh->num_triangles;
+ part->face_indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
+ part->face_indices.count = num_faces;
+ }
+ }
+
+ // HACK(consecutive-faces): Prepare for finalize to re-use a consecutive/zero
+ // index buffer for face materials..
+ uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, num_faces);
+ uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, num_faces);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_file(ufbxi_context *uc)
+{
+ while (!uc->obj.eof) {
+ ufbxi_check(ufbxi_obj_tokenize_line(uc));
+ size_t num_tokens = uc->obj.num_tokens;
+ if (num_tokens == 0) continue;
+
+ ufbx_string cmd = uc->obj.tokens[0];
+ uint32_t key = ufbxi_get_name_key(cmd.data, cmd.length);
+ if (key == ufbxi_obj_cmd1('v')) {
+ ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_POSITION, 1));
+ if (num_tokens >= 7) {
+ size_t num_vertices = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_POSITION];
+ uc->obj.has_vertex_color = true;
+ ufbxi_check(ufbxi_obj_pad_colors(uc, num_vertices - 1));
+ if (uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] < num_vertices) {
+ ufbx_assert(uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] == num_vertices - 1);
+ ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_COLOR, 4));
+ bool *valid = ufbxi_push(&uc->obj.tmp_color_valid, bool, 1);
+ ufbxi_check(valid);
+ *valid = true;
+ }
+ }
+ } else if (key == ufbxi_obj_cmd2('v','t')) {
+ ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_UV, 1));
+ } else if (key == ufbxi_obj_cmd2('v','n')) {
+ ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_NORMAL, 1));
+ } else if (key == ufbxi_obj_cmd1('f')) {
+ ufbxi_check(ufbxi_obj_parse_indices(uc, 1, uc->obj.num_tokens - 1));
+ } else if (key == ufbxi_obj_cmd1('p')) {
+ ufbxi_check(ufbxi_obj_parse_multi_indices(uc, 1));
+ } else if (key == ufbxi_obj_cmd1('l')) {
+ ufbxi_check(ufbxi_obj_parse_multi_indices(uc, 2));
+ } else if (key == ufbxi_obj_cmd1('s')) {
+ if (num_tokens >= 2) {
+ uc->obj.has_face_smoothing = true;
+ uc->obj.face_smoothing = !ufbxi_str_equal(uc->obj.tokens[1], ufbxi_str_c("off"));
+
+ // Fill in previously missed face smoothing data
+ if (uc->obj.tmp_face_smoothing.num_items == 0 && uc->obj.tmp_faces.num_items > 0) {
+ ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_face_smoothing, bool, uc->obj.tmp_faces.num_items));
+ }
+ }
+ } else if (key == ufbxi_obj_cmd1('o')) {
+ if (num_tokens >= 2) {
+ uc->obj.object = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->obj.object, false));
+ uc->obj.object_dirty = true;
+ }
+ } else if (key == ufbxi_obj_cmd1('g')) {
+ if (num_tokens >= 2) {
+ uc->obj.group = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->obj.group, false));
+ uc->obj.group_dirty = true;
+ } else {
+ uc->obj.group = ufbx_empty_string;
+ uc->obj.group_dirty = true;
+ }
+ } else if (key == ufbxi_obj_cmd1('#')) {
+ ufbxi_check(ufbxi_obj_parse_comment(uc));
+ } else if (ufbxi_str_equal(cmd, ufbxi_str_c("mtllib"))) {
+ ufbxi_check(uc->obj.num_tokens >= 2);
+ ufbx_string lib = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
+ lib.data = ufbxi_push_copy(&uc->tmp, char, lib.length + 1, lib.data);
+ ufbxi_check(lib.data);
+ uc->obj.mtllib_relative_path.data = lib.data;
+ uc->obj.mtllib_relative_path.size = lib.length;
+ } else if (ufbxi_str_equal(cmd, ufbxi_str_c("usemtl"))) {
+ ufbxi_check(ufbxi_obj_parse_material(uc));
+ } else if (!uc->opts.disable_quirks && key == 0) {
+ // ZBrush exporter seems to end the files with '\0', sometimes..
+ } else {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_UNKNOWN_OBJ_DIRECTIVE, "Unknown .obj directive, skipped line"));
+ }
+ }
+
+ ufbxi_check(ufbxi_obj_flush_mesh(uc));
+ ufbxi_check(ufbxi_obj_pop_meshes(uc));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_flush_material(ufbxi_context *uc)
+{
+ if (uc->obj.usemtl_fbx_id == 0) return 1;
+
+ ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, uc->obj.usemtl_fbx_id);
+ ufbx_assert(entry);
+ ufbx_material *material = uc->obj.tmp_materials[entry->element_id];
+
+ size_t num_props = uc->obj.tmp_props.num_items;
+ ufbxi_check(ufbxi_obj_pop_props(uc, &material->props.props, num_props));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_prop(ufbxi_context *uc, ufbx_string name, size_t start, bool include_rest, size_t *p_next)
+{
+ if (start >= uc->obj.num_tokens) {
+ if (p_next) {
+ *p_next = start;
+ }
+ return 1;
+ }
+
+ ufbx_prop *prop = ufbxi_push_zero(&uc->obj.tmp_props, ufbx_prop, 1);
+ ufbxi_check(prop);
+ prop->name = name;
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop->name, false));
+
+ uint32_t flags = UFBX_PROP_FLAG_VALUE_STR;
+
+ size_t num_reals = 0;
+ for (; num_reals < 4; num_reals++) {
+ if (start + num_reals >= uc->obj.num_tokens) break;
+ ufbx_string tok = uc->obj.tokens[start + num_reals];
+
+ char *end; // ufbxi_uninit
+ double val = ufbxi_parse_double(tok.data, tok.length, &end, uc->double_parse_flags);
+ if (end != tok.data + tok.length) break;
+
+ prop->value_real_arr[num_reals] = (ufbx_real)val;
+ if (num_reals == 0) {
+ prop->value_int = ufbxi_f64_to_i64(val);
+ flags |= UFBX_PROP_FLAG_VALUE_INT;
+ }
+ }
+
+ size_t num_args = 0;
+ if (!include_rest) {
+ for (; start + num_args < uc->obj.num_tokens - 1; num_args++) {
+ if (ufbxi_match(&uc->obj.tokens[start + num_args], "-[A-Za-z][\\-A-Za-z0-9_]*")) break;
+ }
+ }
+
+ if (num_args > 0 || include_rest) {
+ ufbx_string span = ufbxi_obj_span_token(uc, start, include_rest ? SIZE_MAX : start + num_args - 1);
+ prop->value_str = span;
+ prop->value_blob.data = span.data;
+ prop->value_blob.size = span.length;
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop->value_str, false));
+ ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &prop->value_blob, true));
+ } else {
+ prop->value_str.data = ufbxi_empty_char;
+ }
+
+ if (num_reals > 0) {
+ flags = (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << (num_reals - 1);
+ } else {
+ if (!strcmp(prop->value_str.data, "on")) {
+ prop->value_int = 1;
+ prop->value_real = 1.0f;
+ flags |= UFBX_PROP_FLAG_VALUE_INT;
+ } else if (!strcmp(prop->value_str.data, "off")) {
+ prop->value_int = 0;
+ prop->value_real = 0.0f;
+ flags |= UFBX_PROP_FLAG_VALUE_INT;
+ }
+ }
+
+ prop->flags = (ufbx_prop_flags)flags;
+
+ if (p_next) {
+ *p_next = start + num_args;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_mtl_map(ufbxi_context *uc, size_t prefix_len)
+{
+ if (uc->obj.num_tokens < 2) return 1;
+
+ size_t num_props = 1;
+ ufbxi_check(ufbxi_obj_parse_prop(uc, ufbxi_str_c("obj|args"), 1, true, NULL));
+
+ size_t start = 1;
+ for (; start + 1 < uc->obj.num_tokens; ) {
+ ufbx_string tok = uc->obj.tokens[start];
+ if (ufbxi_match(&tok, "-[A-Za-z][\\-A-Za-z0-9_]*")) {
+ tok.data += 1;
+ tok.length -= 1;
+ ufbxi_check(ufbxi_obj_parse_prop(uc, tok, start + 1, false, &start));
+ num_props++;
+ } else {
+ break;
+ }
+ }
+
+ ufbx_string tex_str = ufbxi_obj_span_token(uc, start, SIZE_MAX);
+ ufbx_blob tex_raw = { tex_str.data, tex_str.length };
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &tex_str, false));
+ ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &tex_raw, true));
+
+ uint64_t fbx_id = 0;
+ ufbx_texture *texture = ufbxi_push_synthetic_element(uc, &fbx_id, NULL, "", ufbx_texture, UFBX_ELEMENT_TEXTURE);
+ ufbxi_check(texture);
+
+ texture->filename.data = ufbxi_empty_char;
+ texture->absolute_filename.data = ufbxi_empty_char;
+ texture->uv_set.data = ufbxi_empty_char;
+
+ texture->relative_filename = tex_str;
+ texture->raw_relative_filename = tex_raw;
+
+ ufbxi_check(ufbxi_obj_pop_props(uc, &texture->props.props, num_props));
+
+ ufbx_string prop = uc->obj.tokens[0];
+ ufbx_assert(prop.length >= prefix_len);
+ prop.data += prefix_len;
+ prop.length -= prefix_len;
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop, false));
+
+ if (uc->obj.usemtl_fbx_id != 0) {
+ ufbxi_check(ufbxi_connect_op(uc, fbx_id, uc->obj.usemtl_fbx_id, prop));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_mtl(ufbxi_context *uc)
+{
+ uc->obj.mesh = NULL;
+ uc->obj.usemtl_fbx_id = 0;
+
+ while (!uc->obj.eof) {
+ ufbxi_check(ufbxi_obj_tokenize_line(uc));
+ size_t num_tokens = uc->obj.num_tokens;
+ if (num_tokens == 0) continue;
+
+ ufbx_string cmd = uc->obj.tokens[0];
+ if (ufbxi_str_equal(cmd, ufbxi_str_c("newmtl"))) {
+ // HACK: Reuse mesh material parsing, but don't allow for empty material name
+ ufbxi_check(uc->obj.num_tokens >= 2);
+ ufbxi_check(ufbxi_obj_flush_material(uc));
+ ufbxi_check(ufbxi_obj_parse_material(uc));
+ } else if (cmd.length > 4 && !memcmp(cmd.data, "map_", 4)) {
+ ufbxi_check(ufbxi_obj_parse_mtl_map(uc, 4));
+ } else if (cmd.length == 4 && (!memcmp(cmd.data, "bump", 4) || !memcmp(cmd.data, "disp", 4) || !memcmp(cmd.data, "norm", 4))) {
+ ufbxi_check(ufbxi_obj_parse_mtl_map(uc, 0));
+ } else if (cmd.length == 1 && cmd.data[0] == '#') {
+ // Implement .mtl magic comment handling here if necessary
+ } else {
+ ufbxi_check(ufbxi_obj_parse_prop(uc, uc->obj.tokens[0], 1, true, NULL));
+ }
+ }
+
+ ufbxi_check(ufbxi_obj_flush_material(uc));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_load_mtl(ufbxi_context *uc)
+{
+ // HACK: Reset everything and switch to loading the .mtl file globally
+ if (uc->close_fn) {
+ uc->close_fn(uc->read_user);
+ }
+
+ uc->read_fn = NULL;
+ uc->close_fn = NULL;
+ uc->read_user = NULL;
+ uc->data_begin = NULL;
+ uc->data = NULL;
+ uc->data_size = 0;
+ uc->yield_size = 0;
+ uc->eof = false;
+ uc->obj.eof = false;
+
+ if (uc->opts.obj_mtl_data.size > 0) {
+ uc->data_begin = uc->data = (const char*)uc->opts.obj_mtl_data.data;
+ uc->data_size = uc->opts.obj_mtl_data.size;
+ ufbxi_check(ufbxi_obj_parse_mtl(uc));
+ return 1;
+ }
+
+ ufbx_stream stream = { 0 };
+ bool has_stream = false;
+ bool needs_stream = false;
+ ufbx_blob stream_path = { 0 };
+
+ if (uc->opts.open_file_cb.fn) {
+ if (uc->opts.obj_mtl_path.length > 0) {
+ has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, uc->opts.obj_mtl_path.data, uc->opts.obj_mtl_path.length, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
+ stream_path.data = uc->opts.obj_mtl_path.data;
+ stream_path.size = uc->opts.obj_mtl_path.length;
+ needs_stream = true;
+ if (!has_stream) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Could not open .mtl file: %s", uc->opts.obj_mtl_path.data));
+ }
+ }
+
+ if (!has_stream && uc->opts.load_external_files && uc->obj.mtllib_relative_path.size > 0) {
+ ufbx_blob dst; // ufbxi_uninit
+ ufbxi_check(ufbxi_resolve_relative_filename(uc, (ufbxi_strblob*)&dst, (const ufbxi_strblob*)&uc->obj.mtllib_relative_path, true));
+ has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, (const char*)dst.data, dst.size, &uc->obj.mtllib_relative_path, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
+ stream_path = uc->obj.mtllib_relative_path;
+ needs_stream = true;
+ if (!has_stream) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Could not open .mtl file: %s", dst.data));
+ }
+ }
+
+ ufbx_string path = uc->scene.metadata.filename;
+ if (!has_stream && uc->opts.load_external_files && uc->opts.obj_search_mtl_by_filename && path.length > 4) {
+ ufbx_string ext = { path.data + path.length - 4, 4 };
+ if (ufbxi_match(&ext, "\\c.obj")) {
+ ufbxi_analysis_assert(path.length < SIZE_MAX - 1);
+ char *copy = ufbxi_push_copy(&uc->tmp, char, path.length + 1, path.data);
+ ufbxi_check(copy);
+ copy[path.length - 3] = copy[path.length - 3] == 'O' ? 'M' : 'm';
+ copy[path.length - 2] = copy[path.length - 2] == 'B' ? 'T' : 't';
+ copy[path.length - 1] = copy[path.length - 1] == 'J' ? 'L' : 'l';
+ has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, copy, path.length, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
+ if (has_stream) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_IMPLICIT_MTL, "Opened .mtl file derived from .obj filename: %s", copy));
+ }
+ }
+ }
+ }
+
+ if (has_stream) {
+ // Adopt `stream` to ufbx read callbacks
+ uc->read_fn = stream.read_fn;
+ uc->close_fn = stream.close_fn;
+ uc->read_user = stream.user;
+
+ int ok = ufbxi_obj_parse_mtl(uc);
+
+ if (uc->close_fn) {
+ uc->close_fn(uc->read_user);
+ }
+ uc->read_fn = NULL;
+ uc->close_fn = NULL;
+ uc->read_user = NULL;
+
+ ufbxi_check(ok);
+ } else if (needs_stream && !uc->opts.ignore_missing_external_files) {
+ ufbxi_set_err_info(&uc->error, (const char*)stream_path.data, stream_path.size);
+ ufbxi_fail_msg("ufbxi_obj_load_mtl()", "External file not found");
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_load(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_obj_init(uc));
+ ufbxi_check(ufbxi_obj_parse_file(uc));
+ ufbxi_check(ufbxi_init_file_paths(uc));
+ ufbxi_check(ufbxi_obj_load_mtl(uc));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_mtl_load(ufbxi_context *uc)
+{
+ ufbxi_check(ufbxi_obj_init(uc));
+ ufbxi_check(ufbxi_init_file_paths(uc));
+ ufbxi_check(ufbxi_obj_parse_mtl(uc));
+
+ return 1;
+}
+
+#else
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_obj_load(ufbxi_context *uc)
+{
+ ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_FORMAT_OBJ");
+ ufbxi_fail_msg("UFBXI_FEATURE_FORMAT_OBJ", "Feature disabled");
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_mtl_load(ufbxi_context *uc)
+{
+ ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_FORMAT_OBJ");
+ ufbxi_fail_msg("UFBXI_FEATURE_FORMAT_OBJ", "Feature disabled");
+}
+
+static ufbxi_forceinline void ufbxi_obj_free(ufbxi_context *uc)
+{
+}
+#endif
+
+// -- Scene pre-processing
+
+typedef struct {
+ ufbx_element *src, *dst;
+} ufbxi_pre_connection;
+
+typedef struct {
+ bool has_constant_scale;
+ bool has_recursive_scale_helper;
+ bool has_skin_deformer;
+ ufbx_vec3 constant_scale;
+ uint32_t element_id;
+ uint32_t first_child;
+ uint32_t next_child;
+ uint32_t parent;
+} ufbxi_pre_node;
+
+typedef struct {
+ bool has_skin_deformer;
+} ufbxi_pre_mesh;
+
+typedef struct {
+ bool has_constant_value;
+ ufbx_vec3 constant_value;
+} ufbxi_pre_anim_value;
+
+static bool ufbxi_pivot_nonzero(ufbx_vec3 offset)
+{
+ // TODO: Expose this as a setting?
+ const double epsilon = 0.0009765625;
+ return ufbx_fabs(offset.x) >= epsilon || ufbx_fabs(offset.y) >= epsilon || ufbx_fabs(offset.z) >= epsilon;
+}
+
+static ufbx_real ufbxi_pivot_div(ufbx_real offset, ufbx_real initial_scale)
+{
+ const double epsilon = 0.0078125;
+ if (ufbx_fabs(initial_scale) >= epsilon) {
+ return offset / initial_scale;
+ } else {
+ return offset;
+ }
+}
+
+// Called between parsing and `ufbxi_finalize_scene()`.
+// This is a very messy function reminiscent of the _old_ ufbx, where we do
+// multiple passes over connections without having a proper scene graph.
+// This, however gives us the advantage of allowing us to modify elements
+// and connections. We can, for example, add new helper nodes and redirect
+// animated properties from source nodes to the helpers. The rest of ufbx
+// will treat these as if they were a part of the source file.
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_pre_finalize_scene(ufbxi_context *uc)
+{
+ bool required = false;
+ if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES || uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY) required = true;
+ if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_HELPER_NODES || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) required = true;
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT || uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) required = true;
+#if defined(UFBX_REGRESSION)
+ required = true;
+#endif
+
+ if (!required) return 1;
+
+ uint32_t num_elements = uc->num_elements;
+ size_t num_nodes = uc->tmp_node_ids.num_items;
+ ufbx_element **elements = ufbxi_push_pop(&uc->tmp_parse, &uc->tmp_element_ptrs, ufbx_element*, num_elements);
+ ufbxi_check(elements);
+
+ size_t num_connections = uc->tmp_connections.num_items;
+ ufbxi_tmp_connection *tmp_connections = ufbxi_push_peek(&uc->tmp_parse, &uc->tmp_connections, ufbxi_tmp_connection, num_connections);
+ ufbxi_check(tmp_connections);
+
+ ufbxi_pre_connection *pre_connections = ufbxi_push(&uc->tmp_parse, ufbxi_pre_connection, num_connections);
+ ufbxi_check(pre_connections);
+
+ uint32_t *instance_counts = ufbxi_push_zero(&uc->tmp_parse, uint32_t, num_elements);
+ ufbxi_check(instance_counts);
+
+ bool *modify_not_supported = ufbxi_push_zero(&uc->tmp_parse, bool, num_elements);
+ ufbxi_check(modify_not_supported);
+
+ ufbx_element_type *node_attrib_type = ufbxi_push_zero(&uc->tmp_parse, ufbx_element_type, num_nodes);
+ ufbxi_check(node_attrib_type);
+
+ bool *has_unscaled_children = ufbxi_push_zero(&uc->tmp_parse, bool, num_nodes);
+ ufbxi_check(has_unscaled_children);
+
+ bool *has_scale_animation = ufbxi_push_zero(&uc->tmp_parse, bool, num_nodes);
+ ufbxi_check(has_scale_animation);
+
+ ufbxi_pre_node *pre_nodes = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_node, num_nodes);
+ ufbxi_check(pre_nodes);
+
+ size_t num_meshes = uc->tmp_typed_element_offsets[UFBX_ELEMENT_MESH].num_items;
+ ufbxi_pre_mesh *pre_meshes = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_mesh, num_meshes);
+ ufbxi_check(pre_meshes);
+
+ size_t num_anim_values = uc->tmp_typed_element_offsets[UFBX_ELEMENT_ANIM_VALUE].num_items;
+ ufbxi_pre_anim_value *pre_anim_values = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_anim_value, num_anim_values);
+ ufbxi_check(pre_anim_values);
+
+ uint64_t *fbx_ids = ufbxi_push_pop(&uc->tmp_parse, &uc->tmp_element_fbx_ids, uint64_t, num_elements);
+ ufbxi_check(fbx_ids);
+
+ // TODO
+ const ufbx_real scale_epsilon = 0.001f;
+ const ufbx_real pivot_epsilon = 0.001f;
+ const ufbx_real compensate_epsilon = 0.01f;
+
+ for (size_t i = 0; i < num_elements; i++) {
+ ufbx_element *element = elements[i];
+ uint32_t id = element->typed_id;
+
+ if (element->type == UFBX_ELEMENT_NODE) {
+ ufbxi_pre_node *pre_node = &pre_nodes[id];
+ pre_node->has_constant_scale = true;
+ pre_node->constant_scale = ufbxi_find_vec3(&element->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
+ pre_node->element_id = element->element_id;
+ pre_node->first_child = ~0u;
+ pre_node->next_child = ~0u;
+ pre_node->parent = ~0u;
+ } if (element->type == UFBX_ELEMENT_ANIM_VALUE) {
+ ufbxi_pre_anim_value *pre_value = &pre_anim_values[id];
+ pre_value->has_constant_value = true;
+ pre_value->constant_value.x = ufbxi_find_real(&element->props, ufbxi_X, UFBX_NAN);
+ pre_value->constant_value.x = ufbxi_find_real(&element->props, ufbxi_d_X, pre_value->constant_value.x);
+ pre_value->constant_value.y = ufbxi_find_real(&element->props, ufbxi_Y, UFBX_NAN);
+ pre_value->constant_value.y = ufbxi_find_real(&element->props, ufbxi_d_Y, pre_value->constant_value.y);
+ pre_value->constant_value.z = ufbxi_find_real(&element->props, ufbxi_Z, UFBX_NAN);
+ pre_value->constant_value.z = ufbxi_find_real(&element->props, ufbxi_d_Z, pre_value->constant_value.z);
+ }
+ }
+
+ for (size_t i = 0; i < num_connections; i++) {
+ ufbxi_tmp_connection *tmp = &tmp_connections[i];
+ ufbxi_pre_connection *pre = &pre_connections[i];
+
+ ufbxi_fbx_id_entry *src_entry = ufbxi_find_fbx_id(uc, tmp->src);
+ ufbxi_fbx_id_entry *dst_entry = ufbxi_find_fbx_id(uc, tmp->dst);
+
+ ufbx_element *src = src_entry ? elements[src_entry->element_id] : NULL;
+ ufbx_element *dst = dst_entry ? elements[dst_entry->element_id] : NULL;
+ pre->src = src;
+ pre->dst = dst;
+ if (!src || !dst) continue;
+
+ if (tmp->src_prop.length == 0 && tmp->dst_prop.length == 0) {
+ // Count number of instances of each attribute
+ if (dst->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *dst_node = (ufbx_node*)dst;
+
+ if (src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
+ uint32_t count = ++instance_counts[src->element_id];
+ node_attrib_type[dst->typed_id] = count == 1 ? src->type : UFBX_ELEMENT_UNKNOWN;
+
+ // These must match what can be trasnsformed in `ufbxi_modify_geometry()`
+ switch (src->type) {
+ case UFBX_ELEMENT_MESH:
+ case UFBX_ELEMENT_LINE_CURVE:
+ case UFBX_ELEMENT_NURBS_CURVE:
+ case UFBX_ELEMENT_NURBS_SURFACE:
+ break; // Nop, supported
+ default:
+ modify_not_supported[dst->element_id] = true;
+ break;
+ }
+ }
+
+ if (src->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *src_node = (ufbx_node*)src;
+ ufbxi_pre_node *pre_dst = &pre_nodes[dst_node->typed_id];
+ ufbxi_pre_node *pre_src = &pre_nodes[src_node->typed_id];
+
+ // Remember parent and add children into a linked list
+ if (pre_src->parent == ~0u) {
+ pre_src->parent = dst_node->typed_id;
+ pre_src->next_child = pre_dst->first_child;
+ pre_dst->first_child = src_node->typed_id;
+ }
+
+ if (uc->opts.inherit_mode_handling != UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
+ if (!dst_node->is_root && src_node->original_inherit_mode != UFBX_INHERIT_MODE_NORMAL) {
+ has_unscaled_children[dst->typed_id] = true;
+ }
+ }
+ }
+ } else if (dst->type == UFBX_ELEMENT_MESH) {
+ if (src->type == UFBX_ELEMENT_SKIN_DEFORMER) {
+ ufbxi_pre_mesh *pre_mesh = &pre_meshes[dst->typed_id];
+ pre_mesh->has_skin_deformer = true;
+ }
+ }
+ } else if (tmp->src_prop.length == 0 && tmp->dst_prop.length != 0) {
+ const char *dst_prop = tmp->dst_prop.data;
+ if (dst->type == UFBX_ELEMENT_ANIM_VALUE && src->type == UFBX_ELEMENT_ANIM_CURVE) {
+ ufbx_anim_curve *src_curve = (ufbx_anim_curve*)src;
+ uint32_t index = 0;
+ if (dst_prop == ufbxi_Y || dst_prop == ufbxi_d_Y) {
+ index = 1;
+ } else if (dst_prop == ufbxi_Z || dst_prop == ufbxi_d_Z) {
+ index = 2;
+ }
+
+ ufbxi_pre_anim_value *pre_value = &pre_anim_values[dst->typed_id];
+ if (src_curve->max_value - src_curve->min_value >= scale_epsilon) {
+ pre_value->has_constant_value = false;
+ } else {
+ ufbx_real constant_value = (src_curve->min_value + src_curve->max_value) * 0.5f;
+ if (ufbx_isnan(pre_value->constant_value.v[index])) {
+ pre_value->constant_value.v[index] = constant_value;
+ }
+ if ((ufbx_real)ufbx_fabs(pre_value->constant_value.v[index] - constant_value) > scale_epsilon) {
+ pre_value->has_constant_value = false;
+ }
+ }
+ }
+ }
+ }
+
+ for (size_t i = 0; i < num_connections; i++) {
+ ufbxi_tmp_connection *tmp = &tmp_connections[i];
+ ufbxi_pre_connection *pre = &pre_connections[i];
+ ufbx_element *src = pre->src, *dst = pre->dst;
+ if (!src || !dst) continue;
+
+ if (tmp->src_prop.length == 0 && tmp->dst_prop.length == 0) {
+ // Count maximum number of instanced attributes in a node
+ if (dst->type == UFBX_ELEMENT_NODE) {
+ if (src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
+ instance_counts[dst->element_id] = ufbxi_max32(instance_counts[dst->element_id], instance_counts[src->element_id]);
+ if (src->type == UFBX_ELEMENT_MESH) {
+ ufbxi_pre_mesh *pre_mesh = &pre_meshes[src->typed_id];
+ if (pre_mesh->has_skin_deformer) {
+ pre_nodes[dst->typed_id].has_skin_deformer = true;
+ }
+ }
+ } else if (src->type == UFBX_ELEMENT_SKIN_DEFORMER) {
+ pre_nodes[dst->typed_id].has_skin_deformer = true;
+ }
+ }
+ } else if (tmp->src_prop.length == 0 && tmp->dst_prop.length != 0) {
+ if (dst->type == UFBX_ELEMENT_NODE) {
+ if (src->type == UFBX_ELEMENT_ANIM_VALUE) {
+ if (tmp->dst_prop.data == ufbxi_Lcl_Scaling) {
+ ufbxi_pre_node *pre_node = &pre_nodes[dst->typed_id];
+ if (pre_node->has_constant_scale) {
+ ufbxi_pre_anim_value *pre_value = &pre_anim_values[src->typed_id];
+ if (!pre_value->has_constant_value) {
+ pre_node->has_constant_scale = false;
+ } else {
+ ufbx_real error = 0.0f;
+ error += (ufbx_real)ufbx_fabs(pre_value->constant_value.x - pre_node->constant_scale.x);
+ error += (ufbx_real)ufbx_fabs(pre_value->constant_value.y - pre_node->constant_scale.y);
+ error += (ufbx_real)ufbx_fabs(pre_value->constant_value.z - pre_node->constant_scale.z);
+ if (error >= scale_epsilon) {
+ pre_node->has_constant_scale = false;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT || uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
+ for (size_t i = 0; i < num_nodes; i++) {
+ ufbxi_pre_node *pre_node = &pre_nodes[i];
+ ufbx_node *node = (ufbx_node*)elements[pre_node->element_id];
+
+ ufbx_vec3 rotation_pivot = ufbxi_find_vec3(&node->props, ufbxi_RotationPivot, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling_pivot = ufbxi_find_vec3(&node->props, ufbxi_ScalingPivot, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling_offset = ufbxi_find_vec3(&node->props, ufbxi_ScalingOffset, 0.0f, 0.0f, 0.0f);
+
+ bool should_modify_pivot = false;
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
+ should_modify_pivot = !ufbxi_is_vec3_zero(rotation_pivot);
+ } else if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
+ should_modify_pivot = ufbxi_pivot_nonzero(rotation_pivot) || ufbxi_pivot_nonzero(scaling_pivot) || ufbxi_pivot_nonzero(scaling_offset);
+ }
+
+ if (should_modify_pivot) {
+ bool skip_geometry_transform = false;
+ bool can_modify_geometry_transform = true;
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
+ if (node_attrib_type[node->typed_id] == UFBX_ELEMENT_EMPTY) {
+ if (!uc->opts.pivot_handling_retain_empties) {
+ skip_geometry_transform = true;
+ } else {
+ can_modify_geometry_transform = false;
+ }
+ }
+ }
+
+ if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK) {
+ if (instance_counts[node->element_id] > 1 || modify_not_supported[node->element_id]) {
+ can_modify_geometry_transform = false;
+ }
+ }
+ // Currently, geometry transform messes up skinning
+ if (pre_node->has_skin_deformer) {
+ can_modify_geometry_transform = false;
+ }
+
+ bool can_modify_pivot = true;
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
+ ufbx_real err = 0.0f;
+ err += (ufbx_real)ufbx_fabs(rotation_pivot.x - scaling_pivot.x);
+ err += (ufbx_real)ufbx_fabs(rotation_pivot.y - scaling_pivot.y);
+ err += (ufbx_real)ufbx_fabs(rotation_pivot.z - scaling_pivot.z);
+ if (err > pivot_epsilon) {
+ can_modify_pivot = false;
+ }
+ }
+
+ if (can_modify_pivot && (can_modify_geometry_transform || skip_geometry_transform)) {
+ ufbx_vec3 geometric_translation = ufbxi_find_vec3(&node->props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
+
+ ufbx_vec3 child_offset = { 0.0f };
+ ufbx_prop *new_props = NULL;
+ size_t num_props = node->props.props.count;
+ size_t new_prop_count = num_props;
+ if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
+ ufbx_assert(!skip_geometry_transform); // not supporeted in legacy mode
+ child_offset = ufbxi_neg3(rotation_pivot);
+ geometric_translation = ufbxi_add3(geometric_translation, child_offset);
+
+ new_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_props + 3);
+ ufbxi_check(new_props);
+ memcpy(new_props, node->props.props.data, num_props * sizeof(ufbx_prop));
+
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_RotationPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_GeometricTranslation, &geometric_translation, UFBX_PROP_VECTOR);
+ } else if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
+ // We can eliminate the post-rotation translation and move it to the geometry/children as follows.
+ // Let Z be the initial value of S in the transform (aka `initial_scale`):
+ //
+ // (Rp-1+Soff+Sp) + S * (Sp-1)
+ // S * (Sp-1 + (Rp-1+Soff+Sp)/S)
+ // S * (Sp-1 + (Rp-1+Soff+Sp)/S - (Rp-1+Soff+Sp)/Z + (Rp-1+Soff+Sp)/Z)
+ //
+ // (Rp-1 + Soff + Sp) + S * (-(Rp-1 + Soff + Sp)/Z + (Sp-1 + (Rp-1 + Soff + Sp)/Z))
+ // ^-scaled_offset--^ ^-unscaled_offset--^ ^-unscaled_offset--^
+ // ^---------------- 0, when S=Z ----------------^ ^------- child_offset ------^
+ //
+ // We need to be careful when doing this in case any component of Z is 0. Fortunately,
+ // the above holds for all `Z != 0`, it will just result in non-zero translation in the parent.
+ ufbx_vec3 initial_scale = ufbxi_find_vec3(&node->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
+ ufbx_vec3 scaled_offset = ufbxi_sub3(ufbxi_add3(scaling_offset, scaling_pivot), rotation_pivot);
+ ufbx_vec3 unscaled_offset;
+ unscaled_offset.x = ufbxi_pivot_div(scaled_offset.x, initial_scale.x);
+ unscaled_offset.y = ufbxi_pivot_div(scaled_offset.y, initial_scale.y);
+ unscaled_offset.z = ufbxi_pivot_div(scaled_offset.z, initial_scale.z);
+
+ // Convert `scaled_offset + S*unscaled_offset` to FBX scaling pivot and offset.
+ ufbx_vec3 new_scaling_pivot = unscaled_offset;
+ ufbx_vec3 new_scaling_offset = ufbxi_sub3(scaled_offset, new_scaling_pivot);
+ child_offset = ufbxi_sub3(unscaled_offset, scaling_pivot);
+
+ new_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_props + 4);
+ ufbxi_check(new_props);
+ memcpy(new_props, node->props.props.data, num_props * sizeof(ufbx_prop));
+
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_RotationPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingPivot, &new_scaling_pivot, UFBX_PROP_VECTOR);
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingOffset, &new_scaling_offset, UFBX_PROP_VECTOR);
+ if (!skip_geometry_transform) {
+ geometric_translation = ufbxi_add3(geometric_translation, child_offset);
+ ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_GeometricTranslation, &geometric_translation, UFBX_PROP_VECTOR);
+ }
+ }
+
+ node->props.props.data = new_props;
+ node->props.props.count = new_prop_count;
+ ufbxi_check(ufbxi_sort_properties(uc, node->props.props.data, node->props.props.count));
+ ufbxi_deduplicate_properties(&node->props.props);
+
+ node->adjust_pre_translation = ufbxi_add3(node->adjust_pre_translation, rotation_pivot);
+ node->has_adjust_transform = true;
+ uint32_t ix = pre_node->first_child;
+ while (ix != ~0u) {
+ ufbxi_pre_node *pre_child = &pre_nodes[ix];
+ ufbx_node *child = (ufbx_node*)elements[pre_child->element_id];
+
+ child->adjust_pre_translation = ufbxi_add3(child->adjust_pre_translation, child_offset);
+ child->has_adjust_transform = true;
+
+ ix = pre_child->next_child;
+ }
+ }
+ }
+ }
+ }
+
+ for (size_t i = 0; i < num_elements; i++) {
+ ufbx_element *element = elements[i];
+ uint64_t fbx_id = fbx_ids[i];
+
+ if (element->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *node = (ufbx_node*)element;
+ bool requires_helper_node = false;
+ if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES) {
+ requires_helper_node = true;
+ } else if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY) {
+ // Setup a geometry transform helper for nodes that have instanced attributes
+ requires_helper_node = instance_counts[i] > 1 || modify_not_supported[i];
+ }
+ if (requires_helper_node) {
+ ufbxi_check(ufbxi_setup_geometry_transform_helper(uc, node, fbx_id));
+ }
+ }
+ }
+
+ for (size_t i = 0; i < num_elements; i++) {
+ ufbx_element *element = elements[i];
+ uint64_t fbx_id = fbx_ids[i];
+
+ if (element->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *node = (ufbx_node*)element;
+ if (has_unscaled_children[node->typed_id] && !node->scale_helper) {
+ ufbxi_pre_node *pre_node = &pre_nodes[node->typed_id];
+ ufbx_real ref = uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE
+ ? pre_node->constant_scale.x : (ufbx_real)1.0f;
+ ufbx_vec3 scale = pre_node->constant_scale;
+ ufbx_real dx = (ufbx_real)ufbx_fabs(scale.x - ref);
+ ufbx_real dy = (ufbx_real)ufbx_fabs(scale.y - ref);
+ ufbx_real dz = (ufbx_real)ufbx_fabs(scale.z - ref);
+ if ((dx + dy + dz >= scale_epsilon || !pre_node->has_constant_scale || (ufbx_real)ufbx_fabs(scale.x) <= compensate_epsilon)
+ && uc->opts.inherit_mode_handling != UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) {
+ ufbxi_check(ufbxi_setup_scale_helper(uc, node, fbx_id));
+
+ // If we added a geometry transform helper that may scale further helpers
+ // recursively for all child nodes using `UFBX_INHERIT_MODE_COMPONENTWISE_SCALE`
+ // This is guaranteed to terminate as `ufbxi_pre_node` may only have one parent,
+ // meaning any cycles must contain `node` itself.
+ uint32_t ix = pre_node->first_child;
+ while (ix != ~0u && ix != node->typed_id) {
+ ufbxi_pre_node *pre_child = &pre_nodes[ix];
+ ufbx_node *child = (ufbx_node*)elements[pre_child->element_id];
+
+ if (pre_child->parent != node->typed_id || child->original_inherit_mode == UFBX_INHERIT_MODE_COMPONENTWISE_SCALE) {
+ if (!pre_child->has_recursive_scale_helper && child->original_inherit_mode != UFBX_INHERIT_MODE_NORMAL) {
+ pre_child->has_recursive_scale_helper = true;
+
+ uint64_t child_fbx_id = fbx_ids[pre_child->element_id];
+ ufbxi_check(ufbxi_setup_scale_helper(uc, child, child_fbx_id));
+ child->is_scale_compensate_parent = false;
+
+ // Traverse to children if any
+ if (pre_child->first_child != ~0u) {
+ ix = pre_child->first_child;
+ continue;
+ }
+ }
+ }
+
+ // Move to next child, popping parents until we find one
+ while (pre_child->next_child == ~0u) {
+ ix = pre_child->parent;
+ if (ix == node->typed_id) break;
+ pre_child = &pre_nodes[ix];
+ }
+ if (ix != node->typed_id) {
+ ix = pre_child->next_child;
+ }
+ }
+
+ } else if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) {
+ if ((ufbx_real)ufbx_fabs(scale.x - 1.0f) >= scale_epsilon) {
+ node->is_scale_compensate_parent = true;
+ }
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+// -- Scene processing
+
+static ufbxi_noinline ufbx_element *ufbxi_find_element_by_fbx_id(ufbxi_context *uc, uint64_t fbx_id)
+{
+ ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, fbx_id);
+ if (entry) {
+ return uc->scene.elements.data[entry->element_id];
+ }
+ return NULL;
+}
+
+ufbxi_forceinline static bool ufbxi_cmp_name_element_less(const ufbx_name_element *a, const ufbx_name_element *b)
+{
+ if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
+ int cmp = strcmp(a->name.data, b->name.data);
+ if (cmp != 0) return cmp < 0;
+ return a->type < b->type;
+}
+
+ufbxi_forceinline static bool ufbxi_cmp_name_element_less_ref(const ufbx_name_element *a, ufbx_string name, ufbx_element_type type, uint32_t key)
+{
+ if (a->_internal_key != key) return a->_internal_key < key;
+ int cmp = ufbxi_str_cmp(a->name, name);
+ if (cmp != 0) return cmp < 0;
+ return a->type < type;
+}
+
+ufbxi_forceinline static bool ufbxi_cmp_prop_less_ref(const ufbx_prop *a, ufbx_string name, uint32_t key)
+{
+ if (a->_internal_key != key) return a->_internal_key < key;
+ return ufbxi_str_less(a->name, name);
+}
+
+ufbxi_forceinline static bool ufbxi_cmp_prop_less_concat(const ufbx_prop *a, const ufbx_string *parts, size_t num_parts, uint32_t key)
+{
+ if (a->_internal_key != key) return a->_internal_key < key;
+ return ufbxi_concat_str_cmp(&a->name, parts, num_parts) < 0;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_name_elements(ufbxi_context *uc, ufbx_name_element *name_elems, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_name_element)));
+ ufbxi_macro_stable_sort(ufbx_name_element, 32, name_elems, uc->tmp_arr, count,
+ ( ufbxi_cmp_name_element_less(a, b) ) );
+ return 1;
+}
+
+ufbxi_noinline static bool ufbxi_cmp_node_less(ufbx_node *a, ufbx_node *b)
+{
+ if (a->node_depth != b->node_depth) return a->node_depth < b->node_depth;
+ if (a->parent && b->parent) {
+ uint32_t a_pid = a->parent->element.element_id, b_pid = b->parent->element.element_id;
+ if (a_pid != b_pid) return a_pid < b_pid;
+ } else {
+ ufbx_assert(a->parent == NULL && b->parent == NULL);
+ }
+ if (a->is_geometry_transform_helper != b->is_geometry_transform_helper) {
+ // Sort geometry transform helpers always before rest of the children.
+ return (unsigned)a->is_geometry_transform_helper > (unsigned)b->is_geometry_transform_helper;
+ }
+ if (a->is_scale_helper != b->is_scale_helper) {
+ // Sort scale helpers after geometry transform helpers.
+ return (unsigned)a->is_scale_helper > (unsigned)b->is_scale_helper;
+ }
+ return a->element.element_id < b->element.element_id;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_node_ptrs(ufbxi_context *uc, ufbx_node **nodes, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_node*)));
+ ufbxi_macro_stable_sort(ufbx_node*, 32, nodes, uc->tmp_arr, count,
+ ( ufbxi_cmp_node_less(*a, *b) ) );
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_cmp_tmp_material_texture_less(const ufbxi_tmp_material_texture *a, const ufbxi_tmp_material_texture *b)
+{
+ if (a->material_id != b->material_id) return a->material_id < b->material_id;
+ if (a->texture_id != b->texture_id) return a->texture_id < b->texture_id;
+ return ufbxi_str_less(a->prop_name, b->prop_name);
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_tmp_material_textures(ufbxi_context *uc, ufbxi_tmp_material_texture *mat_texs, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_tmp_material_texture)));
+ ufbxi_macro_stable_sort(ufbxi_tmp_material_texture, 32, mat_texs, uc->tmp_arr, count,
+ ( ufbxi_cmp_tmp_material_texture_less(a, b) ));
+ return 1;
+}
+
+// We need to be able to assume no padding!
+ufbx_static_assert(connection_size, sizeof(ufbx_connection) == sizeof(ufbx_element*)*2 + sizeof(ufbx_string)*2);
+
+ufbxi_forceinline static bool ufbxi_cmp_connection_less(ufbx_connection *a, ufbx_connection *b, size_t index)
+{
+ ufbx_element *a_elem = (&a->src)[index], *b_elem = (&b->src)[index];
+ if (a_elem != b_elem) return a_elem < b_elem;
+ int cmp = strcmp((&a->src_prop)[index].data, (&b->src_prop)[index].data);
+ if (cmp != 0) return cmp < 0;
+ cmp = strcmp((&a->src_prop)[index ^ 1].data, (&b->src_prop)[index ^ 1].data);
+ return cmp < 0;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_connections(ufbxi_context *uc, ufbx_connection *connections, size_t count, size_t index)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_connection)));
+ ufbxi_macro_stable_sort(ufbx_connection, 32, connections, uc->tmp_arr, count, ( ufbxi_cmp_connection_less(a, b, index) ));
+ return 1;
+}
+
+static uint64_t ufbxi_find_attribute_fbx_id(ufbxi_context *uc, uint64_t node_fbx_id)
+{
+ uint32_t hash = ufbxi_hash64(node_fbx_id);
+ ufbxi_fbx_attr_entry *entry = ufbxi_map_find(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &node_fbx_id);
+ if (entry) {
+ return entry->attr_fbx_id;
+ }
+ return node_fbx_id;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_connections(ufbxi_context *uc)
+{
+ size_t num_connections = uc->tmp_connections.num_items;
+ ufbxi_tmp_connection *tmp_connections = ufbxi_push_pop(&uc->tmp, &uc->tmp_connections, ufbxi_tmp_connection, num_connections);
+ ufbxi_buf_free(&uc->tmp_connections);
+ ufbxi_check(tmp_connections);
+
+ // NOTE: We truncate this array in case not all connections are resolved
+ uc->scene.connections_src.data = ufbxi_push(&uc->result, ufbx_connection, num_connections);
+ ufbxi_check(uc->scene.connections_src.data);
+
+ // HACK: Translate property connections from node to attribute if the property name is not included
+ // in the known node properties and is not a property of the node.
+ if (uc->version > 0 && uc->version < 7000) {
+ ufbxi_for(ufbxi_tmp_connection, tmp_conn, tmp_connections, num_connections) {
+ if (tmp_conn->src_prop.length > 0 && !ufbxi_is_node_property_name(uc, tmp_conn->src_prop.data)) {
+ ufbx_element *src = ufbxi_find_element_by_fbx_id(uc, tmp_conn->src);
+ if (!src || !ufbx_find_prop_len(&src->props, tmp_conn->src_prop.data, tmp_conn->src_prop.length)) {
+ tmp_conn->src = ufbxi_find_attribute_fbx_id(uc, tmp_conn->src);
+ }
+ }
+ if (tmp_conn->dst_prop.length > 0 && !ufbxi_is_node_property_name(uc, tmp_conn->dst_prop.data)) {
+ ufbx_element *dst = ufbxi_find_element_by_fbx_id(uc, tmp_conn->dst);
+ if (!dst || !ufbx_find_prop_len(&dst->props, tmp_conn->dst_prop.data, tmp_conn->dst_prop.length)) {
+ tmp_conn->dst = ufbxi_find_attribute_fbx_id(uc, tmp_conn->dst);
+ }
+ }
+ }
+ }
+
+ ufbxi_for(ufbxi_tmp_connection, tmp_conn, tmp_connections, num_connections) {
+ ufbx_element *src = ufbxi_find_element_by_fbx_id(uc, tmp_conn->src);
+ ufbx_element *dst = ufbxi_find_element_by_fbx_id(uc, tmp_conn->dst);
+ if (!src || !dst) continue;
+
+ if (!uc->opts.disable_quirks) {
+ // Some exporters connect arbitrary non-nodes to root breaking further code, ignore those connections here!
+ if (dst->type == UFBX_ELEMENT_NODE && src->type != UFBX_ELEMENT_NODE && ((ufbx_node*)dst)->is_root) {
+ ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_BAD_ELEMENT_CONNECTED_TO_ROOT, src->element_id, "Non-node element connected to root"));
+ continue;
+ }
+ }
+
+ // Remap connections to geometry transform helpers if necessary, see `ufbxi_setup_geometry_transform_helper()` for how these are setup.
+ if (uc->has_geometry_transform_nodes) {
+ if (dst->type == UFBX_ELEMENT_NODE && src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
+ ufbx_node *node = (ufbx_node*)dst;
+ if (node->has_geometry_transform) {
+ ufbxi_node_extra *extra = (ufbxi_node_extra*)ufbxi_get_element_extra(uc, node->element_id);
+ ufbx_assert(extra);
+ dst = uc->scene.elements.data[extra->geometry_helper_id];
+ ufbx_assert(dst->type == UFBX_ELEMENT_NODE && ((ufbx_node*)dst)->is_geometry_transform_helper);
+ }
+ }
+ }
+
+ // Remap connections to scale helpers if necessary, see `ufbxi_setup_scale_helper()` for how these are setup.
+ if (uc->has_scale_helper_nodes) {
+ if (dst->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *dst_node = (ufbx_node*)dst;
+ if (dst_node->scale_helper) {
+ if (src->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *src_node = (ufbx_node*)src;
+ if (!src_node->is_scale_helper && src_node->original_inherit_mode == UFBX_INHERIT_MODE_NORMAL) {
+ dst = &dst_node->scale_helper->element;
+ }
+ } else if (src->type == UFBX_ELEMENT_ANIM_VALUE) {
+ if (tmp_conn->dst_prop.data == ufbxi_Lcl_Scaling) {
+ dst = &dst_node->scale_helper->element;
+ }
+ } else {
+ dst = &dst_node->scale_helper->element;
+ }
+ }
+ } else if (src->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *src_node = (ufbx_node*)src;
+ if (src_node->scale_helper) {
+ if (dst->type == UFBX_ELEMENT_SKIN_CLUSTER) {
+ src = &src_node->scale_helper->element;
+ }
+ }
+ }
+ }
+
+ // Translate deformers to point to the geometry in 6100, we don't need to worry about
+ // blend shapes here as they're always connected synthetically in older files.
+ if (uc->version > 0 && uc->version < 7000 && dst->type == UFBX_ELEMENT_NODE) {
+ if (src->type == UFBX_ELEMENT_SKIN_DEFORMER || src->type == UFBX_ELEMENT_CACHE_DEFORMER) {
+ uint64_t dst_id = ufbxi_find_attribute_fbx_id(uc, tmp_conn->dst);
+ ufbx_element *dst_elem = ufbxi_find_element_by_fbx_id(uc, dst_id);
+ if (dst_elem) {
+ dst = dst_elem;
+ }
+ }
+ }
+
+ ufbx_connection *conn = &uc->scene.connections_src.data[uc->scene.connections_src.count++];
+ conn->src = src;
+ conn->dst = dst;
+ conn->src_prop = tmp_conn->src_prop;
+ conn->dst_prop = tmp_conn->dst_prop;
+ }
+
+ uc->scene.connections_dst.count = uc->scene.connections_src.count;
+ uc->scene.connections_dst.data = ufbxi_push_copy(&uc->result, ufbx_connection,
+ uc->scene.connections_src.count, uc->scene.connections_src.data);
+ ufbxi_check(uc->scene.connections_dst.data);
+
+ ufbxi_check(ufbxi_sort_connections(uc, uc->scene.connections_src.data, uc->scene.connections_src.count, 0));
+ ufbxi_check(ufbxi_sort_connections(uc, uc->scene.connections_dst.data, uc->scene.connections_dst.count, 1));
+
+ // We don't need the temporary connections at this point anymore
+ ufbxi_buf_free(&uc->tmp_connections);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_add_connections_to_elements(ufbxi_context *uc)
+{
+ ufbx_connection *conn_src = uc->scene.connections_src.data;
+ ufbx_connection *conn_src_end = ufbxi_add_ptr(conn_src, uc->scene.connections_src.count);
+ ufbx_connection *conn_dst = uc->scene.connections_dst.data;
+ ufbx_connection *conn_dst_end = ufbxi_add_ptr(conn_dst, uc->scene.connections_dst.count);
+
+ ufbxi_for_ptr(ufbx_element, p_elem, uc->scene.elements.data, uc->scene.elements.count) {
+ ufbx_element *elem = *p_elem;
+ uint32_t id = elem->element_id;
+
+ while (conn_src < conn_src_end && conn_src->src->element_id < id) conn_src++;
+ while (conn_dst < conn_dst_end && conn_dst->dst->element_id < id) conn_dst++;
+ ufbx_connection *src_end = conn_src, *dst_end = conn_dst;
+
+ while (src_end < conn_src_end && src_end->src->element_id == id) src_end++;
+ while (dst_end < conn_dst_end && dst_end->dst->element_id == id) dst_end++;
+
+ elem->connections_src.data = conn_src;
+ elem->connections_src.count = ufbxi_to_size(src_end - conn_src);
+ elem->connections_dst.data = conn_dst;
+ elem->connections_dst.count = ufbxi_to_size(dst_end - conn_dst);
+
+ // Setup animated properties
+ // TODO: It seems we're invalidating a lot of properties here actually, maybe they
+ // should be initially pushed to `tmp` instead of result if this happens so much..
+ {
+ ufbx_prop *prop = elem->props.props.data, *prop_end = ufbxi_add_ptr(prop, elem->props.props.count);
+ ufbx_prop *copy_start = prop;
+ bool needs_copy = false;
+ size_t num_animated = 0, num_synthetic = 0;
+
+ for (;;) {
+ // Scan to the next animation connection
+ for (; conn_dst < dst_end; conn_dst++) {
+ if (conn_dst->dst_prop.length == 0) continue;
+ if (conn_dst->src_prop.length > 0) break;
+ if (conn_dst->src->type == UFBX_ELEMENT_ANIM_VALUE) break;
+ }
+
+ ufbx_string name = ufbx_empty_string;
+ if (conn_dst < dst_end) {
+ name = conn_dst->dst_prop;
+ }
+ if (name.length == 0) break;
+
+ // NOTE: "Animated" properties also include connected ones as we need
+ // to resolve them during evaluation
+ num_animated++;
+
+ ufbx_anim_value *anim_value = NULL;
+ uint32_t flags = 0;
+ for (; conn_dst < dst_end && conn_dst->dst_prop.data == name.data; conn_dst++) {
+ if (conn_dst->src_prop.length > 0) {
+ flags |= UFBX_PROP_FLAG_CONNECTED;
+ } else if (conn_dst->src->type == UFBX_ELEMENT_ANIM_VALUE) {
+ anim_value = (ufbx_anim_value*)conn_dst->src;
+ flags |= UFBX_PROP_FLAG_ANIMATED;
+ }
+ }
+
+ uint32_t key = ufbxi_get_name_key(name.data, name.length);
+ while (prop != prop_end && ufbxi_name_key_less(prop, name.data, name.length, key)) prop++;
+
+ if (prop != prop_end && prop->name.data == name.data) {
+ prop->flags = (ufbx_prop_flags)((uint32_t)prop->flags | flags);
+ } else {
+ // Animated property that is not in the element property list
+ // Copy the preceding properties to the stack, then push a
+ // synthetic property for the animated property.
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, ufbxi_to_size(prop - copy_start), copy_start));
+ copy_start = prop;
+ needs_copy = true;
+
+ // Let's hope we can find the property in the defaults at least
+ ufbx_prop anim_def_prop;
+ ufbx_prop *def_prop = NULL;
+ if (elem->props.defaults) {
+ def_prop = ufbxi_find_prop_with_key(elem->props.defaults, name.data, key);
+ } else if (anim_value) {
+ memset(&anim_def_prop, 0, sizeof(anim_def_prop));
+ // Hack a couple of common types
+ ufbx_prop_type type = UFBX_PROP_UNKNOWN;
+ if (name.data == ufbxi_Lcl_Translation) type = UFBX_PROP_TRANSLATION;
+ else if (name.data == ufbxi_Lcl_Rotation) type = UFBX_PROP_ROTATION;
+ else if (name.data == ufbxi_Lcl_Scaling) {
+ type = UFBX_PROP_SCALING;
+ anim_def_prop.value_vec3.x = 1.0f;
+ anim_def_prop.value_vec3.y = 1.0f;
+ anim_def_prop.value_vec3.z = 1.0f;
+ }
+ // Property values are only defined in anim_props on legacy files
+ if (uc->version < 6000) {
+ anim_def_prop.value_vec3 = anim_value->default_value;
+ }
+ anim_def_prop.type = type;
+ def_prop = &anim_def_prop;
+ } else {
+ flags |= UFBX_PROP_FLAG_NO_VALUE;
+ }
+
+ ufbx_prop *new_prop = ufbxi_push_zero(&uc->tmp_stack, ufbx_prop, 1);
+ ufbxi_check(new_prop);
+ if (def_prop) *new_prop = *def_prop;
+ flags |= (uint32_t)new_prop->flags;
+ new_prop->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_ANIMATABLE | UFBX_PROP_FLAG_SYNTHETIC | flags);
+ new_prop->name = name;
+ new_prop->_internal_key = key;
+ new_prop->value_str = ufbx_empty_string;
+ new_prop->value_blob = ufbx_empty_blob;
+ num_synthetic++;
+ }
+ }
+
+ // Copy the properties if necessary
+ if (needs_copy) {
+ size_t num_new_props = elem->props.props.count + num_synthetic;
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, ufbxi_to_size(prop_end - copy_start), copy_start));
+ elem->props.props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_prop, num_new_props);
+ ufbxi_check(elem->props.props.data);
+ elem->props.props.count = num_new_props;
+ }
+ elem->props.num_animated = num_animated;
+ }
+
+ conn_src = src_end;
+ conn_dst = dst_end;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_linearize_nodes(ufbxi_context *uc)
+{
+ size_t num_nodes = uc->tmp_node_ids.num_items;
+ uint32_t *node_ids = ufbxi_push_pop(&uc->tmp, &uc->tmp_node_ids, uint32_t, num_nodes);
+ ufbxi_buf_free(&uc->tmp_node_ids);
+ ufbxi_check(node_ids);
+
+ ufbx_node **node_ptrs = ufbxi_push(&uc->tmp_stack, ufbx_node*, num_nodes);
+ ufbxi_check(node_ptrs);
+
+ // Fetch the node pointers
+ for (size_t i = 0; i < num_nodes; i++) {
+ node_ptrs[i] = (ufbx_node*)uc->scene.elements.data[node_ids[i]];
+ ufbx_assert(node_ptrs[i]->element.type == UFBX_ELEMENT_NODE);
+ }
+
+ uc->scene.root_node = node_ptrs[0];
+
+ size_t *node_offsets = ufbxi_push_pop(&uc->tmp_stack, &uc->tmp_typed_element_offsets[UFBX_ELEMENT_NODE], size_t, num_nodes);
+ ufbxi_check(node_offsets);
+
+ // Hook up the parent nodes, we'll assume that there's no cycles at this point
+ ufbxi_for_ptr(ufbx_node, p_node, node_ptrs, num_nodes) {
+ ufbx_node *node = *p_node;
+
+ // Pre-6000 files don't have any explicit root connections so they must always
+ // be connected to the root..
+ if (node->parent == NULL && !(uc->opts.allow_nodes_out_of_root && uc->version >= 6000)) {
+ if (node != uc->scene.root_node) {
+ node->parent = uc->scene.root_node;
+ }
+ }
+
+ ufbxi_for_list(ufbx_connection, conn, node->element.connections_dst) {
+ if (conn->src_prop.length > 0 || conn->dst_prop.length > 0) continue;
+ if (conn->src->type != UFBX_ELEMENT_NODE) continue;
+ ((ufbx_node*)conn->src)->parent = node;
+ }
+ }
+
+ // Count the parent depths and child amounts
+ ufbxi_for_ptr(ufbx_node, p_node, node_ptrs, num_nodes) {
+ ufbx_node *node = *p_node;
+ uint32_t depth = 0;
+
+ for (ufbx_node *p = node->parent; p; p = p->parent) {
+ depth += p->node_depth + 1;
+ if (p->node_depth > 0) break;
+ ufbxi_check_msg(depth <= num_nodes, "Cyclic node hierarchy");
+ }
+
+ if (uc->opts.node_depth_limit > 0) {
+ ufbxi_check_msg(depth <= uc->opts.node_depth_limit, "Node depth limit exceeded");
+ }
+ node->node_depth = depth;
+
+ // Second pass to cache the depths to avoid O(n^2)
+ for (ufbx_node *p = node->parent; p; p = p->parent) {
+ if (--depth <= p->node_depth) break;
+ p->node_depth = depth;
+ }
+ }
+
+ ufbxi_check(ufbxi_sort_node_ptrs(uc, node_ptrs, num_nodes));
+
+ for (uint32_t i = 0; i < num_nodes; i++) {
+ size_t *p_offset = ufbxi_push(&uc->tmp_typed_element_offsets[UFBX_ELEMENT_NODE], size_t, 1);
+ ufbxi_check(p_offset);
+ ufbx_node *node = node_ptrs[i];
+
+ uint32_t original_id = node->element.typed_id;
+ node->element.typed_id = i;
+ *p_offset = node_offsets[original_id];
+ }
+
+ // Pop the temporary arrays
+ ufbxi_pop(&uc->tmp_stack, size_t, num_nodes, NULL);
+ ufbxi_pop(&uc->tmp_stack, ufbx_node*, num_nodes, NULL);
+
+ return 1;
+}
+
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_connection_list ufbxi_find_dst_connections(ufbx_element *element, const char *prop)
+{
+ if (!prop) prop = ufbxi_empty_char;
+
+ size_t begin = element->connections_dst.count, end = begin;
+
+ ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &begin,
+ element->connections_dst.data, 0, element->connections_dst.count,
+ (strcmp(a->dst_prop.data, prop) < 0),
+ (a->dst_prop.data == prop && a->src_prop.length == 0));
+
+ ufbxi_macro_upper_bound_eq(ufbx_connection, 32, &end,
+ element->connections_dst.data, begin, element->connections_dst.count,
+ (a->dst_prop.data == prop && a->src_prop.length == 0));
+
+ ufbx_connection_list result = { element->connections_dst.data + begin, end - begin };
+ return result;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_connection_list ufbxi_find_src_connections(ufbx_element *element, const char *prop)
+{
+ if (!prop) prop = ufbxi_empty_char;
+
+ size_t begin = element->connections_src.count, end = begin;
+
+ ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &begin,
+ element->connections_src.data, 0, element->connections_src.count,
+ (strcmp(a->src_prop.data, prop) < 0),
+ (a->src_prop.data == prop && a->dst_prop.length == 0));
+
+ ufbxi_macro_upper_bound_eq(ufbx_connection, 32, &end,
+ element->connections_src.data, begin, element->connections_src.count,
+ (a->src_prop.data == prop && a->dst_prop.length == 0));
+
+ ufbx_connection_list result = { element->connections_src.data + begin, end - begin };
+ return result;
+}
+
+ufbxi_nodiscard static ufbx_element *ufbxi_get_element_node(ufbx_element *element)
+{
+ if (!element) return NULL;
+ if (element->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *node = (ufbx_node*)element;
+ if (node->is_geometry_transform_helper) return (ufbx_element*)node->parent;
+ return NULL;
+ } else {
+ return element->instances.count > 0 ? &element->instances.data[0]->element : NULL;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_dst_elements(ufbxi_context *uc, void *p_dst_list, ufbx_element *element, bool search_node, bool ignore_duplicates, const char *prop, ufbx_element_type src_type)
+{
+ size_t num_elements = 0;
+
+ do {
+ ufbx_connection_list conns = ufbxi_find_dst_connections(element, prop);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->src->type == src_type) {
+ if (ignore_duplicates) {
+ uint32_t element_id = conn->src->element_id;
+ if (uc->tmp_element_flag[element_id]) {
+ ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_DUPLICATE_CONNECTION, element_id, "Duplicate connection to %u", element->element_id));
+ continue;
+ }
+ uc->tmp_element_flag[element_id] = 1;
+ }
+ ufbx_element **p_elem = ufbxi_push(&uc->tmp_stack, ufbx_element*, 1);
+ ufbxi_check(p_elem);
+ *p_elem = conn->src;
+ num_elements++;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ ufbx_element_list *list = (ufbx_element_list*)p_dst_list;
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_elements);
+ list->count = num_elements;
+ ufbxi_check(list->data);
+
+ if (ignore_duplicates) {
+ ufbxi_for_ptr_list(ufbx_element, p_elem, *list) {
+ uc->tmp_element_flag[(*p_elem)->element_id] = 0;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_src_elements(ufbxi_context *uc, void *p_dst_list, ufbx_element *element, bool search_node, bool ignore_duplicates, const char *prop, ufbx_element_type dst_type)
+{
+ size_t num_elements = 0;
+
+ do {
+ ufbx_connection_list conns = ufbxi_find_src_connections(element, prop);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->dst->type == dst_type) {
+ if (ignore_duplicates) {
+ uint32_t element_id = conn->dst->element_id;
+ if (uc->tmp_element_flag[element_id]) {
+ ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_DUPLICATE_CONNECTION, element_id, "Duplicate connection to %u", element->element_id));
+ continue;
+ }
+ uc->tmp_element_flag[element_id] = 1;
+ }
+ ufbx_element **p_elem = ufbxi_push(&uc->tmp_stack, ufbx_element*, 1);
+ ufbxi_check(p_elem);
+ *p_elem = conn->dst;
+ num_elements++;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ ufbx_element_list *list = (ufbx_element_list*)p_dst_list;
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_elements);
+ list->count = num_elements;
+ ufbxi_check(list->data);
+
+ if (ignore_duplicates) {
+ ufbxi_for_ptr_list(ufbx_element, p_elem, *list) {
+ uc->tmp_element_flag[(*p_elem)->element_id] = 0;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_fetch_dst_element(ufbx_element *element, bool search_node, const char *prop, ufbx_element_type src_type)
+{
+ do {
+ ufbx_connection_list conns = ufbxi_find_dst_connections(element, prop);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->src->type == src_type) {
+ return conn->src;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ return NULL;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_fetch_src_element(ufbx_element *element, bool search_node, const char *prop, ufbx_element_type dst_type)
+{
+ do {
+ ufbx_connection_list conns = ufbxi_find_src_connections(element, prop);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->dst->type == dst_type) {
+ return conn->dst;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ return NULL;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_textures(ufbxi_context *uc, ufbx_material_texture_list *list, ufbx_element *element, bool search_node)
+{
+ size_t num_textures = 0;
+
+ do {
+ ufbxi_for_list(ufbx_connection, conn, element->connections_dst) {
+ if (conn->src_prop.length > 0) continue;
+ if (conn->src->type == UFBX_ELEMENT_TEXTURE) {
+ ufbx_material_texture *tex = ufbxi_push(&uc->tmp_stack, ufbx_material_texture, 1);
+ ufbxi_check(tex);
+ tex->shader_prop = tex->material_prop = conn->dst_prop;
+ tex->texture = (ufbx_texture*)conn->src;
+ num_textures++;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material_texture, num_textures);
+ list->count = num_textures;
+ ufbxi_check(list->data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_mesh_materials(ufbxi_context *uc, ufbx_material_list *list, ufbx_element *element, bool search_node)
+{
+ size_t num_materials = 0;
+
+ do {
+ ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->src->type == UFBX_ELEMENT_MATERIAL) {
+ ufbx_material *mat = (ufbx_material*)conn->src;
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_material*, 1, &mat));
+ num_materials++;
+ }
+ }
+
+ if (num_materials > 0) break;
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material*, num_materials);
+ list->count = num_materials;
+ ufbxi_check(list->data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_deformers(ufbxi_context *uc, ufbx_element_list *list, ufbx_element *element, bool search_node)
+{
+ size_t num_deformers = 0;
+
+ do {
+ ufbxi_for_list(ufbx_connection, conn, element->connections_dst) {
+ if (conn->src_prop.length > 0) continue;
+ ufbx_element_type type = conn->src->type;
+ if (type == UFBX_ELEMENT_SKIN_DEFORMER || type == UFBX_ELEMENT_BLEND_DEFORMER || type == UFBX_ELEMENT_CACHE_DEFORMER) {
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &conn->src));
+ num_deformers++;
+ }
+ }
+ } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
+
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_deformers);
+ list->count = num_deformers;
+ ufbxi_check(list->data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_blend_keyframes(ufbxi_context *uc, ufbx_blend_keyframe_list *list, ufbx_element *element)
+{
+ size_t num_keyframes = 0;
+
+ ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->src->type == UFBX_ELEMENT_BLEND_SHAPE) {
+ ufbx_blend_keyframe key = { (ufbx_blend_shape*)conn->src };
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_blend_keyframe, 1, &key));
+ num_keyframes++;
+ }
+ }
+
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_blend_keyframe, num_keyframes);
+ list->count = num_keyframes;
+ ufbxi_check(list->data);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_texture_layers(ufbxi_context *uc, ufbx_texture_layer_list *list, ufbx_element *element)
+{
+ size_t num_layers = 0;
+
+ ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ if (conn->src->type == UFBX_ELEMENT_TEXTURE) {
+ ufbx_texture *texture = (ufbx_texture*)conn->src;
+ ufbx_texture_layer layer = { texture };
+ layer.alpha = ufbxi_find_real(&texture->props, ufbxi_Texture_alpha, 1.0f);
+ layer.blend_mode = (ufbx_blend_mode)ufbxi_find_enum(&texture->props, ufbxi_BlendMode, UFBX_BLEND_REPLACE, UFBX_BLEND_OVERLAY);
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture_layer, 1, &layer));
+ num_layers++;
+ }
+ }
+
+ list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_texture_layer, num_layers);
+ list->count = num_layers;
+ ufbxi_check(list->data);
+
+ return 1;
+}
+
+static ufbxi_forceinline bool ufbxi_prop_connection_less(const ufbx_connection *a, const char *prop)
+{
+ int cmp = strcmp(a->dst_prop.data, prop);
+ if (cmp != 0) return cmp < 0;
+ return a->src_prop.length == 0;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_connection *ufbxi_find_prop_connection(const ufbx_element *element, const char *prop)
+{
+ if (!prop) prop = ufbxi_empty_char;
+
+ size_t index = SIZE_MAX;
+
+ ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &index,
+ element->connections_dst.data, 0, element->connections_dst.count,
+ (ufbxi_prop_connection_less(a, prop)),
+ (a->dst_prop.data == prop && a->src_prop.length > 0));
+
+ return index < SIZE_MAX ? &element->connections_dst.data[index] : NULL;
+}
+
+ufbxi_forceinline static void ufbxi_patch_index_pointer(ufbxi_context *uc, uint32_t **p_index)
+{
+ if (*p_index == ufbxi_sentinel_index_zero) {
+ *p_index = uc->zero_indices;
+ } else if (*p_index == ufbxi_sentinel_index_consecutive) {
+ *p_index = uc->consecutive_indices;
+ }
+}
+
+ufbxi_nodiscard static bool ufbxi_cmp_anim_prop_less(const ufbx_anim_prop *a, const ufbx_anim_prop *b)
+{
+ if (a->element != b->element) return a->element < b->element;
+ if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
+ return ufbxi_str_less(a->prop_name, b->prop_name);
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_anim_props(ufbxi_context *uc, ufbx_anim_prop *aprops, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_anim_prop)));
+ ufbxi_macro_stable_sort(ufbx_anim_prop, 32, aprops, uc->tmp_arr, count, ( ufbxi_cmp_anim_prop_less(a, b) ));
+ return 1;
+}
+
+ufbxi_noinline static bool ufbxi_material_texture_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_material_texture *a = (const ufbx_material_texture*)va, *b = (const ufbx_material_texture*)vb;
+ return ufbxi_str_less(a->material_prop, b->material_prop);
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_material_textures(ufbxi_context *uc, ufbx_material_texture *textures, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_material_texture)));
+ ufbxi_stable_sort(sizeof(ufbx_material_texture), 32, textures, uc->tmp_arr, count, &ufbxi_material_texture_less, NULL);
+ return 1;
+}
+
+static ufbxi_noinline bool ufbxi_bone_pose_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_bone_pose *a = (const ufbx_bone_pose *)va, *b = (const ufbx_bone_pose *)vb;
+ return a->bone_node->typed_id < b->bone_node->typed_id;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_anim_prop *ufbxi_find_anim_prop_start(ufbx_anim_layer *layer, const ufbx_element *element)
+{
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &index, layer->anim_props.data, 0, layer->anim_props.count,
+ (a->element < element), (a->element == element));
+ return index != SIZE_MAX ? &layer->anim_props.data[index] : NULL;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_bone_poses(ufbxi_context *uc, ufbx_pose *pose)
+{
+ size_t count = pose->bone_poses.count;
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, pose->bone_poses.count * sizeof(ufbx_bone_pose)));
+ ufbxi_stable_sort(sizeof(ufbx_bone_pose), 16, pose->bone_poses.data, uc->tmp_arr, count, &ufbxi_bone_pose_less, NULL);
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_skin_weights(ufbxi_context *uc, ufbx_skin_deformer *skin)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, skin->max_weights_per_vertex * sizeof(ufbx_skin_weight)));
+
+ for (size_t i = 0; i < skin->vertices.count; i++) {
+ ufbx_skin_vertex v = skin->vertices.data[i];
+ ufbxi_macro_stable_sort(ufbx_skin_weight, 32, skin->weights.data + v.weight_begin, uc->tmp_arr, v.num_weights,
+ ( a->weight > b->weight ));
+ }
+
+ return 1;
+}
+
+ufbxi_noinline static bool ufbxi_blend_keyframe_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_blend_keyframe *a = (const ufbx_blend_keyframe*)va, *b = (const ufbx_blend_keyframe*)vb;
+ return a->target_weight < b->target_weight;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_blend_keyframes(ufbxi_context *uc, ufbx_blend_keyframe *keyframes, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_blend_keyframe)));
+ ufbxi_stable_sort(sizeof(ufbx_blend_keyframe), 32, keyframes, uc->tmp_arr, count, &ufbxi_blend_keyframe_less, NULL);
+ return 1;
+}
+
+// Material tables
+
+typedef void (*ufbxi_mat_transform_fn)(ufbx_vec4 *a);
+
+static void ufbxi_mat_transform_invert_x(ufbx_vec4 *v) { v->x = 1.0f - v->x; }
+static void ufbxi_mat_transform_unknown_shininess(ufbx_vec4 *v) { if (v->x >= 0.0f) v->x = (ufbx_real)(1.0f - ufbx_sqrt(v->x) * (ufbx_real)0.1); if (!(v->x >= 0.0f)) v->x = 0.0f; }
+static void ufbxi_mat_transform_blender_opacity(ufbx_vec4 *v) { v->x = 1.0f - v->x; }
+static void ufbxi_mat_transform_blender_shininess(ufbx_vec4 *v) { if (v->x >= 0.0f) v->x = (ufbx_real)(1.0f - ufbx_sqrt(v->x) * (ufbx_real)0.1); if (!(v->x >= 0.0f)) v->x = 0.0f; }
+
+typedef enum {
+ UFBXI_MAT_TRANSFORM_IDENTITY,
+ UFBXI_MAT_TRANSFORM_INVERT_X,
+ UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS,
+ UFBXI_MAT_TRANSFORM_BLENDER_OPACITY,
+ UFBXI_MAT_TRANSFORM_BLENDER_SHININESS,
+
+ UFBXI_MAT_TRANSFORM_COUNT,
+} ufbxi_mat_transform;
+
+typedef enum {
+ // Set `value_vec4.w` (usually alpha) to 1.0 if not defined by the property
+ UFBXI_SHADER_MAPPING_DEFAULT_W_1 = 0x1,
+ // Widen values to RGB if only a single value is present.
+ UFBXI_SHADER_MAPPING_WIDEN_TO_RGB = 0x2,
+ // Multiply the existing value.
+ UFBXI_SHADER_MAPPING_MULTIPLY_VALUE = 0x4,
+} ufbxi_shader_mapping_flag;
+
+typedef enum {
+ // Invert the feature flag
+ UFBXI_SHADER_FEATURE_INVERTED = 0x1,
+ // Enable the feature if the given property exists
+ UFBXI_SHADER_FEATURE_IF_EXISTS = 0x2,
+ // Enable the feature if the given property has a texture
+ UFBXI_SHADER_FEATURE_IF_TEXTURE = 0x4,
+ // Enable if the feature is in [0.5, 1.5], (ie. 2 won't enable this feature)
+ UFBXI_SHADER_FEATURE_IF_AROUND_1 = 0x8,
+
+ UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE = UFBXI_SHADER_FEATURE_IF_EXISTS|UFBXI_SHADER_FEATURE_IF_TEXTURE,
+} ufbxi_shader_feature_flag;
+
+static const ufbxi_mat_transform_fn ufbxi_mat_transform_fns[] = {
+ NULL,
+ &ufbxi_mat_transform_invert_x,
+ &ufbxi_mat_transform_unknown_shininess,
+ &ufbxi_mat_transform_blender_opacity,
+ &ufbxi_mat_transform_blender_shininess,
+};
+
+ufbx_static_assert(transform_count, ufbxi_arraycount(ufbxi_mat_transform_fns) == UFBXI_MAT_TRANSFORM_COUNT);
+
+typedef struct {
+ uint8_t index; // < `ufbx_material_(fbx|pbr)_map`
+ uint8_t flags; // < Combination of `ufbxi_shader_mapping_flag`
+ uint8_t transform; // < `ufbxi_mat_transform`
+ uint8_t prop_len; // < Length of `prop` not including NULL terminator
+ const char *prop; // < Name of FBX material property or shader mapping
+} ufbxi_shader_mapping;
+
+typedef struct {
+ const ufbxi_shader_mapping *data;
+ size_t count;
+ const ufbxi_shader_mapping *features;
+ size_t feature_count;
+ uint32_t default_features;
+ ufbx_string texture_prefix;
+ ufbx_string texture_suffix;
+ ufbx_string texture_enabled_prefix;
+ ufbx_string texture_enabled_suffix;
+} ufbxi_shader_mapping_list;
+
+#define ufbxi_mat_string(str) sizeof(str) - 1, str
+
+static const ufbxi_shader_mapping ufbxi_base_fbx_mapping[] = {
+ { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
+ { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
+ { UFBX_MATERIAL_FBX_DIFFUSE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
+ { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
+ { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("SpecularColor") },
+ { UFBX_MATERIAL_FBX_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("SpecularFactor") },
+ { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("Shininess") },
+ { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("ShininessExponent") },
+ { UFBX_MATERIAL_FBX_REFLECTION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Reflection") },
+ { UFBX_MATERIAL_FBX_REFLECTION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("ReflectionColor") },
+ { UFBX_MATERIAL_FBX_REFLECTION_FACTOR, 0, 0, ufbxi_mat_string("ReflectionFactor") },
+ { UFBX_MATERIAL_FBX_TRANSPARENCY_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
+ { UFBX_MATERIAL_FBX_TRANSPARENCY_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
+ { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
+ { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
+ { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
+ { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
+ { UFBX_MATERIAL_FBX_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
+ { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Ambient") },
+ { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("AmbientColor") },
+ { UFBX_MATERIAL_FBX_AMBIENT_FACTOR, 0, 0, ufbxi_mat_string("AmbientFactor") },
+ { UFBX_MATERIAL_FBX_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+ { UFBX_MATERIAL_FBX_BUMP, 0, 0, ufbxi_mat_string("Bump") },
+ { UFBX_MATERIAL_FBX_BUMP_FACTOR, 0, 0, ufbxi_mat_string("BumpFactor") },
+ { UFBX_MATERIAL_FBX_DISPLACEMENT, 0, 0, ufbxi_mat_string("Displacement") },
+ { UFBX_MATERIAL_FBX_DISPLACEMENT_FACTOR, 0, 0, ufbxi_mat_string("DisplacementFactor") },
+ { UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT, 0, 0, ufbxi_mat_string("VectorDisplacement") },
+ { UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT_FACTOR, 0, 0, ufbxi_mat_string("VectorDisplacementFactor") },
+};
+
+static const ufbxi_shader_mapping ufbxi_obj_fbx_mapping[] = {
+ { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ka") },
+ { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Kd") },
+ { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ks") },
+ { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ke") },
+ { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("Ns") },
+ { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, UFBXI_MAT_TRANSFORM_INVERT_X, ufbxi_mat_string("d") },
+ { UFBX_MATERIAL_FBX_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
+ { UFBX_MATERIAL_FBX_DISPLACEMENT, 0, 0, ufbxi_mat_string("disp") },
+ { UFBX_MATERIAL_FBX_BUMP, 0, 0, ufbxi_mat_string("bump") },
+ { UFBX_MATERIAL_FBX_BUMP, 0, 0, ufbxi_mat_string("Bump") },
+};
+
+static const ufbxi_shader_mapping ufbxi_fbx_lambert_shader_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+};
+
+static const ufbxi_shader_mapping ufbxi_fbx_phong_shader_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("SpecularColor") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("SpecularFactor") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("Shininess") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("ShininessExponent") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+};
+
+static const ufbxi_shader_mapping ufbxi_osl_standard_shader_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specular_roughness") },
+ { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diffuse_roughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular_color") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specular_IOR") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specular_anisotropy") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("specular_rotation") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmission_color") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmission_depth") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmission_scatter") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmission_scatter_anisotropy") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmission_dispersion") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_EXTRA_ROUGHNESS, 0, 0, ufbxi_mat_string("transmission_extra_roughness") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurface_color") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurface_radius") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurface_scale") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurface_anisotropy") },
+ { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("sheen") },
+ { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sheen_color") },
+ { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("sheen_roughness") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
+ { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
+ { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_IOR") },
+ { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coat_anisotropy") },
+ { UFBX_MATERIAL_PBR_COAT_ROTATION, 0, 0, ufbxi_mat_string("coat_rotation") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_normal") },
+ { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_affect_color") },
+ { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_affect_roughness") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thin_film_thickness") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thin_film_IOR") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emission_color") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normalCamera") },
+ { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("tangent") },
+};
+
+static const ufbxi_shader_mapping ufbxi_osl_standard_shader_features[] = {
+ { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thin_walled") },
+};
+
+static const ufbxi_shader_mapping ufbxi_arnold_shader_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specularRoughness") },
+ { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diffuseRoughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specularColor") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specularIOR") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specularAnisotropy") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("specularRotation") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmissionColor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmissionDepth") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmissionScatter") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmissionScatterAnisotropy") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmissionDispersion") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_EXTRA_ROUGHNESS, 0, 0, ufbxi_mat_string("transmissionExtraRoughness") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurfaceColor") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurfaceRadius") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurfaceScale") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurfaceAnisotropy") },
+ { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("sheen") },
+ { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sheenColor") },
+ { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("sheenRoughness") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
+ { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coatColor") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coatRoughness") },
+ { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coatIOR") },
+ { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coatAnisotropy") },
+ { UFBX_MATERIAL_PBR_COAT_ROTATION, 0, 0, ufbxi_mat_string("coatRotation") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coatNormal") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thinFilmThickness") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thinFilmIOR") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emissionColor") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
+ { UFBX_MATERIAL_PBR_INDIRECT_DIFFUSE, 0, 0, ufbxi_mat_string("indirectDiffuse") },
+ { UFBX_MATERIAL_PBR_INDIRECT_SPECULAR, 0, 0, ufbxi_mat_string("indirectSpecular") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normalCamera") },
+ { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("tangent") },
+ { UFBX_MATERIAL_PBR_MATTE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("aiMatteColor") },
+ { UFBX_MATERIAL_PBR_MATTE_FACTOR, 0, 0, ufbxi_mat_string("aiMatteColorA") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_TYPE, 0, 0, ufbxi_mat_string("subsurfaceType") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_PRIORITY, 0, 0, ufbxi_mat_string("dielectricPriority") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_ENABLE_IN_AOV, 0, 0, ufbxi_mat_string("transmitAovs") },
+};
+
+static const ufbxi_shader_mapping ufbxi_arnold_shader_features[] = {
+ { UFBX_MATERIAL_FEATURE_MATTE, 0, 0, ufbxi_mat_string("aiEnableMatte") },
+ { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thinWalled") },
+ { UFBX_MATERIAL_FEATURE_CAUSTICS, 0, 0, ufbxi_mat_string("caustics") },
+ { UFBX_MATERIAL_FEATURE_INTERNAL_REFLECTIONS, 0, 0, ufbxi_mat_string("internalReflections") },
+ { UFBX_MATERIAL_FEATURE_EXIT_TO_BACKGROUND, 0, 0, ufbxi_mat_string("exitToBackground") },
+};
+
+static const ufbxi_shader_mapping ufbxi_3ds_max_physical_material_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base_weight") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
+ { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diff_rough") },
+ { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diff_roughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("reflectivity") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("refl_color") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("anisotropy") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("aniso_angle") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("anisoangle") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("trans_ior") }, // NOTE: Not a typo, IOR is same for transparency/specular
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transparency") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("trans_color") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("trans_depth") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, 0, 0, ufbxi_mat_string("trans_rough") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, 0, 0, ufbxi_mat_string("trans_roughness") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("scattering") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_TINT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sss_color") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sss_scatter_color") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("sss_depth") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("sss_scale") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coating") },
+ { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_rough") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
+ { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_ior") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("clearcoat_bump_map_amt") },
+ { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_affect_color") },
+ { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_affect_roughness") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("cutout") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump_map_amt") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_map_amt") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_TYPE, 0, 0, ufbxi_mat_string("subsurfaceType") },
+};
+
+static const ufbxi_shader_mapping ufbxi_3ds_max_physical_material_features[] = {
+ { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thin_walled") },
+ { UFBX_MATERIAL_FEATURE_SPECULAR, 0, 0, ufbxi_mat_string("material_mode") },
+ { UFBX_MATERIAL_FEATURE_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("material_mode") },
+ { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS, UFBXI_SHADER_FEATURE_INVERTED, 0, ufbxi_mat_string("trans_roughness_lock") },
+ { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("roughness_inv") },
+ { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("trans_roughness_inv") },
+ { UFBX_MATERIAL_FEATURE_COAT_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("coat_roughness_inv") },
+};
+
+static const ufbxi_shader_mapping ufbxi_gltf_material_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|baseColor") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("main|roughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("main|metalness") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("main|normal") },
+ { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("main|ambientOcclusion") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|emission") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|emissionColor") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("main|Alpha") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("extension|clearcoat") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("extension|clearcoatRoughness") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("extension|clearcoatNormal") },
+ { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|sheenColor") },
+ { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("extension|sheenRoughness") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("extension|specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("extension|Specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|specularcolor") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|specularColor") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("extension|transmission") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("extension|indexOfRefraction") },
+};
+
+static const ufbxi_shader_mapping ufbxi_openpbr_material_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base_weight") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specular_roughness") },
+ { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("base_diffuse_roughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("base_metalness") },
+ { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular_weight") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular_color") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specular_roughness_anisotropy") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specular_ior") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission_weight") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmission_color") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmission_depth") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmission_scatter") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmission_scatter_anisotropy") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmission_dispersion_scale") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface_weight") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurface_color") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurface_radius_scale") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurface_radius") },
+ { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurface_scatter_anisotropy") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat_weight") },
+ { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
+ { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coat_roughness_anisotropy") },
+ { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_ior") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_normal_map") },
+ { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("fuzz_weight") },
+ { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("fuzz_color") },
+ { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("fuzz_roughness") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission_weight") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, UFBXI_SHADER_MAPPING_MULTIPLY_VALUE, 0, ufbxi_mat_string("emission_luminance") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emission_color") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_FACTOR, 0, 0, ufbxi_mat_string("thin_film_weight") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thin_film_thickness") },
+ { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thin_film_ior") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump_map_amt") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_map_amt") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump") },
+ { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump_map_amt") },
+ { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("geometry_tangent_map") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("geometry_opacity") },
+};
+
+static const ufbxi_shader_mapping ufbxi_openpbr_material_features[] = {
+ { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("geometry_thin_walled") },
+};
+
+static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_metal_rough_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("Roughness_Map") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
+ { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_amt") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
+};
+
+static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("glossiness") },
+ { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_amt") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
+};
+
+static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_features[] = {
+ { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, UFBXI_SHADER_FEATURE_IF_AROUND_1, 0, ufbxi_mat_string("useGlossiness") },
+};
+
+static const ufbxi_shader_mapping ufbxi_gltf_material_features[] = {
+ { UFBX_MATERIAL_FEATURE_DOUBLE_SIDED, 0, 0, ufbxi_mat_string("main|DoubleSided") },
+ { UFBX_MATERIAL_FEATURE_SHEEN, 0, 0, ufbxi_mat_string("extension|enableSheen") },
+ { UFBX_MATERIAL_FEATURE_COAT, 0, 0, ufbxi_mat_string("extension|enableClearCoat") },
+ { UFBX_MATERIAL_FEATURE_TRANSMISSION, 0, 0, ufbxi_mat_string("extension|enableTransmission") },
+ { UFBX_MATERIAL_FEATURE_IOR, 0, 0, ufbxi_mat_string("extension|enableIndexOfRefraction") },
+ { UFBX_MATERIAL_FEATURE_SPECULAR, 0, 0, ufbxi_mat_string("extension|enableSpecular") },
+ { UFBX_MATERIAL_FEATURE_UNLIT, 0, 0, ufbxi_mat_string("extension|unlit") },
+};
+
+// NOTE: These are just the names used by the standard PBS "preset".
+// In _theory_ we could walk ShaderGraph but that's a bit out of scope for ufbx.
+static const ufbxi_shader_mapping ufbxi_shaderfx_graph_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("color") },
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metallic") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normal") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emissive_intensity") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emissive") },
+ { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
+};
+
+static const ufbxi_shader_mapping ufbxi_blender_phong_shader_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, UFBXI_MAT_TRANSFORM_BLENDER_OPACITY, ufbxi_mat_string("TransparencyFactor") },
+ { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_BLENDER_SHININESS, ufbxi_mat_string("Shininess") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_BLENDER_SHININESS, ufbxi_mat_string("ShininessExponent") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("ReflectionFactor") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
+};
+
+static const ufbxi_shader_mapping ufbxi_obj_pbr_mapping[] = {
+ { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Kd") },
+ { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ks") },
+ { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ke") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("Ns") },
+ { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("Pr") },
+ { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("Ni") },
+ { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("Pm") },
+ { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("d") },
+ { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Tf") },
+ { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("disp") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("Bump") },
+ { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
+ { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ps") },
+ { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("Pc") },
+ { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("Pcr") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("aniso") },
+ { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("anisor") },
+};
+
+static const ufbxi_shader_mapping ufbxi_obj_features[] = {
+ { UFBX_MATERIAL_FEATURE_PBR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pr") },
+ { UFBX_MATERIAL_FEATURE_PBR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pm") },
+ { UFBX_MATERIAL_FEATURE_SHEEN, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ps") },
+ { UFBX_MATERIAL_FEATURE_COAT, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pc") },
+ { UFBX_MATERIAL_FEATURE_METALNESS, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pm") },
+ { UFBX_MATERIAL_FEATURE_IOR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ni") },
+ { UFBX_MATERIAL_FEATURE_OPACITY, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("d") },
+ { UFBX_MATERIAL_FEATURE_TRANSMISSION, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Tf") },
+ { UFBX_MATERIAL_FEATURE_EMISSION, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ke") },
+};
+
+enum {
+ UFBXI_MAT_PBR = 1 << UFBX_MATERIAL_FEATURE_PBR,
+ UFBXI_MAT_METALNESS = 1 << UFBX_MATERIAL_FEATURE_METALNESS,
+ UFBXI_MAT_DIFFUSE = 1 << UFBX_MATERIAL_FEATURE_DIFFUSE,
+ UFBXI_MAT_SPECULAR = 1 << UFBX_MATERIAL_FEATURE_SPECULAR,
+ UFBXI_MAT_EMISSION = 1 << UFBX_MATERIAL_FEATURE_EMISSION,
+ UFBXI_MAT_COAT = 1 << UFBX_MATERIAL_FEATURE_COAT,
+ UFBXI_MAT_SHEEN = 1 << UFBX_MATERIAL_FEATURE_SHEEN,
+ UFBXI_MAT_TRANSMISSION = 1 << UFBX_MATERIAL_FEATURE_TRANSMISSION,
+ UFBXI_MAT_OPACITY = 1 << UFBX_MATERIAL_FEATURE_OPACITY,
+ UFBXI_MAT_AMBIENT_OCCLUSION = 1 << UFBX_MATERIAL_FEATURE_AMBIENT_OCCLUSION,
+ UFBXI_MAT_MATTE = 1 << UFBX_MATERIAL_FEATURE_MATTE,
+ UFBXI_MAT_UNLIT = 1 << UFBX_MATERIAL_FEATURE_UNLIT,
+ UFBXI_MAT_IOR = 1 << UFBX_MATERIAL_FEATURE_IOR,
+ UFBXI_MAT_DIFFUSE_ROUGHNESS = 1 << UFBX_MATERIAL_FEATURE_DIFFUSE_ROUGHNESS,
+ UFBXI_MAT_TRANSMISSION_ROUGHNESS = 1 << UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS,
+ UFBXI_MAT_THIN_WALLED = 1 << UFBX_MATERIAL_FEATURE_THIN_WALLED,
+ UFBXI_MAT_CAUSTICS = 1 << UFBX_MATERIAL_FEATURE_CAUSTICS,
+ UFBXI_MAT_EXIT_TO_BACKGROUND = 1 << UFBX_MATERIAL_FEATURE_EXIT_TO_BACKGROUND,
+ UFBXI_MAT_INTERNAL_REFLECTIONS = 1 << UFBX_MATERIAL_FEATURE_INTERNAL_REFLECTIONS,
+ UFBXI_MAT_DOUBLE_SIDED = 1 << UFBX_MATERIAL_FEATURE_DOUBLE_SIDED,
+};
+
+static const ufbxi_shader_mapping_list ufbxi_shader_pbr_mappings[] = {
+ { // UFBX_SHADER_UNKNOWN
+ ufbxi_fbx_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_phong_shader_pbr_mapping),
+ NULL, 0,
+ (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
+ },
+ { // UFBX_SHADER_FBX_LAMBERT
+ ufbxi_fbx_lambert_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_lambert_shader_pbr_mapping),
+ NULL, 0,
+ (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
+ },
+ { // UFBX_SHADER_FBX_PHONG
+ ufbxi_fbx_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_phong_shader_pbr_mapping),
+ NULL, 0,
+ (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
+ },
+ { // UFBX_SHADER_OSL_STANDARD_SURFACE
+ ufbxi_osl_standard_shader_pbr_mapping, ufbxi_arraycount(ufbxi_osl_standard_shader_pbr_mapping),
+ ufbxi_osl_standard_shader_features, ufbxi_arraycount(ufbxi_osl_standard_shader_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
+ | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
+ },
+ { // UFBX_SHADER_ARNOLD_STANDARD_SURFACE
+ ufbxi_arnold_shader_pbr_mapping, ufbxi_arraycount(ufbxi_arnold_shader_pbr_mapping),
+ ufbxi_arnold_shader_features, ufbxi_arraycount(ufbxi_arnold_shader_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
+ | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
+ },
+ { // UFBX_SHADER_3DS_MAX_PHYSICAL_MATERIAL
+ ufbxi_3ds_max_physical_material_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_physical_material_pbr_mapping),
+ ufbxi_3ds_max_physical_material_features, ufbxi_arraycount(ufbxi_3ds_max_physical_material_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_COAT
+ | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR),
+ { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
+ { NULL, 0 }, ufbxi_string_literal("_map_on"), // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_3DS_MAX_PBR_METAL_ROUGH
+ ufbxi_3ds_max_pbr_metal_rough_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_pbr_metal_rough_pbr_mapping),
+ ufbxi_3ds_max_pbr_features, ufbxi_arraycount(ufbxi_3ds_max_pbr_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_OPACITY),
+ { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
+ { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_3DS_MAX_PBR_SPEC_GLOSS
+ ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping),
+ ufbxi_3ds_max_pbr_features, ufbxi_arraycount(ufbxi_3ds_max_pbr_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_SPECULAR | UFBXI_MAT_DIFFUSE | UFBXI_MAT_OPACITY),
+ { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
+ { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_GLTF_MATERIAL
+ ufbxi_gltf_material_pbr_mapping, ufbxi_arraycount(ufbxi_gltf_material_pbr_mapping),
+ ufbxi_gltf_material_features, ufbxi_arraycount(ufbxi_gltf_material_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_AMBIENT_OCCLUSION),
+ { NULL, 0 }, ufbxi_string_literal("Map"), // texture_prefix/suffix
+ { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_OPENPBR_MATERIAL
+ ufbxi_openpbr_material_pbr_mapping, ufbxi_arraycount(ufbxi_openpbr_material_pbr_mapping),
+ ufbxi_openpbr_material_features, ufbxi_arraycount(ufbxi_openpbr_material_features),
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
+ | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
+ { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
+ { NULL, 0 }, ufbxi_string_literal("_map_on"), // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_SHADERFX_GRAPH
+ ufbxi_shaderfx_graph_pbr_mapping, ufbxi_arraycount(ufbxi_shaderfx_graph_pbr_mapping),
+ NULL, 0,
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_AMBIENT_OCCLUSION),
+ ufbxi_string_literal("TEX_"), ufbxi_string_literal("_map"), // texture_prefix/suffix
+ ufbxi_string_literal("use_"), ufbxi_string_literal("_map"), // texture_enabled_prefix/suffix
+ },
+ { // UFBX_SHADER_BLENDER_PHONG
+ ufbxi_blender_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_blender_phong_shader_pbr_mapping),
+ NULL, 0,
+ (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION),
+ },
+ { // UFBX_SHADER_WAVEFRONT_MTL
+ ufbxi_obj_pbr_mapping, ufbxi_arraycount(ufbxi_obj_pbr_mapping),
+ ufbxi_obj_features, ufbxi_arraycount(ufbxi_obj_features),
+ (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR),
+ },
+};
+
+ufbx_static_assert(shader_pbr_mapping_list, ufbxi_arraycount(ufbxi_shader_pbr_mappings) == UFBX_SHADER_TYPE_COUNT);
+
+enum {
+ UFBXI_MAPPING_FETCH_VALUE = 0x1,
+ UFBXI_MAPPING_FETCH_TEXTURE = 0x2,
+ UFBXI_MAPPING_FETCH_TEXTURE_ENABLED = 0x4,
+ UFBXI_MAPPING_FETCH_FEATURE = 0x8,
+};
+
+ufbxi_noinline static void ufbxi_fetch_mapping_maps(ufbx_material *material, ufbx_material_map *maps, ufbx_material_feature_info *features,
+ ufbx_shader *shader, const ufbxi_shader_mapping *mappings, size_t count, ufbx_string prefix, ufbx_string prefix2, ufbx_string suffix, uint32_t flags)
+{
+ char combined_name[512];
+ ufbx_shader_prop_binding identity_binding;
+
+ ufbxi_for(const ufbxi_shader_mapping, mapping, mappings, count) {
+ ufbx_string prop_name = { mapping->prop, mapping->prop_len };
+ if (prefix.length > 0 || prefix2.length > 0 || suffix.length > 0) {
+ if (prop_name.length + prefix.length + prefix2.length + suffix.length <= sizeof(combined_name)) {
+ char *dst = combined_name;
+
+ if (prefix.length > 0) {
+ memcpy(dst, prefix.data, prefix.length);
+ dst += prefix.length;
+ }
+ if (prefix2.length > 0) {
+ memcpy(dst, prefix2.data, prefix2.length);
+ dst += prefix2.length;
+ }
+ if (prop_name.length > 0) {
+ memcpy(dst, prop_name.data, prop_name.length);
+ dst += prop_name.length;
+ }
+ if (suffix.length > 0) {
+ memcpy(dst, suffix.data, suffix.length);
+ dst += suffix.length;
+ }
+
+ prop_name.data = combined_name;
+ prop_name.length = ufbxi_to_size(dst - combined_name);
+ }
+ }
+
+ ufbx_shader_prop_binding_list bindings = ufbx_find_shader_prop_bindings_len(shader, prop_name.data, prop_name.length);
+ if (bindings.count == 0) {
+ identity_binding.material_prop = prop_name;
+ identity_binding.shader_prop = ufbx_empty_string;
+ bindings.data = &identity_binding;
+ bindings.count = 1;
+ }
+
+ uint32_t mapping_flags = mapping->flags;
+ ufbxi_for_list(ufbx_shader_prop_binding, binding, bindings) {
+ ufbx_string name = binding->material_prop;
+
+ ufbx_prop *prop = ufbx_find_prop_len(&material->props, name.data, name.length);
+ if (flags & UFBXI_MAPPING_FETCH_FEATURE) {
+ ufbx_material_feature_info *feature = &features[mapping->index];
+ if (prop && prop->type != UFBX_PROP_REFERENCE) {
+ feature->enabled = prop->value_int != 0;
+ feature->is_explicit = true;
+ if (mapping_flags & UFBXI_SHADER_FEATURE_IF_AROUND_1) {
+ feature->enabled = (prop->value_real >= 0.5f && prop->value_real <= 1.5f);
+ }
+ if (mapping_flags & UFBXI_SHADER_FEATURE_INVERTED) {
+ feature->enabled = !feature->enabled;
+ }
+ if (mapping_flags & UFBXI_SHADER_FEATURE_IF_EXISTS) {
+ feature->enabled = true;
+ }
+ }
+ if (mapping_flags & UFBXI_SHADER_FEATURE_IF_TEXTURE) {
+ ufbx_texture *texture = ufbx_find_prop_texture_len(material, name.data, name.length);
+ if (texture) {
+ feature->enabled = true;
+ }
+ }
+ continue;
+ }
+
+ ufbx_material_map *map = &maps[mapping->index];
+
+ if (flags & UFBXI_MAPPING_FETCH_VALUE) {
+ if (prop && prop->type != UFBX_PROP_REFERENCE) {
+ if ((mapping->flags & UFBXI_SHADER_MAPPING_MULTIPLY_VALUE) != 0) {
+ map->value_vec4.x *= prop->value_vec4.x;
+ map->value_int = ufbxi_f64_to_i64(map->value_vec4.x);
+ } else {
+ map->value_vec4 = prop->value_vec4;
+ map->value_int = prop->value_int;
+ }
+ map->has_value = true;
+ if (mapping->transform) {
+ ufbxi_mat_transform_fn transform_fn = ufbxi_mat_transform_fns[mapping->transform];
+ transform_fn(&map->value_vec4);
+ }
+
+ uint32_t prop_flags = (uint32_t)prop->flags;
+ if ((mapping->flags & UFBXI_SHADER_MAPPING_DEFAULT_W_1) != 0 && (prop_flags & UFBX_PROP_FLAG_VALUE_VEC4) == 0) {
+ map->value_vec4.w = 1.0f;
+ }
+ if ((mapping->flags & UFBXI_SHADER_MAPPING_WIDEN_TO_RGB) != 0 && (prop_flags & UFBX_PROP_FLAG_VALUE_REAL) != 0) {
+ map->value_vec3.y = map->value_vec3.x;
+ map->value_vec3.z = map->value_vec3.x;
+ }
+ if ((prop_flags & UFBX_PROP_FLAG_VALUE_REAL) != 0) {
+ map->value_components = 1;
+ } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC2) != 0) {
+ map->value_components = 2;
+ } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC3) != 0) {
+ map->value_components = 3;
+ } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC4) != 0) {
+ map->value_components = 4;
+ } else {
+ map->value_components = 0;
+ }
+ }
+ }
+
+ if (flags & UFBXI_MAPPING_FETCH_TEXTURE) {
+ ufbx_texture *texture = ufbx_find_prop_texture_len(material, name.data, name.length);
+ if (texture) {
+ map->texture = texture;
+ map->texture_enabled = true;
+ }
+ }
+
+ if (flags & UFBXI_MAPPING_FETCH_TEXTURE_ENABLED) {
+ if (prop) {
+ map->texture_enabled = prop->value_int != 0;
+ }
+ }
+ }
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_factor(ufbx_material_map *factor_map, ufbx_material_map *color_map)
+{
+ if (!factor_map->has_value) {
+ if (color_map->has_value && !ufbxi_is_vec4_zero(color_map->value_vec4)) {
+ factor_map->value_real = 1.0f;
+ factor_map->value_int = 1;
+ } else {
+ factor_map->value_real = 0.0f;
+ factor_map->value_int = 0;
+ }
+ }
+}
+
+// Some material modes have toggleable roughness/glossiness mode, we read it initially
+// always as roughness and if a matching feature such as `roughness_as_glossiness` is set
+// we transfer the data into the glossiness and invert the roughness.
+typedef struct {
+ uint8_t feature;
+ uint8_t roughness_map;
+ uint8_t glossiness_map;
+} ufbxi_glossiness_remap;
+
+static const ufbxi_glossiness_remap ufbxi_glossiness_remaps[] = {
+ { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_ROUGHNESS, UFBX_MATERIAL_PBR_GLOSSINESS },
+ { UFBX_MATERIAL_FEATURE_COAT_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_COAT_ROUGHNESS, UFBX_MATERIAL_PBR_COAT_GLOSSINESS },
+ { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, UFBX_MATERIAL_PBR_TRANSMISSION_GLOSSINESS },
+};
+
+ufbxi_noinline static void ufbxi_fetch_maps(ufbx_scene *scene, ufbx_material *material)
+{
+ (void)scene;
+
+ ufbx_shader *shader = material->shader;
+ ufbx_assert((uint32_t)material->shader_type < UFBX_SHADER_TYPE_COUNT);
+
+ memset(&material->fbx, 0, sizeof(material->fbx));
+ memset(&material->pbr, 0, sizeof(material->pbr));
+ memset(&material->features, 0, sizeof(material->features));
+
+ const ufbxi_shader_mapping *base_mapping = ufbxi_base_fbx_mapping;
+ size_t num_base_mapping = ufbxi_arraycount(ufbxi_base_fbx_mapping);
+
+ if (scene->metadata.file_format == UFBX_FILE_FORMAT_OBJ || scene->metadata.file_format == UFBX_FILE_FORMAT_MTL) {
+ base_mapping = ufbxi_obj_fbx_mapping;
+ num_base_mapping = ufbxi_arraycount(ufbxi_obj_fbx_mapping);
+ }
+
+ ufbxi_fetch_mapping_maps(material, material->fbx.maps, NULL, NULL,
+ base_mapping, num_base_mapping,
+ ufbx_empty_string, ufbx_empty_string, ufbx_empty_string,
+ UFBXI_MAPPING_FETCH_VALUE | UFBXI_MAPPING_FETCH_TEXTURE);
+
+ ufbxi_shader_mapping_list list = ufbxi_shader_pbr_mappings[material->shader_type];
+
+ for (uint32_t i = 0; i < UFBX_MATERIAL_FEATURE_COUNT; i++) {
+ if ((list.default_features & (1u << i)) != 0) {
+ material->features.features[i].enabled = true;
+ }
+ }
+
+ ufbx_string prefix = ufbx_empty_string;
+ if (!shader) {
+ prefix = material->shader_prop_prefix;
+ }
+
+ if (list.texture_prefix.length > 0 || list.texture_suffix.length > 0) {
+ ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
+ list.data, list.count, prefix, list.texture_prefix, list.texture_suffix,
+ UFBXI_MAPPING_FETCH_TEXTURE);
+ }
+
+ ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
+ list.data, list.count, prefix, ufbx_empty_string, ufbx_empty_string,
+ UFBXI_MAPPING_FETCH_VALUE | UFBXI_MAPPING_FETCH_TEXTURE);
+
+ if (list.texture_enabled_prefix.length > 0 || list.texture_enabled_suffix.length > 0) {
+ ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
+ list.data, list.count, prefix, list.texture_enabled_prefix, list.texture_enabled_suffix,
+ UFBXI_MAPPING_FETCH_TEXTURE_ENABLED);
+ }
+
+ ufbxi_fetch_mapping_maps(material, NULL, material->features.features, shader,
+ list.features, list.feature_count, prefix, ufbx_empty_string, ufbx_empty_string,
+ UFBXI_MAPPING_FETCH_FEATURE);
+
+ ufbxi_update_factor(&material->fbx.diffuse_factor, &material->fbx.diffuse_color);
+ ufbxi_update_factor(&material->fbx.specular_factor, &material->fbx.specular_color);
+ ufbxi_update_factor(&material->fbx.reflection_factor, &material->fbx.reflection_color);
+ ufbxi_update_factor(&material->fbx.transparency_factor, &material->fbx.transparency_color);
+ ufbxi_update_factor(&material->fbx.emission_factor, &material->fbx.emission_color);
+ ufbxi_update_factor(&material->fbx.ambient_factor, &material->fbx.ambient_color);
+
+ ufbxi_update_factor(&material->pbr.base_factor, &material->pbr.base_color);
+ ufbxi_update_factor(&material->pbr.specular_factor, &material->pbr.specular_color);
+ ufbxi_update_factor(&material->pbr.emission_factor, &material->pbr.emission_color);
+ ufbxi_update_factor(&material->pbr.sheen_factor, &material->pbr.sheen_color);
+ ufbxi_update_factor(&material->pbr.thin_film_factor, &material->pbr.thin_film_thickness);
+ ufbxi_update_factor(&material->pbr.transmission_factor, &material->pbr.transmission_color);
+
+ // Patch transmission roughness if only extra roughness is defined
+ if (!material->pbr.transmission_roughness.has_value && material->pbr.roughness.has_value && material->pbr.transmission_extra_roughness.has_value) {
+ material->pbr.transmission_roughness.value_real = material->pbr.roughness.value_real + material->pbr.transmission_extra_roughness.value_real;
+ }
+
+ // Map roughness to glossiness and vice versa
+ ufbxi_for(const ufbxi_glossiness_remap, remap, ufbxi_glossiness_remaps, ufbxi_arraycount(ufbxi_glossiness_remaps)) {
+ ufbx_material_map *roughness = &material->pbr.maps[remap->roughness_map];
+ ufbx_material_map *glossiness = &material->pbr.maps[remap->glossiness_map];
+ if (material->features.features[remap->feature].enabled) {
+ *glossiness = *roughness;
+ memset(roughness, 0, sizeof(ufbx_material_map));
+ if (glossiness->has_value) {
+ roughness->value_real = 1.0f - glossiness->value_real;
+ }
+ } else {
+ if (roughness->has_value) {
+ glossiness->value_real = 1.0f - roughness->value_real;
+ }
+ }
+ }
+}
+
+typedef enum {
+ UFBXI_CONSTRAINT_PROP_NODE,
+ UFBXI_CONSTRAINT_PROP_IK_EFFECTOR,
+ UFBXI_CONSTRAINT_PROP_IK_END_NODE,
+ UFBXI_CONSTRAINT_PROP_AIM_UP,
+ UFBXI_CONSTRAINT_PROP_TARGET,
+} ufbxi_constraint_prop_type;
+
+typedef struct {
+ ufbxi_constraint_prop_type type;
+ const char *name;
+} ufbxi_constraint_prop;
+
+static const ufbxi_constraint_prop ufbxi_constraint_props[] = {
+ { UFBXI_CONSTRAINT_PROP_NODE, "Constrained Object" },
+ { UFBXI_CONSTRAINT_PROP_NODE, "Constrained object (Child)" },
+ { UFBXI_CONSTRAINT_PROP_NODE, "First Joint" },
+ { UFBXI_CONSTRAINT_PROP_TARGET, "Source" },
+ { UFBXI_CONSTRAINT_PROP_TARGET, "Source (Parent)" },
+ { UFBXI_CONSTRAINT_PROP_TARGET, "Aim At Object" },
+ { UFBXI_CONSTRAINT_PROP_TARGET, "Pole Vector Object" },
+ { UFBXI_CONSTRAINT_PROP_IK_EFFECTOR, "Effector" },
+ { UFBXI_CONSTRAINT_PROP_IK_END_NODE, "End Joint" },
+ { UFBXI_CONSTRAINT_PROP_AIM_UP, "World Up Object" },
+};
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_add_constraint_prop(ufbxi_context *uc, ufbx_constraint *constraint, ufbx_node *node, const char *prop)
+{
+ ufbxi_for(const ufbxi_constraint_prop, cprop, ufbxi_constraint_props, ufbxi_arraycount(ufbxi_constraint_props)) {
+ if (strcmp(cprop->name, prop) != 0) continue;
+ switch (cprop->type) {
+ case UFBXI_CONSTRAINT_PROP_NODE: constraint->node = node; break;
+ case UFBXI_CONSTRAINT_PROP_IK_EFFECTOR: constraint->ik_effector = node; break;
+ case UFBXI_CONSTRAINT_PROP_IK_END_NODE: constraint->ik_end_node = node; break;
+ case UFBXI_CONSTRAINT_PROP_AIM_UP: constraint->aim_up_node = node; break;
+ case UFBXI_CONSTRAINT_PROP_TARGET: {
+ ufbx_constraint_target *target = ufbxi_push_zero(&uc->tmp_stack, ufbx_constraint_target, 1);
+ ufbxi_check(target);
+ target->node = node;
+ target->weight = 1.0f;
+ target->transform = ufbx_identity_transform;
+ } break;
+ default:
+ ufbxi_unreachable("Unexpected constraint prop");
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_nurbs_basis(ufbxi_context *uc, ufbx_nurbs_basis *basis)
+{
+ // Check that the basis is reasonable, and so we don't overflow in later code.
+ ufbxi_check(basis->order < UINT32_MAX / 4);
+
+ if (basis->topology == UFBX_NURBS_TOPOLOGY_CLOSED) {
+ basis->num_wrap_control_points = 1;
+ } else if (basis->topology == UFBX_NURBS_TOPOLOGY_PERIODIC) {
+ basis->num_wrap_control_points = basis->order - 1;
+ } else {
+ basis->num_wrap_control_points = 0;
+ }
+
+ if (basis->order > 1) {
+ size_t degree = basis->order - 1;
+ ufbx_real_list knots = basis->knot_vector;
+ if (knots.count >= 2*degree + 1) {
+ basis->t_min = knots.data[degree];
+ basis->t_max = knots.data[knots.count - degree - 1];
+
+ size_t max_spans = knots.count - 2*degree;
+ ufbx_real *spans = ufbxi_push(&uc->result, ufbx_real, max_spans);
+ ufbxi_check(spans);
+
+ ufbx_real prev = -UFBX_INFINITY;
+ size_t num_spans = 0;
+ for (size_t i = 0; i < max_spans; i++) {
+ ufbx_real t = knots.data[degree + i];
+ if (t != prev) {
+ spans[num_spans++] = t;
+ prev = t;
+ }
+ }
+
+ basis->spans.data = spans;
+ basis->spans.count = num_spans;
+ basis->valid = true;
+ for (size_t i = 1; i < knots.count; i++) {
+ if (knots.data[i - 1] > knots.data[i]) {
+ basis->valid = false;
+ break;
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_lod_group(ufbxi_context *uc, ufbx_lod_group *lod)
+{
+ size_t num_levels = 0;
+ for (size_t i = 0; i < lod->instances.count; i++) {
+ num_levels = ufbxi_max_sz(num_levels, lod->instances.data[0]->children.count);
+ }
+
+ char prop_name[64];
+ for (size_t i = 0; ; i++) {
+ int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "Thresholds|Level%zu", i);
+ ufbx_prop *prop = ufbx_find_prop_len(&lod->props, prop_name, (size_t)len);
+ if (!prop) break;
+ num_levels = ufbxi_max_sz(num_levels, i + 1);
+ }
+
+ ufbx_lod_level *levels = ufbxi_push_zero(&uc->result, ufbx_lod_level, num_levels);
+ ufbxi_check(levels);
+
+ lod->relative_distances = ufbx_find_bool(&lod->props, "ThresholdsUsedAsPercentage", false);
+ lod->ignore_parent_transform = !ufbx_find_bool(&lod->props, "WorldSpace", true);
+
+ lod->use_distance_limit = ufbx_find_bool(&lod->props, "MinMaxDistance", false);
+ lod->distance_limit_min = ufbx_find_real(&lod->props, "MinDistance", (ufbx_real)-100.0);
+ lod->distance_limit_max = ufbx_find_real(&lod->props, "MaxDistance", (ufbx_real)100.0);
+
+ lod->lod_levels.data = levels;
+ lod->lod_levels.count = num_levels;
+
+ for (size_t i = 0; i < num_levels; i++) {
+ ufbx_lod_level *level = &levels[i];
+
+ if (i > 0) {
+ int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "Thresholds|Level%zu", i - 1);
+ level->distance = ufbx_find_real_len(&lod->props, prop_name, (size_t)len, 0.0f);
+ } else if (lod->relative_distances) {
+ level->distance = (ufbx_real)100.0;
+ }
+
+ {
+ int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "DisplayLevels|Level%zu", i);
+ int64_t display = ufbx_find_int_len(&lod->props, prop_name, (size_t)len, 0);
+ if (display >= 0 && display <= 2) {
+ level->display = (ufbx_lod_display)display;
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_generate_normals(ufbxi_context *uc, ufbx_mesh *mesh)
+{
+ size_t num_indices = mesh->num_indices;
+
+ mesh->generated_normals = true;
+
+ ufbx_topo_edge *topo = ufbxi_push(&uc->tmp_stack, ufbx_topo_edge, num_indices);
+ ufbxi_check(topo);
+
+ uint32_t *normal_indices = ufbxi_push(&uc->result, uint32_t, num_indices);
+ ufbxi_check(normal_indices);
+
+ ufbx_compute_topology(mesh, topo, num_indices);
+ size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, num_indices, normal_indices, num_indices, false);
+
+ if (num_normals == mesh->num_vertices) {
+ mesh->vertex_normal.unique_per_vertex = true;
+ }
+
+ ufbx_vec3 *normal_data = ufbxi_push(&uc->result, ufbx_vec3, num_normals + 1);
+ ufbxi_check(normal_data);
+
+ normal_data[0] = ufbx_zero_vec3;
+ normal_data++;
+
+ ufbx_compute_normals(mesh, &mesh->vertex_position, normal_indices, num_indices, normal_data, num_normals);
+
+ mesh->vertex_normal.exists = true;
+ mesh->vertex_normal.values.data = normal_data;
+ mesh->vertex_normal.values.count = num_normals;
+ mesh->vertex_normal.indices.data = normal_indices;
+ mesh->vertex_normal.indices.count = num_indices;
+ mesh->vertex_normal.value_reals = 3;
+
+ mesh->skinned_normal = mesh->vertex_normal;
+
+ ufbxi_pop(&uc->tmp_stack, ufbx_topo_edge, num_indices, NULL);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_prop_prefix(ufbxi_context *uc, ufbx_string *dst, ufbx_string prefix)
+{
+ size_t stack_size = 0;
+ if (prefix.length > 0 && prefix.data[prefix.length - 1] != '|') {
+ stack_size = prefix.length + 1;
+ char *copy = ufbxi_push(&uc->tmp_stack, char, stack_size);
+ ufbxi_check(copy);
+ memcpy(copy, prefix.data, prefix.length);
+ copy[prefix.length] = '|';
+
+ prefix.data = copy;
+ prefix.length += 1;
+ }
+
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prefix, false));
+ *dst = prefix;
+
+ if (stack_size > 0) {
+ ufbxi_pop(&uc->tmp_stack, char, stack_size, NULL);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_shader_texture_find_prefix(ufbxi_context *uc, ufbx_texture *texture, ufbx_shader_texture *shader)
+{
+ ufbx_string suffixes[3];
+ size_t num_suffixes = 0;
+
+ suffixes[num_suffixes++] = ufbxi_str_c(" Parameters/Connections");
+ if (shader->shader_name.length > 0) {
+ suffixes[num_suffixes++] = shader->shader_name;
+ }
+ suffixes[num_suffixes++] = ufbxi_str_c("3dsMax|parameters");
+
+ ufbx_assert(num_suffixes <= ufbxi_arraycount(suffixes));
+
+ ufbxi_for(ufbx_string, p_suffix, suffixes, num_suffixes) {
+ ufbx_string suffix = *p_suffix;
+
+ ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
+ if (prop->type != UFBX_PROP_COMPOUND) continue;
+ if (ufbxi_ends_with(prop->name, suffix)) {
+ ufbxi_check(ufbxi_push_prop_prefix(uc, &shader->prop_prefix, prop->name));
+ return 1;
+ }
+ }
+ }
+
+ // Pre-7000 files don't have explicit Compound properties, so let's look for
+ // any property that has the suffix before the last `|` ...
+ ufbxi_for(ufbx_string, p_suffix, suffixes, num_suffixes) {
+ ufbx_string suffix = *p_suffix;
+
+ ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
+ ufbx_string name = prop->name;
+ while (name.length > 0) {
+ if (name.data[name.length - 1] == '|') {
+ break;
+ }
+ name.length--;
+ }
+ if (name.length <= 1) continue;
+ name.length--;
+
+ if (ufbxi_ends_with(name, suffix)) {
+ ufbxi_check(ufbxi_push_prop_prefix(uc, &shader->prop_prefix, name));
+ return 1;
+ }
+ }
+ }
+
+ return 1;
+}
+
+typedef struct {
+ uint64_t shader_id;
+ const char *shader_name;
+ const char *input_name;
+} ufbxi_file_shader;
+
+// Known shaders that represent sampled images.
+static const ufbxi_file_shader ufbxi_file_shaders[] = {
+ { UINT64_C(0x7e73161fad53b12a), "ai_image", "filename" },
+ { 0, "OSLBitmap", ufbxi_Filename },
+ { 0, "OSLBitmap2", ufbxi_Filename },
+ { 0, "OSLBitmap3", ufbxi_Filename },
+ { 0, "UberBitmap", ufbxi_Filename },
+ { 0, "UberBitmap2", ufbxi_Filename },
+};
+
+ufbxi_noinline static void ufbxi_update_shader_texture(ufbx_texture *texture, ufbx_shader_texture *shader)
+{
+ ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
+ ufbx_prop *prop = input->prop;
+ if (prop) {
+ input->prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
+ input->value_vec4 = prop->value_vec4;
+ input->value_int = prop->value_int;
+ input->value_str = prop->value_str;
+ input->value_blob = prop->value_blob;
+ input->texture = (ufbx_texture*)ufbx_get_prop_element(&texture->element, input->prop, UFBX_ELEMENT_TEXTURE);
+ }
+
+ prop = input->texture_prop;
+ if (prop) {
+ input->texture_prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
+ ufbx_texture *tex = (ufbx_texture*)ufbx_get_prop_element(&texture->element, prop, UFBX_ELEMENT_TEXTURE);
+ if (tex) input->texture = tex;
+ }
+
+ input->texture_enabled = input->texture != NULL;
+ prop = input->texture_enabled_prop;
+ if (prop) {
+ input->texture_enabled_prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
+ input->texture_enabled = prop->value_int != 0;
+ }
+ }
+
+ if (shader->type == UFBX_SHADER_TEXTURE_SELECT_OUTPUT) {
+ ufbx_shader_texture_input *map = ufbx_find_shader_texture_input(shader, "sourceMap");
+ ufbx_shader_texture_input *index = ufbx_find_shader_texture_input(shader, "outputChannelIndex");
+ if (index) {
+ shader->main_texture_output_index = index->value_int;
+ }
+ if (map) {
+ shader->main_texture = map->texture;
+ map->texture_output_index = shader->main_texture_output_index;
+ }
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_shader_texture(ufbxi_context *uc, ufbx_texture *texture)
+{
+ uint32_t classid_a = (uint32_t)(uint64_t)ufbx_find_int(&texture->props, "3dsMax|ClassIDa", 0);
+ uint32_t classid_b = (uint32_t)(uint64_t)ufbx_find_int(&texture->props, "3dsMax|ClassIDb", 0);
+ uint64_t classid = (uint64_t)classid_a << 32u | classid_b;
+
+ ufbx_string max_texture = ufbx_find_string(&texture->props, "3dsMax|MaxTexture", ufbx_empty_string);
+
+ // Check first if the texture looks like it could be a shader.
+ ufbx_shader_texture_type type = (ufbx_shader_texture_type)UFBX_SHADER_TEXTURE_TYPE_COUNT;
+
+ if (!strcmp(max_texture.data, "MULTIOUTPUT_TO_OSLMap") || classid == UINT64_C(0x896ef2fc44bd743f)) {
+ type = UFBX_SHADER_TEXTURE_SELECT_OUTPUT;
+ } else if (!strcmp(max_texture.data, "OSLMap") || classid == UINT64_C(0x7f9a7b9d6fcdf00d)) {
+ type = UFBX_SHADER_TEXTURE_OSL;
+ } else if (texture->type == UFBX_TEXTURE_FILE && texture->relative_filename.length == 0 && texture->absolute_filename.length == 0 && !texture->video) {
+ type = UFBX_SHADER_TEXTURE_UNKNOWN;
+ }
+
+ if ((uint32_t)type == UFBX_SHADER_TEXTURE_TYPE_COUNT) return 1;
+
+ ufbx_shader_texture *shader = ufbxi_push_zero(&uc->result, ufbx_shader_texture, 1);
+ ufbxi_check(shader);
+
+ shader->type = type;
+
+ static const char *const name_props[] = {
+ "3dsMax|params|OSLShaderName",
+ };
+
+ static const char *const source_props[] = {
+ "3dsMax|params|OSLCode",
+ };
+
+ shader->shader_source.data = ufbxi_empty_char;
+ shader->shader_name.data = ufbxi_empty_char;
+
+ ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(name_props); i++) {
+ ufbx_prop *prop = ufbx_find_prop(&texture->props, name_props[i]);
+ if (prop) {
+ shader->shader_name = prop->value_str;
+ break;
+ }
+ }
+
+ ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(source_props); i++) {
+ ufbx_prop *prop = ufbx_find_prop(&texture->props, source_props[i]);
+ if (prop) {
+ shader->shader_source = prop->value_str;
+ shader->raw_shader_source = prop->value_blob;
+ break;
+ }
+ }
+
+ ufbxi_check(ufbxi_shader_texture_find_prefix(uc, texture, shader));
+
+ if (shader->shader_name.length == 0) {
+ ufbx_string name = shader->prop_prefix;
+ if (ufbxi_remove_suffix_c(&name, " Parameters/Connections|")) {
+ size_t begin = name.length;
+ while (begin > 0 && name.data[begin - 1] != '|') {
+ begin--;
+ }
+
+ shader->shader_name.data = name.data + begin;
+ shader->shader_name.length = name.length - begin;
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &shader->shader_name, false));
+ }
+ }
+
+ if (shader->shader_name.length == 0) {
+ if (max_texture.length > 0) {
+ shader->shader_name = max_texture;
+ }
+ }
+
+ if (classid != 0) {
+ shader->shader_type_id = classid;
+ }
+
+ if (shader->prop_prefix.length == 0) {
+ // If we not find any shader properties so we might have guessed wrong.
+ // We "leak" (freed with scene) the shader in this case but it's negligible.
+ return 1;
+ }
+
+ ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
+
+ ufbx_string name = prop->name;
+ if (!ufbxi_remove_prefix_str(&name, shader->prop_prefix)) continue;
+
+ // Check if this property is a modifier to an existing input.
+ ufbx_string base_name = name;
+ if (ufbxi_remove_suffix_c(&base_name, "_map") || ufbxi_remove_suffix_c(&base_name, ".shader")) {
+ ufbx_shader_texture_input *base = ufbx_find_shader_texture_input_len(shader, base_name.data, base_name.length);
+ if (base) {
+ base->texture_prop = prop;
+ continue;
+ }
+ } else if (ufbxi_remove_suffix_c(&base_name, ".connected") || ufbxi_remove_suffix_c(&base_name, "Enabled")) {
+ ufbx_shader_texture_input *base = ufbx_find_shader_texture_input_len(shader, base_name.data, base_name.length);
+ if (base) {
+ base->texture_enabled_prop = prop;
+ continue;
+ }
+ }
+
+ // Use `uc->tmp_arr` to store the texture inputs so we can search them while we insert new ones.
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size,
+ (shader->inputs.count + 1) * sizeof(ufbx_shader_texture_input)));
+ shader->inputs.data = (ufbx_shader_texture_input*)uc->tmp_arr;
+
+ // Add a new property
+ ufbx_shader_texture_input *input = &shader->inputs.data[shader->inputs.count++];
+ memset(input, 0, sizeof(ufbx_shader_texture_input));
+
+ // NOTE: This is a bit hackish, we are using a suffix of an interned string. It won't compare
+ // pointer equal to the same string but that shouldn't matter..
+ input->name = name;
+
+ // Connect the property only, values and textures etc are fetched in `ufbxi_update_shader_texture()`.
+ input->prop = prop;
+ }
+
+ // Retain the shader inputs
+ shader->inputs.data = ufbxi_push_copy(&uc->result, ufbx_shader_texture_input, shader->inputs.count, shader->inputs.data);
+ ufbxi_check(shader->inputs.data);
+
+ texture->shader = shader;
+ texture->type = UFBX_TEXTURE_SHADER;
+ uc->scene.metadata.num_shader_textures++;
+
+ if (!uc->opts.disable_quirks) {
+ ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(ufbxi_file_shaders); i++) {
+ const ufbxi_file_shader *fs = &ufbxi_file_shaders[i];
+
+ if ((fs->shader_id && shader->shader_type_id == fs->shader_id) || !strcmp(shader->shader_name.data, fs->shader_name)) {
+ ufbx_shader_texture_input *input = ufbx_find_shader_texture_input(shader, fs->input_name);
+ if (input) {
+ // TODO: Support for specifying relative filename here if ever needed
+ ufbx_prop *prop = input->prop;
+ texture->absolute_filename = prop->value_str;
+ texture->raw_absolute_filename = prop->value_blob;
+ texture->type = UFBX_TEXTURE_FILE;
+ break;
+ }
+ }
+ }
+ }
+
+ ufbxi_update_shader_texture(texture, shader);
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_propagate_main_textures(ufbx_scene *scene)
+{
+ // We need to do at least 2^(N-1) passes for N shader textures
+ size_t mask = scene->metadata.num_shader_textures;
+ while (mask) {
+ mask >>= 1;
+
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
+ ufbx_texture *texture = *p_texture;
+ ufbx_shader_texture *shader = texture->shader;
+ if (!shader) continue;
+
+ ufbx_texture *main_tex = shader->main_texture;
+ if (!main_tex || shader->main_texture_output_index != 0) continue;
+
+ ufbx_shader_texture *main_shader = main_tex->shader;
+ if (!main_shader || !main_shader->main_texture) continue;
+
+ shader->main_texture = main_shader->main_texture;
+ shader->main_texture_output_index = main_shader->main_texture_output_index;
+ }
+ }
+
+ // Remove cyclic main textures
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
+ ufbx_texture *texture = *p_texture;
+ ufbx_shader_texture *shader = texture->shader;
+ if (!shader || !shader->main_texture || shader->main_texture_output_index != 0) continue;
+ ufbx_texture *main_tex = shader->main_texture;
+ if (main_tex && main_tex->shader && main_tex->shader->main_texture) {
+ // Should have been propagated to `texture`
+ shader->main_texture = NULL;
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
+ ufbx_texture *texture = *p_texture;
+ ufbx_shader_texture *shader = texture->shader;
+ if (!shader) continue;
+
+ ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
+ if (!input->texture || !input->texture->shader) continue;
+ ufbx_shader_texture *input_shader = input->texture->shader;
+ if (input_shader->main_texture) {
+ input->texture = input_shader->main_texture;
+ input->texture_output_index = input_shader->main_texture_output_index;
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_material, p_material, scene->materials) {
+ ufbx_material *material = *p_material;
+
+ ufbxi_for_list(ufbx_material_texture, tex, material->textures) {
+ ufbx_shader_texture *shader = tex->texture->shader;
+ if (shader && shader->main_texture && shader->main_texture_output_index == 0) {
+ tex->texture = shader->main_texture;
+ }
+ }
+ }
+}
+
+#define ufbxi_patch_empty(m_dst, m_len, m_src) \
+ do { if (!(m_dst).m_len) m_dst = m_src; } while (0)
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_texture_file(ufbxi_context *uc, ufbx_texture *texture)
+{
+ texture->file_index = UFBX_NO_INDEX;
+
+ const char *key = NULL;
+
+ // HACK: Even the raw entries have a null terminator so we can offset the
+ // pointer by one for relative filenames. This guarantees that an overlapping
+ // absolute and relative filenames will get separate textures.
+ if (texture->raw_absolute_filename.size > 0) {
+ key = (const char*)texture->raw_absolute_filename.data;
+ } else if (texture->raw_relative_filename.size > 0) {
+ key = (const char*)texture->raw_relative_filename.data + 1;
+ }
+
+ if (key == NULL) return 1;
+ uint32_t hash = ufbxi_hash_ptr(key);
+ ufbxi_texture_file_entry *entry = ufbxi_map_find(&uc->texture_file_map, ufbxi_texture_file_entry, hash, &key);
+ if (!entry) {
+ entry = ufbxi_map_insert(&uc->texture_file_map, ufbxi_texture_file_entry, hash, &key);
+ ufbxi_check(entry);
+
+ ufbx_texture_file *file = ufbxi_push_zero(&uc->tmp, ufbx_texture_file, 1);
+ ufbxi_check(file);
+
+ file->index = uc->texture_file_map.size - 1;
+
+ entry->key = key;
+ entry->file = file;
+ }
+
+ ufbx_texture_file *file = entry->file;
+ texture->file_index = file->index;
+ texture->has_file = true;
+ ufbxi_patch_empty(file->filename, length, texture->filename);
+ ufbxi_patch_empty(file->relative_filename, length, texture->relative_filename);
+ ufbxi_patch_empty(file->absolute_filename, length, texture->absolute_filename);
+ ufbxi_patch_empty(file->raw_filename, size, texture->raw_filename);
+ ufbxi_patch_empty(file->raw_relative_filename, size, texture->raw_relative_filename);
+ ufbxi_patch_empty(file->raw_absolute_filename, size, texture->raw_absolute_filename);
+ ufbxi_patch_empty(file->content, size, texture->content);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_pop_texture_files(ufbxi_context *uc)
+{
+ uint32_t num_files = uc->texture_file_map.size;
+ ufbx_texture_file *files = ufbxi_push(&uc->result, ufbx_texture_file, num_files);
+ ufbxi_check(files);
+
+ uc->scene.texture_files.data = files;
+ uc->scene.texture_files.count = num_files;
+
+ ufbxi_texture_file_entry *entries = (ufbxi_texture_file_entry*)uc->texture_file_map.items;
+ for (size_t i = 0; i < num_files; i++) {
+ memcpy(&files[i], entries[i].file, sizeof(ufbx_texture_file));
+ }
+
+ return 1;
+}
+
+typedef struct {
+ ufbx_texture *texture;
+ size_t order;
+} ufbxi_ordered_texture;
+
+ufbxi_noinline static bool ufbxi_ordered_texture_less_texture(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_ordered_texture *a = (const ufbxi_ordered_texture*)va, *b = (const ufbxi_ordered_texture*)vb;
+ return a->texture < b->texture;
+}
+
+ufbxi_noinline static bool ufbxi_ordered_texture_less_order(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_ordered_texture *a = (const ufbxi_ordered_texture*)va, *b = (const ufbxi_ordered_texture*)vb;
+ return a->order < b->order;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_deduplicate_textures(ufbxi_context *uc, ufbxi_buf *dst_buf, ufbxi_ordered_texture **p_dst, size_t *p_dst_count, size_t count)
+{
+ ufbxi_ordered_texture *textures = ufbxi_push_pop(dst_buf, &uc->tmp_stack, ufbxi_ordered_texture, count);
+ ufbxi_check(textures);
+
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_ordered_texture)));
+
+ ufbxi_stable_sort(sizeof(ufbxi_ordered_texture), 16, textures, uc->tmp_arr, count, &ufbxi_ordered_texture_less_texture, NULL);
+
+ // Remove adjacent duplicates
+ size_t dst_ix = 0;
+ for (size_t src_ix = 0; src_ix < count; src_ix++) {
+ if (src_ix > 0 && textures[src_ix - 1].texture == textures[src_ix].texture) {
+ continue;
+ } else {
+ if (src_ix != dst_ix) {
+ textures[dst_ix] = textures[src_ix];
+ }
+ dst_ix++;
+ }
+ }
+
+ size_t new_count = dst_ix;
+ ufbxi_stable_sort(sizeof(ufbxi_ordered_texture), 16, textures, uc->tmp_arr, new_count, &ufbxi_ordered_texture_less_order, NULL);
+
+ *p_dst_count = new_count;
+ *p_dst = textures;
+
+ return 1;
+}
+
+typedef enum {
+ UFBXI_FILE_TEXTURE_FETCH_INITIAL,
+ UFBXI_FILE_TEXTURE_FETCH_STARTED,
+ UFBXI_FILE_TEXTURE_FETCH_FINISHED,
+} ufbxi_file_texture_fetch_state;
+
+// Populate `ufbx_texture.file_textures[]` arrays.
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_file_textures(ufbxi_context *uc)
+{
+ // We keep pointers to `ufbx_texture` in `tmp_stack` as a working set, since we don't know
+ // how deep the shader graphs might be.
+
+ // Start by pushing all the textures into the stack
+ size_t num_stack_textures = uc->scene.textures.count;
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, num_stack_textures, uc->scene.textures.data));
+
+ // Compressed `ufbxi_file_texture_fetch_state`
+ uint8_t *states = ufbxi_push_zero(&uc->tmp, uint8_t, uc->scene.textures.count);
+ ufbxi_check(states);
+
+ while (num_stack_textures-- > 0) {
+ ufbx_texture *texture = NULL;
+ ufbxi_pop(&uc->tmp_stack, ufbx_texture*, 1, &texture);
+
+ ufbxi_file_texture_fetch_state state = (ufbxi_file_texture_fetch_state)states[texture->typed_id];
+ if (state == UFBXI_FILE_TEXTURE_FETCH_FINISHED) continue;
+ ufbx_shader_texture *shader = texture->shader;
+
+ if (state == UFBXI_FILE_TEXTURE_FETCH_STARTED) {
+ states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_FINISHED;
+
+ // HACK: Reuse `tmp_parse` for storing intermediate information as we can clear it.
+ ufbxi_buf_clear(&uc->tmp_parse);
+
+ // Now all non-cyclical dependents should be processed.
+ size_t num_deps = 0;
+
+ if (texture->type == UFBX_TEXTURE_FILE) {
+ ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
+ ufbxi_check(dst);
+ dst->texture = texture;
+ dst->order = num_deps++;
+ }
+
+ ufbxi_for_list(ufbx_texture_layer, layer, texture->layers) {
+ ufbx_texture *dep_tex = layer->texture;
+ if (dep_tex->file_textures.count > 0) {
+ ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
+ ufbxi_check(dst);
+ dst->texture = dep_tex;
+ dst->order = num_deps++;
+ }
+ }
+
+ if (shader) {
+ ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
+ ufbx_texture *dep_tex = input->texture;
+ if (dep_tex && dep_tex->file_textures.count > 0) {
+ ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
+ ufbxi_check(dst);
+ dst->texture = dep_tex;
+ dst->order = num_deps++;
+ }
+ }
+ }
+
+ // Deduplicate the direct dependencies first
+ ufbxi_ordered_texture *deps;
+ ufbxi_check(ufbxi_deduplicate_textures(uc, &uc->tmp_parse, &deps, &num_deps, num_deps));
+
+ if (num_deps == 1) {
+ // If we have only a single dependency (that is not the same one) we can just copy the pointer
+ texture->file_textures = deps[0].texture->file_textures;
+ } else {
+ // Now collect all the file textures and deduplicate them
+ size_t num_files = 0;
+ ufbxi_for(ufbxi_ordered_texture, dep, deps, num_deps) {
+ ufbxi_for_ptr_list(ufbx_texture, p_tex, dep->texture->file_textures) {
+ ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
+ ufbxi_check(dst);
+ dst->texture = *p_tex;
+ dst->order = num_files++;
+ }
+ }
+
+ // Deduplicate the file textures
+ ufbxi_ordered_texture *files;
+ ufbxi_check(ufbxi_deduplicate_textures(uc, &uc->tmp_parse, &files, &num_files, num_files));
+
+ texture->file_textures.count = num_files;
+ texture->file_textures.data = ufbxi_push(&uc->result, ufbx_texture*, num_files);
+ ufbxi_check(texture->file_textures.data);
+
+ for (size_t i = 0; i < num_files; i++) {
+ texture->file_textures.data[i] = files[i].texture;
+ }
+ }
+
+ } else {
+ if (texture->type == UFBX_TEXTURE_FILE) {
+ // Simple case: Just point to self
+ texture->file_textures.count = 1;
+ texture->file_textures.data = ufbxi_push(&uc->result, ufbx_texture*, 1);
+ ufbxi_check(texture->file_textures.data);
+ texture->file_textures.data[0] = texture;
+
+ // In simple cases we can quit here, for more complex file textures queue
+ // the texture in case there are other file textures as inputs.
+ if (!texture->shader) {
+ states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_FINISHED;
+ continue;
+ }
+ }
+
+ // Complex: Process all dependencies first
+ states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_STARTED;
+
+ // Push self first so we can return after processing dependencies
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &texture));
+ num_stack_textures++;
+
+ ufbxi_for_list(ufbx_texture_layer, layer, texture->layers) {
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &layer->texture));
+ num_stack_textures++;
+ }
+
+ if (shader) {
+ ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
+ if (input->texture) {
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &input->texture));
+ num_stack_textures++;
+ }
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static ufbx_node *ufbxi_get_geometry_transform_node(ufbx_element *element)
+{
+ if (element->instances.count == 1) {
+ ufbx_node *node = element->instances.data[0];
+ if (node->has_geometry_transform) return node;
+ }
+ return NULL;
+}
+
+ufbxi_noinline static void ufbxi_mirror_vec3_list(const void *v_list, ufbx_mirror_axis axis, size_t stride)
+{
+ const ufbx_void_list *list = (const ufbx_void_list*)v_list;
+ if (axis == UFBX_MIRROR_AXIS_NONE || !list || list->count == 0) return;
+ if (!stride) stride = sizeof(ufbx_vec3);
+
+ void *ptr = (char*)list->data + (size_t)((int)axis - 1) * sizeof(ufbx_real);
+ void *end = (char*)ptr + list->count * stride;
+ while (ptr != end) {
+ ufbx_real *v = (ufbx_real*)ptr;
+ *v = -*v;
+ ptr = (char*)ptr + stride;
+ }
+}
+
+ufbxi_noinline static void ufbxi_scale_vec3_list(const void *v_list, ufbx_real scale, size_t stride)
+{
+ const ufbx_void_list *list = (const ufbx_void_list*)v_list;
+ if (!list || list->count == 0) return;
+ if (!stride) stride = sizeof(ufbx_vec3);
+
+ void *ptr = list->data, *end = (char*)ptr + list->count * stride;
+ while (ptr != end) {
+ ufbx_vec3 *v = (ufbx_vec3*)ptr;
+ v->x *= scale;
+ v->y *= scale;
+ v->z *= scale;
+ ptr = (char*)ptr + stride;
+ }
+}
+
+ufbxi_noinline static void ufbxi_transform_vec3_list(const void *v_list, const ufbx_matrix *matrix, size_t stride)
+{
+ const ufbx_void_list *list = (const ufbx_void_list*)v_list;
+ if (!list || list->count == 0) return;
+ if (!stride) stride = sizeof(ufbx_vec3);
+
+ void *ptr = list->data, *end = (char*)ptr + list->count * stride;
+ while (ptr != end) {
+ ufbx_vec3 *v = (ufbx_vec3*)ptr;
+ *v = ufbx_transform_position(matrix, *v);
+ ptr = (char*)ptr + stride;
+ }
+}
+
+ufbxi_noinline static void ufbxi_normalize_vec3_list(const ufbx_vec3_list *list)
+{
+ ufbxi_nounroll ufbxi_for_list(ufbx_vec3, normal, *list) {
+ *normal = ufbxi_normalize3(*normal);
+ }
+}
+
+// Forward declare as we're kind of preprocessing ata here that would usually happen later.
+ufbxi_noinline static ufbx_transform ufbxi_get_geometry_transform(const ufbx_props *props, ufbx_node *node);
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_flip_attrib_winding(ufbxi_context *uc, ufbx_mesh *mesh, ufbx_uint32_list *indices, bool is_position)
+{
+ // All zero, no flipping needed
+ if (indices->data == uc->zero_indices || indices->count == 0) return 1;
+
+ if (indices->data == mesh->vertex_position.indices.data && !is_position) {
+ // Sharing indices with vertex position, already flipped.
+ return 1;
+ } else if (indices->data == uc->consecutive_indices) {
+ // Need to duplicate consecutive indices, but we can cache the per mesh.
+ if (uc->tmp_mesh_consecutive_indices) {
+ indices->data = uc->tmp_mesh_consecutive_indices;
+ return 1;
+ }
+ indices->data = ufbxi_push_copy(&uc->result, uint32_t, indices->count, indices->data);
+ ufbxi_check(indices->data);
+ uc->tmp_mesh_consecutive_indices = indices->data;
+ }
+
+ uint32_t *data = indices->data;
+ ufbxi_for_list(ufbx_face, face, mesh->faces) {
+ if (face->num_indices == 0) continue;
+ size_t begin = face->index_begin + 1;
+ size_t end = face->index_begin + face->num_indices - 1;
+ while (begin < end) {
+ uint32_t tmp = data[begin];
+ data[begin] = data[end];
+ data[end] = tmp;
+ begin++;
+ end--;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_flip_winding(ufbxi_context *uc, ufbx_mesh *mesh)
+{
+ uc->tmp_mesh_consecutive_indices = NULL;
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_position.indices, true));
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_normal.indices, false));
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_crease.indices, false));
+ if (mesh->uv_sets.count > 0) {
+ ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_uv.indices, false));
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_tangent.indices, false));
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_bitangent.indices, false));
+ }
+ mesh->vertex_uv = mesh->uv_sets.data[0].vertex_uv;
+ mesh->vertex_bitangent = mesh->uv_sets.data[0].vertex_bitangent;
+ mesh->vertex_tangent = mesh->uv_sets.data[0].vertex_tangent;
+ }
+ if (mesh->color_sets.count > 0) {
+ ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_color.indices, false));
+ }
+ mesh->vertex_color = mesh->color_sets.data[0].vertex_color;
+ }
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->skinned_position.indices, false));
+ if (mesh->skinned_normal.indices.data != mesh->vertex_normal.indices.data) {
+ ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->skinned_normal.indices, false));
+ }
+
+ ufbxi_update_vertex_first_index(mesh);
+
+ // Mapping from old index values to flipped ones, reserve index -1
+ // (aka `UFBX_NO_INDEX`) for itself.
+ if (mesh->edges.count > 0) {
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, (mesh->num_indices + 1) * sizeof(uint32_t)));
+ uint32_t *index_mapping = (uint32_t*)uc->tmp_arr + 1;
+ index_mapping[-1] = UFBX_NO_INDEX;
+ ufbxi_for_list(ufbx_face, face, mesh->faces) {
+ if (face->num_indices == 0) continue;
+ uint32_t begin = face->index_begin;
+ uint32_t count = face->num_indices - 1;
+ index_mapping[begin] = begin;
+ for (uint32_t i = 0; i < count; i++) {
+ index_mapping[begin + 1 + i] = begin + count - i;
+ }
+ }
+
+ ufbxi_for_list(ufbx_edge, p_edge, mesh->edges) {
+ uint32_t a = index_mapping[(int32_t)p_edge->a];
+ uint32_t b = index_mapping[(int32_t)p_edge->b];
+ p_edge->a = b;
+ p_edge->b = a;
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_modify_geometry(ufbxi_context *uc)
+{
+ bool do_mirror = false;
+ bool do_winding = uc->opts.reverse_winding;
+ bool do_scale = false;
+ bool do_geometry_transforms = false;
+ if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY
+ || uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK) {
+ // Prefetch geometry transforms for processing, they will later be overwritten in `ufbxi_update_node()`.
+ ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
+ ufbx_node *node = *p_node;
+ if (node->is_root) continue;
+
+ node->geometry_transform = ufbxi_get_geometry_transform(&node->props, node);
+ if (!ufbxi_is_transform_identity(&node->geometry_transform)) {
+ node->geometry_to_node = ufbx_transform_to_matrix(&node->geometry_transform);
+ node->has_geometry_transform = true;
+ } else {
+ node->geometry_to_node = ufbx_identity_matrix;
+ node->has_geometry_transform = false;
+ }
+ }
+ do_geometry_transforms = true;
+ }
+ if (uc->mirror_axis != 0) {
+ do_mirror = true;
+ }
+ if (uc->scene.metadata.geometry_scale != 1.0f) {
+ do_scale = true;
+ }
+
+ ufbx_real geometry_scale = uc->scene.metadata.geometry_scale;
+ ufbx_mirror_axis mirror_axis = uc->mirror_axis;
+
+ ufbxi_for_ptr_list(ufbx_blend_shape, p_shape, uc->scene.blend_shapes) {
+ ufbx_blend_shape *shape = *p_shape;
+
+ if (do_scale) {
+ ufbxi_scale_vec3_list(&shape->position_offsets, geometry_scale, 0);
+ }
+
+ if (do_mirror) {
+ ufbxi_mirror_vec3_list(&shape->position_offsets, mirror_axis, 0);
+ ufbxi_mirror_vec3_list(&shape->normal_offsets, mirror_axis, 0);
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+
+ if (do_scale) {
+ ufbxi_scale_vec3_list(&mesh->vertex_position.values, geometry_scale, 0);
+ }
+
+ bool do_flip_winding = do_winding;
+ if (do_mirror) {
+ ufbxi_mirror_vec3_list(&mesh->vertex_position.values, mirror_axis, 0);
+ ufbxi_mirror_vec3_list(&mesh->vertex_normal.values, mirror_axis, 0);
+ ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ ufbxi_mirror_vec3_list(&set->vertex_tangent.values, mirror_axis, 0);
+ ufbxi_mirror_vec3_list(&set->vertex_bitangent.values, mirror_axis, 0);
+ }
+ if (!uc->opts.handedness_conversion_retain_winding) {
+ do_flip_winding = !do_flip_winding;
+ }
+ }
+
+ // Flip face winding retaining the first vertex
+ if (do_flip_winding) {
+ mesh->reversed_winding = true;
+ ufbxi_check(ufbxi_flip_winding(uc, mesh));
+ }
+
+ ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&mesh->element);
+ if (do_geometry_transforms && geo_node) {
+ ufbx_matrix tangent_matrix = geo_node->geometry_to_node;
+ tangent_matrix.m03 = 0.0f;
+ tangent_matrix.m13 = 0.0f;
+ tangent_matrix.m23 = 0.0f;
+ ufbx_matrix normal_matrix = ufbx_matrix_for_normals(&geo_node->geometry_to_node);
+
+ ufbxi_transform_vec3_list(&mesh->vertex_position.values, &geo_node->geometry_to_node, 0);
+ ufbxi_transform_vec3_list(&mesh->vertex_normal.values, &normal_matrix, 0);
+ ufbxi_normalize_vec3_list(&mesh->vertex_normal.values);
+
+ ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ ufbxi_transform_vec3_list(&set->vertex_tangent.values, &tangent_matrix, 0);
+ ufbxi_transform_vec3_list(&set->vertex_bitangent.values, &tangent_matrix, 0);
+ ufbxi_normalize_vec3_list(&set->vertex_tangent.values);
+ ufbxi_normalize_vec3_list(&set->vertex_bitangent.values);
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_line_curve, p_curve, uc->scene.line_curves) {
+ ufbx_line_curve *curve = *p_curve;
+
+ if (do_scale) {
+ ufbxi_scale_vec3_list(&curve->control_points, geometry_scale, 0);
+ }
+
+ if (do_mirror) {
+ ufbxi_mirror_vec3_list(&curve->control_points, mirror_axis, 0);
+ }
+
+ ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&curve->element);
+ if (do_geometry_transforms && geo_node) {
+ ufbxi_transform_vec3_list(&curve->control_points, &geo_node->geometry_to_node, 0);
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_nurbs_curve, p_curve, uc->scene.nurbs_curves) {
+ ufbx_nurbs_curve *curve = *p_curve;
+
+ if (do_scale) {
+ ufbxi_scale_vec3_list(&curve->control_points, geometry_scale, sizeof(ufbx_vec4));
+ }
+
+ if (do_mirror) {
+ ufbxi_mirror_vec3_list(&curve->control_points, mirror_axis, sizeof(ufbx_vec4));
+ }
+
+ ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&curve->element);
+ if (do_geometry_transforms && geo_node) {
+ ufbxi_transform_vec3_list(&curve->control_points, &geo_node->geometry_to_node, sizeof(ufbx_vec4));
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_nurbs_surface, p_surface, uc->scene.nurbs_surfaces) {
+ ufbx_nurbs_surface *surface = *p_surface;
+
+ if (do_scale) {
+ ufbxi_scale_vec3_list(&surface->control_points, geometry_scale, sizeof(ufbx_vec4));
+ }
+
+ if (do_mirror) {
+ ufbxi_mirror_vec3_list(&surface->control_points, mirror_axis, sizeof(ufbx_vec4));
+ }
+
+ ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&surface->element);
+ if (do_geometry_transforms && geo_node) {
+ ufbxi_transform_vec3_list(&surface->control_points, &geo_node->geometry_to_node, sizeof(ufbx_vec4));
+ }
+ }
+
+ if (uc->opts.geometry_transform_handling != UFBX_GEOMETRY_TRANSFORM_HANDLING_PRESERVE) {
+ // Reset all geometry transforms if we're not preserving them
+ ufbx_props *defaults = NULL;
+ ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
+ ufbx_node *node = *p_node;
+ if (!defaults) defaults = node->props.defaults;
+
+ if (node->has_geometry_transform) {
+ ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricTranslation, 0.0f);
+ ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricRotation, 0.0f);
+ ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricScaling, 1.0f);
+ }
+ }
+
+ if (defaults) {
+ ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricTranslation, 0.0f);
+ ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricRotation, 0.0f);
+ ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricScaling, 1.0f);
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_postprocess_scene(ufbxi_context *uc)
+{
+ if (uc->opts.normalize_normals || uc->opts.normalize_tangents) {
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+ if (uc->opts.normalize_normals) {
+ ufbxi_normalize_vec3_list(&mesh->vertex_normal.values);
+ }
+ if (uc->opts.normalize_tangents) {
+ ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ ufbxi_normalize_vec3_list(&mesh->vertex_tangent.values);
+ ufbxi_normalize_vec3_list(&mesh->vertex_bitangent.values);
+ }
+ }
+ }
+ }
+
+ if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
+ uc->scene.metadata.ortho_size_unit = 1.0f / uc->scene.metadata.geometry_scale;
+ } else {
+ uc->scene.metadata.ortho_size_unit = 30.0f;
+ }
+}
+
+ufbxi_noinline static size_t ufbxi_next_path_segment(const char *data, size_t begin, size_t length)
+{
+ for (size_t i = begin; i < length; i++) {
+ if (data[i] == '/' || data[i] == '\\') {
+ return i;
+ }
+ }
+ return length;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_absolute_to_relative_path(ufbxi_context *uc, ufbxi_strblob *p_dst, const ufbxi_strblob *p_rel, const ufbxi_strblob *p_src, bool raw)
+{
+ const char *rel = ufbxi_strblob_data(p_rel, raw);
+ const char *src = ufbxi_strblob_data(p_src, raw);
+ size_t rel_length = ufbxi_strblob_length(p_rel, raw);
+ size_t src_length = ufbxi_strblob_length(p_src, raw);
+
+ if (rel_length == 0 || src_length == 0) return 1;
+
+ // Absolute paths must start with the same character (either drive or '/')
+ if (rel[0] != src[0]) return 1;
+
+ // Find the last directory of the path we want to be relative to
+ while (rel_length > 0 && (rel[rel_length - 1] != '/' && rel[rel_length - 1] != '\\')) {
+ rel_length--;
+ }
+
+ if (rel_length == 0) return 1;
+ char separator = rel[rel_length - 1];
+
+ ufbxi_check(rel_length <= (SIZE_MAX - src_length) / 3);
+ size_t max_length = rel_length * 3 + src_length;
+
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, max_length));
+ char *tmp = uc->tmp_arr;
+ size_t tmp_length = 0;
+
+ size_t rel_begin = 0;
+ size_t src_begin = 0;
+ while (rel_begin < rel_length && src_begin < src_length) {
+ size_t rel_end = ufbxi_next_path_segment(rel, rel_begin, rel_length);
+ size_t src_end = ufbxi_next_path_segment(src, src_begin, src_length);
+ if (rel_end != src_end || memcmp(rel + rel_begin, src + src_begin, src_end - src_begin) != 0) break;
+
+ rel_begin = rel_end + 1;
+ src_begin = src_end + 1;
+ }
+
+ while (rel_begin < rel_length) {
+ size_t rel_end = ufbxi_next_path_segment(rel, rel_begin, rel_length);
+ tmp[tmp_length++] = '.';
+ tmp[tmp_length++] = '.';
+ tmp[tmp_length++] = separator;
+ rel_begin = rel_end + 1;
+ }
+
+ while (src_begin < src_length) {
+ size_t src_end = ufbxi_next_path_segment(src, src_begin, src_length);
+ size_t len = src_end - src_begin;
+
+ memcpy(tmp + tmp_length, src + src_begin, len);
+ tmp_length += len;
+
+ if (src_end < src_length) {
+ tmp[tmp_length++] = separator;
+ }
+
+ src_begin = src_end + 1;
+ }
+
+ ufbx_assert(tmp_length <= max_length);
+
+ const char *dst = ufbxi_push_string(&uc->string_pool, tmp, tmp_length, NULL, true);
+ ufbxi_check(dst);
+
+ ufbxi_strblob_set(p_dst, dst, tmp_length, raw);
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_filenames(ufbxi_context *uc, ufbxi_strblob *filename, ufbxi_strblob *absolute_filename, ufbxi_strblob *relative_filename, bool raw)
+{
+ if (ufbxi_strblob_length(relative_filename, raw) == 0) {
+ const ufbxi_strblob *original_file_path = raw
+ ? (const ufbxi_strblob*)&uc->scene.metadata.raw_original_file_path
+ : (const ufbxi_strblob*)&uc->scene.metadata.original_file_path;
+
+ ufbxi_check(ufbxi_absolute_to_relative_path(uc, relative_filename, original_file_path, absolute_filename, raw));
+ }
+
+ ufbxi_check(ufbxi_resolve_relative_filename(uc, filename, relative_filename, raw));
+
+ return 1;
+}
+
+ufbxi_noinline static bool ufbxi_file_content_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_file_content *a = (const ufbxi_file_content*)va, *b = (const ufbxi_file_content*)vb;
+ return ufbxi_str_less(a->absolute_filename, b->absolute_filename);
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_file_contents(ufbxi_context *uc, ufbxi_file_content *content, size_t count)
+{
+ ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_file_content)));
+ ufbxi_stable_sort(sizeof(ufbxi_file_content), 32, content, uc->tmp_arr, count, &ufbxi_file_content_less, NULL);
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_file_content(ufbxi_context *uc, ufbx_string *p_filename, ufbx_blob *p_data)
+{
+ if (p_data->size == 0 || p_filename->length == 0) return 1;
+ ufbxi_file_content *content = ufbxi_push(&uc->tmp_stack, ufbxi_file_content, 1);
+ ufbxi_check(content);
+
+ content->absolute_filename = *p_filename;
+ content->content = *p_data;
+ return 1;
+}
+
+ufbxi_noinline static void ufbxi_fetch_file_content(ufbxi_context *uc, ufbx_string *p_filename, ufbx_blob *p_data)
+{
+ if (p_data->size > 0) return;
+ ufbx_string filename = *p_filename;
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbxi_file_content, 8, &index, uc->file_content, 0, uc->num_file_content,
+ ( ufbxi_str_less(a->absolute_filename, filename) ),
+ ( a->absolute_filename.data == filename.data ));
+ if (index != SIZE_MAX) {
+ *p_data = uc->file_content[index].content;
+ }
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_file_content(ufbxi_context *uc)
+{
+ size_t initial_stack = uc->tmp_stack.num_items;
+
+ ufbxi_for_ptr_list(ufbx_video, p_video, uc->scene.videos) {
+ ufbx_video *video = *p_video;
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&video->filename, (ufbxi_strblob*)&video->absolute_filename, (ufbxi_strblob*)&video->relative_filename, false));
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&video->raw_filename, (ufbxi_strblob*)&video->raw_absolute_filename, (ufbxi_strblob*)&video->raw_relative_filename, true));
+ ufbxi_check(ufbxi_push_file_content(uc, &video->absolute_filename, &video->content));
+ }
+
+ ufbxi_for_ptr_list(ufbx_audio_clip, p_clip, uc->scene.audio_clips) {
+ ufbx_audio_clip *clip = *p_clip;
+ clip->absolute_filename = ufbx_find_string(&clip->props, "Path", ufbx_empty_string);
+ clip->relative_filename = ufbx_find_string(&clip->props, "RelPath", ufbx_empty_string);
+ clip->raw_absolute_filename = ufbx_find_blob(&clip->props, "Path", ufbx_empty_blob);
+ clip->raw_relative_filename = ufbx_find_blob(&clip->props, "RelPath", ufbx_empty_blob);
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&clip->filename, (ufbxi_strblob*)&clip->absolute_filename, (ufbxi_strblob*)&clip->relative_filename, false));
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&clip->raw_filename, (ufbxi_strblob*)&clip->raw_absolute_filename, (ufbxi_strblob*)&clip->raw_relative_filename, true));
+ ufbxi_check(ufbxi_push_file_content(uc, &clip->absolute_filename, &clip->content));
+ }
+
+ uc->num_file_content = uc->tmp_stack.num_items - initial_stack;
+ uc->file_content = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_file_content, uc->num_file_content);
+ ufbxi_check(uc->file_content);
+ ufbxi_check(ufbxi_sort_file_contents(uc, uc->file_content, uc->num_file_content));
+
+ ufbxi_for_ptr_list(ufbx_video, p_video, uc->scene.videos) {
+ ufbx_video *video = *p_video;
+ ufbxi_fetch_file_content(uc, &video->absolute_filename, &video->content);
+ }
+
+ ufbxi_for_ptr_list(ufbx_audio_clip, p_clip, uc->scene.audio_clips) {
+ ufbx_audio_clip *clip = *p_clip;
+ ufbxi_fetch_file_content(uc, &clip->absolute_filename, &clip->content);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_validate_indices(ufbxi_context *uc, ufbx_uint32_list *indices, size_t max_index)
+{
+ if (max_index == 0 && uc->opts.index_error_handling == UFBX_INDEX_ERROR_HANDLING_CLAMP) {
+ indices->data = NULL;
+ indices->count = 0;
+ return 1;
+ }
+
+ ufbxi_nounroll ufbxi_for_list(uint32_t, p_ix, *indices) {
+ uint32_t ix = *p_ix;
+ if (ix >= max_index) {
+ ufbxi_check(ufbxi_fix_index(uc, p_ix, ix, max_index));
+ }
+ }
+
+ return 1;
+}
+
+static bool ufbxi_material_part_usage_less(void *user, const void *va, const void *vb)
+{
+ ufbx_mesh_part *parts = (ufbx_mesh_part*)user;
+ uint32_t a = *(const uint32_t*)va, b = *(const uint32_t*)vb;
+ ufbx_mesh_part *pa = &parts[a];
+ ufbx_mesh_part *pb = &parts[b];
+ if (pa->face_indices.count == 0 || pb->face_indices.count == 0) {
+ if (pa->face_indices.count == pb->face_indices.count) return a < b;
+ return pa->face_indices.count > pb->face_indices.count;
+ }
+ return pa->face_indices.data[0] < pb->face_indices.data[0];
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_mesh_material(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh)
+{
+ size_t num_materials = mesh->materials.count;
+ size_t num_parts = mesh->material_parts.count;
+ size_t num_faces = mesh->faces.count;
+
+ ufbx_mesh_part *parts = mesh->material_parts.data;
+ ufbx_assert(!parts || (mesh->material_parts.count == num_materials) || (mesh->material_parts.count == 1 && num_materials == 0));
+
+ uint32_t *face_material = mesh->face_material.data;
+
+ // Count the number of faces and triangles per material
+ ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
+ ufbx_face face = mesh->faces.data[i];
+ uint32_t mat_ix = 0;
+
+ if (face_material) {
+ mat_ix = face_material[i];
+ if (mat_ix >= num_materials) {
+ face_material[i] = 0;
+ mat_ix = 0;
+ }
+ }
+
+ if (parts) {
+ ufbxi_mesh_part_add_face(&parts[mat_ix], face.num_indices);
+ }
+ }
+
+ if (parts) {
+ // Allocate per-material buffers (clear `num_faces` to 0 to re-use it as
+ // an index when fetching the face indices).
+ uint32_t part_index = 0;
+ ufbxi_for(ufbx_mesh_part, part, parts, num_parts) {
+ part->index = part_index++;
+ part->face_indices.count = part->num_faces;
+ part->face_indices.data = ufbxi_push(buf, uint32_t, part->num_faces);
+ ufbxi_check_err(error, part->face_indices.data);
+ part->num_faces = 0;
+ }
+
+ // Fetch the per-material face indices
+ ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
+ uint32_t mat_ix = face_material ? face_material[i] : 0;
+ if (mat_ix < num_parts) {
+ ufbx_mesh_part *part = &parts[mat_ix];
+ part->face_indices.data[part->num_faces++] = (uint32_t)i;
+ }
+ }
+
+ mesh->material_part_usage_order.count = num_parts;
+ mesh->material_part_usage_order.data = ufbxi_push(buf, uint32_t, num_parts);
+ ufbxi_check_err(error, mesh->material_part_usage_order.data);
+ for (size_t i = 0; i < num_parts; i++) {
+ mesh->material_part_usage_order.data[i] = (uint32_t)i;
+ }
+ ufbxi_unstable_sort(mesh->material_part_usage_order.data, num_parts, sizeof(uint32_t), &ufbxi_material_part_usage_less, parts);
+ }
+
+ return 1;
+}
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_anim anim;
+ uint32_t magic;
+} ufbxi_anim_imp;
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_anim(ufbxi_context *uc, ufbx_anim **p_anim, ufbx_anim_layer **layers, size_t num_layers)
+{
+ ufbx_anim *anim = ufbxi_push_zero(&uc->result, ufbx_anim, 1);
+ ufbxi_check(anim);
+
+ anim->layers.data = layers;
+ anim->layers.count = num_layers;
+
+ *p_anim = anim;
+ return 1;
+}
+
+ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_scene(ufbxi_context *uc)
+{
+ size_t num_elements = uc->num_elements;
+
+ uc->scene.elements.count = num_elements;
+ uc->scene.elements.data = ufbxi_push(&uc->result, ufbx_element*, num_elements);
+ ufbxi_check(uc->scene.elements.data);
+
+ uc->scene.metadata.element_buffer_size = uc->tmp_element_byte_offset;
+ char *element_data = (char*)ufbxi_push_pop(&uc->result, &uc->tmp_elements, uint64_t, uc->tmp_element_byte_offset/8);
+ ufbxi_check(element_data);
+
+ size_t *element_offsets = ufbxi_push_pop(&uc->tmp, &uc->tmp_element_offsets, size_t, uc->tmp_element_offsets.num_items);
+ ufbxi_buf_free(&uc->tmp_element_offsets);
+ ufbxi_check(element_offsets);
+ for (size_t i = 0; i < num_elements; i++) {
+ ufbx_element *element = (ufbx_element*)(element_data + element_offsets[i]);
+
+ if (element->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *node = (ufbx_node*)element;
+ if (node->scale_helper) {
+ ufbxi_node_extra *extra = (ufbxi_node_extra*)ufbxi_get_element_extra(uc, node->element_id);
+ ufbx_assert(extra);
+ node->scale_helper = (ufbx_node*)(element_data + element_offsets[extra->scale_helper_id]);
+ }
+ }
+
+ uc->scene.elements.data[i] = element;
+ }
+
+ uc->scene.elements.count = num_elements;
+ ufbxi_buf_free(&uc->tmp_element_offsets);
+ ufbxi_buf_free(&uc->tmp_elements);
+
+ uc->tmp_element_flag = ufbxi_push_zero(&uc->tmp, uint8_t, num_elements);
+ ufbxi_check(uc->tmp_element_flag);
+
+ uc->scene.metadata.original_file_path = ufbx_find_string(&uc->scene.metadata.scene_props, "DocumentUrl", ufbx_empty_string);
+ uc->scene.metadata.raw_original_file_path = ufbx_find_blob(&uc->scene.metadata.scene_props, "DocumentUrl", ufbx_empty_blob);
+
+ // Resolve and add the connections to elements
+ ufbxi_check(ufbxi_resolve_connections(uc));
+ ufbxi_check(ufbxi_add_connections_to_elements(uc));
+ ufbxi_check(ufbxi_linearize_nodes(uc));
+
+ for (size_t type = 0; type < UFBX_ELEMENT_TYPE_COUNT; type++) {
+ size_t num_typed = uc->tmp_typed_element_offsets[type].num_items;
+ size_t *typed_offsets = ufbxi_push_pop(&uc->tmp, &uc->tmp_typed_element_offsets[type], size_t, num_typed);
+ ufbxi_buf_free(&uc->tmp_typed_element_offsets[type]);
+ ufbxi_check(typed_offsets);
+
+ ufbx_element_list *typed_elems = &uc->scene.elements_by_type[type];
+ typed_elems->count = num_typed;
+ typed_elems->data = ufbxi_push(&uc->result, ufbx_element*, num_typed);
+ ufbxi_check(typed_elems->data);
+
+ for (size_t i = 0; i < num_typed; i++) {
+ typed_elems->data[i] = (ufbx_element*)(element_data + typed_offsets[i]);
+ }
+
+ ufbxi_buf_free(&uc->tmp_typed_element_offsets[type]);
+ }
+
+ // Create named elements
+ uc->scene.elements_by_name.count = num_elements;
+ uc->scene.elements_by_name.data = ufbxi_push(&uc->result, ufbx_name_element, num_elements);
+ ufbxi_check(uc->scene.elements_by_name.data);
+
+ for (size_t i = 0; i < num_elements; i++) {
+
+ ufbx_element *elem = uc->scene.elements.data[i];
+ ufbx_name_element *name_elem = &uc->scene.elements_by_name.data[i];
+
+ name_elem->name = elem->name;
+ name_elem->type = elem->type;
+ name_elem->_internal_key = ufbxi_get_name_key(elem->name.data, elem->name.length);
+ name_elem->element = elem;
+ }
+
+ ufbxi_check(ufbxi_sort_name_elements(uc, uc->scene.elements_by_name.data, num_elements));
+
+ // Setup node children arrays and attribute pointers/lists
+ ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
+ ufbx_node *node = *p_node, *parent = node->parent;
+ if (parent) {
+ parent->children.count++;
+ if (parent->children.data == NULL) {
+ parent->children.data = p_node;
+ }
+
+ if (node->is_geometry_transform_helper) {
+ parent->geometry_transform_helper = node;
+ }
+
+ // Force top-level nodes to have `UFBX_INHERIT_MODE_NORMAL` to make unit scaling work.
+ if (parent->is_root && uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT && uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
+ node->original_inherit_mode = UFBX_INHERIT_MODE_NORMAL;
+ node->inherit_mode = UFBX_INHERIT_MODE_NORMAL;
+ }
+
+ // RrSs nodes inherit scale from their parent, Rrs ignore the scale of
+ // their _immediate_ parent, potentially multiple if chained.
+ if (node->original_inherit_mode == UFBX_INHERIT_MODE_COMPONENTWISE_SCALE) {
+ node->inherit_scale_node = parent;
+ } else if (node->original_inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
+ node->inherit_scale_node = parent->inherit_scale_node;
+ }
+ }
+
+ ufbx_connection_list conns = ufbxi_find_dst_connections(&node->element, NULL);
+
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ ufbx_element *elem = conn->src;
+ ufbx_element_type type = elem->type;
+ if (!(type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB)) continue;
+
+ size_t index = node->all_attribs.count++;
+ if (index == 0) {
+ node->attrib = elem;
+ node->attrib_type = type;
+ } else {
+ if (index == 1) {
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &node->attrib));
+ }
+ ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &elem));
+ }
+
+ switch (elem->type) {
+ case UFBX_ELEMENT_MESH: node->mesh = (ufbx_mesh*)elem; break;
+ case UFBX_ELEMENT_LIGHT: node->light = (ufbx_light*)elem; break;
+ case UFBX_ELEMENT_CAMERA: node->camera = (ufbx_camera*)elem; break;
+ case UFBX_ELEMENT_BONE: node->bone = (ufbx_bone*)elem; break;
+ default: /* No shorthand */ break;
+ }
+ }
+
+ if (node->all_attribs.count > 1) {
+ node->all_attribs.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, node->all_attribs.count);
+ ufbxi_check(node->all_attribs.data);
+ } else if (node->all_attribs.count == 1) {
+ node->all_attribs.data = &node->attrib;
+ }
+
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &node->materials, &node->element, false, false, NULL, UFBX_ELEMENT_MATERIAL));
+ }
+
+ // Resolve bind pose bones that don't use the normal connection system
+ ufbxi_for_ptr_list(ufbx_pose, p_pose, uc->scene.poses) {
+ ufbx_pose *pose = *p_pose;
+
+ // HACK: Transport `ufbxi_tmp_bone_pose` array through the `ufbx_bone_pose` pointer
+ size_t num_bones = pose->bone_poses.count;
+ ufbxi_tmp_bone_pose *tmp_poses = (ufbxi_tmp_bone_pose*)pose->bone_poses.data;
+ pose->bone_poses.data = ufbxi_push(&uc->result, ufbx_bone_pose, num_bones);
+ ufbxi_check(pose->bone_poses.data);
+
+ // Filter only found bones
+ pose->bone_poses.count = 0;
+ for (size_t i = 0; i < num_bones; i++) {
+ ufbx_element *elem = ufbxi_find_element_by_fbx_id(uc, tmp_poses[i].bone_fbx_id);
+ if (!elem || elem->type != UFBX_ELEMENT_NODE) continue;
+
+ ufbx_node *node = (ufbx_node*)elem;
+ ufbx_bone_pose *bone = &pose->bone_poses.data[pose->bone_poses.count++];
+ bone->bone_node = node;
+ bone->bone_to_world = tmp_poses[i].bone_to_world;
+
+ if (pose->is_bind_pose) {
+ if (node->bind_pose == NULL) {
+ node->bind_pose = pose;
+ }
+
+ ufbx_connection_list node_conns = ufbxi_find_src_connections(elem, NULL);
+ ufbxi_for_list(ufbx_connection, conn, node_conns) {
+ if (conn->dst->type != UFBX_ELEMENT_SKIN_CLUSTER) continue;
+ ufbx_skin_cluster *cluster = (ufbx_skin_cluster*)conn->dst;
+ if (ufbxi_matrix_all_zero(&cluster->bind_to_world)) {
+ cluster->bind_to_world = bone->bone_to_world;
+ }
+ }
+ }
+ }
+ ufbxi_check(ufbxi_sort_bone_poses(uc, pose));
+ }
+
+ // Fetch pointers that may break elements
+
+ // Setup node attribute instances
+ for (int type = UFBX_ELEMENT_TYPE_FIRST_ATTRIB; type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB; type++) {
+ ufbxi_for_ptr_list(ufbx_element, p_elem, uc->scene.elements_by_type[type]) {
+ ufbx_element *elem = *p_elem;
+ ufbxi_check(ufbxi_fetch_src_elements(uc, &elem->instances, elem, false, true, NULL, UFBX_ELEMENT_NODE));
+ }
+ }
+
+ bool search_node = uc->version < 7000;
+
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, uc->scene.skin_clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ cluster->bone_node = (ufbx_node*)ufbxi_fetch_dst_element(&cluster->element, false, NULL, UFBX_ELEMENT_NODE);
+ }
+
+ ufbxi_for_ptr_list(ufbx_skin_deformer, p_skin, uc->scene.skin_deformers) {
+ ufbx_skin_deformer *skin = *p_skin;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &skin->clusters, &skin->element, false, true, NULL, UFBX_ELEMENT_SKIN_CLUSTER));
+
+ // Remove clusters without a valid `bone`
+ if (!uc->opts.connect_broken_elements) {
+ size_t num_broken = 0;
+ for (size_t i = 0; i < skin->clusters.count; i++) {
+ if (!skin->clusters.data[i]->bone_node) {
+ num_broken++;
+ } else if (num_broken > 0) {
+ skin->clusters.data[i - num_broken] = skin->clusters.data[i];
+ }
+ }
+ skin->clusters.count -= num_broken;
+ }
+
+ size_t total_weights = 0;
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ ufbxi_check(SIZE_MAX - total_weights > cluster->num_weights);
+ total_weights += cluster->num_weights;
+ }
+
+ size_t num_vertices = 0;
+
+ // Iterate through meshes so we can pad the vertices to the largest one
+ {
+ ufbx_connection_list conns = ufbxi_find_src_connections(&skin->element, NULL);
+ ufbxi_for_list(ufbx_connection, conn, conns) {
+ ufbx_mesh *mesh = NULL;
+ if (conn->dst_prop.length > 0) continue;
+ if (conn->dst->type == UFBX_ELEMENT_MESH) {
+ mesh = (ufbx_mesh*)conn->dst;
+ } else if (conn->dst->type == UFBX_ELEMENT_NODE) {
+ ufbx_node *node = (ufbx_node*)conn->dst;
+ if (node->geometry_transform_helper) node = node->geometry_transform_helper;
+ mesh = node->mesh;
+ }
+ if (!mesh) continue;
+ num_vertices = ufbxi_max_sz(num_vertices, mesh->num_vertices);
+ }
+ }
+
+ if (!uc->opts.skip_skin_vertices) {
+ skin->vertices.count = num_vertices;
+ skin->vertices.data = ufbxi_push_zero(&uc->result, ufbx_skin_vertex, num_vertices);
+ ufbxi_check(skin->vertices.data);
+
+ skin->weights.count = total_weights;
+ skin->weights.data = ufbxi_push_zero(&uc->result, ufbx_skin_weight, total_weights);
+ ufbxi_check(skin->weights.data);
+
+ bool retain_all = !uc->opts.clean_skin_weights;
+
+ // Count the number of weights per vertex
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ for (size_t i = 0; i < cluster->num_weights; i++) {
+ uint32_t vertex = cluster->vertices.data[i];
+ if (vertex < num_vertices && (retain_all || cluster->weights.data[i] > 0.0f)) {
+ skin->vertices.data[vertex].num_weights++;
+ }
+ }
+ }
+
+ ufbx_real default_dq = skin->skinning_method == UFBX_SKINNING_METHOD_DUAL_QUATERNION ? 1.0f : 0.0f;
+
+ // Prefix sum to assign the vertex weight offsets and set up default DQ values
+ uint32_t offset = 0;
+ uint32_t max_weights = 0;
+ for (size_t i = 0; i < num_vertices; i++) {
+ skin->vertices.data[i].weight_begin = offset;
+ skin->vertices.data[i].dq_weight = default_dq;
+ uint32_t num_weights = skin->vertices.data[i].num_weights;
+ offset += num_weights;
+ skin->vertices.data[i].num_weights = 0;
+
+ if (num_weights > max_weights) max_weights = num_weights;
+ }
+ ufbx_assert(offset <= total_weights);
+ skin->max_weights_per_vertex = max_weights;
+
+ // Copy the DQ weights to vertices
+ for (size_t i = 0; i < skin->num_dq_weights; i++) {
+ uint32_t vertex = skin->dq_vertices.data[i];
+ if (vertex < num_vertices) {
+ skin->vertices.data[vertex].dq_weight = skin->dq_weights.data[i];
+ }
+ }
+
+ // Copy the weights to vertices
+ uint32_t cluster_index = 0;
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ for (size_t i = 0; i < cluster->num_weights; i++) {
+ uint32_t vertex = cluster->vertices.data[i];
+ if (vertex < num_vertices && (retain_all || cluster->weights.data[i] > 0.0f)) {
+ uint32_t local_index = skin->vertices.data[vertex].num_weights++;
+ uint32_t index = skin->vertices.data[vertex].weight_begin + local_index;
+ skin->weights.data[index].cluster_index = cluster_index;
+ skin->weights.data[index].weight = cluster->weights.data[i];
+ }
+ }
+ cluster_index++;
+ }
+
+ // Sort the vertex weights by descending weight value
+ ufbxi_check(ufbxi_sort_skin_weights(uc, skin));
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, uc->scene.blend_deformers) {
+ ufbx_blend_deformer *blend = *p_blend;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &blend->channels, &blend->element, false, true, NULL, UFBX_ELEMENT_BLEND_CHANNEL));
+ }
+
+ ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, uc->scene.cache_deformers) {
+ ufbx_cache_deformer *deformer = *p_deformer;
+ deformer->channel = ufbx_find_string(&deformer->props, "ChannelName", ufbx_empty_string);
+ deformer->file = (ufbx_cache_file*)ufbxi_fetch_dst_element(&deformer->element, false, NULL, UFBX_ELEMENT_CACHE_FILE);
+ }
+
+ ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
+ ufbx_cache_file *cache = *p_cache;
+
+ cache->absolute_filename = ufbx_find_string(&cache->props, "CacheAbsoluteFileName", ufbx_empty_string);
+ cache->relative_filename = ufbx_find_string(&cache->props, "CacheFileName", ufbx_empty_string);
+
+ cache->raw_absolute_filename = ufbx_find_blob(&cache->props, "CacheAbsoluteFileName", ufbx_empty_blob);
+ cache->raw_relative_filename = ufbx_find_blob(&cache->props, "CacheFileName", ufbx_empty_blob);
+
+ int64_t type = ufbx_find_int(&cache->props, "CacheFileType", 0);
+ if (type >= 0 && type <= UFBX_CACHE_FILE_FORMAT_MC) {
+ cache->format = (ufbx_cache_file_format)type;
+ }
+
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&cache->filename, (ufbxi_strblob*)&cache->absolute_filename, (ufbxi_strblob*)&cache->relative_filename, false));
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&cache->raw_filename, (ufbxi_strblob*)&cache->raw_absolute_filename, (ufbxi_strblob*)&cache->raw_relative_filename, true));
+ }
+
+ ufbx_assert(uc->tmp_full_weights.num_items == uc->scene.blend_channels.count);
+ ufbx_real_list *full_weights = ufbxi_push_pop(&uc->tmp, &uc->tmp_full_weights, ufbx_real_list, uc->tmp_full_weights.num_items);
+ ufbxi_buf_free(&uc->tmp_full_weights);
+ ufbxi_check(full_weights);
+
+ ufbxi_for_ptr_list(ufbx_blend_channel, p_channel, uc->scene.blend_channels) {
+ ufbx_blend_channel *channel = *p_channel;
+
+ ufbxi_check(ufbxi_fetch_blend_keyframes(uc, &channel->keyframes, &channel->element));
+
+ for (size_t i = 0; i < channel->keyframes.count; i++) {
+ ufbx_blend_keyframe *key = &channel->keyframes.data[i];
+ key->target_weight = 1.0f;
+ if (i < full_weights->count) {
+ if (!uc->blender_full_weights) {
+ key->target_weight = full_weights->data[i] / (ufbx_real)100.0;
+ } else if (full_weights->count == key->shape->num_offsets) {
+ if (i == 0) {
+ // Duplicate `index_data` for modification if we retain DOM
+ if (uc->opts.retain_dom) {
+ full_weights->data = ufbxi_push_copy(&uc->result, ufbx_real, full_weights->count, full_weights->data);
+ ufbxi_check(full_weights->data);
+ }
+ ufbxi_for_list(ufbx_real, p_weight, *full_weights) {
+ *p_weight /= (ufbx_real)100.0;
+ }
+ }
+ key->shape->offset_weights = *full_weights;
+ }
+ }
+ }
+
+ ufbxi_check(ufbxi_sort_blend_keyframes(uc, channel->keyframes.data, channel->keyframes.count));
+ full_weights++;
+
+ if (channel->keyframes.count > 0) {
+ channel->target_shape = channel->keyframes.data[channel->keyframes.count - 1].shape;
+ }
+ }
+
+ {
+ // Generate and patch procedural index buffers
+ uint32_t *zero_indices = ufbxi_push(&uc->result, uint32_t, uc->max_zero_indices);
+ uint32_t *consecutive_indices = ufbxi_push(&uc->result, uint32_t, uc->max_consecutive_indices);
+ ufbxi_check(zero_indices && consecutive_indices);
+
+ memset(zero_indices, 0, sizeof(uint32_t) * uc->max_zero_indices);
+ for (size_t i = 0; i < uc->max_consecutive_indices; i++) {
+ consecutive_indices[i] = (uint32_t)i;
+ }
+
+ uc->zero_indices = zero_indices;
+ uc->consecutive_indices = consecutive_indices;
+
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+
+ ufbxi_patch_index_pointer(uc, &mesh->vertex_position.indices.data);
+ ufbxi_patch_index_pointer(uc, &mesh->vertex_normal.indices.data);
+ ufbxi_patch_index_pointer(uc, &mesh->vertex_color.indices.data);
+ ufbxi_patch_index_pointer(uc, &mesh->vertex_crease.indices.data);
+ ufbxi_patch_index_pointer(uc, &mesh->face_material.data);
+ ufbxi_patch_index_pointer(uc, &mesh->face_group.data);
+
+ ufbxi_patch_index_pointer(uc, &mesh->skinned_position.indices.data);
+ ufbxi_patch_index_pointer(uc, &mesh->skinned_normal.indices.data);
+
+ ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
+ ufbxi_patch_index_pointer(uc, &set->vertex_uv.indices.data);
+ ufbxi_patch_index_pointer(uc, &set->vertex_bitangent.indices.data);
+ ufbxi_patch_index_pointer(uc, &set->vertex_tangent.indices.data);
+ }
+
+ ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
+ ufbxi_patch_index_pointer(uc, &set->vertex_color.indices.data);
+ }
+
+ // Generate normals if necessary
+ if (!mesh->vertex_normal.exists && uc->opts.generate_missing_normals) {
+ ufbxi_check(ufbxi_generate_normals(uc, mesh));
+ }
+
+ // Assign first UV and color sets as the "canonical" ones
+ if (mesh->uv_sets.count > 0) {
+ mesh->vertex_uv = mesh->uv_sets.data[0].vertex_uv;
+ mesh->vertex_bitangent = mesh->uv_sets.data[0].vertex_bitangent;
+ mesh->vertex_tangent = mesh->uv_sets.data[0].vertex_tangent;
+ }
+ if (mesh->color_sets.count > 0) {
+ mesh->vertex_color = mesh->color_sets.data[0].vertex_color;
+ }
+
+ if (mesh->face_group_parts.count == 1) {
+ ufbxi_patch_index_pointer(uc, &mesh->face_group_parts.data[0].face_indices.data);
+ }
+
+ ufbxi_check(ufbxi_fetch_mesh_materials(uc, &mesh->materials, &mesh->element, true));
+
+ // Patch materials to instances if necessary
+ if (mesh->materials.count > 0) {
+ ufbxi_for_ptr_list(ufbx_node, p_node, mesh->instances) {
+ ufbx_node *node = *p_node;
+ if (node->materials.count < mesh->materials.count && mesh->materials.data[0] != NULL) {
+ ufbx_material **materials = ufbxi_push(&uc->result, ufbx_material*, mesh->materials.count);
+ ufbxi_check(materials);
+ ufbxi_nounroll for (size_t i = 0; i < node->materials.count; i++) {
+ materials[i] = node->materials.data[i];
+ }
+ ufbxi_nounroll for (size_t i = node->materials.count; i < mesh->materials.count; i++) {
+ materials[i] = mesh->materials.data[i];
+ }
+ node->materials.data = materials;
+ node->materials.count = mesh->materials.count;
+ }
+ }
+ }
+
+ if (uc->retain_mesh_parts) {
+ size_t num_parts = ufbxi_max_sz(mesh->materials.count, 1);
+ mesh->material_parts.data = ufbxi_push_zero(&uc->result, ufbx_mesh_part, num_parts);
+ ufbxi_check(mesh->material_parts.data);
+ mesh->material_parts.count = num_parts;
+ }
+
+ if (mesh->materials.count <= 1) {
+ // Use the shared consecutive index buffer for mesh faces if there's only one material
+ // See HACK(consecutive-faces) in `ufbxi_read_mesh()`.
+ if (mesh->material_parts.count > 0) {
+ ufbx_mesh_part *part = &mesh->material_parts.data[0];
+ part->num_faces = mesh->num_faces;
+ part->num_triangles = mesh->num_triangles;
+ part->num_empty_faces = mesh->num_empty_faces;
+ part->num_point_faces = mesh->num_point_faces;
+ part->num_line_faces = mesh->num_line_faces;
+ part->face_indices.data = uc->consecutive_indices;
+ part->face_indices.count = mesh->num_faces;
+ mesh->material_part_usage_order.data = uc->zero_indices;
+ mesh->material_part_usage_order.count = 1;
+ }
+
+ if (mesh->materials.count == 1) {
+ mesh->face_material.data = uc->zero_indices;
+ mesh->face_material.count = mesh->num_faces;
+ } else {
+ mesh->face_material.data = NULL;
+ mesh->face_material.count = 0;
+ }
+ } else if (mesh->materials.count > 0) {
+ ufbxi_check(ufbxi_finalize_mesh_material(&uc->result, &uc->error, mesh));
+ }
+
+ // Fetch deformers
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->skin_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_SKIN_DEFORMER));
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->blend_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_BLEND_DEFORMER));
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->cache_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_CACHE_DEFORMER));
+ ufbxi_check(ufbxi_fetch_deformers(uc, &mesh->all_deformers, &mesh->element, search_node));
+
+ // Vertex position must always exist if not explicitly allowed to be missing
+ if (!mesh->vertex_position.exists && !uc->opts.allow_missing_vertex_position) {
+ ufbxi_check(mesh->num_indices == 0);
+ mesh->vertex_position.exists = true;
+ mesh->vertex_position.unique_per_vertex = true;
+ mesh->skinned_position.exists = true;
+ mesh->skinned_position.unique_per_vertex = true;
+ }
+
+ // Update metadata
+ if (mesh->max_face_triangles > uc->scene.metadata.max_face_triangles) {
+ uc->scene.metadata.max_face_triangles = mesh->max_face_triangles;
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_stereo_camera, p_stereo, uc->scene.stereo_cameras) {
+ ufbx_stereo_camera *stereo = *p_stereo;
+ stereo->left = (ufbx_camera*)ufbxi_fetch_dst_element(&stereo->element, search_node, ufbxi_LeftCamera, UFBX_ELEMENT_CAMERA);
+ stereo->right = (ufbx_camera*)ufbxi_fetch_dst_element(&stereo->element, search_node, ufbxi_RightCamera, UFBX_ELEMENT_CAMERA);
+ }
+
+ ufbxi_for_ptr_list(ufbx_nurbs_curve, p_curve, uc->scene.nurbs_curves) {
+ ufbx_nurbs_curve *curve = *p_curve;
+ ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &curve->basis));
+ }
+
+ ufbxi_for_ptr_list(ufbx_nurbs_surface, p_surface, uc->scene.nurbs_surfaces) {
+ ufbx_nurbs_surface *surface = *p_surface;
+ ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &surface->basis_u));
+ ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &surface->basis_v));
+
+ surface->material = (ufbx_material*)ufbxi_fetch_dst_element(&surface->element, true, NULL, UFBX_ELEMENT_MATERIAL);
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, uc->scene.anim_stacks) {
+ ufbx_anim_stack *stack = *p_stack;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &stack->layers, &stack->element, false, true, NULL, UFBX_ELEMENT_ANIM_LAYER));
+
+ ufbxi_check(ufbxi_push_anim(uc, &stack->anim, stack->layers.data, stack->layers.count));
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, uc->scene.anim_layers) {
+ ufbx_anim_layer *layer = *p_layer;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->anim_values, &layer->element, false, true, NULL, UFBX_ELEMENT_ANIM_VALUE));
+
+ ufbxi_check(ufbxi_push_anim(uc, &layer->anim, p_layer, 1));
+
+ uint32_t min_id = UINT32_MAX, max_id = 0;
+
+ // Combine the animated properties with elements (potentially duplicates!)
+ size_t num_anim_props = 0;
+ ufbxi_for_ptr_list(ufbx_anim_value, p_value, layer->anim_values) {
+ ufbx_anim_value *value = *p_value;
+ ufbxi_for_list(ufbx_connection, ac, value->element.connections_src) {
+ if (ac->src_prop.length == 0 && ac->dst_prop.length > 0) {
+ ufbx_anim_prop *aprop = ufbxi_push(&uc->tmp_stack, ufbx_anim_prop, 1);
+ uint32_t id = ac->dst->element_id;
+ min_id = ufbxi_min32(min_id, id);
+ max_id = ufbxi_max32(max_id, id);
+ uint32_t id_mask = ufbxi_arraycount(layer->_element_id_bitmask) - 1;
+ layer->_element_id_bitmask[(id >> 5) & id_mask] |= 1u << (id & 31);
+ ufbxi_check(aprop);
+ aprop->anim_value = value;
+ aprop->element = ac->dst;
+ aprop->_internal_key = ufbxi_get_name_key(ac->dst_prop.data, ac->dst_prop.length);
+ aprop->prop_name = ac->dst_prop;
+ num_anim_props++;
+ }
+ }
+ }
+
+ if (min_id != UINT32_MAX) {
+ layer->_min_element_id = min_id;
+ layer->_max_element_id = max_id;
+ }
+
+ switch (ufbxi_find_int(&layer->props, ufbxi_BlendMode, 0)) {
+ case 0: // Additive
+ layer->blended = true;
+ layer->additive = true;
+ break;
+ case 1: // Override
+ layer->blended = false;
+ layer->additive = false;
+ break;
+ case 2: // Override Passthrough
+ layer->blended = true;
+ layer->additive = false;
+ break;
+ default: // Unknown
+ layer->blended = false;
+ layer->additive = false;
+ break;
+ }
+
+ ufbx_prop *weight_prop = ufbxi_find_prop(&layer->props, ufbxi_Weight);
+ if (weight_prop) {
+ layer->weight = weight_prop->value_real / (ufbx_real)100.0;
+ if (layer->weight < 0.0f) layer->weight = 0.0f;
+ if (layer->weight > 0.99999f) layer->weight = 1.0f;
+ layer->weight_is_animated = (weight_prop->flags & UFBX_PROP_FLAG_ANIMATED) != 0;
+ } else {
+ layer->weight = 1.0f;
+ layer->weight_is_animated = false;
+ }
+ layer->compose_rotation = ufbxi_find_int(&layer->props, ufbxi_RotationAccumulationMode, 0) == 0;
+ layer->compose_scale = ufbxi_find_int(&layer->props, ufbxi_ScaleAccumulationMode, 0) == 0;
+
+ // Add a dummy NULL element animated prop at the end so we can iterate
+ // animated props without worrying about boundary conditions..
+ {
+ ufbx_anim_prop *aprop = ufbxi_push_zero(&uc->tmp_stack, ufbx_anim_prop, 1);
+ ufbxi_check(aprop);
+ }
+
+ layer->anim_props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_anim_prop, num_anim_props + 1);
+ ufbxi_check(layer->anim_props.data);
+ layer->anim_props.count = num_anim_props;
+ ufbxi_check(ufbxi_sort_anim_props(uc, layer->anim_props.data, layer->anim_props.count));
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_value, p_value, uc->scene.anim_values) {
+ ufbx_anim_value *value = *p_value;
+
+ // TODO: Search for things like d|Visibility with a constructed name
+ value->default_value.x = ufbxi_find_real(&value->props, ufbxi_X, value->default_value.x);
+ value->default_value.x = ufbxi_find_real(&value->props, ufbxi_d_X, value->default_value.x);
+ value->default_value.y = ufbxi_find_real(&value->props, ufbxi_Y, value->default_value.y);
+ value->default_value.y = ufbxi_find_real(&value->props, ufbxi_d_Y, value->default_value.y);
+ value->default_value.z = ufbxi_find_real(&value->props, ufbxi_Z, value->default_value.z);
+ value->default_value.z = ufbxi_find_real(&value->props, ufbxi_d_Z, value->default_value.z);
+
+ ufbxi_for_list(ufbx_connection, conn, value->element.connections_dst) {
+ if (conn->src->type == UFBX_ELEMENT_ANIM_CURVE && conn->src_prop.length == 0) {
+ ufbx_anim_curve *curve = (ufbx_anim_curve*)conn->src;
+
+ uint32_t index = 0;
+ const char *name = conn->dst_prop.data;
+ if (name == ufbxi_Y || name == ufbxi_d_Y) index = 1;
+ if (name == ufbxi_Z || name == ufbxi_d_Z) index = 2;
+
+ ufbx_prop *prop = ufbx_find_prop_len(&value->props, conn->dst_prop.data, conn->dst_prop.length);
+ if (prop) {
+ value->default_value.v[index] = prop->value_real;
+ }
+ value->curves[index] = curve;
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_curve, p_curve, uc->scene.anim_curves) {
+ ufbx_anim_curve *curve = *p_curve;
+ if (curve->keyframes.count > 0) {
+ curve->min_time = curve->keyframes.data[0].time;
+ curve->max_time = curve->keyframes.data[curve->keyframes.count - 1].time;
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_shader, p_shader, uc->scene.shaders) {
+ ufbx_shader *shader = *p_shader;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &shader->bindings, &shader->element, false, false, NULL, UFBX_ELEMENT_SHADER_BINDING));
+
+ ufbx_prop *api = ufbx_find_prop(&shader->props, "RenderAPI");
+ if (api) {
+ if (!strcmp(api->value_str.data, "ARNOLD_SHADER_ID")) {
+ shader->type = UFBX_SHADER_ARNOLD_STANDARD_SURFACE;
+ } else if (!strcmp(api->value_str.data, "OSL")) {
+ shader->type = UFBX_SHADER_OSL_STANDARD_SURFACE;
+ } else if (!strcmp(api->value_str.data, "SFX_PBS_SHADER")) {
+ shader->type = UFBX_SHADER_SHADERFX_GRAPH;
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_material, p_material, uc->scene.materials) {
+ ufbx_material *material = *p_material;
+ material->shader = (ufbx_shader*)ufbxi_fetch_src_element(&material->element, false, NULL, UFBX_ELEMENT_SHADER);
+
+ if (!strcmp(material->shading_model_name.data, "lambert") || !strcmp(material->shading_model_name.data, "Lambert")) {
+ material->shader_type = UFBX_SHADER_FBX_LAMBERT;
+ } else if (!strcmp(material->shading_model_name.data, "phong") || !strcmp(material->shading_model_name.data, "Phong")) {
+ material->shader_type = UFBX_SHADER_FBX_PHONG;
+ }
+
+ if (material->shader) {
+ material->shader_type = material->shader->type;
+ } else {
+ if (uc->opts.use_blender_pbr_material && uc->exporter == UFBX_EXPORTER_BLENDER_BINARY && uc->exporter_version >= ufbx_pack_version(4,12,0)) {
+ material->shader_type = UFBX_SHADER_BLENDER_PHONG;
+ }
+
+ // TODO: Is this too strict?
+ if (material->shader_type == UFBX_SHADER_UNKNOWN) {
+ uint32_t classid_a = (uint32_t)(uint64_t)ufbx_find_int(&material->props, "3dsMax|ClassIDa", 0);
+ uint32_t classid_b = (uint32_t)(uint64_t)ufbx_find_int(&material->props, "3dsMax|ClassIDb", 0);
+ if (classid_a == 0x3d6b1cecu && classid_b == 0xdeadc001u) {
+ material->shader_type = UFBX_SHADER_3DS_MAX_PHYSICAL_MATERIAL;
+ material->shader_prop_prefix.data = "3dsMax|Parameters|";
+ material->shader_prop_prefix.length = strlen("3dsMax|Parameters|");
+ } else if (classid_a == 0xf1551e33u && classid_b == 0x37fb1337u) {
+ material->shader_type = UFBX_SHADER_OPENPBR_MATERIAL;
+ material->shader_prop_prefix.data = "3dsMax|Parameters|";
+ material->shader_prop_prefix.length = strlen("3dsMax|Parameters|");
+ } else if (classid_a == 0x38420192u && classid_b == 0x45fe4e1bu) {
+ material->shader_type = UFBX_SHADER_GLTF_MATERIAL;
+ material->shader_prop_prefix.data = "3dsMax|";
+ material->shader_prop_prefix.length = strlen("3dsMax|");
+ } else if (classid_a == 0xd00f1e00u && classid_b == 0xbe77e500u) {
+ material->shader_type = UFBX_SHADER_3DS_MAX_PBR_METAL_ROUGH;
+ material->shader_prop_prefix.data = "3dsMax|main|";
+ material->shader_prop_prefix.length = strlen("3dsMax|main|");
+ } else if (classid_a == 0xd00f1e00u && classid_b == 0x01dbad33u) {
+ material->shader_type = UFBX_SHADER_3DS_MAX_PBR_SPEC_GLOSS;
+ material->shader_prop_prefix.data = "3dsMax|main|";
+ material->shader_prop_prefix.length = strlen("3dsMax|main|");
+ }
+ }
+ }
+
+ ufbxi_check(ufbxi_fetch_textures(uc, &material->textures, &material->element, false));
+ }
+
+ // Ugh.. Patch the textures from meshes for legacy LayerElement-style textures
+ {
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+ size_t num_materials = mesh->materials.count;
+
+ ufbxi_mesh_extra *extra = (ufbxi_mesh_extra*)ufbxi_get_element_extra(uc, mesh->element.element_id);
+ if (!extra) continue;
+ if (num_materials == 0) continue;
+
+ // TODO: This leaks currently to result, probably doesn't matter..
+ ufbx_texture_list textures;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &textures, &mesh->element, true, false, NULL, UFBX_ELEMENT_TEXTURE));
+
+ size_t num_material_textures = 0;
+ ufbxi_for(ufbxi_tmp_mesh_texture, tex, extra->texture_arr, extra->texture_count) {
+ if (tex->all_same) {
+ int32_t texture_id = tex->num_faces > 0 ? (int32_t)tex->face_texture[0] : 0;
+ if (texture_id >= 0 && (size_t)texture_id < textures.count) {
+ ufbxi_tmp_material_texture *mat_texs = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, num_materials);
+ ufbxi_check(mat_texs);
+ num_material_textures += num_materials;
+ for (size_t i = 0; i < num_materials; i++) {
+ mat_texs[i].material_id = (int32_t)i;
+ mat_texs[i].texture_id = texture_id;
+ mat_texs[i].prop_name = tex->prop_name;
+ }
+ }
+ } else if (mesh->face_material.count) {
+ size_t num_faces = ufbxi_min_sz(tex->num_faces, mesh->num_faces);
+ int32_t prev_material = -1;
+ int32_t prev_texture = -1;
+ for (size_t i = 0; i < num_faces; i++) {
+ int32_t texture_id = (int32_t)tex->face_texture[i];
+ int32_t material_id = (int32_t)mesh->face_material.data[i];
+ if (texture_id < 0 || (size_t)texture_id >= textures.count) continue;
+ if (material_id < 0 || (size_t)material_id >= num_materials) continue;
+ if (material_id == prev_material && texture_id == prev_texture) continue;
+ prev_material = material_id;
+ prev_texture = texture_id;
+
+ ufbxi_tmp_material_texture *mat_tex = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, 1);
+ ufbxi_check(mat_tex);
+ mat_tex->material_id = material_id;
+ mat_tex->texture_id = texture_id;
+ mat_tex->prop_name = tex->prop_name;
+ num_material_textures++;
+ }
+ }
+ }
+
+ // Push a sentinel material texture to the end so we don't need to
+ // duplicate the material texture flushing code twice.
+ {
+ ufbxi_tmp_material_texture *mat_tex = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, 1);
+ ufbxi_check(mat_tex);
+ mat_tex->material_id = -1;
+ mat_tex->texture_id = -1;
+ mat_tex->prop_name = ufbx_empty_string;
+ }
+
+ ufbxi_tmp_material_texture *mat_texs = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_tmp_material_texture, num_material_textures + 1);
+ ufbxi_check(mat_texs);
+ ufbxi_check(ufbxi_sort_tmp_material_textures(uc, mat_texs, num_material_textures));
+
+ int32_t prev_material = -2;
+ int32_t prev_texture = -2;
+ const char *prev_prop = NULL;
+ size_t num_textures_in_material = 0;
+ for (size_t i = 0; i < num_material_textures + 1; i++) {
+ ufbxi_tmp_material_texture mat_tex = mat_texs[i];
+ if (mat_tex.material_id != prev_material) {
+ if (prev_material >= 0 && num_textures_in_material > 0) {
+ ufbx_material *mat = mesh->materials.data[prev_material];
+ if (mat && mat->textures.count == 0) {
+ ufbx_material_texture *texs = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material_texture, num_textures_in_material);
+ ufbxi_check(texs);
+ mat->textures.data = texs;
+ mat->textures.count = num_textures_in_material;
+ } else {
+ ufbxi_pop(&uc->tmp_stack, ufbx_material_texture, num_textures_in_material, NULL);
+ }
+ }
+
+ if (mat_tex.material_id < 0) break;
+ prev_material = mat_tex.material_id;
+ prev_texture = -1;
+ prev_prop = NULL;
+ num_textures_in_material = 0;
+ }
+ if (mat_tex.texture_id == prev_texture && mat_tex.prop_name.data == prev_prop) continue;
+ prev_texture = mat_tex.texture_id;
+ prev_prop = mat_tex.prop_name.data;
+
+ ufbx_material_texture *tex = ufbxi_push(&uc->tmp_stack, ufbx_material_texture, 1);
+ ufbxi_check(tex);
+ ufbx_assert(prev_texture >= 0 && (size_t)prev_texture < textures.count);
+ tex->texture = textures.data[prev_texture];
+ tex->shader_prop = tex->material_prop = mat_tex.prop_name;
+ num_textures_in_material++;
+ }
+ }
+ }
+
+ ufbxi_check(ufbxi_resolve_file_content(uc));
+
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, uc->scene.textures) {
+ ufbx_texture *texture = *p_texture;
+ ufbxi_texture_extra *extra = (ufbxi_texture_extra*)ufbxi_get_element_extra(uc, texture->element.element_id);
+
+ ufbx_prop *uv_set = ufbxi_find_prop(&texture->props, ufbxi_UVSet);
+ if (uv_set) {
+ texture->uv_set = uv_set->value_str;
+ } else {
+ texture->uv_set = ufbx_empty_string;
+ }
+
+ texture->video = (ufbx_video*)ufbxi_fetch_dst_element(&texture->element, false, NULL, UFBX_ELEMENT_VIDEO);
+ if (texture->video) {
+ texture->content = texture->video->content;
+ }
+
+ ufbxi_check(ufbxi_finalize_shader_texture(uc, texture));
+
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&texture->filename, (ufbxi_strblob*)&texture->absolute_filename, (ufbxi_strblob*)&texture->relative_filename, false));
+ ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&texture->raw_filename, (ufbxi_strblob*)&texture->raw_absolute_filename, (ufbxi_strblob*)&texture->raw_relative_filename, true));
+
+ // Fetch layered texture layers and patch alphas/blend modes
+ if (texture->type == UFBX_TEXTURE_LAYERED) {
+ ufbxi_check(ufbxi_fetch_texture_layers(uc, &texture->layers, &texture->element));
+ if (extra) {
+ for (size_t i = 0, num = ufbxi_min_sz(extra->num_alphas, texture->layers.count); i < num; i++) {
+ texture->layers.data[i].alpha = extra->alphas[i];
+ }
+ for (size_t i = 0, num = ufbxi_min_sz(extra->num_blend_modes, texture->layers.count); i < num; i++) {
+ int32_t mode = extra->blend_modes[i];
+ if (mode >= 0 && mode < UFBX_BLEND_OVERLAY) {
+ texture->layers.data[i].blend_mode = (ufbx_blend_mode)mode;
+ }
+ }
+ }
+ }
+
+ ufbxi_check(ufbxi_insert_texture_file(uc, texture));
+ }
+
+ ufbxi_propagate_main_textures(&uc->scene);
+ ufbxi_check(ufbxi_pop_texture_files(uc));
+
+ // Second pass to fetch material maps
+ ufbxi_for_ptr_list(ufbx_material, p_material, uc->scene.materials) {
+ ufbx_material *material = *p_material;
+
+ ufbxi_check(ufbxi_sort_material_textures(uc, material->textures.data, material->textures.count));
+ ufbxi_fetch_maps(&uc->scene, material);
+
+ // Fetch `ufbx_material_texture.shader_prop` names
+ if (material->shader) {
+ ufbxi_for_ptr_list(ufbx_shader_binding, p_binding, material->shader->bindings) {
+ ufbx_shader_binding *binding = *p_binding;
+
+ ufbxi_for_list(ufbx_shader_prop_binding, prop, binding->prop_bindings) {
+ ufbx_string name = prop->material_prop;
+
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_material_texture, 4, &index, material->textures.data, 0, material->textures.count,
+ ( ufbxi_str_less(a->material_prop, name) ), ( a->material_prop.data == name.data ));
+ for (; index < material->textures.count && material->textures.data[index].shader_prop.data == name.data; index++) {
+ material->textures.data[index].shader_prop = prop->shader_prop;
+ }
+ }
+ }
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_display_layer, p_layer, uc->scene.display_layers) {
+ ufbx_display_layer *layer = *p_layer;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->nodes, &layer->element, false, true, NULL, UFBX_ELEMENT_NODE));
+ }
+
+ ufbxi_for_ptr_list(ufbx_selection_set, p_set, uc->scene.selection_sets) {
+ ufbx_selection_set *set = *p_set;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &set->nodes, &set->element, false, true, NULL, UFBX_ELEMENT_SELECTION_NODE));
+ }
+
+ ufbxi_for_ptr_list(ufbx_selection_node, p_node, uc->scene.selection_nodes) {
+ ufbx_selection_node *node = *p_node;
+ node->target_node = (ufbx_node*)ufbxi_fetch_dst_element(&node->element, false, NULL, UFBX_ELEMENT_NODE);
+ node->target_mesh = (ufbx_mesh*)ufbxi_fetch_dst_element(&node->element, false, NULL, UFBX_ELEMENT_MESH);
+ if (!node->target_mesh && node->target_node) {
+ node->target_mesh = node->target_node->mesh;
+ } else if (!node->target_node && node->target_mesh && node->target_mesh->instances.count > 0) {
+ node->target_node = node->target_mesh->instances.data[0];
+ }
+
+ ufbx_mesh *mesh = node->target_mesh;
+ if (mesh) {
+ ufbxi_check(ufbxi_validate_indices(uc, &node->vertices, mesh->num_vertices));
+ ufbxi_check(ufbxi_validate_indices(uc, &node->edges, mesh->num_edges));
+ ufbxi_check(ufbxi_validate_indices(uc, &node->faces, mesh->num_faces));
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_constraint, p_constraint, uc->scene.constraints) {
+ ufbx_constraint *constraint = *p_constraint;
+
+ size_t tmp_base = uc->tmp_stack.num_items;
+
+ // Find property connections in _both_ src and dst connections as they are inconsistent
+ // in pre-7000 files. For example "Constrained Object" is a "PO" connection in 6100.
+ ufbxi_for_list(ufbx_connection, conn, constraint->element.connections_src) {
+ if (conn->src_prop.length == 0 || conn->dst->type != UFBX_ELEMENT_NODE) continue;
+ ufbxi_check(ufbxi_add_constraint_prop(uc, constraint, (ufbx_node*)conn->dst, conn->src_prop.data));
+ }
+ ufbxi_for_list(ufbx_connection, conn, constraint->element.connections_dst) {
+ if (conn->dst_prop.length == 0 || conn->src->type != UFBX_ELEMENT_NODE) continue;
+ ufbxi_check(ufbxi_add_constraint_prop(uc, constraint, (ufbx_node*)conn->src, conn->dst_prop.data));
+ }
+
+ size_t num_targets = uc->tmp_stack.num_items - tmp_base;
+ constraint->targets.count = num_targets;
+ constraint->targets.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_constraint_target, num_targets);
+ ufbxi_check(constraint->targets.data);
+ }
+
+ ufbxi_for_ptr_list(ufbx_audio_layer, p_layer, uc->scene.audio_layers) {
+ ufbx_audio_layer *layer = *p_layer;
+ ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->clips, &layer->element, false, true, NULL, UFBX_ELEMENT_AUDIO_CLIP));
+ }
+
+ ufbxi_for_ptr_list(ufbx_lod_group, p_lod, uc->scene.lod_groups) {
+ ufbxi_check(ufbxi_finalize_lod_group(uc, *p_lod));
+ }
+
+ ufbxi_check(ufbxi_fetch_file_textures(uc));
+
+ // NOTE: This will be patched over in `ufbxi_update_scene()` if there are `anim_layers`
+ if (uc->scene.anim_layers.count == 0) {
+ ufbxi_check(ufbxi_push_anim(uc, &uc->scene.anim, NULL, 0));
+ }
+
+ uc->scene.metadata.ktime_second = uc->ktime_sec;
+
+ // Maya seems to use scale of 100/3, Blender binary uses exactly 33, ASCII has always value of 1.0
+ if (uc->version < 6000) {
+ uc->scene.metadata.bone_prop_size_unit = 1.0f;
+ } else if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
+ uc->scene.metadata.bone_prop_size_unit = 33.0f;
+ } else if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
+ uc->scene.metadata.bone_prop_size_unit = 1.0f;
+ } else {
+ uc->scene.metadata.bone_prop_size_unit = (ufbx_real)(100.0/3.0);
+ }
+ if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
+ uc->scene.metadata.bone_prop_limb_length_relative = false;
+ } else {
+ uc->scene.metadata.bone_prop_limb_length_relative = true;
+ }
+
+ return 1;
+}
+
+// -- Interpret the read scene
+
+static ufbxi_forceinline void ufbxi_add_translate(ufbx_transform *t, ufbx_vec3 v)
+{
+ t->translation.x += v.x;
+ t->translation.y += v.y;
+ t->translation.z += v.z;
+}
+
+static ufbxi_forceinline void ufbxi_sub_translate(ufbx_transform *t, ufbx_vec3 v)
+{
+ t->translation.x -= v.x;
+ t->translation.y -= v.y;
+ t->translation.z -= v.z;
+}
+
+static ufbxi_forceinline void ufbxi_mul_scale(ufbx_transform *t, ufbx_vec3 v)
+{
+ t->translation.x *= v.x;
+ t->translation.y *= v.y;
+ t->translation.z *= v.z;
+ t->scale.x *= v.x;
+ t->scale.y *= v.y;
+ t->scale.z *= v.z;
+}
+
+static ufbxi_forceinline void ufbxi_mul_scale_real(ufbx_transform *t, ufbx_real v)
+{
+ t->translation.x *= v;
+ t->translation.y *= v;
+ t->translation.z *= v;
+ t->scale.x *= v;
+ t->scale.y *= v;
+ t->scale.z *= v;
+}
+
+static ufbxi_noinline ufbx_quat ufbxi_mul_quat(ufbx_quat a, ufbx_quat b)
+{
+ ufbx_quat r;
+ r.x = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y;
+ r.y = a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x;
+ r.z = a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w;
+ r.w = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z;
+ return r;
+}
+
+static ufbxi_forceinline void ufbxi_add_weighted_vec3(ufbx_vec3 *r, ufbx_vec3 b, ufbx_real w)
+{
+ r->x += b.x * w;
+ r->y += b.y * w;
+ r->z += b.z * w;
+}
+
+static ufbxi_forceinline void ufbxi_add_weighted_quat(ufbx_quat *r, ufbx_quat b, ufbx_real w)
+{
+ r->x += b.x * w;
+ r->y += b.y * w;
+ r->z += b.z * w;
+ r->w += b.w * w;
+}
+
+static ufbxi_noinline void ufbxi_add_weighted_mat(ufbx_matrix *r, const ufbx_matrix *b, ufbx_real w)
+{
+ ufbxi_add_weighted_vec3(&r->cols[0], b->cols[0], w);
+ ufbxi_add_weighted_vec3(&r->cols[1], b->cols[1], w);
+ ufbxi_add_weighted_vec3(&r->cols[2], b->cols[2], w);
+ ufbxi_add_weighted_vec3(&r->cols[3], b->cols[3], w);
+}
+
+static void ufbxi_mul_rotate(ufbx_transform *t, ufbx_vec3 v, ufbx_rotation_order order)
+{
+ if (ufbxi_is_vec3_zero(v)) return;
+
+ ufbx_quat q = ufbx_euler_to_quat(v, order);
+ if (t->rotation.w != 1.0) {
+ t->rotation = ufbxi_mul_quat(q, t->rotation);
+ } else {
+ t->rotation = q;
+ }
+
+ if (!ufbxi_is_vec3_zero(t->translation)) {
+ t->translation = ufbx_quat_rotate_vec3(q, t->translation);
+ }
+}
+
+static void ufbxi_mul_rotate_quat(ufbx_transform *t, ufbx_quat q)
+{
+ if (ufbxi_is_quat_identity(q)) return;
+
+ if (t->rotation.w != 1.0) {
+ t->rotation = ufbxi_mul_quat(q, t->rotation);
+ } else {
+ t->rotation = q;
+ }
+
+ if (!ufbxi_is_vec3_zero(t->translation)) {
+ t->translation = ufbx_quat_rotate_vec3(q, t->translation);
+ }
+}
+
+static void ufbxi_mul_inv_rotate(ufbx_transform *t, ufbx_vec3 v, ufbx_rotation_order order)
+{
+ if (ufbxi_is_vec3_zero(v)) return;
+
+ ufbx_quat q = ufbx_euler_to_quat(v, order);
+ q.x = -q.x; q.y = -q.y; q.z = -q.z;
+ if (t->rotation.w != 1.0) {
+ t->rotation = ufbxi_mul_quat(q, t->rotation);
+ } else {
+ t->rotation = q;
+ }
+
+ if (!ufbxi_is_vec3_zero(t->translation)) {
+ t->translation = ufbx_quat_rotate_vec3(q, t->translation);
+ }
+}
+
+// -- Updating state from properties
+
+ufbxi_forceinline static void ufbxi_mirror_translation(ufbx_vec3 *p_vec, ufbx_mirror_axis axis)
+{
+ ufbxi_dev_assert(axis);
+ p_vec->v[axis - 1] = -p_vec->v[axis - 1];
+}
+
+ufbxi_forceinline static void ufbxi_mirror_rotation(ufbx_quat *p_quat, ufbx_mirror_axis axis)
+{
+ ufbxi_dev_assert(axis);
+ p_quat->v[axis % 3] = -p_quat->v[axis % 3];
+ p_quat->v[(axis + 1) % 3] = -p_quat->v[(axis + 1) % 3];
+}
+
+ufbxi_noinline static ufbx_transform ufbxi_get_geometry_transform(const ufbx_props *props, ufbx_node *node)
+{
+ ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_GeometricRotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_GeometricScaling, 1.0f, 1.0f, 1.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ // WorldTransform = ParentWorldTransform * T * R * S * (OT * OR * OS)
+
+ ufbxi_mul_scale(&t, scaling);
+ ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_add_translate(&t, translation);
+
+ if (node->has_adjust_transform) {
+ t.translation.x *= node->adjust_translation_scale;
+ t.translation.y *= node->adjust_translation_scale;
+ t.translation.z *= node->adjust_translation_scale;
+ }
+
+ if (node->adjust_mirror_axis) {
+ ufbxi_mirror_translation(&t.translation, node->adjust_mirror_axis);
+ ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
+ }
+
+ return t;
+}
+
+ufbxi_noinline static ufbx_quat ufbxi_get_rotation(const ufbx_props *props, ufbx_rotation_order order, const ufbx_node *node)
+{
+ ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 pre_rotation = ufbxi_find_vec3(props, ufbxi_PreRotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 post_rotation = ufbxi_find_vec3(props, ufbxi_PostRotation, 0.0f, 0.0f, 0.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ if (node->has_adjust_transform) {
+ ufbxi_mul_rotate_quat(&t, node->adjust_post_rotation);
+ }
+
+ if (node->use_rotation_space) {
+ ufbxi_mul_inv_rotate(&t, post_rotation, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_mul_rotate(&t, rotation, order);
+ ufbxi_mul_rotate(&t, pre_rotation, UFBX_ROTATION_ORDER_XYZ);
+ } else {
+ ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
+ }
+
+ if (node->has_adjust_transform) {
+ ufbxi_mul_rotate_quat(&t, node->adjust_pre_rotation);
+ }
+
+ if (node->adjust_mirror_axis) {
+ ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
+ }
+
+ return t.rotation;
+}
+
+ufbxi_noinline static ufbx_vec3 ufbxi_get_scale(const ufbx_props *props, const ufbx_node *node)
+{
+ ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ if (node->has_adjust_transform) {
+ ufbxi_mul_scale_real(&t, node->adjust_post_scale);
+ }
+
+ ufbxi_mul_scale(&t, scaling);
+
+ if (node->has_adjust_transform) {
+ ufbxi_mul_scale_real(&t, node->adjust_pre_scale);
+ }
+
+ return t.scale;
+}
+
+ufbxi_noinline static ufbx_transform ufbxi_get_transform(const ufbx_props *props, ufbx_rotation_order order, const ufbx_node *node, const ufbx_vec3 *translation_scale)
+{
+ ufbx_vec3 scale_pivot = ufbxi_find_vec3(props, ufbxi_ScalingPivot, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rot_pivot = ufbxi_find_vec3(props, ufbxi_RotationPivot, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scale_offset = ufbxi_find_vec3(props, ufbxi_ScalingOffset, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rot_offset = ufbxi_find_vec3(props, ufbxi_RotationOffset, 0.0f, 0.0f, 0.0f);
+
+ ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Lcl_Translation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
+
+ ufbx_vec3 pre_rotation = ufbxi_find_vec3(props, ufbxi_PreRotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 post_rotation = ufbxi_find_vec3(props, ufbxi_PostRotation, 0.0f, 0.0f, 0.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ // WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
+ // NOTE: Rpost is inverted (!) after converting from PostRotation Euler angles
+
+ if (translation_scale) {
+ translation.x *= translation_scale->x;
+ translation.y *= translation_scale->y;
+ translation.z *= translation_scale->z;
+ }
+
+ if (node->has_adjust_transform) {
+ ufbxi_mul_rotate_quat(&t, node->adjust_post_rotation);
+ ufbxi_mul_scale_real(&t, node->adjust_post_scale);
+ }
+
+ ufbxi_sub_translate(&t, scale_pivot);
+ ufbxi_mul_scale(&t, scaling);
+ ufbxi_add_translate(&t, scale_pivot);
+
+ ufbxi_add_translate(&t, scale_offset);
+
+ ufbxi_sub_translate(&t, rot_pivot);
+ if (node->use_rotation_space) {
+ ufbxi_mul_inv_rotate(&t, post_rotation, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_mul_rotate(&t, rotation, order);
+ ufbxi_mul_rotate(&t, pre_rotation, UFBX_ROTATION_ORDER_XYZ);
+ } else {
+ ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
+ }
+ ufbxi_add_translate(&t, rot_pivot);
+
+ ufbxi_add_translate(&t, rot_offset);
+
+ ufbxi_add_translate(&t, translation);
+
+ if (node->has_adjust_transform) {
+ ufbxi_add_translate(&t, node->adjust_pre_translation);
+ ufbxi_mul_rotate_quat(&t, node->adjust_pre_rotation);
+ ufbxi_mul_scale_real(&t, node->adjust_pre_scale);
+ t.translation.x *= node->adjust_translation_scale;
+ t.translation.y *= node->adjust_translation_scale;
+ t.translation.z *= node->adjust_translation_scale;
+ }
+
+ if (node->adjust_mirror_axis) {
+ ufbxi_mirror_translation(&t.translation, node->adjust_mirror_axis);
+ ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
+ }
+
+ // Make sure the fast paths are identical to this function.
+ ufbxi_regression_assert(ufbxi_is_quat_equal(t.rotation, ufbxi_get_rotation(props, order, node)));
+ ufbxi_regression_assert(ufbxi_is_vec3_equal(t.scale, ufbxi_get_scale(props, node)));
+
+ return t;
+}
+
+ufbxi_noinline static ufbx_transform ufbxi_get_texture_transform(const ufbx_props *props)
+{
+ ufbx_vec3 scale_pivot = ufbxi_find_vec3(props, ufbxi_TextureScalingPivot, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rot_pivot = ufbxi_find_vec3(props, ufbxi_TextureRotationPivot, 0.0f, 0.0f, 0.0f);
+
+ ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Translation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Rotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Scaling, 1.0f, 1.0f, 1.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ ufbxi_sub_translate(&t, scale_pivot);
+ ufbxi_mul_scale(&t, scaling);
+ ufbxi_add_translate(&t, scale_pivot);
+
+ ufbxi_sub_translate(&t, rot_pivot);
+ ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_add_translate(&t, rot_pivot);
+
+ ufbxi_add_translate(&t, translation);
+
+ if (ufbxi_find_int(props, ufbxi_UVSwap, 0) != 0) {
+ const ufbx_vec3 swap_scale = { -1.0f, 0.0f, 0.0f };
+ const ufbx_vec3 swap_rotate = { 0.0f, 0.0f, -90.0f };
+ ufbxi_mul_scale(&t, swap_scale);
+ ufbxi_mul_rotate(&t, swap_rotate, UFBX_ROTATION_ORDER_XYZ);
+ }
+
+ return t;
+}
+
+ufbxi_noinline static ufbx_transform ufbxi_get_constraint_transform(const ufbx_props *props)
+{
+ ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Translation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Rotation, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 rotation_offset = ufbxi_find_vec3(props, ufbxi_RotationOffset, 0.0f, 0.0f, 0.0f);
+ ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Scaling, 1.0f, 1.0f, 1.0f);
+
+ ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
+
+ ufbxi_mul_scale(&t, scaling);
+ ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_mul_rotate(&t, rotation_offset, UFBX_ROTATION_ORDER_XYZ);
+ ufbxi_add_translate(&t, translation);
+
+ return t;
+}
+
+ufbxi_noinline static void ufbxi_update_node(ufbx_node *node, const ufbx_transform_override *overrides, size_t num_overrides)
+{
+ node->rotation_order = (ufbx_rotation_order)ufbxi_find_enum(&node->props, ufbxi_RotationOrder, UFBX_ROTATION_ORDER_XYZ, UFBX_ROTATION_ORDER_SPHERIC);
+ node->euler_rotation = ufbxi_find_vec3(&node->props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
+
+ if (!node->is_root) {
+ const bool rotation_active = ufbxi_find_int(&node->props, ufbxi_RotationActive, 1) != 0;
+ const bool rotation_limit_only = ufbxi_find_int(&node->props, ufbxi_RotationSpaceForLimitOnly, 0) != 0;
+ node->use_rotation_space = rotation_active && !rotation_limit_only;
+
+ const ufbx_vec3 *transform_scale = NULL;
+ if (node->parent && node->parent->scale_helper) {
+ transform_scale = &node->parent->scale_helper->local_transform.scale;
+ }
+ node->local_transform = ufbxi_get_transform(&node->props, node->rotation_order, node, transform_scale);
+ if (node->is_scale_helper && node->parent && node->parent->inherit_scale_node) {
+ ufbx_node *scale_parent = node->parent->inherit_scale_node;
+ if (scale_parent->scale_helper) {
+ ufbx_vec3 inherit_scale = scale_parent->scale_helper->local_transform.scale;
+ node->local_transform.scale.x *= inherit_scale.x;
+ node->local_transform.scale.y *= inherit_scale.y;
+ node->local_transform.scale.z *= inherit_scale.z;
+ }
+ }
+
+ if (num_overrides > 0) {
+ uint32_t typed_id = node->typed_id;
+ size_t override_ix = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_transform_override, 16, &override_ix, overrides, 0, num_overrides,
+ ( a->node_id < typed_id ), ( a->node_id == typed_id ));
+ if (override_ix != SIZE_MAX) {
+ node->local_transform = overrides[override_ix].transform;
+ }
+ }
+ node->node_to_parent = ufbx_transform_to_matrix(&node->local_transform);
+ node->geometry_transform = ufbxi_get_geometry_transform(&node->props, node);
+ } else {
+ node->geometry_transform = ufbx_identity_transform;
+ }
+
+ ufbx_matrix unscaled_node_to_parent = ufbxi_unscaled_transform_to_matrix(&node->local_transform);
+
+ node->inherit_scale = node->local_transform.scale;
+
+ ufbx_node *parent = node->parent;
+ if (parent) {
+ if (node->inherit_mode == UFBX_INHERIT_MODE_NORMAL) {
+ node->node_to_world = ufbx_matrix_mul(&parent->node_to_world, &node->node_to_parent);
+ node->unscaled_node_to_world = ufbx_matrix_mul(&parent->node_to_world, &unscaled_node_to_parent);
+ } else {
+ ufbx_transform transform = node->local_transform;
+
+ ufbx_vec3 parent_scale = ufbxi_one_vec3;
+ if (node->inherit_scale_node) {
+ parent_scale = node->inherit_scale_node->inherit_scale;
+ }
+
+ transform.scale.x *= parent_scale.x;
+ transform.scale.y *= parent_scale.y;
+ transform.scale.z *= parent_scale.z;
+ transform.translation.x *= parent->inherit_scale.x;
+ transform.translation.y *= parent->inherit_scale.y;
+ transform.translation.z *= parent->inherit_scale.z;
+
+ ufbx_matrix node_to_unscaled_parent = ufbx_transform_to_matrix(&transform);
+ ufbx_matrix unscaled_node_to_unscaled_parent = ufbxi_unscaled_transform_to_matrix(&transform);
+
+ node->inherit_scale = transform.scale;
+ node->node_to_world = ufbx_matrix_mul(&parent->unscaled_node_to_world, &node_to_unscaled_parent);
+ node->unscaled_node_to_world = ufbx_matrix_mul(&parent->unscaled_node_to_world, &unscaled_node_to_unscaled_parent);
+ }
+ } else {
+ node->node_to_world = node->node_to_parent;
+ node->unscaled_node_to_world = unscaled_node_to_parent;
+ }
+
+ if (!ufbxi_is_transform_identity(&node->geometry_transform)) {
+ node->geometry_to_node = ufbx_transform_to_matrix(&node->geometry_transform);
+ node->geometry_to_world = ufbx_matrix_mul(&node->node_to_world, &node->geometry_to_node);
+ node->has_geometry_transform = true;
+ } else {
+ node->geometry_to_node = ufbx_identity_matrix;
+ node->geometry_to_world = node->node_to_world;
+ node->has_geometry_transform = false;
+ }
+
+ node->visible = ufbxi_find_int(&node->props, ufbxi_Visibility, 1) != 0;
+}
+
+ufbxi_noinline static void ufbxi_update_light(ufbx_light *light)
+{
+ // NOTE: FBX seems to store intensities 100x of what's specified in at least
+ // Maya and Blender, should there be a quirks mode to not do this for specific
+ // exporters. Does the FBX SDK do this transparently as well?
+ light->intensity = ufbxi_find_real(&light->props, ufbxi_Intensity, (ufbx_real)100.0) / (ufbx_real)100.0;
+
+ light->color = ufbxi_find_vec3(&light->props, ufbxi_Color, 1.0f, 1.0f, 1.0f);
+ light->type = (ufbx_light_type)ufbxi_find_enum(&light->props, ufbxi_LightType, 0, UFBX_LIGHT_VOLUME);
+ light->decay = (ufbx_light_decay)ufbxi_find_enum(&light->props, ufbxi_DecayType, UFBX_LIGHT_DECAY_NONE, UFBX_LIGHT_DECAY_CUBIC);
+ light->area_shape = (ufbx_light_area_shape)ufbxi_find_enum(&light->props, ufbxi_AreaLightShape, 0, UFBX_LIGHT_AREA_SHAPE_SPHERE);
+ light->inner_angle = ufbxi_find_real(&light->props, ufbxi_HotSpot, 0.0f);
+ light->inner_angle = ufbxi_find_real(&light->props, ufbxi_InnerAngle, light->inner_angle);
+ light->outer_angle = ufbxi_find_real(&light->props, ufbxi_Cone_angle, 0.0f);
+ light->outer_angle = ufbxi_find_real(&light->props, ufbxi_ConeAngle, light->outer_angle);
+ light->outer_angle = ufbxi_find_real(&light->props, ufbxi_OuterAngle, light->outer_angle);
+ light->cast_light = ufbxi_find_int(&light->props, ufbxi_CastLight, 1) != 0;
+ light->cast_shadows = ufbxi_find_int(&light->props, ufbxi_CastShadows, 0) != 0;
+}
+
+typedef struct {
+ // 1/1000 decimal fixed point for size
+ uint16_t film_size_x, film_size_y;
+} ufbxi_aperture_format;
+
+static const ufbxi_aperture_format ufbxi_aperture_formats[] = {
+ { 1000, 1000, }, // UFBX_APERTURE_FORMAT_CUSTOM
+ { 404, 295, }, // UFBX_APERTURE_FORMAT_16MM_THEATRICAL
+ { 493, 292, }, // UFBX_APERTURE_FORMAT_SUPER_16MM
+ { 864, 630, }, // UFBX_APERTURE_FORMAT_35MM_ACADEMY
+ { 816, 612, }, // UFBX_APERTURE_FORMAT_35MM_TV_PROJECTION
+ { 980, 735, }, // UFBX_APERTURE_FORMAT_35MM_FULL_APERTURE
+ { 825, 446, }, // UFBX_APERTURE_FORMAT_35MM_185_PROJECTION
+ { 864, 732, }, // UFBX_APERTURE_FORMAT_35MM_ANAMORPHIC
+ { 2066, 906, }, // UFBX_APERTURE_FORMAT_70MM_PROJECTION
+ { 1485, 991, }, // UFBX_APERTURE_FORMAT_VISTAVISION
+ { 2080, 1480, }, // UFBX_APERTURE_FORMAT_DYNAVISION
+ { 2772, 2072, }, // UFBX_APERTURE_FORMAT_IMAX
+};
+
+ufbxi_noinline static void ufbxi_update_camera(ufbx_scene *scene, ufbx_camera *camera)
+{
+ camera->projection_mode = (ufbx_projection_mode)ufbxi_find_enum(&camera->props, ufbxi_CameraProjectionType, 0, UFBX_PROJECTION_MODE_ORTHOGRAPHIC);
+ camera->aspect_mode = (ufbx_aspect_mode)ufbxi_find_enum(&camera->props, ufbxi_AspectRatioMode, 0, UFBX_ASPECT_MODE_FIXED_HEIGHT);
+ camera->aperture_mode = (ufbx_aperture_mode)ufbxi_find_enum(&camera->props, ufbxi_ApertureMode, UFBX_APERTURE_MODE_VERTICAL, UFBX_APERTURE_MODE_FOCAL_LENGTH);
+ camera->aperture_format = (ufbx_aperture_format)ufbxi_find_enum(&camera->props, ufbxi_ApertureFormat, UFBX_APERTURE_FORMAT_CUSTOM, UFBX_APERTURE_FORMAT_IMAX);
+ camera->gate_fit = (ufbx_gate_fit)ufbxi_find_enum(&camera->props, ufbxi_GateFit, 0, UFBX_GATE_FIT_STRETCH);
+
+ camera->near_plane = ufbxi_find_real(&camera->props, ufbxi_NearPlane, 0.0f);
+ camera->far_plane = ufbxi_find_real(&camera->props, ufbxi_FarPlane, 0.0f);
+
+ // Search both W/H and Width/Height but prefer the latter
+ ufbx_real aspect_x = ufbxi_find_real(&camera->props, ufbxi_AspectW, 0.0f);
+ ufbx_real aspect_y = ufbxi_find_real(&camera->props, ufbxi_AspectH, 0.0f);
+ aspect_x = ufbxi_find_real(&camera->props, ufbxi_AspectWidth, aspect_x);
+ aspect_y = ufbxi_find_real(&camera->props, ufbxi_AspectHeight, aspect_y);
+
+ ufbx_real fov = ufbxi_find_real(&camera->props, ufbxi_FieldOfView, 0.0f);
+ ufbx_real fov_x = ufbxi_find_real(&camera->props, ufbxi_FieldOfViewX, 0.0f);
+ ufbx_real fov_y = ufbxi_find_real(&camera->props, ufbxi_FieldOfViewY, 0.0f);
+
+ ufbx_real focal_length = ufbxi_find_real(&camera->props, ufbxi_FocalLength, 0.0f);
+ ufbx_real ortho_extent = scene->metadata.ortho_size_unit * ufbxi_find_real(&camera->props, ufbxi_OrthoZoom, 1.0f);
+
+ ufbxi_aperture_format format = ufbxi_aperture_formats[camera->aperture_format];
+ ufbx_vec2 film_size = { (ufbx_real)format.film_size_x * (ufbx_real)0.001, (ufbx_real)format.film_size_y * (ufbx_real)0.001 };
+ ufbx_real squeeze_ratio = camera->aperture_format == UFBX_APERTURE_FORMAT_35MM_ANAMORPHIC ? 2.0f : 1.0f;
+
+ film_size.x = ufbxi_find_real(&camera->props, ufbxi_FilmWidth, film_size.x);
+ film_size.y = ufbxi_find_real(&camera->props, ufbxi_FilmHeight, film_size.y);
+ squeeze_ratio = ufbxi_find_real(&camera->props, ufbxi_FilmSqueezeRatio, squeeze_ratio);
+
+ if (aspect_x <= 0.0f && aspect_y <= 0.0f) {
+ aspect_x = film_size.x > 0.0f ? film_size.x : 1.0f;
+ aspect_y = film_size.y > 0.0f ? film_size.y : 1.0f;
+ } else if (aspect_x <= 0.0f) {
+ if (film_size.x > 0.0f && film_size.y > 0.0f) {
+ aspect_x = aspect_y / film_size.y * film_size.x;
+ } else {
+ aspect_x = aspect_y;
+ }
+ } else if (aspect_y <= 0.0f) {
+ if (film_size.x > 0.0f && film_size.y > 0.0f) {
+ aspect_y = aspect_x / film_size.x * film_size.y;
+ } else {
+ aspect_y = aspect_x;
+ }
+ }
+
+ film_size.y *= squeeze_ratio;
+
+ // TODO: Should this be done always?
+ ortho_extent *= scene->metadata.geometry_scale;
+ camera->near_plane *= scene->metadata.geometry_scale;
+ camera->far_plane *= scene->metadata.geometry_scale;
+
+ camera->focal_length_mm = focal_length;
+ camera->film_size_inch = film_size;
+ camera->squeeze_ratio = squeeze_ratio;
+ camera->orthographic_extent = ortho_extent;
+
+ switch (camera->aspect_mode) {
+ case UFBX_ASPECT_MODE_WINDOW_SIZE:
+ case UFBX_ASPECT_MODE_FIXED_RATIO:
+ camera->resolution_is_pixels = false;
+ camera->resolution.x = aspect_x;
+ camera->resolution.y = aspect_y;
+ break;
+ case UFBX_ASPECT_MODE_FIXED_RESOLUTION:
+ camera->resolution_is_pixels = true;
+ camera->resolution.x = aspect_x;
+ camera->resolution.y = aspect_y;
+ break;
+ case UFBX_ASPECT_MODE_FIXED_WIDTH:
+ camera->resolution_is_pixels = true;
+ camera->resolution.x = aspect_x;
+ camera->resolution.y = aspect_x * aspect_y;
+ break;
+ case UFBX_ASPECT_MODE_FIXED_HEIGHT:
+ camera->resolution_is_pixels = true;
+ camera->resolution.x = aspect_y * aspect_x;
+ camera->resolution.y = aspect_y;
+ break;
+ default:
+ ufbxi_unreachable("Unexpected aspect mode");
+ }
+
+ ufbx_real aspect_ratio = camera->resolution.x / camera->resolution.y;
+ ufbx_real film_ratio = film_size.x / film_size.y;
+
+ camera->aspect_ratio = aspect_ratio;
+
+ ufbx_gate_fit effective_fit = camera->gate_fit;
+ if (effective_fit == UFBX_GATE_FIT_FILL) {
+ effective_fit = aspect_ratio > film_ratio ? UFBX_GATE_FIT_HORIZONTAL : UFBX_GATE_FIT_VERTICAL;
+ } else if (effective_fit == UFBX_GATE_FIT_OVERSCAN) {
+ effective_fit = aspect_ratio < film_ratio ? UFBX_GATE_FIT_HORIZONTAL : UFBX_GATE_FIT_VERTICAL;
+ }
+
+ switch (effective_fit) {
+ case UFBX_GATE_FIT_NONE:
+ camera->aperture_size_inch = camera->film_size_inch;
+ camera->orthographic_size.x = ortho_extent;
+ camera->orthographic_size.y = ortho_extent;
+ break;
+ case UFBX_GATE_FIT_VERTICAL:
+ camera->aperture_size_inch.x = camera->film_size_inch.y * aspect_ratio;
+ camera->aperture_size_inch.y = camera->film_size_inch.y;
+ camera->orthographic_size.x = ortho_extent * aspect_ratio;
+ camera->orthographic_size.y = ortho_extent;
+ break;
+ case UFBX_GATE_FIT_HORIZONTAL:
+ camera->aperture_size_inch.x = camera->film_size_inch.x;
+ camera->aperture_size_inch.y = camera->film_size_inch.x / aspect_ratio;
+ camera->orthographic_size.x = ortho_extent;
+ camera->orthographic_size.y = ortho_extent / aspect_ratio;
+ break;
+ case UFBX_GATE_FIT_FILL:
+ case UFBX_GATE_FIT_OVERSCAN:
+ camera->aperture_size_inch = camera->film_size_inch;
+ camera->orthographic_size.x = ortho_extent;
+ camera->orthographic_size.y = ortho_extent;
+ ufbxi_unreachable("Unreachable, set to vertical/horizontal above");
+ break;
+ case UFBX_GATE_FIT_STRETCH:
+ camera->aperture_size_inch = camera->film_size_inch;
+ camera->orthographic_size.x = ortho_extent;
+ camera->orthographic_size.y = ortho_extent;
+ // TODO: Not sure what to do here...
+ break;
+ default:
+ ufbxi_unreachable("Unexpected gate fit");
+ }
+
+ switch (camera->aperture_mode) {
+ case UFBX_APERTURE_MODE_HORIZONTAL_AND_VERTICAL:
+ camera->field_of_view_deg.x = fov_x;
+ camera->field_of_view_deg.y = fov_y;
+ camera->field_of_view_tan.x = (ufbx_real)ufbx_tan((double)(fov_x * (UFBXI_DEG_TO_RAD * 0.5f)));
+ camera->field_of_view_tan.y = (ufbx_real)ufbx_tan((double)(fov_y * (UFBXI_DEG_TO_RAD * 0.5f)));
+ break;
+ case UFBX_APERTURE_MODE_HORIZONTAL:
+ camera->field_of_view_deg.x = fov;
+ camera->field_of_view_tan.x = (ufbx_real)ufbx_tan((double)(fov * (UFBXI_DEG_TO_RAD * 0.5f)));
+ camera->field_of_view_tan.y = camera->field_of_view_tan.x / aspect_ratio;
+ camera->field_of_view_deg.y = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.y) * UFBXI_RAD_TO_DEG * 2.0f;
+ break;
+ case UFBX_APERTURE_MODE_VERTICAL:
+ camera->field_of_view_deg.y = fov;
+ camera->field_of_view_tan.y = (ufbx_real)ufbx_tan((double)(fov * (UFBXI_DEG_TO_RAD * 0.5f)));
+ camera->field_of_view_tan.x = camera->field_of_view_tan.y * aspect_ratio;
+ camera->field_of_view_deg.x = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.x) * UFBXI_RAD_TO_DEG * 2.0f;
+ break;
+ case UFBX_APERTURE_MODE_FOCAL_LENGTH:
+ camera->field_of_view_tan.x = camera->aperture_size_inch.x / (camera->focal_length_mm * UFBXI_MM_TO_INCH) * 0.5f;
+ camera->field_of_view_tan.y = camera->aperture_size_inch.y / (camera->focal_length_mm * UFBXI_MM_TO_INCH) * 0.5f;
+ camera->field_of_view_deg.x = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.x) * UFBXI_RAD_TO_DEG * 2.0f;
+ camera->field_of_view_deg.y = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.y) * UFBXI_RAD_TO_DEG * 2.0f;
+ break;
+ default:
+ ufbxi_unreachable("Unexpected aperture mode");
+ }
+
+ if (camera->projection_mode == UFBX_PROJECTION_MODE_PERSPECTIVE) {
+ camera->projection_plane = camera->field_of_view_tan;
+ } else {
+ camera->projection_plane = camera->orthographic_size;
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_bone(ufbx_scene *scene, ufbx_bone *bone)
+{
+ ufbx_real unit = scene->metadata.bone_prop_size_unit;
+
+ bone->radius = ufbxi_find_real(&bone->props, ufbxi_Size, unit) / unit;
+ if (scene->metadata.bone_prop_limb_length_relative) {
+ bone->relative_length = ufbxi_find_real(&bone->props, ufbxi_LimbLength, 1.0f);
+ } else {
+ bone->relative_length = 1.0f;
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_line_curve(ufbx_line_curve *line)
+{
+ line->color = ufbxi_find_vec3(&line->props, ufbxi_Color, 1.0f, 1.0f, 1.0f);
+}
+
+ufbxi_noinline static void ufbxi_update_pose(ufbx_pose *pose)
+{
+ ufbxi_for_list(ufbx_bone_pose, bone, pose->bone_poses) {
+ ufbx_node *node = bone->bone_node;
+
+ const ufbx_matrix *parent_to_world = &ufbx_identity_matrix;
+ ufbx_bone_pose *bone_pose = ufbx_get_bone_pose(pose, node->parent);
+ if (bone_pose) {
+ parent_to_world = &bone_pose->bone_to_world;
+ } else if (node->parent) {
+ parent_to_world = &node->parent->node_to_world;
+ }
+
+ ufbx_matrix world_to_parent = ufbx_matrix_invert(parent_to_world);
+ bone->bone_to_parent = ufbx_matrix_mul(&world_to_parent, &bone->bone_to_world);
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_skin_cluster(ufbx_skin_cluster *cluster)
+{
+ if (cluster->bone_node) {
+ cluster->geometry_to_world = ufbx_matrix_mul(&cluster->bone_node->node_to_world, &cluster->geometry_to_bone);
+ } else {
+ cluster->geometry_to_world = ufbx_matrix_mul(&cluster->bind_to_world, &cluster->geometry_to_bone);
+ }
+ cluster->geometry_to_world_transform = ufbx_matrix_to_transform(&cluster->geometry_to_world);
+}
+
+ufbxi_noinline static void ufbxi_update_blend_channel(ufbx_blend_channel *channel)
+{
+ ufbx_real weight = ufbxi_find_real(&channel->props, ufbxi_DeformPercent, 0.0f) * (ufbx_real)0.01;
+ channel->weight = weight;
+
+ ptrdiff_t num_keys = (ptrdiff_t)channel->keyframes.count;
+ if (num_keys > 0) {
+ ufbx_blend_keyframe *keys = channel->keyframes.data;
+
+ // Reset the effective weights to zero and find the split around zero
+ ptrdiff_t last_negative = -1;
+ for (ptrdiff_t i = 0; i < num_keys; i++) {
+ keys[i].effective_weight = (ufbx_real)0.0;
+ if (keys[i].target_weight < 0.0) last_negative = i;
+ }
+
+ // Find either the next or last keyframe away from zero
+ ufbx_blend_keyframe zero_key = { NULL };
+ ufbx_blend_keyframe *prev = &zero_key, *next = &zero_key;
+ if (weight > 0.0) {
+ if (last_negative >= 0) prev = &keys[last_negative];
+ for (ptrdiff_t i = last_negative + 1; i < num_keys; i++) {
+ prev = next;
+ next = &keys[i];
+ if (next->target_weight > weight) break;
+ }
+ } else {
+ if (last_negative + 1 < num_keys) prev = &keys[last_negative + 1];
+ for (ptrdiff_t i = last_negative; i >= 0; i--) {
+ prev = next;
+ next = &keys[i];
+ if (next->target_weight < weight) break;
+ }
+ }
+
+ // Linearly interpolate between the endpoints with the weight
+ ufbx_real delta = next->target_weight - prev->target_weight;
+ if (delta != 0.0) {
+ ufbx_real t = (weight - prev->target_weight) / delta;
+ prev->effective_weight = 1.0f - t;
+ next->effective_weight = t;
+ }
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_material(ufbx_scene *scene, ufbx_material *material)
+{
+ if (material->props.num_animated > 0) {
+ ufbxi_fetch_maps(scene, material);
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_texture(ufbx_texture *texture)
+{
+ texture->uv_transform = ufbxi_get_texture_transform(&texture->props);
+ if (!ufbxi_is_transform_identity(&texture->uv_transform)) {
+ texture->has_uv_transform = true;
+ texture->texture_to_uv = ufbx_transform_to_matrix(&texture->uv_transform);
+ texture->uv_to_texture = ufbx_matrix_invert(&texture->texture_to_uv);
+ } else {
+ texture->has_uv_transform = false;
+ texture->texture_to_uv = ufbx_identity_matrix;
+ texture->uv_to_texture = ufbx_identity_matrix;
+ }
+ texture->wrap_u = (ufbx_wrap_mode)ufbxi_find_enum(&texture->props, ufbxi_WrapModeU, 0, UFBX_WRAP_CLAMP);
+ texture->wrap_v = (ufbx_wrap_mode)ufbxi_find_enum(&texture->props, ufbxi_WrapModeV, 0, UFBX_WRAP_CLAMP);
+
+ if (texture->shader) {
+ ufbxi_update_shader_texture(texture, texture->shader);
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_anim_stack(ufbx_scene *scene, ufbx_anim_stack *stack)
+{
+ ufbx_prop *begin, *end;
+ begin = ufbxi_find_prop(&stack->props, ufbxi_LocalStart);
+ end = ufbxi_find_prop(&stack->props, ufbxi_LocalStop);
+ if (!begin || !end) {
+ begin = ufbxi_find_prop(&stack->props, ufbxi_ReferenceStart);
+ end = ufbxi_find_prop(&stack->props, ufbxi_ReferenceStop);
+ }
+
+ if (begin && end) {
+ stack->time_begin = (double)begin->value_int / (double)scene->metadata.ktime_second;
+ stack->time_end = (double)end->value_int / (double)scene->metadata.ktime_second;
+ }
+
+ stack->anim->time_begin = stack->time_begin;
+ stack->anim->time_end = stack->time_end;
+}
+
+ufbxi_noinline static void ufbxi_update_display_layer(ufbx_display_layer *layer)
+{
+ layer->visible = ufbxi_find_int(&layer->props, ufbxi_Show, 1) != 0;
+ layer->frozen = ufbxi_find_int(&layer->props, ufbxi_Freeze, 1) != 0;
+ layer->ui_color = ufbxi_find_vec3(&layer->props, ufbxi_Color, 0.8f, 0.8f, 0.8f);
+}
+
+ufbxi_noinline static void ufbxi_find_bool3(bool *dst, ufbx_props *props, const char *name, bool default_value)
+{
+ size_t name_len = strlen(name);
+ char local[64];
+ ufbx_assert(name_len < sizeof(local) - 2);
+ memcpy(local, name, name_len);
+
+ size_t local_len = name_len + 1;
+ local[local_len] = '\0';
+
+ int64_t def = default_value ? 1 : 0;
+ local[name_len] = 'X';
+ dst[0] = ufbx_find_int_len(props, local, local_len, def) != 0;
+ local[name_len] = 'Y';
+ dst[1] = ufbx_find_int_len(props, local, local_len, def) != 0;
+ local[name_len] = 'Z';
+ dst[2] = ufbx_find_int_len(props, local, local_len, def) != 0;
+}
+
+ufbxi_noinline static void ufbxi_update_constraint(ufbx_constraint *constraint)
+{
+ ufbx_props *props = &constraint->props;
+ ufbx_constraint_type constraint_type = constraint->type;
+
+ constraint->transform_offset = ufbxi_get_constraint_transform(props);
+
+ constraint->weight = ufbxi_find_real(props, ufbxi_Weight, (ufbx_real)100.0) / (ufbx_real)100.0;
+
+ ufbxi_for_list(ufbx_constraint_target, target, constraint->targets) {
+ ufbx_node *node = target->node;
+
+ ufbx_real weight_scale = (ufbx_real)100.0;
+ if (constraint_type == UFBX_CONSTRAINT_SINGLE_CHAIN_IK) {
+ // IK weights seem to be not scaled 100x?
+ weight_scale = (ufbx_real)1.0;
+ }
+
+ ufbx_prop *prop; // ufbxi_uninit
+ ufbx_string parts[2]; // ufbxi_uninit
+ parts[0] = node->name;
+ parts[1] = ufbxi_str_c(".Weight");
+ prop = ufbx_find_prop_concat(props, parts, 2);
+ target->weight = (prop ? prop->value_real : weight_scale) / weight_scale;
+
+ if (constraint_type == UFBX_CONSTRAINT_PARENT) {
+ parts[1] = ufbxi_str_c(".Offset T");
+ prop = ufbx_find_prop_concat(props, parts, 2);
+ ufbx_vec3 t = prop ? prop->value_vec3 : ufbx_zero_vec3;
+ parts[1] = ufbxi_str_c(".Offset R");
+ prop = ufbx_find_prop_concat(props, parts, 2);
+ ufbx_vec3 r = prop ? prop->value_vec3 : ufbx_zero_vec3;
+ parts[1] = ufbxi_str_c(".Offset S");
+ prop = ufbx_find_prop_concat(props, parts, 2);
+ ufbx_vec3 s = prop ? prop->value_vec3 : ufbxi_one_vec3;
+
+ target->transform.translation = t;
+ target->transform.rotation = ufbx_euler_to_quat(r, UFBX_ROTATION_ORDER_XYZ);
+ target->transform.scale = s;
+ }
+ }
+
+ constraint->active = ufbx_find_int(props, "Active", 1) != 0;
+ if (constraint_type == UFBX_CONSTRAINT_AIM) {
+ ufbxi_find_bool3(constraint->constrain_rotation, props, "Affect", 1);
+
+ const ufbx_vec3 default_aim = { 1.0f, 0.0f, 0.0f };
+ const ufbx_vec3 default_up = { 0.0f, 1.0f, 0.0f };
+
+ int64_t up_type = ufbx_find_int(props, "WorldUpType", 0);
+ if (up_type >= 0 && up_type < UFBX_CONSTRAINT_AIM_UP_NONE) {
+ constraint->aim_up_type = (ufbx_constraint_aim_up_type)up_type;
+ }
+ constraint->aim_vector = ufbx_find_vec3(props, "AimVector", default_aim);
+ constraint->aim_up_vector = ufbx_find_vec3(props, "UpVector", default_up);
+
+ } else if (constraint_type == UFBX_CONSTRAINT_PARENT) {
+ ufbxi_find_bool3(constraint->constrain_translation, props, "AffectTranslation", 1);
+ ufbxi_find_bool3(constraint->constrain_rotation, props, "AffectRotation", 1);
+ ufbxi_find_bool3(constraint->constrain_scale, props, "AffectScale", 0);
+ } else if (constraint_type == UFBX_CONSTRAINT_POSITION) {
+ ufbxi_find_bool3(constraint->constrain_translation, props, "Affect", 1);
+ } else if (constraint_type == UFBX_CONSTRAINT_ROTATION) {
+ ufbxi_find_bool3(constraint->constrain_rotation, props, "Affect", 1);
+ } else if (constraint_type == UFBX_CONSTRAINT_SCALE) {
+ ufbxi_find_bool3(constraint->constrain_scale, props, "Affect", 1);
+ } else if (constraint_type == UFBX_CONSTRAINT_SINGLE_CHAIN_IK) {
+ constraint->constrain_rotation[0] = true;
+ constraint->constrain_rotation[1] = true;
+ constraint->constrain_rotation[2] = true;
+ constraint->ik_pole_vector = ufbx_find_vec3(props, "PoleVectorType", ufbx_zero_vec3);
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_anim(ufbx_scene *scene)
+{
+ if (scene->anim_stacks.count > 0) {
+ scene->anim = scene->anim_stacks.data[0]->anim;
+ }
+}
+
+static ufbxi_forceinline void ufbxi_mirror_matrix_dst(ufbx_matrix *m, ufbx_mirror_axis axis)
+{
+ if (axis == 0) return;
+ int32_t ax = (int32_t)axis - 1;
+ m->cols[0].v[ax] = -m->cols[0].v[ax];
+ m->cols[1].v[ax] = -m->cols[1].v[ax];
+ m->cols[2].v[ax] = -m->cols[2].v[ax];
+ m->cols[3].v[ax] = -m->cols[3].v[ax];
+}
+
+static ufbxi_forceinline void ufbxi_mirror_matrix_src(ufbx_matrix *m, ufbx_mirror_axis axis)
+{
+ if (axis == 0) return;
+ int32_t ax = (int32_t)axis - 1;
+ m->cols[ax].x = -m->cols[ax].x;
+ m->cols[ax].y = -m->cols[ax].y;
+ m->cols[ax].z = -m->cols[ax].z;
+}
+
+static ufbxi_noinline void ufbxi_mirror_matrix(ufbx_matrix *m, ufbx_mirror_axis axis)
+{
+ if (axis == 0) return;
+ ufbxi_mirror_matrix_src(m, axis);
+ ufbxi_mirror_matrix_dst(m, axis);
+}
+
+ufbxi_noinline static void ufbxi_update_initial_clusters(ufbx_scene *scene)
+{
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ cluster->geometry_to_bone = cluster->mesh_node_to_bone;
+ }
+
+ ufbx_mirror_axis mirror_axis = scene->metadata.mirror_axis;
+ ufbx_real geometry_scale = scene->metadata.geometry_scale;
+
+ // Space conversion for bind matrices
+ {
+ ufbx_matrix world_to_units;
+ ufbx_real translation_scale = 1.0f;
+
+ if (scene->metadata.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT && scene->metadata.mirror_axis == UFBX_MIRROR_AXIS_NONE) {
+ world_to_units = scene->root_node->node_to_parent;
+ } else {
+ ufbx_transform root_transform;
+ root_transform.translation = ufbx_zero_vec3;
+ root_transform.rotation = scene->metadata.root_rotation;
+ root_transform.scale.x = scene->metadata.root_scale;
+ root_transform.scale.y = scene->metadata.root_scale;
+ root_transform.scale.z = scene->metadata.root_scale;
+ world_to_units = ufbx_transform_to_matrix(&root_transform);
+ translation_scale = scene->metadata.geometry_scale;
+ }
+
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ cluster->bind_to_world = ufbx_matrix_mul(&world_to_units, &cluster->bind_to_world);
+ cluster->bind_to_world.cols[3].x *= translation_scale;
+ cluster->bind_to_world.cols[3].y *= translation_scale;
+ cluster->bind_to_world.cols[3].z *= translation_scale;
+ ufbxi_mirror_matrix(&cluster->bind_to_world, mirror_axis);
+ }
+
+ ufbxi_for_ptr_list(ufbx_pose, p_pose, scene->poses) {
+ ufbxi_for_list(ufbx_bone_pose, pose, (*p_pose)->bone_poses) {
+ pose->bone_to_world = ufbx_matrix_mul(&world_to_units, &pose->bone_to_world);
+ pose->bone_to_world.cols[3].x *= translation_scale;
+ pose->bone_to_world.cols[3].y *= translation_scale;
+ pose->bone_to_world.cols[3].z *= translation_scale;
+ ufbxi_mirror_matrix(&pose->bone_to_world, mirror_axis);
+ }
+ }
+ }
+
+ // Patch initial `mesh_node_to_bone`
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+
+ ufbx_skin_deformer *skin = (ufbx_skin_deformer*)ufbxi_fetch_src_element(&cluster->element, false, NULL, UFBX_ELEMENT_SKIN_DEFORMER);
+ if (!skin) continue;
+
+ ufbx_node *node = (ufbx_node*)ufbxi_fetch_src_element(&skin->element, false, NULL, UFBX_ELEMENT_NODE);
+ if (!node) {
+ ufbx_mesh *mesh = (ufbx_mesh*)ufbxi_fetch_src_element(&skin->element, false, NULL, UFBX_ELEMENT_MESH);
+ if (mesh && mesh->instances.count > 0) {
+ node = mesh->instances.data[0];
+ }
+ }
+ if (!node) continue;
+
+ // Normalize to the non-helper node
+ if (node->is_geometry_transform_helper) {
+ node = node->parent;
+ }
+
+ if (ufbxi_matrix_all_zero(&cluster->mesh_node_to_bone)) {
+ // If `mesh_node_to_bone` is not explicitly specified compute it from bind pose.
+ ufbx_matrix world_to_bind = ufbx_matrix_invert(&cluster->bind_to_world);
+ cluster->mesh_node_to_bone = ufbx_matrix_mul(&world_to_bind, &node->node_to_world);
+ } else {
+ // If `mesh_node_to_bone` is explicit, we may need to modify it for space conversion.
+ ufbxi_mirror_matrix(&cluster->mesh_node_to_bone, mirror_axis);
+ if (geometry_scale != 1.0f) {
+ cluster->mesh_node_to_bone.cols[3].x *= geometry_scale;
+ cluster->mesh_node_to_bone.cols[3].y *= geometry_scale;
+ cluster->mesh_node_to_bone.cols[3].z *= geometry_scale;
+ }
+ }
+
+ // HACK: Account for geometry transforms by looking at the transform of the
+ // helper node if one is present. I don't think this is exactly how the skinning
+ // matrices are formed.
+ // TODO: Add a test with moving the skinned mesh root around.
+ if (node->geometry_transform_helper) {
+ ufbx_node *geo_node = node->geometry_transform_helper;
+ cluster->geometry_to_bone = ufbx_matrix_mul(&cluster->mesh_node_to_bone, &geo_node->node_to_parent);
+ } else if (node->has_geometry_transform) {
+ cluster->geometry_to_bone = ufbx_matrix_mul(&cluster->mesh_node_to_bone, &node->geometry_to_node);
+ } else {
+ cluster->geometry_to_bone = cluster->mesh_node_to_bone;
+ }
+ }
+}
+
+ufbxi_noinline static ufbx_coordinate_axis ufbxi_find_axis(const ufbx_props *props, const char *axis_name, const char *sign_name)
+{
+ int64_t axis = ufbxi_find_int(props, axis_name, 3);
+ int64_t sign = ufbxi_find_int(props, sign_name, 2);
+
+ switch (axis) {
+ case 0: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_X : UFBX_COORDINATE_AXIS_NEGATIVE_X;
+ case 1: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_Y : UFBX_COORDINATE_AXIS_NEGATIVE_Y;
+ case 2: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_Z : UFBX_COORDINATE_AXIS_NEGATIVE_Z;
+ default: return UFBX_COORDINATE_AXIS_UNKNOWN;
+ }
+}
+
+static const ufbx_real ufbxi_time_mode_fps[] = {
+ 30.0f, // UFBX_TIME_MODE_DEFAULT
+ 120.0f, // UFBX_TIME_MODE_120_FPS
+ 100.0f, // UFBX_TIME_MODE_100_FPS
+ 60.0f, // UFBX_TIME_MODE_60_FPS
+ 50.0f, // UFBX_TIME_MODE_50_FPS
+ 48.0f, // UFBX_TIME_MODE_48_FPS
+ 30.0f, // UFBX_TIME_MODE_30_FPS
+ 30.0f, // UFBX_TIME_MODE_30_FPS_DROP
+ 29.97f, // UFBX_TIME_MODE_NTSC_DROP_FRAME
+ 29.97f, // UFBX_TIME_MODE_NTSC_FULL_FRAME
+ 25.0f, // UFBX_TIME_MODE_PAL
+ 24.0f, // UFBX_TIME_MODE_24_FPS
+ 1000.0f, // UFBX_TIME_MODE_1000_FPS
+ 23.976f, // UFBX_TIME_MODE_FILM_FULL_FRAME
+ 24.0f, // UFBX_TIME_MODE_CUSTOM
+ 96.0f, // UFBX_TIME_MODE_96_FPS
+ 72.0f, // UFBX_TIME_MODE_72_FPS
+ 59.94f, // UFBX_TIME_MODE_59_94_FPS
+};
+
+// Returns whether a non-identity matrix was needed
+static ufbxi_noinline bool ufbxi_axis_matrix(ufbx_matrix *mat, ufbx_coordinate_axes src, ufbx_coordinate_axes dst)
+{
+ uint32_t src_x = (uint32_t)src.right;
+ uint32_t dst_x = (uint32_t)dst.right;
+ uint32_t src_y = (uint32_t)src.up;
+ uint32_t dst_y = (uint32_t)dst.up;
+ uint32_t src_z = (uint32_t)src.front;
+ uint32_t dst_z = (uint32_t)dst.front;
+
+ if (src_x == dst_x && src_y == dst_y && src_z == dst_z) return false;
+
+ // Remap axes (axis enum divided by 2) potentially flipping if the signs (enum parity) doesn't match
+ memset(mat, 0, sizeof(ufbx_matrix));
+ mat->cols[src_x >> 1].v[dst_x >> 1] = ((src_x ^ dst_x) & 1) == 0 ? 1.0f : -1.0f;
+ mat->cols[src_y >> 1].v[dst_y >> 1] = ((src_y ^ dst_y) & 1) == 0 ? 1.0f : -1.0f;
+ mat->cols[src_z >> 1].v[dst_z >> 1] = ((src_z ^ dst_z) & 1) == 0 ? 1.0f : -1.0f;
+
+ return true;
+}
+
+ufbxi_noinline static void ufbxi_update_adjust_transforms(ufbxi_context *uc, ufbx_scene *scene)
+{
+ ufbx_transform root_transform = ufbx_identity_transform;
+ if (!ufbxi_matrix_all_zero(&uc->axis_matrix)) {
+ root_transform = ufbx_matrix_to_transform(&uc->axis_matrix);
+ }
+ root_transform.scale.x *= uc->unit_scale;
+ root_transform.scale.y *= uc->unit_scale;
+ root_transform.scale.z *= uc->unit_scale;
+
+ ufbx_space_conversion conversion = uc->opts.space_conversion;
+
+ ufbx_quat light_post_rotation = ufbx_identity_quat;
+ ufbx_quat camera_post_rotation = ufbx_identity_quat;
+ ufbx_vec3 light_direction = { 0.0f, -1.0f, 0.0f };
+ bool has_light_transform = false;
+ bool has_camera_transform = false;
+
+ if (ufbx_coordinate_axes_valid(uc->opts.target_light_axes)) {
+ ufbx_matrix mat; // ufbxi_uninit
+ ufbx_coordinate_axes light_axes = {
+ UFBX_COORDINATE_AXIS_POSITIVE_X,
+ UFBX_COORDINATE_AXIS_NEGATIVE_Z,
+ UFBX_COORDINATE_AXIS_POSITIVE_Y,
+ };
+ if (ufbxi_axis_matrix(&mat, uc->opts.target_light_axes, light_axes)) {
+ light_post_rotation = ufbx_matrix_to_transform(&mat).rotation;
+
+ ufbx_matrix inv = ufbx_matrix_invert(&mat);
+ light_direction = ufbx_transform_direction(&inv, light_direction);
+ has_light_transform = true;
+ }
+ }
+
+ if (ufbx_coordinate_axes_valid(uc->opts.target_camera_axes)) {
+ ufbx_matrix mat; // ufbxi_uninit
+ ufbx_coordinate_axes camera_axes = {
+ UFBX_COORDINATE_AXIS_POSITIVE_Z,
+ UFBX_COORDINATE_AXIS_POSITIVE_Y,
+ UFBX_COORDINATE_AXIS_NEGATIVE_X,
+ };
+ if (ufbxi_axis_matrix(&mat, uc->opts.target_camera_axes, camera_axes)) {
+ camera_post_rotation = ufbx_matrix_to_transform(&mat).rotation;
+ has_camera_transform = true;
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_light, p_light, scene->lights) {
+ ufbx_light *light = *p_light;
+ light->local_direction.x = 0.0f;
+ light->local_direction.y = -1.0f;
+ light->local_direction.z = 0.0f;
+ }
+
+ scene->metadata.space_conversion = conversion;
+ scene->metadata.geometry_transform_handling = uc->opts.geometry_transform_handling;
+ scene->metadata.inherit_mode_handling = uc->opts.inherit_mode_handling;
+ scene->metadata.pivot_handling = uc->opts.pivot_handling;
+ scene->metadata.handedness_conversion_axis = uc->opts.handedness_conversion_axis;
+
+ ufbx_real root_scale = ufbxi_min3(root_transform.scale);
+ if (conversion == UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY) {
+ scene->metadata.geometry_scale = root_scale;
+ scene->metadata.root_scale = 1.0f;
+ } else {
+ scene->metadata.geometry_scale = 1.0f;
+ scene->metadata.root_scale = root_scale;
+ }
+ scene->metadata.root_rotation = root_transform.rotation;
+
+ ufbxi_for_ptr_list(ufbx_node, p_node, scene->nodes) {
+ ufbx_node *node = *p_node;
+
+ node->adjust_post_rotation = ufbx_identity_quat;
+ node->adjust_pre_rotation = ufbx_identity_quat;
+ node->adjust_pre_scale = 1.0f;
+ node->adjust_post_scale = 1.0f;
+ node->adjust_translation_scale = 1.0f;
+
+ if (conversion == UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS) {
+ if (node->node_depth <= 1 && !node->is_root) {
+ node->adjust_pre_rotation = root_transform.rotation;
+ node->adjust_pre_scale = root_scale;
+ node->has_adjust_transform = true;
+ node->has_root_adjust_transform = true;
+ }
+ } else if (conversion == UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY) {
+ if (!node->is_root) {
+ if (node->node_depth <= 1) {
+ node->adjust_pre_rotation = root_transform.rotation;
+ }
+ node->adjust_translation_scale = root_scale;
+ node->has_adjust_transform = true;
+ }
+ }
+
+ if (node->parent) {
+ // We are not inheriting local scale, so propagate root scale manually and
+ // apply scale compensation if necessary.
+ ufbx_node *parent = node->parent;
+ if (parent->has_root_adjust_transform && node->inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
+ node->adjust_post_scale *= root_scale;
+ node->has_adjust_transform = true;
+ node->has_root_adjust_transform = true;
+ }
+ if (parent->is_scale_compensate_parent && node->original_inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
+ ufbx_vec3 scale = ufbxi_find_vec3(&parent->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
+ ufbx_real size = scale.x;
+ if (ufbx_fabs(scale.y - 1.0f) < ufbx_fabs(size - 1.0f)) size = scale.y;
+ if (ufbx_fabs(scale.z - 1.0f) < ufbx_fabs(size - 1.0f)) size = scale.z;
+ node->adjust_post_scale *= 1.0f / size;
+ node->has_adjust_transform = true;
+ }
+ }
+
+ if (node->all_attribs.count == 1) {
+ if (has_light_transform && node->light) {
+ node->adjust_post_rotation = light_post_rotation;
+ node->light->local_direction = light_direction;
+ node->has_adjust_transform = true;
+ }
+ if (has_camera_transform && node->camera) {
+ node->adjust_post_rotation = camera_post_rotation;
+ node->camera->projection_axes = uc->opts.target_camera_axes;
+ node->has_adjust_transform = true;
+ }
+ }
+ }
+}
+
+ufbxi_noinline static void ufbxi_update_scene(ufbx_scene *scene, bool initial, const ufbx_transform_override *transform_overrides, size_t num_transform_overrides)
+{
+ ufbxi_for_ptr_list(ufbx_node, p_node, scene->nodes) {
+ ufbxi_update_node(*p_node, transform_overrides, num_transform_overrides);
+ }
+
+ ufbxi_for_ptr_list(ufbx_light, p_light, scene->lights) {
+ ufbxi_update_light(*p_light);
+ }
+
+ ufbxi_for_ptr_list(ufbx_camera, p_camera, scene->cameras) {
+ ufbxi_update_camera(scene, *p_camera);
+ }
+
+ ufbxi_for_ptr_list(ufbx_bone, p_bone, scene->bones) {
+ ufbxi_update_bone(scene, *p_bone);
+ }
+
+ ufbxi_for_ptr_list(ufbx_line_curve, p_line, scene->line_curves) {
+ ufbxi_update_line_curve(*p_line);
+ }
+
+ if (initial) {
+ ufbxi_update_initial_clusters(scene);
+
+ ufbxi_for_ptr_list(ufbx_pose, p_pose, scene->poses) {
+ ufbxi_update_pose(*p_pose);
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
+ ufbxi_update_skin_cluster(*p_cluster);
+ }
+
+ ufbxi_for_ptr_list(ufbx_blend_channel, p_channel, scene->blend_channels) {
+ ufbxi_update_blend_channel(*p_channel);
+ }
+
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
+ ufbxi_update_texture(*p_texture);
+ }
+
+ ufbxi_propagate_main_textures(scene);
+
+ ufbxi_for_ptr_list(ufbx_material, p_material, scene->materials) {
+ ufbxi_update_material(scene, *p_material);
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, scene->anim_stacks) {
+ ufbxi_update_anim_stack(scene, *p_stack);
+ }
+
+ ufbxi_for_ptr_list(ufbx_display_layer, p_layer, scene->display_layers) {
+ ufbxi_update_display_layer(*p_layer);
+ }
+
+ ufbxi_for_ptr_list(ufbx_constraint, p_constraint, scene->constraints) {
+ ufbxi_update_constraint(*p_constraint);
+ }
+
+ ufbxi_update_anim(scene);
+}
+
+static ufbxi_noinline void ufbxi_update_scene_metadata(ufbx_metadata *metadata)
+{
+ ufbx_props *props = &metadata->scene_props;
+ metadata->original_application.vendor = ufbx_find_string(props, "Original|ApplicationVendor", ufbx_empty_string);
+ metadata->original_application.name = ufbx_find_string(props, "Original|ApplicationName", ufbx_empty_string);
+ metadata->original_application.version = ufbx_find_string(props, "Original|ApplicationVersion", ufbx_empty_string);
+ metadata->latest_application.vendor = ufbx_find_string(props, "LastSaved|ApplicationVendor", ufbx_empty_string);
+ metadata->latest_application.name = ufbx_find_string(props, "LastSaved|ApplicationName", ufbx_empty_string);
+ metadata->latest_application.version = ufbx_find_string(props, "LastSaved|ApplicationVersion", ufbx_empty_string);
+}
+
+static const ufbx_real ufbxi_pow10_targets[] = {
+ 0.0f,
+ (ufbx_real)1e-8, (ufbx_real)1e-7, (ufbx_real)1e-6, (ufbx_real)1e-5,
+ (ufbx_real)1e-4, (ufbx_real)1e-3, (ufbx_real)1e-2, (ufbx_real)1e-1,
+ (ufbx_real)1e+0, (ufbx_real)1e+1, (ufbx_real)1e+2, (ufbx_real)1e+3,
+ (ufbx_real)1e+4, (ufbx_real)1e+5, (ufbx_real)1e+6, (ufbx_real)1e+7,
+ (ufbx_real)1e+8, (ufbx_real)1e+9,
+};
+
+static ufbxi_noinline ufbx_real ufbxi_round_if_near(const ufbx_real *targets, size_t num_targets, ufbx_real value)
+{
+ for (size_t i = 0; i < num_targets; i++) {
+ double target = targets[i];
+ double error = target * 9.5367431640625e-7;
+ if (error < 0.0) error = -error;
+ if (error < 7.52316384526264005e-37) error = 7.52316384526264005e-37;
+ if (value >= target - error && value <= target + error) {
+ return (ufbx_real)target;
+ }
+ }
+ return value;
+}
+
+static ufbxi_noinline void ufbxi_update_scene_settings(ufbx_scene_settings *settings)
+{
+ ufbx_real unit_scale_factor = ufbxi_find_real(&settings->props, ufbxi_UnitScaleFactor, 1.0f);
+ ufbx_real original_unit_scale_factor = ufbxi_find_real(&settings->props, ufbxi_OriginalUnitScaleFactor, unit_scale_factor);
+
+ settings->axes.up = ufbxi_find_axis(&settings->props, ufbxi_UpAxis, ufbxi_UpAxisSign);
+ settings->axes.front = ufbxi_find_axis(&settings->props, ufbxi_FrontAxis, ufbxi_FrontAxisSign);
+ settings->axes.right = ufbxi_find_axis(&settings->props, ufbxi_CoordAxis, ufbxi_CoordAxisSign);
+ settings->unit_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), unit_scale_factor * (ufbx_real)0.01);
+ settings->original_unit_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), original_unit_scale_factor * (ufbx_real)0.01);
+ settings->frames_per_second = ufbxi_find_real(&settings->props, ufbxi_CustomFrameRate, 24.0f);
+ settings->ambient_color = ufbxi_find_vec3(&settings->props, ufbxi_AmbientColor, 0.0f, 0.0f, 0.0f);
+ settings->original_axis_up = ufbxi_find_axis(&settings->props, ufbxi_OriginalUpAxis, ufbxi_OriginalUpAxisSign);
+
+ ufbx_prop *default_camera = ufbxi_find_prop(&settings->props, ufbxi_DefaultCamera);
+ if (default_camera) {
+ settings->default_camera = default_camera->value_str;
+ } else {
+ settings->default_camera = ufbx_empty_string;
+ }
+
+ settings->time_mode = (ufbx_time_mode)ufbxi_find_enum(&settings->props, ufbxi_TimeMode, UFBX_TIME_MODE_24_FPS, UFBX_TIME_MODE_59_94_FPS);
+ settings->time_protocol = (ufbx_time_protocol)ufbxi_find_enum(&settings->props, ufbxi_TimeProtocol, UFBX_TIME_PROTOCOL_DEFAULT, UFBX_TIME_PROTOCOL_DEFAULT);
+ settings->snap_mode = (ufbx_snap_mode)ufbxi_find_enum(&settings->props, ufbxi_SnapOnFrameMode, UFBX_SNAP_MODE_NONE, UFBX_SNAP_MODE_SNAP_AND_PLAY);
+
+ if (settings->time_mode != UFBX_TIME_MODE_CUSTOM) {
+ settings->frames_per_second = ufbxi_time_mode_fps[settings->time_mode];
+ }
+}
+
+static ufbxi_noinline void ufbxi_update_scene_settings_obj(ufbxi_context *uc)
+{
+ ufbx_scene_settings *settings = &uc->scene.settings;
+ settings->original_unit_meters = settings->unit_meters = uc->opts.obj_unit_meters;
+ if (ufbx_coordinate_axes_valid(uc->opts.obj_axes)) {
+ settings->axes = uc->opts.obj_axes;
+ } else {
+ settings->axes.right = UFBX_COORDINATE_AXIS_UNKNOWN;
+ settings->axes.up = UFBX_COORDINATE_AXIS_UNKNOWN;
+ settings->axes.front = UFBX_COORDINATE_AXIS_UNKNOWN;
+ }
+}
+
+// -- Geometry caches
+
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_geometry_cache cache;
+ uint32_t magic;
+ bool owned_by_scene;
+
+ ufbxi_buf string_buf;
+} ufbxi_geometry_cache_imp;
+
+ufbx_static_assert(geometry_cache_imp_offset, offsetof(ufbxi_geometry_cache_imp, cache) == sizeof(ufbxi_refcount));
+
+typedef struct {
+ ufbx_string name;
+ ufbx_string interpretation;
+ uint32_t sample_rate;
+ uint32_t start_time;
+ uint32_t end_time;
+ uint32_t current_time;
+ uint32_t consecutive_fails;
+ bool try_load;
+} ufbxi_cache_tmp_channel;
+
+typedef enum {
+ UFBXI_CACHE_XML_TYPE_NONE,
+ UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME,
+ UFBXI_CACHE_XML_TYPE_SINGLE_FILE,
+} ufbxi_cache_xml_type;
+
+typedef enum {
+ UFBXI_CACHE_XML_FORMAT_NONE,
+ UFBXI_CACHE_XML_FORMAT_MCC,
+ UFBXI_CACHE_XML_FORMAT_MCX,
+} ufbxi_cache_xml_format;
+
+typedef struct {
+ ufbx_error error;
+ ufbx_string filename;
+ bool owned_by_scene;
+ bool ignore_if_not_found;
+
+ ufbx_geometry_cache_opts opts;
+
+ ufbxi_allocator *ator_tmp;
+ ufbxi_allocator ator_result;
+
+ ufbxi_buf result;
+ ufbxi_buf tmp;
+ ufbxi_buf tmp_stack;
+
+ ufbxi_cache_tmp_channel *channels;
+ size_t num_channels;
+
+ // Temporary array
+ char *tmp_arr;
+ size_t tmp_arr_size;
+
+ ufbxi_string_pool string_pool;
+
+ ufbx_open_file_cb open_file_cb;
+
+ double frames_per_second;
+
+ ufbx_string stream_filename;
+ ufbx_stream stream;
+
+ bool mc_for8;
+
+ bool xml_loaded;
+ ufbx_string xml_filename;
+ uint32_t xml_ticks_per_frame;
+ ufbxi_cache_xml_type xml_type;
+ ufbxi_cache_xml_format xml_format;
+
+ ufbx_string channel_name;
+
+ char *name_buf;
+ size_t name_cap;
+
+ uint64_t file_offset;
+ const char *pos, *pos_end;
+
+ ufbx_geometry_cache cache;
+ ufbxi_geometry_cache_imp *imp;
+
+ char buffer[128];
+} ufbxi_cache_context;
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_read(ufbxi_cache_context *cc, void *dst, size_t size, bool allow_eof)
+{
+ size_t buffered = ufbxi_min_sz(ufbxi_to_size(cc->pos_end - cc->pos), size);
+ memcpy(dst, cc->pos, buffered);
+ cc->pos += buffered;
+ size -= buffered;
+ cc->file_offset += buffered;
+ if (size == 0) return 1;
+ dst = (char*)dst + buffered;
+
+ if (size >= sizeof(cc->buffer)) {
+ size_t num_read = cc->stream.read_fn(cc->stream.user, dst, size);
+ ufbxi_check_err_msg(&cc->error, num_read <= size, "IO error");
+ if (!allow_eof) {
+ ufbxi_check_err_msg(&cc->error, num_read == size, "Truncated file");
+ }
+ cc->file_offset += num_read;
+ size -= num_read;
+ dst = (char*)dst + num_read;
+ } else {
+ size_t num_read = cc->stream.read_fn(cc->stream.user, cc->buffer, sizeof(cc->buffer));
+ ufbxi_check_err_msg(&cc->error, num_read <= sizeof(cc->buffer), "IO error");
+ if (!allow_eof) {
+ ufbxi_check_err_msg(&cc->error, num_read >= size, "Truncated file");
+ }
+ cc->pos = cc->buffer;
+ cc->pos_end = cc->buffer + sizeof(cc->buffer);
+
+ memcpy(dst, cc->pos, size);
+ cc->pos += size;
+ cc->file_offset += size;
+
+ size_t num_written = ufbxi_min_sz(size, num_read);
+ size -= num_written;
+ dst = (char*)dst + num_written;
+ }
+
+ if (size > 0) {
+ memset(dst, 0, size);
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_skip(ufbxi_cache_context *cc, uint64_t size)
+{
+ cc->file_offset += size;
+
+ uint64_t buffered = ufbxi_min64((uint64_t)(cc->pos_end - cc->pos), size);
+ cc->pos += buffered;
+ size -= buffered;
+
+ if (cc->stream.skip_fn) {
+ while (size >= UFBXI_MAX_SKIP_SIZE) {
+ size -= UFBXI_MAX_SKIP_SIZE;
+ ufbxi_check_err_msg(&cc->error, cc->stream.skip_fn(cc->stream.user, UFBXI_MAX_SKIP_SIZE - 1), "Truncated file");
+
+ // Check that we can read at least one byte in case the file is broken
+ // and causes us to seek indefinitely forwards as `fseek()` does not
+ // report if we hit EOF...
+ char single_byte[1]; // ufbxi_uninit
+ size_t num_read = cc->stream.read_fn(cc->stream.user, single_byte, 1);
+ ufbxi_check_err_msg(&cc->error, num_read <= 1, "IO error");
+ ufbxi_check_err_msg(&cc->error, num_read == 1, "Truncated file");
+ }
+
+ if (size > 0) {
+ ufbxi_check_err_msg(&cc->error, cc->stream.skip_fn(cc->stream.user, (size_t)size), "Truncated file");
+ }
+
+ } else {
+ char skip_buf[2048]; // ufbxi_uninit
+ while (size > 0) {
+ size_t to_skip = (size_t)ufbxi_min64(size, sizeof(skip_buf));
+ size -= to_skip;
+ ufbxi_check_err_msg(&cc->error, cc->stream.read_fn(cc->stream.user, skip_buf, to_skip), "Truncated file");
+ }
+ }
+
+ return 1;
+}
+
+#define ufbxi_cache_mc_tag(a,b,c,d) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16 | (uint32_t)(c)<<8u | (uint32_t)(d))
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_tag(ufbxi_cache_context *cc, uint32_t *p_tag)
+{
+ char buf[4]; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, true));
+ *p_tag = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
+ if (*p_tag == ufbxi_cache_mc_tag('F','O','R','8')) {
+ cc->mc_for8 = true;
+ }
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_u32(ufbxi_cache_context *cc, uint32_t *p_value)
+{
+ char buf[4]; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, false));
+ *p_value = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
+ if (cc->mc_for8) {
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, false));
+ }
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_u64(ufbxi_cache_context *cc, uint64_t *p_value)
+{
+ if (!cc->mc_for8) {
+ uint32_t v32; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &v32));
+ *p_value = v32;
+ } else {
+ char buf[8]; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 8, false));
+ uint32_t hi = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
+ uint32_t lo = (uint32_t)(uint8_t)buf[4]<<24u | (uint32_t)(uint8_t)buf[5]<<16 | (uint32_t)(uint8_t)buf[6]<<8u | (uint32_t)(uint8_t)buf[7];
+ *p_value = (uint64_t)hi << 32u | (uint64_t)lo;
+ }
+ return 1;
+}
+
+static const uint8_t ufbxi_cache_data_format_size[] = {
+ 0, 4, 12, 8, 24,
+};
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_mc(ufbxi_cache_context *cc)
+{
+ uint32_t version = 0, time_start = 0, time_end = 0;
+ uint32_t count = 0, time = 0;
+ char skip_buf[8]; // ufbxi_uninit
+
+ for (;;) {
+ uint32_t tag; // ufbxi_uninit
+ uint64_t size; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_tag(cc, &tag));
+ if (tag == 0) break;
+
+ if (tag == ufbxi_cache_mc_tag('C','A','C','H') || tag == ufbxi_cache_mc_tag('M','Y','C','H')) {
+ continue;
+ }
+ if (cc->mc_for8) {
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, skip_buf, 4, false));
+ }
+
+ ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u64(cc, &size));
+ uint64_t begin = cc->file_offset;
+
+ size_t alignment = cc->mc_for8 ? 8 : 4;
+
+ ufbx_cache_data_format format = UFBX_CACHE_DATA_FORMAT_UNKNOWN;
+ switch (tag) {
+ case ufbxi_cache_mc_tag('F','O','R','4'): cc->mc_for8 = false; break;
+ case ufbxi_cache_mc_tag('F','O','R','8'): cc->mc_for8 = true; break;
+ case ufbxi_cache_mc_tag('V','R','S','N'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &version)); break;
+ case ufbxi_cache_mc_tag('S','T','I','M'):
+ ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time_start));
+ time = time_start;
+ break;
+ case ufbxi_cache_mc_tag('E','T','I','M'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time_end)); break;
+ case ufbxi_cache_mc_tag('T','I','M','E'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time)); break;
+ case ufbxi_cache_mc_tag('C','H','N','M'): {
+ ufbxi_check_err(&cc->error, size > 0 && size < SIZE_MAX);
+ size_t length = (size_t)size - 1;
+ size_t padded_length = ((size_t)size + alignment - 1) & ~(alignment - 1);
+ ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->name_buf, &cc->name_cap, padded_length));
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, cc->name_buf, padded_length, false));
+ cc->channel_name.data = cc->name_buf;
+ cc->channel_name.length = length;
+ ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &cc->channel_name, false));
+ } break;
+ case ufbxi_cache_mc_tag('S','I','Z','E'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &count)); break;
+ case ufbxi_cache_mc_tag('F','V','C','A'): format = UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT; break;
+ case ufbxi_cache_mc_tag('D','V','C','A'): format = UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE; break;
+ case ufbxi_cache_mc_tag('F','B','C','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_FLOAT; break;
+ case ufbxi_cache_mc_tag('D','B','C','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE; break;
+ case ufbxi_cache_mc_tag('D','B','L','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE; break;
+ default: ufbxi_fail_err(&cc->error, "Unknown tag");
+ }
+
+ if (format != UFBX_CACHE_DATA_FORMAT_UNKNOWN) {
+ ufbx_cache_frame *frame = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_frame, 1);
+ ufbxi_check_err(&cc->error, frame);
+
+ uint32_t elem_size = ufbxi_cache_data_format_size[format];
+ uint64_t total_size = (uint64_t)elem_size * (uint64_t)count;
+ ufbxi_check_err(&cc->error, size >= elem_size * count);
+
+ frame->channel = cc->channel_name;
+ frame->time = (double)time * (1.0/6000.0);
+ frame->filename = cc->stream_filename;
+ frame->data_format = format;
+ frame->data_encoding = UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN;
+ frame->data_offset = cc->file_offset;
+ frame->data_count = count;
+ frame->data_element_bytes = elem_size;
+ frame->data_total_bytes = total_size;
+ frame->file_format = UFBX_CACHE_FILE_FORMAT_MC;
+
+ uint64_t end = begin + ((size + alignment - 1) & ~(uint64_t)(alignment - 1));
+ ufbxi_check_err(&cc->error, end >= cc->file_offset);
+ uint64_t left = end - cc->file_offset;
+ ufbxi_check_err(&cc->error, ufbxi_cache_skip(cc, left));
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_pc2(ufbxi_cache_context *cc)
+{
+ char header[32]; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, header, sizeof(header), false));
+
+ uint32_t version = ufbxi_read_u32(header + 12);
+ uint32_t num_points = ufbxi_read_u32(header + 16);
+ double start_frame = ufbxi_read_f32(header + 20);
+ double frames_per_sample = ufbxi_read_f32(header + 24);
+ uint32_t num_samples = ufbxi_read_u32(header + 28);
+
+ (void)version;
+
+ ufbx_cache_frame *frames = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_frame, num_samples);
+ ufbxi_check_err(&cc->error, frames);
+
+ uint64_t total_points = (uint64_t)num_points * (uint64_t)num_samples;
+ ufbxi_check_err(&cc->error, total_points < UINT64_MAX / 12);
+
+ uint64_t offset = cc->file_offset;
+
+ // Skip almost to the end of the data and try to read one byte as there's
+ // nothing after the data so we can't detect EOF..
+ if (total_points > 0) {
+ char last_byte[1]; // ufbxi_uninit
+ ufbxi_check_err(&cc->error, ufbxi_cache_skip(cc, total_points * 12 - 1));
+ ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, last_byte, 1, false));
+ }
+
+ for (uint32_t i = 0; i < num_samples; i++) {
+ ufbx_cache_frame *frame = &frames[i];
+
+ double sample_frame = start_frame + (double)i * frames_per_sample;
+ frame->channel = cc->channel_name;
+ frame->time = sample_frame / cc->frames_per_second;
+ frame->filename = cc->stream_filename;
+ frame->data_format = UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT;
+ frame->data_encoding = UFBX_CACHE_DATA_ENCODING_LITTLE_ENDIAN;
+ frame->data_offset = offset;
+ frame->data_count = num_points;
+ frame->data_element_bytes = 12;
+ frame->data_total_bytes = num_points * 12;
+ frame->file_format = UFBX_CACHE_FILE_FORMAT_PC2;
+ offset += num_points * 12;
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline bool ufbxi_tmp_channel_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_cache_tmp_channel *a = (const ufbxi_cache_tmp_channel *)va, *b = (const ufbxi_cache_tmp_channel *)vb;
+ return ufbxi_str_less(a->name, b->name);
+}
+
+static ufbxi_noinline int ufbxi_cache_sort_tmp_channels(ufbxi_cache_context *cc, ufbxi_cache_tmp_channel *channels, size_t count)
+{
+ ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->tmp_arr, &cc->tmp_arr_size, count * sizeof(ufbxi_cache_tmp_channel)));
+ ufbxi_stable_sort(sizeof(ufbxi_cache_tmp_channel), 16, channels, cc->tmp_arr, count, &ufbxi_tmp_channel_less, NULL);
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_xml_imp(ufbxi_cache_context *cc, ufbxi_xml_document *doc)
+{
+ ufbxi_check_err(&cc->error, !cc->xml_loaded);
+
+ cc->xml_loaded = true;
+ cc->xml_ticks_per_frame = 250;
+ cc->xml_filename = cc->stream_filename;
+
+ ufbxi_xml_tag *tag_root = ufbxi_xml_find_child(doc->root, "Autodesk_Cache_File");
+ if (tag_root) {
+ ufbxi_xml_tag *tag_type = ufbxi_xml_find_child(tag_root, "cacheType");
+ ufbxi_xml_tag *tag_fps = ufbxi_xml_find_child(tag_root, "cacheTimePerFrame");
+ ufbxi_xml_tag *tag_channels = ufbxi_xml_find_child(tag_root, "Channels");
+
+ size_t num_extra = 0;
+ ufbxi_for(ufbxi_xml_tag, tag, tag_root->children, tag_root->num_children) {
+ if (tag->num_children != 1) continue;
+ if (strcmp(tag->name.data, "extra") != 0) continue;
+ ufbx_string *extra = ufbxi_push(&cc->tmp_stack, ufbx_string, 1);
+ ufbxi_check_err(&cc->error, extra);
+ *extra = tag->children[0].text;
+ ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, extra, false));
+ num_extra++;
+ }
+ cc->cache.extra_info.count = num_extra;
+ cc->cache.extra_info.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_string, num_extra);
+ ufbxi_check_err(&cc->error, cc->cache.extra_info.data);
+
+ if (tag_type) {
+ ufbxi_xml_attrib *type = ufbxi_xml_find_attrib(tag_type, "Type");
+ ufbxi_xml_attrib *format = ufbxi_xml_find_attrib(tag_type, "Format");
+ if (type) {
+ if (!strcmp(type->value.data, "OneFilePerFrame")) {
+ cc->xml_type = UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME;
+ } else if (!strcmp(type->value.data, "OneFile")) {
+ cc->xml_type = UFBXI_CACHE_XML_TYPE_SINGLE_FILE;
+ }
+ }
+ if (format) {
+ if (!strcmp(format->value.data, "mcc")) {
+ cc->xml_format = UFBXI_CACHE_XML_FORMAT_MCC;
+ } else if (!strcmp(format->value.data, "mcx")) {
+ cc->xml_format = UFBXI_CACHE_XML_FORMAT_MCX;
+ }
+ }
+ }
+
+ if (tag_fps) {
+ ufbxi_xml_attrib *fps = ufbxi_xml_find_attrib(tag_fps, "TimePerFrame");
+ if (fps) {
+ uint32_t value = ufbxi_parse_uint32_radix(fps->value.data, 10);
+ if (value > 0) {
+ cc->xml_ticks_per_frame = value;
+ }
+ }
+ }
+
+ if (tag_channels) {
+ cc->channels = ufbxi_push_zero(&cc->tmp, ufbxi_cache_tmp_channel, tag_channels->num_children);
+ ufbxi_check_err(&cc->error, cc->channels);
+
+ ufbxi_for(ufbxi_xml_tag, tag, tag_channels->children, tag_channels->num_children) {
+ ufbxi_xml_attrib *name = ufbxi_xml_find_attrib(tag, "ChannelName");
+ ufbxi_xml_attrib *type = ufbxi_xml_find_attrib(tag, "ChannelType");
+ ufbxi_xml_attrib *interpretation = ufbxi_xml_find_attrib(tag, "ChannelInterpretation");
+ if (!(name && type && interpretation)) continue;
+
+ ufbxi_cache_tmp_channel *channel = &cc->channels[cc->num_channels++];
+ channel->name = name->value;
+ channel->interpretation = interpretation->value;
+ ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &channel->name, false));
+ ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &channel->interpretation, false));
+
+ ufbxi_xml_attrib *sampling_rate = ufbxi_xml_find_attrib(tag, "SamplingRate");
+ ufbxi_xml_attrib *start_time = ufbxi_xml_find_attrib(tag, "StartTime");
+ ufbxi_xml_attrib *end_time = ufbxi_xml_find_attrib(tag, "EndTime");
+ if (sampling_rate && start_time && end_time) {
+ channel->sample_rate = ufbxi_parse_uint32_radix(sampling_rate->value.data, 10);
+ channel->start_time = ufbxi_parse_uint32_radix(start_time->value.data, 10);
+ channel->end_time = ufbxi_parse_uint32_radix(end_time->value.data, 10);
+ channel->current_time = channel->start_time;
+ channel->try_load = true;
+ }
+ }
+ }
+ }
+
+ ufbxi_check_err(&cc->error, ufbxi_cache_sort_tmp_channels(cc, cc->channels, cc->num_channels));
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_xml(ufbxi_cache_context *cc)
+{
+ ufbxi_xml_load_opts opts = { 0 };
+ opts.ator = cc->ator_tmp;
+ opts.read_fn = cc->stream.read_fn;
+ opts.read_user = cc->stream.user;
+ opts.prefix = cc->pos;
+ opts.prefix_length = ufbxi_to_size(cc->pos_end - cc->pos);
+ ufbxi_xml_document *doc = ufbxi_load_xml(&opts, &cc->error);
+ ufbxi_check_err(&cc->error, doc);
+
+ int xml_ok = ufbxi_cache_load_xml_imp(cc, doc);
+ ufbxi_free_xml(doc);
+ ufbxi_check_err(&cc->error, xml_ok);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_file(ufbxi_cache_context *cc, ufbx_string filename)
+{
+ cc->stream_filename = filename;
+ ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &cc->stream_filename, false));
+
+ // Assume all files have at least 16 bytes of header
+ size_t magic_len = cc->stream.read_fn(cc->stream.user, cc->buffer, 16);
+ ufbxi_check_err_msg(&cc->error, magic_len <= 16, "IO error");
+ ufbxi_check_err_msg(&cc->error, magic_len == 16, "Truncated file");
+ cc->pos = cc->buffer;
+ cc->pos_end = cc->buffer + 16;
+
+ cc->file_offset = 0;
+
+ if (!memcmp(cc->buffer, "POINTCACHE2", 11)) {
+ ufbxi_check_err(&cc->error, ufbxi_cache_load_pc2(cc));
+ } else if (!memcmp(cc->buffer, "FOR4", 4) || !memcmp(cc->buffer, "FOR8", 4)) {
+ ufbxi_check_err(&cc->error, ufbxi_cache_load_mc(cc));
+ } else {
+ ufbxi_check_err(&cc->error, ufbxi_cache_load_xml(cc));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_try_open_file(ufbxi_cache_context *cc, ufbx_string filename, const ufbx_blob *original_filename, bool *p_found)
+{
+ memset(&cc->stream, 0, sizeof(cc->stream));
+ ufbxi_regression_assert(strlen(filename.data) == filename.length);
+ if (!ufbxi_open_file(&cc->open_file_cb, &cc->stream, filename.data, filename.length, original_filename, cc->ator_tmp, UFBX_OPEN_FILE_GEOMETRY_CACHE)) {
+ return 1;
+ }
+
+ int ok = ufbxi_cache_load_file(cc, filename);
+ *p_found = true;
+
+ if (cc->stream.close_fn) {
+ cc->stream.close_fn(cc->stream.user);
+ }
+
+ return ok;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_frame_files(ufbxi_cache_context *cc)
+{
+ if (cc->xml_filename.length == 0) return 1;
+
+ const char *extension = NULL;
+ switch (cc->xml_format) {
+ case UFBXI_CACHE_XML_FORMAT_MCC: extension = "mc"; break;
+ case UFBXI_CACHE_XML_FORMAT_MCX: extension = "mcx"; break;
+ default: return 1;
+ }
+
+ // Ensure worst case space for `path/filenameFrame123Tick456.mcx`
+ size_t name_buf_len = cc->xml_filename.length + 64;
+ char *name_buf = ufbxi_push(&cc->tmp, char, name_buf_len);
+ ufbxi_check_err(&cc->error, name_buf);
+
+ // Find the prefix before `.xml`
+ size_t prefix_len = cc->xml_filename.length;
+ for (size_t i = prefix_len; i > 0; --i) {
+ if (cc->xml_filename.data[i - 1] == '.') {
+ prefix_len = i - 1;
+ break;
+ }
+ }
+ memcpy(name_buf, cc->xml_filename.data, prefix_len);
+
+ char *suffix_data = name_buf + prefix_len;
+ size_t suffix_len = name_buf_len - prefix_len;
+
+ ufbx_string filename;
+ filename.data = name_buf;
+
+ if (cc->xml_type == UFBXI_CACHE_XML_TYPE_SINGLE_FILE) {
+ filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, ".%s", extension);
+ bool found = false;
+ ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename, NULL, &found));
+ } else if (cc->xml_type == UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME) {
+ uint32_t lowest_time = 0;
+ for (;;) {
+ // Find the first `time >= lowest_time` value that has data in some channel
+ uint32_t time = UINT32_MAX;
+ ufbxi_for(ufbxi_cache_tmp_channel, chan, cc->channels, cc->num_channels) {
+ if (!chan->try_load || chan->consecutive_fails > 10) continue;
+ uint32_t sample_rate = chan->sample_rate ? chan->sample_rate : cc->xml_ticks_per_frame;
+ if (chan->current_time < lowest_time) {
+ uint32_t delta = (lowest_time - chan->current_time - 1) / sample_rate;
+ chan->current_time += delta * sample_rate;
+ if (UINT32_MAX - chan->current_time >= sample_rate) {
+ chan->current_time += sample_rate;
+ } else {
+ chan->try_load = false;
+ continue;
+ }
+ }
+ if (chan->current_time <= chan->end_time) {
+ time = ufbxi_min32(time, chan->current_time);
+ }
+ }
+ if (time == UINT32_MAX) break;
+
+ // Try to load a file at the specified frame/tick
+ uint32_t frame = time / cc->xml_ticks_per_frame;
+ uint32_t tick = time % cc->xml_ticks_per_frame;
+ if (tick == 0) {
+ filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, "Frame%u.%s", frame, extension);
+ } else {
+ filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, "Frame%uTick%u.%s", frame, tick, extension);
+ }
+ bool found = false;
+ ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename, NULL, &found));
+
+ // Update channel status
+ ufbxi_for(ufbxi_cache_tmp_channel, chan, cc->channels, cc->num_channels) {
+ if (chan->current_time == time) {
+ chan->consecutive_fails = found ? 0 : chan->consecutive_fails + 1;
+ }
+ }
+
+ lowest_time = time + 1;
+ }
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline bool ufbxi_cmp_cache_frame_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_cache_frame *a = (const ufbx_cache_frame *)va, *b = (const ufbx_cache_frame *)vb;
+ if (a->channel.data != b->channel.data) {
+ // Channel names should be interned
+ ufbxi_regression_assert(!ufbxi_str_equal(a->channel, b->channel));
+ return ufbxi_str_less(a->channel, b->channel);
+ }
+ return a->time < b->time;
+}
+
+static ufbxi_noinline int ufbxi_cache_sort_frames(ufbxi_cache_context *cc, ufbx_cache_frame *frames, size_t count)
+{
+ ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->tmp_arr, &cc->tmp_arr_size, count * sizeof(ufbx_cache_frame)));
+ ufbxi_stable_sort(sizeof(ufbx_cache_frame), 16, frames, cc->tmp_arr, count, &ufbxi_cmp_cache_frame_less, NULL);
+ return 1;
+}
+
+typedef struct {
+ ufbx_cache_interpretation interpretation;
+ const char *pattern;
+} ufbxi_cache_interpretation_name;
+
+static const ufbxi_cache_interpretation_name ufbxi_cache_interpretation_names[] = {
+ { UFBX_CACHE_INTERPRETATION_POINTS, "\\cpoints?" },
+ { UFBX_CACHE_INTERPRETATION_VERTEX_POSITION, "\\cpositions?" },
+ { UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL, "\\cnormals?" },
+};
+
+static ufbxi_noinline int ufbxi_cache_setup_channels(ufbxi_cache_context *cc)
+{
+ ufbxi_cache_tmp_channel *tmp_chan = cc->channels, *tmp_end = ufbxi_add_ptr(tmp_chan, cc->num_channels);
+
+ size_t begin = 0, num_channels = 0;
+ while (begin < cc->cache.frames.count) {
+ ufbx_cache_frame *frame = &cc->cache.frames.data[begin];
+ size_t end = begin + 1;
+ while (end < cc->cache.frames.count && cc->cache.frames.data[end].channel.data == frame->channel.data) {
+ end++;
+ }
+
+ ufbx_cache_channel *chan = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_channel, 1);
+ ufbxi_check_err(&cc->error, chan);
+
+ chan->name = frame->channel;
+ chan->interpretation_name = ufbx_empty_string;
+ chan->frames.data = frame;
+ chan->frames.count = end - begin;
+
+ while (tmp_chan < tmp_end && ufbxi_str_less(tmp_chan->name, chan->name)) {
+ tmp_chan++;
+ }
+ if (tmp_chan < tmp_end && ufbxi_str_equal(tmp_chan->name, chan->name)) {
+ chan->interpretation_name = tmp_chan->interpretation;
+ }
+
+ if (frame->file_format == UFBX_CACHE_FILE_FORMAT_PC2) {
+ chan->interpretation = UFBX_CACHE_INTERPRETATION_VERTEX_POSITION;
+ } else {
+ ufbxi_for(const ufbxi_cache_interpretation_name, name, ufbxi_cache_interpretation_names, ufbxi_arraycount(ufbxi_cache_interpretation_names)) {
+ if (ufbxi_match(&chan->interpretation_name, name->pattern)) {
+ chan->interpretation = name->interpretation;
+ break;
+ }
+ }
+ }
+
+ ufbx_mirror_axis mirror_axis = UFBX_MIRROR_AXIS_NONE;
+ ufbx_real scale_factor = 1.0f;
+ if (chan->interpretation != UFBX_CACHE_INTERPRETATION_UNKNOWN) {
+ mirror_axis = cc->opts.mirror_axis;
+ if (cc->opts.use_scale_factor) {
+ scale_factor = cc->opts.scale_factor;
+ }
+ }
+ chan->mirror_axis = mirror_axis;
+ chan->scale_factor = scale_factor;
+ ufbxi_for_list(ufbx_cache_frame, f, chan->frames) {
+ f->mirror_axis = mirror_axis;
+ f->scale_factor = scale_factor;
+ }
+
+ num_channels++;
+ begin = end;
+ }
+
+ cc->cache.channels.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_cache_channel, num_channels);
+ ufbxi_check_err(&cc->error, cc->cache.channels.data);
+ cc->cache.channels.count = num_channels;
+
+ return 1;
+}
+
+
+static ufbxi_noinline int ufbxi_cache_load_imp(ufbxi_cache_context *cc, ufbx_string filename)
+{
+ cc->tmp.ator = cc->ator_tmp;
+ cc->tmp_stack.ator = cc->ator_tmp;
+
+ cc->channel_name.data = ufbxi_empty_char;
+
+ if (!cc->open_file_cb.fn) {
+ cc->open_file_cb.fn = ufbx_default_open_file;
+ }
+
+ // Make sure the filename we pass to `open_file_fn()` is NULL-terminated
+ char *filename_data = ufbxi_push(&cc->tmp, char, filename.length + 1);
+ ufbxi_check_err(&cc->error, filename_data);
+ memcpy(filename_data, filename.data, filename.length);
+ filename_data[filename.length] = '\0';
+ ufbx_string filename_copy = { filename_data, filename.length };
+
+ // TODO: NULL termination!
+ bool found = false;
+ ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename_copy, NULL, &found));
+ if (!found) {
+ ufbxi_set_err_info(&cc->error, filename.data, filename.length);
+ ufbxi_fail_err_msg(&cc->error, "open_file_fn()", "File not found");
+ }
+
+ cc->cache.root_filename = cc->stream_filename;
+
+ ufbxi_check_err(&cc->error, ufbxi_cache_load_frame_files(cc));
+
+ size_t num_frames = cc->tmp_stack.num_items;
+ cc->cache.frames.count = num_frames;
+ cc->cache.frames.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_cache_frame, num_frames);
+ ufbxi_check_err(&cc->error, cc->cache.frames.data);
+
+ ufbxi_check_err(&cc->error, ufbxi_cache_sort_frames(cc, cc->cache.frames.data, cc->cache.frames.count));
+ ufbxi_check_err(&cc->error, ufbxi_cache_setup_channels(cc));
+
+ // Must be last allocation!
+ cc->imp = ufbxi_push(&cc->result, ufbxi_geometry_cache_imp, 1);
+ ufbxi_check_err(&cc->error, cc->imp);
+
+ ufbxi_init_ref(&cc->imp->refcount, UFBXI_CACHE_IMP_MAGIC, NULL);
+
+ cc->imp->cache = cc->cache;
+ cc->imp->magic = UFBXI_CACHE_IMP_MAGIC;
+ cc->imp->owned_by_scene = cc->owned_by_scene;
+ cc->imp->refcount.ator = cc->ator_result;
+ cc->imp->refcount.buf = cc->result;
+ cc->imp->refcount.buf.ator = &cc->imp->refcount.ator;
+ cc->imp->string_buf = cc->string_pool.buf;
+ cc->imp->string_buf.ator = &cc->imp->refcount.ator;
+
+ return 1;
+}
+
+ufbxi_noinline static ufbx_geometry_cache *ufbxi_cache_load(ufbxi_cache_context *cc, ufbx_string filename)
+{
+ int ok = ufbxi_cache_load_imp(cc, filename);
+
+ ufbxi_buf_free(&cc->tmp);
+ ufbxi_buf_free(&cc->tmp_stack);
+ ufbxi_free(cc->ator_tmp, char, cc->name_buf, cc->name_cap);
+ ufbxi_free(cc->ator_tmp, char, cc->tmp_arr, cc->tmp_arr_size);
+ if (!cc->owned_by_scene) {
+ ufbxi_string_pool_temp_free(&cc->string_pool);
+ ufbxi_free_ator(cc->ator_tmp);
+ }
+
+ if (ok) {
+ return &cc->imp->cache;
+ } else {
+ ufbxi_fix_error_type(&cc->error, "Failed to load geometry cache", NULL);
+ if (!cc->owned_by_scene) {
+ ufbxi_buf_free(&cc->result);
+ ufbxi_buf_free(&cc->string_pool.buf);
+ ufbxi_free_ator(&cc->ator_result);
+ }
+ return NULL;
+ }
+}
+
+ufbxi_noinline static ufbx_geometry_cache *ufbxi_load_geometry_cache(ufbx_string filename, const ufbx_geometry_cache_opts *user_opts, ufbx_error *p_error)
+{
+ ufbx_geometry_cache_opts opts; // ufbxi_uninit
+ if (user_opts) {
+ opts = *user_opts;
+ } else {
+ memset(&opts, 0, sizeof(opts));
+ }
+
+ ufbxi_cache_context cc = { UFBX_ERROR_NONE };
+ ufbxi_allocator ator_tmp = { 0 };
+ ufbxi_init_ator(&cc.error, &ator_tmp, &opts.temp_allocator, "temp");
+ ufbxi_init_ator(&cc.error, &cc.ator_result, &opts.result_allocator, "result");
+ cc.ator_tmp = &ator_tmp;
+
+ cc.opts = opts;
+
+ cc.open_file_cb = opts.open_file_cb;
+
+ cc.string_pool.error = &cc.error;
+ ufbxi_map_init(&cc.string_pool.map, cc.ator_tmp, &ufbxi_map_cmp_string, NULL);
+ cc.string_pool.buf.ator = &cc.ator_result;
+ cc.string_pool.buf.unordered = true;
+ cc.string_pool.initial_size = 64;
+ cc.result.ator = &cc.ator_result;
+
+ cc.frames_per_second = opts.frames_per_second > 0.0 ? opts.frames_per_second : 30.0;
+
+ ufbx_geometry_cache *cache = ufbxi_cache_load(&cc, filename);
+ if (p_error) {
+ if (cache) {
+ ufbxi_clear_error(p_error);
+ } else {
+ *p_error = cc.error;
+ }
+ }
+ return cache;
+}
+
+static ufbxi_noinline void ufbxi_free_geometry_cache_imp(ufbxi_geometry_cache_imp *imp)
+{
+ ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
+ ufbxi_buf_free(&imp->string_buf);
+}
+
+#else
+
+typedef struct {
+ ufbxi_refcount refcount;
+ uint32_t magic;
+ bool owned_by_scene;
+} ufbxi_geometry_cache_imp;
+
+static ufbxi_noinline ufbx_geometry_cache *ufbxi_load_geometry_cache(ufbx_string filename, const ufbx_geometry_cache_opts *user_opts, ufbx_error *p_error)
+{
+ if (p_error) {
+ memset(p_error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(p_error, "UFBX_ENABLE_GEOMETRY_CACHE");
+ ufbxi_report_err_msg(p_error, "UFBXI_FEATURE_GEOMETRY_CACHE", "Feature disabled");
+ }
+ return NULL;
+}
+
+static ufbxi_forceinline void ufbxi_free_geometry_cache_imp(ufbxi_geometry_cache_imp *imp)
+{
+}
+
+#endif
+
+// -- External files
+
+typedef enum {
+ UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE,
+} ufbxi_external_file_type;
+
+typedef struct {
+ ufbxi_external_file_type type;
+ ufbx_string filename;
+ ufbx_string absolute_filename;
+ size_t index;
+ void *data;
+ size_t data_size;
+} ufbxi_external_file;
+
+static bool ufbxi_less_external_file(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_external_file *a = (const ufbxi_external_file*)va, *b = (const ufbxi_external_file*)vb;
+ if (a->type != b->type) return a->type < b->type;
+ int cmp = ufbxi_str_cmp(a->filename, b->filename);
+ if (cmp != 0) return cmp < 0;
+ if (a->index != b->index) return a->index < b->index;
+ return false;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_external_cache(ufbxi_context *uc, ufbxi_external_file *file)
+{
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ ufbxi_cache_context cc = { UFBX_ERROR_NONE };
+ cc.owned_by_scene = true;
+
+ cc.open_file_cb = uc->opts.open_file_cb;
+ cc.frames_per_second = uc->scene.settings.frames_per_second;
+
+ // Temporarily "borrow" allocators for the geometry cache
+ cc.ator_tmp = &uc->ator_tmp;
+ cc.string_pool = uc->string_pool;
+ cc.result = uc->result;
+
+ cc.opts.mirror_axis = uc->mirror_axis;
+ cc.opts.use_scale_factor = true;
+ cc.opts.scale_factor = uc->scene.metadata.geometry_scale;
+
+ ufbx_geometry_cache *cache = ufbxi_cache_load(&cc, file->filename);
+ if (!cache) {
+ if (cc.error.type == UFBX_ERROR_FILE_NOT_FOUND) {
+ memset(&cc.error, 0, sizeof(cc.error));
+ cache = ufbxi_cache_load(&cc, file->absolute_filename);
+ }
+ }
+
+ // Return the "borrowed" allocators
+ uc->string_pool = cc.string_pool;
+ uc->result = cc.result;
+
+ if (!cache) {
+ if (cc.error.type == UFBX_ERROR_FILE_NOT_FOUND) {
+ if (uc->opts.ignore_missing_external_files) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Failed to open geometry cache: %s", file->filename.data));
+ return 1;
+ } else {
+ cc.error.type = UFBX_ERROR_EXTERNAL_FILE_NOT_FOUND;
+ cc.error.description.data = "External file not found";
+ cc.error.description.length = strlen("External file not found");
+ }
+ }
+
+ uc->error = cc.error;
+ return 0;
+ }
+
+ file->data = cache;
+ return 1;
+#else
+ if (uc->opts.ignore_missing_external_files) return 1;
+
+ ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_GEOMETRY_CACHE");
+ ufbxi_fail_msg("UFBXI_FEATURE_GEOMETRY_CACHE", "Feature disabled");
+#endif
+}
+
+static ufbxi_noinline ufbxi_external_file *ufbxi_find_external_file(ufbxi_external_file *files, size_t num_files, ufbxi_external_file_type type, const char *name)
+{
+ size_t ix = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbxi_external_file, 32, &ix, files, 0, num_files,
+ ( type != a->type ? type < a->type : strcmp(a->filename.data, name) < 0 ),
+ ( a->type == type && a->filename.data == name ));
+ return ix != SIZE_MAX ? &files[ix] : NULL;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_external_files(ufbxi_context *uc)
+{
+ size_t num_files = 0;
+
+ // Gather external files to deduplicate them
+ ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
+ ufbx_cache_file *cache = *p_cache;
+ if (cache->filename.length > 0) {
+ ufbxi_external_file *file = ufbxi_push_zero(&uc->tmp_stack, ufbxi_external_file, 1);
+ ufbxi_check(file);
+ file->index = num_files++;
+ file->type = UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE;
+ file->filename = cache->filename;
+ file->absolute_filename = cache->absolute_filename;
+ }
+ }
+
+ // Sort and load the external files
+ ufbxi_external_file *files = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_external_file, num_files);
+ ufbxi_check(files);
+ ufbxi_unstable_sort(files, num_files, sizeof(ufbxi_external_file), &ufbxi_less_external_file, NULL);
+
+ ufbxi_external_file_type prev_type = UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE;
+ const char *prev_name = NULL;
+ ufbxi_for(ufbxi_external_file, file, files, num_files) {
+ if (file->filename.data == prev_name && file->type == prev_type) continue;
+ if (file->type == UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE) {
+ ufbxi_check(ufbxi_load_external_cache(uc, file));
+ }
+ prev_name = file->filename.data;
+ prev_type = file->type;
+ }
+
+ // Patch the loaded files
+ ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
+ ufbx_cache_file *cache = *p_cache;
+ ufbxi_external_file *file = ufbxi_find_external_file(files, num_files,
+ UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE, cache->filename.data);
+ if (file && file->data) {
+ cache->external_cache = (ufbx_geometry_cache*)file->data;
+ }
+ }
+
+ // Patch the geometry deformers
+ ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, uc->scene.cache_deformers) {
+ ufbx_cache_deformer *deformer = *p_deformer;
+ if (!deformer->file || !deformer->file->external_cache) continue;
+ ufbx_geometry_cache *cache = deformer->file->external_cache;
+ deformer->external_cache = cache;
+
+ // HACK: It seems like channels may be connected even if the name is wrong
+ // and they work when exporting from Marvelous to Maya...
+ if (cache->channels.count == 1) {
+ deformer->external_channel = &cache->channels.data[0];
+ } else {
+ ufbx_string channel = deformer->channel;
+ size_t ix = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_cache_channel, 16, &ix, cache->channels.data, 0, cache->channels.count,
+ ( ufbxi_str_less(a->name, channel) ), ( a->name.data == channel.data ));
+ if (ix != SIZE_MAX) {
+ deformer->external_channel = &cache->channels.data[ix];
+ }
+ }
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline void ufbxi_transform_to_axes(ufbxi_context *uc, ufbx_coordinate_axes dst_axes)
+{
+ if (!ufbx_coordinate_axes_valid(uc->scene.settings.axes)) return;
+ if (!ufbxi_axis_matrix(&uc->axis_matrix, uc->scene.settings.axes, dst_axes)) return;
+
+ if (ufbx_matrix_determinant(&uc->axis_matrix) < 0.0f) {
+ if (uc->opts.handedness_conversion_axis != UFBX_MIRROR_AXIS_NONE) {
+ ufbx_mirror_axis mirror_axis = uc->opts.handedness_conversion_axis;
+ uc->mirror_axis = mirror_axis;
+ uc->scene.metadata.mirror_axis = uc->mirror_axis;
+
+ ufbxi_mirror_matrix_dst(&uc->axis_matrix, uc->mirror_axis);
+ ufbxi_dev_assert(ufbx_matrix_determinant(&uc->axis_matrix) >= 0.0f);
+
+ ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
+ ufbx_node *node = *p_node;
+ if (!node->is_root) {
+ node->adjust_mirror_axis = mirror_axis;
+ }
+ }
+ }
+ }
+
+ if (uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT) {
+ ufbx_matrix axis_mat = uc->axis_matrix;
+ if (!ufbxi_is_transform_identity(&uc->scene.root_node->local_transform)) {
+ ufbx_matrix root_mat = ufbx_transform_to_matrix(&uc->scene.root_node->local_transform);
+ axis_mat = ufbx_matrix_mul(&root_mat, &axis_mat);
+ }
+
+ ufbxi_mirror_matrix(&axis_mat, uc->mirror_axis);
+
+ uc->scene.root_node->local_transform = ufbx_matrix_to_transform(&axis_mat);
+ uc->scene.root_node->node_to_parent = axis_mat;
+ }
+}
+
+static ufbxi_noinline int ufbxi_scale_units(ufbxi_context *uc, ufbx_real target_meters)
+{
+ if (uc->scene.settings.unit_meters <= 0.0f) return 1;
+ target_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), target_meters);
+
+ ufbx_real ratio = uc->scene.settings.unit_meters / target_meters;
+ ratio = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), ratio);
+ if (ratio == 1.0f) return 1;
+
+ uc->unit_scale = ratio;
+
+ if (uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT) {
+ uc->scene.root_node->local_transform.scale.x *= ratio;
+ uc->scene.root_node->local_transform.scale.y *= ratio;
+ uc->scene.root_node->local_transform.scale.z *= ratio;
+ uc->scene.root_node->node_to_parent.m00 *= ratio;
+ uc->scene.root_node->node_to_parent.m01 *= ratio;
+ uc->scene.root_node->node_to_parent.m02 *= ratio;
+ uc->scene.root_node->node_to_parent.m10 *= ratio;
+ uc->scene.root_node->node_to_parent.m11 *= ratio;
+ uc->scene.root_node->node_to_parent.m12 *= ratio;
+ uc->scene.root_node->node_to_parent.m20 *= ratio;
+ uc->scene.root_node->node_to_parent.m21 *= ratio;
+ uc->scene.root_node->node_to_parent.m22 *= ratio;
+ }
+
+ return 1;
+}
+
+// -- Curve evaluation
+
+static ufbxi_forceinline double ufbxi_find_cubic_bezier_t(double p1, double p2, double x0)
+{
+ double p1_3 = p1 * 3.0, p2_3 = p2 * 3.0;
+ double a = p1_3 - p2_3 + 1.0;
+ double b = p2_3 - p1_3 - p1_3;
+ double c = p1_3;
+
+ double a_3 = 3.0*a, b_2 = 2.0*b;
+ double t = x0;
+ double x1, t2, t3;
+
+ // Manually unroll three iterations of Newton-Raphson, this is enough
+ // for most tangents
+ t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
+ t -= x1 / (a_3*t2 + b_2*t + c);
+
+ t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
+ t -= x1 / (a_3*t2 + b_2*t + c);
+
+ t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
+ t -= x1 / (a_3*t2 + b_2*t + c);
+
+ // 4 ULP from 1.0
+ const double eps = 8.881784197001252e-16;
+ if (ufbx_fabs(x1) <= eps) return t;
+
+ // Perform more iterations until we reach desired accuracy
+ for (size_t i = 0; i < 4; i++) {
+
+ t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
+ t -= x1 / (a_3*t2 + b_2*t + c);
+
+ t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
+ t -= x1 / (a_3*t2 + b_2*t + c);
+
+ if (ufbx_fabs(x1) <= eps) return t;
+ }
+
+ return t;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_evaluate_skinning(ufbx_scene *scene, ufbx_error *error, ufbxi_buf *buf_result, ufbxi_buf *buf_tmp,
+ double time, bool load_caches, ufbx_geometry_cache_data_opts *cache_opts)
+{
+#if UFBXI_FEATURE_SKINNING_EVALUATION
+ size_t max_skinned_indices = 0;
+
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, scene->meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+ if (mesh->blend_deformers.count == 0 && mesh->skin_deformers.count == 0 && (mesh->cache_deformers.count == 0 || !load_caches)) continue;
+ max_skinned_indices = ufbxi_max_sz(max_skinned_indices, mesh->num_indices);
+ }
+
+ ufbx_topo_edge *topo = ufbxi_push(buf_tmp, ufbx_topo_edge, max_skinned_indices);
+ ufbxi_check_err(error, topo);
+
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, scene->meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+ if (mesh->blend_deformers.count == 0 && mesh->skin_deformers.count == 0 && (mesh->cache_deformers.count == 0 || !load_caches)) continue;
+ if (mesh->num_vertices == 0) continue;
+
+ size_t num_vertices = mesh->num_vertices;
+ ufbx_vec3 *result_pos = ufbxi_push(buf_result, ufbx_vec3, num_vertices + 1);
+ ufbxi_check_err(error, result_pos);
+
+ result_pos[0] = ufbx_zero_vec3;
+ result_pos++;
+
+ bool cached_position = false, cached_normals = false;
+ if (load_caches && mesh->cache_deformers.count > 0) {
+ ufbxi_for_ptr_list(ufbx_cache_deformer, p_cache, mesh->cache_deformers) {
+ ufbx_cache_channel *channel = (*p_cache)->external_channel;
+ if (!channel) continue;
+
+ if ((channel->interpretation == UFBX_CACHE_INTERPRETATION_VERTEX_POSITION || channel->interpretation == UFBX_CACHE_INTERPRETATION_POINTS) && !cached_position) {
+ size_t num_read = ufbx_sample_geometry_cache_vec3(channel, time, result_pos, num_vertices, cache_opts);
+ if (num_read == num_vertices) {
+ mesh->skinned_is_local = true;
+ cached_position = true;
+ }
+ } else if (channel->interpretation == UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL && !cached_normals) {
+ // TODO: Is this right at all?
+ size_t num_normals = mesh->skinned_normal.values.count;
+ ufbx_vec3 *normal_data = ufbxi_push(buf_result, ufbx_vec3, num_normals + 1);
+ ufbxi_check_err(error, normal_data);
+ normal_data[0] = ufbx_zero_vec3;
+ normal_data++;
+
+ size_t num_read = ufbx_sample_geometry_cache_vec3(channel, time, normal_data, num_normals, cache_opts);
+ if (num_read == num_normals) {
+ cached_normals = true;
+ mesh->skinned_normal.values.data = normal_data;
+ }
+ }
+ }
+ }
+
+ if (!cached_position) {
+ memcpy(result_pos, mesh->vertices.data, num_vertices * sizeof(ufbx_vec3));
+
+ ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, mesh->blend_deformers) {
+ ufbx_add_blend_vertex_offsets(*p_blend, result_pos, num_vertices, 1.0f);
+ }
+
+ // TODO: What should we do about multiple skins??
+ if (mesh->skin_deformers.count > 0) {
+ ufbx_matrix *fallback = mesh->instances.count > 0 ? &mesh->instances.data[0]->geometry_to_world : NULL;
+ ufbx_skin_deformer *skin = mesh->skin_deformers.data[0];
+ for (size_t i = 0; i < num_vertices; i++) {
+ ufbx_matrix mat = ufbx_get_skin_vertex_matrix(skin, i, fallback);
+ result_pos[i] = ufbx_transform_position(&mat, result_pos[i]);
+ }
+
+ mesh->skinned_is_local = false;
+ }
+ }
+
+ mesh->skinned_position.values.data = result_pos;
+
+ if (!cached_normals) {
+ size_t num_indices = mesh->num_indices;
+ uint32_t *normal_indices = ufbxi_push(buf_result, uint32_t, num_indices);
+ ufbxi_check_err(error, normal_indices);
+
+ ufbx_compute_topology(mesh, topo, num_indices);
+ size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, num_indices, normal_indices, num_indices, false);
+
+ if (num_normals == mesh->num_vertices) {
+ mesh->skinned_normal.unique_per_vertex = true;
+ }
+
+ ufbx_vec3 *normal_data = ufbxi_push(buf_result, ufbx_vec3, num_normals + 1);
+ ufbxi_check_err(error, normal_data);
+
+ normal_data[0] = ufbx_zero_vec3;
+ normal_data++;
+
+ ufbx_compute_normals(mesh, &mesh->skinned_position, normal_indices, num_indices, normal_data, num_normals);
+
+ mesh->generated_normals = true;
+ mesh->skinned_normal.exists = true;
+ mesh->skinned_normal.values.data = normal_data;
+ mesh->skinned_normal.values.count = num_normals;
+ mesh->skinned_normal.indices.data = normal_indices;
+ mesh->skinned_normal.indices.count = num_indices;
+ mesh->skinned_normal.value_reals = 3;
+ }
+ }
+
+ return 1;
+#else
+ ufbxi_fmt_err_info(error, "UFBX_ENABLE_SKINNING_EVALUATION");
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_SKINNING_EVALUATION", "Feature disabled");
+ return 0;
+#endif
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_fixup_opts_string(ufbxi_context *uc, ufbx_string *str, bool push)
+{
+ if (str->length > 0) {
+ if (str->length == SIZE_MAX) {
+ str->length = str->data ? strlen(str->data) : 0;
+ }
+ if (push) {
+ ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, str, false));
+ }
+ } else {
+ str->data = ufbxi_empty_char;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_resolve_warning_elements(ufbxi_context *uc)
+{
+ size_t num_elements = uc->tmp_element_id.num_items;
+ uint32_t *element_ids = ufbxi_push_pop(&uc->tmp, &uc->tmp_element_id, uint32_t, num_elements);
+ ufbxi_check(element_ids);
+
+ ufbxi_for_list(ufbx_warning, warning, uc->scene.metadata.warnings) {
+ uint32_t element_id = warning->element_id;
+ // Decode `element_id`, see HACK(warning-element) in `ufbxi_vwarnf_imp()` for the encoding.
+ if ((element_id & 0x80000000u) != 0 && element_id != ~0u) {
+ warning->element_id = element_ids[element_id & ~0x80000000u];
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_imp(ufbxi_context *uc)
+{
+ // Check for deferred failure
+ if (uc->deferred_failure) return 0;
+ if (uc->deferred_load) {
+ ufbx_stream stream = { 0 };
+ ufbx_open_file_opts opts = { 0 };
+ const char *filename = uc->load_filename;
+ size_t filename_len = uc->load_filename_len;
+ bool ok = false;
+ if (filename_len == SIZE_MAX) {
+ opts.filename_null_terminated = true;
+ filename_len = strlen(filename);
+ }
+ if (uc->opts.filename.length == 0 || uc->opts.filename.data == NULL) {
+ uc->opts.filename.data = filename;
+ uc->opts.filename.length = filename_len;
+ }
+ ufbx_error error;
+ error.type = UFBX_ERROR_NONE;
+ if (uc->opts.open_main_file_with_default || uc->opts.open_file_cb.fn == &ufbx_default_open_file) {
+ ufbx_open_file_context ctx = (ufbx_open_file_context)&uc->ator_tmp;
+ ok = ufbx_open_file_ctx(&stream, ctx, filename, filename_len, &opts, &error);
+ } else {
+ ok = ufbxi_open_file(&uc->opts.open_file_cb, &stream, uc->load_filename, filename_len, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_MAIN_MODEL);
+ }
+ if (!ok) {
+ if (error.type != UFBX_ERROR_NONE) {
+ // cppcheck-suppress uninitStructMember
+ uc->error = error;
+ } else {
+ ufbxi_set_err_info(&uc->error, filename, filename_len);
+ }
+ ufbxi_fail_msg("open_file_fn()", "File not found");
+ }
+ uc->read_fn = stream.read_fn;
+ uc->skip_fn = stream.skip_fn;
+ uc->size_fn = stream.size_fn;
+ uc->close_fn = stream.close_fn;
+ uc->read_user = stream.user;
+ }
+
+ if (uc->opts.progress_cb.fn && uc->progress_bytes_total == 0 && uc->size_fn) {
+ uint64_t total = uc->size_fn(uc->read_user);
+ ufbxi_check(total != UINT64_MAX);
+ uc->progress_bytes_total = total;
+ }
+
+ ufbxi_check(uc->opts.path_separator >= 0x20 && uc->opts.path_separator <= 0x7e);
+
+ ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.filename, false));
+ ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.obj_mtl_path, true));
+ ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.geometry_transform_helper_name, true));
+ ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.scale_helper_name, true));
+
+ ufbxi_check(ufbxi_thread_pool_init(&uc->thread_pool, &uc->error, &uc->ator_tmp, &uc->opts.thread_opts));
+
+ if (!uc->opts.allow_unsafe) {
+ ufbxi_check_msg(uc->opts.index_error_handling != UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE, "Unsafe options");
+ ufbxi_check_msg(uc->opts.unicode_error_handling != UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE, "Unsafe options");
+ } else {
+ uc->scene.metadata.is_unsafe = true;
+ }
+
+ if (uc->opts.index_error_handling == UFBX_INDEX_ERROR_HANDLING_NO_INDEX) {
+ uc->scene.metadata.may_contain_no_index = true;
+ }
+
+ uc->retain_mesh_parts = !uc->opts.ignore_geometry && !uc->opts.skip_mesh_parts;
+ uc->scene.metadata.may_contain_missing_vertex_position = uc->opts.allow_missing_vertex_position;
+ uc->scene.metadata.may_contain_broken_elements = uc->opts.connect_broken_elements;
+
+ uc->scene.metadata.creator.data = ufbxi_empty_char;
+
+ uc->unit_scale = 1.0f;
+ if (uc->data == NULL) {
+ ufbxi_dev_assert(uc->data_begin == NULL);
+ uc->data_begin = uc->data = ufbxi_zero_size_buffer;
+ }
+
+ uc->retain_vertex_w = (uc->opts.retain_dom || uc->opts.retain_vertex_attrib_w) && !uc->opts.ignore_geometry;
+
+ ufbxi_check(ufbxi_load_strings(uc));
+ ufbxi_check(ufbxi_load_maps(uc));
+ ufbxi_check(ufbxi_determine_format(uc));
+
+ ufbx_file_format format = uc->scene.metadata.file_format;
+
+ if (format == UFBX_FILE_FORMAT_FBX) {
+ ufbxi_check(ufbxi_begin_parse(uc));
+ if (uc->version < 6000) {
+ ufbxi_check(ufbxi_read_legacy_root(uc));
+ } else {
+ ufbxi_check(ufbxi_read_root(uc));
+ }
+ if (!ufbxi_supports_version(uc->version)) {
+ ufbxi_check(ufbxi_warnf(UFBX_WARNING_UNSUPPORTED_VERSION, "Unsupported FBX version (%u)", uc->version));
+ }
+ ufbxi_update_scene_metadata(&uc->scene.metadata);
+ ufbxi_check(ufbxi_init_file_paths(uc));
+ } else if (format == UFBX_FILE_FORMAT_OBJ) {
+ ufbxi_check(ufbxi_obj_load(uc));
+ ufbxi_update_scene_metadata(&uc->scene.metadata);
+ } else if (format == UFBX_FILE_FORMAT_MTL) {
+ ufbxi_check(ufbxi_mtl_load(uc));
+ ufbxi_update_scene_metadata(&uc->scene.metadata);
+ }
+
+ // Fake DOM root if necessary
+ if (uc->opts.retain_dom && !uc->scene.dom_root) {
+ ufbx_dom_node *dom_root = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
+ ufbxi_check(dom_root);
+ dom_root->name.data = ufbxi_empty_char;
+ uc->scene.dom_root = dom_root;
+ }
+
+ ufbxi_check(ufbxi_pre_finalize_scene(uc));
+
+ // We can free `tmp_parse` already here as all parsing is done by now.
+ ufbxi_buf_free(&uc->tmp_parse);
+
+ ufbxi_check(ufbxi_finalize_scene(uc));
+
+ ufbxi_update_scene_settings(&uc->scene.settings);
+ if (uc->scene.metadata.file_format == UFBX_FILE_FORMAT_OBJ) {
+ ufbxi_update_scene_settings_obj(uc);
+ }
+
+ // Axis conversion
+ if (ufbx_coordinate_axes_valid(uc->opts.target_axes)) {
+ ufbxi_transform_to_axes(uc, uc->opts.target_axes);
+ }
+
+ // Unit conversion
+ if (uc->opts.target_unit_meters > 0.0f) {
+ ufbxi_check(ufbxi_scale_units(uc, uc->opts.target_unit_meters));
+ }
+
+ // TODO: This could be done in evaluate as well with refactoring
+ ufbxi_update_adjust_transforms(uc, &uc->scene);
+
+ ufbxi_check(ufbxi_modify_geometry(uc));
+ ufbxi_postprocess_scene(uc);
+
+ ufbxi_update_scene(&uc->scene, true, NULL, 0);
+
+ // Force a non-NULL anim pointer
+ if (!uc->scene.anim) {
+ uc->scene.anim = ufbxi_push_zero(&uc->result, ufbx_anim, 1);
+ }
+
+ if (uc->opts.load_external_files) {
+ ufbxi_check(ufbxi_load_external_files(uc));
+ }
+
+ // Evaluate skinning if requested
+ if (uc->opts.evaluate_skinning) {
+ ufbx_geometry_cache_data_opts cache_opts = { 0 };
+ cache_opts.open_file_cb = uc->opts.open_file_cb;
+ ufbxi_check(ufbxi_evaluate_skinning(&uc->scene, &uc->error, &uc->result, &uc->tmp,
+ 0.0, uc->opts.load_external_files && uc->opts.evaluate_caches, &cache_opts));
+ }
+
+ // Pop warnings to metadata
+ ufbxi_check(ufbxi_pop_warnings(&uc->warnings, &uc->scene.metadata.warnings, uc->scene.metadata.has_warning));
+ ufbxi_check(ufbxi_resolve_warning_elements(uc));
+
+ // Copy local data to the scene
+ uc->scene.metadata.version = uc->version;
+ uc->scene.metadata.ascii = uc->from_ascii;
+ uc->scene.metadata.big_endian = uc->file_big_endian;
+ uc->scene.metadata.geometry_ignored = uc->opts.ignore_geometry;
+ uc->scene.metadata.animation_ignored = uc->opts.ignore_animation;
+ uc->scene.metadata.embedded_ignored = uc->opts.ignore_embedded;
+
+ // Retain the scene, this must be the final allocation as we copy
+ // `ator_result` to `ufbx_scene_imp`.
+ ufbxi_scene_imp *imp = ufbxi_push(&uc->result, ufbxi_scene_imp, 1);
+ ufbxi_check(imp);
+
+ ufbxi_init_ref(&imp->refcount, UFBXI_SCENE_IMP_MAGIC, NULL);
+
+ imp->magic = UFBXI_SCENE_IMP_MAGIC;
+ imp->scene = uc->scene;
+ imp->refcount.ator = uc->ator_result;
+ imp->refcount.ator.error = NULL;
+
+ // Copy retained buffers and translate the allocator struct to the one
+ // contained within `ufbxi_scene_imp`
+ imp->refcount.buf = uc->result;
+ imp->refcount.buf.ator = &imp->refcount.ator;
+ imp->string_buf = uc->string_pool.buf;
+ imp->string_buf.ator = &imp->refcount.ator;
+
+ imp->scene.metadata.result_memory_used = imp->refcount.ator.current_size;
+ imp->scene.metadata.temp_memory_used = uc->ator_tmp.current_size;
+ imp->scene.metadata.result_allocs = imp->refcount.ator.num_allocs;
+ imp->scene.metadata.temp_allocs = uc->ator_tmp.num_allocs;
+
+ ufbxi_for_ptr_list(ufbx_element, p_elem, imp->scene.elements) {
+ (*p_elem)->scene = &imp->scene;
+ }
+
+ uc->scene_imp = imp;
+
+ return 1;
+}
+
+static ufbxi_noinline void ufbxi_free_temp(ufbxi_context *uc)
+{
+ ufbxi_thread_pool_free(&uc->thread_pool);
+
+ ufbxi_string_pool_temp_free(&uc->string_pool);
+ ufbxi_buf_free(&uc->warnings.tmp_stack);
+
+ ufbxi_map_free(&uc->prop_type_map);
+ ufbxi_map_free(&uc->fbx_id_map);
+ ufbxi_map_free(&uc->ptr_fbx_id_map);
+ ufbxi_map_free(&uc->texture_file_map);
+ ufbxi_map_free(&uc->anim_stack_map);
+ ufbxi_map_free(&uc->fbx_attr_map);
+ ufbxi_map_free(&uc->node_prop_set);
+ ufbxi_map_free(&uc->dom_node_map);
+
+ ufbxi_buf_free(&uc->tmp);
+ ufbxi_buf_free(&uc->tmp_parse);
+ for (size_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
+ ufbxi_buf_free(&uc->tmp_thread_parse[i]);
+ }
+ ufbxi_buf_free(&uc->tmp_stack);
+ ufbxi_buf_free(&uc->tmp_connections);
+ ufbxi_buf_free(&uc->tmp_node_ids);
+ ufbxi_buf_free(&uc->tmp_elements);
+ ufbxi_buf_free(&uc->tmp_element_offsets);
+ ufbxi_buf_free(&uc->tmp_element_fbx_ids);
+ ufbxi_buf_free(&uc->tmp_element_ptrs);
+ for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
+ ufbxi_buf_free(&uc->tmp_typed_element_offsets[i]);
+ }
+ ufbxi_buf_free(&uc->tmp_mesh_textures);
+ ufbxi_buf_free(&uc->tmp_full_weights);
+ ufbxi_buf_free(&uc->tmp_dom_nodes);
+ ufbxi_buf_free(&uc->tmp_element_id);
+ ufbxi_buf_free(&uc->tmp_ascii_spans);
+
+ ufbxi_free(&uc->ator_tmp, ufbxi_node, uc->top_nodes, uc->top_nodes_cap);
+ ufbxi_free(&uc->ator_tmp, void*, uc->element_extra_arr, uc->element_extra_cap);
+
+ ufbxi_free(&uc->ator_tmp, char, uc->ascii.token.str_data, uc->ascii.token.str_cap);
+ ufbxi_free(&uc->ator_tmp, char, uc->ascii.prev_token.str_data, uc->ascii.prev_token.str_cap);
+
+ ufbxi_free(&uc->ator_tmp, char, uc->read_buffer, uc->read_buffer_size);
+ ufbxi_free(&uc->ator_tmp, char, uc->tmp_arr, uc->tmp_arr_size);
+ ufbxi_free(&uc->ator_tmp, char, uc->swap_arr, uc->swap_arr_size);
+
+ ufbxi_obj_free(uc);
+
+ ufbxi_free_ator(&uc->ator_tmp);
+}
+
+static ufbxi_noinline void ufbxi_free_result(ufbxi_context *uc)
+{
+ ufbxi_buf_free(&uc->result);
+ ufbxi_buf_free(&uc->string_pool.buf);
+
+ ufbxi_free_ator(&uc->ator_result);
+}
+
+static ufbxi_noinline ufbx_scene *ufbxi_load(ufbxi_context *uc, const ufbx_load_opts *user_opts, ufbx_error *p_error)
+{
+ // Test endianness
+ {
+ uint8_t buf[2];
+ uint16_t val = 0xbbaa;
+ memcpy(buf, &val, 2);
+ uc->local_big_endian = buf[0] == 0xbb;
+ }
+
+ uc->double_parse_flags = ufbxi_parse_double_init_flags();
+
+ if (user_opts) {
+ uc->opts = *user_opts;
+ } else {
+ memset(&uc->opts, 0, sizeof(uc->opts));
+ }
+
+ if (uc->opts.file_size_estimate) {
+ uc->progress_bytes_total = uc->opts.file_size_estimate;
+ }
+
+ if (uc->opts.ignore_all_content) {
+ uc->opts.ignore_geometry = true;
+ uc->opts.ignore_animation = true;
+ uc->opts.ignore_embedded = true;
+ }
+
+ ufbx_inflate_retain inflate_retain;
+ inflate_retain.initialized = false;
+
+ ufbxi_init_ator(&uc->error, &uc->ator_tmp, &uc->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&uc->error, &uc->ator_result, &uc->opts.result_allocator, "result");
+
+ if (uc->opts.read_buffer_size == 0) {
+ uc->opts.read_buffer_size = 0x4000;
+ }
+ if (uc->opts.read_buffer_size <= 32) {
+ uc->opts.read_buffer_size = 32;
+ }
+
+ if (uc->opts.file_format_lookahead == 0) {
+ uc->opts.file_format_lookahead = 0x4000;
+ } else if (uc->opts.file_format_lookahead < UFBXI_MIN_FILE_FORMAT_LOOKAHEAD) {
+ uc->opts.file_format_lookahead = UFBXI_MIN_FILE_FORMAT_LOOKAHEAD;
+ }
+
+ if (!uc->opts.path_separator) {
+ uc->opts.path_separator = UFBX_PATH_SEPARATOR;
+ }
+
+ if (!uc->opts.progress_cb.fn || uc->opts.progress_interval_hint >= SIZE_MAX) {
+ uc->progress_interval = SIZE_MAX;
+ } else if (uc->opts.progress_interval_hint > 0) {
+ uc->progress_interval = (size_t)uc->opts.progress_interval_hint;
+ } else {
+ uc->progress_interval = 0x4000;
+ }
+
+ if (!uc->opts.open_file_cb.fn) {
+ uc->opts.open_file_cb.fn = &ufbx_default_open_file;
+ }
+
+ if (!uc->opts.thread_opts.memory_limit) {
+ uc->opts.thread_opts.memory_limit = 32*1024*1024;
+ }
+
+ uc->synthetic_id_counter = UFBXI_SYNTHETIC_ID_START;
+
+ uc->string_pool.error = &uc->error;
+ ufbxi_map_init(&uc->string_pool.map, &uc->ator_tmp, &ufbxi_map_cmp_string, NULL);
+ uc->string_pool.buf.ator = &uc->ator_result;
+ uc->string_pool.buf.unordered = true;
+ uc->string_pool.initial_size = 1024;
+ uc->string_pool.error_handling = uc->opts.unicode_error_handling;
+
+ ufbxi_map_init(&uc->prop_type_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
+ ufbxi_map_init(&uc->fbx_id_map, &uc->ator_tmp, &ufbxi_map_cmp_uint64, NULL);
+ ufbxi_map_init(&uc->ptr_fbx_id_map, &uc->ator_tmp, &ufbxi_map_cmp_ptr_id, NULL);
+ ufbxi_map_init(&uc->texture_file_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
+ ufbxi_map_init(&uc->anim_stack_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
+ ufbxi_map_init(&uc->fbx_attr_map, &uc->ator_tmp, &ufbxi_map_cmp_uint64, NULL);
+ ufbxi_map_init(&uc->node_prop_set, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
+ ufbxi_map_init(&uc->dom_node_map, &uc->ator_tmp, &ufbxi_map_cmp_uintptr, NULL);
+
+ uc->tmp.ator = &uc->ator_tmp;
+ uc->tmp_parse.ator = &uc->ator_tmp;
+ uc->tmp_stack.ator = &uc->ator_tmp;
+ uc->tmp_connections.ator = &uc->ator_tmp;
+ uc->tmp_node_ids.ator = &uc->ator_tmp;
+ uc->tmp_elements.ator = &uc->ator_tmp;
+ uc->tmp_element_offsets.ator = &uc->ator_tmp;
+ uc->tmp_element_fbx_ids.ator = &uc->ator_tmp;
+ uc->tmp_element_ptrs.ator = &uc->ator_tmp;
+ for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
+ uc->tmp_typed_element_offsets[i].ator = &uc->ator_tmp;
+ }
+ uc->tmp_mesh_textures.ator = &uc->ator_tmp;
+ uc->tmp_full_weights.ator = &uc->ator_tmp;
+ uc->tmp_dom_nodes.ator = &uc->ator_tmp;
+ uc->tmp_element_id.ator = &uc->ator_tmp;
+ uc->tmp_ascii_spans.ator = &uc->ator_tmp;
+
+ for (size_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
+ uc->tmp_thread_parse[i].ator = &uc->ator_tmp;
+ uc->tmp_thread_parse[i].unordered = true;
+ uc->tmp_thread_parse[i].clearable = true;
+ }
+
+ uc->result.ator = &uc->ator_result;
+
+ uc->tmp.unordered = true;
+ uc->tmp_parse.unordered = true;
+ uc->tmp_parse.clearable = true;
+ uc->result.unordered = true;
+
+ uc->warnings.error = &uc->error;
+ uc->warnings.result = &uc->result;
+ uc->warnings.tmp_stack.ator = &uc->ator_tmp;
+ uc->string_pool.warnings = &uc->warnings;
+
+ // Set zero size `swap_arr` to a non-NULL buffer so we can tell the difference between empty
+ // array and an allocation failure.
+ uc->swap_arr = (char*)ufbxi_zero_size_buffer;
+
+ // NOTE: Though `inflate_retain` leaks out of the scope we don't use it outside this function.
+ // cppcheck-suppress autoVariables
+ uc->inflate_retain = &inflate_retain;
+
+ int ok = ufbxi_load_imp(uc);
+
+ if (uc->close_fn) {
+ uc->close_fn(uc->read_user);
+ }
+
+ ufbxi_free_temp(uc);
+
+ if (ok) {
+ if (p_error) {
+ ufbxi_clear_error(p_error);
+ }
+ return &uc->scene_imp->scene;
+ } else {
+ ufbxi_fix_error_type(&uc->error, "Failed to load", p_error);
+ if (p_error && p_error->type == UFBX_ERROR_UNKNOWN && uc->scene.metadata.file_format == UFBX_FILE_FORMAT_FBX && !ufbxi_supports_version(uc->version)) {
+ p_error->description.data = "Unsupported version";
+ p_error->description.length = strlen("Unsupported version");
+ p_error->type = UFBX_ERROR_UNSUPPORTED_VERSION;
+ ufbxi_fmt_err_info(p_error, "%u", uc->version);
+ }
+ ufbxi_free_result(uc);
+ return NULL;
+ }
+}
+
+// -- Animation evaluation
+
+static ufbxi_forceinline bool ufbxi_override_less_than_prop(const ufbx_prop_override *over, uint32_t element_id, const ufbx_prop *prop)
+{
+ if (over->element_id != element_id) return over->element_id < element_id;
+ if (over->_internal_key != prop->_internal_key) return over->_internal_key < prop->_internal_key;
+ return strcmp(over->prop_name.data, prop->name.data);
+}
+
+static ufbxi_forceinline bool ufbxi_override_equals_to_prop(const ufbx_prop_override *over, uint32_t element_id, const ufbx_prop *prop)
+{
+ if (over->element_id != element_id) return false;
+ if (over->_internal_key != prop->_internal_key) return false;
+ return !strcmp(over->prop_name.data, prop->name.data);
+}
+
+static ufbxi_noinline bool ufbxi_find_prop_override(const ufbx_prop_override_list *overrides, uint32_t element_id, ufbx_prop *prop)
+{
+ size_t ix = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_prop_override, 16, &ix, overrides->data, 0, overrides->count,
+ ( ufbxi_override_less_than_prop(a, element_id, prop) ),
+ ( ufbxi_override_equals_to_prop(a, element_id, prop) ));
+
+ if (ix != SIZE_MAX) {
+ const ufbx_prop_override *over = &overrides->data[ix];
+ const uint32_t clear_flags = UFBX_PROP_FLAG_NO_VALUE | UFBX_PROP_FLAG_NOT_FOUND;
+ prop->flags = (ufbx_prop_flags)(((uint32_t)prop->flags & ~clear_flags) | UFBX_PROP_FLAG_OVERRIDDEN);
+ prop->value_vec4 = over->value;
+ prop->value_real_arr[3] = 0.0f;
+ prop->value_int = over->value_int;
+ prop->value_str = over->value_str;
+ prop->value_blob.data = prop->value_str.data;
+ prop->value_blob.size = prop->value_str.length;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static ufbxi_noinline ufbx_prop_override_list ufbxi_find_element_prop_overrides(const ufbx_prop_override_list *overrides, uint32_t element_id)
+{
+ size_t begin = overrides->count, end = begin;
+
+ ufbxi_macro_lower_bound_eq(ufbx_prop_override, 32, &begin, overrides->data, 0, overrides->count,
+ (a->element_id < element_id),
+ (a->element_id == element_id));
+
+ ufbxi_macro_upper_bound_eq(ufbx_prop_override, 32, &end, overrides->data, begin, overrides->count,
+ (a->element_id == element_id));
+
+ ufbx_prop_override_list result = { overrides->data + begin, end - begin };
+ return result;
+}
+
+typedef struct ufbxi_anim_layer_combine_ctx {
+ const ufbx_anim *anim;
+ const ufbx_element *element;
+ double time;
+ ufbx_rotation_order rotation_order;
+ bool has_rotation_order;
+} ufbxi_anim_layer_combine_ctx;
+
+static ufbxi_noinline double ufbxi_pow_abs(double v, double e)
+{
+ if (e <= 0.0) return 1.0;
+ if (e >= 1.0) return v;
+ double sign = v < 0.0 ? -1.0 : 1.0;
+ return sign * ufbx_pow(v * sign, e);
+}
+
+// Recursion is limited by the fact that we recurse only when the property name is "Lcl Rotation"
+// and when recursing we always evaluate the property "RotationOrder"
+static ufbxi_noinline void ufbxi_combine_anim_layer(ufbxi_anim_layer_combine_ctx *ctx, ufbx_anim_layer *layer, ufbx_real weight, const char *prop_name, ufbx_vec3 *result, const ufbx_vec3 *value)
+ ufbxi_recursive_function_void(ufbxi_combine_anim_layer, (ctx, layer, weight, prop_name, result, value), 2,
+ (ufbxi_anim_layer_combine_ctx *ctx, ufbx_anim_layer *layer, ufbx_real weight, const char *prop_name, ufbx_vec3 *result, const ufbx_vec3 *value))
+{
+ if (layer->compose_rotation && layer->blended && prop_name == ufbxi_Lcl_Rotation && !ctx->has_rotation_order) {
+ ufbx_prop rp = ufbx_evaluate_prop_len(ctx->anim, ctx->element, ufbxi_RotationOrder, sizeof(ufbxi_RotationOrder) - 1, ctx->time);
+ // NOTE: Defaults to 0 (UFBX_ROTATION_XYZ) gracefully if property is not found
+ if (rp.value_int >= 0 && rp.value_int <= UFBX_ROTATION_ORDER_SPHERIC) {
+ ctx->rotation_order = (ufbx_rotation_order)rp.value_int;
+ } else {
+ ctx->rotation_order = UFBX_ROTATION_ORDER_XYZ;
+ }
+ ctx->has_rotation_order = true;
+ }
+
+ if (layer->additive) {
+ if (layer->compose_scale && prop_name == ufbxi_Lcl_Scaling) {
+ result->x *= (ufbx_real)ufbxi_pow_abs(value->x, weight);
+ result->y *= (ufbx_real)ufbxi_pow_abs(value->y, weight);
+ result->z *= (ufbx_real)ufbxi_pow_abs(value->z, weight);
+ } else if (layer->compose_rotation && prop_name == ufbxi_Lcl_Rotation) {
+ ufbx_quat a = ufbx_euler_to_quat(*result, ctx->rotation_order);
+ ufbx_quat b = ufbx_euler_to_quat(*value, ctx->rotation_order);
+ b = ufbx_quat_slerp(ufbx_identity_quat, b, weight);
+ ufbx_quat res = ufbxi_mul_quat(a, b);
+ *result = ufbx_quat_to_euler(res, ctx->rotation_order);
+ } else {
+ result->x += value->x * weight;
+ result->y += value->y * weight;
+ result->z += value->z * weight;
+ }
+ } else if (layer->blended) {
+ ufbx_real res_weight = 1.0f - weight;
+ if (layer->compose_scale && prop_name == ufbxi_Lcl_Scaling) {
+ result->x = (ufbx_real)(ufbxi_pow_abs(result->x, res_weight) * ufbxi_pow_abs(value->x, weight));
+ result->y = (ufbx_real)(ufbxi_pow_abs(result->y, res_weight) * ufbxi_pow_abs(value->y, weight));
+ result->z = (ufbx_real)(ufbxi_pow_abs(result->z, res_weight) * ufbxi_pow_abs(value->z, weight));
+ } else if (layer->compose_rotation && prop_name == ufbxi_Lcl_Rotation) {
+ ufbx_quat a = ufbx_euler_to_quat(*result, ctx->rotation_order);
+ ufbx_quat b = ufbx_euler_to_quat(*value, ctx->rotation_order);
+ ufbx_quat res = ufbx_quat_slerp(a, b, weight);
+ *result = ufbx_quat_to_euler(res, ctx->rotation_order);
+ } else {
+ result->x = result->x * res_weight + value->x * weight;
+ result->y = result->y * res_weight + value->y * weight;
+ result->z = result->z * res_weight + value->z * weight;
+ }
+ } else {
+ *result = *value;
+ }
+}
+
+static ufbxi_forceinline bool ufbxi_anim_layer_might_contain_id(const ufbx_anim_layer *layer, uint32_t id)
+{
+ uint32_t id_mask = ufbxi_arraycount(layer->_element_id_bitmask) - 1;
+ bool ok = id - layer->_min_element_id <= (layer->_max_element_id - layer->_min_element_id);
+ ok &= (layer->_element_id_bitmask[(id >> 5) & id_mask] & (1u << (id & 31))) != 0;
+ return ok;
+}
+
+static ufbxi_noinline void ufbxi_evaluate_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *props, size_t num_props, uint32_t flags)
+{
+ ufbxi_anim_layer_combine_ctx combine_ctx = { anim, element, time };
+
+ uint32_t element_id = element->element_id;
+ size_t num_layers = anim->layers.count;
+ for (size_t layer_ix = 0; layer_ix < num_layers; layer_ix++) {
+ ufbx_anim_layer *layer = anim->layers.data[layer_ix];
+ if (!ufbxi_anim_layer_might_contain_id(layer, element_id)) continue;
+
+ // Find the weight for the current layer
+ // TODO: Should this be searched from multiple layers?
+ ufbx_real weight = layer_ix < anim->override_layer_weights.count ? anim->override_layer_weights.data[layer_ix] : layer->weight;
+ if (layer->weight_is_animated && layer->blended) {
+ ufbx_anim_prop *weight_aprop = ufbxi_find_anim_prop_start(layer, &layer->element);
+ if (weight_aprop) {
+ weight = ufbx_evaluate_anim_value_real_flags(weight_aprop->anim_value, time, flags) / (ufbx_real)100.0;
+ if (weight < 0.0f) weight = 0.0f;
+ if (weight > 0.99999f) weight = 1.0f;
+ }
+ }
+
+ ufbx_anim_prop *aprop = ufbxi_find_anim_prop_start(layer, element);
+ if (!aprop) continue;
+
+ for (size_t i = 0; i < num_props; i++) {
+ ufbx_prop *prop = &props[i];
+
+ // Don't evaluate on top of overridden properties
+ if ((prop->flags & UFBX_PROP_FLAG_OVERRIDDEN) != 0) continue;
+
+ // Connections override animation by default
+ if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) continue;
+
+ // Skip until we reach `aprop >= prop`
+ // NOTE: No need to check for end as `anim_props` is terminated with a NULL sentinel.
+ while (aprop->element == element && aprop->_internal_key < prop->_internal_key) aprop++;
+ if (aprop->prop_name.data != prop->name.data) {
+ while (aprop->element == element && strcmp(aprop->prop_name.data, prop->name.data) < 0) aprop++;
+ }
+
+ // TODO: Should we skip the blending for the first layer _per property_
+ // This could be done by having `UFBX_PROP_FLAG_ANIMATION_EVALUATED`
+ // that gets set for the first layer of animation that is applied.
+ if (aprop->prop_name.data == prop->name.data) {
+ ufbx_vec3 v = ufbx_evaluate_anim_value_vec3_flags(aprop->anim_value, time, flags);
+ if (layer_ix == 0) {
+ prop->value_vec3 = v;
+ } else {
+ ufbxi_combine_anim_layer(&combine_ctx, layer, weight, prop->name.data, &prop->value_vec3, &v);
+ }
+ }
+ }
+ }
+
+ ufbxi_for(ufbx_prop, prop, props, num_props) {
+ if (prop->flags & UFBX_PROP_FLAG_OVERRIDDEN) continue;
+ prop->value_int = ufbxi_f64_to_i64(prop->value_real);
+ }
+}
+
+// Recursion limited by not calling `ufbx_evaluate_prop_len()` with a connected property,
+// meaning it will never call `ufbxi_evaluate_connected_prop()` again indirectly.
+static ufbxi_noinline void ufbxi_evaluate_connected_prop(ufbx_prop *prop, const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags)
+ ufbxi_recursive_function_void(ufbxi_evaluate_connected_prop, (prop, anim, element, name, time, flags), 3,
+ (ufbx_prop *prop, const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags))
+{
+ ufbx_connection *conn = ufbxi_find_prop_connection(element, name);
+
+ for (size_t i = 0; i < 1000 && conn; i++) {
+ ufbx_connection *next_conn = ufbxi_find_prop_connection(conn->src, conn->src_prop.data);
+ if (!next_conn) break;
+ conn = next_conn;
+ }
+
+ // Found a non-cyclic connection
+ if (conn && !ufbxi_find_prop_connection(conn->src, conn->src_prop.data)) {
+ ufbx_prop ep = ufbx_evaluate_prop_flags_len(anim, conn->src, conn->src_prop.data, conn->src_prop.length, time, flags);
+ prop->value_vec4 = ep.value_vec4;
+ prop->value_int = ep.value_int;
+ prop->value_str = ep.value_str;
+ prop->value_blob = ep.value_blob;
+ } else {
+ // Connection not found, maybe it's animated?
+ prop->flags = (ufbx_prop_flags)((uint32_t)prop->flags & ~(uint32_t)UFBX_PROP_FLAG_CONNECTED);
+ }
+}
+
+typedef struct {
+ const ufbx_prop *prop, *prop_end;
+ const ufbx_prop_override *over, *over_end;
+ ufbx_prop tmp;
+} ufbxi_prop_iter;
+
+static ufbxi_noinline void ufbxi_init_prop_iter_slow(ufbxi_prop_iter *iter, const ufbx_anim *anim, const ufbx_element *element)
+{
+ iter->prop = element->props.props.data;
+ iter->prop_end = element->props.props.data + element->props.props.count;
+
+ ufbx_prop_override_list over = ufbxi_find_element_prop_overrides(&anim->prop_overrides, element->element_id);
+ iter->over = over.data;
+ iter->over_end = over.data + over.count;
+ if (over.count > 0) {
+ memset(&iter->tmp, 0, sizeof(ufbx_prop));
+ }
+}
+
+static ufbxi_forceinline void ufbxi_init_prop_iter(ufbxi_prop_iter *iter, const ufbx_anim *anim, const ufbx_element *element)
+{
+ iter->prop = element->props.props.data;
+ iter->prop_end = ufbxi_add_ptr(element->props.props.data, element->props.props.count);
+ iter->over = iter->over_end = NULL;
+ if (anim->prop_overrides.count > 0) {
+ ufbxi_init_prop_iter_slow(iter, anim, element);
+ }
+}
+
+static ufbxi_noinline const ufbx_prop *ufbxi_next_prop_slow(ufbxi_prop_iter *iter)
+{
+ const ufbx_prop *prop = iter->prop;
+ const ufbx_prop_override *over = iter->over;
+ if (prop == iter->prop_end && over == iter->over_end) return NULL;
+
+ // We can use `UINT32_MAX` as a terminating key (aka prefix) as prop names must
+ // be valid UTF-8 and the byte sequence "\xff\xff\xff\xff" is not valid.
+ uint32_t prop_key = prop != iter->prop_end ? prop->_internal_key : UINT32_MAX;
+ uint32_t over_key = over != iter->over_end ? over->_internal_key : UINT32_MAX;
+
+ int cmp = 0;
+ if (prop_key != over_key) {
+ cmp = prop_key < over_key ? -1 : 1;
+ } else {
+ cmp = strcmp(prop->name.data, over->prop_name.data);
+ }
+
+ if (cmp >= 0) {
+ ufbx_prop *dst = &iter->tmp;
+ dst->name = over->prop_name;
+ dst->_internal_key = over->_internal_key;
+ dst->type = UFBX_PROP_UNKNOWN;
+ dst->flags = UFBX_PROP_FLAG_OVERRIDDEN;
+ dst->value_str = over->value_str;
+ dst->value_blob.data = dst->value_str.data;
+ dst->value_blob.size = dst->value_str.length;
+ dst->value_int = over->value_int;
+ dst->value_vec4 = over->value;
+ iter->over = over + 1;
+ if (cmp == 0) {
+ iter->prop = prop + 1;
+ }
+ return dst;
+ } else {
+ iter->prop = prop + 1;
+ return prop;
+ }
+}
+
+static ufbxi_forceinline const ufbx_prop *ufbxi_next_prop(ufbxi_prop_iter *iter)
+{
+ if (iter->over == iter->over_end) {
+ if (iter->prop == iter->prop_end) return NULL;
+ return iter->prop++;
+ } else {
+ return ufbxi_next_prop_slow(iter);
+ }
+}
+
+static ufbxi_noinline ufbx_props ufbxi_evaluate_selected_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *props, const char *const *prop_names, size_t max_props, uint32_t flags)
+{
+ const char *name = prop_names[0];
+ uint32_t key = ufbxi_get_name_key_c(name);
+ size_t num_props = 0;
+
+#if defined(UFBX_REGRESSION)
+ for (size_t i = 1; i < max_props; i++) {
+ ufbx_assert(strcmp(prop_names[i - 1], prop_names[i]) < 0);
+ }
+#endif
+
+ size_t name_ix = 0;
+
+ ufbxi_prop_iter iter; // ufbxi_uninit
+ ufbxi_init_prop_iter(&iter, anim, element);
+ const ufbx_prop *prop = NULL;
+ while ((prop = ufbxi_next_prop(&iter)) != NULL) {
+ while (name_ix < max_props) {
+ if (key > prop->_internal_key) break;
+ if (name == prop->name.data) {
+ if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
+ ufbx_prop *dst = &props[num_props++];
+ *dst = *prop;
+ ufbxi_evaluate_connected_prop(dst, anim, element, name, time, flags);
+ } else if ((prop->flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_OVERRIDDEN)) != 0) {
+ props[num_props++] = *prop;
+ }
+ break;
+ } else if (strcmp(name, prop->name.data) < 0) {
+ name_ix++;
+ if (name_ix < max_props) {
+ name = prop_names[name_ix];
+ key = ufbxi_get_name_key_c(name);
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ ufbxi_evaluate_props(anim, element, time, props, num_props, flags);
+
+ ufbx_props prop_list;
+ prop_list.props.data = props;
+ prop_list.props.count = prop_list.num_animated = num_props;
+ prop_list.defaults = (ufbx_props*)&element->props;
+ return prop_list;
+}
+
+// Recursion limited by not calling `ufbx_evaluate_curve()` with `UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION`.
+static ufbxi_noinline ufbx_real ufbxi_extrapolate_curve(const ufbx_anim_curve *curve, double real_time, uint32_t flags)
+ ufbxi_recursive_function(ufbx_real, ufbxi_extrapolate_curve, (curve, real_time, flags), 3,
+ (const ufbx_anim_curve *curve, double real_time, uint32_t flags))
+{
+ bool pre = real_time < curve->min_time;
+ const ufbx_keyframe *key;
+ ufbx_extrapolation ext;
+ if (pre) {
+ key = &curve->keyframes.data[0];
+ ext = curve->pre_extrapolation;
+ } else {
+ key = &curve->keyframes.data[curve->keyframes.count - 1];
+ ext = curve->post_extrapolation;
+ }
+
+ if (ext.mode == UFBX_EXTRAPOLATION_CONSTANT) {
+ return key->value;
+ } else if (ext.mode == UFBX_EXTRAPOLATION_SLOPE) {
+ ufbx_tangent tangent = *(pre ? &key->right : &key->left);
+ return key->value + (ufbx_real)(tangent.dy * ((real_time - key->time) / tangent.dx));
+ } else if (ext.repeat_count == 0) {
+ return key->value;
+ }
+
+ // Perform all operations in KTime ticks to be frame perfect
+ double scale = (double)curve->element.scene->metadata.ktime_second;
+ double min_time = ufbx_rint(curve->min_time * scale);
+ double max_time = ufbx_rint(curve->max_time * scale);
+ double time = real_time * scale;
+
+ double delta = pre ? min_time - time : time - max_time;
+ double duration = max_time - min_time;
+
+ // Require at least one KTime unit
+ if (!(duration >= 1.0)) return key->value;
+
+ double rep = delta / duration;
+ double rep_n = ufbx_floor(rep);
+ double rep_d = delta - rep_n * duration;
+
+ if (ext.repeat_count > 0 && rep_n >= (double)ext.repeat_count) {
+ // Clamp to the repeat count to handle mirroring
+ rep_n = (double)(ext.repeat_count - 1);
+ rep_d = duration;
+ }
+
+ if (ext.mode == UFBX_EXTRAPOLATION_MIRROR) {
+ double rep_parity = rep_n*0.5 - ufbx_floor(rep_n*0.5);
+ if (rep_parity <= 0.25) {
+ rep_d = duration - rep_d;
+ }
+ }
+
+ if (pre) rep_d = duration - rep_d;
+ double new_time = (min_time + rep_d) / scale;
+
+ ufbx_real value = ufbx_evaluate_curve_flags(curve, new_time, key->value, flags | UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION);
+
+ if (ext.mode == UFBX_EXTRAPOLATION_REPEAT_RELATIVE) {
+ ufbx_real val_delta = curve->keyframes.data[curve->keyframes.count - 1].value - curve->keyframes.data[0].value;
+ if (pre) val_delta = -val_delta;
+ value += val_delta * (ufbx_real)(rep_n + 1.0);
+ }
+
+ return value;
+}
+
+#if UFBXI_FEATURE_SCENE_EVALUATION
+
+typedef struct {
+ char *src_element;
+ char *dst_element;
+
+ ufbxi_scene_imp *src_imp;
+ ufbx_scene src_scene;
+ ufbx_evaluate_opts opts;
+ ufbx_anim *anim;
+ double time;
+
+ ufbx_error error;
+
+ // Allocators
+ ufbxi_allocator ator_result;
+ ufbxi_allocator ator_tmp;
+
+ ufbxi_buf result;
+ ufbxi_buf tmp;
+
+ ufbx_scene scene;
+
+ ufbxi_scene_imp *scene_imp;
+} ufbxi_eval_context;
+
+static ufbxi_forceinline ufbx_element *ufbxi_translate_element(ufbxi_eval_context *ec, void *elem)
+{
+ return elem ? (ufbx_element*)(ec->dst_element + ((char*)elem - ec->src_element)) : NULL;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_translate_element_list(ufbxi_eval_context *ec, void *p_list)
+{
+ ufbx_element_list *list = (ufbx_element_list*)p_list;
+ size_t count = list->count;
+ ufbx_element **src = list->data;
+ ufbx_element **dst = ufbxi_push(&ec->result, ufbx_element*, count);
+ ufbxi_check_err(&ec->error, dst);
+ list->data = dst;
+ for (size_t i = 0; i < count; i++) {
+ dst[i] = ufbxi_translate_element(ec, src[i]);
+ }
+ return 1;
+}
+
+static ufbxi_noinline void ufbxi_translate_maps(ufbxi_eval_context *ec, ufbx_material_map *maps, size_t count)
+{
+ ufbxi_nounroll ufbxi_for(ufbx_material_map, map, maps, count) {
+ map->texture = (ufbx_texture*)ufbxi_translate_element(ec, map->texture);
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_translate_anim(ufbxi_eval_context *ec, ufbx_anim **p_anim)
+{
+ ufbx_anim *anim = ufbxi_push_copy(&ec->result, ufbx_anim, 1, *p_anim);
+ ufbxi_check_err(&ec->error, anim);
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &anim->layers));
+ *p_anim = anim;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_evaluate_imp(ufbxi_eval_context *ec)
+{
+ ec->scene = ec->src_scene;
+ size_t num_elements = ec->scene.elements.count;
+
+ char *element_data = (char*)ufbxi_push(&ec->result, uint64_t, ec->scene.metadata.element_buffer_size/8);
+ ufbxi_check_err(&ec->error, element_data);
+
+ ec->scene.elements.data = ufbxi_push(&ec->result, ufbx_element*, num_elements);
+ ufbxi_check_err(&ec->error, ec->scene.elements.data);
+
+ ec->src_element = (char*)ec->src_scene.elements.data[0];
+ ec->dst_element = element_data;
+
+ for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
+ ec->scene.elements_by_type[i].data = ufbxi_push(&ec->result, ufbx_element*, ec->scene.elements_by_type[i].count);
+ ufbxi_check_err(&ec->error, ec->scene.elements_by_type[i].data);
+ }
+
+ size_t num_connections = ec->scene.connections_dst.count;
+ ec->scene.connections_src.data = ufbxi_push(&ec->result, ufbx_connection, num_connections);
+ ec->scene.connections_dst.data = ufbxi_push(&ec->result, ufbx_connection, num_connections);
+ ufbxi_check_err(&ec->error, ec->scene.connections_src.data);
+ ufbxi_check_err(&ec->error, ec->scene.connections_dst.data);
+ for (size_t i = 0; i < num_connections; i++) {
+ ufbx_connection *src = &ec->scene.connections_src.data[i];
+ ufbx_connection *dst = &ec->scene.connections_dst.data[i];
+ *src = ec->src_scene.connections_src.data[i];
+ *dst = ec->src_scene.connections_dst.data[i];
+ src->src = ufbxi_translate_element(ec, src->src);
+ src->dst = ufbxi_translate_element(ec, src->dst);
+ dst->src = ufbxi_translate_element(ec, dst->src);
+ dst->dst = ufbxi_translate_element(ec, dst->dst);
+ }
+
+ ec->scene.elements_by_name.data = ufbxi_push(&ec->result, ufbx_name_element, num_elements);
+ ufbxi_check_err(&ec->error, ec->scene.elements_by_name.data);
+
+ ec->scene.root_node = (ufbx_node*)ufbxi_translate_element(ec, ec->scene.root_node);
+ ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &ec->scene.anim));
+
+ for (size_t i = 0; i < num_elements; i++) {
+ ufbx_element *src = ec->src_scene.elements.data[i];
+ ufbx_element *dst = ufbxi_translate_element(ec, src);
+ size_t size = ufbx_element_type_size[src->type];
+ ufbx_assert(size > 0);
+ memcpy(dst, src, size);
+
+ ec->scene.elements.data[i] = dst;
+ ec->scene.elements_by_type[src->type].data[src->typed_id] = dst;
+
+ dst->connections_src.data = ec->scene.connections_src.data + (dst->connections_src.data - ec->src_scene.connections_src.data);
+ dst->connections_dst.data = ec->scene.connections_dst.data + (dst->connections_dst.data - ec->src_scene.connections_dst.data);
+ if (dst->instances.count > 0) {
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &dst->instances));
+ }
+
+ ufbx_name_element named = ec->src_scene.elements_by_name.data[i];
+ named.element = ufbxi_translate_element(ec, named.element);
+ ec->scene.elements_by_name.data[i] = named;
+ }
+
+ ufbxi_for_ptr_list(ufbx_node, p_node, ec->scene.nodes) {
+ ufbx_node *node = *p_node;
+ node->parent = (ufbx_node*)ufbxi_translate_element(ec, node->parent);
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->children));
+
+ node->attrib = ufbxi_translate_element(ec, node->attrib);
+ node->mesh = (ufbx_mesh*)ufbxi_translate_element(ec, node->mesh);
+ node->light = (ufbx_light*)ufbxi_translate_element(ec, node->light);
+ node->camera = (ufbx_camera*)ufbxi_translate_element(ec, node->camera);
+ node->bone = (ufbx_bone*)ufbxi_translate_element(ec, node->bone);
+ node->inherit_scale_node = (ufbx_node*)ufbxi_translate_element(ec, node->inherit_scale_node);
+ node->scale_helper = (ufbx_node*)ufbxi_translate_element(ec, node->scale_helper);
+ node->bind_pose = (ufbx_pose*)ufbxi_translate_element(ec, node->bind_pose);
+
+ if (node->all_attribs.count > 1) {
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->all_attribs));
+ } else if (node->all_attribs.count == 1) {
+ node->all_attribs.data = &node->attrib;
+ }
+
+ node->geometry_transform_helper = (ufbx_node*)ufbxi_translate_element(ec, node->geometry_transform_helper);
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->materials));
+ }
+
+ ufbxi_for_ptr_list(ufbx_mesh, p_mesh, ec->scene.meshes) {
+ ufbx_mesh *mesh = *p_mesh;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->materials));
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->skin_deformers));
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->blend_deformers));
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->cache_deformers));
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->all_deformers));
+ }
+
+ ufbxi_for_ptr_list(ufbx_stereo_camera, p_stereo, ec->scene.stereo_cameras) {
+ ufbx_stereo_camera *stereo = *p_stereo;
+ stereo->left = (ufbx_camera*)ufbxi_translate_element(ec, stereo->left);
+ stereo->right = (ufbx_camera*)ufbxi_translate_element(ec, stereo->right);
+ }
+
+ ufbxi_for_ptr_list(ufbx_skin_deformer, p_skin, ec->scene.skin_deformers) {
+ ufbx_skin_deformer *skin = *p_skin;
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &skin->clusters));
+ }
+
+ ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, ec->scene.skin_clusters) {
+ ufbx_skin_cluster *cluster = *p_cluster;
+ cluster->bone_node = (ufbx_node*)ufbxi_translate_element(ec, cluster->bone_node);
+ }
+
+ ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, ec->scene.blend_deformers) {
+ ufbx_blend_deformer *blend = *p_blend;
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &blend->channels));
+ }
+
+ ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, ec->scene.blend_channels) {
+ ufbx_blend_channel *chan = *p_chan;
+
+ ufbx_blend_keyframe *keys = ufbxi_push(&ec->result, ufbx_blend_keyframe, chan->keyframes.count);
+ ufbxi_check_err(&ec->error, keys);
+ for (size_t i = 0; i < chan->keyframes.count; i++) {
+ keys[i] = chan->keyframes.data[i];
+ keys[i].shape = (ufbx_blend_shape*)ufbxi_translate_element(ec, keys[i].shape);
+ }
+ chan->keyframes.data = keys;
+ chan->target_shape = (ufbx_blend_shape*)ufbxi_translate_element(ec, chan->target_shape);
+ }
+
+ ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, ec->scene.cache_deformers) {
+ ufbx_cache_deformer *deformer = *p_deformer;
+ deformer->file = (ufbx_cache_file*)ufbxi_translate_element(ec, deformer->file);
+ }
+
+ ufbxi_for_ptr_list(ufbx_material, p_material, ec->scene.materials) {
+ ufbx_material *material = *p_material;
+
+ material->shader = (ufbx_shader*)ufbxi_translate_element(ec, material->shader);
+ ufbxi_translate_maps(ec, material->fbx.maps, UFBX_MATERIAL_FBX_MAP_COUNT);
+ ufbxi_translate_maps(ec, material->pbr.maps, UFBX_MATERIAL_PBR_MAP_COUNT);
+
+ ufbx_material_texture *textures = ufbxi_push(&ec->result, ufbx_material_texture, material->textures.count);
+ ufbxi_check_err(&ec->error, textures);
+ for (size_t i = 0; i < material->textures.count; i++) {
+ textures[i] = material->textures.data[i];
+ textures[i].texture = (ufbx_texture*)ufbxi_translate_element(ec, textures[i].texture);
+ }
+ material->textures.data = textures;
+ }
+
+ ufbxi_for_ptr_list(ufbx_texture, p_texture, ec->scene.textures) {
+ ufbx_texture *texture = *p_texture;
+ texture->video = (ufbx_video*)ufbxi_translate_element(ec, texture->video);
+
+ ufbx_texture_layer *layers = ufbxi_push(&ec->result, ufbx_texture_layer, texture->layers.count);
+ ufbxi_check_err(&ec->error, layers);
+ for (size_t i = 0; i < texture->layers.count; i++) {
+ layers[i] = texture->layers.data[i];
+ layers[i].texture = (ufbx_texture*)ufbxi_translate_element(ec, layers[i].texture);
+ }
+ texture->layers.data = layers;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &texture->file_textures));
+
+ if (texture->shader) {
+ ufbx_shader_texture *shader = texture->shader;
+ shader = ufbxi_push_copy(&ec->result, ufbx_shader_texture, 1, shader);
+ ufbxi_check_err(&ec->error, shader);
+ texture->shader = shader;
+
+ ufbx_shader_texture_input *inputs = ufbxi_push_copy(&ec->result, ufbx_shader_texture_input, shader->inputs.count, shader->inputs.data);
+ ufbxi_check_err(&ec->error, inputs);
+ shader->inputs.data = inputs;
+ }
+ }
+
+ ufbxi_for_ptr_list(ufbx_shader, p_shader, ec->scene.shaders) {
+ ufbx_shader *shader = *p_shader;
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &shader->bindings));
+ }
+
+ ufbxi_for_ptr_list(ufbx_display_layer, p_layer, ec->scene.display_layers) {
+ ufbx_display_layer *layer = *p_layer;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->nodes));
+ }
+
+ ufbxi_for_ptr_list(ufbx_selection_set, p_set, ec->scene.selection_sets) {
+ ufbx_selection_set *set = *p_set;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &set->nodes));
+ }
+
+ ufbxi_for_ptr_list(ufbx_selection_node, p_node, ec->scene.selection_nodes) {
+ ufbx_selection_node *node = *p_node;
+
+ node->target_node = (ufbx_node*)ufbxi_translate_element(ec, node->target_node);
+ node->target_mesh = (ufbx_mesh*)ufbxi_translate_element(ec, node->target_mesh);
+ }
+
+ ufbxi_for_ptr_list(ufbx_constraint, p_constraint, ec->scene.constraints) {
+ ufbx_constraint *constraint = *p_constraint;
+
+ constraint->node = (ufbx_node*)ufbxi_translate_element(ec, constraint->node);
+ constraint->aim_up_node = (ufbx_node*)ufbxi_translate_element(ec, constraint->aim_up_node);
+ constraint->ik_effector = (ufbx_node*)ufbxi_translate_element(ec, constraint->ik_effector);
+ constraint->ik_end_node = (ufbx_node*)ufbxi_translate_element(ec, constraint->ik_end_node);
+
+ ufbx_constraint_target *targets = ufbxi_push(&ec->result, ufbx_constraint_target, constraint->targets.count);
+ ufbxi_check_err(&ec->error, targets);
+ for (size_t i = 0; i < constraint->targets.count; i++) {
+ targets[i] = constraint->targets.data[i];
+ targets[i].node = (ufbx_node*)ufbxi_translate_element(ec, targets[i].node);
+ }
+ constraint->targets.data = targets;
+ }
+
+ ufbxi_for_ptr_list(ufbx_audio_layer, p_layer, ec->scene.audio_layers) {
+ ufbx_audio_layer *layer = *p_layer;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->clips));
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, ec->scene.anim_stacks) {
+ ufbx_anim_stack *stack = *p_stack;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &stack->layers));
+ ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &stack->anim));
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, ec->scene.anim_layers) {
+ ufbx_anim_layer *layer = *p_layer;
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->anim_values));
+ ufbx_anim_prop *props = ufbxi_push(&ec->result, ufbx_anim_prop, layer->anim_props.count + 1);
+ ufbxi_check_err(&ec->error, props);
+ for (size_t i = 0; i < layer->anim_props.count; i++) {
+ props[i] = layer->anim_props.data[i];
+ props[i].element = ufbxi_translate_element(ec, props[i].element);
+ props[i].anim_value = (ufbx_anim_value*)ufbxi_translate_element(ec, props[i].anim_value);
+ }
+ // Maintain NULL sentinel
+ memset(props + layer->anim_props.count, 0, sizeof(ufbx_anim_prop));
+ layer->anim_props.data = props;
+ }
+
+ ufbxi_for_ptr_list(ufbx_pose, p_pose, ec->scene.poses) {
+ ufbx_pose *pose = *p_pose;
+
+ ufbx_bone_pose *bones = ufbxi_push(&ec->result, ufbx_bone_pose, pose->bone_poses.count);
+ ufbxi_check_err(&ec->error, bones);
+ for (size_t i = 0; i < pose->bone_poses.count; i++) {
+ bones[i] = pose->bone_poses.data[i];
+ bones[i].bone_node = (ufbx_node*)ufbxi_translate_element(ec, bones[i].bone_node);
+ }
+ pose->bone_poses.data = bones;
+ }
+
+ ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &ec->anim));
+
+ ufbxi_for_ptr_list(ufbx_anim_value, p_value, ec->scene.anim_values) {
+ ufbx_anim_value *value = *p_value;
+ value->curves[0] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[0]);
+ value->curves[1] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[1]);
+ value->curves[2] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[2]);
+ }
+
+ ufbx_anim anim = *ec->anim;
+ ufbx_prop_override *over = anim.prop_overrides.data, *over_end = ufbxi_add_ptr(over, anim.prop_overrides.count);
+
+ // Evaluate the properties
+ ufbxi_for_ptr_list(ufbx_element, p_elem, ec->scene.elements) {
+ ufbx_element *elem = *p_elem;
+ size_t num_animated = elem->props.num_animated;
+ size_t num_override = 0;
+
+ // Setup the overrides for this element if found
+ while (over != over_end && over->element_id == elem->element_id) {
+ num_override++;
+ over++;
+ }
+
+ num_animated += num_override;
+ if (num_animated == 0) continue;
+
+ anim.prop_overrides.data = ufbxi_sub_ptr(over, num_override);
+ anim.prop_overrides.count = num_override;
+
+ ufbx_prop *props = ufbxi_push(&ec->result, ufbx_prop, num_animated);
+ ufbxi_check_err(&ec->error, props);
+
+ elem->props = ufbx_evaluate_props_flags(&anim, elem, ec->time, props, num_animated, ec->opts.evaluate_flags);
+ elem->props.defaults = &ec->src_scene.elements.data[elem->element_id]->props;
+ }
+
+ // Update all derived values
+ ufbxi_update_scene(&ec->scene, false, anim.transform_overrides.data, anim.transform_overrides.count);
+
+ // Evaluate skinning if requested
+ if (ec->opts.evaluate_skinning) {
+ ufbx_geometry_cache_data_opts cache_opts = { 0 };
+ cache_opts.open_file_cb = ec->opts.open_file_cb;
+ ufbxi_check_err(&ec->error, ufbxi_evaluate_skinning(&ec->scene, &ec->error, &ec->result, &ec->tmp,
+ ec->time, ec->opts.load_external_files && ec->opts.evaluate_caches, &cache_opts));
+ }
+
+ // Retain the scene, this must be the final allocation as we copy
+ // `ator_result` to `ufbx_scene_imp`.
+ ufbxi_scene_imp *imp = ufbxi_push_zero(&ec->result, ufbxi_scene_imp, 1);
+ ufbxi_check_err(&ec->error, imp);
+
+ ufbx_assert(ec->src_imp->magic == UFBXI_SCENE_IMP_MAGIC);
+ ufbxi_init_ref(&imp->refcount, UFBXI_SCENE_IMP_MAGIC, &ec->src_imp->refcount);
+
+ imp->magic = UFBXI_SCENE_IMP_MAGIC;
+ imp->scene = ec->scene;
+ imp->refcount.ator = ec->ator_result;
+ imp->refcount.ator.error = NULL;
+
+ // Copy retained buffers and translate the allocator struct to the one
+ // contained within `ufbxi_scene_imp`
+ imp->refcount.buf = ec->result;
+ imp->refcount.buf.ator = &imp->refcount.ator;
+
+ imp->scene.metadata.result_memory_used = imp->refcount.ator.current_size;
+ imp->scene.metadata.temp_memory_used = ec->ator_tmp.current_size;
+ imp->scene.metadata.result_allocs = imp->refcount.ator.num_allocs;
+ imp->scene.metadata.temp_allocs = ec->ator_tmp.num_allocs;
+
+ ufbxi_for_ptr_list(ufbx_element, p_elem, imp->scene.elements) {
+ (*p_elem)->scene = &imp->scene;
+ }
+
+ ec->scene_imp = imp;
+ ec->result.ator = &ec->ator_result;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline ufbx_scene *ufbxi_evaluate_scene(ufbxi_eval_context *ec, ufbx_scene *scene, const ufbx_anim *anim, double time, const ufbx_evaluate_opts *user_opts, ufbx_error *p_error)
+{
+ if (user_opts) {
+ ec->opts = *user_opts;
+ } else {
+ memset(&ec->opts, 0, sizeof(ec->opts));
+ }
+
+ ec->src_imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
+ ec->src_scene = *scene;
+ ec->anim = anim ? (ufbx_anim*)anim : scene->anim;
+ ec->time = time;
+
+ ufbxi_init_ator(&ec->error, &ec->ator_tmp, &ec->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&ec->error, &ec->ator_result, &ec->opts.result_allocator, "result");
+
+ ec->result.ator = &ec->ator_result;
+ ec->tmp.ator = &ec->ator_tmp;
+
+ ec->result.unordered = true;
+ ec->tmp.unordered = true;
+
+ if (ufbxi_evaluate_imp(ec)) {
+ ufbxi_buf_free(&ec->tmp);
+ ufbxi_free_ator(&ec->ator_tmp);
+ if (p_error) {
+ ufbxi_clear_error(p_error);
+ }
+ return &ec->scene_imp->scene;
+ } else {
+ ufbxi_fix_error_type(&ec->error, "Failed to evaluate", p_error);
+ ufbxi_buf_free(&ec->tmp);
+ ufbxi_buf_free(&ec->result);
+ ufbxi_free_ator(&ec->ator_tmp);
+ ufbxi_free_ator(&ec->ator_result);
+ return NULL;
+ }
+}
+
+#endif
+
+typedef struct {
+ ufbx_error error;
+ ufbxi_allocator ator_result;
+ ufbxi_buf result;
+ const ufbx_scene *scene;
+ ufbx_anim_opts opts;
+
+ ufbx_anim anim;
+ ufbxi_anim_imp *imp;
+} ufbxi_create_anim_context;
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_check_string(ufbx_error *error, ufbx_string *dst, const ufbx_string *src)
+{
+ size_t length = src->length != SIZE_MAX ? src->length : strlen(src->data);
+ const char *data = length != 0 ? src->data : ufbxi_empty_char;
+ if (length > 0) {
+ size_t valid_length = ufbxi_utf8_valid_length(data, length);
+ ufbxi_check_err_msg(error, valid_length == length, "Invalid UTF-8");
+ }
+
+ dst->data = data;
+ dst->length = length;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_anim_string(ufbxi_create_anim_context *ac, ufbx_string *str)
+{
+ size_t length = str->length;
+ if (length > 0) {
+ char *copy = ufbxi_push(&ac->result, char, length + 1);
+ ufbxi_check_err(&ac->error, copy);
+ memcpy(copy, str->data, length);
+ copy[str->length] = '\0';
+ str->data = copy;
+ } else {
+ ufbx_assert(str->data == ufbxi_empty_char);
+ }
+
+ return 1;
+}
+
+static bool ufbxi_prop_override_prop_name_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_prop_override *a = (const ufbx_prop_override*)va, *b = (const ufbx_prop_override*)vb;
+ if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
+ return ufbxi_str_less(a->prop_name, b->prop_name);
+}
+
+static bool ufbxi_prop_override_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_prop_override *a = (const ufbx_prop_override*)va, *b = (const ufbx_prop_override*)vb;
+ if (a->element_id != b->element_id) return a->element_id < b->element_id;
+ if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
+ return strcmp(a->prop_name.data, b->prop_name.data) < 0;
+}
+
+static bool ufbxi_transform_override_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_transform_override *a = (const ufbx_transform_override*)va, *b = (const ufbx_transform_override*)vb;
+ return a->node_id < b->node_id;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_create_anim_imp(ufbxi_create_anim_context *ac)
+{
+ const ufbx_scene *scene = ac->scene;
+ ufbx_anim *anim = &ac->anim;
+
+ ufbxi_init_ator(&ac->error, &ac->ator_result, &ac->opts.result_allocator, "result");
+ ac->result.unordered = true;
+ ac->result.ator = &ac->ator_result;
+
+ anim->ignore_connections = ac->opts.ignore_connections;
+ anim->custom = true;
+
+ size_t num_layers = ac->opts.layer_ids.count;
+ anim->layers.count = num_layers;
+ anim->layers.data = ufbxi_push_zero(&ac->result, ufbx_anim_layer*, num_layers);
+ ufbxi_check_err(&ac->error, anim->layers.data);
+
+ if (ac->opts.override_layer_weights.count > 0) {
+ ufbxi_check_err_msg(&ac->error, ac->opts.override_layer_weights.count == num_layers, "override_layer_weights[] count must match layer_ids[] count");
+ anim->override_layer_weights.data = ufbxi_push_copy(&ac->result, ufbx_real, num_layers, ac->opts.override_layer_weights.data);
+ ufbxi_check_err(&ac->error, anim->override_layer_weights.data);
+ anim->override_layer_weights.count = num_layers;
+ }
+
+ for (size_t i = 0; i < num_layers; i++) {
+ uint32_t index = ac->opts.layer_ids.data[i];
+ ufbxi_check_err_msg(&ac->error, index < scene->anim_layers.count, "layer_ids out of bounds");
+ anim->layers.data[i] = ac->scene->anim_layers.data[index];
+ }
+
+ ufbx_const_prop_override_desc_list prop_overrides = ac->opts.prop_overrides;
+ if (prop_overrides.count > 0) {
+ anim->prop_overrides.count = prop_overrides.count;
+ anim->prop_overrides.data = ufbxi_push_zero(&ac->result, ufbx_prop_override, prop_overrides.count);
+ ufbxi_check_err(&ac->error, anim->prop_overrides.data);
+
+ for (size_t i = 0; i < prop_overrides.count; i++) {
+ const ufbx_prop_override_desc *src = &prop_overrides.data[i];
+ ufbx_prop_override *dst = &anim->prop_overrides.data[i];
+
+ dst->element_id = src->element_id;
+ dst->value = src->value;
+ dst->value_int = src->value_int;
+
+ if (dst->value.x != 0.0f && dst->value_int == 0) {
+ dst->value_int = (int64_t)dst->value.x;
+ } else if (dst->value_int != 0 && dst->value.x == 0.0f) {
+ dst->value.x = (ufbx_real)dst->value_int;
+ }
+
+ ufbxi_check_err(&ac->error, ufbxi_check_string(&ac->error, &dst->prop_name, &src->prop_name));
+ ufbxi_check_err(&ac->error, ufbxi_check_string(&ac->error, &dst->value_str, &src->value_str));
+
+ dst->_internal_key = ufbxi_get_name_key(dst->prop_name.data, dst->prop_name.length);
+ }
+
+ // Sort `anim->prop_overrides` first by `prop_name` only so we can deduplicate and
+ // convert them to global strings in `ufbxi_strings[]` if possible.
+ ufbxi_unstable_sort(anim->prop_overrides.data, anim->prop_overrides.count, sizeof(ufbx_prop_override), &ufbxi_prop_override_prop_name_less, NULL);
+
+ const ufbx_string *global_str = ufbxi_strings, *global_end = global_str + ufbxi_arraycount(ufbxi_strings);
+ ufbx_string prev_name = { ufbxi_empty_char };
+ ufbxi_for_list(ufbx_prop_override, over, anim->prop_overrides) {
+ if (over->value_str.length > 0) {
+ ufbxi_check_err(&ac->error, ufbxi_push_anim_string(ac, &over->value_str));
+ }
+
+ if (ufbxi_str_equal(over->prop_name, prev_name)) {
+ over->prop_name = prev_name;
+ continue;
+ }
+
+ while (global_str != global_end && ufbxi_str_less(*global_str, over->prop_name)) {
+ ++global_str;
+ }
+
+ if (global_str != global_end && ufbxi_str_equal(*global_str, over->prop_name)) {
+ over->prop_name = *global_str;
+ } else {
+ ufbxi_check_err(&ac->error, ufbxi_push_anim_string(ac, &over->prop_name));
+ }
+
+ prev_name = over->prop_name;
+ }
+
+ // Sort `anim->prop_overrides` to the actual order expected by evaluation.
+ ufbxi_unstable_sort(anim->prop_overrides.data, anim->prop_overrides.count, sizeof(ufbx_prop_override), &ufbxi_prop_override_less, NULL);
+
+ for (size_t i = 1; i < prop_overrides.count; i++) {
+ const ufbx_prop_override *prev = &anim->prop_overrides.data[i - 1];
+ const ufbx_prop_override *next = &anim->prop_overrides.data[i];
+ if (prev->element_id == next->element_id && prev->prop_name.data == next->prop_name.data) {
+ ufbxi_fmt_err_info(&ac->error, "element %u prop \"%s\"", prev->element_id, prev->prop_name.data);
+ ufbxi_fail_err_msg(&ac->error, "Duplicate override", "Duplicate override");
+ }
+ }
+ }
+
+ if (ac->opts.transform_overrides.count > 0) {
+ anim->transform_overrides.count = ac->opts.transform_overrides.count;
+ anim->transform_overrides.data = ufbxi_push_copy(&ac->result, ufbx_transform_override, anim->transform_overrides.count, ac->opts.transform_overrides.data);
+ ufbxi_check_err(&ac->error, anim->transform_overrides.data);
+ ufbxi_unstable_sort(anim->transform_overrides.data, anim->transform_overrides.count, sizeof(ufbx_transform_override), &ufbxi_transform_override_less, NULL);
+ }
+
+ ac->imp = ufbxi_push(&ac->result, ufbxi_anim_imp, 1);
+ ufbxi_check_err(&ac->error, ac->imp);
+
+ ufbxi_init_ref(&ac->imp->refcount, UFBXI_ANIM_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, scene))->refcount);
+
+ ac->imp->magic = UFBXI_ANIM_IMP_MAGIC;
+ ac->imp->anim = ac->anim;
+ ac->imp->refcount.ator = ac->ator_result;
+ ac->imp->refcount.buf = ac->result;
+
+ return 1;
+}
+
+// -- Animation baking
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_baked_anim bake;
+ uint32_t magic;
+} ufbxi_baked_anim_imp;
+
+#if UFBXI_FEATURE_ANIMATION_BAKING
+
+typedef struct {
+ double time;
+ uint32_t flags;
+} ufbxi_bake_time;
+
+UFBX_LIST_TYPE(ufbxi_bake_time_list, ufbxi_bake_time);
+
+typedef struct {
+ ufbx_error error;
+ ufbxi_allocator ator_tmp;
+ ufbxi_allocator ator_result;
+
+ ufbxi_buf result;
+ ufbxi_buf tmp;
+ ufbxi_buf tmp_prop;
+ ufbxi_buf tmp_times;
+ ufbxi_buf tmp_bake_props;
+ ufbxi_buf tmp_nodes;
+ ufbxi_buf tmp_elements;
+ ufbxi_buf tmp_props;
+ ufbxi_buf tmp_bake_stack;
+
+ ufbxi_bake_time_list layer_weight_times;
+
+ ufbx_baked_node **baked_nodes;
+ bool *nodes_to_bake;
+
+ char *tmp_arr;
+ size_t tmp_arr_size;
+
+ const ufbx_scene *scene;
+ const ufbx_anim *anim;
+ ufbx_bake_opts opts;
+
+ double ktime_offset;
+
+ double time_begin;
+ double time_end;
+ double time_min;
+ double time_max;
+
+ ufbx_baked_anim bake;
+ ufbxi_baked_anim_imp *imp;
+} ufbxi_bake_context;
+
+typedef struct {
+ uint32_t sort_id;
+ uint32_t element_id;
+ const char *prop_name;
+ ufbx_anim_value *anim_value;
+} ufbxi_bake_prop;
+
+static bool ufbxi_bake_prop_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbxi_bake_prop *a = (const ufbxi_bake_prop*)va;
+ const ufbxi_bake_prop *b = (const ufbxi_bake_prop*)vb;
+ if (a->sort_id != b->sort_id) return a->sort_id < b->sort_id;
+ if (a->element_id != b->element_id) return a->element_id < b->element_id;
+ if (a->prop_name != b->prop_name) return strcmp(a->prop_name, b->prop_name) < 0;
+ return false;
+}
+
+ufbx_static_assert(bake_step_left, UFBX_BAKED_KEY_STEP_LEFT == 0x1);
+ufbx_static_assert(bake_step_right, UFBX_BAKED_KEY_STEP_RIGHT == 0x2);
+ufbx_static_assert(bake_step_key, UFBX_BAKED_KEY_STEP_KEY == 0x4);
+static ufbxi_forceinline int ufbxi_cmp_bake_time(ufbxi_bake_time a, ufbxi_bake_time b)
+{
+ if (a.time != b.time) return a.time < b.time ? -1 : 1;
+ // Bit twiddling for a fast sorting of `0x1 (LEFT) < 0x0 < 0x2 (RIGHT)`
+ // by `step ^ 1`: `0x0 (LEFT) < 0x1 < 0x3 (RIGHT)`
+ uint32_t a_step = a.flags & 0x3, b_step = b.flags & 0x3;
+ if (a_step != b_step) return (a_step ^ 0x1) < (b_step ^ 0x1) ? -1 : 1;
+ return 0;
+}
+
+ufbxi_nodiscard static ufbxi_forceinline int ufbxi_bake_push_time(ufbxi_bake_context *bc, double time, uint32_t flags)
+{
+ ufbxi_bake_time *p_key = ufbxi_push_fast(&bc->tmp_times, ufbxi_bake_time, 1);
+ if (!p_key) return 0;
+ p_key->time = time;
+ p_key->flags = flags;
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_times(ufbxi_bake_context *bc, const ufbx_anim_value *anim_value, bool resample_linear, uint32_t key_flag)
+{
+ double sample_rate = bc->opts.resample_rate;
+ double min_duration = bc->opts.minimum_sample_rate > 0.0 ? 1.0 / bc->opts.minimum_sample_rate : 0.0;
+
+ for (size_t curve_ix = 0; curve_ix < 3; curve_ix++) {
+ ufbx_anim_curve *curve = anim_value->curves[curve_ix];
+ if (!curve) continue;
+
+ const ufbx_keyframe *keys = curve->keyframes.data;
+ size_t num_keys = curve->keyframes.count;
+ for (size_t key_ix = 0; key_ix < num_keys; key_ix++) {
+ ufbx_keyframe a = keys[key_ix];
+ double a_time = a.time;
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, a_time, key_flag));
+ if (key_ix + 1 >= num_keys) break;
+ ufbx_keyframe b = keys[key_ix + 1];
+ double b_time = b.time;
+
+ // Skip fully flat sections
+ if (a.value == b.value && a.right.dy == 0.0f && b.left.dy == 0.0f) continue;
+
+ if (a.interpolation == UFBX_INTERPOLATION_CONSTANT_PREV) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, b_time, UFBX_BAKED_KEY_STEP_LEFT));
+ } else if (a.interpolation == UFBX_INTERPOLATION_CONSTANT_NEXT) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, a_time, UFBX_BAKED_KEY_STEP_RIGHT));
+ } else if ((resample_linear || a.interpolation == UFBX_INTERPOLATION_CUBIC) && sample_rate > 0.0) {
+ double duration = b_time - a_time;
+ if (duration <= min_duration) continue;
+
+ double factor = 1.0;
+ while (duration * sample_rate / factor >= (double)bc->opts.max_keyframe_segments) {
+ factor *= 2.0;
+ }
+
+ double padding = 0.5 / sample_rate;
+ double start = ufbx_ceil((a_time + padding) * sample_rate / factor) * factor;
+ double stop = b_time - padding;
+ for (size_t i = 0; i < bc->opts.max_keyframe_segments; i++) {
+ double time = (start + (double)i * factor) / sample_rate;
+ if (time >= stop) break;
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, time, 0));
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+static const char *const ufbxi_transform_props[] = {
+ ufbxi_Lcl_Translation, ufbxi_Lcl_Rotation, ufbxi_Lcl_Scaling, ufbxi_PreRotation, ufbxi_PostRotation,
+ ufbxi_RotationOffset, ufbxi_ScalingOffset, ufbxi_RotationPivot, ufbxi_ScalingPivot, ufbxi_RotationOrder,
+};
+
+static const char *const ufbxi_complex_translation_props[] = {
+ ufbxi_ScalingPivot, ufbxi_RotationPivot, ufbxi_RotationOffset, ufbxi_ScalingOffset,
+};
+
+static const char *const ufbxi_complex_rotation_props[] = {
+ ufbxi_PreRotation, ufbxi_PostRotation, ufbxi_RotationOrder,
+};
+
+static const char *const ufbxi_complex_rotation_sources[] = {
+ ufbxi_Lcl_Rotation, ufbxi_PreRotation, ufbxi_PostRotation, ufbxi_RotationOrder,
+};
+
+ufbxi_nodiscard static ufbxi_noinline bool ufbxi_in_list(const char *const *items, size_t count, const char *item)
+{
+ for (size_t i = 0; i < count; i++) {
+ if (items[i] == item) return true;
+ }
+ return false;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_sort_bake_times(ufbxi_bake_context *bc, ufbxi_bake_time *times, size_t count)
+{
+ ufbxi_check_err(&bc->error, ufbxi_grow_array(&bc->ator_tmp, &bc->tmp_arr, &bc->tmp_arr_size, count * sizeof(ufbxi_bake_time)));
+ ufbxi_macro_stable_sort(ufbxi_bake_time, 32, times, bc->tmp_arr, count, ( ufbxi_cmp_bake_time(*a, *b) < 0 ));
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_bake_times(ufbxi_bake_context *bc, ufbxi_bake_time_list *p_dst)
+{
+ if (bc->layer_weight_times.count > 0) {
+ ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_times, ufbxi_bake_time, bc->layer_weight_times.count, bc->layer_weight_times.data));
+ }
+
+ if (bc->tmp_times.num_items == 0) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, bc->time_begin, 0));
+ ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, bc->time_end, 0));
+ }
+
+ size_t num_times = bc->tmp_times.num_items;
+ ufbxi_bake_time *times = ufbxi_push_pop(&bc->tmp_prop, &bc->tmp_times, ufbxi_bake_time, num_times);
+ ufbxi_check_err(&bc->error, times);
+
+ ufbxi_check_err(&bc->error, ufbxi_sort_bake_times(bc, times, num_times));
+
+ // Deduplicate times
+ if (num_times > 0) {
+ size_t dst = 0;
+ ufbxi_bake_time prev = times[0];
+ for (size_t src = 1; src < num_times; src++) {
+ ufbxi_bake_time next = times[src];
+ // Merge keys with the same time and step flags `(0x1, 0x2)`
+ if (next.time == prev.time) {
+ if (((next.flags ^ prev.flags) & 0x3) == 0) {
+ prev.flags |= next.flags;
+ continue;
+ } else if (prev.flags & UFBX_BAKED_KEY_STEP_LEFT) {
+ next.flags |= UFBX_BAKED_KEY_STEP_KEY;
+ } else if (next.flags & UFBX_BAKED_KEY_STEP_RIGHT) {
+ prev.flags |= UFBX_BAKED_KEY_STEP_KEY;
+ }
+ }
+
+ times[dst++] = prev;
+ prev = next;
+ }
+ times[dst++] = prev;
+ num_times = dst;
+ }
+
+ // Cull too close resampled keys, these may arise during merging multiple times
+ if (num_times > 0) {
+ double min_dist = 0.25 / bc->opts.resample_rate;
+ uint32_t keep_flags = UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT|UFBX_BAKED_KEY_STEP_KEY|UFBX_BAKED_KEY_KEYFRAME;
+
+ size_t dst = 0;
+ for (size_t src = 0; src < num_times; src++) {
+ ufbxi_bake_time cur = times[src];
+ double delta = UFBX_INFINITY;
+
+ bool keep = true;
+ if ((cur.flags & keep_flags) == 0) {
+ if (dst > 0) delta = cur.time - times[dst - 1].time;
+ if (src + 1 < num_times) delta = ufbx_fmin(delta, times[src + 1].time - cur.time);
+ if (delta < min_dist) keep = false;
+ }
+ if (keep) {
+ times[dst++] = cur;
+ }
+ }
+ num_times = dst;
+ }
+
+ // Enforce maximum sample rate
+ if (bc->opts.maximum_sample_rate > 0.0) {
+ const double epsilon = 0.0078125 / bc->opts.maximum_sample_rate;
+ double sample_rate = bc->opts.maximum_sample_rate;
+ double max_interval = 1.0 / bc->opts.maximum_sample_rate;
+ double min_interval = 1.0 / bc->opts.maximum_sample_rate - epsilon;
+ size_t dst = 0, src = 0;
+
+ // Pre-expand constant keyframes
+ for (size_t i = 0; i < num_times; i++) {
+ if ((times[i].flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
+ double sign = (times[i].flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 ? -1.0 : 1.0;
+ double time = times[i].time + sign * max_interval;
+ if (i > 0) time = ufbx_fmax(time, times[i - 1].time);
+ if (i + 1 < num_times) time = ufbx_fmin(time, times[i + 1].time);
+ times[i].time = time;
+ times[i].flags = UFBX_BAKED_KEY_REDUCED;
+ }
+ }
+
+ ufbxi_bake_time prev_time = { -UFBX_INFINITY };
+ while (src < num_times) {
+ ufbxi_bake_time src_time = times[src];
+ src++;
+
+ size_t start_src = src;
+ ufbxi_bake_time next_time;
+ next_time.time = ufbx_ceil(src_time.time * sample_rate - epsilon) / sample_rate;
+ next_time.flags = UFBX_BAKED_KEY_REDUCED;
+ while (src < num_times && times[src].time <= next_time.time + epsilon) {
+ src++;
+ }
+
+ if (src != start_src || src_time.time - prev_time.time <= min_interval) {
+ prev_time = next_time;
+ } else {
+ prev_time = src_time;
+ }
+
+ if (dst == 0 || prev_time.time > times[dst - 1].time) {
+ times[dst++] = prev_time;
+ }
+ }
+
+ num_times = dst;
+ }
+
+ if (num_times > 0) {
+ if (times[0].time < bc->time_min) bc->time_min = times[0].time;
+ if (times[num_times - 1].time > bc->time_max) bc->time_max = times[num_times - 1].time;
+ }
+
+ p_dst->data = times;
+ p_dst->count = num_times;
+
+ return 1;
+}
+
+#define ufbxi_add_epsilon(a, epsilon) ((a)>0 ? (a)*(epsilon) : (a)/(epsilon))
+#define ufbxi_sub_epsilon(a, epsilon) ((a)>0 ? (a)/(epsilon) : (a)*(epsilon))
+
+static ufbxi_noinline bool ufbxi_postprocess_step(ufbxi_bake_context *bc, double prev_time, double next_time, double *p_time, ufbx_baked_key_flags flags)
+{
+ ufbxi_dev_assert((flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0);
+ bool left = (flags & UFBX_BAKED_KEY_STEP_LEFT) != 0;
+
+ double step = 0.001;
+ double epsilon = 1.0 + UFBX_FLT_EPSILON * 4.0f;
+
+ double time = *p_time;
+ switch (bc->opts.step_handling) {
+ case UFBX_BAKE_STEP_HANDLING_DEFAULT:
+ break;
+ case UFBX_BAKE_STEP_HANDLING_CUSTOM_DURATION:
+ step = bc->opts.step_custom_duration;
+ epsilon = 1.0 + bc->opts.step_custom_epsilon;
+ break;
+ case UFBX_BAKE_STEP_HANDLING_IDENTICAL_TIME:
+ return true;
+ case UFBX_BAKE_STEP_HANDLING_ADJACENT_DOUBLE:
+ if (left) {
+ *p_time = time = ufbx_nextafter(time, -UFBX_INFINITY);
+ return time > prev_time;
+ } else {
+ *p_time = time = ufbx_nextafter(time, UFBX_INFINITY);
+ return time < next_time;
+ }
+ case UFBX_BAKE_STEP_HANDLING_IGNORE:
+ return false;
+ default:
+ ufbxi_unreachable("Unhandled bake step handling");
+ return false;
+ }
+
+ if (left) {
+ double min_time = ufbx_fmax(prev_time + step, ufbxi_add_epsilon(prev_time, epsilon));
+ *p_time = time = ufbx_fmin(time - step, ufbxi_sub_epsilon(time, epsilon));
+ return time > min_time;
+ } else {
+ double max_time = ufbx_fmin(next_time - step, ufbxi_sub_epsilon(next_time, epsilon));
+ *p_time = time = ufbx_fmax(time + step, ufbxi_add_epsilon(time, epsilon));
+ return time < max_time;
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_postprocess_vec3(ufbxi_bake_context *bc, ufbx_baked_vec3_list *p_dst, bool *p_constant, ufbx_baked_vec3_list src)
+{
+ if (src.count == 0) return 1;
+
+ // Offset times
+ if (bc->ktime_offset != 0.0) {
+ double scale = (double)bc->scene->metadata.ktime_second;
+ double offset = bc->ktime_offset;
+ for (size_t i = 0; i < src.count; i++) {
+ src.data[i].time = ufbx_rint(src.data[i].time * scale + offset) / scale;
+ }
+ }
+
+ // Postprocess stepped tangents
+ {
+ size_t dst = 0;
+ double prev_time = src.data[0].time;
+ for (size_t i = 0; i < src.count; i++) {
+ ufbx_baked_vec3 cur = src.data[i];
+ double next_time = i + 1 < src.count ? src.data[i + 1].time : UFBX_INFINITY;
+ bool keep = true;
+ if ((cur.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
+ keep = ufbxi_postprocess_step(bc, prev_time, next_time, &cur.time, cur.flags);
+ }
+ if (keep) {
+ src.data[dst] = cur;
+ dst++;
+ prev_time = cur.time;
+ }
+ }
+ src.count = dst;
+ }
+
+ if (bc->opts.key_reduction_enabled) {
+ double threshold = bc->opts.key_reduction_threshold * bc->opts.key_reduction_threshold;
+ for (size_t pass = 0; pass < bc->opts.key_reduction_passes; pass++) {
+ size_t dst = 1;
+ for (size_t i = 1; i < src.count; i++) {
+ ufbx_baked_vec3 prev = src.data[i - 1];
+ ufbx_baked_vec3 cur = src.data[i];
+ if (i + 1 < src.count) {
+ ufbx_baked_vec3 next = src.data[i + 1];
+ double delta = (cur.time - prev.time) / (next.time - prev.time);
+ ufbx_vec3 tmp = ufbxi_lerp3(prev.value, next.value, (ufbx_real)delta);
+ double error = 0.0;
+ error += ((double)tmp.x - (double)cur.value.x) * ((double)tmp.x - (double)cur.value.x);
+ error += ((double)tmp.y - (double)cur.value.y) * ((double)tmp.y - (double)cur.value.y);
+ error += ((double)tmp.z - (double)cur.value.z) * ((double)tmp.z - (double)cur.value.z);
+ if (error <= threshold) {
+ src.data[dst] = src.data[i + 1];
+ i += 1;
+ dst += 1;
+ continue;
+ }
+ }
+
+ src.data[dst] = src.data[i];
+ dst += 1;
+ }
+ if (dst == src.count) break;
+ src.count = dst;
+ }
+ }
+
+ bool constant = true;
+ ufbx_vec3 ref = src.data[0].value;
+ for (size_t i = 1; i < src.count; i++) {
+ ufbx_vec3 v = src.data[i].value;
+ if (v.x != ref.x || v.y != ref.y || v.z != ref.z) {
+ constant = false;
+ break;
+ }
+ }
+ *p_constant = constant;
+
+ p_dst->count = src.count;
+ p_dst->data = ufbxi_push_copy(&bc->result, ufbx_baked_vec3, src.count, src.data);
+ ufbxi_check_err(&bc->error, p_dst->data);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_postprocess_quat(ufbxi_bake_context *bc, ufbx_baked_quat_list *p_dst, bool *p_constant, ufbx_baked_quat_list src)
+{
+ if (src.count == 0) return 1;
+
+ // Offset times
+ if (bc->ktime_offset != 0.0) {
+ double scale = (double)bc->scene->metadata.ktime_second;
+ double offset = bc->ktime_offset;
+ for (size_t i = 0; i < src.count; i++) {
+ src.data[i].time = ufbx_rint(src.data[i].time * scale + offset) / scale;
+ }
+ }
+
+ // Postprocess stepped tangents
+ {
+ size_t dst = 0;
+ double prev_time = src.data[0].time;
+ for (size_t i = 0; i < src.count; i++) {
+ ufbx_baked_quat cur = src.data[i];
+ double next_time = i + 1 < src.count ? src.data[i + 1].time : UFBX_INFINITY;
+ bool keep = true;
+ if ((cur.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
+ keep = ufbxi_postprocess_step(bc, prev_time, next_time, &cur.time, cur.flags);
+ }
+ if (keep) {
+ prev_time = cur.time;
+ src.data[dst] = cur;
+ dst++;
+ }
+ }
+ src.count = dst;
+ }
+
+ // Fix quaternion antipodality
+ for (size_t i = 1; i < src.count; i++) {
+ src.data[i].value = ufbx_quat_fix_antipodal(src.data[i].value, src.data[i - 1].value);
+ }
+
+ if (bc->opts.key_reduction_enabled) {
+ double threshold = bc->opts.key_reduction_threshold * bc->opts.key_reduction_threshold;
+ for (size_t pass = 0; pass < bc->opts.key_reduction_passes; pass++) {
+ size_t dst = 1;
+ for (size_t i = 1; i < src.count; i++) {
+ ufbx_baked_quat prev = src.data[i - 1];
+ ufbx_baked_quat cur = src.data[i];
+ if (i + 1 < src.count) {
+ ufbx_baked_quat next = src.data[i + 1];
+ double delta = (cur.time - prev.time) / (next.time - prev.time);
+ double error = 0.0;
+
+ if (bc->opts.key_reduction_rotation) {
+ ufbx_quat tmp = ufbx_quat_slerp(prev.value, next.value, (ufbx_real)delta);
+ error += ((double)tmp.x - (double)cur.value.x) * ((double)tmp.x - (double)cur.value.x);
+ error += ((double)tmp.y - (double)cur.value.y) * ((double)tmp.y - (double)cur.value.y);
+ error += ((double)tmp.z - (double)cur.value.z) * ((double)tmp.z - (double)cur.value.z);
+ error += ((double)tmp.w - (double)cur.value.w) * ((double)tmp.w - (double)cur.value.w);
+ } else {
+ error += ((double)prev.value.x - (double)cur.value.x) * ((double)prev.value.x - (double)cur.value.x);
+ error += ((double)prev.value.y - (double)cur.value.y) * ((double)prev.value.y - (double)cur.value.y);
+ error += ((double)prev.value.z - (double)cur.value.z) * ((double)prev.value.z - (double)cur.value.z);
+ error += ((double)prev.value.w - (double)cur.value.w) * ((double)prev.value.w - (double)cur.value.w);
+ error += ((double)next.value.x - (double)cur.value.x) * ((double)next.value.x - (double)cur.value.x);
+ error += ((double)next.value.y - (double)cur.value.y) * ((double)next.value.y - (double)cur.value.y);
+ error += ((double)next.value.z - (double)cur.value.z) * ((double)next.value.z - (double)cur.value.z);
+ error += ((double)next.value.w - (double)cur.value.w) * ((double)next.value.w - (double)cur.value.w);
+ error *= 0.5;
+ }
+
+ if (error <= threshold) {
+ src.data[dst] = src.data[i + 1];
+ i += 1;
+ dst += 1;
+ continue;
+ }
+ }
+
+ src.data[dst] = src.data[i];
+ dst += 1;
+ }
+ if (dst == src.count) break;
+ src.count = dst;
+ }
+ }
+
+ bool constant = true;
+ ufbx_quat ref = src.data[0].value;
+ for (size_t i = 1; i < src.count; i++) {
+ ufbx_quat v = src.data[i].value;
+ if (v.x != ref.x || v.y != ref.y || v.z != ref.z || v.w != ref.w) {
+ constant = false;
+ break;
+ }
+ }
+ *p_constant = constant;
+
+ p_dst->count = src.count;
+ p_dst->data = ufbxi_push_copy(&bc->result, ufbx_baked_quat, src.count, src.data);
+ ufbxi_check_err(&bc->error, p_dst->data);
+
+ return 1;
+}
+
+static ufbxi_forceinline double ufbxi_bake_time_sample_time(ufbxi_bake_time time)
+{
+ // Move an infinitesimal step for stepped tangents
+ if ((time.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
+ double dir = (time.flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 ? -UFBX_INFINITY : UFBX_INFINITY;
+ return ufbx_nextafter(time.time, dir);
+ } else {
+ return time.time;
+ }
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_resampled_times(ufbxi_bake_context *bc, const ufbx_baked_vec3_list *p_keys)
+{
+ ufbx_baked_vec3_list keys = *p_keys;
+
+ ufbxi_bake_time *times = ufbxi_push(&bc->tmp_times, ufbxi_bake_time, keys.count);
+ ufbxi_check_err(&bc->error, times);
+ for (size_t i = 0; i < keys.count; i++) {
+ ufbx_baked_key_flags flags = keys.data[i].flags;
+ double time = keys.data[i].time;
+ if ((flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 && i + 1 < keys.count && (keys.data[i + 1].flags & UFBX_BAKED_KEY_STEP_KEY) != 0) {
+ time = keys.data[i + 1].time;
+ } else if ((flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && i > 0 && (keys.data[i - 1].flags & UFBX_BAKED_KEY_STEP_KEY) != 0) {
+ time = keys.data[i - 1].time;
+ }
+ times[i].time = time;
+ times[i].flags = flags & 0x7;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_node_imp(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
+{
+ ufbx_assert(bc->baked_nodes && bc->nodes_to_bake);
+
+ ufbx_node *node = (ufbx_node*)bc->scene->elements.data[element_id];
+ ufbxi_dev_assert(node->element.type == UFBX_ELEMENT_NODE);
+
+ bool complex_translation = false;
+ bool complex_rotation = false;
+
+ for (size_t i = 0; i < ufbxi_arraycount(ufbxi_complex_translation_props); i++) {
+ const char *name = ufbxi_complex_translation_props[i];
+ ufbx_prop *prop = ufbxi_find_prop(&node->props, name);
+ if (prop && !ufbxi_is_vec3_zero(prop->value_vec3)) {
+ complex_translation = true;
+ }
+ ufbxi_for(ufbxi_bake_prop, bprop, props, count) {
+ if (bprop->prop_name == name) {
+ complex_translation = true;
+ }
+ }
+ }
+
+ for (size_t i = 0; i < ufbxi_arraycount(ufbxi_complex_rotation_props); i++) {
+ const char *name = ufbxi_complex_rotation_props[i];
+ ufbxi_for(ufbxi_bake_prop, bprop, props, count) {
+ if (bprop->prop_name == name) {
+ complex_rotation = true;
+ }
+ }
+ }
+
+ ufbxi_bake_time_list times_t, times_r, times_s;
+
+ // Translation
+ bool resample_translation = false;
+
+ // Account for the _resampled_ scale helper scale animation to keep the
+ // translation scale consistent with the parent scaling.
+ ufbx_baked_node *scale_helper_t = NULL;
+ ufbx_vec3 constant_scale_t = { 1.0f, 1.0f, 1.0f };
+ if (!node->is_scale_helper && node->parent && node->parent->scale_helper) {
+ scale_helper_t = bc->baked_nodes[node->parent->scale_helper->typed_id];
+ if (scale_helper_t) {
+ if (!scale_helper_t->constant_scale) {
+ resample_translation = true;
+ }
+ ufbxi_check_err(&bc->error, ufbxi_push_resampled_times(bc, &scale_helper_t->scale_keys));
+ } else {
+ constant_scale_t = node->parent->scale_helper->inherit_scale;
+ }
+ }
+
+ if (complex_translation) {
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ // Literally any transform related property can affect complex translation
+ if (ufbxi_in_list(ufbxi_transform_props, ufbxi_arraycount(ufbxi_transform_props), prop->prop_name)) {
+ bool resample_linear = resample_translation || prop->prop_name != ufbxi_Lcl_Translation;
+ uint32_t key_flag = prop->prop_name == ufbxi_Lcl_Translation ? UFBX_BAKED_KEY_KEYFRAME : 0;
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_linear, key_flag));
+ }
+ }
+ } else {
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ if (prop->prop_name == ufbxi_Lcl_Translation) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_translation, UFBX_BAKED_KEY_KEYFRAME));
+ }
+ }
+ }
+
+ ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_t));
+
+ // Rotation
+ if (complex_rotation) {
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ if (ufbxi_in_list(ufbxi_complex_rotation_sources, ufbxi_arraycount(ufbxi_complex_rotation_sources), prop->prop_name)) {
+ bool resample_linear = !bc->opts.no_resample_rotation || prop->prop_name != ufbxi_Lcl_Rotation;
+ uint32_t key_flag = prop->prop_name == ufbxi_Lcl_Rotation ? UFBX_BAKED_KEY_KEYFRAME : 0;
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_linear, key_flag));
+ }
+ }
+ } else {
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ if (prop->prop_name == ufbxi_Lcl_Rotation) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, !bc->opts.no_resample_rotation, UFBX_BAKED_KEY_KEYFRAME));
+ }
+ }
+ }
+ ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_r));
+
+ // Scaling
+ bool resample_scale = false;
+
+ // Account for the resampled scale
+ ufbx_baked_node *scale_helper_s = NULL;
+ ufbx_vec3 constant_scale_s = { 1.0f, 1.0f, 1.0f };
+ if (node->is_scale_helper && node->parent && node->parent->inherit_scale_node && node->parent->inherit_scale_node->scale_helper) {
+ ufbx_node *inherit_helper = node->parent->inherit_scale_node->scale_helper;
+ scale_helper_s = bc->baked_nodes[inherit_helper->typed_id];
+ if (scale_helper_s) {
+ if (!scale_helper_s->constant_scale) {
+ resample_scale = true;
+ }
+ ufbxi_check_err(&bc->error, ufbxi_push_resampled_times(bc, &scale_helper_s->scale_keys));
+ } else {
+ constant_scale_s = inherit_helper->local_transform.scale;
+ }
+ }
+
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ if (prop->prop_name == ufbxi_Lcl_Scaling) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_scale, UFBX_BAKED_KEY_KEYFRAME));
+ }
+ }
+ ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_s));
+
+ ufbx_baked_vec3_list keys_t;
+ ufbx_baked_quat_list keys_r;
+ ufbx_baked_vec3_list keys_s;
+
+ keys_t.count = times_t.count;
+ keys_t.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys_t.count);
+ ufbxi_check_err(&bc->error, keys_t.data);
+
+ keys_r.count = times_r.count;
+ keys_r.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_quat, keys_r.count);
+ ufbxi_check_err(&bc->error, keys_r.data);
+
+ keys_s.count = times_s.count;
+ keys_s.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys_s.count);
+ ufbxi_check_err(&bc->error, keys_s.data);
+
+ size_t ix_t = 0, ix_r = 0, ix_s = 0;
+ while (ix_t < times_t.count || ix_r < times_r.count || ix_s < times_s.count) {
+ ufbxi_bake_time bake_time = { UFBX_INFINITY };
+ uint32_t flags_r = 0, flags_t = 0, flags_s = 0;
+
+ uint32_t flags = 0;
+ if (ix_r < times_r.count) {
+ bake_time = times_r.data[ix_r];
+ flags_r = bake_time.flags;
+ bake_time.flags &= 0x7;
+ flags |= UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION;
+ }
+ if (ix_t < times_t.count) {
+ ufbxi_bake_time t = times_t.data[ix_t];
+ int cmp = ufbxi_cmp_bake_time(t, bake_time);
+ if (cmp <= 0) {
+ if (cmp < 0) {
+ bake_time = t;
+ flags = 0;
+ }
+ bake_time.flags |= t.flags & 0x7;
+ flags_t = t.flags;
+ flags |= UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION;
+ }
+ }
+ if (ix_s < times_s.count) {
+ ufbxi_bake_time t = times_s.data[ix_s];
+ int cmp = ufbxi_cmp_bake_time(t, bake_time);
+ if (cmp <= 0) {
+ if (cmp < 0) {
+ bake_time = t;
+ flags = 0;
+ }
+ bake_time.flags |= t.flags & 0x7;
+ flags_s = t.flags;
+ flags |= UFBX_TRANSFORM_FLAG_INCLUDE_SCALE;
+ }
+ }
+
+ flags |= UFBX_TRANSFORM_FLAG_IGNORE_SCALE_HELPER|UFBX_TRANSFORM_FLAG_IGNORE_COMPONENTWISE_SCALE|UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES;
+ if (bc->opts.evaluate_flags & UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION) {
+ flags |= UFBX_TRANSFORM_FLAG_NO_EXTRAPOLATION;
+ }
+
+ double eval_time = ufbxi_bake_time_sample_time(bake_time);
+ ufbx_transform transform = ufbx_evaluate_transform_flags(bc->anim, node, eval_time, flags);
+
+ if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION) {
+ if (scale_helper_t) {
+ ufbx_vec3 scale = ufbx_evaluate_baked_vec3(scale_helper_t->scale_keys, eval_time);
+ transform.translation.x *= scale.x;
+ transform.translation.y *= scale.y;
+ transform.translation.z *= scale.z;
+ }
+
+ transform.translation.x *= constant_scale_t.x;
+ transform.translation.y *= constant_scale_t.y;
+ transform.translation.z *= constant_scale_t.z;
+
+ keys_t.data[ix_t].time = bake_time.time;
+ keys_t.data[ix_t].value = transform.translation;
+ keys_t.data[ix_t].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_t);
+ ix_t++;
+ }
+ if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) {
+ keys_r.data[ix_r].time = bake_time.time;
+ keys_r.data[ix_r].value = transform.rotation;
+ keys_r.data[ix_r].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_r);
+ ix_r++;
+ }
+ if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) {
+ if (scale_helper_s) {
+ ufbx_vec3 scale = ufbx_evaluate_baked_vec3(scale_helper_s->scale_keys, eval_time);
+ transform.scale.x *= scale.x;
+ transform.scale.y *= scale.y;
+ transform.scale.z *= scale.z;
+ }
+
+ transform.scale.x *= constant_scale_s.x;
+ transform.scale.y *= constant_scale_s.y;
+ transform.scale.z *= constant_scale_s.z;
+
+ keys_s.data[ix_s].time = bake_time.time;
+ keys_s.data[ix_s].value = transform.scale;
+ keys_s.data[ix_s].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_s);
+ ix_s++;
+ }
+ }
+
+ ufbx_baked_node *baked_node = ufbxi_push_zero(&bc->tmp_nodes, ufbx_baked_node, 1);
+ ufbxi_check_err(&bc->error, baked_node);
+
+ baked_node->element_id = node->element_id;
+ baked_node->typed_id = node->typed_id;
+ ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_node->translation_keys, &baked_node->constant_translation, keys_t));
+ ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_quat(bc, &baked_node->rotation_keys, &baked_node->constant_rotation, keys_r));
+ ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_node->scale_keys, &baked_node->constant_scale, keys_s));
+
+ bc->baked_nodes[node->typed_id] = baked_node;
+
+ ufbxi_buf_clear(&bc->tmp_prop);
+
+ // If this node is a scale helper, make sure to bake its siblings and
+ // potentially their scale helpers if they are not a part of the animation.
+ if (node->is_scale_helper) {
+ ufbx_assert(node->parent);
+ ufbxi_for_ptr_list(ufbx_node, p_child, node->parent->children) {
+ ufbx_node *child = *p_child;
+ if (child == node) continue;
+ if (!bc->nodes_to_bake[child->typed_id]) {
+ bc->nodes_to_bake[child->typed_id] = true;
+ ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_bake_stack, uint32_t, 1, &child->element_id));
+ }
+ if (child->inherit_scale_node && child->inherit_scale_node->scale_helper && child->scale_helper
+ && bc->nodes_to_bake[child->inherit_scale_node->scale_helper->typed_id]) {
+ ufbx_assert(bc->baked_nodes[child->inherit_scale_node->scale_helper->typed_id]);
+ if (!bc->nodes_to_bake[child->scale_helper->typed_id]) {
+ bc->nodes_to_bake[child->scale_helper->typed_id] = true;
+ ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_bake_stack, uint32_t, 1, &child->scale_helper->element_id));
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_node(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
+{
+ ufbxi_check_err(&bc->error, ufbxi_bake_node_imp(bc, element_id, props, count));
+
+ // Baking a node may cause further nodes to be baked, so keep going
+ // until all dependencies are baked.
+ while (bc->tmp_bake_stack.num_items > 0) {
+ uint32_t child_id = 0;
+ ufbxi_pop(&bc->tmp_bake_stack, uint32_t, 1, &child_id);
+ ufbxi_check_err(&bc->error, ufbxi_bake_node_imp(bc, child_id, NULL, 0));
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim_prop(ufbxi_bake_context *bc, ufbx_element *element, const char *prop_name, ufbxi_bake_prop *props, size_t count)
+{
+ ufbxi_for(ufbxi_bake_prop, prop, props, count) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, false, UFBX_BAKED_KEY_KEYFRAME));
+ }
+
+ ufbxi_bake_time_list times;
+ ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times));
+
+ ufbx_baked_vec3_list keys;
+ keys.count = times.count;
+ keys.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys.count);
+ ufbxi_check_err(&bc->error, keys.data);
+
+ ufbx_string name;
+ name.data = prop_name;
+ name.length = strlen(prop_name);
+
+ for (size_t i = 0; i < times.count; i++) {
+ ufbxi_bake_time bake_time = times.data[i];
+ double eval_time = ufbxi_bake_time_sample_time(bake_time);
+ ufbx_prop prop = ufbx_evaluate_prop_flags_len(bc->anim, element, name.data, name.length, eval_time, bc->opts.evaluate_flags);
+ keys.data[i].time = bake_time.time;
+ keys.data[i].value = prop.value_vec3;
+ keys.data[i].flags = (ufbx_baked_key_flags)bake_time.flags;
+ }
+
+ ufbx_baked_prop *baked_prop = ufbxi_push_zero(&bc->tmp_props, ufbx_baked_prop, 1);
+ ufbxi_check_err(&bc->error, baked_prop);
+
+ baked_prop->name.length = strlen(prop_name);
+ baked_prop->name.data = ufbxi_push_copy(&bc->result, char, baked_prop->name.length + 1, prop_name);
+ ufbxi_check_err(&bc->error, baked_prop->name.data);
+
+ ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_prop->keys, &baked_prop->constant_value, keys));
+
+ ufbxi_buf_clear(&bc->tmp_prop);
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_element(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
+{
+ ufbx_element *element = bc->scene->elements.data[element_id];
+ if (element->type == UFBX_ELEMENT_NODE && !bc->opts.skip_node_transforms) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_node(bc, element_id, props, count));
+ }
+
+ size_t begin = 0;
+ while (begin < count) {
+ const char *prop_name = props[begin].prop_name;
+ size_t end = begin + 1;
+ while (end < count && props[end].prop_name == prop_name) {
+ end++;
+ }
+
+ // Don't bake transform related props for nodes unless specifically requested
+ if (element->type == UFBX_ELEMENT_NODE && !bc->opts.bake_transform_props && ufbxi_in_list(ufbxi_transform_props, ufbxi_arraycount(ufbxi_transform_props), prop_name)) {
+ begin = end;
+ continue;
+ }
+
+ ufbxi_check_err(&bc->error, ufbxi_bake_anim_prop(bc, element, prop_name, props + begin, end - begin));
+ begin = end;
+ }
+
+ size_t num_props = bc->tmp_props.num_items;
+ if (num_props > 0) {
+ ufbx_baked_element *baked_elem = ufbxi_push_zero(&bc->tmp_elements, ufbx_baked_element, 1);
+ ufbxi_check_err(&bc->error, baked_elem);
+
+ baked_elem->element_id = element->element_id;
+ baked_elem->props.count = num_props;
+ baked_elem->props.data = ufbxi_push_pop(&bc->result, &bc->tmp_props, ufbx_baked_prop, num_props);
+ ufbxi_check_err(&bc->error, baked_elem->props.data);
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline bool ufbxi_baked_node_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_baked_node *a = (const ufbx_baked_node*)va, *b = (const ufbx_baked_node*)vb;
+ return a->typed_id < b->typed_id;
+}
+
+static ufbxi_noinline bool ufbxi_baked_element_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_baked_element *a = (const ufbx_baked_element*)va, *b = (const ufbx_baked_element*)vb;
+ return a->element_id < b->element_id;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim(ufbxi_bake_context *bc)
+{
+ const ufbx_anim *anim = bc->anim;
+ const ufbx_scene *scene = bc->scene;
+
+ if (!bc->opts.skip_node_transforms) {
+ bc->baked_nodes = ufbxi_push_zero(&bc->result, ufbx_baked_node*, scene->nodes.count);
+ ufbxi_check_err(&bc->error, bc->baked_nodes);
+ bc->nodes_to_bake = ufbxi_push_zero(&bc->result, bool, scene->nodes.count);
+ ufbxi_check_err(&bc->error, bc->nodes_to_bake);
+ }
+
+ ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, anim->layers) {
+ ufbx_anim_layer *layer = *p_layer;
+
+ ufbxi_for_list(ufbx_anim_prop, anim_prop, layer->anim_props) {
+ ufbxi_bake_prop *prop = ufbxi_push(&bc->tmp_bake_props, ufbxi_bake_prop, 1);
+ ufbxi_check_err(&bc->error, prop);
+
+ ufbx_element *element = anim_prop->element;
+
+ // Sort nodes by `typed_id` to make sure we process them in order.
+ if (element->type == UFBX_ELEMENT_NODE) {
+ if (bc->nodes_to_bake) {
+ bc->nodes_to_bake[element->typed_id] = true;
+ }
+ prop->sort_id = element->typed_id;
+ } else {
+ prop->sort_id = UINT32_MAX;
+ }
+
+ prop->element_id = element->element_id;
+ prop->prop_name = anim_prop->prop_name.data;
+ prop->anim_value = anim_prop->anim_value;
+ }
+ }
+
+ size_t num_props = bc->tmp_bake_props.num_items;
+ ufbxi_bake_prop *props = ufbxi_push_pop(&bc->tmp, &bc->tmp_bake_props, ufbxi_bake_prop, num_props);
+ ufbxi_check_err(&bc->error, props);
+
+ ufbxi_unstable_sort(props, num_props, sizeof(ufbxi_bake_prop), &ufbxi_bake_prop_less, NULL);
+
+ // Pre-bake layer weight times
+ if (!bc->opts.ignore_layer_weight_animation) {
+ bool has_weight_times = false;
+ ufbxi_for(ufbxi_bake_prop, prop, props, num_props) {
+ if (prop->prop_name != ufbxi_Weight) continue;
+ ufbx_element *element = scene->elements.data[prop->element_id];
+ if (element->type == UFBX_ELEMENT_ANIM_LAYER) {
+ ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, true, 0));
+ has_weight_times = true;
+ }
+ }
+
+ if (has_weight_times) {
+ ufbxi_bake_time_list weight_times = { 0 };
+ ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &weight_times));
+
+ bc->layer_weight_times.count = weight_times.count;
+ bc->layer_weight_times.data = ufbxi_push_copy(&bc->tmp, ufbxi_bake_time, weight_times.count, weight_times.data);
+ ufbxi_check_err(&bc->error, bc->layer_weight_times.data);
+
+ ufbxi_buf_clear(&bc->tmp_prop);
+ }
+ }
+
+ size_t begin = 0;
+ while (begin < num_props) {
+ uint32_t element_id = props[begin].element_id;
+ size_t end = begin + 1;
+ while (end < num_props && props[end].element_id == element_id) {
+ end++;
+ }
+ ufbxi_check_err(&bc->error, ufbxi_bake_element(bc, element_id, props + begin, end - begin));
+ begin = end;
+ }
+
+ size_t num_nodes = bc->tmp_nodes.num_items;
+ size_t num_elements = bc->tmp_elements.num_items;
+
+ bc->bake.nodes.count = num_nodes;
+ bc->bake.nodes.data = ufbxi_push_pop(&bc->result, &bc->tmp_nodes, ufbx_baked_node, num_nodes);
+ ufbxi_check_err(&bc->error, bc->bake.nodes.data);
+
+ bc->bake.elements.count = num_elements;
+ bc->bake.elements.data = ufbxi_push_pop(&bc->result, &bc->tmp_elements, ufbx_baked_element, num_elements);
+ ufbxi_check_err(&bc->error, bc->bake.elements.data);
+
+ ufbxi_unstable_sort(bc->bake.nodes.data, bc->bake.nodes.count, sizeof(ufbx_baked_node), &ufbxi_baked_node_less, NULL);
+ ufbxi_unstable_sort(bc->bake.elements.data, bc->bake.elements.count, sizeof(ufbx_baked_element), &ufbxi_baked_element_less, NULL);
+
+ if (bc->time_min < bc->time_max) {
+ bc->bake.key_time_min = bc->time_min;
+ bc->bake.key_time_max = bc->time_max;
+ }
+
+ if (bc->time_begin < bc->time_end) {
+ bc->bake.playback_time_begin = bc->time_begin;
+ bc->bake.playback_time_end = bc->time_end;
+ bc->bake.playback_duration = bc->time_end - bc->time_begin;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim_imp(ufbxi_bake_context *bc, const ufbx_anim *anim)
+{
+ if (bc->opts.resample_rate <= 0.0) bc->opts.resample_rate = 30.0;
+ if (bc->opts.minimum_sample_rate <= 0.0) bc->opts.minimum_sample_rate = 19.5;
+ if (bc->opts.max_keyframe_segments == 0) bc->opts.max_keyframe_segments = 32;
+ if (bc->opts.key_reduction_threshold == 0) bc->opts.key_reduction_threshold = 0.000001;
+ if (bc->opts.key_reduction_passes == 0) bc->opts.key_reduction_passes = 4;
+
+ if (bc->opts.trim_start_time && anim->time_begin > 0.0) {
+ bc->ktime_offset = -anim->time_begin * (double)bc->scene->metadata.ktime_second;
+ }
+
+ ufbxi_init_ator(&bc->error, &bc->ator_tmp, &bc->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&bc->error, &bc->ator_result, &bc->opts.result_allocator, "result");
+
+ bc->result.unordered = true;
+ bc->result.ator = &bc->ator_result;
+
+ bc->tmp.unordered = true;
+ bc->tmp.ator = &bc->ator_tmp;
+
+ bc->tmp_prop.ator = &bc->ator_tmp;
+ bc->tmp_prop.unordered = true;
+ bc->tmp_prop.clearable = true;
+
+ bc->tmp_times.ator = &bc->ator_tmp;
+ bc->tmp_bake_props.ator = &bc->ator_tmp;
+ bc->tmp_nodes.ator = &bc->ator_tmp;
+ bc->tmp_elements.ator = &bc->ator_tmp;
+ bc->tmp_props.ator = &bc->ator_tmp;
+ bc->tmp_bake_stack.ator = &bc->ator_tmp;
+
+ bc->anim = anim;
+ if (anim->time_begin < anim->time_end) {
+ bc->time_begin = anim->time_begin;
+ bc->time_end = anim->time_end;
+ }
+ bc->time_min = UFBX_INFINITY;
+ bc->time_max = -UFBX_INFINITY;
+
+ bc->imp = ufbxi_push(&bc->result, ufbxi_baked_anim_imp, 1);
+ ufbxi_check_err(&bc->error, bc->imp);
+
+ ufbxi_check_err(&bc->error, ufbxi_bake_anim(bc));
+
+ ufbxi_init_ref(&bc->imp->refcount, UFBXI_BAKED_ANIM_IMP_MAGIC, NULL);
+
+ bc->bake.metadata.result_memory_used = bc->ator_result.current_size;
+ bc->bake.metadata.temp_memory_used = bc->ator_tmp.current_size;
+ bc->bake.metadata.result_allocs = bc->ator_result.num_allocs;
+ bc->bake.metadata.temp_allocs = bc->ator_tmp.num_allocs;
+
+ bc->imp->magic = UFBXI_BAKED_ANIM_IMP_MAGIC;
+ bc->imp->bake = bc->bake;
+ bc->imp->refcount.ator = bc->ator_result;
+ bc->imp->refcount.buf = bc->result;
+
+ return 1;
+}
+
+#endif
+
+// -- NURBS
+
+static ufbxi_forceinline ufbx_real ufbxi_nurbs_weight(const ufbx_real_list *knots, size_t knot, size_t degree, ufbx_real u)
+{
+ if (knot >= knots->count) return 0.0f;
+ if (knots->count - knot < degree) return 0.0f;
+ ufbx_real prev_u = knots->data[knot], next_u = knots->data[knot + degree];
+ if (prev_u >= next_u) return 0.0f;
+ if (u <= prev_u) return 0.0f;
+ if (u >= next_u) return 1.0f;
+ return (u - prev_u) / (next_u - prev_u);
+}
+
+static ufbxi_forceinline ufbx_real ufbxi_nurbs_deriv(const ufbx_real_list *knots, size_t knot, size_t degree)
+{
+ if (knot >= knots->count) return 0.0f;
+ if (knots->count - knot < degree) return 0.0f;
+ ufbx_real prev_u = knots->data[knot], next_u = knots->data[knot + degree];
+ if (prev_u >= next_u) return 0.0f;
+ return (ufbx_real)degree / (next_u - prev_u);
+}
+
+typedef struct {
+ ufbxi_refcount refcount;
+ ufbx_line_curve curve;
+ uint32_t magic;
+} ufbxi_line_curve_imp;
+
+ufbx_static_assert(line_curve_imp_offset, offsetof(ufbxi_line_curve_imp, curve) == sizeof(ufbxi_refcount));
+
+#if UFBXI_FEATURE_TESSELLATION
+
+typedef struct {
+ ufbx_error error;
+
+ ufbx_tessellate_curve_opts opts;
+
+ const ufbx_nurbs_curve *curve;
+
+ ufbxi_allocator ator_tmp;
+ ufbxi_allocator ator_result;
+
+ ufbxi_buf result;
+
+ ufbx_line_curve line;
+
+ ufbxi_line_curve_imp *imp;
+
+} ufbxi_tessellate_curve_context;
+
+typedef struct {
+ ufbx_error error;
+
+ ufbx_tessellate_surface_opts opts;
+
+ const ufbx_nurbs_surface *surface;
+
+ ufbxi_allocator ator_tmp;
+ ufbxi_allocator ator_result;
+
+ ufbxi_buf tmp;
+ ufbxi_buf result;
+
+ ufbxi_map position_map;
+
+ ufbx_mesh mesh;
+
+ ufbxi_mesh_imp *imp;
+
+} ufbxi_tessellate_surface_context;
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_tessellate_nurbs_curve_imp(ufbxi_tessellate_curve_context *tc)
+{
+ if (tc->opts.span_subdivision <= 0) {
+ tc->opts.span_subdivision = 4;
+ }
+ size_t num_sub = tc->opts.span_subdivision;
+
+ const ufbx_nurbs_curve *curve = tc->curve;
+ ufbx_line_curve *line = &tc->line;
+ ufbxi_check_err_msg(&tc->error, curve->basis.valid && curve->control_points.count > 0, "Bad NURBS geometry");
+
+ ufbxi_init_ator(&tc->error, &tc->ator_tmp, &tc->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&tc->error, &tc->ator_result, &tc->opts.result_allocator, "result");
+
+ tc->result.unordered = true;
+ tc->result.ator = &tc->ator_result;
+
+ size_t num_spans = curve->basis.spans.count;
+
+ // Check conservatively that we don't overflow anything
+ {
+ size_t over_spans = num_spans * 2 * sizeof(ufbx_real);
+ size_t over = over_spans * num_sub;
+ ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over, over_spans, num_sub));
+ }
+
+ bool is_open = curve->basis.topology == UFBX_NURBS_TOPOLOGY_OPEN;
+
+ size_t num_indices = num_spans + (num_spans - 1) * (num_sub - 1);
+ size_t num_vertices = num_indices - (is_open ? 0u : 1u);
+ ufbxi_check_err(&tc->error, num_indices <= INT32_MAX);
+
+ uint32_t *indices = ufbxi_push(&tc->result, uint32_t, num_indices);
+ ufbx_vec3 *vertices = ufbxi_push(&tc->result, ufbx_vec3, num_vertices);
+ ufbx_line_segment *segments = ufbxi_push(&tc->result, ufbx_line_segment, 1);
+ ufbxi_check_err(&tc->error, indices && vertices && segments);
+
+ for (size_t span_ix = 0; span_ix < num_spans; span_ix++) {
+ size_t num_splits = span_ix + 1 == num_spans ? 1 : num_sub;
+
+ for (size_t sub_ix = 0; sub_ix < num_splits; sub_ix++) {
+ size_t ix = span_ix * num_sub + sub_ix;
+
+ if (ix < num_vertices) {
+ ufbx_real u = curve->basis.spans.data[span_ix];
+ if (sub_ix > 0) {
+ ufbx_real t = (ufbx_real)sub_ix / (ufbx_real)num_sub;
+ u = u * (1.0f - t) + t * curve->basis.spans.data[span_ix + 1];
+ }
+
+ ufbx_curve_point point = ufbx_evaluate_nurbs_curve(curve, u);
+ vertices[ix] = point.position;
+ indices[ix] = (uint32_t)ix;
+ } else {
+ indices[ix] = 0;
+ }
+ }
+ }
+
+ segments[0].index_begin = 0;
+ segments[0].num_indices = (uint32_t)num_indices;
+
+ line->element.name.data = ufbxi_empty_char;
+ line->element.type = UFBX_ELEMENT_LINE_CURVE;
+ line->element.typed_id = UINT32_MAX;
+ line->element.element_id = UINT32_MAX;
+
+ line->color.x = 1.0f;
+ line->color.y = 1.0f;
+ line->color.z = 1.0f;
+
+ line->control_points.data = vertices;
+ line->control_points.count = num_vertices;
+ line->point_indices.data = indices;
+ line->point_indices.count = num_indices;
+ line->segments.data = segments;
+ line->segments.count = 1;
+
+ line->from_tessellated_nurbs = true;
+
+ tc->imp = ufbxi_push(&tc->result, ufbxi_line_curve_imp, 1);
+ ufbxi_check_err(&tc->error, tc->imp);
+
+ ufbxi_init_ref(&tc->imp->refcount, UFBXI_LINE_CURVE_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, curve->element.scene))->refcount);
+
+ tc->imp->magic = UFBXI_LINE_CURVE_IMP_MAGIC;
+ tc->imp->curve = tc->line;
+ tc->imp->refcount.ator = tc->ator_result;
+ tc->imp->refcount.buf = tc->result;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_tessellate_nurbs_surface_imp(ufbxi_tessellate_surface_context *tc)
+{
+ if (tc->opts.span_subdivision_u <= 0) {
+ tc->opts.span_subdivision_u = 4;
+ }
+ if (tc->opts.span_subdivision_v <= 0) {
+ tc->opts.span_subdivision_v = 4;
+ }
+
+ size_t sub_u = tc->opts.span_subdivision_u;
+ size_t sub_v = tc->opts.span_subdivision_v;
+
+ const ufbx_nurbs_surface *surface = tc->surface;
+ ufbx_mesh *mesh = &tc->mesh;
+ ufbxi_check_err_msg(&tc->error, surface->basis_u.valid && surface->basis_v.valid
+ && surface->num_control_points_u > 0 && surface->num_control_points_v > 0, "Bad NURBS geometry");
+
+ ufbxi_init_ator(&tc->error, &tc->ator_tmp, &tc->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&tc->error, &tc->ator_result, &tc->opts.result_allocator, "result");
+
+ tc->result.unordered = true;
+ tc->tmp.unordered = true;
+
+ tc->result.ator = &tc->ator_result;
+ tc->tmp.ator = &tc->ator_tmp;
+
+ bool open_u = surface->basis_u.topology == UFBX_NURBS_TOPOLOGY_OPEN;
+ bool open_v = surface->basis_v.topology == UFBX_NURBS_TOPOLOGY_OPEN;
+
+ size_t spans_u = surface->basis_u.spans.count;
+ size_t spans_v = surface->basis_v.spans.count;
+
+ // Check conservatively that we don't overflow anything
+ {
+ size_t over_spans_u = spans_u * 2 * sizeof(ufbx_real);
+ size_t over_spans_v = spans_v * 2 * sizeof(ufbx_real);
+ size_t over_u = over_spans_u * sub_u;
+ size_t over_v = over_spans_v * sub_v;
+ size_t over_uv = over_u * over_v;
+ ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_u, over_spans_u, sub_u));
+ ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_v, over_spans_v, sub_v));
+ ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_uv, over_u, over_v));
+ }
+
+ size_t faces_u = (spans_u - 1) * sub_u;
+ size_t faces_v = (spans_v - 1) * sub_v;
+
+ size_t indices_u = spans_u + (spans_u - 1) * (sub_u - 1);
+ size_t indices_v = spans_v + (spans_v - 1) * (sub_v - 1);
+
+ size_t num_faces = faces_u * faces_v;
+ size_t num_indices = indices_u * indices_v;
+ ufbxi_check_err(&tc->error, num_indices <= INT32_MAX);
+
+ uint32_t *position_ix = ufbxi_push(&tc->tmp, uint32_t, num_indices);
+ ufbx_vec3 *positions = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
+ ufbx_vec3 *normals = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
+ ufbx_vec2 *uvs = ufbxi_push(&tc->result, ufbx_vec2, num_indices + 1);
+ ufbx_vec3 *tangents = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
+ ufbx_vec3 *bitangents = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
+ ufbxi_check_err(&tc->error, position_ix && uvs && tangents && bitangents);
+
+ *positions++ = ufbx_zero_vec3;
+ *normals++ = ufbx_zero_vec3;
+ *uvs++ = ufbx_zero_vec2;
+ *tangents++ = ufbx_zero_vec3;
+ *bitangents++ = ufbx_zero_vec3;
+
+ uint32_t num_positions = 0;
+
+ for (size_t span_v = 0; span_v < spans_v; span_v++) {
+ size_t splits_v = span_v + 1 == spans_v ? 1 : sub_v;
+
+ for (size_t split_v = 0; split_v < splits_v; split_v++) {
+ size_t ix_v = span_v * sub_v + split_v;
+ ufbx_assert(ix_v < indices_v);
+
+ ufbx_real v = surface->basis_v.spans.data[span_v];
+ if (split_v > 0) {
+ ufbx_real t = (ufbx_real)split_v / (ufbx_real)splits_v;
+ v = v * (1.0f - t) + t * surface->basis_v.spans.data[span_v + 1];
+ }
+ ufbx_real original_v = v;
+ if (span_v + 1 == spans_v && !open_v) {
+ v = surface->basis_v.spans.data[0];
+ }
+
+ for (size_t span_u = 0; span_u < spans_u; span_u++) {
+ size_t splits_u = span_u + 1 == spans_u ? 1 : sub_u;
+ for (size_t split_u = 0; split_u < splits_u; split_u++) {
+ size_t ix_u = span_u * sub_u + split_u;
+ ufbx_assert(ix_u < indices_u);
+
+ ufbx_real u = surface->basis_u.spans.data[span_u];
+ if (split_u > 0) {
+ ufbx_real t = (ufbx_real)split_u / (ufbx_real)splits_u;
+ u = u * (1.0f - t) + t * surface->basis_u.spans.data[span_u + 1];
+ }
+ ufbx_real original_u = u;
+ if (span_u + 1 == spans_u && !open_u) {
+ u = surface->basis_u.spans.data[0];
+ }
+
+ ufbx_surface_point point = ufbx_evaluate_nurbs_surface(surface, u, v);
+ ufbx_vec3 pos = point.position;
+
+ ufbx_vec3 tangent_u = ufbxi_slow_normalize3(&point.derivative_u);
+ ufbx_vec3 tangent_v = ufbxi_slow_normalize3(&point.derivative_v);
+
+ // Check if there's any wrapped positions that we could match
+ size_t neighbors[5]; // ufbxi_uninit
+ size_t num_neighbors = 0;
+
+ if ((span_v == 0 && (span_u > 0 || split_u > 0)) || (span_u == 0 && (span_v > 0 || split_v > 0))) {
+ // Top/left
+ neighbors[num_neighbors++] = 0;
+ }
+ if (span_v + 1 == spans_v) {
+ // Bottom
+ neighbors[num_neighbors++] = ix_u;
+ if (span_u > 0 || split_u > 0) {
+ neighbors[num_neighbors++] = ix_v * indices_u;
+ }
+ }
+ if (span_u + 1 == spans_u) {
+ // Right
+ neighbors[num_neighbors++] = ix_v * indices_u;
+ if (span_v > 0 || split_v > 0) {
+ neighbors[num_neighbors++] = indices_u - 1;
+ }
+ }
+
+ size_t ix = ix_v * indices_u + ix_u;
+
+ uint32_t pos_ix = num_positions;
+ for (size_t i = 0; i < num_neighbors; i++) {
+ size_t nb_ix = neighbors[i];
+ ufbx_assert(nb_ix < ix);
+ uint32_t nb_pos_ix = position_ix[nb_ix];
+ ufbx_vec3 nb_pos = positions[nb_pos_ix];
+ ufbx_real dx = nb_pos.x - pos.x;
+ ufbx_real dy = nb_pos.y - pos.y;
+ ufbx_real dz = nb_pos.z - pos.z;
+ ufbx_real delta = dx*dx + dy*dy + dz*dz;
+ if (delta < 0.0000001f) { // TODO: Configurable / something more rigorous
+ pos_ix = nb_pos_ix;
+ break;
+ }
+ }
+
+ position_ix[ix] = pos_ix;
+ if (pos_ix == num_positions) {
+ positions[pos_ix] = pos;
+ num_positions = pos_ix + 1;
+ }
+ uvs[ix].x = original_u;
+ uvs[ix].y = original_v;
+ tangents[ix] = tangent_u;
+ bitangents[ix] = tangent_v;
+ }
+ }
+ }
+ }
+
+ ufbx_face *faces = ufbxi_push(&tc->result, ufbx_face, num_faces);
+ uint32_t *vertex_ix = ufbxi_push(&tc->result, uint32_t, num_faces * 4);
+ uint32_t *attrib_ix = ufbxi_push(&tc->result, uint32_t, num_faces * 4);
+ ufbxi_check_err(&tc->error, faces && vertex_ix && attrib_ix);
+
+ size_t face_ix = 0;
+ size_t dst_index = 0;
+
+ size_t num_triangles = 0;
+
+ for (size_t face_v = 0; face_v < faces_v; face_v++) {
+ for (size_t face_u = 0; face_u < faces_u; face_u++) {
+
+ attrib_ix[dst_index + 0] = (uint32_t)((face_v + 0) * indices_u + (face_u + 0));
+ attrib_ix[dst_index + 1] = (uint32_t)((face_v + 0) * indices_u + (face_u + 1));
+ attrib_ix[dst_index + 2] = (uint32_t)((face_v + 1) * indices_u + (face_u + 1));
+ attrib_ix[dst_index + 3] = (uint32_t)((face_v + 1) * indices_u + (face_u + 0));
+
+ vertex_ix[dst_index + 0] = position_ix[attrib_ix[dst_index + 0]];
+ vertex_ix[dst_index + 1] = position_ix[attrib_ix[dst_index + 1]];
+ vertex_ix[dst_index + 2] = position_ix[attrib_ix[dst_index + 2]];
+ vertex_ix[dst_index + 3] = position_ix[attrib_ix[dst_index + 3]];
+
+ bool is_triangle = false;
+ for (size_t prev_ix = 0; prev_ix < 4; prev_ix++) {
+ size_t next_ix = (prev_ix + 1) % 4;
+ if (vertex_ix[dst_index + prev_ix] == vertex_ix[dst_index + next_ix]) {
+ for (size_t i = next_ix; i < 3; i++) {
+ attrib_ix[dst_index + i] = attrib_ix[dst_index + i + 1];
+ vertex_ix[dst_index + i] = vertex_ix[dst_index + i + 1];
+ }
+ is_triangle = true;
+ break;
+ }
+ }
+
+ faces[face_ix].index_begin = (uint32_t)dst_index;
+ faces[face_ix].num_indices = is_triangle ? 3 : 4;
+ dst_index += is_triangle ? 3 : 4;
+ num_triangles += is_triangle ? 1 : 2;
+ face_ix++;
+ }
+ }
+
+ ufbxi_check_err(&tc->error, positions && normals);
+
+ mesh->element.name.data = ufbxi_empty_char;
+ mesh->element.type = UFBX_ELEMENT_MESH;
+ mesh->element.typed_id = UINT32_MAX;
+ mesh->element.element_id = UINT32_MAX;
+
+ mesh->vertices.data = positions;
+ mesh->vertices.count = num_positions;
+ mesh->num_vertices = num_positions;
+ mesh->vertex_indices.data = vertex_ix;
+ mesh->vertex_indices.count = dst_index;
+
+ mesh->faces.data = faces;
+ mesh->faces.count = num_faces;
+
+ mesh->vertex_position.exists = true;
+ mesh->vertex_position.values.data = positions;
+ mesh->vertex_position.values.count = num_positions;
+ mesh->vertex_position.indices.data = vertex_ix;
+ mesh->vertex_position.indices.count = dst_index;
+ mesh->vertex_position.unique_per_vertex = true;
+
+ mesh->vertex_uv.exists = true;
+ mesh->vertex_uv.values.data = uvs;
+ mesh->vertex_uv.values.count = dst_index;
+ mesh->vertex_uv.indices.data = attrib_ix;
+ mesh->vertex_uv.indices.count = dst_index;
+
+ mesh->vertex_normal.exists = true;
+ mesh->vertex_normal.values.data = normals;
+ mesh->vertex_normal.values.count = num_positions;
+ mesh->vertex_normal.indices.data = vertex_ix;
+ mesh->vertex_normal.indices.count = dst_index;
+
+ mesh->vertex_tangent.exists = true;
+ mesh->vertex_tangent.values.data = tangents;
+ mesh->vertex_tangent.values.count = dst_index;
+ mesh->vertex_tangent.indices.data = attrib_ix;
+ mesh->vertex_tangent.indices.count = dst_index;
+
+ mesh->vertex_bitangent.exists = true;
+ mesh->vertex_bitangent.values.data = bitangents;
+ mesh->vertex_bitangent.values.count = dst_index;
+ mesh->vertex_bitangent.indices.data = attrib_ix;
+ mesh->vertex_bitangent.indices.count = dst_index;
+
+ mesh->num_faces = num_faces;
+ mesh->num_triangles = num_triangles;
+ mesh->num_indices = dst_index;
+ mesh->max_face_triangles = 2;
+
+ if (surface->material) {
+ mesh->face_material.data = ufbxi_push_zero(&tc->result, uint32_t, num_faces);
+ ufbxi_check_err(&tc->error, mesh->face_material.data);
+
+ ufbx_material **mat = ufbxi_push_zero(&tc->result, ufbx_material*, 1);
+ ufbxi_check_err(&tc->error, mat);
+
+ *mat = surface->material;
+ mesh->materials.data = mat;
+ mesh->materials.count = 1;
+ }
+
+ if (!tc->opts.skip_mesh_parts) {
+ mesh->material_parts.count = 1;
+ mesh->material_parts.data = ufbxi_push_zero(&tc->result, ufbx_mesh_part, 1);
+ ufbxi_check_err(&tc->error, mesh->material_parts.data);
+ }
+
+ ufbxi_check_err(&tc->error, ufbxi_finalize_mesh_material(&tc->result, &tc->error, mesh));
+ ufbxi_check_err(&tc->error, ufbxi_finalize_mesh(&tc->result, &tc->error, mesh));
+
+ mesh->generated_normals = true;
+ ufbx_compute_normals(mesh, &mesh->vertex_position,
+ mesh->vertex_normal.indices.data, mesh->vertex_normal.indices.count,
+ mesh->vertex_normal.values.data, mesh->vertex_normal.values.count);
+
+ if (surface->flip_normals) {
+ ufbxi_nounroll ufbxi_for_list(ufbx_vec3, normal, mesh->vertex_normal.values) {
+ normal->x *= -1.0f;
+ normal->y *= -1.0f;
+ normal->z *= -1.0f;
+ }
+ }
+
+ tc->imp = ufbxi_push(&tc->result, ufbxi_mesh_imp, 1);
+ ufbxi_check_err(&tc->error, tc->imp);
+
+ ufbxi_init_ref(&tc->imp->refcount, UFBXI_MESH_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, surface->element.scene))->refcount);
+
+ tc->imp->magic = UFBXI_MESH_IMP_MAGIC;
+ tc->imp->mesh = tc->mesh;
+ tc->imp->refcount.ator = tc->ator_result;
+ tc->imp->refcount.buf = tc->result;
+ tc->imp->mesh.subdivision_evaluated = true;
+
+ return 1;
+}
+
+#endif
+
+// -- Topology
+
+#if UFBXI_FEATURE_KD
+
+typedef struct {
+ ufbx_real split;
+ uint32_t index_plus_one; // 0 for empty
+ uint32_t slow_left;
+ uint32_t slow_right;
+ uint32_t slow_end;
+} ufbxi_kd_node;
+
+typedef struct {
+ ufbx_face face;
+ ufbx_vertex_vec3 positions;
+ ufbx_vec3 axes[3];
+ ufbxi_kd_node kd_nodes[1 << (UFBXI_KD_FAST_DEPTH + 1)];
+ uint32_t *kd_indices;
+
+ // Temporary
+ ufbx_vec3 cur_axis_dir;
+ ufbx_face cur_face;
+} ufbxi_ngon_context;
+
+typedef struct {
+ ufbx_real min_t[2];
+ ufbx_real max_t[2];
+ ufbx_vec2 points[3];
+ uint32_t indices[3];
+} ufbxi_kd_triangle;
+
+ufbxi_noinline static ufbx_vec2 ufbxi_ngon_project(ufbxi_ngon_context *nc, uint32_t index)
+{
+ ufbx_vec3 point = nc->positions.values.data[nc->positions.indices.data[nc->face.index_begin + index]];
+
+ ufbx_vec2 p;
+ p.x = ufbxi_dot3(nc->axes[0], point);
+ p.y = ufbxi_dot3(nc->axes[1], point);
+ return p;
+}
+
+ufbxi_forceinline static ufbx_real ufbxi_orient2d(ufbx_vec2 a, ufbx_vec2 b, ufbx_vec2 c)
+{
+ return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
+}
+
+ufbxi_noinline static bool ufbxi_kd_check_point(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t index)
+{
+ if (index == tri->indices[0] || index == tri->indices[1] || index == tri->indices[2]) return false;
+ ufbx_vec2 p = ufbxi_ngon_project(nc, index);
+
+ ufbx_real u = ufbxi_orient2d(p, tri->points[0], tri->points[1]);
+ ufbx_real v = ufbxi_orient2d(p, tri->points[1], tri->points[2]);
+ ufbx_real w = ufbxi_orient2d(p, tri->points[2], tri->points[0]);
+
+ if (u <= 0.0f && v <= 0.0f && w <= 0.0f) return true;
+ if (u >= 0.0f && v >= 0.0f && w >= 0.0f) return true;
+ return false;
+}
+
+// Recursion limited by 32-bit indices in input, minus halvings from `ufbxi_kd_check_fast()`
+ufbxi_noinline static bool ufbxi_kd_check_slow(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t begin, uint32_t count, uint32_t axis)
+ ufbxi_recursive_function(bool, ufbxi_kd_check_slow, (nc, tri, begin, count, axis), 32 - UFBXI_KD_FAST_DEPTH,
+ (ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t begin, uint32_t count, uint32_t axis))
+{
+ ufbx_vertex_vec3 pos = nc->positions;
+ uint32_t *kd_indices = nc->kd_indices;
+
+ while (count > 0) {
+ uint32_t num_left = count / 2;
+ uint32_t begin_right = begin + num_left + 1;
+ uint32_t num_right = count - (num_left + 1);
+
+ uint32_t index = kd_indices[begin + num_left];
+ ufbx_vec3 point = pos.values.data[pos.indices.data[nc->face.index_begin + index]];
+ ufbx_real split = ufbxi_dot3(point, nc->axes[axis]);
+ bool hit_left = tri->min_t[axis] <= split;
+ bool hit_right = tri->max_t[axis] >= split;
+
+ if (hit_left && hit_right) {
+ if (ufbxi_kd_check_point(nc, tri, index)) {
+ return true;
+ }
+
+ if (ufbxi_kd_check_slow(nc, tri, begin_right, num_right, axis ^ 1)) {
+ return true;
+ }
+ }
+
+ axis ^= 1;
+ if (hit_left) {
+ count = num_left;
+ } else {
+ begin = begin_right;
+ count = num_right;
+ }
+ }
+
+ return false;
+}
+
+// Recursion limited by `UFBXI_KD_FAST_DEPTH`
+ufbxi_noinline static bool ufbxi_kd_check_fast(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t kd_index, uint32_t axis, uint32_t depth)
+ ufbxi_recursive_function(bool, ufbxi_kd_check_fast, (nc, tri, kd_index, axis, depth), UFBXI_KD_FAST_DEPTH,
+ (ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t kd_index, uint32_t axis, uint32_t depth))
+{
+ for (;;) {
+ ufbxi_kd_node node = nc->kd_nodes[kd_index];
+ if (node.index_plus_one == 0) return false;
+
+ bool hit_left = tri->min_t[axis] <= node.split;
+ bool hit_right = tri->max_t[axis] >= node.split;
+
+ uint32_t side = hit_left ? 0 : 1;
+ uint32_t child_kd_index = kd_index * 2 + 1 + side;
+ if (hit_left && hit_right) {
+
+ // Check for the point on the split plane
+ uint32_t index = node.index_plus_one - 1;
+ if (ufbxi_kd_check_point(nc, tri, index)) {
+ return true;
+ }
+
+ // Recurse always to the right if we hit both sides
+ if (depth + 1 == UFBXI_KD_FAST_DEPTH) {
+ if (ufbxi_kd_check_slow(nc, tri, node.slow_right, node.slow_end - node.slow_right, axis ^ 1)) {
+ return true;
+ }
+ } else {
+ if (ufbxi_kd_check_fast(nc, tri, child_kd_index + 1, axis ^ 1, depth + 1)) {
+ return true;
+ }
+ }
+ }
+
+ depth++;
+ axis ^= 1;
+ kd_index = child_kd_index;
+
+ if (depth == UFBXI_KD_FAST_DEPTH) {
+ if (hit_left) {
+ return ufbxi_kd_check_slow(nc, tri, node.slow_left, node.slow_right - node.slow_left, axis);
+ } else {
+ return ufbxi_kd_check_slow(nc, tri, node.slow_right, node.slow_end - node.slow_right, axis);
+ }
+ }
+ }
+}
+
+ufbxi_noinline static bool ufbxi_kd_check(ufbxi_ngon_context *nc, const ufbx_vec2 *points, const uint32_t *indices)
+{
+ ufbxi_kd_triangle tri; // ufbxi_uninit
+ tri.points[0] = points[0];
+ tri.points[1] = points[1];
+ tri.points[2] = points[2];
+ tri.indices[0] = indices[0];
+ tri.indices[1] = indices[1];
+ tri.indices[2] = indices[2];
+ tri.min_t[0] = ufbxi_min_real(ufbxi_min_real(points[0].x, points[1].x), points[2].x);
+ tri.min_t[1] = ufbxi_min_real(ufbxi_min_real(points[0].y, points[1].y), points[2].y);
+ tri.max_t[0] = ufbxi_max_real(ufbxi_max_real(points[0].x, points[1].x), points[2].x);
+ tri.max_t[1] = ufbxi_max_real(ufbxi_max_real(points[0].y, points[1].y), points[2].y);
+ return ufbxi_kd_check_fast(nc, &tri, 0, 0, 0);
+}
+
+ufbxi_noinline static bool ufbxi_kd_index_less(void *user, const void *va, const void *vb)
+{
+ ufbxi_ngon_context *nc = (ufbxi_ngon_context*)user;
+ ufbx_vertex_vec3 *pos = &nc->positions;
+ const uint32_t a = *(const uint32_t*)va, b = *(const uint32_t*)vb;
+ ufbx_real da = ufbxi_dot3(nc->cur_axis_dir, pos->values.data[pos->indices.data[nc->cur_face.index_begin + a]]);
+ ufbx_real db = ufbxi_dot3(nc->cur_axis_dir, pos->values.data[pos->indices.data[nc->cur_face.index_begin + b]]);
+ return da < db;
+}
+
+// Recursion limited by 32-bit indices in input
+ufbxi_noinline static void ufbxi_kd_build(ufbxi_ngon_context *nc, uint32_t *indices, uint32_t *tmp, uint32_t num, uint32_t axis, uint32_t fast_index, uint32_t depth)
+ ufbxi_recursive_function_void(ufbxi_kd_build, (nc, indices, tmp, num, axis, fast_index, depth), 32,
+ (ufbxi_ngon_context *nc, uint32_t *indices, uint32_t *tmp, uint32_t num, uint32_t axis, uint32_t fast_index, uint32_t depth))
+{
+ if (num == 0) return;
+
+ ufbx_vertex_vec3 pos = nc->positions;
+ ufbx_vec3 axis_dir = nc->axes[axis];
+ ufbx_face face = nc->face;
+
+ nc->cur_axis_dir = axis_dir;
+ nc->cur_face = face;
+
+ // Sort the remaining indices based on the axis
+ ufbxi_stable_sort(sizeof(uint32_t), 16, indices, tmp, num, &ufbxi_kd_index_less, nc);
+
+ uint32_t num_left = num / 2;
+ uint32_t begin_right = num_left + 1;
+ uint32_t num_right = num - begin_right;
+ uint32_t dst_right = num_left + 1;
+ if (depth < UFBXI_KD_FAST_DEPTH) {
+ uint32_t skip_left = 1u << (UFBXI_KD_FAST_DEPTH - depth - 1);
+ dst_right = dst_right > skip_left ? dst_right - skip_left : 0;
+
+ uint32_t index = indices[num_left];
+ ufbxi_kd_node *kd = &nc->kd_nodes[fast_index];
+
+ kd->split = ufbxi_dot3(axis_dir, pos.values.data[pos.indices.data[face.index_begin + index]]);
+ kd->index_plus_one = index + 1;
+
+ if (depth + 1 == UFBXI_KD_FAST_DEPTH) {
+ kd->slow_left = (uint32_t)(indices - nc->kd_indices);
+ kd->slow_right = kd->slow_left + num_left;
+ kd->slow_end = kd->slow_right + num_right;
+ } else {
+ kd->slow_left = UINT32_MAX;
+ kd->slow_right = UINT32_MAX;
+ kd->slow_end = UINT32_MAX;
+ }
+ }
+
+ uint32_t child_fast = fast_index * 2 + 1;
+ ufbxi_kd_build(nc, indices, tmp, num_left, axis ^ 1, child_fast + 0, depth + 1);
+
+ if (dst_right != begin_right) {
+ memmove(indices + dst_right, indices + begin_right, num_right * sizeof(uint32_t));
+ }
+
+ ufbxi_kd_build(nc, indices + dst_right, tmp, num_right, axis ^ 1, child_fast + 1, depth + 1);
+}
+
+#endif
+
+#if UFBXI_FEATURE_TRIANGULATION
+
+ufbxi_noinline static ufbx_real ufbxi_ngon_tri_weight(const ufbx_vec2 *points)
+{
+ ufbx_vec2 p0 = points[0], p1 = points[1], p2 = points[2];
+ ufbx_real orient = ufbxi_orient2d(p0, p1, p2);
+ if (orient <= 0.0f) return -1.0f;
+
+ ufbx_real a = ufbxi_distsq2(p0, p1);
+ ufbx_real b = ufbxi_distsq2(p1, p2);
+ ufbx_real c = ufbxi_distsq2(p2, p0);
+ ufbx_real ab = (a + b - c) / (ufbx_real)ufbx_sqrt(4.0f * a * b);
+ ufbx_real bc = (b + c - a) / (ufbx_real)ufbx_sqrt(4.0f * b * c);
+ ufbx_real ca = (c + a - b) / (ufbx_real)ufbx_sqrt(4.0f * c * a);
+ return (ufbx_real)ufbx_fmax(UFBX_EPSILON, 2.0f - ufbx_fmax(ufbx_fmax(ab, bc), ca));
+}
+
+ufbxi_noinline static uint32_t ufbxi_triangulate_ngon(ufbxi_ngon_context *nc, uint32_t *indices, uint32_t num_indices)
+{
+ ufbx_face face = nc->face;
+ ufbx_assert(face.num_indices > 4);
+
+ // Form an orthonormal basis to project the polygon into a 2D plane
+ ufbx_vec3 normal = ufbx_get_weighted_face_normal(&nc->positions, face);
+ ufbx_real len = ufbxi_length3(normal);
+ if (len > UFBX_EPSILON) {
+ normal = ufbxi_mul3(normal, 1.0f / len);
+ } else {
+ normal.x = 1.0f;
+ normal.y = 0.0f;
+ normal.z = 0.0f;
+ }
+
+ ufbx_vec3 axis; // ufbxi_uninit
+ if (normal.x*normal.x < 0.5f) {
+ axis.x = 1.0f;
+ axis.y = 0.0f;
+ axis.z = 0.0f;
+ } else {
+ axis.x = 0.0f;
+ axis.y = 1.0f;
+ axis.z = 0.0f;
+ }
+ nc->axes[0] = ufbxi_slow_normalized_cross3(&axis, &normal);
+ nc->axes[1] = ufbxi_slow_normalized_cross3(&normal, &nc->axes[0]);
+ nc->axes[2] = normal;
+
+ uint32_t *kd_indices = indices;
+ nc->kd_indices = kd_indices;
+
+ uint32_t *kd_tmp = indices + face.num_indices;
+
+ // Collect all the reflex corners for intersection testing.
+ uint32_t num_kd_indices = 0;
+ {
+ ufbx_vec2 a = ufbxi_ngon_project(nc, face.num_indices - 1);
+ ufbx_vec2 b = ufbxi_ngon_project(nc, 0);
+ for (uint32_t i = 0; i < face.num_indices; i++) {
+ uint32_t next = i + 1 < face.num_indices ? i + 1 : 0;
+ ufbx_vec2 c = ufbxi_ngon_project(nc, next);
+
+ if (ufbxi_orient2d(a, b, c) <= 0.0f) {
+ kd_indices[num_kd_indices++] = i;
+ }
+
+ a = b;
+ b = c;
+ }
+ }
+
+ // Build a KD-tree of the vertices.
+ uint32_t num_skip_indices = (1u << (UFBXI_KD_FAST_DEPTH + 1)) - 1;
+ uint32_t kd_slow_indices = num_kd_indices > num_skip_indices ? num_kd_indices - num_skip_indices : 0;
+ ufbxi_ignore(kd_slow_indices);
+ ufbx_assert(kd_slow_indices + face.num_indices * 2 <= num_indices);
+ ufbxi_kd_build(nc, kd_indices, kd_tmp, num_kd_indices, 0, 0, 0);
+
+ uint32_t *edges = indices + num_indices - face.num_indices * 2;
+
+ // Initialize `edges` to be a connectivity structure where:
+ // `edges[2*i + 0]` is the previous vertex of `i`
+ // `edges[2*i + 1]` is the next vertex of `i`
+ // When clipped we mark indices with the high bit (0x80000000)
+ for (uint32_t i = 0; i < face.num_indices; i++) {
+ edges[i*2 + 0] = i > 0 ? i - 1 : face.num_indices - 1;
+ edges[i*2 + 1] = i + 1 < face.num_indices ? i + 1 : 0;
+ }
+
+ // Core of the ear clipping algorithm.
+ // Iterate through the polygon corners looking for potential ears satisfying:
+ // - Angle must be less than 180deg
+ // - The triangle formed by the two edges must be contained within the polygon
+ // As these properties change only locally between modifications we only need
+ // to iterate the polygon once if we move backwards one step every time we clip an ear.
+ uint32_t indices_left = face.num_indices;
+ {
+ uint32_t point_indices[4] = { 0, 1, 2, 3 };
+ ufbx_real weights[2]; // ufbxi_uninit
+ ufbx_vec2 points[4]; // ufbxi_uninit
+
+ uint32_t num_steps = 0;
+ while (indices_left > 3) {
+ points[0] = ufbxi_ngon_project(nc, point_indices[0]);
+ points[1] = ufbxi_ngon_project(nc, point_indices[1]);
+ points[2] = ufbxi_ngon_project(nc, point_indices[2]);
+ points[3] = ufbxi_ngon_project(nc, point_indices[3]);
+
+ weights[0] = ufbxi_ngon_tri_weight(points + 0);
+ weights[1] = ufbxi_ngon_tri_weight(points + 1);
+
+ uint32_t first_side = weights[1] > weights[0] ? 1 : 0;
+ bool clipped = false;
+ ufbxi_nounroll for (uint32_t side_ix = 0; side_ix < 2; side_ix++) {
+ uint32_t side = side_ix ^ first_side;
+ if (!(weights[side] >= 0.0f)) break;
+
+ // If there is no reflex angle contained within the triangle formed
+ // by `{ a, b, c }` connect the vertices `a - c` (prev, next) directly.
+ if (!ufbxi_kd_check(nc, points + side, point_indices + side)) {
+ uint32_t ia = point_indices[side + 0];
+ uint32_t ib = point_indices[side + 1];
+ uint32_t ic = point_indices[side + 2];
+
+ // Mark as clipped
+ edges[ib*2 + 0] |= 0x80000000;
+ edges[ib*2 + 1] |= 0x80000000;
+
+ edges[ic*2 + 0] = ia;
+ edges[ia*2 + 1] = ic;
+
+ indices_left -= 1;
+
+ // TODO: This may cause O(n^2) behavior!
+ num_steps = 0;
+
+ if (side == 1) {
+ point_indices[2] = point_indices[3];
+ point_indices[3] = edges[point_indices[3]*2 + 1];
+ } else {
+ point_indices[1] = point_indices[0];
+ point_indices[0] = edges[point_indices[0]*2 + 0];
+ }
+
+ clipped = true;
+ break;
+ }
+ }
+ if (clipped) continue;
+
+ // Continue forward
+ point_indices[0] = point_indices[1];
+ point_indices[1] = point_indices[2];
+ point_indices[2] = point_indices[3];
+ point_indices[3] = edges[point_indices[3]*2 + 1];
+ num_steps++;
+
+ // If we have walked around the entire polygon it is irregular and
+ // ear cutting won't find any more triangles.
+ // TODO: This could be stricter?
+ if (num_steps >= face.num_indices*2) break;
+ }
+
+ // Fallback: Cut non-ears until the polygon is completed.
+ // TODO: Could do something better here..
+ uint32_t ix = point_indices[1];
+ while (indices_left > 3) {
+ uint32_t prev = edges[ix*2 + 0];
+ uint32_t next = edges[ix*2 + 1];
+
+ // Mark as clipped
+ edges[ix*2 + 0] |= 0x80000000;
+ edges[ix*2 + 1] |= 0x80000000;
+
+ edges[prev*2 + 1] = next;
+ edges[next*2 + 0] = prev;
+
+ indices_left -= 1;
+ ix = next;
+ }
+
+ // Now we have a single triangle left at `ix`.
+ edges[ix*2 + 0] |= 0x80000000;
+ edges[ix*2 + 1] |= 0x80000000;
+ }
+
+ // Expand the adjacency information `edges` into proper triangles.
+ // Care needs to be taken here as both refer to the same memory area:
+ // The last 4 triangles may overlap in source and destination so we write
+ // them to a stack buffer and copy them over in the end.
+ uint32_t max_triangles = face.num_indices - 2;
+ uint32_t num_triangles = 0, num_last_triangles = 0;
+ uint32_t last_triangles[4*3]; // ufbxi_uninit
+
+ uint32_t index_begin = face.index_begin;
+ for (uint32_t ix = 0; ix < face.num_indices; ix++) {
+ uint32_t prev = edges[ix*2 + 0];
+ uint32_t next = edges[ix*2 + 1];
+ if (!(prev & 0x80000000)) continue;
+
+ uint32_t *dst = indices + num_triangles * 3;
+ if (num_triangles + 4 >= max_triangles) {
+ dst = last_triangles + num_last_triangles * 3;
+ num_last_triangles++;
+ }
+
+ dst[0] = index_begin + (prev & 0x7fffffff);
+ dst[1] = index_begin + ix;
+ dst[2] = index_begin + (next & 0x7fffffff);
+ num_triangles++;
+ }
+
+ // Copy over the last triangles
+ ufbx_assert(num_triangles == max_triangles);
+ memcpy(indices + (max_triangles - num_last_triangles) * 3, last_triangles, num_last_triangles * 3 * sizeof(uint32_t));
+
+ return num_triangles;
+}
+
+#endif
+
+static bool ufbxi_topo_less_index_prev_next(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_topo_edge *a = (const ufbx_topo_edge*)va, *b = (const ufbx_topo_edge*)vb;
+ if ((int32_t)a->prev != (int32_t)b->prev) return (int32_t)a->prev < (int32_t)b->prev;
+ return (int32_t)a->next < (int32_t)b->next;
+}
+
+static bool ufbxi_topo_less_index_index(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ const ufbx_topo_edge *a = (const ufbx_topo_edge*)va, *b = (const ufbx_topo_edge*)vb;
+ return (int32_t)a->index < (int32_t)b->index;
+}
+
+ufbxi_noinline static void ufbxi_compute_topology(const ufbx_mesh *mesh, ufbx_topo_edge *topo)
+{
+ size_t num_indices = mesh->num_indices;
+
+ // Temporarily use `prev` and `next` for vertices
+ for (uint32_t fi = 0; fi < mesh->num_faces; fi++) {
+ ufbx_face face = mesh->faces.data[fi];
+ for (uint32_t pi = 0; pi < face.num_indices; pi++) {
+ ufbx_topo_edge *te = &topo[face.index_begin + pi];
+ uint32_t ni = (pi + 1) % face.num_indices;
+ uint32_t va = mesh->vertex_indices.data[face.index_begin + pi];
+ uint32_t vb = mesh->vertex_indices.data[face.index_begin + ni];
+
+ if (vb < va) {
+ uint32_t vt = va; va = vb; vb = vt;
+ }
+ te->index = face.index_begin + pi;
+ te->twin = UFBX_NO_INDEX;
+ te->edge = UFBX_NO_INDEX;
+ te->prev = va;
+ te->next = vb;
+ te->face = fi;
+ te->flags = (ufbx_topo_flags)0;
+ }
+ }
+
+ ufbxi_unstable_sort(topo, num_indices, sizeof(ufbx_topo_edge), &ufbxi_topo_less_index_prev_next, NULL);
+
+ if (mesh->edges.data) {
+ for (uint32_t ei = 0; ei < mesh->num_edges; ei++) {
+ ufbx_edge edge = mesh->edges.data[ei];
+ uint32_t va = mesh->vertex_indices.data[edge.a];
+ uint32_t vb = mesh->vertex_indices.data[edge.b];
+ if (vb < va) {
+ uint32_t vt = va; va = vb; vb = vt;
+ }
+
+ size_t ix = num_indices;
+ ufbxi_macro_lower_bound_eq(ufbx_topo_edge, 32, &ix, topo, 0, num_indices,
+ (a->prev == va ? a->next < vb : a->prev < va), (a->prev == va && a->next == vb));
+
+ for (; ix < num_indices && topo[ix].prev == va && topo[ix].next == vb; ix++) {
+ topo[ix].edge = ei;
+ }
+ }
+ }
+
+ // Connect paired edges
+ for (size_t i0 = 0; i0 < num_indices; ) {
+ size_t i1 = i0;
+
+ uint32_t a = topo[i0].prev, b = topo[i0].next;
+ while (i1 + 1 < num_indices && topo[i1 + 1].prev == a && topo[i1 + 1].next == b) i1++;
+
+ if (i1 == i0 + 1) {
+ topo[i0].twin = topo[i1].index;
+ topo[i1].twin = topo[i0].index;
+ } else if (i1 > i0 + 1) {
+ for (size_t i = i0; i <= i1; i++) {
+ topo[i].flags = (ufbx_topo_flags)(topo[i].flags | UFBX_TOPO_NON_MANIFOLD);
+ }
+ }
+
+ i0 = i1 + 1;
+ }
+
+ ufbxi_unstable_sort(topo, num_indices, sizeof(ufbx_topo_edge), &ufbxi_topo_less_index_index, NULL);
+
+ // Fix `prev` and `next` to the actual index values
+ for (uint32_t fi = 0; fi < mesh->num_faces; fi++) {
+ ufbx_face face = mesh->faces.data[fi];
+ for (uint32_t i = 0; i < face.num_indices; i++) {
+ ufbx_topo_edge *to = &topo[face.index_begin + i];
+ to->prev = (uint32_t)(face.index_begin + (i + face.num_indices - 1) % face.num_indices);
+ to->next = (uint32_t)(face.index_begin + (i + 1) % face.num_indices);
+ }
+ }
+}
+
+static bool ufbxi_is_edge_smooth(const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index, bool assume_smooth)
+{
+ ufbxi_ignore(num_topo);
+ ufbx_assert((size_t)index < num_topo);
+ if (mesh->edge_smoothing.data) {
+ uint32_t edge = topo[index].edge;
+ if (edge != UFBX_NO_INDEX && mesh->edge_smoothing.data[edge]) return true;
+ }
+
+ if (mesh->face_smoothing.data) {
+ if (mesh->face_smoothing.data[topo[index].face]) return true;
+ uint32_t twin = topo[index].twin;
+ if (twin != UFBX_NO_INDEX) {
+ if (mesh->face_smoothing.data[topo[twin].face]) return true;
+ }
+ }
+
+ if (!mesh->edge_smoothing.data && !mesh->face_smoothing.data && mesh->vertex_normal.exists) {
+ uint32_t twin = topo[index].twin;
+ if (twin != UFBX_NO_INDEX && mesh->vertex_normal.exists) {
+ ufbx_assert((size_t)twin < num_topo);
+ ufbx_vec3 a0 = ufbx_get_vertex_vec3(&mesh->vertex_normal, index);
+ ufbx_vec3 a1 = ufbx_get_vertex_vec3(&mesh->vertex_normal, topo[index].next);
+ ufbx_vec3 b0 = ufbx_get_vertex_vec3(&mesh->vertex_normal, topo[twin].next);
+ ufbx_vec3 b1 = ufbx_get_vertex_vec3(&mesh->vertex_normal, twin);
+ if (a0.x == b0.x && a0.y == b0.y && a0.z == b0.z) return true;
+ if (a1.x == b1.x && a1.y == b1.y && a1.z == b1.z) return true;
+ }
+ } else if (assume_smooth) {
+ return true;
+ }
+
+ return false;
+}
+
+// -- Subdivision
+
+#if UFBXI_FEATURE_SUBDIVISION
+
+typedef struct {
+ const void *data;
+ ufbx_real weight;
+} ufbxi_subdivide_input;
+
+typedef int ufbxi_subdivide_sum_fn(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs);
+
+typedef struct {
+ ufbxi_subdivide_sum_fn *sum_fn;
+ void *sum_user;
+
+ const void *values;
+ size_t stride;
+
+ const uint32_t *indices;
+
+ bool check_split_data;
+ bool ignore_indices;
+
+ ufbx_subdivision_boundary boundary;
+
+} ufbxi_subdivide_layer_input;
+
+typedef struct {
+ void *values;
+ size_t num_values;
+ uint32_t *indices;
+ size_t num_indices;
+ bool unique_per_vertex;
+} ufbxi_subdivide_layer_output;
+
+typedef struct {
+ ufbx_subdivision_weight *weights;
+ size_t num_weights;
+} ufbxi_subdivision_vertex_weights;
+
+typedef struct {
+ ufbxi_mesh_imp *imp;
+
+ ufbx_error error;
+
+ ufbx_mesh *src_mesh_ptr;
+ ufbx_mesh src_mesh;
+ ufbx_mesh dst_mesh;
+ ufbx_topo_edge *topo;
+ size_t num_topo;
+
+ ufbx_subdivide_opts opts;
+
+ ufbxi_allocator ator_result;
+ ufbxi_allocator ator_tmp;
+
+ ufbxi_buf result;
+ ufbxi_buf tmp;
+ ufbxi_buf source;
+
+ ufbxi_subdivide_input *inputs;
+ size_t inputs_cap;
+
+ ufbx_real *tmp_vertex_weights;
+ ufbx_subdivision_weight *tmp_weights;
+ size_t total_weights;
+ size_t max_vertex_weights;
+
+} ufbxi_subdivide_context;
+
+static int ufbxi_subdivide_sum_vec2(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
+{
+ (void)user;
+ ufbx_vec2 dst = { 0 };
+ ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
+ const ufbx_vec2 *src = (const ufbx_vec2*)inputs[i].data;
+ ufbx_real weight = inputs[i].weight;
+ dst.x += src->x * weight;
+ dst.y += src->y * weight;
+ }
+ *(ufbx_vec2*)output = dst;
+
+ return 1;
+}
+
+static int ufbxi_subdivide_sum_vec3(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
+{
+ (void)user;
+ ufbx_vec3 dst = { 0 };
+ ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
+ const ufbx_vec3 *src = (const ufbx_vec3*)inputs[i].data;
+ ufbx_real weight = inputs[i].weight;
+ dst.x += src->x * weight;
+ dst.y += src->y * weight;
+ dst.z += src->z * weight;
+ }
+ *(ufbx_vec3*)output = dst;
+
+ return 1;
+}
+
+static int ufbxi_subdivide_sum_vec4(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
+{
+ (void)user;
+ ufbx_vec4 dst = { 0 };
+ ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
+ const ufbx_vec4 *src = (const ufbx_vec4*)inputs[i].data;
+ ufbx_real weight = inputs[i].weight;
+ dst.x += src->x * weight;
+ dst.y += src->y * weight;
+ dst.z += src->z * weight;
+ dst.w += src->w * weight;
+ }
+ *(ufbx_vec4*)output = dst;
+
+ return 1;
+}
+
+static ufbxi_noinline bool ufbxi_subdivision_weight_less(void *user, const void *va, const void *vb)
+{
+ (void)user;
+ ufbx_subdivision_weight a = *(const ufbx_subdivision_weight*)va, b = *(const ufbx_subdivision_weight*)vb;
+ ufbxi_dev_assert(a.index != b.index);
+ if (a.weight != b.weight) return a.weight > b.weight;
+ return a.index < b.index;
+}
+
+static int ufbxi_subdivide_sum_vertex_weights(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
+{
+ ufbxi_subdivide_context *sc = (ufbxi_subdivide_context*)user;
+
+ ufbx_real *vertex_weights = sc->tmp_vertex_weights;
+ ufbx_subdivision_weight *tmp_weights = sc->tmp_weights;
+ size_t num_weights = 0;
+
+ ufbxi_nounroll for (size_t input_ix = 0; input_ix != num_inputs; input_ix++) {
+ ufbxi_subdivision_vertex_weights src = *(const ufbxi_subdivision_vertex_weights*)inputs[input_ix].data;
+ ufbx_real input_weight = inputs[input_ix].weight;
+
+ for (size_t weight_ix = 0; weight_ix < src.num_weights; weight_ix++) {
+ ufbx_real weight = input_weight * src.weights[weight_ix].weight;
+ if (weight < 1.175494351e-38f) continue;
+
+ uint32_t vx = src.weights[weight_ix].index;
+ ufbxi_dev_assert(vx < sc->src_mesh.num_vertices);
+
+ ufbx_real prev = vertex_weights[vx];
+ vertex_weights[vx] = prev + weight;
+ if (prev == 0.0f) {
+ tmp_weights[num_weights++].index = vx;
+ }
+ }
+ }
+
+ ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
+ uint32_t vx = tmp_weights[i].index;
+ tmp_weights[i].weight = vertex_weights[vx];
+ vertex_weights[vx] = 0.0f;
+ }
+
+ ufbxi_unstable_sort(tmp_weights, num_weights, sizeof(ufbx_subdivision_weight), ufbxi_subdivision_weight_less, NULL);
+
+ if (sc->max_vertex_weights != SIZE_MAX) {
+ num_weights = ufbxi_min_sz(sc->max_vertex_weights, num_weights);
+
+ // Normalize weights
+ ufbx_real prefix_weight = 0.0f;
+ ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
+ prefix_weight += tmp_weights[i].weight;
+ }
+ ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
+ tmp_weights[i].weight /= prefix_weight;
+ }
+ }
+
+ sc->total_weights += num_weights;
+ ufbx_subdivision_weight *weights = ufbxi_push_copy(&sc->tmp, ufbx_subdivision_weight, num_weights, tmp_weights);
+ ufbxi_check_err(&sc->error, weights);
+
+ ufbxi_subdivision_vertex_weights *dst = (ufbxi_subdivision_vertex_weights*)output;
+ dst->weights = weights;
+ dst->num_weights = num_weights;
+
+ return 1;
+}
+
+static ufbxi_subdivide_sum_fn *const ufbxi_real_sum_fns[] = {
+ NULL,
+ &ufbxi_subdivide_sum_vec2,
+ &ufbxi_subdivide_sum_vec3,
+ &ufbxi_subdivide_sum_vec4,
+};
+
+ufbxi_noinline static bool ufbxi_is_edge_split(const ufbxi_subdivide_layer_input *input, const ufbx_topo_edge *topo, uint32_t index)
+{
+ uint32_t twin = topo[index].twin;
+ if (twin != UFBX_NO_INDEX) {
+ uint32_t a0 = input->indices[index];
+ uint32_t a1 = input->indices[topo[index].next];
+ uint32_t b0 = input->indices[topo[twin].next];
+ uint32_t b1 = input->indices[twin];
+ if (a0 == b0 && a1 == b1) return false;
+ if (!input->check_split_data) return true;
+ size_t stride = input->stride;
+ char *da0 = (char*)input->values + a0 * stride;
+ char *da1 = (char*)input->values + a1 * stride;
+ char *db0 = (char*)input->values + b0 * stride;
+ char *db1 = (char*)input->values + b1 * stride;
+ if (!memcmp(da0, db0, stride) && !memcmp(da1, db1, stride)) return false;
+ return true;
+ }
+
+ return false;
+}
+
+static ufbx_real ufbxi_edge_crease(const ufbx_mesh *mesh, bool split, const ufbx_topo_edge *topo, uint32_t index)
+{
+ if (topo[index].twin == UFBX_NO_INDEX) return 1.0f;
+ if (split) return 1.0f;
+ if (mesh->edge_crease.data && topo[index].edge != UFBX_NO_INDEX) return mesh->edge_crease.data[topo[index].edge] * (ufbx_real)10.0;
+ return 0.0f;
+}
+
+static ufbxi_noinline int ufbxi_subdivide_layer(ufbxi_subdivide_context *sc, ufbxi_subdivide_layer_output *output, const ufbxi_subdivide_layer_input *input)
+{
+ ufbx_subdivision_boundary boundary = input->boundary;
+
+ const ufbx_mesh *mesh = &sc->src_mesh;
+ const ufbx_topo_edge *topo = sc->topo;
+ size_t num_topo = sc->num_topo;
+
+ uint32_t *edge_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
+ ufbxi_check_err(&sc->error, edge_indices);
+
+ size_t num_edge_values = 0;
+ for (uint32_t ix = 0; ix < (uint32_t)mesh->num_indices; ix++) {
+ uint32_t twin = topo[ix].twin;
+ if (twin < ix && !ufbxi_is_edge_split(input, topo, ix)) {
+ edge_indices[ix] = edge_indices[twin];
+ } else {
+ edge_indices[ix] = (uint32_t)num_edge_values++;
+ }
+ }
+
+ size_t stride = input->stride;
+ size_t num_initial_values = (num_edge_values + mesh->num_faces + mesh->num_indices);
+ char *values = (char*)ufbxi_push_size(&sc->tmp, stride, num_initial_values);
+ ufbxi_check_err(&sc->error, values);
+
+ char *face_values = values;
+ char *edge_values = face_values + mesh->num_faces * stride;
+ char *vertex_values = edge_values + num_edge_values * stride;
+
+ size_t num_vertex_values = 0;
+
+ uint32_t *vertex_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
+ ufbxi_check_err(&sc->error, vertex_indices);
+
+ size_t min_inputs = ufbxi_max_sz(32, mesh->max_face_triangles + 2);
+ ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, min_inputs));
+ ufbxi_subdivide_input *inputs = sc->inputs;
+
+ // Assume initially unique per vertex, remove if not the case
+ output->unique_per_vertex = true;
+
+ bool sharp_corners = false;
+ bool sharp_splits = false;
+ bool sharp_all = false;
+
+ switch (boundary) {
+ case UFBX_SUBDIVISION_BOUNDARY_DEFAULT:
+ case UFBX_SUBDIVISION_BOUNDARY_SHARP_NONE:
+ case UFBX_SUBDIVISION_BOUNDARY_LEGACY:
+ // All smooth
+ break;
+ case UFBX_SUBDIVISION_BOUNDARY_SHARP_CORNERS:
+ sharp_corners = true;
+ break;
+ case UFBX_SUBDIVISION_BOUNDARY_SHARP_BOUNDARY:
+ sharp_corners = true;
+ sharp_splits = true;
+ break;
+ case UFBX_SUBDIVISION_BOUNDARY_SHARP_INTERIOR:
+ sharp_all = true;
+ break;
+ default:
+ ufbxi_unreachable("Bad boundary mode");
+ }
+
+ ufbxi_subdivide_sum_fn *sum_fn = input->sum_fn;
+ void *sum_user = input->sum_user;
+
+ // Mark unused indices as `UFBX_NO_INDEX` so we can patch non-manifold
+ ufbxi_nounroll for (size_t i = 0; i < mesh->num_indices; i++) {
+ vertex_indices[i] = UFBX_NO_INDEX;
+ }
+
+ // Face points
+ for (size_t fi = 0; fi < mesh->num_faces; fi++) {
+ ufbx_face face = mesh->faces.data[fi];
+ char *dst = face_values + fi * stride;
+
+ ufbx_real weight = 1.0f / (ufbx_real)face.num_indices;
+ for (uint32_t ci = 0; ci < face.num_indices; ci++) {
+ uint32_t ix = face.index_begin + ci;
+ inputs[ci].data = (const char*)input->values + input->indices[ix] * stride;
+ inputs[ci].weight = weight;
+ }
+
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, face.num_indices));
+ }
+
+ // Edge points
+ for (uint32_t ix = 0; ix < mesh->num_indices; ix++) {
+ char *dst = edge_values + edge_indices[ix] * stride;
+
+ uint32_t twin = topo[ix].twin;
+ bool split = ufbxi_is_edge_split(input, topo, ix);
+
+ if (split || (topo[ix].flags & UFBX_TOPO_NON_MANIFOLD) != 0) {
+ output->unique_per_vertex = false;
+ }
+
+ ufbx_real crease = 0.0f;
+ if (split || twin == UFBX_NO_INDEX) {
+ crease = 1.0f;
+ } else if (topo[ix].edge != UFBX_NO_INDEX && mesh->edge_crease.data) {
+ crease = mesh->edge_crease.data[topo[ix].edge] * (ufbx_real)10.0;
+ }
+ if (sharp_all) crease = 1.0f;
+
+ const char *v0 = (const char*)input->values + input->indices[ix] * stride;
+ const char *v1 = (const char*)input->values + input->indices[topo[ix].next] * stride;
+
+ // TODO: Unify
+ if (twin < ix && !split) {
+ // Already calculated
+ } else if (crease <= 0.0f) {
+ const char *f0 = face_values + topo[ix].face * stride;
+ const char *f1 = face_values + topo[twin].face * stride;
+ inputs[0].data = v0;
+ inputs[0].weight = 0.25f;
+ inputs[1].data = v1;
+ inputs[1].weight = 0.25f;
+ inputs[2].data = f0;
+ inputs[2].weight = 0.25f;
+ inputs[3].data = f1;
+ inputs[3].weight = 0.25f;
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 4));
+ } else if (crease >= 1.0f) {
+ inputs[0].data = v0;
+ inputs[0].weight = 0.5f;
+ inputs[1].data = v1;
+ inputs[1].weight = 0.5f;
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 2));
+ } else if (crease < 1.0f) {
+ const char *f0 = face_values + topo[ix].face * stride;
+ const char *f1 = face_values + topo[twin].face * stride;
+ ufbx_real w0 = 0.25f + 0.25f * crease;
+ ufbx_real w1 = 0.25f - 0.25f * crease;
+
+ inputs[0].data = v0;
+ inputs[0].weight = w0;
+ inputs[1].data = v1;
+ inputs[1].weight = w0;
+ inputs[2].data = f0;
+ inputs[2].weight = w1;
+ inputs[3].data = f1;
+ inputs[3].weight = w1;
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 4));
+ }
+ }
+
+ // Vertex points
+ for (size_t vi = 0; vi < mesh->num_vertices; vi++) {
+ uint32_t original_start = mesh->vertex_first_index.data[vi];
+ if (original_start == UFBX_NO_INDEX) continue;
+
+ // Find a topological boundary, or if not found a split edge
+ uint32_t start = original_start;
+ for (uint32_t cur = start;;) {
+ uint32_t prev = ufbx_topo_prev_vertex_edge(topo, num_topo, cur);
+ if (prev == UFBX_NO_INDEX) { start = cur; break; } // Topological boundary: Stop and use as start
+ if (ufbxi_is_edge_split(input, topo, prev)) start = cur; // Split edge: Consider as start
+ if (prev == original_start) break; // Loop: Stop, use original start or split if found
+ cur = prev;
+ }
+
+ original_start = start;
+ while (start != UFBX_NO_INDEX) {
+ if (start != original_start) {
+ output->unique_per_vertex = false;
+ }
+
+ uint32_t value_index = (uint32_t)num_vertex_values++;
+ char *dst = vertex_values + value_index * stride;
+
+ // We need to compute the average crease value and keep track of
+ // two creased edges, if there's more we use the corner rule that
+ // does not need the information.
+ ufbx_real total_crease = 0.0f;
+ size_t num_crease = 0;
+ size_t num_split = 0;
+ bool on_boundary = false;
+ bool non_manifold = false;
+ size_t crease_input_indices[2]; // ufbxi_uninit
+
+ // At start we always have two edges and a single face
+ uint32_t start_prev = topo[start].prev;
+ uint32_t end_edge = topo[start_prev].twin;
+ size_t valence = 2;
+
+ non_manifold |= (topo[start].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
+ non_manifold |= (topo[start_prev].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
+
+ const char *v0 = (const char*)input->values + input->indices[start] * stride;
+
+ size_t num_inputs = 4;
+
+ {
+ const char *e0 = (const char*)input->values + input->indices[topo[start].next] * stride;
+ const char *e1 = (const char*)input->values + input->indices[start_prev] * stride;
+ const char *f0 = face_values + topo[start].face * stride;
+ inputs[0].data = v0;
+ inputs[1].data = e0;
+ inputs[2].data = e1;
+ inputs[3].data = f0;
+ }
+
+ bool start_split = ufbxi_is_edge_split(input, topo, start);
+ bool prev_split = end_edge != UFBX_NO_INDEX && ufbxi_is_edge_split(input, topo, end_edge);
+
+ // Either of the first two edges may be creased
+ ufbx_real start_crease = ufbxi_edge_crease(mesh, start_split, topo, start);
+ if (start_crease > 0.0f) {
+ total_crease += start_crease;
+ crease_input_indices[num_crease++] = 1;
+ }
+ ufbx_real prev_crease = ufbxi_edge_crease(mesh, prev_split, topo, start_prev);
+ if (prev_crease > 0.0f) {
+ total_crease += prev_crease;
+ crease_input_indices[num_crease++] = 2;
+ }
+
+ if (end_edge != UFBX_NO_INDEX) {
+ if (prev_split) {
+ num_split++;
+ }
+ } else {
+ on_boundary = true;
+ }
+
+ ufbxi_check_err(&sc->error, vertex_indices[start] == UFBX_NO_INDEX);
+ vertex_indices[start] = value_index;
+
+ if (start_split) {
+ // We need to special case if the first edge is split as we have
+ // handled it already in the code above..
+ start = ufbx_topo_next_vertex_edge(topo, num_topo, start);
+ num_split++;
+ } else {
+ // Follow vertex edges until we either hit a topological/split boundary
+ // or loop back to the left edge we accounted for in `start_prev`
+ uint32_t cur = start;
+ for (;;) {
+ cur = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
+
+ // Topological boundary: Finished
+ if (cur == UFBX_NO_INDEX) {
+ on_boundary = true;
+ start = UFBX_NO_INDEX;
+ break;
+ }
+
+ non_manifold |= (topo[cur].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
+ ufbxi_check_err(&sc->error, vertex_indices[cur] == UFBX_NO_INDEX);
+ vertex_indices[cur] = value_index;
+
+ bool split = ufbxi_is_edge_split(input, topo, cur);
+
+ // Looped: Add the face from the other side still if not split
+ if (cur == end_edge && !split) {
+ ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, num_inputs + 1));
+ const char *f0 = face_values + topo[cur].face * stride;
+ inputs[num_inputs].data = f0;
+ start = UFBX_NO_INDEX;
+ num_inputs += 1;
+ break;
+ }
+
+ // Add the edge crease, this also handles boundaries as they
+ // have an implicit crease of 1.0 using `ufbxi_edge_crease()`
+ ufbx_real cur_crease = ufbxi_edge_crease(mesh, split, topo, cur);
+ if (cur_crease > 0.0f) {
+ total_crease += cur_crease;
+ if (num_crease < 2) crease_input_indices[num_crease] = num_inputs;
+ num_crease++;
+ }
+
+ // Add the new edge and face to the sum
+ {
+ ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, num_inputs + 2));
+ inputs = sc->inputs;
+
+ const char *e0 = (char*)input->values + input->indices[topo[cur].next] * stride;
+ const char *f0 = face_values + topo[cur].face * stride;
+ inputs[num_inputs + 0].data = e0;
+ inputs[num_inputs + 1].data = f0;
+ num_inputs += 2;
+ }
+ valence++;
+
+ // If we landed at a split edge advance to the next one
+ // and continue from there in the outer loop
+ if (split) {
+ start = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
+ num_split++;
+ break;
+ }
+ }
+ }
+
+ if (start == original_start) start = UFBX_NO_INDEX;
+
+ // Weights for various subdivision masks
+ ufbx_real fe_weight = 1.0f / (ufbx_real)(valence*valence);
+ ufbx_real v_weight = (ufbx_real)(valence - 2) / (ufbx_real)valence;
+
+ // Select the right subdivision mask depending on valence and crease
+ if (num_crease > 2
+ || (sharp_corners && valence == 2 && (num_split > 0 || on_boundary))
+ || (sharp_splits && (num_split > 0 || on_boundary))
+ || sharp_all
+ || non_manifold) {
+ // Corner: Copy as-is
+ inputs[0].data = v0;
+ inputs[0].weight = 1.0f;
+ num_inputs = 1;
+ } else if (num_crease == 2) {
+ // Boundary: Interpolate edge
+ total_crease *= 0.5f;
+ if (total_crease < 0.0f) total_crease = 0.0f;
+ if (total_crease > 1.0f) total_crease = 1.0f;
+
+ inputs[0].weight = v_weight * (1.0f - total_crease) + 0.75f * total_crease;
+ ufbx_real few = fe_weight * (1.0f - total_crease);
+ for (size_t i = 1; i < num_inputs; i++) {
+ inputs[i].weight = few;
+ }
+
+ // Add weight to the creased edges
+ inputs[crease_input_indices[0]].weight += 0.125f * total_crease;
+ inputs[crease_input_indices[1]].weight += 0.125f * total_crease;
+ } else {
+ // Regular: Weighted sum with the accumulated edge/face points
+ inputs[0].weight = v_weight;
+ for (size_t i = 1; i < num_inputs; i++) {
+ inputs[i].weight = fe_weight;
+ }
+
+ }
+
+ if (mesh->vertex_crease.exists) {
+ ufbx_real v = ufbx_get_vertex_real(&mesh->vertex_crease, original_start);
+ v *= (ufbx_real)10.0;
+ if (v > 0.0f) {
+ if (v > 1.0) v = 1.0f;
+
+ ufbx_real iv = 1.0f - v;
+ inputs[0].weight = 1.0f * v + (inputs[0].weight) * iv;
+ for (size_t i = 1; i < num_inputs; i++) {
+ inputs[i].weight *= iv;
+ }
+ }
+ }
+
+#if defined(UFBX_REGRESSION)
+ {
+ ufbx_real total_weight = 0.0f;
+ for (size_t i = 0; i < num_inputs; i++) {
+ total_weight += inputs[i].weight;
+ }
+ ufbx_assert(ufbx_fabs(total_weight - 1.0f) < 0.001f);
+ }
+#endif
+
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, num_inputs));
+ }
+ }
+
+ // Copy non-manifold vertex values as-is
+ for (size_t old_ix = 0; old_ix < mesh->num_indices; old_ix++) {
+ uint32_t ix = vertex_indices[old_ix];
+ if (ix == UFBX_NO_INDEX) {
+ ix = (uint32_t)num_vertex_values++;
+ vertex_indices[old_ix] = ix;
+ const char *src = (const char*)input->values + input->indices[old_ix] * stride;
+ char *dst = vertex_values + ix * stride;
+
+ inputs[0].data = src;
+ inputs[0].weight = 1.0f;
+ ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 1));
+ }
+ }
+
+ ufbx_assert(num_vertex_values <= mesh->num_indices);
+ size_t num_values = num_edge_values + mesh->num_faces + num_vertex_values;
+ char *new_values = (char*)ufbxi_push_size(&sc->result, stride, (num_values+1));
+ ufbxi_check_err(&sc->error, new_values);
+
+ memset(new_values, 0, stride);
+ new_values += stride;
+
+ memcpy(new_values, values, num_values * stride);
+
+ output->values = new_values;
+ output->num_values = num_values;
+
+ if (!input->ignore_indices) {
+ uint32_t *new_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices * 4);
+ ufbxi_check_err(&sc->error, new_indices);
+
+ uint32_t face_start = 0;
+ uint32_t edge_start = (uint32_t)(face_start + mesh->num_faces);
+ uint32_t vert_start = (uint32_t)(edge_start + num_edge_values);
+ uint32_t *p_ix = new_indices;
+ for (size_t ix = 0; ix < mesh->num_indices; ix++) {
+ p_ix[0] = vert_start + vertex_indices[ix];
+ p_ix[1] = edge_start + edge_indices[ix];
+ p_ix[2] = face_start + topo[ix].face;
+ p_ix[3] = edge_start + edge_indices[topo[ix].prev];
+ p_ix += 4;
+ }
+ output->indices = new_indices;
+ output->num_indices = mesh->num_indices * 4;
+ } else {
+ output->indices = NULL;
+ output->num_indices = 0;
+ }
+
+ return 1;
+}
+
+static ufbxi_noinline int ufbxi_subdivide_attrib(ufbxi_subdivide_context *sc, ufbx_vertex_attrib *attrib, ufbx_subdivision_boundary boundary, bool check_split_data)
+{
+ if (!attrib->exists) return 1;
+
+ ufbx_assert(attrib->value_reals >= 2 && attrib->value_reals <= 4);
+
+ ufbxi_subdivide_layer_input input; // ufbxi_uninit
+ input.sum_fn = ufbxi_real_sum_fns[attrib->value_reals - 1];
+ input.sum_user = NULL;
+ input.values = attrib->values.data;
+ input.indices = attrib->indices.data;
+ input.stride = attrib->value_reals * sizeof(ufbx_real);
+ input.boundary = boundary;
+ input.check_split_data = check_split_data;
+ input.ignore_indices = false;
+
+ ufbxi_subdivide_layer_output output; // ufbxi_uninit
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_layer(sc, &output, &input));
+
+ attrib->values.data = output.values;
+ attrib->indices.data = output.indices;
+ attrib->values.count = output.num_values;
+ attrib->indices.count = output.num_indices;
+
+ return 1;
+}
+
+static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_subdivision_copy_weights(ufbxi_subdivide_context *sc, ufbx_subdivision_weight_range_list ranges, ufbx_subdivision_weight_list weights)
+{
+ ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, ranges.count);
+ ufbxi_check_return_err(&sc->error, dst, NULL);
+
+ ufbxi_nounroll for (size_t i = 0; i != ranges.count; i++) {
+ ufbx_subdivision_weight_range range = ranges.data[i];
+ dst[i].weights = weights.data + range.weight_begin;
+ dst[i].num_weights = range.num_weights;
+ }
+
+ return dst;
+}
+
+static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_init_source_vertex_weights(ufbxi_subdivide_context *sc, size_t num_vertices)
+{
+ ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, num_vertices);
+ ufbx_subdivision_weight *weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, num_vertices);
+ ufbxi_check_return_err(&sc->error, dst && weights, NULL);
+
+ ufbxi_nounroll for (size_t i = 0; i != num_vertices; i++) {
+ dst[i].weights = weights + i;
+ dst[i].num_weights = 1;
+ weights[i].index = (uint32_t)i;
+ weights[i].weight = 1.0f;
+ }
+
+ return dst;
+}
+
+static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_init_skin_weights(ufbxi_subdivide_context *sc, size_t num_vertices, const ufbx_skin_deformer *skin)
+{
+ ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, num_vertices);
+ ufbxi_check_return_err(&sc->error, dst, NULL);
+
+ for (size_t i = 0; i < num_vertices; i++) {
+ ufbxi_dev_assert(i < skin->vertices.count);
+ ufbx_skin_vertex vertex = skin->vertices.data[i];
+ size_t num_weights = ufbxi_min_sz(sc->max_vertex_weights, vertex.num_weights);
+
+ ufbx_subdivision_weight *weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, num_weights);
+ ufbxi_check_err(&sc->error, weights);
+
+ const ufbx_skin_weight *skin_weights = skin->weights.data + vertex.weight_begin;
+
+ dst[i].weights = weights;
+ dst[i].num_weights = num_weights;
+ ufbxi_nounroll for (size_t wi = 0; wi != num_weights; wi++) {
+ ufbxi_check_err(&sc->error, skin_weights[wi].cluster_index <= INT32_MAX);
+ weights[wi].index = skin_weights[wi].cluster_index;
+ weights[wi].weight = skin_weights[wi].weight;
+ }
+ }
+
+ return dst;
+}
+
+static ufbxi_noinline int ufbxi_subdivide_weights(ufbxi_subdivide_context *sc, ufbx_subdivision_weight_range_list *ranges,
+ ufbx_subdivision_weight_list *weights, const ufbxi_subdivision_vertex_weights *src)
+{
+ ufbxi_check_err(&sc->error, src);
+
+ ufbxi_subdivide_layer_input input; // ufbxi_uninit
+ input.sum_fn = ufbxi_subdivide_sum_vertex_weights;
+ input.sum_user = sc;
+ input.values = src;
+ input.indices = sc->src_mesh.vertex_indices.data;
+ input.stride = sizeof(ufbxi_subdivision_vertex_weights);
+ input.boundary = sc->opts.boundary;
+ input.check_split_data = false;
+ input.ignore_indices = true;
+
+ sc->total_weights = 0;
+
+ ufbxi_subdivide_layer_output output; // ufbxi_uninit
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_layer(sc, &output, &input));
+
+ size_t num_vertices = output.num_values;
+ ufbx_assert(num_vertices == sc->dst_mesh.vertex_position.values.count);
+
+ ufbx_subdivision_weight_range *dst_ranges = ufbxi_push(&sc->result, ufbx_subdivision_weight_range, num_vertices);
+ ufbx_subdivision_weight *dst_weights = ufbxi_push(&sc->result, ufbx_subdivision_weight, sc->total_weights);
+ ufbxi_check_err(&sc->error, ranges && weights);
+
+ ufbxi_subdivision_vertex_weights *src_weights = (ufbxi_subdivision_vertex_weights*)output.values;
+
+ size_t weight_offset = 0;
+ for (size_t vi = 0; vi < num_vertices; vi++) {
+ ufbxi_subdivision_vertex_weights ws = src_weights[vi];
+ ufbxi_check_err(&sc->error, (size_t)UINT32_MAX - weight_offset >= ws.num_weights);
+
+ dst_ranges[vi].weight_begin = (uint32_t)weight_offset;
+ dst_ranges[vi].num_weights = (uint32_t)ws.num_weights;
+ memcpy(dst_weights + weight_offset, ws.weights, ws.num_weights * sizeof(ufbx_subdivision_weight));
+ weight_offset += ws.num_weights;
+ }
+
+ ranges->data = dst_ranges;
+ ranges->count = num_vertices;
+ weights->data = dst_weights;
+ weights->count = sc->total_weights;
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_vertex_crease(ufbxi_subdivide_context *sc, ufbx_vertex_real *ufbxi_restrict dst, const ufbx_vertex_real *ufbxi_restrict src)
+{
+ size_t src_indices = src->indices.count;
+ size_t src_values = src->values.count;
+
+ dst->values.count = src_values + 1;
+ dst->values.data = ufbxi_push(&sc->result, ufbx_real, dst->values.count);
+ ufbxi_check_err(&sc->error, dst->values.data);
+ dst->values.data[src_values] = 0.0f;
+
+ dst->indices.count = src_indices * 4;
+ dst->indices.data = ufbxi_push(&sc->result, uint32_t, dst->indices.count);
+ ufbxi_check_err(&sc->error, dst->indices.data);
+
+ // Reduce the amount of vertex crease on each iteration
+ ufbxi_nounroll for (size_t i = 0; i < src_values; i++) {
+ ufbx_real crease = src->values.data[i];
+ if (crease < 0.999f) crease -= 0.1f;
+ if (crease < 0.0f) crease = 0.0f;
+ dst->values.data[i] = crease;
+ }
+
+ // Write the crease at the vertex corner and zero (at `src_values`) on other ones
+ uint32_t zero_index = (uint32_t)src_values;
+ ufbxi_nounroll for (size_t i = 0; i < src_indices; i++) {
+ uint32_t *quad = dst->indices.data + i * 4;
+ quad[0] = src->indices.data[i];
+ quad[1] = zero_index;
+ quad[2] = zero_index;
+ quad[3] = zero_index;
+ }
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_mesh_level(ufbxi_subdivide_context *sc)
+{
+ const ufbx_mesh *mesh = &sc->src_mesh;
+ ufbx_mesh *result = &sc->dst_mesh;
+
+ *result = *mesh;
+
+ ufbx_topo_edge *topo = ufbxi_push(&sc->tmp, ufbx_topo_edge, mesh->num_indices);
+ ufbxi_check_err(&sc->error, topo);
+ ufbx_compute_topology(mesh, topo, mesh->num_indices);
+ sc->topo = topo;
+ sc->num_topo = mesh->num_indices;
+
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->vertex_position, sc->opts.boundary, false));
+
+ memset(&result->vertex_uv, 0, sizeof(result->vertex_uv));
+ memset(&result->vertex_tangent, 0, sizeof(result->vertex_tangent));
+ memset(&result->vertex_bitangent, 0, sizeof(result->vertex_bitangent));
+ memset(&result->vertex_color, 0, sizeof(result->vertex_color));
+
+ result->uv_sets.data = ufbxi_push_copy(&sc->result, ufbx_uv_set, result->uv_sets.count, result->uv_sets.data);
+ ufbxi_check_err(&sc->error, result->uv_sets.data);
+
+ result->color_sets.data = ufbxi_push_copy(&sc->result, ufbx_color_set, result->color_sets.count, result->color_sets.data);
+ ufbxi_check_err(&sc->error, result->color_sets.data);
+
+ ufbxi_for_list(ufbx_uv_set, set, result->uv_sets) {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_uv, sc->opts.uv_boundary, true));
+ if (sc->opts.interpolate_tangents) {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_tangent, sc->opts.uv_boundary, true));
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_bitangent, sc->opts.uv_boundary, true));
+ } else {
+ memset(&set->vertex_tangent, 0, sizeof(set->vertex_tangent));
+ memset(&set->vertex_bitangent, 0, sizeof(set->vertex_bitangent));
+ }
+ }
+
+ ufbxi_for_list(ufbx_color_set, set, result->color_sets) {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_color, sc->opts.uv_boundary, true));
+ }
+
+ if (result->uv_sets.count > 0) {
+ result->vertex_uv = result->uv_sets.data[0].vertex_uv;
+ result->vertex_bitangent = result->uv_sets.data[0].vertex_bitangent;
+ result->vertex_tangent = result->uv_sets.data[0].vertex_tangent;
+ }
+ if (result->color_sets.count > 0) {
+ result->vertex_color = result->color_sets.data[0].vertex_color;
+ }
+
+ if (sc->opts.interpolate_normals && !sc->opts.ignore_normals) {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->vertex_normal, sc->opts.boundary, true));
+ ufbxi_for_list(ufbx_vec3, normal, result->vertex_normal.values) {
+ *normal = ufbxi_slow_normalize3(normal);
+ }
+ if (mesh->skinned_normal.values.data == mesh->vertex_normal.values.data) {
+ result->skinned_normal = result->vertex_normal;
+ } else {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->skinned_normal, sc->opts.boundary, true));
+ ufbxi_for_list(ufbx_vec3, normal, result->skinned_normal.values) {
+ *normal = ufbxi_slow_normalize3(normal);
+ }
+ }
+ }
+
+ if (result->vertex_crease.exists) {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_vertex_crease(sc, &result->vertex_crease, &mesh->vertex_crease));
+ }
+
+ if (mesh->skinned_position.values.data == mesh->vertex_position.values.data) {
+ result->skinned_position = result->vertex_position;
+ } else {
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->skinned_position, sc->opts.boundary, false));
+ }
+
+ ufbx_subdivision_result *result_sub = ufbxi_push_zero(&sc->result, ufbx_subdivision_result, 1);
+ ufbxi_check_err(&sc->error, result_sub);
+ result->subdivision_result = result_sub;
+
+ if (sc->opts.evaluate_source_vertices || sc->opts.evaluate_skin_weights) {
+ ufbx_subdivision_result *mesh_sub = mesh->subdivision_result;
+
+ ufbx_skin_deformer *skin = NULL;
+ if (sc->opts.evaluate_skin_weights) {
+ if (mesh->skin_deformers.count > 0) {
+ ufbxi_check_err(&sc->error, sc->opts.skin_deformer_index < mesh->skin_deformers.count);
+ skin = mesh->skin_deformers.data[sc->opts.skin_deformer_index];
+ }
+ }
+
+ size_t max_weights = 0;
+ if (sc->opts.evaluate_source_vertices) {
+ max_weights = ufbxi_max_sz(max_weights, mesh->num_vertices);
+ }
+ if (skin) {
+ max_weights = ufbxi_max_sz(max_weights, skin->clusters.count);
+ }
+
+ sc->tmp_vertex_weights = ufbxi_push_zero(&sc->tmp, ufbx_real, mesh->num_vertices);
+ sc->tmp_weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, max_weights);
+ ufbxi_check_err(&sc->error, sc->tmp_vertex_weights && sc->tmp_weights);
+
+ if (sc->opts.evaluate_source_vertices) {
+ sc->max_vertex_weights = sc->opts.max_source_vertices ? sc->opts.max_source_vertices : SIZE_MAX;
+
+ ufbxi_subdivision_vertex_weights *weights;
+ if (mesh_sub && mesh_sub->source_vertex_ranges.count > 0) {
+ weights = ufbxi_subdivision_copy_weights(sc, mesh_sub->source_vertex_ranges, mesh_sub->source_vertex_weights);
+ } else {
+ weights = ufbxi_init_source_vertex_weights(sc, mesh->num_vertices);
+ }
+
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_weights(sc, &result_sub->source_vertex_ranges, &result_sub->source_vertex_weights, weights));
+ }
+
+ if (skin) {
+ sc->max_vertex_weights = sc->opts.max_skin_weights ? sc->opts.max_skin_weights : SIZE_MAX;
+
+ ufbxi_subdivision_vertex_weights *weights;
+ if (mesh_sub && mesh_sub->source_vertex_ranges.count > 0) {
+ weights = ufbxi_subdivision_copy_weights(sc, mesh_sub->skin_cluster_ranges, mesh_sub->skin_cluster_weights);
+ } else {
+ weights = ufbxi_init_skin_weights(sc, mesh->num_vertices, skin);
+ }
+
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_weights(sc, &result_sub->skin_cluster_ranges, &result_sub->skin_cluster_weights, weights));
+ }
+
+ }
+
+ result->num_vertices = result->vertex_position.values.count;
+ result->num_indices = mesh->num_indices * 4;
+ result->num_faces = mesh->num_indices;
+ result->num_triangles = mesh->num_indices * 2;
+
+ result->vertex_indices.data = result->vertex_position.indices.data;
+ result->vertex_indices.count = result->num_indices;
+ result->vertices.data = result->vertex_position.values.data;
+ result->vertices.count = result->num_vertices;
+
+ result->faces.count = result->num_faces;
+ result->faces.data = ufbxi_push(&sc->result, ufbx_face, result->num_faces);
+ ufbxi_check_err(&sc->error, result->faces.data);
+
+ for (size_t i = 0; i < result->num_faces; i++) {
+ result->faces.data[i].index_begin = (uint32_t)(i * 4);
+ result->faces.data[i].num_indices = 4;
+ }
+
+ if (mesh->edges.data) {
+ result->num_edges = mesh->num_edges*2 + result->num_faces;
+ result->edges.count = result->num_edges;
+ result->edges.data = ufbxi_push(&sc->result, ufbx_edge, result->num_edges);
+ ufbxi_check_err(&sc->error, result->edges.data);
+
+ if (mesh->edge_crease.data) {
+ result->edge_crease.count = result->num_edges;
+ result->edge_crease.data = ufbxi_push(&sc->result, ufbx_real, result->num_edges);
+ ufbxi_check_err(&sc->error, result->edge_crease.data);
+ }
+ if (mesh->edge_smoothing.data) {
+ result->edge_smoothing.count = result->num_edges;
+ result->edge_smoothing.data = ufbxi_push(&sc->result, bool, result->num_edges);
+ ufbxi_check_err(&sc->error, result->edge_smoothing.data);
+ }
+ if (mesh->edge_visibility.data) {
+ result->edge_visibility.count = result->num_edges;
+ result->edge_visibility.data = ufbxi_push(&sc->result, bool, result->num_edges);
+ ufbxi_check_err(&sc->error, result->edge_visibility.data);
+ }
+
+ size_t di = 0;
+ for (size_t i = 0; i < mesh->num_edges; i++) {
+ ufbx_edge edge = mesh->edges.data[i];
+ uint32_t face_ix = topo[edge.a].face;
+ ufbx_face face = mesh->faces.data[face_ix];
+ uint32_t offset = edge.a - face.index_begin;
+ uint32_t next = (offset + 1) % (uint32_t)face.num_indices;
+
+ uint32_t a = (face.index_begin + offset) * 4;
+ uint32_t b = (face.index_begin + next) * 4;
+
+ result->edges.data[di + 0].a = a;
+ result->edges.data[di + 0].b = a + 1;
+ result->edges.data[di + 1].a = b + 3;
+ result->edges.data[di + 1].b = b;
+
+ if (mesh->edge_crease.data) {
+ ufbx_real crease = mesh->edge_crease.data[i];
+ if (crease < 0.999f) crease -= (ufbx_real)0.1;
+ if (crease < 0.0f) crease = 0.0f;
+ result->edge_crease.data[di + 0] = crease;
+ result->edge_crease.data[di + 1] = crease;
+ }
+
+ if (mesh->edge_smoothing.data) {
+ result->edge_smoothing.data[di + 0] = mesh->edge_smoothing.data[i];
+ result->edge_smoothing.data[di + 1] = mesh->edge_smoothing.data[i];
+ }
+
+ if (mesh->edge_visibility.data) {
+ result->edge_visibility.data[di + 0] = mesh->edge_visibility.data[i];
+ result->edge_visibility.data[di + 1] = mesh->edge_visibility.data[i];
+ }
+
+ di += 2;
+ }
+
+ for (size_t fi = 0; fi < result->num_faces; fi++) {
+ result->edges.data[di].a = (uint32_t)(fi * 4 + 1);
+ result->edges.data[di].b = (uint32_t)(fi * 4 + 2);
+
+ if (result->edge_crease.data) {
+ result->edge_crease.data[di] = 0.0f;
+ }
+
+ if (result->edge_smoothing.data) {
+ result->edge_smoothing.data[di + 0] = true;
+ }
+
+ if (result->edge_visibility.data) {
+ result->edge_visibility.data[di + 0] = false;
+ }
+
+ di++;
+ }
+ }
+
+ if (mesh->face_material.data) {
+ result->face_material.count = result->num_faces;
+ result->face_material.data = ufbxi_push(&sc->result, uint32_t, result->num_faces);
+ ufbxi_check_err(&sc->error, result->face_material.data);
+ }
+ if (mesh->face_smoothing.data) {
+ result->face_smoothing.count = result->num_faces;
+ result->face_smoothing.data = ufbxi_push(&sc->result, bool, result->num_faces);
+ ufbxi_check_err(&sc->error, result->face_smoothing.data);
+ }
+ if (mesh->face_group.data) {
+ result->face_group.count = result->num_faces;
+ result->face_group.data = ufbxi_push(&sc->result, uint32_t, result->num_faces);
+ ufbxi_check_err(&sc->error, result->face_group.data);
+ }
+ if (mesh->face_hole.data) {
+ result->face_hole.count = result->num_faces;
+ result->face_hole.data = ufbxi_push(&sc->result, bool, result->num_faces);
+ ufbxi_check_err(&sc->error, result->face_hole.data);
+ }
+
+ if (result->material_parts.count > 0) {
+ result->material_parts.data = ufbxi_push_zero(&sc->result, ufbx_mesh_part, result->material_parts.count);
+ ufbxi_check_err(&sc->error, result->materials.data);
+ }
+
+ size_t index_offset = 0;
+ for (size_t i = 0; i < mesh->num_faces; i++) {
+ ufbx_face face = mesh->faces.data[i];
+
+ uint32_t mat = 0;
+ if (mesh->face_material.data) {
+ mat = mesh->face_material.data[i];
+ for (size_t ci = 0; ci < face.num_indices; ci++) {
+ result->face_material.data[index_offset + ci] = mat;
+ }
+ }
+ if (mesh->face_smoothing.data) {
+ bool flag = mesh->face_smoothing.data[i];
+ for (size_t ci = 0; ci < face.num_indices; ci++) {
+ result->face_smoothing.data[index_offset + ci] = flag;
+ }
+ }
+ if (mesh->face_group.data) {
+ uint32_t group = mesh->face_group.data[i];
+ for (size_t ci = 0; ci < face.num_indices; ci++) {
+ result->face_group.data[index_offset + ci] = group;
+ }
+ }
+ if (mesh->face_hole.data) {
+ bool flag = mesh->face_hole.data[i];
+ for (size_t ci = 0; ci < face.num_indices; ci++) {
+ result->face_hole.data[index_offset + ci] = flag;
+ }
+ }
+ index_offset += face.num_indices;
+ }
+
+ // Will be filled in by `ufbxi_finalize_mesh()`.
+ result->vertex_first_index.count = 0;
+
+ ufbxi_check_err(&sc->error, ufbxi_finalize_mesh_material(&sc->result, &sc->error, result));
+ ufbxi_check_err(&sc->error, ufbxi_finalize_mesh(&sc->result, &sc->error, result));
+ ufbxi_check_err(&sc->error, ufbxi_update_face_groups(&sc->result, &sc->error, result, true));
+
+ return 1;
+}
+
+ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_mesh_imp(ufbxi_subdivide_context *sc, size_t level)
+{
+ if (sc->opts.boundary == UFBX_SUBDIVISION_BOUNDARY_DEFAULT) {
+ sc->opts.boundary = sc->src_mesh.subdivision_boundary;
+ }
+
+ if (sc->opts.uv_boundary == UFBX_SUBDIVISION_BOUNDARY_DEFAULT) {
+ sc->opts.uv_boundary = sc->src_mesh.subdivision_uv_boundary;
+ }
+
+ ufbxi_init_ator(&sc->error, &sc->ator_tmp, &sc->opts.temp_allocator, "temp");
+ ufbxi_init_ator(&sc->error, &sc->ator_result, &sc->opts.result_allocator, "result");
+
+ sc->result.unordered = true;
+ sc->source.unordered = true;
+ sc->tmp.unordered = true;
+
+ sc->source.ator = &sc->ator_tmp;
+ sc->tmp.ator = &sc->ator_tmp;
+
+ for (size_t i = 1; i < level; i++) {
+ sc->result.ator = &sc->ator_tmp;
+
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_mesh_level(sc));
+
+ sc->src_mesh = sc->dst_mesh;
+
+ ufbxi_buf_free(&sc->source);
+ ufbxi_buf_free(&sc->tmp);
+ sc->source = sc->result;
+ memset(&sc->result, 0, sizeof(sc->result));
+ }
+
+ sc->result.ator = &sc->ator_result;
+ ufbxi_check_err(&sc->error, ufbxi_subdivide_mesh_level(sc));
+ ufbxi_buf_free(&sc->tmp);
+
+ ufbx_mesh *mesh = &sc->dst_mesh;
+
+ // Subdivision always results in a mesh that consists only of quads
+ mesh->max_face_triangles = 2;
+ mesh->num_empty_faces = 0;
+ mesh->num_point_faces = 0;
+ mesh->num_line_faces = 0;
+
+ if (!sc->opts.interpolate_normals) {
+ memset(&mesh->vertex_normal, 0, sizeof(mesh->vertex_normal));
+ memset(&mesh->skinned_normal, 0, sizeof(mesh->skinned_normal));
+ }
+
+ if (!sc->opts.interpolate_normals && !sc->opts.ignore_normals) {
+
+ ufbx_topo_edge *topo = ufbxi_push(&sc->tmp, ufbx_topo_edge, mesh->num_indices);
+ ufbxi_check_err(&sc->error, topo);
+ ufbx_compute_topology(mesh, topo, mesh->num_indices);
+
+ uint32_t *normal_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
+ ufbxi_check_err(&sc->error, normal_indices);
+
+ size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, mesh->num_indices, normal_indices, mesh->num_indices, true);
+ if (num_normals == mesh->num_vertices) {
+ mesh->skinned_normal.unique_per_vertex = true;
+ }
+
+ ufbx_vec3 *normal_data = ufbxi_push(&sc->result, ufbx_vec3, num_normals + 1);
+ ufbxi_check_err(&sc->error, normal_data);
+ normal_data[0] = ufbx_zero_vec3;
+ normal_data++;
+
+ ufbx_compute_normals(mesh, &mesh->skinned_position, normal_indices, mesh->num_indices, normal_data, num_normals);
+
+ mesh->generated_normals = true;
+ mesh->vertex_normal.exists = true;
+ mesh->vertex_normal.values.data = normal_data;
+ mesh->vertex_normal.values.count = num_normals;
+ mesh->vertex_normal.indices.data = normal_indices;
+ mesh->vertex_normal.indices.count = mesh->num_indices;
+
+ mesh->skinned_normal = mesh->vertex_normal;
+ }
+
+ ufbxi_refcount *parent = NULL;
+ if (sc->src_mesh_ptr->subdivision_evaluated && sc->src_mesh_ptr->from_tessellated_nurbs) {
+ parent = &(ufbxi_get_imp(ufbxi_mesh_imp, sc->src_mesh_ptr))->refcount;
+ } else {
+ parent = &(ufbxi_get_imp(ufbxi_scene_imp, sc->src_mesh_ptr->element.scene))->refcount;
+ }
+
+ ufbxi_patch_mesh_reals(mesh);
+
+ sc->imp = ufbxi_push(&sc->result, ufbxi_mesh_imp, 1);
+ ufbxi_check_err(&sc->error, sc->imp);
+
+ sc->dst_mesh.subdivision_result->result_memory_used = sc->ator_result.current_size;
+ sc->dst_mesh.subdivision_result->temp_memory_used = sc->ator_tmp.current_size;
+ sc->dst_mesh.subdivision_result->result_allocs = sc->ator_result.num_allocs;
+ sc->dst_mesh.subdivision_result->temp_allocs = sc->ator_tmp.num_allocs;
+
+ ufbxi_init_ref(&sc->imp->refcount, UFBXI_MESH_IMP_MAGIC, parent);
+
+ sc->imp->magic = UFBXI_MESH_IMP_MAGIC;
+ sc->imp->mesh = sc->dst_mesh;
+ sc->imp->refcount.ator = sc->ator_result;
+ sc->imp->refcount.buf = sc->result;
+ sc->imp->mesh.subdivision_evaluated = true;
+
+ return 1;
+}
+
+ufbxi_noinline static ufbx_mesh *ufbxi_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *user_opts, ufbx_error *p_error)
+{
+ ufbxi_subdivide_context sc = { 0 };
+ if (user_opts) {
+ sc.opts = *user_opts;
+ }
+
+ sc.src_mesh_ptr = (ufbx_mesh*)mesh;
+ sc.src_mesh = *mesh;
+
+ int ok = ufbxi_subdivide_mesh_imp(&sc, level);
+
+ ufbxi_free(&sc.ator_tmp, ufbxi_subdivide_input, sc.inputs, sc.inputs_cap);
+ ufbxi_buf_free(&sc.tmp);
+ ufbxi_buf_free(&sc.source);
+
+ if (ok) {
+ ufbxi_free_ator(&sc.ator_tmp);
+ if (p_error) {
+ ufbxi_clear_error(p_error);
+ }
+
+ ufbxi_mesh_imp *imp = sc.imp;
+ return &imp->mesh;
+ } else {
+ ufbxi_fix_error_type(&sc.error, "Failed to subdivide", p_error);
+ ufbxi_buf_free(&sc.result);
+ ufbxi_free_ator(&sc.ator_tmp);
+ ufbxi_free_ator(&sc.ator_result);
+ return NULL;
+ }
+}
+
+#else
+
+ufbxi_noinline static ufbx_mesh *ufbxi_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *user_opts, ufbx_error *p_error)
+{
+ if (p_error) {
+ memset(p_error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(p_error, "UFBX_ENABLE_SUBDIVISION");
+ ufbxi_report_err_msg(p_error, "UFBXI_FEATURE_SUBDIVISION", "Feature disabled");
+ }
+ return NULL;
+}
+
+#endif
+
+// -- Utility
+
+#if UFBXI_FEATURE_INDEX_GENERATION
+
+static int ufbxi_map_cmp_vertex(void *user, const void *va, const void *vb)
+{
+ size_t size = *(size_t*)user;
+#if defined(UFBX_REGRESSION)
+ ufbx_assert(size % 8 == 0);
+#endif
+ for (size_t i = 0; i < size; i += 8) {
+ uint64_t a = *(const uint64_t*)((const char*)va + i);
+ uint64_t b = *(const uint64_t*)((const char*)vb + i);
+ if (a != b) return a < b ? -1 : +1;
+ }
+ return 0;
+}
+
+typedef struct {
+ char *begin, *ptr;
+ size_t vertex_size;
+ size_t packed_offset;
+} ufbxi_vertex_stream;
+
+static ufbxi_noinline size_t ufbxi_generate_indices(const ufbx_vertex_stream *user_streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
+{
+ bool fail = false;
+
+ ufbxi_allocator ator = { 0 };
+ ufbxi_init_ator(error, &ator, allocator, "allocator");
+
+ ufbxi_vertex_stream local_streams[16]; // ufbxi_uninit
+ uint64_t local_packed_vertex[64]; // ufbxi_uninit
+
+ ufbxi_vertex_stream *streams = NULL;
+ if (num_streams > ufbxi_arraycount(local_streams)) {
+ streams = ufbxi_alloc(&ator, ufbxi_vertex_stream, num_streams);
+ if (!streams) fail = true;
+ } else {
+ streams = local_streams;
+ }
+
+ size_t packed_size = 0;
+ if (!fail) {
+ for (size_t i = 0; i < num_streams; i++) {
+ if (user_streams[i].vertex_count < num_indices) {
+ ufbxi_fmt_err_info(error, "%zu", i);
+ ufbxi_report_err_msg(error, "user_streams[i].vertex_count < num_indices", "Truncated vertex stream");
+ fail = true;
+ break;
+ }
+
+ size_t vertex_size = user_streams[i].vertex_size;
+ size_t align = ufbxi_size_align_mask(vertex_size);
+ packed_size = ufbxi_align_to_mask(packed_size, align);
+ streams[i].ptr = streams[i].begin = (char*)user_streams[i].data;
+ streams[i].vertex_size = vertex_size;
+ streams[i].packed_offset = packed_size;
+ packed_size += vertex_size;
+ }
+ packed_size = ufbxi_align_to_mask(packed_size, 7);
+ }
+
+ if (!fail && packed_size == 0) {
+ ufbxi_report_err_msg(error, "packed_size != 0", "Zero vertex size");
+ fail = true;
+ }
+
+ char *packed_vertex = NULL;
+ if (!fail) {
+ if (packed_size > sizeof(local_packed_vertex)) {
+ ufbx_assert(packed_size % 8 == 0);
+ packed_vertex = (char*)ufbxi_alloc(&ator, uint64_t, packed_size / 8);
+ if (!packed_vertex) fail = true;
+ } else {
+ packed_vertex = (char*)local_packed_vertex;
+ }
+ }
+
+ ufbxi_map map = { 0 };
+ ufbxi_map_init(&map, &ator, &ufbxi_map_cmp_vertex, &packed_size);
+
+ if (num_indices > 0 && !ufbxi_map_grow_size(&map, packed_size, num_indices)) {
+ fail = true;
+ }
+
+ if (!fail) {
+ ufbx_assert(packed_vertex != NULL);
+ memset(packed_vertex, 0, packed_size);
+
+ for (size_t i = 0; i < num_indices; i++) {
+ for (size_t si = 0; si < num_streams; si++) {
+ size_t size = streams[si].vertex_size, offset = streams[si].packed_offset;
+ char *ptr = streams[si].ptr;
+ memcpy(packed_vertex + offset, ptr, size);
+ streams[si].ptr = ptr + size;
+ }
+
+ uint32_t hash = ufbxi_hash_string(packed_vertex, packed_size);
+ void *entry = ufbxi_map_find_size(&map, packed_size, hash, packed_vertex);
+ if (!entry) {
+ entry = ufbxi_map_insert_size(&map, packed_size, hash, packed_vertex);
+ if (!entry) {
+ fail = true;
+ break;
+ }
+ memcpy(entry, packed_vertex, packed_size);
+ }
+ uint32_t index = (uint32_t)(ufbxi_to_size((char*)entry - (char*)map.items) / packed_size);
+ indices[i] = index;
+ }
+ }
+
+ size_t result_vertices = 0;
+ if (!fail) {
+ result_vertices = map.size;
+
+ for (size_t si = 0; si < num_streams; si++) {
+ size_t vertex_size = streams[si].vertex_size;
+ char *dst = streams[si].begin;
+ char *src = ufbxi_add_ptr((char*)map.items, streams[si].packed_offset);
+ for (size_t i = 0; i < result_vertices; i++) {
+ memcpy(dst, src, vertex_size);
+ dst += vertex_size;
+ src += packed_size;
+ }
+ }
+
+ ufbxi_clear_error(error);
+ } else {
+ ufbxi_fix_error_type(error, "Failed to generate indices", NULL);
+ }
+
+ if (streams && streams != local_streams) {
+ ufbxi_free(&ator, ufbxi_vertex_stream, streams, num_streams);
+ }
+ if (packed_vertex && packed_vertex != (char*)local_packed_vertex) {
+ ufbxi_free(&ator, uint64_t, packed_vertex, packed_size / 8);
+ }
+
+ ufbxi_map_free(&map);
+ ufbxi_free_ator(&ator);
+
+ return result_vertices;
+}
+
+#else
+
+static ufbxi_noinline size_t ufbxi_generate_indices(const ufbx_vertex_stream *user_streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
+{
+ if (error) {
+ memset(error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(error, "UFBX_ENABLE_INDEX_GENERATION");
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_INDEX_GENERATION", "Feature disabled");
+ }
+ return 0;
+}
+
+#endif
+
+static ufbxi_noinline void ufbxi_free_scene_imp(ufbxi_scene_imp *imp)
+{
+ ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
+ ufbxi_buf_free(&imp->string_buf);
+}
+
+static ufbxi_noinline void ufbxi_init_ref(ufbxi_refcount *refcount, uint32_t magic, ufbxi_refcount *parent)
+{
+ if (parent) {
+ ufbxi_retain_ref(parent);
+ }
+
+ ufbxi_atomic_counter_init(&refcount->refcount);
+ refcount->self_magic = UFBXI_REFCOUNT_IMP_MAGIC;
+ refcount->type_magic = magic;
+ refcount->parent = parent;
+}
+
+static ufbxi_noinline void ufbxi_retain_ref(ufbxi_refcount *refcount)
+{
+ ufbx_assert(refcount->self_magic == UFBXI_REFCOUNT_IMP_MAGIC);
+ size_t count = ufbxi_atomic_counter_inc(&refcount->refcount);
+ ufbxi_ignore(count);
+ ufbx_assert(count < SIZE_MAX / 2);
+}
+
+static ufbxi_noinline void ufbxi_release_ref(ufbxi_refcount *refcount)
+{
+ while (refcount) {
+ ufbx_assert(refcount->self_magic == UFBXI_REFCOUNT_IMP_MAGIC);
+ if (ufbxi_atomic_counter_dec(&refcount->refcount) > 0) return;
+ ufbxi_atomic_counter_free(&refcount->refcount);
+
+ ufbxi_refcount *parent = refcount->parent;
+ uint32_t type_magic = refcount->type_magic;
+
+ refcount->self_magic = 0;
+ refcount->type_magic = 0;
+
+ // Type-specific cleanup
+ switch (type_magic) {
+ case UFBXI_SCENE_IMP_MAGIC: ufbxi_free_scene_imp((ufbxi_scene_imp*)refcount); break;
+ case UFBXI_CACHE_IMP_MAGIC: ufbxi_free_geometry_cache_imp((ufbxi_geometry_cache_imp*)refcount); break;
+ default: break;
+ }
+
+ // We need to free `data_buf` last and be careful to copy it to
+ // the stack since the `ufbxi_refcount` that contains it is allocated
+ // from the same result buffer!
+ ufbxi_allocator ator = refcount->ator;
+ ufbxi_buf buf = refcount->buf;
+ buf.ator = &ator;
+ ufbxi_buf_free(&buf);
+ ufbxi_free_ator(&ator);
+
+ refcount = parent;
+ }
+}
+
+static ufbxi_noinline void *ufbxi_uninitialized_options(ufbx_error *p_error)
+{
+ if (p_error) {
+ memset(p_error, 0, sizeof(ufbx_error));
+ p_error->type = UFBX_ERROR_UNINITIALIZED_OPTIONS;
+ p_error->description.data = "Uninitialized options";
+ p_error->description.length = strlen("Uninitialized options");
+ }
+ return NULL;
+}
+
+#define ufbxi_check_opts_ptr(m_type, m_opts, m_error) do { if (m_opts) { \
+ uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
+ ufbx_assert(opts_cleared_to_zero == 0); \
+ if (opts_cleared_to_zero != 0) return (m_type*)ufbxi_uninitialized_options(m_error); \
+ } } while (0)
+
+#define ufbxi_check_opts_return(m_value, m_opts, m_error) do { if (m_opts) { \
+ uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
+ ufbx_assert(opts_cleared_to_zero == 0); \
+ if (opts_cleared_to_zero != 0) { \
+ ufbxi_uninitialized_options(m_error); \
+ return m_value; \
+ } \
+ } } while (0)
+
+#define ufbxi_check_opts_return_no_error(m_value, m_opts) do { if (m_opts) { \
+ uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
+ if (opts_cleared_to_zero != 0) return m_value; \
+ } } while (0)
+
+// -- API
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ufbx_abi_data_def const ufbx_string ufbx_empty_string = { ufbxi_empty_char, 0 };
+ufbx_abi_data_def const ufbx_blob ufbx_empty_blob = { NULL, 0 };
+ufbx_abi_data_def const ufbx_matrix ufbx_identity_matrix = { 1,0,0, 0,1,0, 0,0,1, 0,0,0 };
+ufbx_abi_data_def const ufbx_transform ufbx_identity_transform = { {0,0,0}, {0,0,0,1}, {1,1,1} };
+ufbx_abi_data_def const ufbx_vec2 ufbx_zero_vec2 = { 0,0 };
+ufbx_abi_data_def const ufbx_vec3 ufbx_zero_vec3 = { 0,0,0 };
+ufbx_abi_data_def const ufbx_vec4 ufbx_zero_vec4 = { 0,0,0,0 };
+ufbx_abi_data_def const ufbx_quat ufbx_identity_quat = { 0,0,0,1 };
+
+ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_right_handed_y_up = {
+ UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Y, UFBX_COORDINATE_AXIS_POSITIVE_Z,
+};
+ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_right_handed_z_up = {
+ UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Z, UFBX_COORDINATE_AXIS_NEGATIVE_Y,
+};
+ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_left_handed_y_up = {
+ UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Y, UFBX_COORDINATE_AXIS_NEGATIVE_Z,
+};
+ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_left_handed_z_up = {
+ UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Z, UFBX_COORDINATE_AXIS_POSITIVE_Y,
+};
+
+ufbx_abi_data_def const size_t ufbx_element_type_size[UFBX_ELEMENT_TYPE_COUNT] = {
+ sizeof(ufbx_unknown),
+ sizeof(ufbx_node),
+ sizeof(ufbx_mesh),
+ sizeof(ufbx_light),
+ sizeof(ufbx_camera),
+ sizeof(ufbx_bone),
+ sizeof(ufbx_empty),
+ sizeof(ufbx_line_curve),
+ sizeof(ufbx_nurbs_curve),
+ sizeof(ufbx_nurbs_surface),
+ sizeof(ufbx_nurbs_trim_surface),
+ sizeof(ufbx_nurbs_trim_boundary),
+ sizeof(ufbx_procedural_geometry),
+ sizeof(ufbx_stereo_camera),
+ sizeof(ufbx_camera_switcher),
+ sizeof(ufbx_marker),
+ sizeof(ufbx_lod_group),
+ sizeof(ufbx_skin_deformer),
+ sizeof(ufbx_skin_cluster),
+ sizeof(ufbx_blend_deformer),
+ sizeof(ufbx_blend_channel),
+ sizeof(ufbx_blend_shape),
+ sizeof(ufbx_cache_deformer),
+ sizeof(ufbx_cache_file),
+ sizeof(ufbx_material),
+ sizeof(ufbx_texture),
+ sizeof(ufbx_video),
+ sizeof(ufbx_shader),
+ sizeof(ufbx_shader_binding),
+ sizeof(ufbx_anim_stack),
+ sizeof(ufbx_anim_layer),
+ sizeof(ufbx_anim_value),
+ sizeof(ufbx_anim_curve),
+ sizeof(ufbx_display_layer),
+ sizeof(ufbx_selection_set),
+ sizeof(ufbx_selection_node),
+ sizeof(ufbx_character),
+ sizeof(ufbx_constraint),
+ sizeof(ufbx_audio_layer),
+ sizeof(ufbx_audio_clip),
+ sizeof(ufbx_pose),
+ sizeof(ufbx_metadata_object),
+};
+
+ufbx_abi bool ufbx_default_open_file(void *user, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_info *info)
+{
+ (void)user;
+ return ufbx_open_file_ctx(stream, info->context, path, path_len, NULL, NULL);
+}
+
+ufbx_abi bool ufbx_open_file(ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error)
+{
+ return ufbx_open_file_ctx(stream, (ufbx_open_file_context)NULL, path, path_len, opts, error);
+}
+
+ufbx_abi bool ufbx_open_file_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error)
+{
+ bool ok = false;
+ ufbxi_file_context fc; // ufbxi_uninit
+ ufbxi_begin_file_context(&fc, ctx, NULL);
+ if (path_len == SIZE_MAX) path_len = strlen(path);
+#if !defined(UFBX_NO_STDIO)
+ ok = ufbxi_stdio_open(&fc, stream, path, path_len, opts ? opts->filename_null_terminated : false);
+#else
+ (void)stream;
+ (void)path;
+ (void)path_len;
+ (void)opts;
+ ufbxi_fmt_err_info(&fc.error, "UFBX_NO_STDIO");
+ ufbxi_report_err_msg(&fc.error, "UFBX_NO_STDIO", "Feature disabled");
+#endif
+ ufbxi_end_file_context(&fc, error, ok);
+ return ok;
+}
+
+ufbx_abi bool ufbx_open_memory(ufbx_stream *stream, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error)
+{
+ return ufbx_open_memory_ctx(stream, (ufbx_open_file_context)NULL, data, data_size, opts, error);
+}
+
+ufbx_abi bool ufbx_open_memory_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error)
+{
+ ufbx_open_memory_opts local_opts; // ufbxi_uninit
+ if (!opts) {
+ memset(&local_opts, 0, sizeof(local_opts));
+ opts = &local_opts;
+ }
+ ufbx_assert(opts->_begin_zero == 0 && opts->_end_zero == 0);
+
+ ufbxi_file_context fc; // ufbxi_uninit
+ ufbxi_begin_file_context(&fc, ctx, &opts->allocator);
+
+ size_t copy_size = opts->no_copy ? 0 : data_size;
+
+ // Align the allocation size to 8 bytes to make sure the header is aligned.
+ size_t self_size = ufbxi_align_to_mask(sizeof(ufbxi_memory_stream) + copy_size, 7);
+
+ void *memory = ufbxi_alloc(&fc.ator, char, self_size);
+ if (!memory) {
+ ufbxi_end_file_context(&fc, error, false);
+ return false;
+ }
+
+ ufbxi_memory_stream *mem = (ufbxi_memory_stream*)memory;
+ memset(mem, 0, sizeof(ufbxi_memory_stream));
+
+ mem->size = data_size;
+ mem->self_size = self_size;
+ mem->close_cb = opts->close_cb;
+
+ if (opts->no_copy) {
+ mem->data = data;
+ } else {
+ memcpy(mem->data_copy, data, data_size);
+ mem->data = mem->data_copy;
+ }
+
+ // Transplant the allocator in the result blob
+ if (fc.parent_ator) {
+ mem->parent_ator = fc.parent_ator;
+ } else {
+ fc.parent_ator = &mem->local_ator;
+ }
+
+ stream->read_fn = ufbxi_memory_read;
+ stream->skip_fn = ufbxi_memory_skip;
+ stream->size_fn = ufbxi_memory_size;
+ stream->close_fn = ufbxi_memory_close;
+ stream->user = mem;
+
+ ufbxi_end_file_context(&fc, error, true);
+
+ return true;
+}
+
+ufbx_abi bool ufbx_is_thread_safe(void)
+{
+ return UFBXI_THREAD_SAFE != 0;
+}
+
+ufbx_abi ufbx_scene *ufbx_load_memory(const void *data, size_t size, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_scene, opts, error);
+ ufbxi_context uc; // ufbxi_uninit
+ memset(&uc, 0, sizeof(ufbxi_context));
+ uc.data_begin = uc.data = (const char *)data;
+ uc.data_size = size;
+ uc.progress_bytes_total = size;
+ return ufbxi_load(&uc, opts, error);
+}
+
+ufbx_abi ufbx_scene *ufbx_load_file(const char *filename, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ return ufbx_load_file_len(filename, SIZE_MAX, opts, error);
+}
+
+ufbx_abi ufbx_scene *ufbx_load_file_len(const char *filename, size_t filename_len, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_scene, opts, error);
+ ufbxi_context uc; // ufbxi_uninit
+ memset(&uc, 0, sizeof(ufbxi_context));
+ uc.deferred_load = true;
+ uc.load_filename = filename;
+ uc.load_filename_len = filename_len;
+ return ufbxi_load(&uc, opts, error);
+}
+
+ufbx_abi ufbx_scene *ufbx_load_stdio(void *file_void, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ return ufbx_load_stdio_prefix(file_void, NULL, 0, opts, error);
+}
+
+ufbx_abi ufbx_scene *ufbx_load_stdio_prefix(void *file_void, const void *prefix, size_t prefix_size, const ufbx_load_opts *opts, ufbx_error *error)
+{
+#if !defined(UFBX_NO_STDIO)
+ if (!file_void) return NULL;
+ ufbx_stream stream = { 0 };
+ ufbxi_stdio_init(&stream, file_void, false);
+ return ufbx_load_stream_prefix(&stream, prefix, prefix_size, opts, error);
+#else
+ (void)file_void;
+ (void)prefix;
+ (void)prefix_size;
+ (void)opts;
+
+ ufbxi_context uc; // ufbxi_uninit
+ memset(&uc, 0, sizeof(ufbxi_context));
+ ufbxi_fmt_err_info(&uc.error, "UFBX_NO_STDIO");
+ ufbxi_report_err_msg(&uc.error, "UFBX_NO_STDIO", "Feature disabled");
+ uc.deferred_failure = true;
+ return ufbxi_load(&uc, NULL, error);
+#endif
+}
+
+ufbx_abi ufbx_scene *ufbx_load_stream(const ufbx_stream *stream, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ return ufbx_load_stream_prefix(stream, NULL, 0, opts, error);
+}
+
+ufbx_abi ufbx_scene *ufbx_load_stream_prefix(const ufbx_stream *stream, const void *prefix, size_t prefix_size, const ufbx_load_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_scene, opts, error);
+ ufbxi_context uc; // ufbxi_uninit
+ memset(&uc, 0, sizeof(ufbxi_context));
+ uc.data_begin = uc.data = (const char *)prefix;
+ uc.data_size = prefix_size;
+ uc.read_fn = stream->read_fn;
+ uc.skip_fn = stream->skip_fn;
+ uc.size_fn = stream->size_fn;
+ uc.close_fn = stream->close_fn;
+ uc.read_user = stream->user;
+
+ ufbx_scene *scene = ufbxi_load(&uc, opts, error);
+ return scene;
+}
+
+ufbx_abi void ufbx_free_scene(ufbx_scene *scene)
+{
+ if (!scene) return;
+
+ ufbxi_scene_imp *imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
+ ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
+ if (imp->magic != UFBXI_SCENE_IMP_MAGIC) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_retain_scene(ufbx_scene *scene)
+{
+ if (!scene) return;
+
+ ufbxi_scene_imp *imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
+ ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
+ if (imp->magic != UFBXI_SCENE_IMP_MAGIC) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+ufbx_abi ufbxi_noinline size_t ufbx_format_error(char *dst, size_t dst_size, const ufbx_error *error)
+{
+ if (!dst || !dst_size) return 0;
+ if (!error) {
+ *dst = '\0';
+ return 0;
+ }
+
+ size_t offset = 0;
+
+ {
+ int num;
+ if (error->info_length > 0 && error->info_length < UFBX_ERROR_INFO_LENGTH) {
+ num = ufbxi_snprintf(dst + offset, dst_size - offset, "ufbx v%u.%u.%u error: %s (%.*s)\n",
+ UFBX_SOURCE_VERSION/1000000, UFBX_SOURCE_VERSION/1000%1000, UFBX_SOURCE_VERSION%1000,
+ error->description.data ? error->description.data : "Unknown error",
+ (int)error->info_length, error->info);
+ } else {
+ num = ufbxi_snprintf(dst + offset, dst_size - offset, "ufbx v%u.%u.%u error: %s\n",
+ UFBX_SOURCE_VERSION/1000000, UFBX_SOURCE_VERSION/1000%1000, UFBX_SOURCE_VERSION%1000,
+ error->description.data ? error->description.data : "Unknown error");
+ }
+
+ if (num > 0) offset = ufbxi_min_sz(offset + (size_t)num, dst_size - 1);
+ }
+
+ size_t stack_size = ufbxi_min_sz(error->stack_size, UFBX_ERROR_STACK_MAX_DEPTH);
+ int line_width = 6;
+ for (size_t i = 0; i < stack_size; i++) {
+ const ufbx_error_frame *frame = &error->stack[i];
+ int num = ufbxi_snprintf(dst + offset, dst_size - offset, "%*u:%s: %s\n", line_width, frame->source_line, frame->function.data, frame->description.data);
+ if (num > 0) offset = ufbxi_min_sz(offset + (size_t)num, dst_size - 1);
+ }
+
+ return offset;
+}
+
+ufbx_abi ufbx_prop *ufbx_find_prop_len(const ufbx_props *props, const char *name, size_t name_len)
+{
+ uint32_t key = ufbxi_get_name_key(name, name_len);
+ ufbx_string name_str = ufbxi_safe_string(name, name_len);
+
+ while (props) {
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_prop, 4, &index, props->props.data, 0, props->props.count,
+ ( ufbxi_cmp_prop_less_ref(a, name_str, key) ), ( a->_internal_key == key && ufbxi_str_equal(a->name, name_str) ));
+ if (index != SIZE_MAX) return &props->props.data[index];
+
+ props = props->defaults;
+ }
+
+ return NULL;
+}
+
+ufbx_abi ufbx_real ufbx_find_real_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_real def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_real;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_find_vec3_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_vec3 def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_vec3;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi ufbxi_noinline int64_t ufbx_find_int_len(const ufbx_props *props, const char *name, size_t name_len, int64_t def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_int;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi bool ufbx_find_bool_len(const ufbx_props *props, const char *name, size_t name_len, bool def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_int != 0;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi ufbxi_noinline ufbx_string ufbx_find_string_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_string def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_str;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi ufbx_blob ufbx_find_blob_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_blob def)
+{
+ ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
+ if (prop) {
+ return prop->value_blob;
+ } else {
+ return def;
+ }
+}
+
+ufbx_abi ufbx_prop *ufbx_find_prop_concat(const ufbx_props *props, const ufbx_string *parts, size_t num_parts)
+{
+ uint32_t key = ufbxi_get_concat_key(parts, num_parts);
+
+ while (props) {
+ size_t index = SIZE_MAX;
+
+ ufbxi_macro_lower_bound_eq(ufbx_prop, 2, &index, props->props.data, 0, props->props.count,
+ ( ufbxi_cmp_prop_less_concat(a, parts, num_parts, key) ),
+ ( a->_internal_key == key && ufbxi_concat_str_cmp(&a->name, parts, num_parts) == 0 ));
+ if (index != SIZE_MAX) return &props->props.data[index];
+
+ props = props->defaults;
+ }
+
+ return NULL;
+}
+
+ufbx_abi ufbx_element *ufbx_find_element_len(const ufbx_scene *scene, ufbx_element_type type, const char *name, size_t name_len)
+{
+ if (!scene) return NULL;
+ ufbx_string name_str = ufbxi_safe_string(name, name_len);
+ uint32_t key = ufbxi_get_name_key(name, name_len);
+
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_name_element, 16, &index, scene->elements_by_name.data, 0, scene->elements_by_name.count,
+ ( ufbxi_cmp_name_element_less_ref(a, name_str, type, key) ), ( ufbxi_str_equal(a->name, name_str) && a->type == type ));
+
+ return index < SIZE_MAX ? scene->elements_by_name.data[index].element : NULL;
+}
+
+ufbx_abi ufbx_element *ufbx_get_prop_element(const ufbx_element *element, const ufbx_prop *prop, ufbx_element_type type)
+{
+ ufbx_assert(element && prop);
+ if (!element || !prop) return NULL;
+ return ufbxi_fetch_dst_element((ufbx_element*)element, false, prop->name.data, type);
+}
+
+ufbx_abi ufbx_element *ufbx_find_prop_element_len(const ufbx_element *element, const char *name, size_t name_len, ufbx_element_type type)
+{
+ const ufbx_prop *prop = ufbx_find_prop_len(&element->props, name, name_len);
+ if (prop) {
+ return ufbx_get_prop_element(element, prop, type);
+ } else {
+ return NULL;
+ }
+}
+
+ufbx_abi ufbx_node *ufbx_find_node_len(const ufbx_scene *scene, const char *name, size_t name_len)
+{
+ return (ufbx_node*)ufbx_find_element_len(scene, UFBX_ELEMENT_NODE, name, name_len);
+}
+
+ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack_len(const ufbx_scene *scene, const char *name, size_t name_len)
+{
+ return (ufbx_anim_stack*)ufbx_find_element_len(scene, UFBX_ELEMENT_ANIM_STACK, name, name_len);
+}
+
+ufbx_abi ufbx_material *ufbx_find_material_len(const ufbx_scene *scene, const char *name, size_t name_len)
+{
+ return (ufbx_material*)ufbx_find_element_len(scene, UFBX_ELEMENT_MATERIAL, name, name_len);
+}
+
+ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop_len(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop, size_t prop_len)
+{
+ ufbx_assert(layer);
+ ufbx_assert(element);
+ if (!layer || !element) return NULL;
+
+ ufbx_string prop_str = ufbxi_safe_string(prop, prop_len);
+
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &index, layer->anim_props.data, 0, layer->anim_props.count,
+ ( a->element != element ? a->element < element : ufbxi_str_less(a->prop_name, prop_str) ),
+ ( a->element == element && ufbxi_str_equal(a->prop_name, prop_str) ));
+
+ if (index == SIZE_MAX) return NULL;
+ return &layer->anim_props.data[index];
+}
+
+ufbx_abi ufbxi_noinline ufbx_anim_prop_list ufbx_find_anim_props(const ufbx_anim_layer *layer, const ufbx_element *element)
+{
+ ufbx_anim_prop_list result = { 0 };
+ ufbx_assert(layer);
+ ufbx_assert(element);
+ if (!layer || !element) return result;
+
+ size_t begin = layer->anim_props.count, end = begin;
+ ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &begin, layer->anim_props.data, 0, layer->anim_props.count,
+ ( a->element < element ), ( a->element == element ));
+
+ ufbxi_macro_upper_bound_eq(ufbx_anim_prop, 16, &end, layer->anim_props.data, begin, layer->anim_props.count,
+ ( a->element == element ));
+
+ if (begin != end) {
+ result.data = layer->anim_props.data + begin;
+ result.count = end - begin;
+ }
+
+ return result;
+}
+
+ufbx_abi ufbxi_noinline ufbx_matrix ufbx_get_compatible_matrix_for_normals(const ufbx_node *node)
+{
+ if (!node) return ufbx_identity_matrix;
+
+ ufbx_transform geom_rot = ufbx_identity_transform;
+ geom_rot.rotation = node->geometry_transform.rotation;
+ ufbx_matrix geom_rot_mat = ufbx_transform_to_matrix(&geom_rot);
+
+ ufbx_matrix norm_mat = ufbx_matrix_mul(&node->node_to_world, &geom_rot_mat);
+ norm_mat = ufbx_matrix_for_normals(&norm_mat);
+ return norm_mat;
+}
+
+ufbx_abi ufbx_real ufbx_evaluate_curve(const ufbx_anim_curve *curve, double time, ufbx_real default_value)
+{
+ return ufbx_evaluate_curve_flags(curve, time, default_value, 0);
+}
+
+ufbx_abi ufbx_real ufbx_evaluate_curve_flags(const ufbx_anim_curve *curve, double time, ufbx_real default_value, uint32_t flags)
+{
+ if (!curve) return default_value;
+ if (curve->keyframes.count <= 1) {
+ if (curve->keyframes.count == 1) {
+ return curve->keyframes.data[0].value;
+ } else {
+ return default_value;
+ }
+ }
+
+ if ((flags & UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION) == 0) {
+ if (time < curve->min_time || time > curve->max_time) {
+ return ufbxi_extrapolate_curve(curve, time, flags);
+ }
+ }
+
+ size_t begin = 0;
+ size_t end = curve->keyframes.count;
+ const ufbx_keyframe *keys = curve->keyframes.data;
+ while (end - begin >= 8) {
+ size_t mid = (begin + end) >> 1;
+ if (keys[mid].time <= time) {
+ begin = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ end = curve->keyframes.count;
+ for (; begin < end; begin++) {
+ const ufbx_keyframe *next = &keys[begin];
+ if (next->time <= time) continue;
+
+ // First keyframe
+ if (begin == 0) return next->value;
+
+ const ufbx_keyframe *prev = next - 1;
+
+ // Exact keyframe
+ if (prev->time == time) return prev->value;
+
+ double rcp_delta = 1.0 / (next->time - prev->time);
+ double t = (time - prev->time) * rcp_delta;
+
+ switch (prev->interpolation) {
+
+ case UFBX_INTERPOLATION_CONSTANT_PREV:
+ return prev->value;
+
+ case UFBX_INTERPOLATION_CONSTANT_NEXT:
+ return next->value;
+
+ case UFBX_INTERPOLATION_LINEAR:
+ return (ufbx_real)(prev->value*(1.0 - t) + next->value*t);
+
+ case UFBX_INTERPOLATION_CUBIC:
+ {
+ double x1 = prev->right.dx * rcp_delta;
+ double x2 = 1.0 - next->left.dx * rcp_delta;
+ t = ufbxi_find_cubic_bezier_t(x1, x2, t);
+
+ double t2 = t*t, t3 = t2*t;
+ double u = 1.0 - t, u2 = u*u, u3 = u2*u;
+
+ double y0 = prev->value;
+ double y3 = next->value;
+ double y1 = y0 + prev->right.dy;
+ double y2 = y3 - next->left.dy;
+
+ return (ufbx_real)(u3*y0 + 3.0 * (u2*t*y1 + u*t2*y2) + t3*y3);
+ }
+
+ default:
+ ufbxi_unreachable("Bad interpolation mode");
+ return 0.0f;
+
+ }
+ }
+
+ // Last keyframe
+ return curve->keyframes.data[curve->keyframes.count - 1].value;
+}
+
+ufbx_abi ufbxi_noinline ufbx_real ufbx_evaluate_anim_value_real(const ufbx_anim_value *anim_value, double time)
+{
+ return ufbx_evaluate_anim_value_real_flags(anim_value, time, 0);
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_evaluate_anim_value_vec3(const ufbx_anim_value *anim_value, double time)
+{
+ return ufbx_evaluate_anim_value_vec3_flags(anim_value, time, 0);
+}
+
+ufbx_abi ufbxi_noinline ufbx_real ufbx_evaluate_anim_value_real_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags)
+{
+ if (!anim_value) {
+ return 0.0f;
+ }
+
+ ufbx_real res = anim_value->default_value.x;
+ if (anim_value->curves[0]) res = ufbx_evaluate_curve_flags(anim_value->curves[0], time, res, flags);
+ return res;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_evaluate_anim_value_vec3_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags)
+{
+ if (!anim_value) {
+ ufbx_vec3 zero = { 0.0f };
+ return zero;
+ }
+
+ ufbx_vec3 res = anim_value->default_value;
+ if (anim_value->curves[0]) res.x = ufbx_evaluate_curve_flags(anim_value->curves[0], time, res.x, flags);
+ if (anim_value->curves[1]) res.y = ufbx_evaluate_curve_flags(anim_value->curves[1], time, res.y, flags);
+ if (anim_value->curves[2]) res.z = ufbx_evaluate_curve_flags(anim_value->curves[2], time, res.z, flags);
+ return res;
+}
+
+ufbx_abi ufbxi_noinline ufbx_prop ufbx_evaluate_prop_len(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time)
+{
+ return ufbx_evaluate_prop_flags_len(anim, element, name, name_len, time, 0);
+}
+
+ufbx_abi ufbxi_noinline ufbx_prop ufbx_evaluate_prop_flags_len(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time, uint32_t flags)
+{
+ ufbx_prop result;
+
+ ufbx_prop *prop = ufbx_find_prop_len(&element->props, name, name_len);
+ if (prop) {
+ result = *prop;
+ } else {
+ memset(&result, 0, sizeof(result));
+ result.name.data = name;
+ result.name.length = name_len;
+ result._internal_key = ufbxi_get_name_key(name, name_len);
+ result.flags = UFBX_PROP_FLAG_NOT_FOUND;
+ result.value_str.data = ufbxi_empty_char;
+ result.value_str.length = 0;
+ result.value_blob.data = NULL;
+ result.value_blob.size = 0;
+ }
+
+ if (anim->prop_overrides.count > 0) {
+ ufbxi_find_prop_override(&anim->prop_overrides, element->element_id, &result);
+ return result;
+ }
+
+ if ((result.flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_CONNECTED)) == 0) return result;
+
+ if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
+ ufbxi_evaluate_connected_prop(&result, anim, element, prop->name.data, time, flags);
+ }
+
+ ufbxi_evaluate_props(anim, element, time, &result, 1, flags);
+
+ return result;
+}
+
+ufbx_abi ufbxi_noinline ufbx_props ufbx_evaluate_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size)
+{
+ return ufbx_evaluate_props_flags(anim, element, time, buffer, buffer_size, 0);
+}
+
+ufbx_abi ufbxi_noinline ufbx_props ufbx_evaluate_props_flags(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size, uint32_t flags)
+{
+ ufbx_props ret = { NULL };
+ if (!element) return ret;
+
+ size_t num_anim = 0;
+ ufbxi_prop_iter iter; // ufbxi_uninit
+ ufbxi_init_prop_iter(&iter, anim, element);
+ const ufbx_prop *prop = NULL;
+ while ((prop = ufbxi_next_prop(&iter)) != NULL) {
+ if (!(prop->flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_OVERRIDDEN|UFBX_PROP_FLAG_CONNECTED))) continue;
+ if (num_anim >= buffer_size) break;
+
+ ufbx_prop *dst = &buffer[num_anim++];
+ *dst = *prop;
+
+ if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
+ ufbxi_evaluate_connected_prop(dst, anim, element, prop->name.data, time, flags);
+ }
+ }
+
+ ufbxi_evaluate_props(anim, element, time, buffer, num_anim, flags);
+
+ ret.props.data = buffer;
+ ret.props.count = ret.num_animated = num_anim;
+ ret.defaults = (ufbx_props*)&element->props;
+ return ret;
+}
+
+ufbx_abi ufbxi_noinline ufbx_transform ufbx_evaluate_transform(const ufbx_anim *anim, const ufbx_node *node, double time)
+{
+ return ufbx_evaluate_transform_flags(anim, node, time, 0);
+}
+
+static const char *const ufbxi_transform_props_all[] = {
+ ufbxi_Lcl_Rotation,
+ ufbxi_Lcl_Scaling,
+ ufbxi_Lcl_Translation,
+ ufbxi_PostRotation,
+ ufbxi_PreRotation,
+ ufbxi_RotationOffset,
+ ufbxi_RotationOrder,
+ ufbxi_RotationPivot,
+ ufbxi_ScalingOffset,
+ ufbxi_ScalingPivot,
+};
+
+static const char *const ufbxi_transform_props_rotation[] = {
+ ufbxi_Lcl_Rotation,
+ ufbxi_PostRotation,
+ ufbxi_PreRotation,
+ ufbxi_RotationOrder,
+};
+
+static const char *const ufbxi_transform_props_scale[] = {
+ ufbxi_Lcl_Scaling,
+};
+
+static const char *const ufbxi_transform_props_rotation_scale[] = {
+ ufbxi_Lcl_Rotation,
+ ufbxi_Lcl_Scaling,
+ ufbxi_PostRotation,
+ ufbxi_PreRotation,
+ ufbxi_RotationOrder,
+};
+
+ufbx_abi ufbxi_noinline ufbx_transform ufbx_evaluate_transform_flags(const ufbx_anim *anim, const ufbx_node *node, double time, uint32_t flags)
+{
+ ufbx_assert(anim);
+ ufbx_assert(node);
+ if (!node) return ufbx_identity_transform;
+ if (!anim) return node->local_transform;
+ if (node->is_root) return node->local_transform;
+
+ if ((flags & UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES) == 0) {
+ flags |= UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION;
+ }
+
+ const char *const *prop_names = ufbxi_transform_props_all;
+ size_t num_prop_names = ufbxi_arraycount(ufbxi_transform_props_all);
+ uint32_t components = flags & (UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION);
+ if (components == (UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE)) {
+ prop_names = ufbxi_transform_props_rotation_scale;
+ num_prop_names = ufbxi_arraycount(ufbxi_transform_props_rotation_scale);
+ } else if (components == UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) {
+ prop_names = ufbxi_transform_props_rotation;
+ num_prop_names = ufbxi_arraycount(ufbxi_transform_props_rotation);
+ } else if (components == UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) {
+ prop_names = ufbxi_transform_props_scale;
+ num_prop_names = ufbxi_arraycount(ufbxi_transform_props_scale);
+ } else if (components == 0) {
+ return ufbx_identity_transform;
+ }
+
+ const ufbx_vec3 *translation_scale = NULL;
+ ufbx_prop helper_scale; // ufbxi_uninit
+ ufbx_vec3 scale_factor = ufbxi_one_vec3;
+ bool use_scale_factor = false;
+
+ if (node->parent && (flags & (UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION)) != 0) {
+ ufbx_node *parent = node->parent;
+
+ if ((flags & UFBX_TRANSFORM_FLAG_IGNORE_COMPONENTWISE_SCALE) == 0 && parent->inherit_scale_node) {
+ ufbx_node *p = parent->inherit_scale_node;
+
+ if (node->is_scale_helper) {
+ use_scale_factor = true;
+ }
+
+ while (p && p->scale_helper) {
+ ufbx_prop scale = ufbx_evaluate_prop(anim, &p->scale_helper->element, ufbxi_Lcl_Scaling, time);
+ scale_factor.x *= scale.value_vec3.x;
+ scale_factor.y *= scale.value_vec3.y;
+ scale_factor.z *= scale.value_vec3.z;
+ p = p->inherit_scale_node;
+ }
+ }
+
+ if (parent->scale_helper && (flags & UFBX_TRANSFORM_FLAG_IGNORE_SCALE_HELPER) == 0) {
+ helper_scale = ufbx_evaluate_prop(anim, &parent->scale_helper->element, ufbxi_Lcl_Scaling, time);
+ if (helper_scale.flags & UFBX_PROP_FLAG_NOT_FOUND) {
+ helper_scale.value_vec3.x = 1.0f;
+ helper_scale.value_vec3.y = 1.0f;
+ helper_scale.value_vec3.z = 1.0f;
+ }
+ helper_scale.value_vec3.x *= scale_factor.x;
+ helper_scale.value_vec3.y *= scale_factor.y;
+ helper_scale.value_vec3.z *= scale_factor.z;
+ translation_scale = &helper_scale.value_vec3;
+ }
+ }
+
+ uint32_t eval_flags = 0;
+ if (flags & UFBX_TRANSFORM_FLAG_NO_EXTRAPOLATION) {
+ eval_flags |= UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION;
+ }
+
+ ufbx_prop buf[ufbxi_arraycount(ufbxi_transform_props_all)]; // ufbxi_uninit
+ ufbx_props props = ufbxi_evaluate_selected_props(anim, &node->element, time, buf, prop_names, num_prop_names, eval_flags);
+ ufbx_rotation_order order = (ufbx_rotation_order)ufbxi_find_enum(&props, ufbxi_RotationOrder, UFBX_ROTATION_ORDER_XYZ, UFBX_ROTATION_ORDER_SPHERIC);
+
+ ufbx_transform transform; // ufbxi_uninit
+ if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION) != 0) {
+ transform = ufbxi_get_transform(&props, order, node, translation_scale);
+ } else {
+ transform.translation = ufbx_zero_vec3;
+ if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) != 0) {
+ transform.rotation = ufbxi_get_rotation(&props, order, node);
+ } else {
+ transform.rotation = ufbx_identity_quat;
+ }
+ if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) != 0) {
+ transform.scale = ufbxi_get_scale(&props, node);
+ } else {
+ transform.scale = ufbxi_one_vec3;
+ }
+ }
+
+ if (use_scale_factor) {
+ transform.scale.x *= scale_factor.x;
+ transform.scale.y *= scale_factor.y;
+ transform.scale.z *= scale_factor.z;
+ }
+ return transform;
+}
+
+ufbx_abi ufbx_real ufbx_evaluate_blend_weight(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time)
+{
+ return ufbx_evaluate_blend_weight_flags(anim, channel, time, 0);
+}
+
+ufbx_abi ufbx_real ufbx_evaluate_blend_weight_flags(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time, uint32_t flags)
+{
+ const char *prop_names[] = {
+ ufbxi_DeformPercent,
+ };
+
+ ufbx_prop buf[ufbxi_arraycount(prop_names)]; // ufbxi_uninit
+ ufbx_props props = ufbxi_evaluate_selected_props(anim, &channel->element, time, buf, prop_names, ufbxi_arraycount(prop_names), flags);
+ return ufbxi_find_real(&props, ufbxi_DeformPercent, channel->weight * (ufbx_real)100.0) * (ufbx_real)0.01;
+}
+
+ufbx_abi ufbx_scene *ufbx_evaluate_scene(const ufbx_scene *scene, const ufbx_anim *anim, double time, const ufbx_evaluate_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_scene, opts, error);
+#if UFBXI_FEATURE_SCENE_EVALUATION
+ ufbxi_eval_context ec = { 0 };
+ return ufbxi_evaluate_scene(&ec, (ufbx_scene*)scene, anim, time, opts, error);
+#else
+ if (error) {
+ memset(error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(error, "UFBX_ENABLE_SCENE_EVALUATION");
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_SCENE_EVALUATION", "Feature disabled");
+ }
+ return NULL;
+#endif
+}
+
+ufbx_abi ufbx_anim *ufbx_create_anim(const ufbx_scene *scene, const ufbx_anim_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_anim, opts, error);
+ ufbx_assert(scene);
+
+ ufbxi_create_anim_context ac = { UFBX_ERROR_NONE };
+ if (opts) {
+ ac.opts = *opts;
+ }
+
+ ac.scene = scene;
+
+ int ok = ufbxi_create_anim_imp(&ac);
+
+ if (ok) {
+ ufbxi_clear_error(error);
+ ufbxi_anim_imp *imp = ac.imp;
+ return &imp->anim;
+ } else {
+ ufbxi_fix_error_type(&ac.error, "Failed to create anim", error);
+ ufbxi_buf_free(&ac.result);
+ ufbxi_free_ator(&ac.ator_result);
+ return NULL;
+ }
+}
+
+ufbx_abi void ufbx_free_anim(ufbx_anim *anim)
+{
+ if (!anim) return;
+ if (!anim->custom) return;
+
+ ufbxi_anim_imp *imp = ufbxi_get_imp(ufbxi_anim_imp, anim);
+ ufbx_assert(imp->magic == UFBXI_ANIM_IMP_MAGIC);
+ if (imp->magic != UFBXI_ANIM_IMP_MAGIC) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_retain_anim(ufbx_anim *anim)
+{
+ if (!anim) return;
+ if (!anim->custom) return;
+
+ ufbxi_anim_imp *imp = ufbxi_get_imp(ufbxi_anim_imp, anim);
+ ufbx_assert(imp->magic == UFBXI_ANIM_IMP_MAGIC);
+ if (imp->magic != UFBXI_ANIM_IMP_MAGIC) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+ufbx_abi ufbx_baked_anim *ufbx_bake_anim(const ufbx_scene *scene, const ufbx_anim *anim, const ufbx_bake_opts *opts, ufbx_error *error)
+{
+ ufbx_assert(scene);
+#if UFBXI_FEATURE_ANIMATION_BAKING
+ ufbxi_check_opts_ptr(ufbx_baked_anim, opts, error);
+ if (!anim) {
+ anim = scene->anim;
+ }
+
+ ufbxi_bake_context bc = { UFBX_ERROR_NONE };
+ if (opts) {
+ bc.opts = *opts;
+ }
+
+ bc.scene = scene;
+
+ int ok = ufbxi_bake_anim_imp(&bc, anim);
+
+ ufbxi_buf_free(&bc.tmp);
+ ufbxi_buf_free(&bc.tmp_prop);
+ ufbxi_buf_free(&bc.tmp_times);
+ ufbxi_buf_free(&bc.tmp_bake_props);
+ ufbxi_buf_free(&bc.tmp_nodes);
+ ufbxi_buf_free(&bc.tmp_elements);
+ ufbxi_buf_free(&bc.tmp_props);
+ ufbxi_buf_free(&bc.tmp_bake_stack);
+ ufbxi_free(&bc.ator_tmp, char, bc.tmp_arr, bc.tmp_arr_size);
+ ufbxi_free_ator(&bc.ator_tmp);
+
+ if (ok) {
+ ufbxi_clear_error(error);
+ ufbxi_baked_anim_imp *imp = bc.imp;
+ return &imp->bake;
+ } else {
+ ufbxi_fix_error_type(&bc.error, "Failed to bake anim", error);
+ ufbxi_buf_free(&bc.result);
+ ufbxi_free_ator(&bc.ator_result);
+ return NULL;
+ }
+#else
+ if (error) {
+ memset(error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(error, "UFBX_ENABLE_ANIMATION_BAKING");
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_ANIMATION_BAKING", "Feature disabled");
+ }
+ return NULL;
+#endif
+}
+
+ufbx_abi void ufbx_retain_baked_anim(ufbx_baked_anim *bake)
+{
+ if (!bake) return;
+
+ ufbxi_baked_anim_imp *imp = ufbxi_get_imp(ufbxi_baked_anim_imp, bake);
+ ufbx_assert(imp->magic == UFBXI_BAKED_ANIM_IMP_MAGIC);
+ if (imp->magic != UFBXI_BAKED_ANIM_IMP_MAGIC) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_free_baked_anim(ufbx_baked_anim *bake)
+{
+ if (!bake) return;
+
+ ufbxi_baked_anim_imp *imp = ufbxi_get_imp(ufbxi_baked_anim_imp, bake);
+ ufbx_assert(imp->magic == UFBXI_BAKED_ANIM_IMP_MAGIC);
+ if (imp->magic != UFBXI_BAKED_ANIM_IMP_MAGIC) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+
+ufbx_abi ufbx_baked_node *ufbx_find_baked_node_by_typed_id(ufbx_baked_anim *bake, uint32_t typed_id)
+{
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_baked_node, 8, &index, bake->nodes.data, 0, bake->nodes.count,
+ ( a->typed_id < typed_id ), ( a->typed_id == typed_id) );
+ return index < SIZE_MAX ? &bake->nodes.data[index] : NULL;
+}
+
+ufbx_abi ufbx_baked_node *ufbx_find_baked_node(ufbx_baked_anim *bake, ufbx_node *node)
+{
+ if (!bake || !node) return NULL;
+ return ufbx_find_baked_node_by_typed_id(bake, node->typed_id);
+}
+
+ufbx_abi ufbx_baked_element *ufbx_find_baked_element_by_element_id(ufbx_baked_anim *bake, uint32_t element_id)
+{
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_baked_element, 8, &index, bake->elements.data, 0, bake->elements.count,
+ ( a->element_id < element_id ), ( a->element_id == element_id) );
+ return index < SIZE_MAX ? &bake->elements.data[index] : NULL;
+}
+
+ufbx_abi ufbx_baked_element *ufbx_find_baked_element(ufbx_baked_anim *bake, ufbx_element *element)
+{
+ if (!bake || !element) return NULL;
+ return ufbx_find_baked_element_by_element_id(bake, element->element_id);
+}
+
+ufbx_abi ufbx_vec3 ufbx_evaluate_baked_vec3(ufbx_baked_vec3_list keyframes, double time)
+{
+ size_t begin = 0;
+ size_t end = keyframes.count;
+ const ufbx_baked_vec3 *keys = keyframes.data;
+ while (end - begin >= 8) {
+ size_t mid = (begin + end) >> 1;
+ if (keys[mid].time <= time) {
+ begin = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ end = keyframes.count;
+ for (; begin < end; begin++) {
+ const ufbx_baked_vec3 *next = &keys[begin];
+ if (next->time <= time) continue;
+ if (begin == 0) return next->value;
+
+ const ufbx_baked_vec3 *prev = next - 1;
+ if (prev > keys && (prev->flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && prev[-1].time == time) prev--;
+ if (time == prev->time) return prev->value;
+ double t = (time - prev->time) / (next->time - prev->time);
+ if (prev->flags & UFBX_BAKED_KEY_STEP_LEFT) t = 0.0;
+ if (next->flags & UFBX_BAKED_KEY_STEP_RIGHT) t = 1.0;
+ return ufbxi_lerp3(prev->value, next->value, (ufbx_real)t);
+ }
+
+ return keyframes.data[keyframes.count - 1].value;
+}
+
+ufbx_abi ufbx_quat ufbx_evaluate_baked_quat(ufbx_baked_quat_list keyframes, double time)
+{
+ size_t begin = 0;
+ size_t end = keyframes.count;
+ const ufbx_baked_quat *keys = keyframes.data;
+ while (end - begin >= 8) {
+ size_t mid = (begin + end) >> 1;
+ if (keys[mid].time <= time) {
+ begin = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ end = keyframes.count;
+ for (; begin < end; begin++) {
+ const ufbx_baked_quat *next = &keys[begin];
+ if (next->time <= time) continue;
+ if (begin == 0) return next->value;
+
+ const ufbx_baked_quat *prev = next - 1;
+ if (prev > keys && prev[-1].time == time) prev--;
+ if (time == prev->time) return prev->value;
+ double t = (time - prev->time) / (next->time - prev->time);
+ if (prev > keys && (prev->flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && prev[-1].time == time) prev--;
+ if (prev->flags & UFBX_BAKED_KEY_STEP_LEFT) t = 0.0;
+ if (next->flags & UFBX_BAKED_KEY_STEP_RIGHT) t = 1.0;
+ return ufbx_quat_slerp(prev->value, next->value, (ufbx_real)t);
+ }
+
+ return keyframes.data[keyframes.count - 1].value;
+}
+
+ufbx_abi ufbx_bone_pose *ufbx_get_bone_pose(const ufbx_pose *pose, const ufbx_node *node)
+{
+ if (!pose || !node) return NULL;
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_bone_pose, 8, &index, pose->bone_poses.data, 0, pose->bone_poses.count,
+ ( a->bone_node->typed_id < node->typed_id ), ( a->bone_node == node ));
+ return index < SIZE_MAX ? &pose->bone_poses.data[index] : NULL;
+}
+
+ufbx_abi ufbx_texture *ufbx_find_prop_texture_len(const ufbx_material *material, const char *name, size_t name_len)
+{
+ ufbx_string name_str = ufbxi_safe_string(name, name_len);
+ if (!material) return NULL;
+
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_material_texture, 4, &index, material->textures.data, 0, material->textures.count,
+ ( ufbxi_str_less(a->material_prop, name_str) ), ( ufbxi_str_equal(a->material_prop, name_str) ));
+ return index < SIZE_MAX ? material->textures.data[index].texture : NULL;
+}
+
+ufbx_abi ufbx_string ufbx_find_shader_prop_len(const ufbx_shader *shader, const char *name, size_t name_len)
+{
+ ufbx_shader_prop_binding_list bindings = ufbx_find_shader_prop_bindings_len(shader, name, name_len);
+ if (bindings.count > 0) {
+ return bindings.data[0].material_prop;
+ }
+ return ufbx_empty_string;
+}
+
+ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings_len(const ufbx_shader *shader, const char *name, size_t name_len)
+{
+ ufbx_shader_prop_binding_list bindings = { NULL, 0 };
+
+ ufbx_string name_str = ufbxi_safe_string(name, name_len);
+ if (!shader) return bindings;
+
+ ufbxi_for_ptr_list(ufbx_shader_binding, p_bind, shader->bindings) {
+ ufbx_shader_binding *bind = *p_bind;
+
+ size_t begin = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_shader_prop_binding, 4, &begin, bind->prop_bindings.data, 0, bind->prop_bindings.count,
+ ( ufbxi_str_less(a->shader_prop, name_str) ), ( ufbxi_str_equal(a->shader_prop, name_str) ));
+
+ if (begin != SIZE_MAX) {
+
+ size_t end = begin;
+ ufbxi_macro_upper_bound_eq(ufbx_shader_prop_binding, 4, &end, bind->prop_bindings.data, begin, bind->prop_bindings.count,
+ ( ufbxi_str_equal(a->shader_prop, name_str) ));
+
+ bindings.data = bind->prop_bindings.data + begin;
+ bindings.count = end - begin;
+ break;
+ }
+ }
+
+ return bindings;
+}
+
+ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input_len(const ufbx_shader_texture *shader, const char *name, size_t name_len)
+{
+ ufbx_string name_str = ufbxi_safe_string(name, name_len);
+
+ size_t index = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_shader_texture_input, 4, &index, shader->inputs.data, 0, shader->inputs.count,
+ ( ufbxi_str_less(a->name, name_str) ), ( ufbxi_str_equal(a->name, name_str) ));
+
+ if (index != SIZE_MAX) {
+ return &shader->inputs.data[index];
+ }
+
+ return NULL;
+}
+
+ufbx_abi bool ufbx_coordinate_axes_valid(ufbx_coordinate_axes axes)
+{
+ if (axes.right < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.right > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
+ if (axes.up < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.up > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
+ if (axes.front < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.front > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
+
+ // Check that all the positive/negative axes are used
+ uint32_t mask = 0;
+ mask |= 1u << ((uint32_t)axes.right >> 1);
+ mask |= 1u << ((uint32_t)axes.up >> 1);
+ mask |= 1u << ((uint32_t)axes.front >> 1);
+ return (mask & 0x7u) == 0x7u;
+}
+
+ufbx_abi ufbx_quat ufbx_quat_mul(ufbx_quat a, ufbx_quat b)
+{
+ return ufbxi_mul_quat(a, b);
+}
+
+ufbx_abi ufbx_vec3 ufbx_vec3_normalize(ufbx_vec3 v)
+{
+ return ufbxi_normalize3(v);
+}
+
+ufbx_abi ufbxi_noinline ufbx_real ufbx_quat_dot(ufbx_quat a, ufbx_quat b)
+{
+ return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
+}
+
+ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_normalize(ufbx_quat q)
+{
+ ufbx_real norm = ufbx_quat_dot(q, q);
+ if (norm == 0.0) return ufbx_identity_quat;
+ norm = (ufbx_real)ufbx_sqrt(norm);
+ q.x /= norm;
+ q.y /= norm;
+ q.z /= norm;
+ q.w /= norm;
+ return q;
+}
+
+ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_fix_antipodal(ufbx_quat q, ufbx_quat reference)
+{
+ if (ufbx_quat_dot(q, reference) < 0.0f) {
+ q.x = -q.x; q.y = -q.y; q.z = -q.z; q.w = -q.w;
+ }
+ return q;
+}
+
+ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_slerp(ufbx_quat a, ufbx_quat b, ufbx_real t)
+{
+ double dot = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
+ if (dot < 0.0) {
+ dot = -dot;
+ b.x = -b.x; b.y = -b.y; b.z = -b.z; b.w = -b.w;
+ }
+ double omega = ufbx_acos(ufbx_fmin(ufbx_fmax(dot, 0.0), 1.0));
+ if (omega <= 1.175494351e-38f) return a;
+ double rcp_so = 1.0 / ufbx_sin(omega);
+ double af = ufbx_sin((1.0 - t) * omega) * rcp_so;
+ double bf = ufbx_sin(t * omega) * rcp_so;
+
+ double x = af*a.x + bf*b.x;
+ double y = af*a.y + bf*b.y;
+ double z = af*a.z + bf*b.z;
+ double w = af*a.w + bf*b.w;
+ double rcp_len = 1.0 / ufbx_sqrt(x*x + y*y + z*z + w*w);
+
+ ufbx_quat ret;
+ ret.x = (ufbx_real)(x * rcp_len);
+ ret.y = (ufbx_real)(y * rcp_len);
+ ret.z = (ufbx_real)(z * rcp_len);
+ ret.w = (ufbx_real)(w * rcp_len);
+ return ret;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_quat_rotate_vec3(ufbx_quat q, ufbx_vec3 v)
+{
+ ufbx_real xy = q.x*v.y - q.y*v.x;
+ ufbx_real xz = q.x*v.z - q.z*v.x;
+ ufbx_real yz = q.y*v.z - q.z*v.y;
+ ufbx_vec3 r;
+ r.x = 2.0f * (+ q.w*yz + q.y*xy + q.z*xz) + v.x;
+ r.y = 2.0f * (- q.x*xy - q.w*xz + q.z*yz) + v.y;
+ r.z = 2.0f * (- q.x*xz - q.y*yz + q.w*xy) + v.z;
+ return r;
+}
+
+ufbx_abi ufbxi_noinline ufbx_quat ufbx_euler_to_quat(ufbx_vec3 v, ufbx_rotation_order order)
+{
+ double vx = v.x * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
+ double vy = v.y * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
+ double vz = v.z * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
+ double cx = ufbx_cos(vx), sx = ufbx_sin(vx);
+ double cy = ufbx_cos(vy), sy = ufbx_sin(vy);
+ double cz = ufbx_cos(vz), sz = ufbx_sin(vz);
+ ufbx_quat q;
+
+ // Generated by `misc/gen_rotation_order.py`
+ switch (order) {
+ case UFBX_ROTATION_ORDER_XYZ:
+ q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
+ break;
+ case UFBX_ROTATION_ORDER_XZY:
+ q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
+ break;
+ case UFBX_ROTATION_ORDER_YZX:
+ q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
+ break;
+ case UFBX_ROTATION_ORDER_YXZ:
+ q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
+ break;
+ case UFBX_ROTATION_ORDER_ZXY:
+ q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
+ break;
+ case UFBX_ROTATION_ORDER_ZYX:
+ q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
+ q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
+ q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
+ q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
+ break;
+ default:
+ q.x = q.y = q.z = 0.0f; q.w = 1.0f;
+ break;
+ }
+
+ return q;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_quat_to_euler(ufbx_quat q, ufbx_rotation_order order)
+{
+ // TODO: Derive these rigorously
+ #if defined(UFBX_REAL_IS_FLOAT)
+ const double eps = 0.9999999;
+ #else
+ const double eps = 0.999999999;
+ #endif
+
+ double vx, vy, vz;
+ double t;
+
+ double qx = q.x, qy = q.y, qz = q.z, qw = q.w;
+
+ // Generated by `misc/gen_quat_to_euler.py`
+ switch (order) {
+ case UFBX_ROTATION_ORDER_XYZ:
+ t = 2.0f*(qw*qy - qx*qz);
+ if (ufbx_fabs(t) < eps) {
+ vy = ufbx_asin(t);
+ vz = ufbx_atan2(2.0f*(qw*qz + qx*qy), 2.0f*(qw*qw + qx*qx) - 1.0f);
+ vx = -ufbx_atan2(-2.0f*(qw*qx + qy*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
+ } else {
+ vy = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vz = ufbx_atan2(-2.0f*t*(qw*qx - qy*qz), t*(2.0f*qw*qy + 2.0f*qx*qz));
+ vx = 0.0f;
+ }
+ break;
+ case UFBX_ROTATION_ORDER_XZY:
+ t = 2.0f*(qw*qz + qx*qy);
+ if (ufbx_fabs(t) < eps) {
+ vz = ufbx_asin(t);
+ vy = ufbx_atan2(2.0f*(qw*qy - qx*qz), 2.0f*(qw*qw + qx*qx) - 1.0f);
+ vx = -ufbx_atan2(-2.0f*(qw*qx - qy*qz), 2.0f*(qw*qw + qy*qy) - 1.0f);
+ } else {
+ vz = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vy = ufbx_atan2(2.0f*t*(qw*qx + qy*qz), -t*(2.0f*qx*qy - 2.0f*qw*qz));
+ vx = 0.0f;
+ }
+ break;
+ case UFBX_ROTATION_ORDER_YZX:
+ t = 2.0f*(qw*qz - qx*qy);
+ if (ufbx_fabs(t) < eps) {
+ vz = ufbx_asin(t);
+ vx = ufbx_atan2(2.0f*(qw*qx + qy*qz), 2.0f*(qw*qw + qy*qy) - 1.0f);
+ vy = -ufbx_atan2(-2.0f*(qw*qy + qx*qz), 2.0f*(qw*qw + qx*qx) - 1.0f);
+ } else {
+ vz = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vx = ufbx_atan2(-2.0f*t*(qw*qy - qx*qz), t*(2.0f*qw*qz + 2.0f*qx*qy));
+ vy = 0.0f;
+ }
+ break;
+ case UFBX_ROTATION_ORDER_YXZ:
+ t = 2.0f*(qw*qx + qy*qz);
+ if (ufbx_fabs(t) < eps) {
+ vx = ufbx_asin(t);
+ vz = ufbx_atan2(2.0f*(qw*qz - qx*qy), 2.0f*(qw*qw + qy*qy) - 1.0f);
+ vy = -ufbx_atan2(-2.0f*(qw*qy - qx*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
+ } else {
+ vx = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vz = ufbx_atan2(2.0f*t*(qw*qy + qx*qz), -t*(2.0f*qy*qz - 2.0f*qw*qx));
+ vy = 0.0f;
+ }
+ break;
+ case UFBX_ROTATION_ORDER_ZXY:
+ t = 2.0f*(qw*qx - qy*qz);
+ if (ufbx_fabs(t) < eps) {
+ vx = ufbx_asin(t);
+ vy = ufbx_atan2(2.0f*(qw*qy + qx*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
+ vz = -ufbx_atan2(-2.0f*(qw*qz + qx*qy), 2.0f*(qw*qw + qy*qy) - 1.0f);
+ } else {
+ vx = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vy = ufbx_atan2(-2.0f*t*(qw*qz - qx*qy), t*(2.0f*qw*qx + 2.0f*qy*qz));
+ vz = 0.0f;
+ }
+ break;
+ case UFBX_ROTATION_ORDER_ZYX:
+ t = 2.0f*(qw*qy + qx*qz);
+ if (ufbx_fabs(t) < eps) {
+ vy = ufbx_asin(t);
+ vx = ufbx_atan2(2.0f*(qw*qx - qy*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
+ vz = -ufbx_atan2(-2.0f*(qw*qz - qx*qy), 2.0f*(qw*qw + qx*qx) - 1.0f);
+ } else {
+ vy = ufbx_copysign(UFBXI_DPI*0.5, t);
+ vx = ufbx_atan2(2.0f*t*(qw*qz + qx*qy), -t*(2.0f*qx*qz - 2.0f*qw*qy));
+ vz = 0.0f;
+ }
+ break;
+ default:
+ vx = vy = vz = 0.0;
+ break;
+ }
+
+ vx *= UFBXI_RAD_TO_DEG_DOUBLE;
+ vy *= UFBXI_RAD_TO_DEG_DOUBLE;
+ vz *= UFBXI_RAD_TO_DEG_DOUBLE;
+
+ ufbx_vec3 v = { (ufbx_real)vx, (ufbx_real)vy, (ufbx_real)vz };
+ return v;
+}
+
+ufbx_abi ufbxi_noinline ufbx_matrix ufbx_matrix_mul(const ufbx_matrix *a, const ufbx_matrix *b)
+{
+ ufbx_assert(a && b);
+ if (!a || !b) return ufbx_identity_matrix;
+
+ ufbx_matrix dst;
+
+ dst.m03 = a->m00*b->m03 + a->m01*b->m13 + a->m02*b->m23 + a->m03;
+ dst.m13 = a->m10*b->m03 + a->m11*b->m13 + a->m12*b->m23 + a->m13;
+ dst.m23 = a->m20*b->m03 + a->m21*b->m13 + a->m22*b->m23 + a->m23;
+
+ dst.m00 = a->m00*b->m00 + a->m01*b->m10 + a->m02*b->m20;
+ dst.m10 = a->m10*b->m00 + a->m11*b->m10 + a->m12*b->m20;
+ dst.m20 = a->m20*b->m00 + a->m21*b->m10 + a->m22*b->m20;
+
+ dst.m01 = a->m00*b->m01 + a->m01*b->m11 + a->m02*b->m21;
+ dst.m11 = a->m10*b->m01 + a->m11*b->m11 + a->m12*b->m21;
+ dst.m21 = a->m20*b->m01 + a->m21*b->m11 + a->m22*b->m21;
+
+ dst.m02 = a->m00*b->m02 + a->m01*b->m12 + a->m02*b->m22;
+ dst.m12 = a->m10*b->m02 + a->m11*b->m12 + a->m12*b->m22;
+ dst.m22 = a->m20*b->m02 + a->m21*b->m12 + a->m22*b->m22;
+
+ return dst;
+}
+
+ufbx_abi ufbx_real ufbx_matrix_determinant(const ufbx_matrix *m)
+{
+ return
+ - m->m02*m->m11*m->m20 + m->m01*m->m12*m->m20 + m->m02*m->m10*m->m21
+ - m->m00*m->m12*m->m21 - m->m01*m->m10*m->m22 + m->m00*m->m11*m->m22;
+}
+
+ufbx_abi ufbx_matrix ufbx_matrix_invert(const ufbx_matrix *m)
+{
+ ufbx_real det = ufbx_matrix_determinant(m);
+
+ ufbx_matrix r;
+ if (ufbx_fabs(det) <= UFBX_EPSILON) {
+ memset(&r, 0, sizeof(r));
+ return r;
+ }
+
+ ufbx_real rcp_det = 1.0f / det;
+
+ r.m00 = ( - m->m12*m->m21 + m->m11*m->m22) * rcp_det;
+ r.m10 = ( + m->m12*m->m20 - m->m10*m->m22) * rcp_det;
+ r.m20 = ( - m->m11*m->m20 + m->m10*m->m21) * rcp_det;
+ r.m01 = ( + m->m02*m->m21 - m->m01*m->m22) * rcp_det;
+ r.m11 = ( - m->m02*m->m20 + m->m00*m->m22) * rcp_det;
+ r.m21 = ( + m->m01*m->m20 - m->m00*m->m21) * rcp_det;
+ r.m02 = ( - m->m02*m->m11 + m->m01*m->m12) * rcp_det;
+ r.m12 = ( + m->m02*m->m10 - m->m00*m->m12) * rcp_det;
+ r.m22 = ( - m->m01*m->m10 + m->m00*m->m11) * rcp_det;
+ r.m03 = (m->m03*m->m12*m->m21 - m->m02*m->m13*m->m21 - m->m03*m->m11*m->m22 + m->m01*m->m13*m->m22 + m->m02*m->m11*m->m23 - m->m01*m->m12*m->m23) * rcp_det;
+ r.m13 = (m->m02*m->m13*m->m20 - m->m03*m->m12*m->m20 + m->m03*m->m10*m->m22 - m->m00*m->m13*m->m22 - m->m02*m->m10*m->m23 + m->m00*m->m12*m->m23) * rcp_det;
+ r.m23 = (m->m03*m->m11*m->m20 - m->m01*m->m13*m->m20 - m->m03*m->m10*m->m21 + m->m00*m->m13*m->m21 + m->m01*m->m10*m->m23 - m->m00*m->m11*m->m23) * rcp_det;
+
+ return r;
+}
+
+ufbx_abi ufbxi_noinline ufbx_matrix ufbx_matrix_for_normals(const ufbx_matrix *m)
+{
+ ufbx_real det = ufbx_matrix_determinant(m);
+ ufbx_real det_sign = det >= 0.0f ? 1.0f : -1.0f;
+
+ ufbx_matrix r;
+ r.m00 = ( - m->m12*m->m21 + m->m11*m->m22) * det_sign;
+ r.m01 = ( + m->m12*m->m20 - m->m10*m->m22) * det_sign;
+ r.m02 = ( - m->m11*m->m20 + m->m10*m->m21) * det_sign;
+ r.m10 = ( + m->m02*m->m21 - m->m01*m->m22) * det_sign;
+ r.m11 = ( - m->m02*m->m20 + m->m00*m->m22) * det_sign;
+ r.m12 = ( + m->m01*m->m20 - m->m00*m->m21) * det_sign;
+ r.m20 = ( - m->m02*m->m11 + m->m01*m->m12) * det_sign;
+ r.m21 = ( + m->m02*m->m10 - m->m00*m->m12) * det_sign;
+ r.m22 = ( - m->m01*m->m10 + m->m00*m->m11) * det_sign;
+ r.m03 = r.m13 = r.m23 = 0.0f;
+
+ return r;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_transform_position(const ufbx_matrix *m, ufbx_vec3 v)
+{
+ ufbx_assert(m);
+ if (!m) return ufbx_zero_vec3;
+
+ ufbx_vec3 r;
+ r.x = m->m00*v.x + m->m01*v.y + m->m02*v.z + m->m03;
+ r.y = m->m10*v.x + m->m11*v.y + m->m12*v.z + m->m13;
+ r.z = m->m20*v.x + m->m21*v.y + m->m22*v.z + m->m23;
+ return r;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_transform_direction(const ufbx_matrix *m, ufbx_vec3 v)
+{
+ ufbx_assert(m);
+ if (!m) return ufbx_zero_vec3;
+
+ ufbx_vec3 r;
+ r.x = m->m00*v.x + m->m01*v.y + m->m02*v.z;
+ r.y = m->m10*v.x + m->m11*v.y + m->m12*v.z;
+ r.z = m->m20*v.x + m->m21*v.y + m->m22*v.z;
+ return r;
+}
+
+ufbx_abi ufbxi_noinline ufbx_matrix ufbx_transform_to_matrix(const ufbx_transform *t)
+{
+ ufbx_assert(t);
+ if (!t) return ufbx_identity_matrix;
+
+ ufbx_quat q = t->rotation;
+ ufbx_real sx = 2.0f * t->scale.x, sy = 2.0f * t->scale.y, sz = 2.0f * t->scale.z;
+ ufbx_real xx = q.x*q.x, xy = q.x*q.y, xz = q.x*q.z, xw = q.x*q.w;
+ ufbx_real yy = q.y*q.y, yz = q.y*q.z, yw = q.y*q.w;
+ ufbx_real zz = q.z*q.z, zw = q.z*q.w;
+ ufbx_matrix m;
+ m.m00 = sx * (- yy - zz + 0.5f);
+ m.m10 = sx * (+ xy + zw);
+ m.m20 = sx * (- yw + xz);
+ m.m01 = sy * (- zw + xy);
+ m.m11 = sy * (- xx - zz + 0.5f);
+ m.m21 = sy * (+ xw + yz);
+ m.m02 = sz * (+ xz + yw);
+ m.m12 = sz * (- xw + yz);
+ m.m22 = sz * (- xx - yy + 0.5f);
+ m.m03 = t->translation.x;
+ m.m13 = t->translation.y;
+ m.m23 = t->translation.z;
+ return m;
+}
+
+ufbx_abi ufbxi_noinline ufbx_transform ufbx_matrix_to_transform(const ufbx_matrix *m)
+{
+ ufbx_assert(m);
+ if (!m) return ufbx_identity_transform;
+
+ ufbx_real det = ufbx_matrix_determinant(m);
+
+ ufbx_transform t;
+ t.translation = m->cols[3];
+ t.scale.x = ufbxi_length3(m->cols[0]);
+ t.scale.y = ufbxi_length3(m->cols[1]);
+ t.scale.z = ufbxi_length3(m->cols[2]);
+
+ // Flip a single non-zero axis if negative determinant
+ ufbx_real sign_x = 1.0f;
+ ufbx_real sign_y = 1.0f;
+ ufbx_real sign_z = 1.0f;
+ if (det < 0.0f) {
+ if (t.scale.x > 0.0f) sign_x = -1.0f;
+ else if (t.scale.y > 0.0f) sign_y = -1.0f;
+ else if (t.scale.z > 0.0f) sign_z = -1.0f;
+ }
+
+ ufbx_vec3 x = ufbxi_mul3(m->cols[0], t.scale.x > 0.0f ? sign_x / t.scale.x : 0.0f);
+ ufbx_vec3 y = ufbxi_mul3(m->cols[1], t.scale.y > 0.0f ? sign_y / t.scale.y : 0.0f);
+ ufbx_vec3 z = ufbxi_mul3(m->cols[2], t.scale.z > 0.0f ? sign_z / t.scale.z : 0.0f);
+ ufbx_real trace = x.x + y.y + z.z;
+ if (trace > 0.0f) {
+ ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, trace + 1.0)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
+ t.rotation.x = (y.z - z.y) * b;
+ t.rotation.y = (z.x - x.z) * b;
+ t.rotation.z = (x.y - y.x) * b;
+ t.rotation.w = 0.5f * a;
+ } else if (x.x > y.y && x.x > z.z) {
+ ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 + x.x - y.y - z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
+ t.rotation.x = 0.5f * a;
+ t.rotation.y = (y.x + x.y) * b;
+ t.rotation.z = (z.x + x.z) * b;
+ t.rotation.w = (y.z - z.y) * b;
+ }
+ else if (y.y > z.z) {
+ ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 - x.x + y.y - z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
+ t.rotation.x = (y.x + x.y) * b;
+ t.rotation.y = 0.5f * a;
+ t.rotation.z = (z.y + y.z) * b;
+ t.rotation.w = (z.x - x.z) * b;
+ }
+ else {
+ ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 - x.x - y.y + z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
+ t.rotation.x = (z.x + x.z) * b;
+ t.rotation.y = (z.y + y.z) * b;
+ t.rotation.z = 0.5f * a;
+ t.rotation.w = (x.y - y.x) * b;
+ }
+
+ ufbx_real len = t.rotation.x*t.rotation.x + t.rotation.y*t.rotation.y + t.rotation.z*t.rotation.z + t.rotation.w*t.rotation.w;
+ if (ufbx_fabs(len - 1.0f) > UFBX_EPSILON) {
+ if (ufbx_fabs(len) <= UFBX_EPSILON) {
+ t.rotation = ufbx_identity_quat;
+ } else {
+ t.rotation.x /= len;
+ t.rotation.y /= len;
+ t.rotation.z /= len;
+ t.rotation.w /= len;
+ }
+ }
+
+ t.scale.x *= sign_x;
+ t.scale.y *= sign_y;
+ t.scale.z *= sign_z;
+
+ return t;
+}
+
+ufbx_abi ufbxi_noinline ufbx_matrix ufbx_catch_get_skin_vertex_matrix(ufbx_panic *panic, const ufbx_skin_deformer *skin, size_t vertex, const ufbx_matrix *fallback)
+{
+ ufbx_assert(skin);
+ if (ufbxi_panicf(panic, vertex < skin->vertices.count, "vertex (%zu) out of bounds (%zu)", vertex, skin->vertices.count)) return ufbx_identity_matrix;
+
+ if (!skin || vertex >= skin->vertices.count) return ufbx_identity_matrix;
+ ufbx_skin_vertex skin_vertex = skin->vertices.data[vertex];
+
+ ufbx_matrix mat = { 0.0f };
+ ufbx_quat q0 = { 0.0f }, qe = { 0.0f };
+ ufbx_quat first_q0 = { 0.0f };
+ ufbx_vec3 qs = { 0.0f, 0.0f, 0.0f };
+ ufbx_real total_weight = 0.0f;
+
+ for (uint32_t i = 0; i < skin_vertex.num_weights; i++) {
+ ufbx_skin_weight weight = skin->weights.data[skin_vertex.weight_begin + i];
+ ufbx_skin_cluster *cluster = skin->clusters.data[weight.cluster_index];
+ const ufbx_node *node = cluster->bone_node;
+ if (!node) continue;
+
+ total_weight += weight.weight;
+ if (skin_vertex.dq_weight > 0.0f) {
+ ufbx_transform t = cluster->geometry_to_world_transform;
+ ufbx_quat vq0 = t.rotation;
+ if (i == 0) first_q0 = vq0;
+
+ if (ufbx_quat_dot(first_q0, vq0) < 0.0f) {
+ vq0.x = -vq0.x;
+ vq0.y = -vq0.y;
+ vq0.z = -vq0.z;
+ vq0.w = -vq0.w;
+ }
+
+ ufbx_quat vqt = { 0.5f * t.translation.x, 0.5f * t.translation.y, 0.5f * t.translation.z };
+ ufbx_quat vqe = ufbxi_mul_quat(vqt, vq0);
+ ufbxi_add_weighted_quat(&q0, vq0, weight.weight);
+ ufbxi_add_weighted_quat(&qe, vqe, weight.weight);
+ ufbxi_add_weighted_vec3(&qs, t.scale, weight.weight);
+ }
+
+ if (skin_vertex.dq_weight < 1.0f) {
+ ufbxi_add_weighted_mat(&mat, &cluster->geometry_to_world, (1.0f-skin_vertex.dq_weight) * weight.weight);
+ }
+ }
+
+ if (total_weight <= 0.0f) {
+ if (fallback) {
+ return *fallback;
+ } else {
+ return ufbx_identity_matrix;
+ }
+ }
+
+ if (ufbx_fabs(total_weight - 1.0f) > UFBX_EPSILON) {
+ ufbx_real rcp_weight = ufbx_fabs(total_weight) > UFBX_EPSILON ? 1.0f / total_weight : 0.0f;
+ if (skin_vertex.dq_weight > 0.0f) {
+ q0.x *= rcp_weight; q0.y *= rcp_weight; q0.z *= rcp_weight; q0.w *= rcp_weight;
+ qe.x *= rcp_weight; qe.y *= rcp_weight; qe.z *= rcp_weight; qe.w *= rcp_weight;
+ qs.x *= rcp_weight; qs.y *= rcp_weight; qs.z *= rcp_weight;
+ }
+ if (skin_vertex.dq_weight < 1.0f) {
+ mat.m00 *= rcp_weight; mat.m01 *= rcp_weight; mat.m02 *= rcp_weight; mat.m03 *= rcp_weight;
+ mat.m10 *= rcp_weight; mat.m11 *= rcp_weight; mat.m12 *= rcp_weight; mat.m13 *= rcp_weight;
+ mat.m20 *= rcp_weight; mat.m21 *= rcp_weight; mat.m22 *= rcp_weight; mat.m23 *= rcp_weight;
+ }
+ }
+
+ if (skin_vertex.dq_weight > 0.0f) {
+ ufbx_transform dqt; // ufbxi_uninit
+ ufbx_real rcp_len = (ufbx_real)(1.0 / ufbx_sqrt(q0.x*q0.x + q0.y*q0.y + q0.z*q0.z + q0.w*q0.w));
+ ufbx_real rcp_len2x2 = 2.0f * rcp_len * rcp_len;
+ dqt.rotation.x = q0.x * rcp_len;
+ dqt.rotation.y = q0.y * rcp_len;
+ dqt.rotation.z = q0.z * rcp_len;
+ dqt.rotation.w = q0.w * rcp_len;
+ dqt.scale.x = qs.x;
+ dqt.scale.y = qs.y;
+ dqt.scale.z = qs.z;
+ dqt.translation.x = rcp_len2x2 * (- qe.w*q0.x + qe.x*q0.w - qe.y*q0.z + qe.z*q0.y);
+ dqt.translation.y = rcp_len2x2 * (- qe.w*q0.y + qe.x*q0.z + qe.y*q0.w - qe.z*q0.x);
+ dqt.translation.z = rcp_len2x2 * (- qe.w*q0.z - qe.x*q0.y + qe.y*q0.x + qe.z*q0.w);
+ ufbx_matrix dqm = ufbx_transform_to_matrix(&dqt);
+ if (skin_vertex.dq_weight < 1.0f) {
+ ufbxi_add_weighted_mat(&mat, &dqm, skin_vertex.dq_weight);
+ } else {
+ mat = dqm;
+ }
+ }
+
+ return mat;
+}
+
+ufbx_abi ufbxi_noinline uint32_t ufbx_get_blend_shape_offset_index(const ufbx_blend_shape *shape, size_t vertex)
+{
+ ufbx_assert(shape);
+ if (!shape) return UFBX_NO_INDEX;
+
+ size_t index = SIZE_MAX;
+ uint32_t vertex_ix = (uint32_t)vertex;
+
+ ufbxi_macro_lower_bound_eq(uint32_t, 16, &index, shape->offset_vertices.data, 0, shape->num_offsets,
+ ( *a < vertex_ix ), ( *a == vertex_ix ));
+ if (index >= UINT32_MAX) return UFBX_NO_INDEX;
+
+ return (uint32_t)index;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_get_blend_shape_vertex_offset(const ufbx_blend_shape *shape, size_t vertex)
+{
+ uint32_t index = ufbx_get_blend_shape_offset_index(shape, vertex);
+ if (index == UFBX_NO_INDEX) return ufbx_zero_vec3;
+ return shape->position_offsets.data[index];
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_get_blend_vertex_offset(const ufbx_blend_deformer *blend, size_t vertex)
+{
+ ufbx_assert(blend);
+ if (!blend) return ufbx_zero_vec3;
+
+ ufbx_vec3 offset = ufbx_zero_vec3;
+
+ ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, blend->channels) {
+ ufbx_blend_channel *chan = *p_chan;
+ ufbxi_for_list(ufbx_blend_keyframe, key, chan->keyframes) {
+ if (key->effective_weight == 0.0f) continue;
+
+ ufbx_vec3 key_offset = ufbx_get_blend_shape_vertex_offset(key->shape, vertex);
+ ufbxi_add_weighted_vec3(&offset, key_offset, key->effective_weight);
+ }
+ }
+
+ return offset;
+}
+
+ufbx_abi void ufbx_add_blend_shape_vertex_offsets(const ufbx_blend_shape *shape, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight)
+{
+ if (weight == 0.0f) return;
+ if (!vertices) return;
+
+ size_t num_offsets = shape->num_offsets;
+ uint32_t *vertex_indices = shape->offset_vertices.data;
+ ufbx_vec3 *offsets = shape->position_offsets.data;
+ ufbx_real_list weights = shape->offset_weights;
+ for (size_t i = 0; i < num_offsets; i++) {
+ uint32_t index = vertex_indices[i];
+ if (index < num_vertices) {
+ ufbx_real vertex_weight = weight;
+ if (i < weights.count) {
+ vertex_weight *= weights.data[i];
+ }
+ ufbxi_add_weighted_vec3(&vertices[index], offsets[i], vertex_weight);
+ }
+ }
+}
+
+ufbx_abi void ufbx_add_blend_vertex_offsets(const ufbx_blend_deformer *blend, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight)
+{
+ ufbx_assert(blend);
+ if (!blend) return;
+
+ ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, blend->channels) {
+ ufbx_blend_channel *chan = *p_chan;
+ ufbxi_for_list(ufbx_blend_keyframe, key, chan->keyframes) {
+ if (key->effective_weight == 0.0f) continue;
+ ufbx_add_blend_shape_vertex_offsets(key->shape, vertices, num_vertices, weight * key->effective_weight);
+ }
+ }
+}
+
+ufbx_abi size_t ufbx_evaluate_nurbs_basis(const ufbx_nurbs_basis *basis, ufbx_real u, ufbx_real *weights, size_t num_weights, ufbx_real *derivatives, size_t num_derivatives)
+{
+ ufbx_assert(basis);
+ if (!basis) return SIZE_MAX;
+ if (basis->order == 0) return SIZE_MAX;
+ if (!basis->valid) return SIZE_MAX;
+
+ size_t degree = basis->order - 1;
+ ufbx_assert(degree >= 1);
+
+ // Binary search for the knot span `[min_u, max_u]` where `min_u <= u < max_u`
+ ufbx_real_list knots = basis->knot_vector;
+ size_t knot = SIZE_MAX;
+
+ if (u <= basis->t_min) {
+ knot = degree;
+ u = basis->t_min;
+ } else if (u >= basis->t_max) {
+ knot = basis->knot_vector.count - degree - 2;
+ u = basis->t_max;
+ } else {
+ ufbxi_macro_lower_bound_eq(ufbx_real, 8, &knot, knots.data, 0, knots.count - 1,
+ ( a[1] <= u ), ( a[0] <= u && u < a[1] ));
+ }
+
+ // The found effective control points are found left from `knot`, locally
+ // we use `knot - ix` here as it's more convenient for the following algorithm
+ // but we return it as `knot - degree` so that users can find the control points
+ // at `points[knot], points[knot+1], ..., points[knot+degree]`
+ if (knot < degree) return SIZE_MAX;
+
+ if (num_derivatives == 0) derivatives = NULL;
+ if (num_weights < basis->order) return knot - degree;
+ if (!weights) return knot - degree;
+
+ weights[0] = 1.0f;
+ for (size_t p = 1; p <= degree; p++) {
+
+ ufbx_real prev = 0.0f;
+ ufbx_real g = 1.0f - ufbxi_nurbs_weight(&knots, knot - p + 1, p, u);
+ ufbx_real dg = 0.0f;
+ if (derivatives && p == degree) {
+ dg = ufbxi_nurbs_deriv(&knots, knot - p + 1, p);
+ }
+
+ for (size_t i = p; i > 0; i--) {
+ ufbx_real f = ufbxi_nurbs_weight(&knots, knot - p + i, p, u);
+ ufbx_real weight = weights[i - 1];
+ weights[i] = f*weight + g*prev;
+
+ if (derivatives && p == degree) {
+ ufbx_real df = ufbxi_nurbs_deriv(&knots, knot - p + i, p);
+ if (i < num_derivatives) {
+ derivatives[i] = df*weight - dg*prev;
+ }
+ dg = df;
+ }
+
+ prev = weight;
+ g = 1.0f - f;
+ }
+
+ weights[0] = g*prev;
+ if (derivatives && p == degree) {
+ derivatives[0] = -dg*prev;
+ }
+ }
+
+ return knot - degree;
+}
+
+ufbx_abi ufbxi_noinline ufbx_curve_point ufbx_evaluate_nurbs_curve(const ufbx_nurbs_curve *curve, ufbx_real u)
+{
+ ufbx_curve_point result = { false };
+
+ ufbx_assert(curve);
+ if (!curve) return result;
+
+ ufbx_real weights[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
+ ufbx_real derivs[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
+ size_t base = ufbx_evaluate_nurbs_basis(&curve->basis, u, weights, UFBXI_MAX_NURBS_ORDER, derivs, UFBXI_MAX_NURBS_ORDER);
+ if (base == SIZE_MAX) return result;
+
+ ufbx_vec4 p = { 0 };
+ ufbx_vec4 d = { 0 };
+
+ size_t order = curve->basis.order;
+ if (order > UFBXI_MAX_NURBS_ORDER) return result;
+ if (curve->control_points.count == 0) return result;
+
+ for (size_t i = 0; i < order; i++) {
+ size_t ix = (base + i) % curve->control_points.count;
+ ufbx_vec4 cp = curve->control_points.data[ix];
+ ufbx_real weight = weights[i] * cp.w, deriv = derivs[i] * cp.w;
+
+ p.x += cp.x * weight;
+ p.y += cp.y * weight;
+ p.z += cp.z * weight;
+ p.w += weight;
+
+ d.x += cp.x * deriv;
+ d.y += cp.y * deriv;
+ d.z += cp.z * deriv;
+ d.w += deriv;
+ }
+
+ ufbx_real rcp_w = 1.0f / p.w;
+ result.valid = true;
+ result.position.x = p.x * rcp_w;
+ result.position.y = p.y * rcp_w;
+ result.position.z = p.z * rcp_w;
+ result.derivative.x = (d.x - d.w*result.position.x) * rcp_w;
+ result.derivative.y = (d.y - d.w*result.position.y) * rcp_w;
+ result.derivative.z = (d.z - d.w*result.position.z) * rcp_w;
+ return result;
+}
+
+ufbx_abi ufbxi_noinline ufbx_surface_point ufbx_evaluate_nurbs_surface(const ufbx_nurbs_surface *surface, ufbx_real u, ufbx_real v)
+{
+ ufbx_surface_point result = { false };
+
+ ufbx_assert(surface);
+ if (!surface) return result;
+
+ ufbx_real weights_u[UFBXI_MAX_NURBS_ORDER], weights_v[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
+ ufbx_real derivs_u[UFBXI_MAX_NURBS_ORDER], derivs_v[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
+ size_t base_u = ufbx_evaluate_nurbs_basis(&surface->basis_u, u, weights_u, UFBXI_MAX_NURBS_ORDER, derivs_u, UFBXI_MAX_NURBS_ORDER);
+ size_t base_v = ufbx_evaluate_nurbs_basis(&surface->basis_v, v, weights_v, UFBXI_MAX_NURBS_ORDER, derivs_v, UFBXI_MAX_NURBS_ORDER);
+ if (base_u == SIZE_MAX || base_v == SIZE_MAX) return result;
+
+ ufbx_vec4 p = { 0 };
+ ufbx_vec4 du = { 0 };
+ ufbx_vec4 dv = { 0 };
+
+ size_t num_u = surface->num_control_points_u;
+ size_t num_v = surface->num_control_points_v;
+ size_t order_u = surface->basis_u.order;
+ size_t order_v = surface->basis_v.order;
+ if (order_u > UFBXI_MAX_NURBS_ORDER || order_v > UFBXI_MAX_NURBS_ORDER) return result;
+ if (num_u == 0 || num_v == 0) return result;
+
+ for (size_t vi = 0; vi < order_v; vi++) {
+ size_t vix = (base_v + vi) % num_v;
+ ufbx_real weight_v = weights_v[vi], deriv_v = derivs_v[vi];
+
+ for (size_t ui = 0; ui < order_u; ui++) {
+ size_t uix = (base_u + ui) % num_u;
+ ufbx_real weight_u = weights_u[ui], deriv_u = derivs_u[ui];
+ ufbx_vec4 cp = surface->control_points.data[vix * num_u + uix];
+
+ ufbx_real weight = weight_u * weight_v * cp.w;
+ ufbx_real wderiv_u = deriv_u * weight_v * cp.w;
+ ufbx_real wderiv_v = deriv_v * weight_u * cp.w;
+
+ p.x += cp.x * weight;
+ p.y += cp.y * weight;
+ p.z += cp.z * weight;
+ p.w += weight;
+
+ du.x += cp.x * wderiv_u;
+ du.y += cp.y * wderiv_u;
+ du.z += cp.z * wderiv_u;
+ du.w += wderiv_u;
+
+ dv.x += cp.x * wderiv_v;
+ dv.y += cp.y * wderiv_v;
+ dv.z += cp.z * wderiv_v;
+ dv.w += wderiv_v;
+ }
+ }
+
+ ufbx_real rcp_w = 1.0f / p.w;
+ result.valid = true;
+ result.position.x = p.x * rcp_w;
+ result.position.y = p.y * rcp_w;
+ result.position.z = p.z * rcp_w;
+ result.derivative_u.x = (du.x - du.w*result.position.x) * rcp_w;
+ result.derivative_u.y = (du.y - du.w*result.position.y) * rcp_w;
+ result.derivative_u.z = (du.z - du.w*result.position.z) * rcp_w;
+ result.derivative_v.x = (dv.x - dv.w*result.position.x) * rcp_w;
+ result.derivative_v.y = (dv.y - dv.w*result.position.y) * rcp_w;
+ result.derivative_v.z = (dv.z - dv.w*result.position.z) * rcp_w;
+ return result;
+}
+
+ufbx_abi ufbx_line_curve *ufbx_tessellate_nurbs_curve(const ufbx_nurbs_curve *curve, const ufbx_tessellate_curve_opts *opts, ufbx_error *error)
+{
+#if UFBXI_FEATURE_TESSELLATION
+ ufbxi_check_opts_ptr(ufbx_line_curve, opts, error);
+ ufbx_assert(curve);
+ if (!curve) return NULL;
+
+ ufbxi_tessellate_curve_context tc = { UFBX_ERROR_NONE };
+ if (opts) {
+ tc.opts = *opts;
+ }
+
+ tc.curve = curve;
+
+ int ok = ufbxi_tessellate_nurbs_curve_imp(&tc);
+
+ ufbxi_free_ator(&tc.ator_tmp);
+
+ if (ok) {
+ ufbxi_clear_error(error);
+ ufbxi_line_curve_imp *imp = tc.imp;
+ return &imp->curve;
+ } else {
+ ufbxi_fix_error_type(&tc.error, "Failed to tessellate", error);
+ ufbxi_buf_free(&tc.result);
+ ufbxi_free_ator(&tc.ator_result);
+ return NULL;
+ }
+#else
+ if (error) {
+ memset(error, 0, sizeof(ufbx_error));
+ ufbxi_fmt_err_info(error, "UFBX_ENABLE_TESSELLATION");
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_TESSELLATION", "Feature disabled");
+ }
+ return NULL;
+#endif
+}
+
+ufbx_abi ufbx_mesh *ufbx_tessellate_nurbs_surface(const ufbx_nurbs_surface *surface, const ufbx_tessellate_surface_opts *opts, ufbx_error *error)
+{
+#if UFBXI_FEATURE_TESSELLATION
+ ufbx_assert(surface);
+ ufbxi_check_opts_ptr(ufbx_mesh, opts, error);
+ if (!surface) return NULL;
+
+ ufbxi_tessellate_surface_context tc = { UFBX_ERROR_NONE };
+ if (opts) {
+ tc.opts = *opts;
+ }
+
+ tc.surface = surface;
+
+ int ok = ufbxi_tessellate_nurbs_surface_imp(&tc);
+
+ ufbxi_buf_free(&tc.tmp);
+ ufbxi_map_free(&tc.position_map);
+ ufbxi_free_ator(&tc.ator_tmp);
+
+ if (ok) {
+ ufbxi_clear_error(error);
+ ufbxi_mesh_imp *imp = tc.imp;
+ return &imp->mesh;
+ } else {
+ ufbxi_fix_error_type(&tc.error, "Failed to tessellate", error);
+ ufbxi_buf_free(&tc.result);
+ ufbxi_free_ator(&tc.ator_result);
+ return NULL;
+ }
+#else
+ if (error) {
+ memset(error, 0, sizeof(ufbx_error));
+ ufbxi_report_err_msg(error, "UFBXI_FEATURE_TESSELLATION", "Feature disabled");
+ }
+ return NULL;
+#endif
+}
+
+ufbx_abi void ufbx_free_line_curve(ufbx_line_curve *line_curve)
+{
+ if (!line_curve) return;
+ if (!line_curve->from_tessellated_nurbs) return;
+
+ ufbxi_line_curve_imp *imp = ufbxi_get_imp(ufbxi_line_curve_imp, line_curve);
+ ufbx_assert(imp->magic == UFBXI_LINE_CURVE_IMP_MAGIC);
+ if (imp->magic != UFBXI_LINE_CURVE_IMP_MAGIC) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_retain_line_curve(ufbx_line_curve *line_curve)
+{
+ if (!line_curve) return;
+ if (!line_curve->from_tessellated_nurbs) return;
+
+ ufbxi_line_curve_imp *imp = ufbxi_get_imp(ufbxi_line_curve_imp, line_curve);
+ ufbx_assert(imp->magic == UFBXI_LINE_CURVE_IMP_MAGIC);
+ if (imp->magic != UFBXI_LINE_CURVE_IMP_MAGIC) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+ufbx_abi uint32_t ufbx_find_face_index(ufbx_mesh *mesh, size_t index)
+{
+ if (!mesh || index > UINT32_MAX) return UFBX_NO_INDEX;
+ uint32_t ix = (uint32_t)index;
+
+ size_t face_ix = SIZE_MAX;
+ ufbxi_macro_lower_bound_eq(ufbx_face, 4, &face_ix, mesh->faces.data, 0, mesh->faces.count,
+ ( a->index_begin + a->num_indices <= ix ), ( ix >= a->index_begin && ix < a->index_begin + a->num_indices ));
+ return (uint32_t)face_ix;
+}
+
+ufbx_abi ufbxi_noinline uint32_t ufbx_catch_triangulate_face(ufbx_panic *panic, uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face)
+{
+#if UFBXI_FEATURE_TRIANGULATION
+ if (face.num_indices < 3) return 0;
+
+ size_t required_indices = ((size_t)face.num_indices - 2) * 3;
+ if (ufbxi_panicf(panic, num_indices >= required_indices, "Face needs at least %zu indices for triangles, got space for %zu", required_indices, num_indices)) return 0;
+ if (ufbxi_panicf(panic, face.index_begin < mesh->num_indices, "Face index begin (%u) out of bounds (%zu)", face.index_begin, mesh->num_indices)) return 0;
+ if (ufbxi_panicf(panic, mesh->num_indices - face.index_begin >= face.num_indices, "Face index end (%u + %u) out of bounds (%zu)", face.index_begin, face.num_indices, mesh->num_indices)) return 0;
+
+ if (face.num_indices == 3) {
+ // Fast case: Already a triangle
+ indices[0] = face.index_begin + 0;
+ indices[1] = face.index_begin + 1;
+ indices[2] = face.index_begin + 2;
+ return 1;
+ } else if (face.num_indices == 4) {
+ // Quad: Split along the shortest axis unless a vertex crosses the axis
+ uint32_t i0 = face.index_begin + 0;
+ uint32_t i1 = face.index_begin + 1;
+ uint32_t i2 = face.index_begin + 2;
+ uint32_t i3 = face.index_begin + 3;
+ ufbx_vec3 v0 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i0]];
+ ufbx_vec3 v1 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i1]];
+ ufbx_vec3 v2 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i2]];
+ ufbx_vec3 v3 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i3]];
+
+ ufbx_vec3 a = ufbxi_sub3(v2, v0);
+ ufbx_vec3 b = ufbxi_sub3(v3, v1);
+
+ ufbx_vec3 na1 = ufbxi_normalize3(ufbxi_cross3(a, ufbxi_sub3(v1, v0)));
+ ufbx_vec3 na3 = ufbxi_normalize3(ufbxi_cross3(a, ufbxi_sub3(v0, v3)));
+ ufbx_vec3 nb0 = ufbxi_normalize3(ufbxi_cross3(b, ufbxi_sub3(v1, v0)));
+ ufbx_vec3 nb2 = ufbxi_normalize3(ufbxi_cross3(b, ufbxi_sub3(v2, v1)));
+
+ ufbx_real dot_aa = ufbxi_dot3(a, a);
+ ufbx_real dot_bb = ufbxi_dot3(b, b);
+ ufbx_real dot_na = ufbxi_dot3(na1, na3);
+ ufbx_real dot_nb = ufbxi_dot3(nb0, nb2);
+
+ bool split_a = dot_aa <= dot_bb;
+
+ if (dot_na < 0.0f || dot_nb < 0.0f) {
+ split_a = dot_na >= dot_nb;
+ }
+
+ if (split_a) {
+ indices[0] = i0;
+ indices[1] = i1;
+ indices[2] = i2;
+ indices[3] = i2;
+ indices[4] = i3;
+ indices[5] = i0;
+ } else {
+ indices[0] = i1;
+ indices[1] = i2;
+ indices[2] = i3;
+ indices[3] = i3;
+ indices[4] = i0;
+ indices[5] = i1;
+ }
+
+ return 2;
+ } else {
+ ufbxi_ngon_context nc = { 0 };
+ nc.positions = mesh->vertex_position;
+ nc.face = face;
+
+ uint32_t num_indices_u32 = num_indices < UINT32_MAX ? (uint32_t)num_indices : UINT32_MAX;
+
+ uint32_t local_indices[12]; // ufbxi_uninit
+ if (num_indices_u32 < 12) {
+ uint32_t num_tris = ufbxi_triangulate_ngon(&nc, local_indices, 12);
+ memcpy(indices, local_indices, num_tris * 3 * sizeof(uint32_t));
+ return num_tris;
+ } else {
+ return ufbxi_triangulate_ngon(&nc, indices, num_indices_u32);
+ }
+ }
+#else
+ ufbxi_panicf_imp(panic, "Triangulation disabled");
+ return 0;
+#endif
+}
+
+ufbx_abi void ufbx_catch_compute_topology(ufbx_panic *panic, const ufbx_mesh *mesh, ufbx_topo_edge *indices, size_t num_indices)
+{
+ if (ufbxi_panicf(panic, num_indices >= mesh->num_indices, "Required mesh.num_indices (%zu) indices, got %zu", mesh->num_indices, num_indices)) return;
+
+ ufbxi_compute_topology(mesh, indices);
+}
+
+ufbx_abi uint32_t ufbx_catch_topo_next_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index)
+{
+ if (index == UFBX_NO_INDEX) return UFBX_NO_INDEX;
+ if (ufbxi_panicf(panic, (size_t)index < num_topo, "index (%u) out of bounds (%zu)", index, num_topo)) return UFBX_NO_INDEX;
+ uint32_t twin = topo[index].twin;
+ if (twin == UFBX_NO_INDEX) return UFBX_NO_INDEX;
+ if (ufbxi_panicf(panic, (size_t)twin < num_topo, "Corrupted topology structure")) return UFBX_NO_INDEX;
+ return topo[twin].next;
+}
+
+ufbx_abi uint32_t ufbx_catch_topo_prev_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index)
+{
+ if (index == UFBX_NO_INDEX) return UFBX_NO_INDEX;
+ if (ufbxi_panicf(panic, (size_t)index < num_topo, "index (%u) out of bounds (%zu)", index, num_topo)) return UFBX_NO_INDEX;
+ return topo[topo[index].prev].twin;
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_catch_get_weighted_face_normal(ufbx_panic *panic, const ufbx_vertex_vec3 *positions, ufbx_face face)
+{
+ if (ufbxi_panicf(panic, face.index_begin <= positions->indices.count, "Face index begin (%u) out of bounds (%zu)", face.index_begin, positions->indices.count)) return ufbx_zero_vec3;
+ if (ufbxi_panicf(panic, positions->indices.count - face.index_begin >= face.num_indices, "Face index end (%u + %u) out of bounds (%zu)", face.index_begin, face.num_indices, positions->indices.count)) return ufbx_zero_vec3;
+
+ if (face.num_indices < 3) {
+ return ufbx_zero_vec3;
+ } else if (face.num_indices == 3) {
+ ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + 0);
+ ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + 1);
+ ufbx_vec3 c = ufbx_get_vertex_vec3(positions, face.index_begin + 2);
+ return ufbxi_cross3(ufbxi_sub3(b, a), ufbxi_sub3(c, a));
+ } else if (face.num_indices == 4) {
+ ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + 0);
+ ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + 1);
+ ufbx_vec3 c = ufbx_get_vertex_vec3(positions, face.index_begin + 2);
+ ufbx_vec3 d = ufbx_get_vertex_vec3(positions, face.index_begin + 3);
+ return ufbxi_cross3(ufbxi_sub3(c, a), ufbxi_sub3(d, b));
+ } else {
+ // Newell's Method
+ ufbx_vec3 result = ufbx_zero_vec3;
+ for (size_t i = 0; i < face.num_indices; i++) {
+ size_t next = i + 1 < face.num_indices ? i + 1 : 0;
+ ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + i);
+ ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + next);
+ result.x += (a.y - b.y) * (a.z + b.z);
+ result.y += (a.z - b.z) * (a.x + b.x);
+ result.z += (a.x - b.x) * (a.y + b.y);
+ }
+ return result;
+ }
+}
+
+size_t ufbx_catch_generate_normal_mapping(ufbx_panic *panic, const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth)
+{
+ uint32_t next_index = 0;
+ if (ufbxi_panicf(panic, num_normal_indices >= mesh->num_indices, "Expected at least mesh.num_indices (%zu), got %zu", mesh->num_indices, num_normal_indices)) return 0;
+
+ for (size_t i = 0; i < mesh->num_indices; i++) {
+ normal_indices[i] = UFBX_NO_INDEX;
+ }
+
+ // Walk around vertices and merge around smooth edges
+ for (size_t vi = 0; vi < mesh->num_vertices; vi++) {
+ uint32_t original_start = mesh->vertex_first_index.data[vi];
+ if (original_start == UFBX_NO_INDEX) continue;
+ uint32_t start = original_start, cur = start;
+
+ for (;;) {
+ uint32_t prev = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
+ if (!ufbxi_is_edge_smooth(mesh, topo, num_topo, cur, assume_smooth)) start = cur;
+ if (prev == UFBX_NO_INDEX) { start = cur; break; }
+ if (prev == original_start) break;
+ cur = prev;
+ }
+
+ normal_indices[start] = next_index++;
+ uint32_t next = start;
+ for (;;) {
+ next = ufbx_topo_prev_vertex_edge(topo, num_topo, next);
+ if (next == UFBX_NO_INDEX || next == start) break;
+
+ if (!ufbxi_is_edge_smooth(mesh, topo, num_topo, next, assume_smooth)) {
+ ++next_index;
+ }
+ normal_indices[next] = next_index - 1;
+ }
+ }
+
+ // Assign non-manifold indices
+ for (size_t i = 0; i < mesh->num_indices; i++) {
+ if (normal_indices[i] == UFBX_NO_INDEX) {
+ normal_indices[i] = next_index++;
+ }
+ }
+
+ return (size_t)next_index;
+}
+
+ufbx_abi size_t ufbx_generate_normal_mapping(const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth)
+{
+ return ufbx_catch_generate_normal_mapping(NULL, mesh, topo, num_topo, normal_indices, num_normal_indices, assume_smooth);
+}
+
+ufbx_abi void ufbx_catch_compute_normals(ufbx_panic *panic, const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions, const uint32_t *normal_indices, size_t num_normal_indices, ufbx_vec3 *normals, size_t num_normals)
+{
+ if (ufbxi_panicf(panic, num_normal_indices >= mesh->num_indices, "Expected at least mesh.num_indices (%zu), got %zu", mesh->num_indices, num_normal_indices)) return;
+
+ memset(normals, 0, sizeof(ufbx_vec3)*num_normals);
+
+ for (size_t fi = 0; fi < mesh->num_faces; fi++) {
+ ufbx_face face = mesh->faces.data[fi];
+ ufbx_vec3 normal = ufbx_get_weighted_face_normal(positions, face);
+ for (size_t ix = 0; ix < face.num_indices; ix++) {
+ uint32_t index = normal_indices[face.index_begin + ix];
+
+ if (ufbxi_panicf(panic, index < num_normals, "Normal index (%u) out of bounds (%zu) at %zu", index, num_normals, ix)) return;
+
+ ufbx_vec3 *n = &normals[index];
+ *n = ufbxi_add3(*n, normal);
+ }
+ }
+
+ for (size_t i = 0; i < num_normals; i++) {
+ ufbx_real len = ufbxi_length3(normals[i]);
+ if (len > 0.0f) {
+ normals[i].x /= len;
+ normals[i].y /= len;
+ normals[i].z /= len;
+ }
+ }
+}
+
+ufbx_abi void ufbx_compute_normals(const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions, const uint32_t *normal_indices, size_t num_normal_indices, ufbx_vec3 *normals, size_t num_normals)
+{
+ ufbx_catch_compute_normals(NULL, mesh, positions, normal_indices, num_normal_indices, normals, num_normals);
+}
+
+ufbx_abi ufbx_mesh *ufbx_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_mesh, opts, error);
+ if (!mesh) return NULL;
+ if (level == 0) return (ufbx_mesh*)mesh;
+ return ufbxi_subdivide_mesh(mesh, level, opts, error);
+}
+
+ufbx_abi void ufbx_free_mesh(ufbx_mesh *mesh)
+{
+ if (!mesh) return;
+ if (!mesh->subdivision_evaluated && !mesh->from_tessellated_nurbs) return;
+
+ ufbxi_mesh_imp *imp = ufbxi_get_imp(ufbxi_mesh_imp, mesh);
+ ufbx_assert(imp->magic == UFBXI_MESH_IMP_MAGIC);
+ if (imp->magic != UFBXI_MESH_IMP_MAGIC) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_retain_mesh(ufbx_mesh *mesh)
+{
+ if (!mesh) return;
+ if (!mesh->subdivision_evaluated && !mesh->from_tessellated_nurbs) return;
+
+ ufbxi_mesh_imp *imp = ufbxi_get_imp(ufbxi_mesh_imp, mesh);
+ ufbx_assert(imp->magic == UFBXI_MESH_IMP_MAGIC);
+ if (imp->magic != UFBXI_MESH_IMP_MAGIC) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache(
+ const char *filename,
+ const ufbx_geometry_cache_opts *opts, ufbx_error *error)
+{
+ return ufbx_load_geometry_cache_len(filename, strlen(filename),
+ opts, error);
+}
+
+ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache_len(
+ const char *filename, size_t filename_len,
+ const ufbx_geometry_cache_opts *opts, ufbx_error *error)
+{
+ ufbxi_check_opts_ptr(ufbx_geometry_cache, opts, error);
+ ufbx_string str = ufbxi_safe_string(filename, filename_len);
+ return ufbxi_load_geometry_cache(str, opts, error);
+}
+
+ufbx_abi void ufbx_free_geometry_cache(ufbx_geometry_cache *cache)
+{
+ if (!cache) return;
+
+ ufbxi_geometry_cache_imp *imp = ufbxi_get_imp(ufbxi_geometry_cache_imp, cache);
+ ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
+ if (imp->magic != UFBXI_CACHE_IMP_MAGIC) return;
+ if (imp->owned_by_scene) return;
+ ufbxi_release_ref(&imp->refcount);
+}
+
+ufbx_abi void ufbx_retain_geometry_cache(ufbx_geometry_cache *cache)
+{
+ if (!cache) return;
+
+ ufbxi_geometry_cache_imp *imp = ufbxi_get_imp(ufbxi_geometry_cache_imp, cache);
+ ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
+ if (imp->magic != UFBXI_CACHE_IMP_MAGIC) return;
+ if (imp->owned_by_scene) return;
+ ufbxi_retain_ref(&imp->refcount);
+}
+
+typedef struct {
+ union {
+ double f64[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
+ float f32[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
+ } src;
+ ufbx_real dst[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
+} ufbxi_geometry_cache_buffer;
+
+ufbx_abi ufbxi_noinline size_t ufbx_read_geometry_cache_real(const ufbx_cache_frame *frame, ufbx_real *data, size_t count, const ufbx_geometry_cache_data_opts *user_opts)
+{
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ ufbxi_check_opts_return_no_error(0, user_opts);
+ if (!frame || count == 0) return 0;
+ ufbx_assert(data);
+ if (!data) return 0;
+
+ ufbx_geometry_cache_data_opts opts; // ufbxi_uninit
+ if (user_opts) {
+ opts = *user_opts;
+ } else {
+ memset(&opts, 0, sizeof(opts));
+ }
+
+ if (!opts.open_file_cb.fn) {
+ opts.open_file_cb.fn = ufbx_default_open_file;
+ }
+
+ bool use_double = false;
+
+ size_t src_count = 0;
+
+ switch (frame->data_format) {
+ case UFBX_CACHE_DATA_FORMAT_UNKNOWN: src_count = 0; break;
+ case UFBX_CACHE_DATA_FORMAT_REAL_FLOAT: src_count = frame->data_count; break;
+ case UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT: src_count = frame->data_count * 3; break;
+ case UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE: src_count = frame->data_count; use_double = true; break;
+ case UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE: src_count = frame->data_count * 3; use_double = true; break;
+ default: ufbxi_unreachable("Bad data_format"); break;
+ }
+
+ bool src_big_endian = false;
+ switch (frame->data_encoding) {
+ case UFBX_CACHE_DATA_ENCODING_UNKNOWN: return 0;
+ case UFBX_CACHE_DATA_ENCODING_LITTLE_ENDIAN: src_big_endian = false; break;
+ case UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN: src_big_endian = true; break;
+ default: ufbxi_unreachable("Bad data_encoding"); break;
+ }
+
+ // Test endianness
+ bool dst_big_endian;
+ {
+ uint8_t buf[2];
+ uint16_t val = 0xbbaa;
+ memcpy(buf, &val, 2);
+ dst_big_endian = buf[0] == 0xbb;
+ }
+
+ if (src_count == 0) return 0;
+ src_count = ufbxi_min_sz(src_count, count);
+
+ ufbx_stream stream = { 0 };
+ if (!ufbxi_open_file(&opts.open_file_cb, &stream, frame->filename.data, frame->filename.length, NULL, NULL, UFBX_OPEN_FILE_GEOMETRY_CACHE)) {
+ return 0;
+ }
+
+ // Skip to the correct point in the file
+ uint64_t offset = frame->data_offset;
+ if (stream.skip_fn) {
+ while (offset > 0) {
+ size_t to_skip = (size_t)ufbxi_min64(offset, UFBXI_MAX_SKIP_SIZE);
+ if (!stream.skip_fn(stream.user, to_skip)) break;
+ offset -= to_skip;
+ }
+ } else {
+ char buffer[4096]; // ufbxi_uninit
+ while (offset > 0) {
+ size_t to_skip = (size_t)ufbxi_min64(offset, sizeof(buffer));
+ size_t num_read = stream.read_fn(stream.user, buffer, to_skip);
+ if (num_read != to_skip) break;
+ offset -= to_skip;
+ }
+ }
+
+ // Failed to skip all the way
+ if (offset > 0) {
+ if (stream.close_fn) {
+ stream.close_fn(stream.user);
+ }
+ return 0;
+ }
+
+ ufbx_real *dst = data;
+ size_t mirror_ix = (size_t)frame->mirror_axis - 1;
+ ufbxi_geometry_cache_buffer buffer; // ufbxi_uninit
+ while (src_count > 0) {
+ size_t to_read = ufbxi_min_sz(src_count, UFBXI_GEOMETRY_CACHE_BUFFER_SIZE);
+ src_count -= to_read;
+ size_t num_read = 0;
+ if (use_double) {
+ size_t bytes_read = stream.read_fn(stream.user, buffer.src.f64, to_read * sizeof(double));
+ if (bytes_read == SIZE_MAX) bytes_read = 0;
+ num_read = bytes_read / sizeof(double);
+ if (src_big_endian != dst_big_endian) {
+ for (size_t i = 0; i < num_read; i++) {
+ char t, *v = (char*)&buffer.src.f64[i];
+ t = v[0]; v[0] = v[7]; v[7] = t;
+ t = v[1]; v[1] = v[6]; v[6] = t;
+ t = v[2]; v[2] = v[5]; v[5] = t;
+ t = v[3]; v[3] = v[4]; v[4] = t;
+ }
+ }
+ ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
+ buffer.dst[i] = (ufbx_real)buffer.src.f64[i];
+ }
+ } else {
+ size_t bytes_read = stream.read_fn(stream.user, buffer.src.f32, to_read * sizeof(float));
+ if (bytes_read == SIZE_MAX) bytes_read = 0;
+ num_read = bytes_read / sizeof(float);
+ if (src_big_endian != dst_big_endian) {
+ for (size_t i = 0; i < num_read; i++) {
+ char t, *v = (char*)&buffer.src.f32[i];
+ t = v[0]; v[0] = v[3]; v[3] = t;
+ t = v[1]; v[1] = v[2]; v[2] = t;
+ }
+ }
+ ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
+ buffer.dst[i] = (ufbx_real)buffer.src.f32[i];
+ }
+ }
+
+ if (!opts.ignore_transform) {
+ ufbx_real scale = frame->scale_factor;
+ if (scale != 1.0f) {
+ for (size_t i = 0; i < num_read; i++) {
+ buffer.dst[i] *= scale;
+ }
+ }
+ if (frame->mirror_axis) {
+ while (mirror_ix < num_read) {
+ buffer.dst[mirror_ix] = -buffer.dst[mirror_ix];
+ mirror_ix += 3;
+ }
+ mirror_ix -= num_read;
+ }
+ }
+
+ if (dst) {
+ ufbx_real weight = opts.use_weight ? opts.weight : 1.0f;
+ if (opts.additive) {
+ ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
+ dst[i] += buffer.dst[i] * weight;
+ }
+ } else {
+ ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
+ dst[i] = buffer.dst[i] * weight;
+ }
+ }
+ dst += num_read;
+ }
+
+ if (num_read != to_read) break;
+ }
+
+ if (stream.close_fn) {
+ stream.close_fn(stream.user);
+ }
+
+ return ufbxi_to_size(dst - data);
+#else
+ return 0;
+#endif
+}
+
+ufbx_abi ufbxi_noinline size_t ufbx_sample_geometry_cache_real(const ufbx_cache_channel *channel, double time, ufbx_real *data, size_t count, const ufbx_geometry_cache_data_opts *user_opts)
+{
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ ufbxi_check_opts_return_no_error(0, user_opts);
+ if (!channel || count == 0) return 0;
+ ufbx_assert(data);
+ if (!data) return 0;
+ if (channel->frames.count == 0) return 0;
+
+ ufbx_geometry_cache_data_opts opts;
+ if (user_opts) {
+ opts = *user_opts;
+ } else {
+ memset(&opts, 0, sizeof(opts));
+ }
+
+ size_t begin = 0;
+ size_t end = channel->frames.count;
+ const ufbx_cache_frame *frames = channel->frames.data;
+ while (end - begin >= 8) {
+ size_t mid = (begin + end) >> 1;
+ if (frames[mid].time < time) {
+ begin = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ const double eps = 0.00000001;
+
+ end = channel->frames.count;
+ for (; begin < end; begin++) {
+ const ufbx_cache_frame *next = &frames[begin];
+ if (next->time < time) continue;
+
+ // First keyframe
+ if (begin == 0) {
+ return ufbx_read_geometry_cache_real(next, data, count, &opts);
+ }
+
+ const ufbx_cache_frame *prev = next - 1;
+
+ // Snap to exact frames if near
+ if (ufbx_fabs(next->time - time) < eps) {
+ return ufbx_read_geometry_cache_real(next, data, count, &opts);
+ }
+ if (ufbx_fabs(prev->time - time) < eps) {
+ return ufbx_read_geometry_cache_real(prev, data, count, &opts);
+ }
+
+ double rcp_delta = 1.0 / (next->time - prev->time);
+ double t = (time - prev->time) * rcp_delta;
+
+ ufbx_real original_weight = opts.use_weight ? opts.weight : 1.0f;
+
+ opts.use_weight = true;
+ opts.weight = (ufbx_real)(original_weight * (1.0 - t));
+ size_t num_prev = ufbx_read_geometry_cache_real(prev, data, count, &opts);
+
+ opts.additive = true;
+ opts.weight = (ufbx_real)(original_weight * t);
+ return ufbx_read_geometry_cache_real(next, data, num_prev, &opts);
+ }
+
+ // Last frame
+ const ufbx_cache_frame *last = &frames[end - 1];
+ return ufbx_read_geometry_cache_real(last, data, count, &opts);
+#else
+ return 0;
+#endif
+}
+
+ufbx_abi ufbxi_noinline size_t ufbx_read_geometry_cache_vec3(const ufbx_cache_frame *frame, ufbx_vec3 *data, size_t count, const ufbx_geometry_cache_data_opts *opts)
+{
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ if (!frame || count == 0) return 0;
+ ufbx_assert(data);
+ if (!data) return 0;
+ return ufbx_read_geometry_cache_real(frame, (ufbx_real*)data, count * 3, opts) / 3;
+#else
+ return 0;
+#endif
+}
+
+ufbx_abi ufbxi_noinline size_t ufbx_sample_geometry_cache_vec3(const ufbx_cache_channel *channel, double time, ufbx_vec3 *data, size_t count, const ufbx_geometry_cache_data_opts *opts)
+{
+#if UFBXI_FEATURE_GEOMETRY_CACHE
+ if (!channel || count == 0) return 0;
+ ufbx_assert(data);
+ if (!data) return 0;
+ return ufbx_sample_geometry_cache_real(channel, time, (ufbx_real*)data, count * 3, opts) / 3;
+#else
+ return 0;
+#endif
+}
+
+ufbx_abi ufbx_dom_node *ufbx_dom_find_len(const ufbx_dom_node *parent, const char *name, size_t name_len)
+{
+ ufbx_string ref = ufbxi_safe_string(name, name_len);
+ ufbxi_for_ptr_list(ufbx_dom_node, p_child, parent->children) {
+ if (ufbxi_str_equal((*p_child)->name, ref)) return (ufbx_dom_node*)*p_child;
+ }
+ return NULL;
+}
+
+ufbx_abi size_t ufbx_generate_indices(const ufbx_vertex_stream *streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
+{
+ ufbx_error local_error; // ufbxi_uninit
+ if (!error) {
+ error = &local_error;
+ }
+ memset(error, 0, sizeof(ufbx_error));
+ return ufbxi_generate_indices(streams, num_streams, indices, num_indices, allocator, error);
+}
+
+ufbx_abi void ufbx_thread_pool_run_task(ufbx_thread_pool_context ctx, uint32_t index)
+{
+ ufbxi_thread_pool_execute((ufbxi_thread_pool*)ctx, index);
+}
+
+ufbx_abi void ufbx_thread_pool_set_user_ptr(ufbx_thread_pool_context ctx, void *user)
+{
+ ufbxi_thread_pool *pool = (ufbxi_thread_pool*)ctx;
+ pool->user_ptr = user;
+}
+
+ufbx_abi void *ufbx_thread_pool_get_user_ptr(ufbx_thread_pool_context ctx)
+{
+ ufbxi_thread_pool *pool = (ufbxi_thread_pool*)ctx;
+ return pool->user_ptr;
+}
+
+ufbx_abi ufbxi_noinline ufbx_real ufbx_catch_get_vertex_real(ufbx_panic *panic, const ufbx_vertex_real *v, size_t index)
+{
+ if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return 0.0f;
+ uint32_t ix = v->indices.data[index];
+ if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return 0.0f;
+ return v->values.data[(int32_t)ix];
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec2 ufbx_catch_get_vertex_vec2(ufbx_panic *panic, const ufbx_vertex_vec2 *v, size_t index)
+{
+ if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec2;
+ uint32_t ix = v->indices.data[index];
+ if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec2;
+ return v->values.data[(int32_t)ix];
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_catch_get_vertex_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index)
+{
+ if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec3;
+ uint32_t ix = v->indices.data[index];
+ if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec3;
+ return v->values.data[(int32_t)ix];
+}
+
+ufbx_abi ufbxi_noinline ufbx_vec4 ufbx_catch_get_vertex_vec4(ufbx_panic *panic, const ufbx_vertex_vec4 *v, size_t index)
+{
+ if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec4;
+ uint32_t ix = v->indices.data[index];
+ if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec4;
+ return v->values.data[(int32_t)ix];
+}
+
+ufbx_abi ufbx_real ufbx_catch_get_vertex_w_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index)
+{
+ if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return 0.0f;
+ if (v->values_w.count == 0) return 0.0f;
+ uint32_t ix = v->indices.data[index];
+ if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return 0.0f;
+ return v->values_w.data[(int32_t)ix];
+}
+
+ufbx_abi ufbx_unknown *ufbx_as_unknown(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_UNKNOWN ? (ufbx_unknown*)element : NULL; }
+ufbx_abi ufbx_node *ufbx_as_node(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NODE ? (ufbx_node*)element : NULL; }
+ufbx_abi ufbx_mesh *ufbx_as_mesh(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MESH ? (ufbx_mesh*)element : NULL; }
+ufbx_abi ufbx_light *ufbx_as_light(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LIGHT ? (ufbx_light*)element : NULL; }
+ufbx_abi ufbx_camera *ufbx_as_camera(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CAMERA ? (ufbx_camera*)element : NULL; }
+ufbx_abi ufbx_bone *ufbx_as_bone(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BONE ? (ufbx_bone*)element : NULL; }
+ufbx_abi ufbx_empty *ufbx_as_empty(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_EMPTY ? (ufbx_empty*)element : NULL; }
+ufbx_abi ufbx_line_curve *ufbx_as_line_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LINE_CURVE ? (ufbx_line_curve*)element : NULL; }
+ufbx_abi ufbx_nurbs_curve *ufbx_as_nurbs_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_CURVE ? (ufbx_nurbs_curve*)element : NULL; }
+ufbx_abi ufbx_nurbs_surface *ufbx_as_nurbs_surface(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_SURFACE ? (ufbx_nurbs_surface*)element : NULL; }
+ufbx_abi ufbx_nurbs_trim_surface *ufbx_as_nurbs_trim_surface(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_TRIM_SURFACE ? (ufbx_nurbs_trim_surface*)element : NULL; }
+ufbx_abi ufbx_nurbs_trim_boundary *ufbx_as_nurbs_trim_boundary(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_TRIM_BOUNDARY ? (ufbx_nurbs_trim_boundary*)element : NULL; }
+ufbx_abi ufbx_procedural_geometry *ufbx_as_procedural_geometry(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_PROCEDURAL_GEOMETRY ? (ufbx_procedural_geometry*)element : NULL; }
+ufbx_abi ufbx_stereo_camera *ufbx_as_stereo_camera(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_STEREO_CAMERA ? (ufbx_stereo_camera*)element : NULL; }
+ufbx_abi ufbx_camera_switcher *ufbx_as_camera_switcher(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CAMERA_SWITCHER ? (ufbx_camera_switcher*)element : NULL; }
+ufbx_abi ufbx_marker *ufbx_as_marker(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MARKER ? (ufbx_marker*)element : NULL; }
+ufbx_abi ufbx_lod_group *ufbx_as_lod_group(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LOD_GROUP ? (ufbx_lod_group*)element : NULL; }
+ufbx_abi ufbx_skin_deformer *ufbx_as_skin_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SKIN_DEFORMER ? (ufbx_skin_deformer*)element : NULL; }
+ufbx_abi ufbx_skin_cluster *ufbx_as_skin_cluster(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SKIN_CLUSTER ? (ufbx_skin_cluster*)element : NULL; }
+ufbx_abi ufbx_blend_deformer *ufbx_as_blend_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_DEFORMER ? (ufbx_blend_deformer*)element : NULL; }
+ufbx_abi ufbx_blend_channel *ufbx_as_blend_channel(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_CHANNEL ? (ufbx_blend_channel*)element : NULL; }
+ufbx_abi ufbx_blend_shape *ufbx_as_blend_shape(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_SHAPE ? (ufbx_blend_shape*)element : NULL; }
+ufbx_abi ufbx_cache_deformer *ufbx_as_cache_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CACHE_DEFORMER ? (ufbx_cache_deformer*)element : NULL; }
+ufbx_abi ufbx_cache_file *ufbx_as_cache_file(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CACHE_FILE ? (ufbx_cache_file*)element : NULL; }
+ufbx_abi ufbx_material *ufbx_as_material(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MATERIAL ? (ufbx_material*)element : NULL; }
+ufbx_abi ufbx_texture *ufbx_as_texture(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_TEXTURE ? (ufbx_texture*)element : NULL; }
+ufbx_abi ufbx_video *ufbx_as_video(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_VIDEO ? (ufbx_video*)element : NULL; }
+ufbx_abi ufbx_shader *ufbx_as_shader(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SHADER ? (ufbx_shader*)element : NULL; }
+ufbx_abi ufbx_shader_binding *ufbx_as_shader_binding(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SHADER_BINDING ? (ufbx_shader_binding*)element : NULL; }
+ufbx_abi ufbx_anim_stack *ufbx_as_anim_stack(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_STACK ? (ufbx_anim_stack*)element : NULL; }
+ufbx_abi ufbx_anim_layer *ufbx_as_anim_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_LAYER ? (ufbx_anim_layer*)element : NULL; }
+ufbx_abi ufbx_anim_value *ufbx_as_anim_value(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_VALUE ? (ufbx_anim_value*)element : NULL; }
+ufbx_abi ufbx_anim_curve *ufbx_as_anim_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_CURVE ? (ufbx_anim_curve*)element : NULL; }
+ufbx_abi ufbx_display_layer *ufbx_as_display_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_DISPLAY_LAYER ? (ufbx_display_layer*)element : NULL; }
+ufbx_abi ufbx_selection_set *ufbx_as_selection_set(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SELECTION_SET ? (ufbx_selection_set*)element : NULL; }
+ufbx_abi ufbx_selection_node *ufbx_as_selection_node(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SELECTION_NODE ? (ufbx_selection_node*)element : NULL; }
+ufbx_abi ufbx_character *ufbx_as_character(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CHARACTER ? (ufbx_character*)element : NULL; }
+ufbx_abi ufbx_constraint *ufbx_as_constraint(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CONSTRAINT ? (ufbx_constraint*)element : NULL; }
+ufbx_abi ufbx_audio_layer *ufbx_as_audio_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_AUDIO_LAYER ? (ufbx_audio_layer*)element : NULL; }
+ufbx_abi ufbx_audio_clip *ufbx_as_audio_clip(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_AUDIO_CLIP ? (ufbx_audio_clip*)element : NULL; }
+ufbx_abi ufbx_pose *ufbx_as_pose(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_POSE ? (ufbx_pose*)element : NULL; }
+ufbx_abi ufbx_metadata_object *ufbx_as_metadata_object(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_METADATA_OBJECT ? (ufbx_metadata_object*)element : NULL; }
+
+ufbx_abi bool ufbx_dom_is_array(const ufbx_dom_node *node) {
+ if (!node || node->values.count != 1) return false;
+ ufbx_dom_value v = node->values.data[0];
+ return v.type >= UFBX_DOM_VALUE_ARRAY_I32 && v.type <= UFBX_DOM_VALUE_ARRAY_BLOB;
+}
+ufbx_abi size_t ufbx_dom_array_size(const ufbx_dom_node *node) {
+ return ufbx_dom_is_array(node) ? (size_t)node->values.data[0].value_int : (size_t)0;
+}
+ufbx_abi ufbx_int32_list ufbx_dom_as_int32_list(const ufbx_dom_node *node) {
+ ufbx_int32_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_I32) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (int32_t*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(int32_t);
+ }
+ return list;
+}
+ufbx_abi ufbx_int64_list ufbx_dom_as_int64_list(const ufbx_dom_node *node) {
+ ufbx_int64_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_I64) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (int64_t*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(int64_t);
+ }
+ return list;
+}
+ufbx_abi ufbx_float_list ufbx_dom_as_float_list(const ufbx_dom_node *node) {
+ ufbx_float_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_F32) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (float*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(float);
+ }
+ return list;
+}
+ufbx_abi ufbx_double_list ufbx_dom_as_double_list(const ufbx_dom_node *node) {
+ ufbx_double_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_F64) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (double*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(double);
+ }
+ return list;
+}
+ufbx_abi ufbx_real_list ufbx_dom_as_real_list(const ufbx_dom_node *node) {
+ ufbx_real_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == (sizeof(ufbx_real) == sizeof(double) ? UFBX_DOM_VALUE_ARRAY_F64 : UFBX_DOM_VALUE_ARRAY_F32)) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (ufbx_real*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(ufbx_real);
+ }
+ return list;
+}
+ufbx_abi ufbx_blob_list ufbx_dom_as_blob_list(const ufbx_dom_node *node) {
+ ufbx_blob_list list = { NULL, 0 };
+ if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_BLOB) {
+ ufbx_dom_value value = node->values.data[0];
+ list.data = (ufbx_blob*)value.value_blob.data;
+ list.count = value.value_blob.size / sizeof(ufbx_blob);
+ }
+ return list;
+}
+
+// -- String API
+
+ufbx_abi ufbx_prop *ufbx_find_prop(const ufbx_props *props, const char *name) { return ufbx_find_prop_len(props, name, strlen(name)); }
+ufbx_abi ufbx_real ufbx_find_real(const ufbx_props *props, const char *name, ufbx_real def) { return ufbx_find_real_len(props, name, strlen(name), def); }
+ufbx_abi ufbx_vec3 ufbx_find_vec3(const ufbx_props *props, const char *name, ufbx_vec3 def) { return ufbx_find_vec3_len(props, name, strlen(name), def); }
+ufbx_abi int64_t ufbx_find_int(const ufbx_props *props, const char *name, int64_t def) { return ufbx_find_int_len(props, name, strlen(name), def); }
+ufbx_abi bool ufbx_find_bool(const ufbx_props *props, const char *name, bool def) { return ufbx_find_bool_len(props, name, strlen(name), def); }
+ufbx_abi ufbx_string ufbx_find_string(const ufbx_props *props, const char *name, ufbx_string def) { return ufbx_find_string_len(props, name, strlen(name), def); }
+ufbx_abi ufbx_blob ufbx_find_blob(const ufbx_props *props, const char *name, ufbx_blob def) { return ufbx_find_blob_len(props, name, strlen(name), def); }
+ufbx_abi ufbx_element *ufbx_find_prop_element(const ufbx_element *element, const char *name, ufbx_element_type type) { return ufbx_find_prop_element_len(element, name, strlen(name), type); }
+ufbx_abi ufbx_element *ufbx_find_element(const ufbx_scene *scene, ufbx_element_type type, const char *name) { return ufbx_find_element_len(scene, type, name, strlen(name)); }
+ufbx_abi ufbx_node *ufbx_find_node(const ufbx_scene *scene, const char *name) { return ufbx_find_node_len(scene, name, strlen(name)); }
+ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack(const ufbx_scene *scene, const char *name) { return ufbx_find_anim_stack_len(scene, name, strlen(name)); }
+ufbx_abi ufbx_material *ufbx_find_material(const ufbx_scene *scene, const char *name) { return ufbx_find_material_len(scene, name, strlen(name)); }
+ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop) { return ufbx_find_anim_prop_len(layer, element, prop, strlen(prop)); }
+ufbx_abi ufbx_prop ufbx_evaluate_prop(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time) { return ufbx_evaluate_prop_len(anim, element, name, strlen(name), time); }
+ufbx_abi ufbx_prop ufbx_evaluate_prop_flags(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags) { return ufbx_evaluate_prop_flags_len(anim, element, name, strlen(name), time, flags); }
+ufbx_abi ufbx_texture *ufbx_find_prop_texture(const ufbx_material *material, const char *name) { return ufbx_find_prop_texture_len(material, name, strlen(name)); }
+ufbx_abi ufbx_string ufbx_find_shader_prop(const ufbx_shader *shader, const char *name) { return ufbx_find_shader_prop_len(shader, name, strlen(name)); }
+ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings(const ufbx_shader *shader, const char *name) { return ufbx_find_shader_prop_bindings_len(shader, name, strlen(name)); }
+ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input(const ufbx_shader_texture *shader, const char *name) { return ufbx_find_shader_texture_input_len(shader, name, strlen(name)); }
+ufbx_abi ufbx_dom_node *ufbx_dom_find(const ufbx_dom_node *parent, const char *name) { return ufbx_dom_find_len(parent, name, strlen(name)); }
+
+// -- Catch API
+
+ufbx_abi uint32_t ufbx_triangulate_face(uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face) {
+ return ufbx_catch_triangulate_face(NULL, indices, num_indices, mesh, face);
+}
+ufbx_abi void ufbx_compute_topology(const ufbx_mesh *mesh, ufbx_topo_edge *topo, size_t num_topo) {
+ ufbx_catch_compute_topology(NULL, mesh, topo, num_topo);
+}
+ufbx_abi uint32_t ufbx_topo_next_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index) {
+ return ufbx_catch_topo_next_vertex_edge(NULL, topo, num_topo, index);
+}
+ufbx_abi uint32_t ufbx_topo_prev_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index) {
+ return ufbx_catch_topo_prev_vertex_edge(NULL, topo, num_topo, index);
+}
+ufbx_abi ufbx_vec3 ufbx_get_weighted_face_normal(const ufbx_vertex_vec3 *positions, ufbx_face face) {
+ return ufbx_catch_get_weighted_face_normal(NULL, positions, face);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#if defined(UFBX_STRING_PREFIX)
+ #undef strlen
+ #undef memcpy
+ #undef memmove
+ #undef memset
+ #undef memchr
+ #undef memcmp
+ #undef strcmp
+ #undef strncmp
+#endif
+
+#if defined(_MSC_VER)
+ #pragma warning(pop)
+#elif defined(__clang__)
+ #pragma clang diagnostic pop
+#elif defined(__GNUC__)
+ #pragma GCC diagnostic pop
+#endif
diff --git a/third_party/ufbx/ufbx.h b/third_party/ufbx/ufbx.h
new file mode 100644
index 00000000..3d572e0a
--- /dev/null
+++ b/third_party/ufbx/ufbx.h
@@ -0,0 +1,6073 @@
+#ifndef UFBX_UFBX_H_INCLUDED
+#define UFBX_UFBX_H_INCLUDED
+
+// -- User configuration
+
+#if defined(UFBX_CONFIG_HEADER)
+ #include UFBX_CONFIG_HEADER
+#endif
+
+// -- Headers
+
+#if !defined(UFBX_NO_LIBC_TYPES)
+ #include <stdint.h>
+ #include <stddef.h>
+ #include <stdbool.h>
+#endif
+
+// -- Platform
+
+#ifndef UFBX_STDC
+ #if defined(__STDC_VERSION__)
+ #define UFBX_STDC __STDC_VERSION__
+ #else
+ #define UFBX_STDC 0
+ #endif
+#endif
+
+#ifndef UFBX_CPP
+ #if defined(__cplusplus)
+ #define UFBX_CPP __cplusplus
+ #else
+ #define UFBX_CPP 0
+ #endif
+#endif
+
+#ifndef UFBX_PLATFORM_MSC
+ #if !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
+ #define UFBX_PLATFORM_MSC _MSC_VER
+ #else
+ #define UFBX_PLATFORM_MSC 0
+ #endif
+#endif
+
+#ifndef UFBX_PLATFORM_GNUC
+ #if !defined(UFBX_STANDARD_C) && defined(__GNUC__)
+ #define UFBX_PLATFORM_GNUC __GNUC__
+ #else
+ #define UFBX_PLATFORM_GNUC 0
+ #endif
+#endif
+
+#ifndef UFBX_CPP11
+ // MSVC does not advertise C++11 by default so we need special detection
+ #if UFBX_CPP >= 201103L || (UFBX_CPP > 0 && UFBX_PLATFORM_MSC >= 1900)
+ #define UFBX_CPP11 1
+ #else
+ #define UFBX_CPP11 0
+ #endif
+#endif
+
+#if defined(_MSC_VER)
+ #pragma warning(push)
+ #pragma warning(disable: 4061) // enumerator 'ENUM' in switch of enum 'enum' is not explicitly handled by a case label
+ #pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union
+ #pragma warning(disable: 4505) // unreferenced local function has been removed
+ #pragma warning(disable: 4820) // type': 'N' bytes padding added after data member 'member'
+#elif defined(__clang__)
+ #pragma clang diagnostic push
+ #pragma clang diagnostic ignored "-Wpedantic"
+ #pragma clang diagnostic ignored "-Wpadded"
+ #if defined(__cplusplus)
+ #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
+ #pragma clang diagnostic ignored "-Wold-style-cast"
+ #endif
+#elif defined(__GNUC__)
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wpedantic"
+ #pragma GCC diagnostic ignored "-Wpadded"
+ #if defined(__cplusplus)
+ #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
+ #pragma GCC diagnostic ignored "-Wold-style-cast"
+ #else
+ #if __GNUC__ >= 5
+ #pragma GCC diagnostic ignored "-Wc90-c99-compat"
+ #pragma GCC diagnostic ignored "-Wc99-c11-compat"
+ #endif
+ #endif
+#endif
+
+#if UFBX_PLATFORM_MSC
+ #define ufbx_inline static __forceinline
+#elif UFBX_PLATFORM_GNUC
+ #define ufbx_inline static inline __attribute__((always_inline, unused))
+#else
+ #define ufbx_inline static
+#endif
+
+// Assertion function used in ufbx, defaults to C standard `assert()`.
+// You can define this to your custom preferred assert macro, but in that case
+// make sure that it is also used within `ufbx.c`.
+// Defining `UFBX_NO_ASSERT` to any value disables assertions.
+#ifndef ufbx_assert
+ #if defined(UFBX_NO_ASSERT) || defined(UFBX_NO_LIBC)
+ #define ufbx_assert(cond) (void)0
+ #else
+ #include <assert.h>
+ #define ufbx_assert(cond) assert(cond)
+ #endif
+#endif
+
+// Pointer may be `NULL`.
+#define ufbx_nullable
+
+// Changing this value from default or calling this function can lead into
+// breaking API guarantees.
+#define ufbx_unsafe
+
+// Linkage of the main ufbx API functions.
+// Defaults to nothing, or `static` if `UFBX_STATIC` is defined.
+// If you want to isolate ufbx to a single translation unit you can do the following:
+// #define UFBX_STATIC
+// #include "ufbx.h"
+// #include "ufbx.c"
+#ifndef ufbx_abi
+ #if defined(UFBX_STATIC)
+ #define ufbx_abi static
+ #else
+ #define ufbx_abi
+ #endif
+#endif
+
+// Linkage of the main ufbx data fields in the header.
+// Defaults to `extern`, or `static` if `UFBX_STATIC` is defined.
+#ifndef ufbx_abi_data
+ #if defined(UFBX_STATIC)
+ #define ufbx_abi_data static
+ #else
+ #define ufbx_abi_data extern
+ #endif
+#endif
+
+// Linkage of the main ufbx data fields in the source.
+// Defaults to nothing, or `static` if `UFBX_STATIC` is defined.
+#ifndef ufbx_abi_data_definition
+ #if defined(UFBX_STATIC)
+ #define ufbx_abi_data_def static
+ #else
+ #define ufbx_abi_data_def
+ #endif
+#endif
+
+// -- Configuration
+
+#ifndef UFBX_REAL_TYPE
+ #if defined(UFBX_REAL_IS_FLOAT)
+ #define UFBX_REAL_TYPE float
+ #else
+ #define UFBX_REAL_TYPE double
+ #endif
+#endif
+
+// Limits for embedded arrays within structures.
+#define UFBX_ERROR_STACK_MAX_DEPTH 8
+#define UFBX_PANIC_MESSAGE_LENGTH 128
+#define UFBX_ERROR_INFO_LENGTH 256
+
+// Number of thread groups to use if threading is enabled.
+// A thread group processes a number of tasks and is then waited and potentially
+// re-used later. In essence, this controls the granularity of threading.
+#define UFBX_THREAD_GROUP_COUNT 4
+
+// -- Language
+
+// bindgen-disable
+
+#if UFBX_CPP11
+
+template <typename T, typename U>
+struct ufbxi_type_is { };
+
+template <typename T>
+struct ufbxi_type_is<T, T> { using type = int; };
+
+template <typename T>
+struct ufbx_converter { };
+
+#define UFBX_CONVERSION_IMPL(p_name) \
+ template <typename T, typename S=typename ufbxi_type_is<T, decltype(ufbx_converter<T>::from(*(const p_name*)nullptr))>::type> \
+ operator T() const { return ufbx_converter<T>::from(*this); }
+
+#define UFBX_CONVERSION_TO_IMPL(p_name) \
+ template <typename T, typename S=typename ufbxi_type_is<p_name, decltype(ufbx_converter<T>::to(*(const T*)nullptr))>::type> \
+ p_name(const T &t) { *this = ufbx_converter<T>::to(t); }
+
+#define UFBX_CONVERSION_LIST_IMPL(p_name) \
+ template <typename T, typename S=typename ufbxi_type_is<T, decltype(ufbx_converter<T>::from_list((p_name*)nullptr, (size_t)0))>::type> \
+ operator T() const { return ufbx_converter<T>::from_list(data, count); }
+
+#else
+
+#define UFBX_CONVERSION_IMPL(p_name)
+#define UFBX_CONVERSION_TO_IMPL(p_name)
+#define UFBX_CONVERSION_LIST_IMPL(p_name)
+
+#endif
+
+#if defined(__cplusplus)
+ #define UFBX_LIST_TYPE(p_name, p_type) struct p_name { p_type *data; size_t count; \
+ p_type &operator[](size_t index) const { ufbx_assert(index < count); return data[index]; } \
+ p_type *begin() const { return data; } \
+ p_type *end() const { return data + count; } \
+ UFBX_CONVERSION_LIST_IMPL(p_type) \
+ }
+#else
+ #define UFBX_LIST_TYPE(p_name, p_type) typedef struct p_name { p_type *data; size_t count; } p_name
+#endif
+
+// This cannot be enabled automatically if supported as the source file may be
+// compiled with a different compiler using different settings than the header
+// consumers, in practice it should work but it causes issues such as #70.
+#if (UFBX_STDC >= 202311L || UFBX_CPP11) && defined(UFBX_USE_EXPLICIT_ENUM)
+ #define UFBX_ENUM_REPR : int
+ #define UFBX_ENUM_FORCE_WIDTH(p_prefix)
+ #define UFBX_FLAG_REPR : int
+ #define UFBX_FLAG_FORCE_WIDTH(p_prefix)
+ #define UFBX_HAS_FORCE_32BIT 0
+#else
+ #define UFBX_ENUM_REPR
+ #define UFBX_ENUM_FORCE_WIDTH(p_prefix) p_prefix##_FORCE_32BIT = 0x7fffffff
+ #define UFBX_FLAG_REPR
+ #define UFBX_FLAG_FORCE_WIDTH(p_prefix) p_prefix##_FORCE_32BIT = 0x7fffffff
+ #define UFBX_HAS_FORCE_32BIT 1
+#endif
+
+#define UFBX_ENUM_TYPE(p_name, p_prefix, p_last) \
+ enum { p_prefix##_COUNT = p_last + 1 }
+
+#if UFBX_CPP
+ #define UFBX_VERTEX_ATTRIB_IMPL(p_type) \
+ p_type &operator[](size_t index) const { ufbx_assert(index < indices.count); return values.data[indices.data[index]]; }
+#else
+ #define UFBX_VERTEX_ATTRIB_IMPL(p_type)
+#endif
+
+#if UFBX_CPP11
+ #define UFBX_CALLBACK_IMPL(p_name, p_fn, p_return, p_params, p_args) \
+ template <typename F> static p_return _cpp_adapter p_params { F &f = *static_cast<F*>(user); return f p_args; } \
+ p_name() = default; \
+ p_name(p_fn *f) : fn(f), user(nullptr) { } \
+ template <typename F> p_name(F *f) : fn(&_cpp_adapter<F>), user(static_cast<void*>(f)) { }
+#else
+ #define UFBX_CALLBACK_IMPL(p_name, p_fn, p_return, p_params, p_args)
+#endif
+
+// bindgen-enable
+
+// -- Version
+
+// Packing/unpacking for `UFBX_HEADER_VERSION` and `ufbx_source_version`.
+#define ufbx_pack_version(major, minor, patch) ((major)*1000000u + (minor)*1000u + (patch))
+#define ufbx_version_major(version) ((uint32_t)(version)/1000000u%1000u)
+#define ufbx_version_minor(version) ((uint32_t)(version)/1000u%1000u)
+#define ufbx_version_patch(version) ((uint32_t)(version)%1000u)
+
+// Version of the ufbx header.
+// `UFBX_VERSION` is simply an alias of `UFBX_HEADER_VERSION`.
+// `ufbx_source_version` contains the version of the corresponding source file.
+// HINT: The version can be compared numerically to the result of `ufbx_pack_version()`,
+// for example `#if UFBX_VERSION >= ufbx_pack_version(0, 12, 0)`.
+#define UFBX_HEADER_VERSION ufbx_pack_version(0, 23, 1)
+#define UFBX_VERSION UFBX_HEADER_VERSION
+
+// -- Basic types
+
+// Main floating point type used everywhere in ufbx, defaults to `double`.
+// If you define `UFBX_REAL_IS_FLOAT` to any value, `ufbx_real` will be defined
+// as `float` instead.
+// You can also manually define `UFBX_REAL_TYPE` to any floating point type.
+typedef UFBX_REAL_TYPE ufbx_real;
+
+// Null-terminated UTF-8 encoded string within an FBX file
+typedef struct ufbx_string {
+ const char *data;
+ size_t length;
+
+ UFBX_CONVERSION_IMPL(ufbx_string)
+} ufbx_string;
+
+// Opaque byte buffer blob
+typedef struct ufbx_blob {
+ const void *data;
+ size_t size;
+
+ UFBX_CONVERSION_IMPL(ufbx_blob)
+} ufbx_blob;
+
+// 2D vector
+typedef struct ufbx_vec2 {
+ union {
+ struct { ufbx_real x, y; };
+ ufbx_real v[2];
+ };
+
+ UFBX_CONVERSION_IMPL(ufbx_vec2)
+} ufbx_vec2;
+
+// 3D vector
+typedef struct ufbx_vec3 {
+ union {
+ struct { ufbx_real x, y, z; };
+ ufbx_real v[3];
+ };
+
+ UFBX_CONVERSION_IMPL(ufbx_vec3)
+} ufbx_vec3;
+
+// 4D vector
+typedef struct ufbx_vec4 {
+ union {
+ struct { ufbx_real x, y, z, w; };
+ ufbx_real v[4];
+ };
+
+ UFBX_CONVERSION_IMPL(ufbx_vec4)
+} ufbx_vec4;
+
+// Quaternion
+typedef struct ufbx_quat {
+ union {
+ struct { ufbx_real x, y, z, w; };
+ ufbx_real v[4];
+ };
+
+ UFBX_CONVERSION_IMPL(ufbx_quat)
+} ufbx_quat;
+
+// Order in which Euler-angle rotation axes are applied for a transform
+// NOTE: The order in the name refers to the order of axes *applied*,
+// not the multiplication order: eg. `UFBX_ROTATION_ORDER_XYZ` is `Z*Y*X`
+// [TODO: Figure out what the spheric rotation order is...]
+typedef enum ufbx_rotation_order UFBX_ENUM_REPR {
+ UFBX_ROTATION_ORDER_XYZ,
+ UFBX_ROTATION_ORDER_XZY,
+ UFBX_ROTATION_ORDER_YZX,
+ UFBX_ROTATION_ORDER_YXZ,
+ UFBX_ROTATION_ORDER_ZXY,
+ UFBX_ROTATION_ORDER_ZYX,
+ UFBX_ROTATION_ORDER_SPHERIC,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_ROTATION_ORDER)
+} ufbx_rotation_order;
+
+UFBX_ENUM_TYPE(ufbx_rotation_order, UFBX_ROTATION_ORDER, UFBX_ROTATION_ORDER_SPHERIC);
+
+// Explicit translation+rotation+scale transformation.
+// NOTE: Rotation is a quaternion, not Euler angles!
+typedef struct ufbx_transform {
+ ufbx_vec3 translation;
+ ufbx_quat rotation;
+ ufbx_vec3 scale;
+
+ UFBX_CONVERSION_IMPL(ufbx_transform)
+} ufbx_transform;
+
+// 4x3 matrix encoding an affine transformation.
+// `cols[0..2]` are the X/Y/Z basis vectors, `cols[3]` is the translation
+typedef struct ufbx_matrix {
+ union {
+ struct {
+ ufbx_real m00, m10, m20;
+ ufbx_real m01, m11, m21;
+ ufbx_real m02, m12, m22;
+ ufbx_real m03, m13, m23;
+ };
+ ufbx_vec3 cols[4];
+ ufbx_real v[12];
+ };
+
+ UFBX_CONVERSION_IMPL(ufbx_matrix)
+} ufbx_matrix;
+
+typedef struct ufbx_void_list {
+ void *data;
+ size_t count;
+} ufbx_void_list;
+
+UFBX_LIST_TYPE(ufbx_bool_list, bool);
+UFBX_LIST_TYPE(ufbx_uint32_list, uint32_t);
+UFBX_LIST_TYPE(ufbx_real_list, ufbx_real);
+UFBX_LIST_TYPE(ufbx_vec2_list, ufbx_vec2);
+UFBX_LIST_TYPE(ufbx_vec3_list, ufbx_vec3);
+UFBX_LIST_TYPE(ufbx_vec4_list, ufbx_vec4);
+UFBX_LIST_TYPE(ufbx_string_list, ufbx_string);
+
+// Sentinel value used to represent a missing index.
+#define UFBX_NO_INDEX ((uint32_t)~0u)
+
+// -- Document object model
+
+typedef enum ufbx_dom_value_type UFBX_ENUM_REPR {
+ UFBX_DOM_VALUE_NUMBER,
+ UFBX_DOM_VALUE_STRING,
+ UFBX_DOM_VALUE_BLOB,
+ UFBX_DOM_VALUE_ARRAY_I32,
+ UFBX_DOM_VALUE_ARRAY_I64,
+ UFBX_DOM_VALUE_ARRAY_F32,
+ UFBX_DOM_VALUE_ARRAY_F64,
+ UFBX_DOM_VALUE_ARRAY_BLOB,
+ UFBX_DOM_VALUE_ARRAY_IGNORED,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_DOM_VALUE_TYPE)
+} ufbx_dom_value_type;
+
+UFBX_ENUM_TYPE(ufbx_dom_value_type, UFBX_DOM_VALUE_TYPE, UFBX_DOM_VALUE_ARRAY_IGNORED);
+
+typedef struct ufbx_dom_node ufbx_dom_node;
+
+UFBX_LIST_TYPE(ufbx_int32_list, int32_t);
+UFBX_LIST_TYPE(ufbx_int64_list, int64_t);
+UFBX_LIST_TYPE(ufbx_float_list, float);
+UFBX_LIST_TYPE(ufbx_double_list, double);
+UFBX_LIST_TYPE(ufbx_blob_list, ufbx_blob);
+
+typedef struct ufbx_dom_value {
+ ufbx_dom_value_type type;
+ ufbx_string value_str;
+ ufbx_blob value_blob;
+ int64_t value_int;
+ double value_float;
+} ufbx_dom_value;
+
+UFBX_LIST_TYPE(ufbx_dom_node_list, ufbx_dom_node*);
+UFBX_LIST_TYPE(ufbx_dom_value_list, ufbx_dom_value);
+
+struct ufbx_dom_node {
+ ufbx_string name;
+ ufbx_dom_node_list children;
+ ufbx_dom_value_list values;
+};
+
+// -- Properties
+
+// FBX elements have properties which are arbitrary key/value pairs that can
+// have inherited default values or be animated. In most cases you don't need
+// to access these unless you need a feature not implemented directly in ufbx.
+// NOTE: Prefer using `ufbx_find_prop[_len](...)` to search for a property by
+// name as it can find it from the defaults if necessary.
+
+typedef struct ufbx_prop ufbx_prop;
+typedef struct ufbx_props ufbx_props;
+
+// Data type contained within the property. All the data fields are always
+// populated regardless of type, so there's no need to switch by type usually
+// eg. `prop->value_real` and `prop->value_int` have the same value (well, close)
+// if `prop->type == UFBX_PROP_INTEGER`. String values are not converted from/to.
+typedef enum ufbx_prop_type UFBX_ENUM_REPR {
+ UFBX_PROP_UNKNOWN,
+ UFBX_PROP_BOOLEAN,
+ UFBX_PROP_INTEGER,
+ UFBX_PROP_NUMBER,
+ UFBX_PROP_VECTOR,
+ UFBX_PROP_COLOR,
+ UFBX_PROP_COLOR_WITH_ALPHA,
+ UFBX_PROP_STRING,
+ UFBX_PROP_DATE_TIME,
+ UFBX_PROP_TRANSLATION,
+ UFBX_PROP_ROTATION,
+ UFBX_PROP_SCALING,
+ UFBX_PROP_DISTANCE,
+ UFBX_PROP_COMPOUND,
+ UFBX_PROP_BLOB,
+ UFBX_PROP_REFERENCE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_PROP_TYPE)
+} ufbx_prop_type;
+
+UFBX_ENUM_TYPE(ufbx_prop_type, UFBX_PROP_TYPE, UFBX_PROP_REFERENCE);
+
+// Property flags: Advanced information about properties, not usually needed.
+typedef enum ufbx_prop_flags UFBX_FLAG_REPR {
+ // Supports animation.
+ // NOTE: ufbx ignores this and allows animations on non-animatable properties.
+ UFBX_PROP_FLAG_ANIMATABLE = 0x1,
+
+ // User defined (custom) property.
+ UFBX_PROP_FLAG_USER_DEFINED = 0x2,
+
+ // Hidden in UI.
+ UFBX_PROP_FLAG_HIDDEN = 0x4,
+
+ // Disallow modification from UI for components.
+ UFBX_PROP_FLAG_LOCK_X = 0x10,
+ UFBX_PROP_FLAG_LOCK_Y = 0x20,
+ UFBX_PROP_FLAG_LOCK_Z = 0x40,
+ UFBX_PROP_FLAG_LOCK_W = 0x80,
+
+ // Disable animation from components.
+ UFBX_PROP_FLAG_MUTE_X = 0x100,
+ UFBX_PROP_FLAG_MUTE_Y = 0x200,
+ UFBX_PROP_FLAG_MUTE_Z = 0x400,
+ UFBX_PROP_FLAG_MUTE_W = 0x800,
+
+ // Property created by ufbx when an element has a connected `ufbx_anim_prop`
+ // but doesn't contain the `ufbx_prop` it's referring to.
+ // NOTE: The property may have been found in the templated defaults.
+ UFBX_PROP_FLAG_SYNTHETIC = 0x1000,
+
+ // The property has at least one `ufbx_anim_prop` in some layer.
+ UFBX_PROP_FLAG_ANIMATED = 0x2000,
+
+ // Used by `ufbx_evaluate_prop()` to indicate the the property was not found.
+ UFBX_PROP_FLAG_NOT_FOUND = 0x4000,
+
+ // The property is connected to another one.
+ // This use case is relatively rare so `ufbx_prop` does not track connections
+ // directly. You can find connections from `ufbx_element.connections_dst` where
+ // `ufbx_connection.dst_prop` is this property and `ufbx_connection.src_prop` is defined.
+ UFBX_PROP_FLAG_CONNECTED = 0x8000,
+
+ // The value of this property is undefined (represented as zero).
+ UFBX_PROP_FLAG_NO_VALUE = 0x10000,
+
+ // This property has been overridden by the user.
+ // See `ufbx_anim.prop_overrides` for more information.
+ UFBX_PROP_FLAG_OVERRIDDEN = 0x20000,
+
+ // Value type.
+ // `REAL/VEC2/VEC3/VEC4` are mutually exclusive but may coexist with eg. `STRING`
+ // in some rare cases where the string defines the unit for the vector.
+ UFBX_PROP_FLAG_VALUE_REAL = 0x100000,
+ UFBX_PROP_FLAG_VALUE_VEC2 = 0x200000,
+ UFBX_PROP_FLAG_VALUE_VEC3 = 0x400000,
+ UFBX_PROP_FLAG_VALUE_VEC4 = 0x800000,
+ UFBX_PROP_FLAG_VALUE_INT = 0x1000000,
+ UFBX_PROP_FLAG_VALUE_STR = 0x2000000,
+ UFBX_PROP_FLAG_VALUE_BLOB = 0x4000000,
+
+ UFBX_FLAG_FORCE_WIDTH(UFBX_PROP_FLAGS)
+} ufbx_prop_flags;
+
+// Single property with name/type/value.
+struct ufbx_prop {
+ ufbx_string name;
+
+ uint32_t _internal_key;
+
+ ufbx_prop_type type;
+ ufbx_prop_flags flags;
+
+ ufbx_string value_str;
+ ufbx_blob value_blob;
+ int64_t value_int;
+ union {
+ ufbx_real value_real_arr[4];
+ ufbx_real value_real;
+ ufbx_vec2 value_vec2;
+ ufbx_vec3 value_vec3;
+ ufbx_vec4 value_vec4;
+ };
+};
+
+UFBX_LIST_TYPE(ufbx_prop_list, ufbx_prop);
+
+// List of alphabetically sorted properties with potential defaults.
+// For animated objects in as scene from `ufbx_evaluate_scene()` this list
+// only has the animated properties, the originals are stored under `defaults`.
+struct ufbx_props {
+ ufbx_prop_list props;
+ size_t num_animated;
+
+ ufbx_nullable ufbx_props *defaults;
+};
+
+typedef struct ufbx_scene ufbx_scene;
+
+// -- Elements
+
+// Element is the lowest level representation of the FBX file in ufbx.
+// An element contains type, id, name, and properties (see `ufbx_props` above)
+// Elements may be connected to each other arbitrarily via `ufbx_connection`
+
+typedef struct ufbx_element ufbx_element;
+
+// Unknown
+typedef struct ufbx_unknown ufbx_unknown;
+
+// Nodes
+typedef struct ufbx_node ufbx_node;
+
+// Node attributes (common)
+typedef struct ufbx_mesh ufbx_mesh;
+typedef struct ufbx_light ufbx_light;
+typedef struct ufbx_camera ufbx_camera;
+typedef struct ufbx_bone ufbx_bone;
+typedef struct ufbx_empty ufbx_empty;
+
+// Node attributes (curves/surfaces)
+typedef struct ufbx_line_curve ufbx_line_curve;
+typedef struct ufbx_nurbs_curve ufbx_nurbs_curve;
+typedef struct ufbx_nurbs_surface ufbx_nurbs_surface;
+typedef struct ufbx_nurbs_trim_surface ufbx_nurbs_trim_surface;
+typedef struct ufbx_nurbs_trim_boundary ufbx_nurbs_trim_boundary;
+
+// Node attributes (advanced)
+typedef struct ufbx_procedural_geometry ufbx_procedural_geometry;
+typedef struct ufbx_stereo_camera ufbx_stereo_camera;
+typedef struct ufbx_camera_switcher ufbx_camera_switcher;
+typedef struct ufbx_marker ufbx_marker;
+typedef struct ufbx_lod_group ufbx_lod_group;
+
+// Deformers
+typedef struct ufbx_skin_deformer ufbx_skin_deformer;
+typedef struct ufbx_skin_cluster ufbx_skin_cluster;
+typedef struct ufbx_blend_deformer ufbx_blend_deformer;
+typedef struct ufbx_blend_channel ufbx_blend_channel;
+typedef struct ufbx_blend_shape ufbx_blend_shape;
+typedef struct ufbx_cache_deformer ufbx_cache_deformer;
+typedef struct ufbx_cache_file ufbx_cache_file;
+
+// Materials
+typedef struct ufbx_material ufbx_material;
+typedef struct ufbx_texture ufbx_texture;
+typedef struct ufbx_video ufbx_video;
+typedef struct ufbx_shader ufbx_shader;
+typedef struct ufbx_shader_binding ufbx_shader_binding;
+
+// Animation
+typedef struct ufbx_anim_stack ufbx_anim_stack;
+typedef struct ufbx_anim_layer ufbx_anim_layer;
+typedef struct ufbx_anim_value ufbx_anim_value;
+typedef struct ufbx_anim_curve ufbx_anim_curve;
+
+// Collections
+typedef struct ufbx_display_layer ufbx_display_layer;
+typedef struct ufbx_selection_set ufbx_selection_set;
+typedef struct ufbx_selection_node ufbx_selection_node;
+
+// Constraints
+typedef struct ufbx_character ufbx_character;
+typedef struct ufbx_constraint ufbx_constraint;
+
+// Audio
+typedef struct ufbx_audio_layer ufbx_audio_layer;
+typedef struct ufbx_audio_clip ufbx_audio_clip;
+
+// Miscellaneous
+typedef struct ufbx_pose ufbx_pose;
+typedef struct ufbx_metadata_object ufbx_metadata_object;
+
+UFBX_LIST_TYPE(ufbx_element_list, ufbx_element*);
+UFBX_LIST_TYPE(ufbx_unknown_list, ufbx_unknown*);
+UFBX_LIST_TYPE(ufbx_node_list, ufbx_node*);
+UFBX_LIST_TYPE(ufbx_mesh_list, ufbx_mesh*);
+UFBX_LIST_TYPE(ufbx_light_list, ufbx_light*);
+UFBX_LIST_TYPE(ufbx_camera_list, ufbx_camera*);
+UFBX_LIST_TYPE(ufbx_bone_list, ufbx_bone*);
+UFBX_LIST_TYPE(ufbx_empty_list, ufbx_empty*);
+UFBX_LIST_TYPE(ufbx_line_curve_list, ufbx_line_curve*);
+UFBX_LIST_TYPE(ufbx_nurbs_curve_list, ufbx_nurbs_curve*);
+UFBX_LIST_TYPE(ufbx_nurbs_surface_list, ufbx_nurbs_surface*);
+UFBX_LIST_TYPE(ufbx_nurbs_trim_surface_list, ufbx_nurbs_trim_surface*);
+UFBX_LIST_TYPE(ufbx_nurbs_trim_boundary_list, ufbx_nurbs_trim_boundary*);
+UFBX_LIST_TYPE(ufbx_procedural_geometry_list, ufbx_procedural_geometry*);
+UFBX_LIST_TYPE(ufbx_stereo_camera_list, ufbx_stereo_camera*);
+UFBX_LIST_TYPE(ufbx_camera_switcher_list, ufbx_camera_switcher*);
+UFBX_LIST_TYPE(ufbx_marker_list, ufbx_marker*);
+UFBX_LIST_TYPE(ufbx_lod_group_list, ufbx_lod_group*);
+UFBX_LIST_TYPE(ufbx_skin_deformer_list, ufbx_skin_deformer*);
+UFBX_LIST_TYPE(ufbx_skin_cluster_list, ufbx_skin_cluster*);
+UFBX_LIST_TYPE(ufbx_blend_deformer_list, ufbx_blend_deformer*);
+UFBX_LIST_TYPE(ufbx_blend_channel_list, ufbx_blend_channel*);
+UFBX_LIST_TYPE(ufbx_blend_shape_list, ufbx_blend_shape*);
+UFBX_LIST_TYPE(ufbx_cache_deformer_list, ufbx_cache_deformer*);
+UFBX_LIST_TYPE(ufbx_cache_file_list, ufbx_cache_file*);
+UFBX_LIST_TYPE(ufbx_material_list, ufbx_material*);
+UFBX_LIST_TYPE(ufbx_texture_list, ufbx_texture*);
+UFBX_LIST_TYPE(ufbx_video_list, ufbx_video*);
+UFBX_LIST_TYPE(ufbx_shader_list, ufbx_shader*);
+UFBX_LIST_TYPE(ufbx_shader_binding_list, ufbx_shader_binding*);
+UFBX_LIST_TYPE(ufbx_anim_stack_list, ufbx_anim_stack*);
+UFBX_LIST_TYPE(ufbx_anim_layer_list, ufbx_anim_layer*);
+UFBX_LIST_TYPE(ufbx_anim_value_list, ufbx_anim_value*);
+UFBX_LIST_TYPE(ufbx_anim_curve_list, ufbx_anim_curve*);
+UFBX_LIST_TYPE(ufbx_display_layer_list, ufbx_display_layer*);
+UFBX_LIST_TYPE(ufbx_selection_set_list, ufbx_selection_set*);
+UFBX_LIST_TYPE(ufbx_selection_node_list, ufbx_selection_node*);
+UFBX_LIST_TYPE(ufbx_character_list, ufbx_character*);
+UFBX_LIST_TYPE(ufbx_constraint_list, ufbx_constraint*);
+UFBX_LIST_TYPE(ufbx_audio_layer_list, ufbx_audio_layer*);
+UFBX_LIST_TYPE(ufbx_audio_clip_list, ufbx_audio_clip*);
+UFBX_LIST_TYPE(ufbx_pose_list, ufbx_pose*);
+UFBX_LIST_TYPE(ufbx_metadata_object_list, ufbx_metadata_object*);
+
+typedef enum ufbx_element_type UFBX_ENUM_REPR {
+ UFBX_ELEMENT_UNKNOWN, // < `ufbx_unknown`
+ UFBX_ELEMENT_NODE, // < `ufbx_node`
+ UFBX_ELEMENT_MESH, // < `ufbx_mesh`
+ UFBX_ELEMENT_LIGHT, // < `ufbx_light`
+ UFBX_ELEMENT_CAMERA, // < `ufbx_camera`
+ UFBX_ELEMENT_BONE, // < `ufbx_bone`
+ UFBX_ELEMENT_EMPTY, // < `ufbx_empty`
+ UFBX_ELEMENT_LINE_CURVE, // < `ufbx_line_curve`
+ UFBX_ELEMENT_NURBS_CURVE, // < `ufbx_nurbs_curve`
+ UFBX_ELEMENT_NURBS_SURFACE, // < `ufbx_nurbs_surface`
+ UFBX_ELEMENT_NURBS_TRIM_SURFACE, // < `ufbx_nurbs_trim_surface`
+ UFBX_ELEMENT_NURBS_TRIM_BOUNDARY, // < `ufbx_nurbs_trim_boundary`
+ UFBX_ELEMENT_PROCEDURAL_GEOMETRY, // < `ufbx_procedural_geometry`
+ UFBX_ELEMENT_STEREO_CAMERA, // < `ufbx_stereo_camera`
+ UFBX_ELEMENT_CAMERA_SWITCHER, // < `ufbx_camera_switcher`
+ UFBX_ELEMENT_MARKER, // < `ufbx_marker`
+ UFBX_ELEMENT_LOD_GROUP, // < `ufbx_lod_group`
+ UFBX_ELEMENT_SKIN_DEFORMER, // < `ufbx_skin_deformer`
+ UFBX_ELEMENT_SKIN_CLUSTER, // < `ufbx_skin_cluster`
+ UFBX_ELEMENT_BLEND_DEFORMER, // < `ufbx_blend_deformer`
+ UFBX_ELEMENT_BLEND_CHANNEL, // < `ufbx_blend_channel`
+ UFBX_ELEMENT_BLEND_SHAPE, // < `ufbx_blend_shape`
+ UFBX_ELEMENT_CACHE_DEFORMER, // < `ufbx_cache_deformer`
+ UFBX_ELEMENT_CACHE_FILE, // < `ufbx_cache_file`
+ UFBX_ELEMENT_MATERIAL, // < `ufbx_material`
+ UFBX_ELEMENT_TEXTURE, // < `ufbx_texture`
+ UFBX_ELEMENT_VIDEO, // < `ufbx_video`
+ UFBX_ELEMENT_SHADER, // < `ufbx_shader`
+ UFBX_ELEMENT_SHADER_BINDING, // < `ufbx_shader_binding`
+ UFBX_ELEMENT_ANIM_STACK, // < `ufbx_anim_stack`
+ UFBX_ELEMENT_ANIM_LAYER, // < `ufbx_anim_layer`
+ UFBX_ELEMENT_ANIM_VALUE, // < `ufbx_anim_value`
+ UFBX_ELEMENT_ANIM_CURVE, // < `ufbx_anim_curve`
+ UFBX_ELEMENT_DISPLAY_LAYER, // < `ufbx_display_layer`
+ UFBX_ELEMENT_SELECTION_SET, // < `ufbx_selection_set`
+ UFBX_ELEMENT_SELECTION_NODE, // < `ufbx_selection_node`
+ UFBX_ELEMENT_CHARACTER, // < `ufbx_character`
+ UFBX_ELEMENT_CONSTRAINT, // < `ufbx_constraint`
+ UFBX_ELEMENT_AUDIO_LAYER, // < `ufbx_audio_layer`
+ UFBX_ELEMENT_AUDIO_CLIP, // < `ufbx_audio_clip`
+ UFBX_ELEMENT_POSE, // < `ufbx_pose`
+ UFBX_ELEMENT_METADATA_OBJECT, // < `ufbx_metadata_object`
+
+ UFBX_ELEMENT_TYPE_FIRST_ATTRIB = UFBX_ELEMENT_MESH,
+ UFBX_ELEMENT_TYPE_LAST_ATTRIB = UFBX_ELEMENT_LOD_GROUP,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_ELEMENT_TYPE)
+} ufbx_element_type;
+
+UFBX_ENUM_TYPE(ufbx_element_type, UFBX_ELEMENT_TYPE, UFBX_ELEMENT_METADATA_OBJECT);
+
+// Connection between two elements.
+// Source and destination are somewhat arbitrary but the destination is
+// often the "container" like a parent node or mesh containing a deformer.
+typedef struct ufbx_connection {
+ ufbx_element *src;
+ ufbx_element *dst;
+ ufbx_string src_prop;
+ ufbx_string dst_prop;
+} ufbx_connection;
+
+UFBX_LIST_TYPE(ufbx_connection_list, ufbx_connection);
+
+// Element "base-class" common to each element.
+// Some fields (like `connections_src`) are advanced and not visible
+// in the specialized element structs.
+// NOTE: The `element_id` value is consistent when loading the
+// _same_ file, but re-exporting the file will invalidate them.
+struct ufbx_element {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ ufbx_element_type type;
+ ufbx_connection_list connections_src;
+ ufbx_connection_list connections_dst;
+ ufbx_nullable ufbx_dom_node *dom_node;
+ ufbx_scene *scene;
+};
+
+// -- Unknown
+
+struct ufbx_unknown {
+ // Shared "base-class" header, see `ufbx_element`.
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // FBX format specific type information.
+ // In ASCII FBX format:
+ // super_type: ID, "type::name", "sub_type" { ... }
+ ufbx_string type;
+ ufbx_string super_type;
+ ufbx_string sub_type;
+};
+
+// -- Nodes
+
+// Inherit type specifies how hierarchial node transforms are combined.
+// This only affects the final scaling, as rotation and translation are always
+// inherited correctly.
+// NOTE: These don't map to `"InheritType"` property as there may be new ones for
+// compatibility with various exporters.
+typedef enum ufbx_inherit_mode UFBX_ENUM_REPR {
+
+ // Normal matrix composition of hierarchy: `R*S*r*s`.
+ // child.node_to_world = parent.node_to_world * child.node_to_parent;
+ UFBX_INHERIT_MODE_NORMAL,
+
+ // Ignore parent scale when computing the transform: `R*r*s`.
+ // ufbx_transform t = node.local_transform;
+ // t.translation *= parent.inherit_scale;
+ // t.scale *= node.inherit_scale_node.inherit_scale;
+ // child.node_to_world = parent.unscaled_node_to_world * t;
+ // Also known as "Segment scale compensate" in some software.
+ UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE,
+
+ // Apply parent scale component-wise: `R*r*S*s`.
+ // ufbx_transform t = node.local_transform;
+ // t.translation *= parent.inherit_scale;
+ // t.scale *= node.inherit_scale_node.inherit_scale;
+ // child.node_to_world = parent.unscaled_node_to_world * t;
+ UFBX_INHERIT_MODE_COMPONENTWISE_SCALE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_INHERIT_MODE)
+} ufbx_inherit_mode;
+
+UFBX_ENUM_TYPE(ufbx_inherit_mode, UFBX_INHERIT_MODE, UFBX_INHERIT_MODE_COMPONENTWISE_SCALE);
+
+// Axis used to mirror transformations for handedness conversion.
+typedef enum ufbx_mirror_axis UFBX_ENUM_REPR {
+
+ UFBX_MIRROR_AXIS_NONE,
+ UFBX_MIRROR_AXIS_X,
+ UFBX_MIRROR_AXIS_Y,
+ UFBX_MIRROR_AXIS_Z,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_MIRROR_AXIS)
+} ufbx_mirror_axis;
+
+UFBX_ENUM_TYPE(ufbx_mirror_axis, UFBX_MIRROR_AXIS, UFBX_MIRROR_AXIS_Z);
+
+// Nodes form the scene transformation hierarchy and can contain attached
+// elements such as meshes or lights. In normal cases a single `ufbx_node`
+// contains only a single attached element, so using `type/mesh/...` is safe.
+struct ufbx_node {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Node hierarchy
+
+ // Parent node containing this one if not root.
+ //
+ // Always non-`NULL` for non-root nodes unless
+ // `ufbx_load_opts.allow_nodes_out_of_root` is enabled.
+ ufbx_nullable ufbx_node *parent;
+
+ // List of child nodes parented to this node.
+ ufbx_node_list children;
+
+ // Common attached element type and typed pointers. Set to `NULL` if not in
+ // use, so checking `attrib_type` is not required.
+ //
+ // HINT: If you need less common attributes access `ufbx_node.attrib`, you
+ // can use utility functions like `ufbx_as_nurbs_curve(attrib)` to convert
+ // and check the attribute in one step.
+ ufbx_nullable ufbx_mesh *mesh;
+ ufbx_nullable ufbx_light *light;
+ ufbx_nullable ufbx_camera *camera;
+ ufbx_nullable ufbx_bone *bone;
+
+ // Less common attributes use these fields.
+ //
+ // Defined even if it is one of the above, eg. `ufbx_mesh`. In case there
+ // is multiple attributes this will be the first one.
+ ufbx_nullable ufbx_element *attrib;
+
+ // Geometry transform helper if one exists.
+ // See `UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES`.
+ ufbx_nullable ufbx_node *geometry_transform_helper;
+
+ // Scale helper if one exists.
+ // See `UFBX_INHERIT_MODE_HANDLING_HELPER_NODES`.
+ ufbx_nullable ufbx_node *scale_helper;
+
+ // `attrib->type` if `attrib` is defined, otherwise `UFBX_ELEMENT_UNKNOWN`.
+ ufbx_element_type attrib_type;
+
+ // List of _all_ attached attribute elements.
+ //
+ // In most cases there is only zero or one attributes per node, but if you
+ // have a very exotic FBX file nodes may have multiple attributes.
+ ufbx_element_list all_attribs;
+
+ // Local transform in parent, geometry transform is a non-inherited
+ // transform applied only to attachments like meshes
+ ufbx_inherit_mode inherit_mode;
+ ufbx_inherit_mode original_inherit_mode;
+ ufbx_transform local_transform;
+ ufbx_transform geometry_transform;
+
+ // Combined scale when using `UFBX_INHERIT_MODE_COMPONENTWISE_SCALE`.
+ // Contains `local_transform.scale` otherwise.
+ ufbx_vec3 inherit_scale;
+
+ // Node where scale is inherited from for `UFBX_INHERIT_MODE_COMPONENTWISE_SCALE`
+ // and even for `UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE`.
+ // For componentwise-scale nodes, this will point to `parent`, for scale ignoring
+ // nodes this will point to the parent of the nearest componentwise-scaled node
+ // in the parent chain.
+ ufbx_nullable ufbx_node *inherit_scale_node;
+
+ // Raw Euler angles in degrees for those who want them
+
+ // Specifies the axis order `euler_rotation` is applied in.
+ ufbx_rotation_order rotation_order;
+ // Rotation around the local X/Y/Z axes in `rotation_order`.
+ // The angles are specified in degrees.
+ ufbx_vec3 euler_rotation;
+
+ // Matrices derived from the transformations, for transforming geometry
+ // prefer using `geometry_to_world` as that supports geometric transforms.
+
+ // Transform from this node to `parent` space.
+ // Equivalent to `ufbx_transform_to_matrix(&local_transform)`.
+ ufbx_matrix node_to_parent;
+ // Transform from this node to the world space, ie. multiplying all the
+ // `node_to_parent` matrices of the parent chain together.
+ ufbx_matrix node_to_world;
+ // Transform from the attribute to this node. Does not affect the transforms
+ // of `children`!
+ // Equivalent to `ufbx_transform_to_matrix(&geometry_transform)`.
+ ufbx_matrix geometry_to_node;
+ // Transform from attribute space to world space.
+ // Equivalent to `ufbx_matrix_mul(&node_to_world, &geometry_to_node)`.
+ ufbx_matrix geometry_to_world;
+ // Transform from this node to world space, ignoring self scaling.
+ ufbx_matrix unscaled_node_to_world;
+
+ // ufbx-specific adjustment for switching between coodrinate/unit systems.
+ // HINT: In most cases you don't need to deal with these as these are baked
+ // into all the transforms above and into `ufbx_evaluate_transform()`.
+ ufbx_vec3 adjust_pre_translation; // < Translation applied between parent and self
+ ufbx_quat adjust_pre_rotation; // < Rotation applied between parent and self
+ ufbx_real adjust_pre_scale; // < Scaling applied between parent and self
+ ufbx_quat adjust_post_rotation; // < Rotation applied in local space at the end
+ ufbx_real adjust_post_scale; // < Scaling applied in local space at the end
+ ufbx_real adjust_translation_scale; // < Scaling applied to translation only
+ ufbx_mirror_axis adjust_mirror_axis; // < Mirror translation and rotation on this axis
+
+ // Materials used by `mesh` or other `attrib`.
+ // There may be multiple copies of a single `ufbx_mesh` with different materials
+ // in the `ufbx_node` instances.
+ ufbx_material_list materials;
+
+ // Bind pose
+ ufbx_nullable ufbx_pose *bind_pose;
+
+ // Visibility state.
+ bool visible;
+
+ // True if this node is the implicit root node of the scene.
+ bool is_root;
+
+ // True if the node has a non-identity `geometry_transform`.
+ bool has_geometry_transform;
+
+ // If `true`, you should apply `RotationOrder`, `PreRotation` and `PostRotation` properties.
+ // See `UFBX_RotationOrder`, `UFBX_PreRotation`, `UFBX_PostRotation`.
+ bool use_rotation_space;
+
+ // If `true`, the transform is adjusted by ufbx, not enabled by default.
+ // See `adjust_pre_rotation`, `adjust_pre_scale`, `adjust_post_rotation`,
+ // and `adjust_post_scale`.
+ bool has_adjust_transform;
+
+ // Scale is adjusted by root scale.
+ bool has_root_adjust_transform;
+
+ // True if this node is a synthetic geometry transform helper.
+ // See `UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES`.
+ bool is_geometry_transform_helper;
+
+ // True if the node is a synthetic scale compensation helper.
+ // See `UFBX_INHERIT_MODE_HANDLING_HELPER_NODES`.
+ bool is_scale_helper;
+
+ // Parent node to children that can compensate for parent scale.
+ bool is_scale_compensate_parent;
+
+ // How deep is this node in the parent hierarchy. Root node is at depth `0`
+ // and the immediate children of root at `1`.
+ uint32_t node_depth;
+};
+
+// Vertex attribute: All attributes are stored in a consistent indexed format
+// regardless of how it's actually stored in the file.
+//
+// `values` is a contiguous array of attribute values.
+// `indices` maps each mesh index into a value in the `values` array.
+//
+// If `unique_per_vertex` is set then the attribute is guaranteed to have a
+// single defined value per vertex accessible via:
+// attrib.values.data[attrib.indices.data[mesh->vertex_first_index[vertex_ix]]
+typedef struct ufbx_vertex_attrib {
+ // Is this attribute defined by the mesh.
+ bool exists;
+ // List of values the attribute uses.
+ ufbx_void_list values;
+ // Indices into `values[]`, indexed up to `ufbx_mesh.num_indices`.
+ ufbx_uint32_list indices;
+ // Number of `ufbx_real` entries per value.
+ size_t value_reals;
+ // `true` if this attribute is defined per vertex, instead of per index.
+ bool unique_per_vertex;
+ // Optional 4th 'W' component for the attribute.
+ // May be defined for the following:
+ // ufbx_mesh.vertex_normal
+ // ufbx_mesh.vertex_tangent / ufbx_uv_set.vertex_tangent
+ // ufbx_mesh.vertex_bitangent / ufbx_uv_set.vertex_bitangent
+ // NOTE: This is not loaded by default, set `ufbx_load_opts.retain_vertex_attrib_w`.
+ ufbx_real_list values_w;
+} ufbx_vertex_attrib;
+
+// 1D vertex attribute, see `ufbx_vertex_attrib` for information
+typedef struct ufbx_vertex_real {
+ bool exists;
+ ufbx_real_list values;
+ ufbx_uint32_list indices;
+ size_t value_reals;
+ bool unique_per_vertex;
+ ufbx_real_list values_w;
+
+ UFBX_VERTEX_ATTRIB_IMPL(ufbx_real)
+} ufbx_vertex_real;
+
+// 2D vertex attribute, see `ufbx_vertex_attrib` for information
+typedef struct ufbx_vertex_vec2 {
+ bool exists;
+ ufbx_vec2_list values;
+ ufbx_uint32_list indices;
+ size_t value_reals;
+ bool unique_per_vertex;
+ ufbx_real_list values_w;
+
+ UFBX_VERTEX_ATTRIB_IMPL(ufbx_vec2)
+} ufbx_vertex_vec2;
+
+// 3D vertex attribute, see `ufbx_vertex_attrib` for information
+typedef struct ufbx_vertex_vec3 {
+ bool exists;
+ ufbx_vec3_list values;
+ ufbx_uint32_list indices;
+ size_t value_reals;
+ bool unique_per_vertex;
+ ufbx_real_list values_w;
+
+ UFBX_VERTEX_ATTRIB_IMPL(ufbx_vec3)
+} ufbx_vertex_vec3;
+
+// 4D vertex attribute, see `ufbx_vertex_attrib` for information
+typedef struct ufbx_vertex_vec4 {
+ bool exists;
+ ufbx_vec4_list values;
+ ufbx_uint32_list indices;
+ size_t value_reals;
+ bool unique_per_vertex;
+ ufbx_real_list values_w;
+
+ UFBX_VERTEX_ATTRIB_IMPL(ufbx_vec4)
+} ufbx_vertex_vec4;
+
+// Vertex UV set/layer
+typedef struct ufbx_uv_set {
+ ufbx_string name;
+ uint32_t index;
+
+ // Vertex attributes, see `ufbx_mesh` attributes for more information
+ ufbx_vertex_vec2 vertex_uv; // < UV / texture coordinates
+ ufbx_vertex_vec3 vertex_tangent; // < (optional) Tangent vector in UV.x direction
+ ufbx_vertex_vec3 vertex_bitangent; // < (optional) Tangent vector in UV.y direction
+} ufbx_uv_set;
+
+// Vertex color set/layer
+typedef struct ufbx_color_set {
+ ufbx_string name;
+ uint32_t index;
+
+ // Vertex attributes, see `ufbx_mesh` attributes for more information
+ ufbx_vertex_vec4 vertex_color; // < Per-vertex RGBA color
+} ufbx_color_set;
+
+UFBX_LIST_TYPE(ufbx_uv_set_list, ufbx_uv_set);
+UFBX_LIST_TYPE(ufbx_color_set_list, ufbx_color_set);
+
+// Edge between two _indices_ in a mesh
+typedef struct ufbx_edge {
+ union {
+ struct { uint32_t a, b; };
+ uint32_t indices[2];
+ };
+} ufbx_edge;
+
+UFBX_LIST_TYPE(ufbx_edge_list, ufbx_edge);
+
+// Polygonal face with arbitrary number vertices, a single face contains a
+// contiguous range of mesh indices, eg. `{5,3}` would have indices 5, 6, 7
+//
+// NOTE: `num_indices` maybe less than 3 in which case the face is invalid!
+// [TODO #23: should probably remove the bad faces at load time]
+typedef struct ufbx_face {
+ uint32_t index_begin;
+ uint32_t num_indices;
+} ufbx_face;
+
+UFBX_LIST_TYPE(ufbx_face_list, ufbx_face);
+
+// Subset of mesh faces used by a single material or group.
+typedef struct ufbx_mesh_part {
+
+ // Index of the mesh part.
+ uint32_t index;
+
+ // Sub-set of the geometry
+ size_t num_faces; // < Number of faces (polygons)
+ size_t num_triangles; // < Number of triangles if triangulated
+
+ size_t num_empty_faces; // < Number of faces with zero vertices
+ size_t num_point_faces; // < Number of faces with a single vertex
+ size_t num_line_faces; // < Number of faces with two vertices
+
+ // Indices to `ufbx_mesh.faces[]`.
+ // Always contains `num_faces` elements.
+ ufbx_uint32_list face_indices;
+
+} ufbx_mesh_part;
+
+UFBX_LIST_TYPE(ufbx_mesh_part_list, ufbx_mesh_part);
+
+typedef struct ufbx_face_group {
+ int32_t id; // < Numerical ID for this group.
+ ufbx_string name; // < Name for the face group.
+} ufbx_face_group;
+
+UFBX_LIST_TYPE(ufbx_face_group_list, ufbx_face_group);
+
+typedef struct ufbx_subdivision_weight_range {
+ uint32_t weight_begin;
+ uint32_t num_weights;
+} ufbx_subdivision_weight_range;
+
+UFBX_LIST_TYPE(ufbx_subdivision_weight_range_list, ufbx_subdivision_weight_range);
+
+typedef struct ufbx_subdivision_weight {
+ ufbx_real weight;
+ uint32_t index;
+} ufbx_subdivision_weight;
+
+UFBX_LIST_TYPE(ufbx_subdivision_weight_list, ufbx_subdivision_weight);
+
+typedef struct ufbx_subdivision_result {
+ size_t result_memory_used;
+ size_t temp_memory_used;
+ size_t result_allocs;
+ size_t temp_allocs;
+
+ // Weights of vertices in the source model.
+ // Defined if `ufbx_subdivide_opts.evaluate_source_vertices` is set.
+ ufbx_subdivision_weight_range_list source_vertex_ranges;
+ ufbx_subdivision_weight_list source_vertex_weights;
+
+ // Weights of skin clusters in the source model.
+ // Defined if `ufbx_subdivide_opts.evaluate_skin_weights` is set.
+ ufbx_subdivision_weight_range_list skin_cluster_ranges;
+ ufbx_subdivision_weight_list skin_cluster_weights;
+
+} ufbx_subdivision_result;
+
+typedef enum ufbx_subdivision_display_mode UFBX_ENUM_REPR {
+ UFBX_SUBDIVISION_DISPLAY_DISABLED,
+ UFBX_SUBDIVISION_DISPLAY_HULL,
+ UFBX_SUBDIVISION_DISPLAY_HULL_AND_SMOOTH,
+ UFBX_SUBDIVISION_DISPLAY_SMOOTH,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SUBDIVISION_DISPLAY_MODE)
+} ufbx_subdivision_display_mode;
+
+UFBX_ENUM_TYPE(ufbx_subdivision_display_mode, UFBX_SUBDIVISION_DISPLAY_MODE, UFBX_SUBDIVISION_DISPLAY_SMOOTH);
+
+typedef enum ufbx_subdivision_boundary UFBX_ENUM_REPR {
+ UFBX_SUBDIVISION_BOUNDARY_DEFAULT,
+ UFBX_SUBDIVISION_BOUNDARY_LEGACY,
+ // OpenSubdiv: `VTX_BOUNDARY_EDGE_AND_CORNER` / `FVAR_LINEAR_CORNERS_ONLY`
+ UFBX_SUBDIVISION_BOUNDARY_SHARP_CORNERS,
+ // OpenSubdiv: `VTX_BOUNDARY_EDGE_ONLY` / `FVAR_LINEAR_NONE`
+ UFBX_SUBDIVISION_BOUNDARY_SHARP_NONE,
+ // OpenSubdiv: `FVAR_LINEAR_BOUNDARIES`
+ UFBX_SUBDIVISION_BOUNDARY_SHARP_BOUNDARY,
+ // OpenSubdiv: `FVAR_LINEAR_ALL`
+ UFBX_SUBDIVISION_BOUNDARY_SHARP_INTERIOR,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SUBDIVISION_BOUNDARY)
+} ufbx_subdivision_boundary;
+
+UFBX_ENUM_TYPE(ufbx_subdivision_boundary, UFBX_SUBDIVISION_BOUNDARY, UFBX_SUBDIVISION_BOUNDARY_SHARP_INTERIOR);
+
+// Polygonal mesh geometry.
+//
+// Example mesh with two triangles (x, z) and a quad (y).
+// The faces have a constant UV coordinate x/y/z.
+// The vertices have _per vertex_ normals that point up/down.
+//
+// ^ ^ ^
+// A---B-----C
+// |x / /|
+// | / y / |
+// |/ / z|
+// D-----E---F
+// v v v
+//
+// Attributes may have multiple values within a single vertex, for example a
+// UV seam vertex has two UV coordinates. Thus polygons are defined using
+// an index that counts each corner of each face polygon. If an attribute is
+// defined (even per-vertex) it will always have a valid `indices` array.
+//
+// {0,3} {3,4} {7,3} faces ({ index_begin, num_indices })
+// 0 1 2 3 4 5 6 7 8 9 index
+//
+// 0 1 3 1 2 4 3 2 4 5 vertex_indices[index]
+// A B D B C E D C E F vertices[vertex_indices[index]]
+//
+// 0 0 1 0 0 1 1 0 1 1 vertex_normal.indices[index]
+// ^ ^ v ^ ^ v v ^ v v vertex_normal.data[vertex_normal.indices[index]]
+//
+// 0 0 0 1 1 1 1 2 2 2 vertex_uv.indices[index]
+// x x x y y y y z z z vertex_uv.data[vertex_uv.indices[index]]
+//
+// Vertex position can also be accessed uniformly through an accessor:
+// 0 1 3 1 2 4 3 2 4 5 vertex_position.indices[index]
+// A B D B C E D C E F vertex_position.data[vertex_position.indices[index]]
+//
+// Some geometry data is specified per logical vertex. Vertex positions are
+// the only attribute that is guaranteed to be defined _uniquely_ per vertex.
+// Vertex attributes _may_ be defined per vertex if `unique_per_vertex == true`.
+// You can access the per-vertex values by first finding the first index that
+// refers to the given vertex.
+//
+// 0 1 2 3 4 5 vertex
+// A B C D E F vertices[vertex]
+//
+// 0 1 4 2 5 9 vertex_first_index[vertex]
+// 0 0 0 1 1 1 vertex_normal.indices[vertex_first_index[vertex]]
+// ^ ^ ^ v v v vertex_normal.data[vertex_normal.indices[vertex_first_index[vertex]]]
+//
+struct ufbx_mesh {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Number of "logical" vertices that would be treated as a single point,
+ // one vertex may be split to multiple indices for split attributes, eg. UVs
+ size_t num_vertices; // < Number of logical "vertex" points
+ size_t num_indices; // < Number of combiend vertex/attribute tuples
+ size_t num_faces; // < Number of faces (polygons) in the mesh
+ size_t num_triangles; // < Number of triangles if triangulated
+
+ // Number of edges in the mesh.
+ // NOTE: May be zero in valid meshes if the file doesn't contain edge adjacency data!
+ size_t num_edges;
+
+ size_t max_face_triangles; // < Maximum number of triangles in a face in this mesh
+
+ size_t num_empty_faces; // < Number of faces with zero vertices
+ size_t num_point_faces; // < Number of faces with a single vertex
+ size_t num_line_faces; // < Number of faces with two vertices
+
+ // Faces and optional per-face extra data
+ ufbx_face_list faces; // < Face index range
+ ufbx_bool_list face_smoothing; // < Should the face have soft normals
+ ufbx_uint32_list face_material; // < Indices to `ufbx_mesh.materials[]` and `ufbx_node.materials[]`
+ ufbx_uint32_list face_group; // < Face polygon group index, indices to `ufbx_mesh.face_groups[]`
+ ufbx_bool_list face_hole; // < Should the face be hidden as a "hole"
+
+ // Edges and optional per-edge extra data
+ ufbx_edge_list edges; // < Edge index range
+ ufbx_bool_list edge_smoothing; // < Should the edge have soft normals
+ ufbx_real_list edge_crease; // < Crease value for subdivision surfaces
+ ufbx_bool_list edge_visibility; // < Should the edge be visible
+
+ // Logical vertices and positions, alternatively you can use
+ // `vertex_position` for consistent interface with other attributes.
+ ufbx_uint32_list vertex_indices;
+ ufbx_vec3_list vertices;
+
+ // First index referring to a given vertex, `UFBX_NO_INDEX` if the vertex is unused.
+ ufbx_uint32_list vertex_first_index;
+
+ // Vertex attributes, see the comment over the struct.
+ //
+ // NOTE: Not all meshes have all attributes, in that case `indices/data == NULL`!
+ //
+ // NOTE: UV/tangent/bitangent and color are the from first sets,
+ // use `uv_sets/color_sets` to access the other layers.
+ ufbx_vertex_vec3 vertex_position; // < Vertex positions
+ ufbx_vertex_vec3 vertex_normal; // < (optional) Normal vectors, always defined if `ufbx_load_opts.generate_missing_normals`
+ ufbx_vertex_vec2 vertex_uv; // < (optional) UV / texture coordinates
+ ufbx_vertex_vec3 vertex_tangent; // < (optional) Tangent vector in UV.x direction
+ ufbx_vertex_vec3 vertex_bitangent; // < (optional) Tangent vector in UV.y direction
+ ufbx_vertex_vec4 vertex_color; // < (optional) Per-vertex RGBA color
+ ufbx_vertex_real vertex_crease; // < (optional) Crease value for subdivision surfaces
+
+ // Multiple named UV/color sets
+ // NOTE: The first set contains the same data as `vertex_uv/color`!
+ ufbx_uv_set_list uv_sets;
+ ufbx_color_set_list color_sets;
+
+ // Materials used by the mesh.
+ // NOTE: These can be wrong if you want to support per-instance materials!
+ // Use `ufbx_node.materials[]` to get the per-instance materials at the same indices.
+ ufbx_material_list materials;
+
+ // Face groups for this mesh.
+ ufbx_face_group_list face_groups;
+
+ // Segments that use a given material.
+ // Defined even if the mesh doesn't have any materials.
+ ufbx_mesh_part_list material_parts;
+
+ // Segments for each face group.
+ ufbx_mesh_part_list face_group_parts;
+
+ // Order of `material_parts` by first face that refers to it.
+ // Useful for compatibility with FBX SDK and various importers using it,
+ // as they use this material order by default.
+ ufbx_uint32_list material_part_usage_order;
+
+ // Skinned vertex positions, for efficiency the skinned positions are the
+ // same as the static ones for non-skinned meshes and `skinned_is_local`
+ // is set to true meaning you need to transform them manually using
+ // `ufbx_transform_position(&node->geometry_to_world, skinned_pos)`!
+ bool skinned_is_local;
+ ufbx_vertex_vec3 skinned_position;
+ ufbx_vertex_vec3 skinned_normal;
+
+ // Deformers
+ ufbx_skin_deformer_list skin_deformers;
+ ufbx_blend_deformer_list blend_deformers;
+ ufbx_cache_deformer_list cache_deformers;
+ ufbx_element_list all_deformers;
+
+ // Subdivision
+ uint32_t subdivision_preview_levels;
+ uint32_t subdivision_render_levels;
+ ufbx_subdivision_display_mode subdivision_display_mode;
+ ufbx_subdivision_boundary subdivision_boundary;
+ ufbx_subdivision_boundary subdivision_uv_boundary;
+
+ // The winding of the faces has been reversed.
+ bool reversed_winding;
+
+ // Normals have been generated instead of evaluated.
+ // Either from missing normals (via `ufbx_load_opts.generate_missing_normals`), skinning,
+ // tessellation, or subdivision.
+ bool generated_normals;
+
+ // Subdivision (result)
+ bool subdivision_evaluated;
+ ufbx_nullable ufbx_subdivision_result *subdivision_result;
+
+ // Tessellation (result)
+ bool from_tessellated_nurbs;
+};
+
+// The kind of light source
+typedef enum ufbx_light_type UFBX_ENUM_REPR {
+ // Single point at local origin, at `node->world_transform.position`
+ UFBX_LIGHT_POINT,
+ // Infinite directional light pointing locally towards `light->local_direction`
+ // For global: `ufbx_transform_direction(&node->node_to_world, light->local_direction)`
+ UFBX_LIGHT_DIRECTIONAL,
+ // Cone shaped light towards `light->local_direction`, between `light->inner/outer_angle`.
+ // For global: `ufbx_transform_direction(&node->node_to_world, light->local_direction)`
+ UFBX_LIGHT_SPOT,
+ // Area light, shape specified by `light->area_shape`
+ // TODO: Units?
+ UFBX_LIGHT_AREA,
+ // Volumetric light source
+ // TODO: How does this work
+ UFBX_LIGHT_VOLUME,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_LIGHT_TYPE)
+} ufbx_light_type;
+
+UFBX_ENUM_TYPE(ufbx_light_type, UFBX_LIGHT_TYPE, UFBX_LIGHT_VOLUME);
+
+// How fast does the light intensity decay at a distance
+typedef enum ufbx_light_decay UFBX_ENUM_REPR {
+ UFBX_LIGHT_DECAY_NONE, // < 1 (no decay)
+ UFBX_LIGHT_DECAY_LINEAR, // < 1 / d
+ UFBX_LIGHT_DECAY_QUADRATIC, // < 1 / d^2 (physically accurate)
+ UFBX_LIGHT_DECAY_CUBIC, // < 1 / d^3
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_LIGHT_DECAY)
+} ufbx_light_decay;
+
+UFBX_ENUM_TYPE(ufbx_light_decay, UFBX_LIGHT_DECAY, UFBX_LIGHT_DECAY_CUBIC);
+
+typedef enum ufbx_light_area_shape UFBX_ENUM_REPR {
+ UFBX_LIGHT_AREA_SHAPE_RECTANGLE,
+ UFBX_LIGHT_AREA_SHAPE_SPHERE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_LIGHT_AREA_SHAPE)
+} ufbx_light_area_shape;
+
+UFBX_ENUM_TYPE(ufbx_light_area_shape, UFBX_LIGHT_AREA_SHAPE, UFBX_LIGHT_AREA_SHAPE_SPHERE);
+
+// Light source attached to a `ufbx_node`
+struct ufbx_light {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Color and intensity of the light, usually you want to use `color * intensity`
+ // NOTE: `intensity` is 0.01x of the property `"Intensity"` as that matches
+ // matches values in DCC programs before exporting.
+ ufbx_vec3 color;
+ ufbx_real intensity;
+
+ // Direction the light is aimed at in node's local space, usually -Y
+ ufbx_vec3 local_direction;
+
+ // Type of the light and shape parameters
+ ufbx_light_type type;
+ ufbx_light_decay decay;
+ ufbx_light_area_shape area_shape;
+ ufbx_real inner_angle;
+ ufbx_real outer_angle;
+
+ bool cast_light;
+ bool cast_shadows;
+};
+
+typedef enum ufbx_projection_mode UFBX_ENUM_REPR {
+ // Perspective projection.
+ UFBX_PROJECTION_MODE_PERSPECTIVE,
+
+ // Orthographic projection.
+ UFBX_PROJECTION_MODE_ORTHOGRAPHIC,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_PROJECTION_MODE)
+} ufbx_projection_mode;
+
+UFBX_ENUM_TYPE(ufbx_projection_mode, UFBX_PROJECTION_MODE, UFBX_PROJECTION_MODE_ORTHOGRAPHIC);
+
+// Method of specifying the rendering resolution from properties
+// NOTE: Handled internally by ufbx, ignore unless you interpret `ufbx_props` directly!
+typedef enum ufbx_aspect_mode UFBX_ENUM_REPR {
+ // No defined resolution
+ UFBX_ASPECT_MODE_WINDOW_SIZE,
+ // `"AspectWidth"` and `"AspectHeight"` are relative to each other
+ UFBX_ASPECT_MODE_FIXED_RATIO,
+ // `"AspectWidth"` and `"AspectHeight"` are both pixels
+ UFBX_ASPECT_MODE_FIXED_RESOLUTION,
+ // `"AspectWidth"` is pixels, `"AspectHeight"` is relative to width
+ UFBX_ASPECT_MODE_FIXED_WIDTH,
+ // < `"AspectHeight"` is pixels, `"AspectWidth"` is relative to height
+ UFBX_ASPECT_MODE_FIXED_HEIGHT,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_ASPECT_MODE)
+} ufbx_aspect_mode;
+
+UFBX_ENUM_TYPE(ufbx_aspect_mode, UFBX_ASPECT_MODE, UFBX_ASPECT_MODE_FIXED_HEIGHT);
+
+// Method of specifying the field of view from properties
+// NOTE: Handled internally by ufbx, ignore unless you interpret `ufbx_props` directly!
+typedef enum ufbx_aperture_mode UFBX_ENUM_REPR {
+ // Use separate `"FieldOfViewX"` and `"FieldOfViewY"` as horizontal/vertical FOV angles
+ UFBX_APERTURE_MODE_HORIZONTAL_AND_VERTICAL,
+ // Use `"FieldOfView"` as horizontal FOV angle, derive vertical angle via aspect ratio
+ UFBX_APERTURE_MODE_HORIZONTAL,
+ // Use `"FieldOfView"` as vertical FOV angle, derive horizontal angle via aspect ratio
+ UFBX_APERTURE_MODE_VERTICAL,
+ // Compute the field of view from the render gate size and focal length
+ UFBX_APERTURE_MODE_FOCAL_LENGTH,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_APERTURE_MODE)
+} ufbx_aperture_mode;
+
+UFBX_ENUM_TYPE(ufbx_aperture_mode, UFBX_APERTURE_MODE, UFBX_APERTURE_MODE_FOCAL_LENGTH);
+
+// Method of specifying the render gate size from properties
+// NOTE: Handled internally by ufbx, ignore unless you interpret `ufbx_props` directly!
+typedef enum ufbx_gate_fit UFBX_ENUM_REPR {
+ // Use the film/aperture size directly as the render gate
+ UFBX_GATE_FIT_NONE,
+ // Fit the render gate to the height of the film, derive width from aspect ratio
+ UFBX_GATE_FIT_VERTICAL,
+ // Fit the render gate to the width of the film, derive height from aspect ratio
+ UFBX_GATE_FIT_HORIZONTAL,
+ // Fit the render gate so that it is fully contained within the film gate
+ UFBX_GATE_FIT_FILL,
+ // Fit the render gate so that it fully contains the film gate
+ UFBX_GATE_FIT_OVERSCAN,
+ // Stretch the render gate to match the film gate
+ // TODO: Does this differ from `UFBX_GATE_FIT_NONE`?
+ UFBX_GATE_FIT_STRETCH,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_GATE_FIT)
+} ufbx_gate_fit;
+
+UFBX_ENUM_TYPE(ufbx_gate_fit, UFBX_GATE_FIT, UFBX_GATE_FIT_STRETCH);
+
+// Camera film/aperture size defaults
+// NOTE: Handled internally by ufbx, ignore unless you interpret `ufbx_props` directly!
+typedef enum ufbx_aperture_format UFBX_ENUM_REPR {
+ UFBX_APERTURE_FORMAT_CUSTOM, // < Use `"FilmWidth"` and `"FilmHeight"`
+ UFBX_APERTURE_FORMAT_16MM_THEATRICAL, // < 0.404 x 0.295 inches
+ UFBX_APERTURE_FORMAT_SUPER_16MM, // < 0.493 x 0.292 inches
+ UFBX_APERTURE_FORMAT_35MM_ACADEMY, // < 0.864 x 0.630 inches
+ UFBX_APERTURE_FORMAT_35MM_TV_PROJECTION, // < 0.816 x 0.612 inches
+ UFBX_APERTURE_FORMAT_35MM_FULL_APERTURE, // < 0.980 x 0.735 inches
+ UFBX_APERTURE_FORMAT_35MM_185_PROJECTION, // < 0.825 x 0.446 inches
+ UFBX_APERTURE_FORMAT_35MM_ANAMORPHIC, // < 0.864 x 0.732 inches (squeeze ratio: 2)
+ UFBX_APERTURE_FORMAT_70MM_PROJECTION, // < 2.066 x 0.906 inches
+ UFBX_APERTURE_FORMAT_VISTAVISION, // < 1.485 x 0.991 inches
+ UFBX_APERTURE_FORMAT_DYNAVISION, // < 2.080 x 1.480 inches
+ UFBX_APERTURE_FORMAT_IMAX, // < 2.772 x 2.072 inches
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_APERTURE_FORMAT)
+} ufbx_aperture_format;
+
+UFBX_ENUM_TYPE(ufbx_aperture_format, UFBX_APERTURE_FORMAT, UFBX_APERTURE_FORMAT_IMAX);
+
+typedef enum ufbx_coordinate_axis UFBX_ENUM_REPR {
+ UFBX_COORDINATE_AXIS_POSITIVE_X,
+ UFBX_COORDINATE_AXIS_NEGATIVE_X,
+ UFBX_COORDINATE_AXIS_POSITIVE_Y,
+ UFBX_COORDINATE_AXIS_NEGATIVE_Y,
+ UFBX_COORDINATE_AXIS_POSITIVE_Z,
+ UFBX_COORDINATE_AXIS_NEGATIVE_Z,
+ UFBX_COORDINATE_AXIS_UNKNOWN,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_COORDINATE_AXIS)
+} ufbx_coordinate_axis;
+
+UFBX_ENUM_TYPE(ufbx_coordinate_axis, UFBX_COORDINATE_AXIS, UFBX_COORDINATE_AXIS_UNKNOWN);
+
+// Coordinate axes the scene is represented in.
+// NOTE: `front` is the _opposite_ from forward!
+typedef struct ufbx_coordinate_axes {
+ ufbx_coordinate_axis right;
+ ufbx_coordinate_axis up;
+ ufbx_coordinate_axis front;
+} ufbx_coordinate_axes;
+
+// Camera attached to a `ufbx_node`
+struct ufbx_camera {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Projection mode (perspective/orthographic).
+ ufbx_projection_mode projection_mode;
+
+ // If set to `true`, `resolution` represents actual pixel values, otherwise
+ // it's only useful for its aspect ratio.
+ bool resolution_is_pixels;
+
+ // Render resolution, either in pixels or arbitrary units, depending on above
+ ufbx_vec2 resolution;
+
+ // Horizontal/vertical field of view in degrees
+ // Valid if `projection_mode == UFBX_PROJECTION_MODE_PERSPECTIVE`.
+ ufbx_vec2 field_of_view_deg;
+
+ // Component-wise `tan(field_of_view_deg)`, also represents the size of the
+ // frustum slice at distance of 1.
+ // Valid if `projection_mode == UFBX_PROJECTION_MODE_PERSPECTIVE`.
+ ufbx_vec2 field_of_view_tan;
+
+ // Orthographic camera extents.
+ // Valid if `projection_mode == UFBX_PROJECTION_MODE_ORTHOGRAPHIC`.
+ ufbx_real orthographic_extent;
+
+ // Orthographic camera size.
+ // Valid if `projection_mode == UFBX_PROJECTION_MODE_ORTHOGRAPHIC`.
+ ufbx_vec2 orthographic_size;
+
+ // Size of the projection plane at distance 1.
+ // Equal to `field_of_view_tan` if perspective, `orthographic_size` if orthographic.
+ ufbx_vec2 projection_plane;
+
+ // Aspect ratio of the camera.
+ ufbx_real aspect_ratio;
+
+ // Near plane of the frustum in units from the camera.
+ ufbx_real near_plane;
+
+ // Far plane of the frustum in units from the camera.
+ ufbx_real far_plane;
+
+ // Coordinate system that the projection uses.
+ // FBX saves cameras with +X forward and +Y up, but you can override this using
+ // `ufbx_load_opts.target_camera_axes` and it will be reflected here.
+ ufbx_coordinate_axes projection_axes;
+
+ // Advanced properties used to compute the above
+ ufbx_aspect_mode aspect_mode;
+ ufbx_aperture_mode aperture_mode;
+ ufbx_gate_fit gate_fit;
+ ufbx_aperture_format aperture_format;
+ ufbx_real focal_length_mm; // < Focal length in millimeters
+ ufbx_vec2 film_size_inch; // < Film size in inches
+ ufbx_vec2 aperture_size_inch; // < Aperture/film gate size in inches
+ ufbx_real squeeze_ratio; // < Anamoprhic stretch ratio
+};
+
+// Bone attached to a `ufbx_node`, provides the logical length of the bone
+// but most interesting information is directly in `ufbx_node`.
+// NOTE: The FBX format calls these Skeleton node attributes.
+struct ufbx_bone {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Visual radius of the bone
+ ufbx_real radius;
+
+ // Length of the bone relative to the distance between two nodes
+ ufbx_real relative_length;
+
+ // Is the bone a root bone
+ bool is_root;
+};
+
+// Empty/NULL/locator connected to a node, actual details in `ufbx_node`
+// NOTE: The FBX format calls these Null node attributes.
+struct ufbx_empty {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+};
+
+// -- Node attributes (curves/surfaces)
+
+// Segment of a `ufbx_line_curve`, indices refer to `ufbx_line_curve.point_indices[]`
+typedef struct ufbx_line_segment {
+ uint32_t index_begin;
+ uint32_t num_indices;
+} ufbx_line_segment;
+
+UFBX_LIST_TYPE(ufbx_line_segment_list, ufbx_line_segment);
+
+struct ufbx_line_curve {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ ufbx_vec3 color;
+
+ ufbx_vec3_list control_points; // < List of possible values the line passes through
+ ufbx_uint32_list point_indices; // < Indices to `control_points[]` the line goes through
+
+ ufbx_line_segment_list segments;
+
+ // Tessellation (result)
+ bool from_tessellated_nurbs;
+};
+
+typedef enum ufbx_nurbs_topology UFBX_ENUM_REPR {
+ // The endpoints are not connected.
+ UFBX_NURBS_TOPOLOGY_OPEN,
+ // Repeats first `ufbx_nurbs_basis.order - 1` control points after the end.
+ UFBX_NURBS_TOPOLOGY_PERIODIC,
+ // Repeats the first control point after the end.
+ UFBX_NURBS_TOPOLOGY_CLOSED,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_NURBS_TOPOLOGY)
+} ufbx_nurbs_topology;
+
+UFBX_ENUM_TYPE(ufbx_nurbs_topology, UFBX_NURBS_TOPOLOGY, UFBX_NURBS_TOPOLOGY_CLOSED);
+
+// NURBS basis functions for an axis
+typedef struct ufbx_nurbs_basis {
+
+ // Number of control points influencing a point on the curve/surface.
+ // Equal to the degree plus one.
+ uint32_t order;
+
+ // Topology (periodicity) of the dimension.
+ ufbx_nurbs_topology topology;
+
+ // Subdivision of the parameter range to control points.
+ ufbx_real_list knot_vector;
+
+ // Range for the parameter value.
+ ufbx_real t_min;
+ ufbx_real t_max;
+
+ // Parameter values of control points.
+ ufbx_real_list spans;
+
+ // `true` if this axis is two-dimensional.
+ bool is_2d;
+
+ // Number of control points that need to be copied to the end.
+ // This is just for convenience as it could be derived from `topology` and
+ // `order`. If for example `num_wrap_control_points == 3` you should repeat
+ // the first 3 control points after the end.
+ // HINT: You don't need to worry about this if you use ufbx functions
+ // like `ufbx_evaluate_nurbs_curve()` as they handle this internally.
+ size_t num_wrap_control_points;
+
+ // `true` if the parametrization is well defined.
+ bool valid;
+
+} ufbx_nurbs_basis;
+
+struct ufbx_nurbs_curve {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Basis in the U axis
+ ufbx_nurbs_basis basis;
+
+ // Linear array of control points
+ // NOTE: The control points are _not_ homogeneous, meaning you have to multiply
+ // them by `w` before evaluating the surface.
+ ufbx_vec4_list control_points;
+};
+
+struct ufbx_nurbs_surface {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Basis in the U/V axes
+ ufbx_nurbs_basis basis_u;
+ ufbx_nurbs_basis basis_v;
+
+ // Number of control points for the U/V axes
+ size_t num_control_points_u;
+ size_t num_control_points_v;
+
+ // 2D array of control points.
+ // Memory layout: `V * num_control_points_u + U`
+ // NOTE: The control points are _not_ homogeneous, meaning you have to multiply
+ // them by `w` before evaluating the surface.
+ ufbx_vec4_list control_points;
+
+ // How many segments tessellate each span in `ufbx_nurbs_basis.spans`.
+ uint32_t span_subdivision_u;
+ uint32_t span_subdivision_v;
+
+ // If `true` the resulting normals should be flipped when evaluated.
+ bool flip_normals;
+
+ // Material for the whole surface.
+ // NOTE: May be `NULL`!
+ ufbx_nullable ufbx_material *material;
+};
+
+struct ufbx_nurbs_trim_surface {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+};
+
+struct ufbx_nurbs_trim_boundary {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+};
+
+// -- Node attributes (advanced)
+
+struct ufbx_procedural_geometry {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+};
+
+struct ufbx_stereo_camera {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ ufbx_nullable ufbx_camera *left;
+ ufbx_nullable ufbx_camera *right;
+};
+
+struct ufbx_camera_switcher {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+};
+
+typedef enum ufbx_marker_type UFBX_ENUM_REPR {
+ UFBX_MARKER_UNKNOWN, // < Unknown marker type
+ UFBX_MARKER_FK_EFFECTOR, // < FK (Forward Kinematics) effector
+ UFBX_MARKER_IK_EFFECTOR, // < IK (Inverse Kinematics) effector
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_MARKER_TYPE)
+} ufbx_marker_type;
+
+UFBX_ENUM_TYPE(ufbx_marker_type, UFBX_MARKER_TYPE, UFBX_MARKER_IK_EFFECTOR);
+
+// Tracking marker for effectors
+struct ufbx_marker {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // Type of the marker
+ ufbx_marker_type type;
+};
+
+// LOD level display mode.
+typedef enum ufbx_lod_display UFBX_ENUM_REPR {
+ UFBX_LOD_DISPLAY_USE_LOD, // < Display the LOD level if the distance is appropriate.
+ UFBX_LOD_DISPLAY_SHOW, // < Always display the LOD level.
+ UFBX_LOD_DISPLAY_HIDE, // < Never display the LOD level.
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_LOD_DISPLAY)
+} ufbx_lod_display;
+
+UFBX_ENUM_TYPE(ufbx_lod_display, UFBX_LOD_DISPLAY, UFBX_LOD_DISPLAY_HIDE);
+
+// Single LOD level within an LOD group.
+// Specifies properties of the Nth child of the _node_ containing the LOD group.
+typedef struct ufbx_lod_level {
+
+ // Minimum distance to show this LOD level.
+ // NOTE: In world units by default, or in screen percentage if
+ // `ufbx_lod_group.relative_distances` is set.
+ ufbx_real distance;
+
+ // LOD display mode.
+ // NOTE: Mostly for editing, you should probably ignore this
+ // unless making a modeling program.
+ ufbx_lod_display display;
+
+} ufbx_lod_level;
+
+UFBX_LIST_TYPE(ufbx_lod_level_list, ufbx_lod_level);
+
+// Group of LOD (Level of Detail) levels for an object.
+// The actual LOD models are defined in the parent `ufbx_node.children`.
+struct ufbx_lod_group {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ ufbx_node_list instances;
+ }; };
+
+ // If set to `true`, `ufbx_lod_level.distance` represents a screen size percentage.
+ bool relative_distances;
+
+ // LOD levels matching in order to `ufbx_node.children`.
+ ufbx_lod_level_list lod_levels;
+
+ // If set to `true` don't account for parent transform when computing the distance.
+ bool ignore_parent_transform;
+
+ // If `use_distance_limit` is enabled hide the group if the distance is not between
+ // `distance_limit_min` and `distance_limit_max`.
+ bool use_distance_limit;
+ ufbx_real distance_limit_min;
+ ufbx_real distance_limit_max;
+};
+
+// -- Deformers
+
+// Method to evaluate the skinning on a per-vertex level
+typedef enum ufbx_skinning_method UFBX_ENUM_REPR {
+ // Linear blend skinning: Blend transformation matrices by vertex weights
+ UFBX_SKINNING_METHOD_LINEAR,
+ // One vertex should have only one bone attached
+ UFBX_SKINNING_METHOD_RIGID,
+ // Convert the transformations to dual quaternions and blend in that space
+ UFBX_SKINNING_METHOD_DUAL_QUATERNION,
+ // Blend between `UFBX_SKINNING_METHOD_LINEAR` and `UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR`
+ // The blend weight can be found either per-vertex in `ufbx_skin_vertex.dq_weight`
+ // or in `ufbx_skin_deformer.dq_vertices/dq_weights` (indexed by vertex).
+ UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SKINNING_METHOD)
+} ufbx_skinning_method;
+
+UFBX_ENUM_TYPE(ufbx_skinning_method, UFBX_SKINNING_METHOD, UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR);
+
+// Skin weight information for a single mesh vertex
+typedef struct ufbx_skin_vertex {
+
+ // Each vertex is influenced by weights from `ufbx_skin_deformer.weights[]`
+ // The weights are sorted by decreasing weight so you can take the first N
+ // weights to get a cheaper approximation of the vertex.
+ // NOTE: The weights are not guaranteed to be normalized!
+ uint32_t weight_begin; // < Index to start from in the `weights[]` array
+ uint32_t num_weights; // < Number of weights influencing the vertex
+
+ // Blend weight between Linear Blend Skinning (0.0) and Dual Quaternion (1.0).
+ // Should be used if `skinning_method == UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR`
+ ufbx_real dq_weight;
+
+} ufbx_skin_vertex;
+
+UFBX_LIST_TYPE(ufbx_skin_vertex_list, ufbx_skin_vertex);
+
+// Single per-vertex per-cluster weight, see `ufbx_skin_vertex`
+typedef struct ufbx_skin_weight {
+ uint32_t cluster_index; // < Index into `ufbx_skin_deformer.clusters[]`
+ ufbx_real weight; // < Amount this bone influence the vertex
+} ufbx_skin_weight;
+
+UFBX_LIST_TYPE(ufbx_skin_weight_list, ufbx_skin_weight);
+
+// Skin deformer specifies a binding between a logical set of bones (a skeleton)
+// and a mesh. Each bone is represented by a `ufbx_skin_cluster` that contains
+// the binding matrix and a `ufbx_node *bone` that has the current transformation.
+struct ufbx_skin_deformer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ ufbx_skinning_method skinning_method;
+
+ // Clusters (bones) in the skin
+ ufbx_skin_cluster_list clusters;
+
+ // Per-vertex weight information
+ ufbx_skin_vertex_list vertices;
+ ufbx_skin_weight_list weights;
+
+ // Largest amount of weights a single vertex can have
+ size_t max_weights_per_vertex;
+
+ // Blend weights between Linear Blend Skinning (0.0) and Dual Quaternion (1.0).
+ // HINT: You probably want to use `vertices` and `ufbx_skin_vertex.dq_weight` instead!
+ // NOTE: These may be out-of-bounds for a given mesh, `vertices` is always safe.
+ size_t num_dq_weights;
+ ufbx_uint32_list dq_vertices;
+ ufbx_real_list dq_weights;
+};
+
+// Cluster of vertices bound to a single bone.
+struct ufbx_skin_cluster {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // The bone node the cluster is attached to
+ // NOTE: Always valid if found from `ufbx_skin_deformer.clusters[]` unless
+ // `ufbx_load_opts.connect_broken_elements` is `true`.
+ ufbx_nullable ufbx_node *bone_node;
+
+ // Binding matrix from local mesh vertices to the bone
+ ufbx_matrix geometry_to_bone;
+
+ // Binding matrix from local mesh _node_ to the bone.
+ // NOTE: Prefer `geometry_to_bone` in most use cases!
+ ufbx_matrix mesh_node_to_bone;
+
+ // Matrix that specifies the rest/bind pose transform of the node,
+ // not generally needed for skinning, use `geometry_to_bone` instead.
+ ufbx_matrix bind_to_world;
+
+ // Precomputed matrix/transform that accounts for the current bone transform
+ // ie. `ufbx_matrix_mul(&cluster->bone->node_to_world, &cluster->geometry_to_bone)`
+ ufbx_matrix geometry_to_world;
+ ufbx_transform geometry_to_world_transform;
+
+ // Raw weights indexed by each _vertex_ of a mesh (not index!)
+ // HINT: It may be simpler to use `ufbx_skin_deformer.vertices[]/weights[]` instead!
+ // NOTE: These may be out-of-bounds for a given mesh, `ufbx_skin_deformer.vertices` is always safe.
+ size_t num_weights; // < Number of vertices in the cluster
+ ufbx_uint32_list vertices; // < Vertex indices in `ufbx_mesh.vertices[]`
+ ufbx_real_list weights; // < Per-vertex weight values
+};
+
+// Blend shape deformer can contain multiple channels (think of sliders between morphs)
+// that may optionally have in-between keyframes.
+struct ufbx_blend_deformer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Independent morph targets of the deformer.
+ ufbx_blend_channel_list channels;
+};
+
+// Blend shape associated with a target weight in a series of morphs
+typedef struct ufbx_blend_keyframe {
+ // The target blend shape offsets.
+ ufbx_blend_shape *shape;
+
+ // Weight value at which to apply the keyframe at full strength
+ ufbx_real target_weight;
+
+ // The weight the shape should be currently applied with
+ ufbx_real effective_weight;
+} ufbx_blend_keyframe;
+
+UFBX_LIST_TYPE(ufbx_blend_keyframe_list, ufbx_blend_keyframe);
+
+// Blend channel consists of multiple morph-key targets that are interpolated.
+// In simple cases there will be only one keyframe that is the target shape.
+struct ufbx_blend_channel {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Current weight of the channel
+ ufbx_real weight;
+
+ // Key morph targets to blend between depending on `weight`
+ // In usual cases there's only one target per channel
+ ufbx_blend_keyframe_list keyframes;
+
+ // Final blend shape ignoring any intermediate blend shapes.
+ ufbx_nullable ufbx_blend_shape *target_shape;
+};
+
+// Blend shape target containing the actual vertex offsets
+struct ufbx_blend_shape {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Vertex offsets to apply over the base mesh
+ // NOTE: The `offset_vertices` may be out-of-bounds for a given mesh!
+ size_t num_offsets; // < Number of vertex offsets in the following arrays
+ ufbx_uint32_list offset_vertices; // < Indices to `ufbx_mesh.vertices[]`
+ ufbx_vec3_list position_offsets; // < Always specified per-vertex offsets
+ ufbx_vec3_list normal_offsets; // < Empty if not specified
+
+ // Optional weights for the offsets.
+ // NOTE: These are technically not supported in FBX and are only written by Blender.
+ ufbx_real_list offset_weights;
+};
+
+typedef enum ufbx_cache_file_format UFBX_ENUM_REPR {
+ UFBX_CACHE_FILE_FORMAT_UNKNOWN, // < Unknown cache file format
+ UFBX_CACHE_FILE_FORMAT_PC2, // < .pc2 Point cache file
+ UFBX_CACHE_FILE_FORMAT_MC, // < .mc/.mcx Maya cache file
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CACHE_FILE_FORMAT)
+} ufbx_cache_file_format;
+
+UFBX_ENUM_TYPE(ufbx_cache_file_format, UFBX_CACHE_FILE_FORMAT, UFBX_CACHE_FILE_FORMAT_MC);
+
+typedef enum ufbx_cache_data_format UFBX_ENUM_REPR {
+ UFBX_CACHE_DATA_FORMAT_UNKNOWN, // < Unknown data format
+ UFBX_CACHE_DATA_FORMAT_REAL_FLOAT, // < `float data[]`
+ UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT, // < `struct { float x, y, z; } data[]`
+ UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE, // < `double data[]`
+ UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE, // < `struct { double x, y, z; } data[]`
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CACHE_DATA_FORMAT)
+} ufbx_cache_data_format;
+
+UFBX_ENUM_TYPE(ufbx_cache_data_format, UFBX_CACHE_DATA_FORMAT, UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE);
+
+typedef enum ufbx_cache_data_encoding UFBX_ENUM_REPR {
+ UFBX_CACHE_DATA_ENCODING_UNKNOWN, // < Unknown data encoding
+ UFBX_CACHE_DATA_ENCODING_LITTLE_ENDIAN, // < Contiguous little-endian array
+ UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN, // < Contiguous big-endian array
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CACHE_DATA_ENCODING)
+} ufbx_cache_data_encoding;
+
+UFBX_ENUM_TYPE(ufbx_cache_data_encoding, UFBX_CACHE_DATA_ENCODING, UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN);
+
+// Known interpretations of geometry cache data.
+typedef enum ufbx_cache_interpretation UFBX_ENUM_REPR {
+ // Unknown interpretation, see `ufbx_cache_channel.interpretation_name` for more information.
+ UFBX_CACHE_INTERPRETATION_UNKNOWN,
+
+ // Generic "points" interpretation, FBX SDK default. Usually fine to interpret
+ // as vertex positions if no other cache channels are specified.
+ UFBX_CACHE_INTERPRETATION_POINTS,
+
+ // Vertex positions.
+ UFBX_CACHE_INTERPRETATION_VERTEX_POSITION,
+
+ // Vertex normals.
+ UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CACHE_INTERPRETATION)
+} ufbx_cache_interpretation;
+
+UFBX_ENUM_TYPE(ufbx_cache_interpretation, UFBX_CACHE_INTERPRETATION, UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL);
+
+typedef struct ufbx_cache_frame {
+
+ // Name of the channel this frame belongs to.
+ ufbx_string channel;
+
+ // Time of this frame in seconds.
+ double time;
+
+ // Name of the file containing the data.
+ // The specified file may contain multiple frames, use `data_offset` etc. to
+ // read at the right position.
+ ufbx_string filename;
+
+ // Format of the wrapper file.
+ ufbx_cache_file_format file_format;
+
+ // Axis to mirror the read data by.
+ ufbx_mirror_axis mirror_axis;
+
+ // Factor to scale the geometry by.
+ ufbx_real scale_factor;
+
+ ufbx_cache_data_format data_format; // < Format of the data in the file
+ ufbx_cache_data_encoding data_encoding; // < Binary encoding of the data
+ uint64_t data_offset; // < Byte offset into the file
+ uint32_t data_count; // < Number of data elements
+ uint32_t data_element_bytes; // < Size of a single data element in bytes
+ uint64_t data_total_bytes; // < Size of the whole data blob in bytes
+} ufbx_cache_frame;
+
+UFBX_LIST_TYPE(ufbx_cache_frame_list, ufbx_cache_frame);
+
+typedef struct ufbx_cache_channel {
+
+ // Name of the geometry cache channel.
+ ufbx_string name;
+
+ // What does the data in this channel represent.
+ ufbx_cache_interpretation interpretation;
+
+ // Source name for `interpretation`, especially useful if `interpretation` is
+ // `UFBX_CACHE_INTERPRETATION_UNKNOWN`.
+ ufbx_string interpretation_name;
+
+ // List of frames belonging to this channel.
+ // Sorted by time (`ufbx_cache_frame.time`).
+ ufbx_cache_frame_list frames;
+
+ // Axis to mirror the frames by.
+ ufbx_mirror_axis mirror_axis;
+
+ // Factor to scale the geometry by.
+ ufbx_real scale_factor;
+
+} ufbx_cache_channel;
+
+UFBX_LIST_TYPE(ufbx_cache_channel_list, ufbx_cache_channel);
+
+typedef struct ufbx_geometry_cache {
+ ufbx_string root_filename;
+ ufbx_cache_channel_list channels;
+ ufbx_cache_frame_list frames;
+ ufbx_string_list extra_info;
+} ufbx_geometry_cache;
+
+struct ufbx_cache_deformer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ ufbx_string channel;
+ ufbx_nullable ufbx_cache_file *file;
+
+ // Only valid if `ufbx_load_opts.load_external_files` is set!
+ ufbx_nullable ufbx_geometry_cache *external_cache;
+ ufbx_nullable ufbx_cache_channel *external_channel;
+};
+
+struct ufbx_cache_file {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Filename relative to the currently loaded file.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_string filename;
+ // Absolute filename specified in the file.
+ ufbx_string absolute_filename;
+ // Relative filename specified in the file.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_string relative_filename;
+
+ // Filename relative to the loaded file, non-UTF-8 encoded.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_blob raw_filename;
+ // Absolute filename specified in the file, non-UTF-8 encoded.
+ ufbx_blob raw_absolute_filename;
+ // Relative filename specified in the file, non-UTF-8 encoded.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_blob raw_relative_filename;
+
+ ufbx_cache_file_format format;
+
+ // Only valid if `ufbx_load_opts.load_external_files` is set!
+ ufbx_nullable ufbx_geometry_cache *external_cache;
+};
+
+// -- Materials
+
+// Material property, either specified with a constant value or a mapped texture
+typedef struct ufbx_material_map {
+
+ // Constant value or factor for the map.
+ // May be specified simultaneously with a texture, in this case most shading models
+ // use multiplicative tinting of the texture values.
+ union {
+ ufbx_real value_real;
+ ufbx_vec2 value_vec2;
+ ufbx_vec3 value_vec3;
+ ufbx_vec4 value_vec4;
+ };
+ int64_t value_int;
+
+ // Texture if connected, otherwise `NULL`.
+ // May be valid but "disabled" (application specific) if `texture_enabled == false`.
+ ufbx_nullable ufbx_texture *texture;
+
+ // `true` if the file has specified any of the values above.
+ // NOTE: The value may be set to a non-zero default even if `has_value == false`,
+ // for example missing factors are set to `1.0` if a color is defined.
+ bool has_value;
+
+ // Controls whether shading should use `texture`.
+ // NOTE: Some shading models allow this to be `true` even if `texture == NULL`.
+ bool texture_enabled;
+
+ // Set to `true` if this feature should be disabled (specific to shader type).
+ bool feature_disabled;
+
+ // Number of components in the value from 1 to 4 if defined, 0 if not.
+ uint8_t value_components;
+
+} ufbx_material_map;
+
+// Material feature
+typedef struct ufbx_material_feature_info {
+
+ // Whether the material model uses this feature or not.
+ // NOTE: The feature can be enabled but still not used if eg. the corresponding factor is at zero!
+ bool enabled;
+
+ // Explicitly enabled/disabled by the material.
+ bool is_explicit;
+
+} ufbx_material_feature_info;
+
+// Texture attached to an FBX property
+typedef struct ufbx_material_texture {
+ ufbx_string material_prop; // < Name of the property in `ufbx_material.props`
+ ufbx_string shader_prop; // < Shader-specific property mapping name
+
+ // Texture attached to the property.
+ ufbx_texture *texture;
+
+} ufbx_material_texture;
+
+UFBX_LIST_TYPE(ufbx_material_texture_list, ufbx_material_texture);
+
+// Shading model type
+typedef enum ufbx_shader_type UFBX_ENUM_REPR {
+ // Unknown shading model
+ UFBX_SHADER_UNKNOWN,
+ // FBX builtin diffuse material
+ UFBX_SHADER_FBX_LAMBERT,
+ // FBX builtin diffuse+specular material
+ UFBX_SHADER_FBX_PHONG,
+ // Open Shading Language standard surface
+ // https://github.com/Autodesk/standard-surface
+ UFBX_SHADER_OSL_STANDARD_SURFACE,
+ // Arnold standard surface
+ // https://docs.arnoldrenderer.com/display/A5AFMUG/Standard+Surface
+ UFBX_SHADER_ARNOLD_STANDARD_SURFACE,
+ // 3ds Max Physical Material
+ // https://knowledge.autodesk.com/support/3ds-max/learn-explore/caas/CloudHelp/cloudhelp/2022/ENU/3DSMax-Lighting-Shading/files/GUID-C1328905-7783-4917-AB86-FC3CC19E8972-htm.html
+ UFBX_SHADER_3DS_MAX_PHYSICAL_MATERIAL,
+ // 3ds Max PBR (Metal/Rough) material
+ // https://knowledge.autodesk.com/support/3ds-max/learn-explore/caas/CloudHelp/cloudhelp/2021/ENU/3DSMax-Lighting-Shading/files/GUID-A16234A5-6500-4662-8B20-A5EC9FE1B255-htm.html
+ UFBX_SHADER_3DS_MAX_PBR_METAL_ROUGH,
+ // 3ds Max PBR (Spec/Gloss) material
+ // https://knowledge.autodesk.com/support/3ds-max/learn-explore/caas/CloudHelp/cloudhelp/2021/ENU/3DSMax-Lighting-Shading/files/GUID-18087194-B2A6-43EF-9B80-8FD1736FAE52-htm.html
+ UFBX_SHADER_3DS_MAX_PBR_SPEC_GLOSS,
+ // 3ds glTF Material
+ // https://help.autodesk.com/view/3DSMAX/2023/ENU/?guid=GUID-7ABFB805-1D9F-417E-9C22-704BFDF160FA
+ UFBX_SHADER_GLTF_MATERIAL,
+ // 3ds OpenPBR Material
+ // https://help.autodesk.com/view/3DSMAX/2025/ENU/?guid=GUID-CD90329C-1E2B-4BBA-9285-3BB46253B9C2
+ UFBX_SHADER_OPENPBR_MATERIAL,
+ // Stingray ShaderFX shader graph.
+ // Contains a serialized `"ShaderGraph"` in `ufbx_props`.
+ UFBX_SHADER_SHADERFX_GRAPH,
+ // Variation of the FBX phong shader that can recover PBR properties like
+ // `metalness` or `roughness` from the FBX non-physical values.
+ // NOTE: Enable `ufbx_load_opts.use_blender_pbr_material`.
+ UFBX_SHADER_BLENDER_PHONG,
+ // Wavefront .mtl format shader (used by .obj files)
+ UFBX_SHADER_WAVEFRONT_MTL,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SHADER_TYPE)
+} ufbx_shader_type;
+
+UFBX_ENUM_TYPE(ufbx_shader_type, UFBX_SHADER_TYPE, UFBX_SHADER_WAVEFRONT_MTL);
+
+// FBX builtin material properties, matches maps in `ufbx_material_fbx_maps`
+typedef enum ufbx_material_fbx_map UFBX_ENUM_REPR {
+ UFBX_MATERIAL_FBX_DIFFUSE_FACTOR,
+ UFBX_MATERIAL_FBX_DIFFUSE_COLOR,
+ UFBX_MATERIAL_FBX_SPECULAR_FACTOR,
+ UFBX_MATERIAL_FBX_SPECULAR_COLOR,
+ UFBX_MATERIAL_FBX_SPECULAR_EXPONENT,
+ UFBX_MATERIAL_FBX_REFLECTION_FACTOR,
+ UFBX_MATERIAL_FBX_REFLECTION_COLOR,
+ UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR,
+ UFBX_MATERIAL_FBX_TRANSPARENCY_COLOR,
+ UFBX_MATERIAL_FBX_EMISSION_FACTOR,
+ UFBX_MATERIAL_FBX_EMISSION_COLOR,
+ UFBX_MATERIAL_FBX_AMBIENT_FACTOR,
+ UFBX_MATERIAL_FBX_AMBIENT_COLOR,
+ UFBX_MATERIAL_FBX_NORMAL_MAP,
+ UFBX_MATERIAL_FBX_BUMP,
+ UFBX_MATERIAL_FBX_BUMP_FACTOR,
+ UFBX_MATERIAL_FBX_DISPLACEMENT_FACTOR,
+ UFBX_MATERIAL_FBX_DISPLACEMENT,
+ UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT_FACTOR,
+ UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_MATERIAL_FBX_MAP)
+} ufbx_material_fbx_map;
+
+UFBX_ENUM_TYPE(ufbx_material_fbx_map, UFBX_MATERIAL_FBX_MAP, UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT);
+
+// Known PBR material properties, matches maps in `ufbx_material_pbr_maps`
+typedef enum ufbx_material_pbr_map UFBX_ENUM_REPR {
+ UFBX_MATERIAL_PBR_BASE_FACTOR,
+ UFBX_MATERIAL_PBR_BASE_COLOR,
+ UFBX_MATERIAL_PBR_ROUGHNESS,
+ UFBX_MATERIAL_PBR_METALNESS,
+ UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS,
+ UFBX_MATERIAL_PBR_SPECULAR_FACTOR,
+ UFBX_MATERIAL_PBR_SPECULAR_COLOR,
+ UFBX_MATERIAL_PBR_SPECULAR_IOR,
+ UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY,
+ UFBX_MATERIAL_PBR_SPECULAR_ROTATION,
+ UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR,
+ UFBX_MATERIAL_PBR_TRANSMISSION_COLOR,
+ UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH,
+ UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER,
+ UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY,
+ UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION,
+ UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS,
+ UFBX_MATERIAL_PBR_TRANSMISSION_EXTRA_ROUGHNESS,
+ UFBX_MATERIAL_PBR_TRANSMISSION_PRIORITY,
+ UFBX_MATERIAL_PBR_TRANSMISSION_ENABLE_IN_AOV,
+ UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR,
+ UFBX_MATERIAL_PBR_SUBSURFACE_COLOR,
+ UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS,
+ UFBX_MATERIAL_PBR_SUBSURFACE_SCALE,
+ UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY,
+ UFBX_MATERIAL_PBR_SUBSURFACE_TINT_COLOR,
+ UFBX_MATERIAL_PBR_SUBSURFACE_TYPE,
+ UFBX_MATERIAL_PBR_SHEEN_FACTOR,
+ UFBX_MATERIAL_PBR_SHEEN_COLOR,
+ UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS,
+ UFBX_MATERIAL_PBR_COAT_FACTOR,
+ UFBX_MATERIAL_PBR_COAT_COLOR,
+ UFBX_MATERIAL_PBR_COAT_ROUGHNESS,
+ UFBX_MATERIAL_PBR_COAT_IOR,
+ UFBX_MATERIAL_PBR_COAT_ANISOTROPY,
+ UFBX_MATERIAL_PBR_COAT_ROTATION,
+ UFBX_MATERIAL_PBR_COAT_NORMAL,
+ UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_COLOR,
+ UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_ROUGHNESS,
+ UFBX_MATERIAL_PBR_THIN_FILM_FACTOR,
+ UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS,
+ UFBX_MATERIAL_PBR_THIN_FILM_IOR,
+ UFBX_MATERIAL_PBR_EMISSION_FACTOR,
+ UFBX_MATERIAL_PBR_EMISSION_COLOR,
+ UFBX_MATERIAL_PBR_OPACITY,
+ UFBX_MATERIAL_PBR_INDIRECT_DIFFUSE,
+ UFBX_MATERIAL_PBR_INDIRECT_SPECULAR,
+ UFBX_MATERIAL_PBR_NORMAL_MAP,
+ UFBX_MATERIAL_PBR_TANGENT_MAP,
+ UFBX_MATERIAL_PBR_DISPLACEMENT_MAP,
+ UFBX_MATERIAL_PBR_MATTE_FACTOR,
+ UFBX_MATERIAL_PBR_MATTE_COLOR,
+ UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION,
+ UFBX_MATERIAL_PBR_GLOSSINESS,
+ UFBX_MATERIAL_PBR_COAT_GLOSSINESS,
+ UFBX_MATERIAL_PBR_TRANSMISSION_GLOSSINESS,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_MATERIAL_PBR_MAP)
+} ufbx_material_pbr_map;
+
+UFBX_ENUM_TYPE(ufbx_material_pbr_map, UFBX_MATERIAL_PBR_MAP, UFBX_MATERIAL_PBR_TRANSMISSION_GLOSSINESS);
+
+// Known material features
+typedef enum ufbx_material_feature UFBX_ENUM_REPR {
+ UFBX_MATERIAL_FEATURE_PBR,
+ UFBX_MATERIAL_FEATURE_METALNESS,
+ UFBX_MATERIAL_FEATURE_DIFFUSE,
+ UFBX_MATERIAL_FEATURE_SPECULAR,
+ UFBX_MATERIAL_FEATURE_EMISSION,
+ UFBX_MATERIAL_FEATURE_TRANSMISSION,
+ UFBX_MATERIAL_FEATURE_COAT,
+ UFBX_MATERIAL_FEATURE_SHEEN,
+ UFBX_MATERIAL_FEATURE_OPACITY,
+ UFBX_MATERIAL_FEATURE_AMBIENT_OCCLUSION,
+ UFBX_MATERIAL_FEATURE_MATTE,
+ UFBX_MATERIAL_FEATURE_UNLIT,
+ UFBX_MATERIAL_FEATURE_IOR,
+ UFBX_MATERIAL_FEATURE_DIFFUSE_ROUGHNESS,
+ UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS,
+ UFBX_MATERIAL_FEATURE_THIN_WALLED,
+ UFBX_MATERIAL_FEATURE_CAUSTICS,
+ UFBX_MATERIAL_FEATURE_EXIT_TO_BACKGROUND,
+ UFBX_MATERIAL_FEATURE_INTERNAL_REFLECTIONS,
+ UFBX_MATERIAL_FEATURE_DOUBLE_SIDED,
+ UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS,
+ UFBX_MATERIAL_FEATURE_COAT_ROUGHNESS_AS_GLOSSINESS,
+ UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_MATERIAL_FEATURE)
+} ufbx_material_feature;
+
+UFBX_ENUM_TYPE(ufbx_material_feature, UFBX_MATERIAL_FEATURE, UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS);
+
+typedef struct ufbx_material_fbx_maps {
+ union {
+ ufbx_material_map maps[UFBX_MATERIAL_FBX_MAP_COUNT];
+ struct {
+ ufbx_material_map diffuse_factor;
+ ufbx_material_map diffuse_color;
+ ufbx_material_map specular_factor;
+ ufbx_material_map specular_color;
+ ufbx_material_map specular_exponent;
+ ufbx_material_map reflection_factor;
+ ufbx_material_map reflection_color;
+ ufbx_material_map transparency_factor;
+ ufbx_material_map transparency_color;
+ ufbx_material_map emission_factor;
+ ufbx_material_map emission_color;
+ ufbx_material_map ambient_factor;
+ ufbx_material_map ambient_color;
+ ufbx_material_map normal_map;
+ ufbx_material_map bump;
+ ufbx_material_map bump_factor;
+ ufbx_material_map displacement_factor;
+ ufbx_material_map displacement;
+ ufbx_material_map vector_displacement_factor;
+ ufbx_material_map vector_displacement;
+ };
+ };
+} ufbx_material_fbx_maps;
+
+typedef struct ufbx_material_pbr_maps {
+ union {
+ ufbx_material_map maps[UFBX_MATERIAL_PBR_MAP_COUNT];
+ struct {
+ ufbx_material_map base_factor;
+ ufbx_material_map base_color;
+ ufbx_material_map roughness;
+ ufbx_material_map metalness;
+ ufbx_material_map diffuse_roughness;
+ ufbx_material_map specular_factor;
+ ufbx_material_map specular_color;
+ ufbx_material_map specular_ior;
+ ufbx_material_map specular_anisotropy;
+ ufbx_material_map specular_rotation;
+ ufbx_material_map transmission_factor;
+ ufbx_material_map transmission_color;
+ ufbx_material_map transmission_depth;
+ ufbx_material_map transmission_scatter;
+ ufbx_material_map transmission_scatter_anisotropy;
+ ufbx_material_map transmission_dispersion;
+ ufbx_material_map transmission_roughness;
+ ufbx_material_map transmission_extra_roughness;
+ ufbx_material_map transmission_priority;
+ ufbx_material_map transmission_enable_in_aov;
+ ufbx_material_map subsurface_factor;
+ ufbx_material_map subsurface_color;
+ ufbx_material_map subsurface_radius;
+ ufbx_material_map subsurface_scale;
+ ufbx_material_map subsurface_anisotropy;
+ ufbx_material_map subsurface_tint_color;
+ ufbx_material_map subsurface_type;
+ ufbx_material_map sheen_factor;
+ ufbx_material_map sheen_color;
+ ufbx_material_map sheen_roughness;
+ ufbx_material_map coat_factor;
+ ufbx_material_map coat_color;
+ ufbx_material_map coat_roughness;
+ ufbx_material_map coat_ior;
+ ufbx_material_map coat_anisotropy;
+ ufbx_material_map coat_rotation;
+ ufbx_material_map coat_normal;
+ ufbx_material_map coat_affect_base_color;
+ ufbx_material_map coat_affect_base_roughness;
+ ufbx_material_map thin_film_factor;
+ ufbx_material_map thin_film_thickness;
+ ufbx_material_map thin_film_ior;
+ ufbx_material_map emission_factor;
+ ufbx_material_map emission_color;
+ ufbx_material_map opacity;
+ ufbx_material_map indirect_diffuse;
+ ufbx_material_map indirect_specular;
+ ufbx_material_map normal_map;
+ ufbx_material_map tangent_map;
+ ufbx_material_map displacement_map;
+ ufbx_material_map matte_factor;
+ ufbx_material_map matte_color;
+ ufbx_material_map ambient_occlusion;
+ ufbx_material_map glossiness;
+ ufbx_material_map coat_glossiness;
+ ufbx_material_map transmission_glossiness;
+ };
+ };
+} ufbx_material_pbr_maps;
+
+typedef struct ufbx_material_features {
+ union {
+ ufbx_material_feature_info features[UFBX_MATERIAL_FEATURE_COUNT];
+ struct {
+ ufbx_material_feature_info pbr;
+ ufbx_material_feature_info metalness;
+ ufbx_material_feature_info diffuse;
+ ufbx_material_feature_info specular;
+ ufbx_material_feature_info emission;
+ ufbx_material_feature_info transmission;
+ ufbx_material_feature_info coat;
+ ufbx_material_feature_info sheen;
+ ufbx_material_feature_info opacity;
+ ufbx_material_feature_info ambient_occlusion;
+ ufbx_material_feature_info matte;
+ ufbx_material_feature_info unlit;
+ ufbx_material_feature_info ior;
+ ufbx_material_feature_info diffuse_roughness;
+ ufbx_material_feature_info transmission_roughness;
+ ufbx_material_feature_info thin_walled;
+ ufbx_material_feature_info caustics;
+ ufbx_material_feature_info exit_to_background;
+ ufbx_material_feature_info internal_reflections;
+ ufbx_material_feature_info double_sided;
+ ufbx_material_feature_info roughness_as_glossiness;
+ ufbx_material_feature_info coat_roughness_as_glossiness;
+ ufbx_material_feature_info transmission_roughness_as_glossiness;
+ };
+ };
+} ufbx_material_features;
+
+// Surface material properties such as color, roughness, etc. Each property may
+// be optionally bound to an `ufbx_texture`.
+struct ufbx_material {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // FBX builtin properties
+ // NOTE: These may be empty if the material is using a custom shader
+ ufbx_material_fbx_maps fbx;
+
+ // PBR material properties, defined for all shading models but may be
+ // somewhat approximate if `shader == NULL`.
+ ufbx_material_pbr_maps pbr;
+
+ // Material features, primarily applies to `pbr`.
+ ufbx_material_features features;
+
+ // Shading information
+ ufbx_shader_type shader_type; // < Always defined
+ ufbx_nullable ufbx_shader *shader; // < Optional extended shader information
+ ufbx_string shading_model_name; // < Often one of `{ "lambert", "phong", "unknown" }`
+
+ // Prefix before shader property names with trailing `|`.
+ // For example `"3dsMax|Parameters|"` where properties would have names like
+ // `"3dsMax|Parameters|base_color"`. You can ignore this if you use the built-in
+ // `ufbx_material_fbx_maps fbx` and `ufbx_material_pbr_maps pbr` structures.
+ ufbx_string shader_prop_prefix;
+
+ // All textures attached to the material, if you want specific maps if might be
+ // more convenient to use eg. `fbx.diffuse_color.texture` or `pbr.base_color.texture`
+ ufbx_material_texture_list textures; // < Sorted by `material_prop`
+};
+
+typedef enum ufbx_texture_type UFBX_ENUM_REPR {
+
+ // Texture associated with an image file/sequence. `texture->filename` and
+ // and `texture->relative_filename` contain the texture's path. If the file
+ // has embedded content `texture->content` may hold `texture->content_size`
+ // bytes of raw image data.
+ UFBX_TEXTURE_FILE,
+
+ // The texture consists of multiple texture layers blended together.
+ UFBX_TEXTURE_LAYERED,
+
+ // Reserved as these _should_ exist in FBX files.
+ UFBX_TEXTURE_PROCEDURAL,
+
+ // Node in a shader graph.
+ // Use `ufbx_texture.shader` for more information.
+ UFBX_TEXTURE_SHADER,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_TEXTURE_TYPE)
+} ufbx_texture_type;
+
+UFBX_ENUM_TYPE(ufbx_texture_type, UFBX_TEXTURE_TYPE, UFBX_TEXTURE_SHADER);
+
+// Blend modes to combine layered textures with, compatible with common blend
+// mode definitions in many art programs. Simpler blend modes have equations
+// specified below where `src` is the layer to composite over `dst`.
+// See eg. https://www.w3.org/TR/2013/WD-compositing-1-20131010/#blendingseparable
+typedef enum ufbx_blend_mode UFBX_ENUM_REPR {
+ UFBX_BLEND_TRANSLUCENT, // < `src` effects result alpha
+ UFBX_BLEND_ADDITIVE, // < `src + dst`
+ UFBX_BLEND_MULTIPLY, // < `src * dst`
+ UFBX_BLEND_MULTIPLY_2X, // < `2 * src * dst`
+ UFBX_BLEND_OVER, // < `src * src_alpha + dst * (1-src_alpha)`
+ UFBX_BLEND_REPLACE, // < `src` Replace the contents
+ UFBX_BLEND_DISSOLVE, // < `random() + src_alpha >= 1.0 ? src : dst`
+ UFBX_BLEND_DARKEN, // < `min(src, dst)`
+ UFBX_BLEND_COLOR_BURN, // < `src > 0 ? 1 - min(1, (1-dst) / src) : 0`
+ UFBX_BLEND_LINEAR_BURN, // < `src + dst - 1`
+ UFBX_BLEND_DARKER_COLOR, // < `value(src) < value(dst) ? src : dst`
+ UFBX_BLEND_LIGHTEN, // < `max(src, dst)`
+ UFBX_BLEND_SCREEN, // < `1 - (1-src)*(1-dst)`
+ UFBX_BLEND_COLOR_DODGE, // < `src < 1 ? dst / (1 - src)` : (dst>0?1:0)`
+ UFBX_BLEND_LINEAR_DODGE, // < `src + dst`
+ UFBX_BLEND_LIGHTER_COLOR, // < `value(src) > value(dst) ? src : dst`
+ UFBX_BLEND_SOFT_LIGHT, // < https://www.w3.org/TR/2013/WD-compositing-1-20131010/#blendingsoftlight
+ UFBX_BLEND_HARD_LIGHT, // < https://www.w3.org/TR/2013/WD-compositing-1-20131010/#blendinghardlight
+ UFBX_BLEND_VIVID_LIGHT, // < Combination of `COLOR_DODGE` and `COLOR_BURN`
+ UFBX_BLEND_LINEAR_LIGHT, // < Combination of `LINEAR_DODGE` and `LINEAR_BURN`
+ UFBX_BLEND_PIN_LIGHT, // < Combination of `DARKEN` and `LIGHTEN`
+ UFBX_BLEND_HARD_MIX, // < Produces primary colors depending on similarity
+ UFBX_BLEND_DIFFERENCE, // < `abs(src - dst)`
+ UFBX_BLEND_EXCLUSION, // < `dst + src - 2 * src * dst`
+ UFBX_BLEND_SUBTRACT, // < `dst - src`
+ UFBX_BLEND_DIVIDE, // < `dst / src`
+ UFBX_BLEND_HUE, // < Replace hue
+ UFBX_BLEND_SATURATION, // < Replace saturation
+ UFBX_BLEND_COLOR, // < Replace hue and saturatio
+ UFBX_BLEND_LUMINOSITY, // < Replace value
+ UFBX_BLEND_OVERLAY, // < Same as `HARD_LIGHT` but with `src` and `dst` swapped
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_BLEND_MODE)
+} ufbx_blend_mode;
+
+UFBX_ENUM_TYPE(ufbx_blend_mode, UFBX_BLEND_MODE, UFBX_BLEND_OVERLAY);
+
+// Blend modes to combine layered textures with, compatible with common blend
+typedef enum ufbx_wrap_mode UFBX_ENUM_REPR {
+ UFBX_WRAP_REPEAT, // < Repeat the texture past the [0,1] range
+ UFBX_WRAP_CLAMP, // < Clamp the normalized texture coordinates to [0,1]
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_WRAP_MODE)
+} ufbx_wrap_mode;
+
+UFBX_ENUM_TYPE(ufbx_wrap_mode, UFBX_WRAP_MODE, UFBX_WRAP_CLAMP);
+
+// Single layer in a layered texture
+typedef struct ufbx_texture_layer {
+ ufbx_texture *texture; // < The inner texture to evaluate, never `NULL`
+ ufbx_blend_mode blend_mode; // < Equation to combine the layer to the background
+ ufbx_real alpha; // < Blend weight of this layer
+} ufbx_texture_layer;
+
+UFBX_LIST_TYPE(ufbx_texture_layer_list, ufbx_texture_layer);
+
+typedef enum ufbx_shader_texture_type UFBX_ENUM_REPR {
+ UFBX_SHADER_TEXTURE_UNKNOWN,
+
+ // Select an output of a multi-output shader.
+ // HINT: If this type is used the `ufbx_shader_texture.main_texture` and
+ // `ufbx_shader_texture.main_texture_output_index` fields are set.
+ UFBX_SHADER_TEXTURE_SELECT_OUTPUT,
+
+ // Open Shading Language (OSL) shader.
+ // https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
+ UFBX_SHADER_TEXTURE_OSL,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SHADER_TEXTURE_TYPE)
+} ufbx_shader_texture_type;
+
+UFBX_ENUM_TYPE(ufbx_shader_texture_type, UFBX_SHADER_TEXTURE_TYPE, UFBX_SHADER_TEXTURE_OSL);
+
+// Input to a shader texture, see `ufbx_shader_texture`.
+typedef struct ufbx_shader_texture_input {
+
+ // Name of the input.
+ ufbx_string name;
+
+ // Constant value of the input.
+ union {
+ ufbx_real value_real;
+ ufbx_vec2 value_vec2;
+ ufbx_vec3 value_vec3;
+ ufbx_vec4 value_vec4;
+ };
+ int64_t value_int;
+ ufbx_string value_str;
+ ufbx_blob value_blob;
+
+ // Texture connected to this input.
+ ufbx_nullable ufbx_texture *texture;
+
+ // Index of the output to use if `texture` is a multi-output shader node.
+ int64_t texture_output_index;
+
+ // Controls whether shading should use `texture`.
+ // NOTE: Some shading models allow this to be `true` even if `texture == NULL`.
+ bool texture_enabled;
+
+ // Property representing this input.
+ ufbx_prop *prop;
+
+ // Property representing `texture`.
+ ufbx_nullable ufbx_prop *texture_prop;
+
+ // Property representing `texture_enabled`.
+ ufbx_nullable ufbx_prop *texture_enabled_prop;
+
+} ufbx_shader_texture_input;
+
+UFBX_LIST_TYPE(ufbx_shader_texture_input_list, ufbx_shader_texture_input);
+
+// Texture that emulates a shader graph node.
+// 3ds Max exports some materials as node graphs serialized to textures.
+// ufbx can parse a small subset of these, as normal maps are often hidden behind
+// some kind of bump node.
+// NOTE: These encode a lot of details of 3ds Max internals, not recommended for direct use.
+// HINT: `ufbx_texture.file_textures[]` contains a list of "real" textures that are connected
+// to the `ufbx_texture` that is pretending to be a shader node.
+typedef struct ufbx_shader_texture {
+
+ // Type of this shader node.
+ ufbx_shader_texture_type type;
+
+ // Name of the shader to use.
+ ufbx_string shader_name;
+
+ // 64-bit opaque identifier for the shader type.
+ uint64_t shader_type_id;
+
+ // Input values/textures (possibly further shader textures) to the shader.
+ // Sorted by `ufbx_shader_texture_input.name`.
+ ufbx_shader_texture_input_list inputs;
+
+ // Shader source code if found.
+ ufbx_string shader_source;
+ ufbx_blob raw_shader_source;
+
+ // Representative texture for this shader.
+ // Only specified if `main_texture.outputs[main_texture_output_index]` is semantically
+ // equivalent to this texture.
+ ufbx_texture *main_texture;
+
+ // Output index of `main_texture` if it is a multi-output shader.
+ int64_t main_texture_output_index;
+
+ // Prefix for properties related to this shader in `ufbx_texture`.
+ // NOTE: Contains the trailing '|' if not empty.
+ ufbx_string prop_prefix;
+
+} ufbx_shader_texture;
+
+// Unique texture within the file.
+typedef struct ufbx_texture_file {
+
+ // Index in `ufbx_scene.texture_files[]`.
+ uint32_t index;
+
+ // Paths to the resource.
+
+ // Filename relative to the currently loaded file.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_string filename;
+ // Absolute filename specified in the file.
+ ufbx_string absolute_filename;
+ // Relative filename specified in the file.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_string relative_filename;
+
+ // Filename relative to the loaded file, non-UTF-8 encoded.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_blob raw_filename;
+ // Absolute filename specified in the file, non-UTF-8 encoded.
+ ufbx_blob raw_absolute_filename;
+ // Relative filename specified in the file, non-UTF-8 encoded.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_blob raw_relative_filename;
+
+ // Optional embedded content blob, eg. raw .png format data
+ ufbx_blob content;
+
+} ufbx_texture_file;
+
+UFBX_LIST_TYPE(ufbx_texture_file_list, ufbx_texture_file);
+
+// Texture that controls material appearance
+struct ufbx_texture {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Texture type (file / layered / procedural / shader)
+ ufbx_texture_type type;
+
+ // FILE: Paths to the resource
+
+ // Filename relative to the currently loaded file.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_string filename;
+ // Absolute filename specified in the file.
+ ufbx_string absolute_filename;
+ // Relative filename specified in the file.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_string relative_filename;
+
+ // Filename relative to the loaded file, non-UTF-8 encoded.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_blob raw_filename;
+ // Absolute filename specified in the file, non-UTF-8 encoded.
+ ufbx_blob raw_absolute_filename;
+ // Relative filename specified in the file, non-UTF-8 encoded.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_blob raw_relative_filename;
+
+ // FILE: Optional embedded content blob, eg. raw .png format data
+ ufbx_blob content;
+
+ // FILE: Optional video texture
+ ufbx_nullable ufbx_video *video;
+
+ // FILE: Index into `ufbx_scene.texture_files[]` or `UFBX_NO_INDEX`.
+ uint32_t file_index;
+
+ // FILE: True if `file_index` has a valid value.
+ bool has_file;
+
+ // LAYERED: Inner texture layers, ordered from _bottom_ to _top_
+ ufbx_texture_layer_list layers;
+
+ // SHADER: Shader information
+ // NOTE: May be specified even if `type == UFBX_TEXTURE_FILE` if `ufbx_load_opts.disable_quirks`
+ // is _not_ specified. Some known shaders that represent files are interpreted as `UFBX_TEXTURE_FILE`.
+ ufbx_nullable ufbx_shader_texture *shader;
+
+ // List of file textures representing this texture.
+ // Defined even if `type == UFBX_TEXTURE_FILE` in which case the array contains only itself.
+ ufbx_texture_list file_textures;
+
+ // Name of the UV set to use
+ ufbx_string uv_set;
+
+ // Wrapping mode
+ ufbx_wrap_mode wrap_u;
+ ufbx_wrap_mode wrap_v;
+
+ // UV transform
+ bool has_uv_transform; // < Has a non-identity `transform` and derived matrices.
+ ufbx_transform uv_transform; // < Texture transformation in UV space
+ ufbx_matrix texture_to_uv; // < Matrix representation of `transform`
+ ufbx_matrix uv_to_texture; // < UV coordinate to normalized texture coordinate matrix
+};
+
+// TODO: Video textures
+struct ufbx_video {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Paths to the resource
+
+ // Filename relative to the currently loaded file.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_string filename;
+ // Absolute filename specified in the file.
+ ufbx_string absolute_filename;
+ // Relative filename specified in the file.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_string relative_filename;
+
+ // Filename relative to the loaded file, non-UTF-8 encoded.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_blob raw_filename;
+ // Absolute filename specified in the file, non-UTF-8 encoded.
+ ufbx_blob raw_absolute_filename;
+ // Relative filename specified in the file, non-UTF-8 encoded.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_blob raw_relative_filename;
+
+ // Optional embedded content blob
+ ufbx_blob content;
+};
+
+// Shader specifies a shading model and contains `ufbx_shader_binding` elements
+// that define how to interpret FBX properties in the shader.
+struct ufbx_shader {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Known shading model
+ ufbx_shader_type type;
+
+ // TODO: Expose actual properties here
+
+ // Bindings from FBX properties to the shader
+ // HINT: `ufbx_find_shader_prop()` translates shader properties to FBX properties
+ ufbx_shader_binding_list bindings;
+};
+
+// Binding from a material property to shader implementation
+typedef struct ufbx_shader_prop_binding {
+ ufbx_string shader_prop; // < Property name used by the shader implementation
+ ufbx_string material_prop; // < Property name inside `ufbx_material.props`
+} ufbx_shader_prop_binding;
+
+UFBX_LIST_TYPE(ufbx_shader_prop_binding_list, ufbx_shader_prop_binding);
+
+// Shader binding table
+struct ufbx_shader_binding {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ ufbx_shader_prop_binding_list prop_bindings; // < Sorted by `shader_prop`
+};
+
+// -- Animation
+
+typedef struct ufbx_prop_override {
+ uint32_t element_id;
+
+ uint32_t _internal_key;
+
+ ufbx_string prop_name;
+ ufbx_vec4 value;
+ ufbx_string value_str;
+ int64_t value_int;
+} ufbx_prop_override;
+
+UFBX_LIST_TYPE(ufbx_prop_override_list, ufbx_prop_override);
+
+typedef struct ufbx_transform_override {
+ uint32_t node_id;
+ ufbx_transform transform;
+} ufbx_transform_override;
+
+UFBX_LIST_TYPE(ufbx_transform_override_list, ufbx_transform_override);
+
+// Animation descriptor used for evaluating animation.
+// Usually obtained from `ufbx_scene` via either global animation `ufbx_scene.anim`,
+// per-stack animation `ufbx_anim_stack.anim` or per-layer animation `ufbx_anim_layer.anim`.
+//
+// For advanced usage you can use `ufbx_create_anim()` to create animation descriptors
+// with custom layers, property overrides, special flags, etc.
+typedef struct ufbx_anim {
+
+ // Time begin/end for the animation, both may be zero if absent.
+ double time_begin;
+ double time_end;
+
+ // List of layers in the animation.
+ ufbx_anim_layer_list layers;
+
+ // Optional overrides for weights for each layer in `layers[]`.
+ ufbx_real_list override_layer_weights;
+
+ // Sorted by `element_id, prop_name`
+ ufbx_prop_override_list prop_overrides;
+
+ // Sorted by `node_id`
+ ufbx_transform_override_list transform_overrides;
+
+ // Evaluate connected properties as if they would not be connected.
+ bool ignore_connections;
+
+ // Custom `ufbx_anim` created by `ufbx_create_anim()`.
+ bool custom;
+
+} ufbx_anim;
+
+struct ufbx_anim_stack {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ double time_begin;
+ double time_end;
+
+ ufbx_anim_layer_list layers;
+ ufbx_anim *anim;
+};
+
+typedef struct ufbx_anim_prop {
+ ufbx_element *element;
+
+ uint32_t _internal_key;
+
+ ufbx_string prop_name;
+ ufbx_anim_value *anim_value;
+} ufbx_anim_prop;
+
+UFBX_LIST_TYPE(ufbx_anim_prop_list, ufbx_anim_prop);
+
+struct ufbx_anim_layer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ ufbx_real weight;
+ bool weight_is_animated;
+ bool blended;
+ bool additive;
+ bool compose_rotation;
+ bool compose_scale;
+
+ ufbx_anim_value_list anim_values;
+ ufbx_anim_prop_list anim_props; // < Sorted by `element,prop_name`
+
+ ufbx_anim *anim;
+
+ uint32_t _min_element_id;
+ uint32_t _max_element_id;
+ uint32_t _element_id_bitmask[4];
+};
+
+struct ufbx_anim_value {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ ufbx_vec3 default_value;
+ ufbx_nullable ufbx_anim_curve *curves[3];
+};
+
+// Animation curve segment interpolation mode between two keyframes
+typedef enum ufbx_interpolation UFBX_ENUM_REPR {
+ UFBX_INTERPOLATION_CONSTANT_PREV, // < Hold previous key value
+ UFBX_INTERPOLATION_CONSTANT_NEXT, // < Hold next key value
+ UFBX_INTERPOLATION_LINEAR, // < Linear interpolation between two keys
+ UFBX_INTERPOLATION_CUBIC, // < Cubic interpolation, see `ufbx_tangent`
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_INTERPOLATION)
+} ufbx_interpolation;
+
+UFBX_ENUM_TYPE(ufbx_interpolation, UFBX_INTERPOLATION, UFBX_INTERPOLATION_CUBIC);
+
+typedef enum ufbx_extrapolation_mode UFBX_ENUM_REPR {
+ UFBX_EXTRAPOLATION_CONSTANT, // < Use the value of the first/last keyframe
+ UFBX_EXTRAPOLATION_REPEAT, // < Repeat the whole animation curve
+ UFBX_EXTRAPOLATION_MIRROR, // < Repeat with mirroring
+ UFBX_EXTRAPOLATION_SLOPE, // < Use the tangent of the last keyframe to linearly extrapolate
+ UFBX_EXTRAPOLATION_REPEAT_RELATIVE, // < Repeat the animation curve but connect the first and last keyframe values
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_EXTRAPOLATION)
+} ufbx_extrapolation_mode;
+
+UFBX_ENUM_TYPE(ufbx_extrapolation_mode, UFBX_EXTRAPOLATION_MODE, UFBX_EXTRAPOLATION_REPEAT_RELATIVE);
+
+typedef struct ufbx_extrapolation {
+ ufbx_extrapolation_mode mode;
+
+ // Count used for repeating modes.
+ // Negative values mean infinite repetition.
+ int32_t repeat_count;
+} ufbx_extrapolation;
+
+// Tangent vector at a keyframe, may be split into left/right
+typedef struct ufbx_tangent {
+ float dx; // < Derivative in the time axis
+ float dy; // < Derivative in the (curve specific) value axis
+} ufbx_tangent;
+
+// Single real `value` at a specified `time`, interpolation between two keyframes
+// is determined by the `interpolation` field of the _previous_ key.
+// If `interpolation == UFBX_INTERPOLATION_CUBIC` the span is evaluated as a
+// cubic bezier curve through the following points:
+//
+// (prev->time, prev->value)
+// (prev->time + prev->right.dx, prev->value + prev->right.dy)
+// (next->time - next->left.dx, next->value - next->left.dy)
+// (next->time, next->value)
+//
+// HINT: You can use `ufbx_evaluate_curve(ufbx_anim_curve *curve, double time)`
+// rather than trying to manually handle all the interpolation modes.
+typedef struct ufbx_keyframe {
+ double time;
+ ufbx_real value;
+ ufbx_interpolation interpolation;
+ ufbx_tangent left;
+ ufbx_tangent right;
+} ufbx_keyframe;
+
+UFBX_LIST_TYPE(ufbx_keyframe_list, ufbx_keyframe);
+
+struct ufbx_anim_curve {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // List of keyframes that define the curve.
+ ufbx_keyframe_list keyframes;
+
+ // Extrapolation before the curve.
+ ufbx_extrapolation pre_extrapolation;
+ // Extrapolation after the curve.
+ ufbx_extrapolation post_extrapolation;
+
+ // Value range for all the keyframes.
+ ufbx_real min_value;
+ ufbx_real max_value;
+
+ // Time range for all the keyframes.
+ double min_time;
+ double max_time;
+};
+
+// -- Collections
+
+// Collection of nodes to hide/freeze
+struct ufbx_display_layer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Nodes included in the layer (exclusively at most one layer per node)
+ ufbx_node_list nodes;
+
+ // Layer state
+ bool visible; // < Contained nodes are visible
+ bool frozen; // < Contained nodes cannot be edited
+
+ ufbx_vec3 ui_color; // < Visual color for UI
+};
+
+// Named set of nodes/geometry features to select.
+struct ufbx_selection_set {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Included nodes and geometry features
+ ufbx_selection_node_list nodes;
+};
+
+// Selection state of a node, potentially contains vertex/edge/face selection as well.
+struct ufbx_selection_node {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Selection targets, possibly `NULL`
+ ufbx_nullable ufbx_node *target_node;
+ ufbx_nullable ufbx_mesh *target_mesh;
+ bool include_node; // < Is `target_node` included in the selection
+
+ // Indices to selected components.
+ // Guaranteed to be valid as per `ufbx_load_opts.index_error_handling`
+ // if `target_mesh` is not `NULL`.
+ ufbx_uint32_list vertices; // < Indices to `ufbx_mesh.vertices`
+ ufbx_uint32_list edges; // < Indices to `ufbx_mesh.edges`
+ ufbx_uint32_list faces; // < Indices to `ufbx_mesh.faces`
+};
+
+// -- Constraints
+
+struct ufbx_character {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+};
+
+// Type of property constrain eg. position or look-at
+typedef enum ufbx_constraint_type UFBX_ENUM_REPR {
+ UFBX_CONSTRAINT_UNKNOWN,
+ UFBX_CONSTRAINT_AIM,
+ UFBX_CONSTRAINT_PARENT,
+ UFBX_CONSTRAINT_POSITION,
+ UFBX_CONSTRAINT_ROTATION,
+ UFBX_CONSTRAINT_SCALE,
+ // Inverse kinematic chain to a single effector `ufbx_constraint.ik_effector`
+ // `targets` optionally contains a list of pole targets!
+ UFBX_CONSTRAINT_SINGLE_CHAIN_IK,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CONSTRAINT_TYPE)
+} ufbx_constraint_type;
+
+UFBX_ENUM_TYPE(ufbx_constraint_type, UFBX_CONSTRAINT_TYPE, UFBX_CONSTRAINT_SINGLE_CHAIN_IK);
+
+// Target to follow with a constraint
+typedef struct ufbx_constraint_target {
+ ufbx_node *node; // < Target node reference
+ ufbx_real weight; // < Relative weight to other targets (does not always sum to 1)
+ ufbx_transform transform; // < Offset from the actual target
+} ufbx_constraint_target;
+
+UFBX_LIST_TYPE(ufbx_constraint_target_list, ufbx_constraint_target);
+
+// Method to determine the up vector in aim constraints
+typedef enum ufbx_constraint_aim_up_type UFBX_ENUM_REPR {
+ UFBX_CONSTRAINT_AIM_UP_SCENE, // < Align the up vector to the scene global up vector
+ UFBX_CONSTRAINT_AIM_UP_TO_NODE, // < Aim the up vector at `ufbx_constraint.aim_up_node`
+ UFBX_CONSTRAINT_AIM_UP_ALIGN_NODE, // < Copy the up vector from `ufbx_constraint.aim_up_node`
+ UFBX_CONSTRAINT_AIM_UP_VECTOR, // < Use `ufbx_constraint.aim_up_vector` as the up vector
+ UFBX_CONSTRAINT_AIM_UP_NONE, // < Don't align the up vector to anything
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CONSTRAINT_AIM_UP_TYPE)
+} ufbx_constraint_aim_up_type;
+
+UFBX_ENUM_TYPE(ufbx_constraint_aim_up_type, UFBX_CONSTRAINT_AIM_UP_TYPE, UFBX_CONSTRAINT_AIM_UP_NONE);
+
+// Method to determine the up vector in aim constraints
+typedef enum ufbx_constraint_ik_pole_type UFBX_ENUM_REPR {
+ UFBX_CONSTRAINT_IK_POLE_VECTOR, // < Use towards calculated from `ufbx_constraint.targets`
+ UFBX_CONSTRAINT_IK_POLE_NODE, // < Use `ufbx_constraint.ik_pole_vector` directly
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_CONSTRAINT_IK_POLE_TYPE)
+} ufbx_constraint_ik_pole_type;
+
+UFBX_ENUM_TYPE(ufbx_constraint_ik_pole_type, UFBX_CONSTRAINT_IK_POLE_TYPE, UFBX_CONSTRAINT_IK_POLE_NODE);
+
+struct ufbx_constraint {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Type of constraint to use
+ ufbx_constraint_type type;
+ ufbx_string type_name;
+
+ // Node to be constrained
+ ufbx_nullable ufbx_node *node;
+
+ // List of weighted targets for the constraint (pole vectors for IK)
+ ufbx_constraint_target_list targets;
+
+ // State of the constraint
+ ufbx_real weight;
+ bool active;
+
+ // Translation/rotation/scale axes the constraint is applied to
+ bool constrain_translation[3];
+ bool constrain_rotation[3];
+ bool constrain_scale[3];
+
+ // Offset from the constrained position
+ ufbx_transform transform_offset;
+
+ // AIM: Target and up vectors
+ ufbx_vec3 aim_vector;
+ ufbx_constraint_aim_up_type aim_up_type;
+ ufbx_nullable ufbx_node *aim_up_node;
+ ufbx_vec3 aim_up_vector;
+
+ // SINGLE_CHAIN_IK: Target for the IK, `targets` contains pole vectors!
+ ufbx_nullable ufbx_node *ik_effector;
+ ufbx_nullable ufbx_node *ik_end_node;
+ ufbx_vec3 ik_pole_vector;
+};
+
+// -- Audio
+
+struct ufbx_audio_layer {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Clips contained in this layer.
+ ufbx_audio_clip_list clips;
+};
+
+struct ufbx_audio_clip {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Filename relative to the currently loaded file.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_string filename;
+ // Absolute filename specified in the file.
+ ufbx_string absolute_filename;
+ // Relative filename specified in the file.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_string relative_filename;
+
+ // Filename relative to the loaded file, non-UTF-8 encoded.
+ // HINT: If using functions other than `ufbx_load_file()`, you can provide
+ // `ufbx_load_opts.filename/raw_filename` to let ufbx resolve this.
+ ufbx_blob raw_filename;
+ // Absolute filename specified in the file, non-UTF-8 encoded.
+ ufbx_blob raw_absolute_filename;
+ // Relative filename specified in the file, non-UTF-8 encoded.
+ // NOTE: May be absolute if the file is saved in a different drive.
+ ufbx_blob raw_relative_filename;
+
+ // Optional embedded content blob, eg. raw .png format data
+ ufbx_blob content;
+};
+
+// -- Miscellaneous
+
+typedef struct ufbx_bone_pose {
+
+ // Node to apply the pose to.
+ ufbx_node *bone_node;
+
+ // Matrix from node local space to world space.
+ ufbx_matrix bone_to_world;
+
+ // Matrix from node local space to parent space.
+ // NOTE: FBX only stores world transformations so this is approximated from
+ // the parent world transform.
+ ufbx_matrix bone_to_parent;
+
+} ufbx_bone_pose;
+
+UFBX_LIST_TYPE(ufbx_bone_pose_list, ufbx_bone_pose);
+
+struct ufbx_pose {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+
+ // Set if this pose is marked as a bind pose.
+ bool is_bind_pose;
+
+ // List of bone poses.
+ // Sorted by `ufbx_node.typed_id`.
+ ufbx_bone_pose_list bone_poses;
+};
+
+struct ufbx_metadata_object {
+ union { ufbx_element element; struct {
+ ufbx_string name;
+ ufbx_props props;
+ uint32_t element_id;
+ uint32_t typed_id;
+ }; };
+};
+
+// -- Named elements
+
+typedef struct ufbx_name_element {
+ ufbx_string name;
+ ufbx_element_type type;
+
+ uint32_t _internal_key;
+
+ ufbx_element *element;
+} ufbx_name_element;
+
+UFBX_LIST_TYPE(ufbx_name_element_list, ufbx_name_element);
+
+// -- Scene
+
+// Scene is the root object loaded by ufbx that everything is accessed from.
+
+typedef enum ufbx_exporter UFBX_ENUM_REPR {
+ UFBX_EXPORTER_UNKNOWN,
+ UFBX_EXPORTER_FBX_SDK,
+ UFBX_EXPORTER_BLENDER_BINARY,
+ UFBX_EXPORTER_BLENDER_ASCII,
+ UFBX_EXPORTER_MOTION_BUILDER,
+ UFBX_EXPORTER_UFBX_WRITE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_EXPORTER)
+} ufbx_exporter;
+
+UFBX_ENUM_TYPE(ufbx_exporter, UFBX_EXPORTER, UFBX_EXPORTER_UFBX_WRITE);
+
+typedef struct ufbx_application {
+ ufbx_string vendor;
+ ufbx_string name;
+ ufbx_string version;
+} ufbx_application;
+
+typedef enum ufbx_file_format UFBX_ENUM_REPR {
+ UFBX_FILE_FORMAT_UNKNOWN, // < Unknown file format
+ UFBX_FILE_FORMAT_FBX, // < .fbx Kaydara/Autodesk FBX file
+ UFBX_FILE_FORMAT_OBJ, // < .obj Wavefront OBJ file
+ UFBX_FILE_FORMAT_MTL, // < .mtl Wavefront MTL (Material template library) file
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_FILE_FORMAT)
+} ufbx_file_format;
+
+UFBX_ENUM_TYPE(ufbx_file_format, UFBX_FILE_FORMAT, UFBX_FILE_FORMAT_MTL);
+
+typedef enum ufbx_warning_type UFBX_ENUM_REPR {
+ // Missing external file file (for example .mtl for Wavefront .obj file or a
+ // geometry cache)
+ UFBX_WARNING_MISSING_EXTERNAL_FILE,
+
+ // Loaded a Wavefront .mtl file derived from the filename instead of a proper
+ // `mtllib` statement.
+ UFBX_WARNING_IMPLICIT_MTL,
+
+ // Truncated array has been auto-expanded.
+ UFBX_WARNING_TRUNCATED_ARRAY,
+
+ // Geometry data has been defined but has no data.
+ UFBX_WARNING_MISSING_GEOMETRY_DATA,
+
+ // Duplicated connection between two elements that shouldn't have.
+ UFBX_WARNING_DUPLICATE_CONNECTION,
+
+ // Vertex 'W' attribute length differs from main attribute.
+ UFBX_WARNING_BAD_VERTEX_W_ATTRIBUTE,
+
+ // Missing polygon mapping type.
+ UFBX_WARNING_MISSING_POLYGON_MAPPING,
+
+ // Unsupported version, loaded but may be incorrect.
+ // If the loading fails `UFBX_ERROR_UNSUPPORTED_VERSION` is issued instead.
+ UFBX_WARNING_UNSUPPORTED_VERSION,
+
+ // Out-of-bounds index has been clamped to be in-bounds.
+ // HINT: You can use `ufbx_index_error_handling` to adjust behavior.
+ UFBX_WARNING_INDEX_CLAMPED,
+
+ // Non-UTF8 encoded strings.
+ // HINT: You can use `ufbx_unicode_error_handling` to adjust behavior.
+ UFBX_WARNING_BAD_UNICODE,
+
+ // Invalid base64-encoded embedded content ignored.
+ UFBX_WARNING_BAD_BASE64_CONTENT,
+
+ // Non-node element connected to root.
+ UFBX_WARNING_BAD_ELEMENT_CONNECTED_TO_ROOT,
+
+ // Duplicated object ID in the file, connections will be wrong.
+ UFBX_WARNING_DUPLICATE_OBJECT_ID,
+
+ // Empty face has been removed.
+ // Use `ufbx_load_opts.allow_empty_faces` if you want to allow them.
+ UFBX_WARNING_EMPTY_FACE_REMOVED,
+
+ // Unknown .obj file directive.
+ UFBX_WARNING_UNKNOWN_OBJ_DIRECTIVE,
+
+ // Warnings after this one are deduplicated.
+ // See `ufbx_warning.count` for how many times they happened.
+ UFBX_WARNING_TYPE_FIRST_DEDUPLICATED = UFBX_WARNING_INDEX_CLAMPED,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_WARNING_TYPE)
+} ufbx_warning_type;
+
+UFBX_ENUM_TYPE(ufbx_warning_type, UFBX_WARNING_TYPE, UFBX_WARNING_UNKNOWN_OBJ_DIRECTIVE);
+
+// Warning about a non-fatal issue in the file.
+// Often contains information about issues that ufbx has corrected about the
+// file but it might indicate something is not working properly.
+typedef struct ufbx_warning {
+ // Type of the warning.
+ ufbx_warning_type type;
+ // Description of the warning.
+ ufbx_string description;
+ // The element related to this warning or `UFBX_NO_INDEX` if not related to a specific element.
+ uint32_t element_id;
+ // Number of times this warning was encountered.
+ size_t count;
+} ufbx_warning;
+
+UFBX_LIST_TYPE(ufbx_warning_list, ufbx_warning);
+
+typedef enum ufbx_thumbnail_format UFBX_ENUM_REPR {
+ UFBX_THUMBNAIL_FORMAT_UNKNOWN, // < Unknown format
+ UFBX_THUMBNAIL_FORMAT_RGB_24, // < 8-bit RGB pixels, in memory R,G,B
+ UFBX_THUMBNAIL_FORMAT_RGBA_32, // < 8-bit RGBA pixels, in memory R,G,B,A
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_THUMBNAIL_FORMAT)
+} ufbx_thumbnail_format;
+
+UFBX_ENUM_TYPE(ufbx_thumbnail_format, UFBX_THUMBNAIL_FORMAT, UFBX_THUMBNAIL_FORMAT_RGBA_32);
+
+// Specify how unit / coordinate system conversion should be performed.
+// Affects how `ufbx_load_opts.target_axes` and `ufbx_load_opts.target_unit_meters` work,
+// has no effect if neither is specified.
+typedef enum ufbx_space_conversion UFBX_ENUM_REPR {
+
+ // Store the space conversion transform in the root node.
+ // Sets `ufbx_node.local_transform` of the root node.
+ UFBX_SPACE_CONVERSION_TRANSFORM_ROOT,
+
+ // Perform the conversion by using "adjust" transforms.
+ // Compensates for the transforms using `ufbx_node.adjust_pre_rotation` and
+ // `ufbx_node.adjust_pre_scale`. You don't need to account for these unless
+ // you are manually building transforms from `ufbx_props`.
+ UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS,
+
+ // Perform the conversion by scaling geometry in addition to adjusting transforms.
+ // Compensates transforms like `UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS` but
+ // applies scaling to geometry as well.
+ UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SPACE_CONVERSION)
+} ufbx_space_conversion;
+
+UFBX_ENUM_TYPE(ufbx_space_conversion, UFBX_SPACE_CONVERSION, UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY);
+
+// How to handle FBX node geometry transforms.
+// FBX nodes can have "geometry transforms" that affect only the attached meshes,
+// but not the children. This is not allowed in many scene representations so
+// ufbx provides some ways to simplify them.
+// Geometry transforms can also be used to transform any other attributes such
+// as lights or cameras.
+typedef enum ufbx_geometry_transform_handling UFBX_ENUM_REPR {
+
+ // Preserve the geometry transforms as-is.
+ // To be correct for all files you have to use `ufbx_node.geometry_transform`,
+ // `ufbx_node.geometry_to_node`, or `ufbx_node.geometry_to_world` to compensate
+ // for any potential geometry transforms.
+ UFBX_GEOMETRY_TRANSFORM_HANDLING_PRESERVE,
+
+ // Add helper nodes between the nodes and geometry where needed.
+ // The created nodes have `ufbx_node.is_geometry_transform_helper` set and are
+ // named `ufbx_load_opts.geometry_transform_helper_name`.
+ UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES,
+
+ // Modify the geometry of meshes attached to nodes with geometry transforms.
+ // Will add helper nodes like `UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES` if
+ // necessary, for example if there are multiple instances of the same mesh with
+ // geometry transforms.
+ UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY,
+
+ // Modify the geometry of meshes attached to nodes with geometry transforms.
+ // NOTE: This will not work correctly for instanced geometry.
+ UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_GEOMETRY_TRANSFORM_HANDLING)
+} ufbx_geometry_transform_handling;
+
+UFBX_ENUM_TYPE(ufbx_geometry_transform_handling, UFBX_GEOMETRY_TRANSFORM_HANDLING, UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK);
+
+// How to handle FBX transform inherit modes.
+typedef enum ufbx_inherit_mode_handling UFBX_ENUM_REPR {
+
+ // Preserve inherit mode in `ufbx_node.inherit_mode`.
+ // NOTE: To correctly handle all scenes you would need to handle the
+ // non-standard inherit modes.
+ UFBX_INHERIT_MODE_HANDLING_PRESERVE,
+
+ // Create scale helper nodes parented to nodes that need special inheritance.
+ // Scale helper nodes will have `ufbx_node.is_scale_helper` and parents of
+ // scale helpers will have `ufbx_node.scale_helper` pointing to it.
+ UFBX_INHERIT_MODE_HANDLING_HELPER_NODES,
+
+ // Attempt to compensate for bone scale by inversely scaling children.
+ // NOTE: This only works for uniform non-animated scaling, if scale is
+ // non-uniform or animated, ufbx will add scale helpers in the same way
+ // as `UFBX_INHERIT_MODE_HANDLING_HELPER_NODES`.
+ UFBX_INHERIT_MODE_HANDLING_COMPENSATE,
+
+ // Attempt to compensate for bone scale by inversely scaling children.
+ // Will never create helper nodes.
+ UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK,
+
+ // Ignore non-standard inheritance modes.
+ // Forces all nodes to have `UFBX_INHERIT_MODE_NORMAL` regardless of the
+ // inherit mode specified in the file. This can be useful for emulating
+ // results from importers/programs that don't support inherit modes.
+ UFBX_INHERIT_MODE_HANDLING_IGNORE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_INHERIT_MODE_HANDLING)
+} ufbx_inherit_mode_handling;
+
+UFBX_ENUM_TYPE(ufbx_inherit_mode_handling, UFBX_INHERIT_MODE_HANDLING, UFBX_INHERIT_MODE_HANDLING_IGNORE);
+
+// How to handle FBX transform pivots.
+typedef enum ufbx_pivot_handling UFBX_ENUM_REPR {
+
+ // Take pivots into account when computing the transform.
+ UFBX_PIVOT_HANDLING_RETAIN,
+
+ // Translate objects to be located at their pivot.
+ // NOTE: Only applied if rotation and scaling pivots are equal.
+ // NOTE: Results in geometric translation. Use `ufbx_geometry_transform_handling`
+ // to interpret these in a standard scene graph.
+ UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT,
+
+ // Translate objects to be located at their rotation pivot.
+ // NOTE: Results in geometric translation. Use `ufbx_geometry_transform_handling`
+ // to interpret these in a standard scene graph.
+ // NOTE: By default the original transforms of empties are not retained when using this,
+ // use `ufbx_load_opts.pivot_handling_retain_empties` to prevent adjusting these pivots.
+ UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_PIVOT_HANDLING)
+} ufbx_pivot_handling;
+
+UFBX_ENUM_TYPE(ufbx_pivot_handling, UFBX_PIVOT_HANDLING, UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT);
+
+// Embedded thumbnail in the file, valid if the dimensions are non-zero.
+typedef struct ufbx_thumbnail {
+ ufbx_props props;
+
+ // Extents of the thumbnail
+ uint32_t width;
+ uint32_t height;
+
+ // Format of `ufbx_thumbnail.data`.
+ ufbx_thumbnail_format format;
+
+ // Thumbnail pixel data, layout as contiguous rows from bottom to top.
+ // See `ufbx_thumbnail.format` for the pixel format.
+ ufbx_blob data;
+} ufbx_thumbnail;
+
+// Miscellaneous data related to the loaded file
+typedef struct ufbx_metadata {
+
+ // List of non-fatal warnings about the file.
+ // If you need to only check whether a specific warning was triggered you
+ // can use `ufbx_metadata.has_warning[]`.
+ ufbx_warning_list warnings;
+
+ // FBX ASCII file format.
+ bool ascii;
+
+ // FBX version in integer format, eg. 7400 for 7.4.
+ uint32_t version;
+
+ // File format of the source file.
+ ufbx_file_format file_format;
+
+ // Index arrays may contain `UFBX_NO_INDEX` instead of a valid index
+ // to indicate gaps.
+ bool may_contain_no_index;
+
+ // May contain meshes with no defined vertex position.
+ // NOTE: `ufbx_mesh.vertex_position.exists` may be `false`!
+ bool may_contain_missing_vertex_position;
+
+ // Arrays may contain items with `NULL` element references.
+ // See `ufbx_load_opts.connect_broken_elements`.
+ bool may_contain_broken_elements;
+
+ // Some API guarantees do not apply (depending on unsafe options used).
+ // Loaded with `ufbx_load_opts.allow_unsafe` enabled.
+ bool is_unsafe;
+
+ // Flag for each possible warning type.
+ // See `ufbx_metadata.warnings[]` for detailed warning information.
+ bool has_warning[UFBX_WARNING_TYPE_COUNT];
+
+ ufbx_string creator;
+ bool big_endian;
+
+ ufbx_string filename;
+ ufbx_string relative_root;
+
+ ufbx_blob raw_filename;
+ ufbx_blob raw_relative_root;
+
+ ufbx_exporter exporter;
+ uint32_t exporter_version;
+
+ ufbx_props scene_props;
+
+ ufbx_application original_application;
+ ufbx_application latest_application;
+
+ ufbx_thumbnail thumbnail;
+
+ bool geometry_ignored;
+ bool animation_ignored;
+ bool embedded_ignored;
+
+ size_t max_face_triangles;
+
+ size_t result_memory_used;
+ size_t temp_memory_used;
+ size_t result_allocs;
+ size_t temp_allocs;
+
+ size_t element_buffer_size;
+ size_t num_shader_textures;
+
+ ufbx_real bone_prop_size_unit;
+ bool bone_prop_limb_length_relative;
+
+ ufbx_real ortho_size_unit;
+
+ int64_t ktime_second; // < One second in internal KTime units
+
+ ufbx_string original_file_path;
+ ufbx_blob raw_original_file_path;
+
+ // Conversion methods applied for the scene.
+ ufbx_space_conversion space_conversion;
+ ufbx_geometry_transform_handling geometry_transform_handling;
+ ufbx_inherit_mode_handling inherit_mode_handling;
+ ufbx_pivot_handling pivot_handling;
+ ufbx_mirror_axis handedness_conversion_axis;
+
+ // Transform that has been applied to root for axis/unit conversion.
+ ufbx_quat root_rotation;
+ ufbx_real root_scale;
+
+ // Axis that the scene has been mirrored by.
+ // All geometry has been mirrored in this axis.
+ ufbx_mirror_axis mirror_axis;
+
+ // Amount geometry has been scaled.
+ // See `UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY`.
+ ufbx_real geometry_scale;
+
+} ufbx_metadata;
+
+typedef enum ufbx_time_mode UFBX_ENUM_REPR {
+ UFBX_TIME_MODE_DEFAULT,
+ UFBX_TIME_MODE_120_FPS,
+ UFBX_TIME_MODE_100_FPS,
+ UFBX_TIME_MODE_60_FPS,
+ UFBX_TIME_MODE_50_FPS,
+ UFBX_TIME_MODE_48_FPS,
+ UFBX_TIME_MODE_30_FPS,
+ UFBX_TIME_MODE_30_FPS_DROP,
+ UFBX_TIME_MODE_NTSC_DROP_FRAME,
+ UFBX_TIME_MODE_NTSC_FULL_FRAME,
+ UFBX_TIME_MODE_PAL,
+ UFBX_TIME_MODE_24_FPS,
+ UFBX_TIME_MODE_1000_FPS,
+ UFBX_TIME_MODE_FILM_FULL_FRAME,
+ UFBX_TIME_MODE_CUSTOM,
+ UFBX_TIME_MODE_96_FPS,
+ UFBX_TIME_MODE_72_FPS,
+ UFBX_TIME_MODE_59_94_FPS,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_TIME_MODE)
+} ufbx_time_mode;
+
+UFBX_ENUM_TYPE(ufbx_time_mode, UFBX_TIME_MODE, UFBX_TIME_MODE_59_94_FPS);
+
+typedef enum ufbx_time_protocol UFBX_ENUM_REPR {
+ UFBX_TIME_PROTOCOL_SMPTE,
+ UFBX_TIME_PROTOCOL_FRAME_COUNT,
+ UFBX_TIME_PROTOCOL_DEFAULT,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_TIME_PROTOCOL)
+} ufbx_time_protocol;
+
+UFBX_ENUM_TYPE(ufbx_time_protocol, UFBX_TIME_PROTOCOL, UFBX_TIME_PROTOCOL_DEFAULT);
+
+typedef enum ufbx_snap_mode UFBX_ENUM_REPR {
+ UFBX_SNAP_MODE_NONE,
+ UFBX_SNAP_MODE_SNAP,
+ UFBX_SNAP_MODE_PLAY,
+ UFBX_SNAP_MODE_SNAP_AND_PLAY,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_SNAP_MODE)
+} ufbx_snap_mode;
+
+UFBX_ENUM_TYPE(ufbx_snap_mode, UFBX_SNAP_MODE, UFBX_SNAP_MODE_SNAP_AND_PLAY);
+
+// Global settings: Axes and time/unit scales
+typedef struct ufbx_scene_settings {
+ ufbx_props props;
+
+ // Mapping of X/Y/Z axes to world-space directions.
+ // HINT: Use `ufbx_load_opts.target_axes` to normalize this.
+ // NOTE: This contains the _original_ axes even if you supply `ufbx_load_opts.target_axes`.
+ ufbx_coordinate_axes axes;
+
+ // How many meters does a single world-space unit represent.
+ // FBX files usually default to centimeters, reported as `0.01` here.
+ // HINT: Use `ufbx_load_opts.target_unit_meters` to normalize this.
+ ufbx_real unit_meters;
+
+ // Frames per second the animation is defined at.
+ double frames_per_second;
+
+ ufbx_vec3 ambient_color;
+ ufbx_string default_camera;
+
+ // Animation user interface settings.
+ // HINT: Use `ufbx_scene_settings.frames_per_second` instead of interpreting these yourself.
+ ufbx_time_mode time_mode;
+ ufbx_time_protocol time_protocol;
+ ufbx_snap_mode snap_mode;
+
+ // Original `axes.up` value for the scene.
+ // NOTE: This may be `UFBX_COORDINATE_AXIS_UNKNOWN` if not specified in the file.
+ ufbx_coordinate_axis original_axis_up;
+
+ // Original `unit_meters` value for the scene.
+ ufbx_real original_unit_meters;
+
+} ufbx_scene_settings;
+
+struct ufbx_scene {
+ ufbx_metadata metadata;
+
+ // Global settings
+ ufbx_scene_settings settings;
+
+ // Node instances in the scene
+ ufbx_node *root_node;
+
+ // Default animation descriptor
+ ufbx_anim *anim;
+
+ union {
+ struct {
+ ufbx_unknown_list unknowns;
+
+ // Nodes
+ ufbx_node_list nodes;
+
+ // Node attributes (common)
+ ufbx_mesh_list meshes;
+ ufbx_light_list lights;
+ ufbx_camera_list cameras;
+ ufbx_bone_list bones;
+ ufbx_empty_list empties;
+
+ // Node attributes (curves/surfaces)
+ ufbx_line_curve_list line_curves;
+ ufbx_nurbs_curve_list nurbs_curves;
+ ufbx_nurbs_surface_list nurbs_surfaces;
+ ufbx_nurbs_trim_surface_list nurbs_trim_surfaces;
+ ufbx_nurbs_trim_boundary_list nurbs_trim_boundaries;
+
+ // Node attributes (advanced)
+ ufbx_procedural_geometry_list procedural_geometries;
+ ufbx_stereo_camera_list stereo_cameras;
+ ufbx_camera_switcher_list camera_switchers;
+ ufbx_marker_list markers;
+ ufbx_lod_group_list lod_groups;
+
+ // Deformers
+ ufbx_skin_deformer_list skin_deformers;
+ ufbx_skin_cluster_list skin_clusters;
+ ufbx_blend_deformer_list blend_deformers;
+ ufbx_blend_channel_list blend_channels;
+ ufbx_blend_shape_list blend_shapes;
+ ufbx_cache_deformer_list cache_deformers;
+ ufbx_cache_file_list cache_files;
+
+ // Materials
+ ufbx_material_list materials;
+ ufbx_texture_list textures;
+ ufbx_video_list videos;
+ ufbx_shader_list shaders;
+ ufbx_shader_binding_list shader_bindings;
+
+ // Animation
+ ufbx_anim_stack_list anim_stacks;
+ ufbx_anim_layer_list anim_layers;
+ ufbx_anim_value_list anim_values;
+ ufbx_anim_curve_list anim_curves;
+
+ // Collections
+ ufbx_display_layer_list display_layers;
+ ufbx_selection_set_list selection_sets;
+ ufbx_selection_node_list selection_nodes;
+
+ // Constraints
+ ufbx_character_list characters;
+ ufbx_constraint_list constraints;
+
+ // Audio
+ ufbx_audio_layer_list audio_layers;
+ ufbx_audio_clip_list audio_clips;
+
+ // Miscellaneous
+ ufbx_pose_list poses;
+ ufbx_metadata_object_list metadata_objects;
+ };
+
+ ufbx_element_list elements_by_type[UFBX_ELEMENT_TYPE_COUNT];
+ };
+
+ // Unique texture files referenced by the scene.
+ ufbx_texture_file_list texture_files;
+
+ // All elements and connections in the whole file
+ ufbx_element_list elements; // < Sorted by `id`
+ ufbx_connection_list connections_src; // < Sorted by `src,src_prop`
+ ufbx_connection_list connections_dst; // < Sorted by `dst,dst_prop`
+
+ // Elements sorted by name, type
+ ufbx_name_element_list elements_by_name;
+
+ // Enabled if `ufbx_load_opts.retain_dom == true`.
+ ufbx_nullable ufbx_dom_node *dom_root;
+};
+
+// -- Curves
+
+typedef struct ufbx_curve_point {
+ bool valid;
+ ufbx_vec3 position;
+ ufbx_vec3 derivative;
+} ufbx_curve_point;
+
+typedef struct ufbx_surface_point {
+ bool valid;
+ ufbx_vec3 position;
+ ufbx_vec3 derivative_u;
+ ufbx_vec3 derivative_v;
+} ufbx_surface_point;
+
+// -- Mesh topology
+
+typedef enum ufbx_topo_flags UFBX_FLAG_REPR {
+ UFBX_TOPO_NON_MANIFOLD = 0x1, // < Edge with three or more faces
+
+ UFBX_FLAG_FORCE_WIDTH(UFBX_TOPO_FLAGS)
+} ufbx_topo_flags;
+
+typedef struct ufbx_topo_edge {
+ uint32_t index; // < Starting index of the edge, always defined
+ uint32_t next; // < Ending index of the edge / next per-face `ufbx_topo_edge`, always defined
+ uint32_t prev; // < Previous per-face `ufbx_topo_edge`, always defined
+ uint32_t twin; // < `ufbx_topo_edge` on the opposite side, `UFBX_NO_INDEX` if not found
+ uint32_t face; // < Index into `mesh->faces[]`, always defined
+ uint32_t edge; // < Index into `mesh->edges[]`, `UFBX_NO_INDEX` if not found
+
+ ufbx_topo_flags flags;
+} ufbx_topo_edge;
+
+// Vertex data array for `ufbx_generate_indices()`.
+// NOTE: `ufbx_generate_indices()` compares the vertices using `memcmp()`, so
+// any padding should be cleared to zero.
+typedef struct ufbx_vertex_stream {
+ void *data; // < Data pointer of shape `char[vertex_count][vertex_size]`.
+ size_t vertex_count; // < Number of vertices in this stream, for sanity checking.
+ size_t vertex_size; // < Size of a vertex in bytes.
+} ufbx_vertex_stream;
+
+// -- Memory callbacks
+
+// You can optionally provide an allocator to ufbx, the default is to use the
+// CRT malloc/realloc/free
+
+// Allocate `size` bytes, must be at least 8 byte aligned
+typedef void *ufbx_alloc_fn(void *user, size_t size);
+
+// Reallocate `old_ptr` from `old_size` to `new_size`
+// NOTE: If omit `alloc_fn` and `free_fn` they will be translated to:
+// `alloc(size)` -> `realloc_fn(user, NULL, 0, size)`
+// `free_fn(ptr, size)` -> `realloc_fn(user, ptr, size, 0)`
+typedef void *ufbx_realloc_fn(void *user, void *old_ptr, size_t old_size, size_t new_size);
+
+// Free pointer `ptr` (of `size` bytes) returned by `alloc_fn` or `realloc_fn`
+typedef void ufbx_free_fn(void *user, void *ptr, size_t size);
+
+// Free the allocator itself
+typedef void ufbx_free_allocator_fn(void *user);
+
+// Allocator callbacks and user context
+// NOTE: The allocator will be stored to the loaded scene and will be called
+// again from `ufbx_free_scene()` so make sure `user` outlives that!
+// You can use `free_allocator_fn()` to free the allocator yourself.
+typedef struct ufbx_allocator {
+ // Callback functions, see `typedef`s above for information
+ ufbx_alloc_fn *alloc_fn;
+ ufbx_realloc_fn *realloc_fn;
+ ufbx_free_fn *free_fn;
+ ufbx_free_allocator_fn *free_allocator_fn;
+ void *user;
+} ufbx_allocator;
+
+typedef struct ufbx_allocator_opts {
+ // Allocator callbacks
+ ufbx_allocator allocator;
+
+ // Maximum number of bytes to allocate before failing
+ size_t memory_limit;
+
+ // Maximum number of allocations to attempt before failing
+ size_t allocation_limit;
+
+ // Threshold to swap from batched allocations to individual ones
+ // Defaults to 1MB if set to zero
+ // NOTE: If set to `1` ufbx will allocate everything in the smallest
+ // possible chunks which may be useful for debugging (eg. ASAN)
+ size_t huge_threshold;
+
+ // Maximum size of a single allocation containing sub-allocations.
+ // Defaults to 16MB if set to zero
+ // The maximum amount of wasted memory depends on `max_chunk_size` and
+ // `huge_threshold`: each chunk can waste up to `huge_threshold` bytes
+ // internally and the last chunk might be incomplete. So for example
+ // with the defaults we can waste around 1MB/16MB = 6.25% overall plus
+ // up to 32MB due to the two incomplete blocks. The actual amounts differ
+ // slightly as the chunks start out at 4kB and double in size each time,
+ // meaning that the maximum fixed overhead (up to 32MB with defaults) is
+ // at most ~30% of the total allocation size.
+ size_t max_chunk_size;
+
+} ufbx_allocator_opts;
+
+// -- IO callbacks
+
+// Try to read up to `size` bytes to `data`, return the amount of read bytes.
+// Return `SIZE_MAX` to indicate an IO error.
+typedef size_t ufbx_read_fn(void *user, void *data, size_t size);
+
+// Skip `size` bytes in the file.
+typedef bool ufbx_skip_fn(void *user, size_t size);
+
+// Get the size of the file.
+// Return `0` if unknown, `UINT64_MAX` if error.
+typedef uint64_t ufbx_size_fn(void *user);
+
+// Close the file
+typedef void ufbx_close_fn(void *user);
+
+typedef struct ufbx_stream {
+ ufbx_read_fn *read_fn; // < Required
+ ufbx_skip_fn *skip_fn; // < Optional: Will use `read_fn()` if missing
+ ufbx_size_fn *size_fn; // < Optional
+ ufbx_close_fn *close_fn; // < Optional
+
+ // Context passed to other functions
+ void *user;
+} ufbx_stream;
+
+typedef enum ufbx_open_file_type UFBX_ENUM_REPR {
+ UFBX_OPEN_FILE_MAIN_MODEL, // < Main model file
+ UFBX_OPEN_FILE_GEOMETRY_CACHE, // < Unknown geometry cache file
+ UFBX_OPEN_FILE_OBJ_MTL, // < .mtl material library file
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_OPEN_FILE_TYPE)
+} ufbx_open_file_type;
+
+UFBX_ENUM_TYPE(ufbx_open_file_type, UFBX_OPEN_FILE_TYPE, UFBX_OPEN_FILE_OBJ_MTL);
+
+typedef uintptr_t ufbx_open_file_context;
+
+typedef struct ufbx_open_file_info {
+ // Context that can be passed to the following functions to use a shared allocator:
+ // ufbx_open_file_ctx()
+ // ufbx_open_memory_ctx()
+ ufbx_open_file_context context;
+
+ // Kind of file to load.
+ ufbx_open_file_type type;
+
+ // Original filename in the file, not resolved or UTF-8 encoded.
+ // NOTE: Not necessarily NULL-terminated!
+ ufbx_blob original_filename;
+} ufbx_open_file_info;
+
+// Callback for opening an external file from the filesystem
+typedef bool ufbx_open_file_fn(void *user, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_info *info);
+
+typedef struct ufbx_open_file_cb {
+ ufbx_open_file_fn *fn;
+ void *user;
+
+ UFBX_CALLBACK_IMPL(ufbx_open_file_cb, ufbx_open_file_fn, bool,
+ (void *user, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_info *info),
+ (stream, path, path_len, info))
+} ufbx_open_file_cb;
+
+// Options for `ufbx_open_file()`.
+typedef struct ufbx_open_file_opts {
+ uint32_t _begin_zero;
+
+ // Allocator to allocate the memory with.
+ ufbx_allocator_opts allocator;
+
+ // The filename is guaranteed to be NULL-terminated.
+ ufbx_unsafe bool filename_null_terminated;
+
+ uint32_t _end_zero;
+} ufbx_open_file_opts;
+
+// Memory stream options
+typedef void ufbx_close_memory_fn(void *user, void *data, size_t data_size);
+
+typedef struct ufbx_close_memory_cb {
+ ufbx_close_memory_fn *fn;
+ void *user;
+
+ UFBX_CALLBACK_IMPL(ufbx_close_memory_cb, ufbx_close_memory_fn, void,
+ (void *user, void *data, size_t data_size),
+ (data, data_size))
+} ufbx_close_memory_cb;
+
+// Options for `ufbx_open_memory()`.
+typedef struct ufbx_open_memory_opts {
+ uint32_t _begin_zero;
+
+ // Allocator to allocate the memory with.
+ // NOTE: Used even if no copy is made to allocate a small metadata block.
+ ufbx_allocator_opts allocator;
+
+ // Do not copy the memory.
+ // You can use `close_cb` to free the memory when the stream is closed.
+ // NOTE: This means the provided data pointer is referenced after creating
+ // the memory stream, make sure the data stays valid until the stream is closed!
+ ufbx_unsafe bool no_copy;
+
+ // Callback to free the memory blob.
+ ufbx_close_memory_cb close_cb;
+
+ uint32_t _end_zero;
+} ufbx_open_memory_opts;
+
+// Detailed error stack frame.
+// NOTE: You must compile `ufbx.c` with `UFBX_ENABLE_ERROR_STACK` to enable the error stack.
+typedef struct ufbx_error_frame {
+ uint32_t source_line;
+ ufbx_string function;
+ ufbx_string description;
+} ufbx_error_frame;
+
+// Error causes (and `UFBX_ERROR_NONE` for no error).
+typedef enum ufbx_error_type UFBX_ENUM_REPR {
+
+ // No error, operation has been performed successfully.
+ UFBX_ERROR_NONE,
+
+ // Unspecified error, most likely caused by an invalid FBX file or a file
+ // that contains something ufbx can't handle.
+ UFBX_ERROR_UNKNOWN,
+
+ // File not found.
+ UFBX_ERROR_FILE_NOT_FOUND,
+
+ // Empty file.
+ UFBX_ERROR_EMPTY_FILE,
+
+ // External file not found.
+ // See `ufbx_load_opts.load_external_files` for more information.
+ UFBX_ERROR_EXTERNAL_FILE_NOT_FOUND,
+
+ // Out of memory (allocator returned `NULL`).
+ UFBX_ERROR_OUT_OF_MEMORY,
+
+ // `ufbx_allocator_opts.memory_limit` exhausted.
+ UFBX_ERROR_MEMORY_LIMIT,
+
+ // `ufbx_allocator_opts.allocation_limit` exhausted.
+ UFBX_ERROR_ALLOCATION_LIMIT,
+
+ // File ended abruptly.
+ UFBX_ERROR_TRUNCATED_FILE,
+
+ // IO read error.
+ // eg. returning `SIZE_MAX` from `ufbx_stream.read_fn` or stdio `ferror()` condition.
+ UFBX_ERROR_IO,
+
+ // User cancelled the loading via `ufbx_load_opts.progress_cb` returning `UFBX_PROGRESS_CANCEL`.
+ UFBX_ERROR_CANCELLED,
+
+ // Could not detect file format from file data or filename.
+ // HINT: You can supply it manually using `ufbx_load_opts.file_format` or use `ufbx_load_opts.filename`
+ // when using `ufbx_load_memory()` to let ufbx guess the format from the extension.
+ UFBX_ERROR_UNRECOGNIZED_FILE_FORMAT,
+
+ // Options struct (eg. `ufbx_load_opts`) is not cleared to zero.
+ // Make sure you initialize the structure to zero via eg.
+ // ufbx_load_opts opts = { 0 }; // C
+ // ufbx_load_opts opts = { }; // C++
+ UFBX_ERROR_UNINITIALIZED_OPTIONS,
+
+ // The vertex streams in `ufbx_generate_indices()` are empty.
+ UFBX_ERROR_ZERO_VERTEX_SIZE,
+
+ // Vertex stream passed to `ufbx_generate_indices()`.
+ UFBX_ERROR_TRUNCATED_VERTEX_STREAM,
+
+ // Invalid UTF-8 encountered in a file when loading with `UFBX_UNICODE_ERROR_HANDLING_ABORT_LOADING`.
+ UFBX_ERROR_INVALID_UTF8,
+
+ // Feature needed for the operation has been compiled out.
+ UFBX_ERROR_FEATURE_DISABLED,
+
+ // Attempting to tessellate an invalid NURBS object.
+ // See `ufbx_nurbs_basis.valid`.
+ UFBX_ERROR_BAD_NURBS,
+
+ // Out of bounds index in the file when loading with `UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING`.
+ UFBX_ERROR_BAD_INDEX,
+
+ // Node is deeper than `ufbx_load_opts.node_depth_limit` in the hierarchy.
+ UFBX_ERROR_NODE_DEPTH_LIMIT,
+
+ // Error parsing ASCII array in a thread.
+ // Threaded ASCII parsing is slightly more strict than non-threaded, for cursed files,
+ // set `ufbx_load_opts.force_single_thread_ascii_parsing` to `true`.
+ UFBX_ERROR_THREADED_ASCII_PARSE,
+
+ // Unsafe options specified without enabling `ufbx_load_opts.allow_unsafe`.
+ UFBX_ERROR_UNSAFE_OPTIONS,
+
+ // Duplicated override property in `ufbx_create_anim()`
+ UFBX_ERROR_DUPLICATE_OVERRIDE,
+
+ // Unsupported file format version.
+ // ufbx still tries to load files with unsupported versions, see `UFBX_WARNING_UNSUPPORTED_VERSION`.
+ UFBX_ERROR_UNSUPPORTED_VERSION,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_ERROR_TYPE)
+} ufbx_error_type;
+
+UFBX_ENUM_TYPE(ufbx_error_type, UFBX_ERROR_TYPE, UFBX_ERROR_UNSUPPORTED_VERSION);
+
+// Error description with detailed stack trace
+// HINT: You can use `ufbx_format_error()` for formatting the error
+typedef struct ufbx_error {
+
+ // Type of the error, or `UFBX_ERROR_NONE` if successful.
+ ufbx_error_type type;
+
+ // Description of the error type.
+ ufbx_string description;
+
+ // Internal error stack.
+ // NOTE: You must compile `ufbx.c` with `UFBX_ENABLE_ERROR_STACK` to enable the error stack.
+ uint32_t stack_size;
+ ufbx_error_frame stack[UFBX_ERROR_STACK_MAX_DEPTH];
+
+ // Additional error information, such as missing file filename.
+ // `info` is a NULL-terminated UTF-8 string containing `info_length` bytes, excluding the trailing `'\0'`.
+ size_t info_length;
+ char info[UFBX_ERROR_INFO_LENGTH];
+
+} ufbx_error;
+
+// -- Progress callbacks
+
+// Loading progress information.
+typedef struct ufbx_progress {
+ uint64_t bytes_read;
+ uint64_t bytes_total;
+} ufbx_progress;
+
+// Progress result returned from `ufbx_progress_fn()` callback.
+// Determines whether ufbx should continue or abort the loading.
+typedef enum ufbx_progress_result UFBX_ENUM_REPR {
+
+ // Continue loading the file.
+ UFBX_PROGRESS_CONTINUE = 0x100,
+
+ // Cancel loading and fail with `UFBX_ERROR_CANCELLED`.
+ UFBX_PROGRESS_CANCEL = 0x200,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_PROGRESS_RESULT)
+} ufbx_progress_result;
+
+// Called periodically with the current progress.
+// Return `UFBX_PROGRESS_CANCEL` to cancel further processing.
+typedef ufbx_progress_result ufbx_progress_fn(void *user, const ufbx_progress *progress);
+
+typedef struct ufbx_progress_cb {
+ ufbx_progress_fn *fn;
+ void *user;
+
+ UFBX_CALLBACK_IMPL(ufbx_progress_cb, ufbx_progress_fn, ufbx_progress_result,
+ (void *user, const ufbx_progress *progress),
+ (progress))
+} ufbx_progress_cb;
+
+// -- Inflate
+
+typedef struct ufbx_inflate_input ufbx_inflate_input;
+typedef struct ufbx_inflate_retain ufbx_inflate_retain;
+
+// Source data/stream to decompress with `ufbx_inflate()`
+struct ufbx_inflate_input {
+ // Total size of the data in bytes
+ size_t total_size;
+
+ // (optional) Initial or complete data chunk
+ const void *data;
+ size_t data_size;
+
+ // (optional) Temporary buffer, defaults to 256b stack buffer
+ void *buffer;
+ size_t buffer_size;
+
+ // (optional) Streaming read function, concatenated after `data`
+ ufbx_read_fn *read_fn;
+ void *read_user;
+
+ // (optional) Progress reporting
+ ufbx_progress_cb progress_cb;
+ uint64_t progress_interval_hint; // < Bytes between progress report calls
+
+ // (optional) Change the progress scope
+ uint64_t progress_size_before;
+ uint64_t progress_size_after;
+
+ // (optional) No the DEFLATE header
+ bool no_header;
+
+ // (optional) No the Adler32 checksum
+ bool no_checksum;
+
+ // (optional) Force internal fast lookup bit amount
+ size_t internal_fast_bits;
+};
+
+// Persistent data between `ufbx_inflate()` calls
+// NOTE: You must set `initialized` to `false`, but `data` may be uninitialized
+struct ufbx_inflate_retain {
+ bool initialized;
+ uint64_t data[1024];
+};
+
+typedef enum ufbx_index_error_handling UFBX_ENUM_REPR {
+ // Clamp to a valid value.
+ UFBX_INDEX_ERROR_HANDLING_CLAMP,
+ // Set bad indices to `UFBX_NO_INDEX`.
+ // This is the recommended way if you need to deal with files with gaps in information.
+ // HINT: If you use this `ufbx_get_vertex_TYPE()` functions will return zero
+ // on invalid indices instead of failing.
+ UFBX_INDEX_ERROR_HANDLING_NO_INDEX,
+ // Fail loading entierely when encountering a bad index.
+ UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING,
+ // Pass bad indices through as-is.
+ // Requires `ufbx_load_opts.allow_unsafe`.
+ // UNSAFE: Breaks any API guarantees regarding indexes being in bounds and makes
+ // `ufbx_get_vertex_TYPE()` memory-unsafe to use.
+ UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_INDEX_ERROR_HANDLING)
+} ufbx_index_error_handling;
+
+UFBX_ENUM_TYPE(ufbx_index_error_handling, UFBX_INDEX_ERROR_HANDLING, UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE);
+
+typedef enum ufbx_unicode_error_handling UFBX_ENUM_REPR {
+ // Replace errors with U+FFFD "Replacement Character"
+ UFBX_UNICODE_ERROR_HANDLING_REPLACEMENT_CHARACTER,
+ // Replace errors with '_' U+5F "Low Line"
+ UFBX_UNICODE_ERROR_HANDLING_UNDERSCORE,
+ // Replace errors with '?' U+3F "Question Mark"
+ UFBX_UNICODE_ERROR_HANDLING_QUESTION_MARK,
+ // Remove errors from the output
+ UFBX_UNICODE_ERROR_HANDLING_REMOVE,
+ // Fail loading on encountering an Unicode error
+ UFBX_UNICODE_ERROR_HANDLING_ABORT_LOADING,
+ // Ignore and pass-through non-UTF-8 string data.
+ // Requires `ufbx_load_opts.allow_unsafe`.
+ // UNSAFE: Breaks API guarantee that `ufbx_string` is UTF-8 encoded.
+ UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE,
+
+ UFBX_ENUM_FORCE_WIDTH(UFBX_UNICODE_ERROR_HANDLING)
+} ufbx_unicode_error_handling;
+
+UFBX_ENUM_TYPE(ufbx_unicode_error_handling, UFBX_UNICODE_ERROR_HANDLING, UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE);
+
+typedef enum ufbx_baked_key_flags UFBX_FLAG_REPR {
+ // This keyframe represents a constant step from the left side
+ UFBX_BAKED_KEY_STEP_LEFT = 0x1,
+ // This keyframe represents a constant step from the right side
+ UFBX_BAKED_KEY_STEP_RIGHT = 0x2,
+ // This keyframe is the main part of a step
+ // Bordering either `UFBX_BAKED_KEY_STEP_LEFT` or `UFBX_BAKED_KEY_STEP_RIGHT`.
+ UFBX_BAKED_KEY_STEP_KEY = 0x4,
+ // This keyframe is a real keyframe in the source animation
+ UFBX_BAKED_KEY_KEYFRAME = 0x8,
+ // This keyframe has been reduced by maximum sample rate.
+ // See `ufbx_bake_opts.maximum_sample_rate`.
+ UFBX_BAKED_KEY_REDUCED = 0x10,
+
+ UFBX_FLAG_FORCE_WIDTH(UFBX_BAKED_KEY)
+} ufbx_baked_key_flags;
+
+typedef struct ufbx_baked_vec3 {
+ double time; // < Time of the keyframe, in seconds
+ ufbx_vec3 value; // < Value at `time`, can be linearly interpolated
+ ufbx_baked_key_flags flags; // < Additional information about the keyframe
+} ufbx_baked_vec3;
+
+UFBX_LIST_TYPE(ufbx_baked_vec3_list, ufbx_baked_vec3);
+
+typedef struct ufbx_baked_quat {
+ double time; // < Time of the keyframe, in seconds
+ ufbx_quat value; // < Value at `time`, can be (spherically) linearly interpolated
+ ufbx_baked_key_flags flags; // < Additional information about the keyframe
+} ufbx_baked_quat;
+
+UFBX_LIST_TYPE(ufbx_baked_quat_list, ufbx_baked_quat);
+
+// Baked transform animation for a single node.
+typedef struct ufbx_baked_node {
+
+ // Typed ID of the node, maps to `ufbx_scene.nodes[]`.
+ uint32_t typed_id;
+ // Element ID of the element, maps to `ufbx_scene.elements[]`.
+ uint32_t element_id;
+
+ // The translation channel has constant values for the whole animation.
+ bool constant_translation;
+ // The rotation channel has constant values for the whole animation.
+ bool constant_rotation;
+ // The scale channel has constant values for the whole animation.
+ bool constant_scale;
+
+ // Translation keys for the animation, maps to `ufbx_node.local_transform.translation`.
+ ufbx_baked_vec3_list translation_keys;
+ // Rotation keyframes, maps to `ufbx_node.local_transform.rotation`.
+ ufbx_baked_quat_list rotation_keys;
+ // Scale keyframes, maps to `ufbx_node.local_transform.scale`.
+ ufbx_baked_vec3_list scale_keys;
+
+} ufbx_baked_node;
+
+UFBX_LIST_TYPE(ufbx_baked_node_list, ufbx_baked_node);
+
+// Baked property animation.
+typedef struct ufbx_baked_prop {
+ // Name of the property, eg. `"Visibility"`.
+ ufbx_string name;
+ // The value of the property is constant for the whole animation.
+ bool constant_value;
+ // Property value keys.
+ ufbx_baked_vec3_list keys;
+} ufbx_baked_prop;
+
+UFBX_LIST_TYPE(ufbx_baked_prop_list, ufbx_baked_prop);
+
+// Baked property animation for a single element.
+typedef struct ufbx_baked_element {
+ // Element ID of the element, maps to `ufbx_scene.elements[]`.
+ uint32_t element_id;
+ // List of properties the animation modifies.
+ ufbx_baked_prop_list props;
+} ufbx_baked_element;
+
+UFBX_LIST_TYPE(ufbx_baked_element_list, ufbx_baked_element);
+
+typedef struct ufbx_baked_anim_metadata {
+ // Memory statistics
+ size_t result_memory_used;
+ size_t temp_memory_used;
+ size_t result_allocs;
+ size_t temp_allocs;
+} ufbx_baked_anim_metadata;
+
+// Animation baked into linearly interpolated keyframes.
+// See `ufbx_bake_anim()`.
+typedef struct ufbx_baked_anim {
+
+ // Nodes that are modified by the animation.
+ // Some nodes may be missing if the specified animation does not transform them.
+ // Conversely, some non-obviously animated nodes may be included as exporters
+ // often may add dummy keyframes for objects.
+ ufbx_baked_node_list nodes;
+
+ // Element properties modified by the animation.
+ ufbx_baked_element_list elements;
+
+ // Playback time range for the animation.
+ double playback_time_begin;
+ double playback_time_end;
+ double playback_duration;
+
+ // Keyframe time range.
+ double key_time_min;
+ double key_time_max;
+
+ // Additional bake information.
+ ufbx_baked_anim_metadata metadata;
+
+} ufbx_baked_anim;
+
+// -- Thread API
+
+// Internal thread pool handle.
+// Passed to `ufbx_thread_pool_run_task()` from an user thread to run ufbx tasks.
+// HINT: This context can store a user pointer via `ufbx_thread_pool_set_user_ptr()`.
+typedef uintptr_t ufbx_thread_pool_context;
+
+// Thread pool creation information from ufbx.
+typedef struct ufbx_thread_pool_info {
+ uint32_t max_concurrent_tasks;
+} ufbx_thread_pool_info;
+
+// Initialize the thread pool.
+// Return `true` on success.
+typedef bool ufbx_thread_pool_init_fn(void *user, ufbx_thread_pool_context ctx, const ufbx_thread_pool_info *info);
+
+// Run tasks `count` tasks in threads.
+// You must call `ufbx_thread_pool_run_task()` with indices `[start_index, start_index + count)`.
+// The threads are launched in batches indicated by `group`, see `UFBX_THREAD_GROUP_COUNT` for more information.
+// Ideally, you should run all the task indices in parallel within each `ufbx_thread_pool_run_fn()` call.
+typedef void ufbx_thread_pool_run_fn(void *user, ufbx_thread_pool_context ctx, uint32_t group, uint32_t start_index, uint32_t count);
+
+// Wait for previous tasks spawned in `ufbx_thread_pool_run_fn()` to finish.
+// `group` specifies the batch to wait for, `max_index` contains `start_index + count` from that group instance.
+typedef void ufbx_thread_pool_wait_fn(void *user, ufbx_thread_pool_context ctx, uint32_t group, uint32_t max_index);
+
+// Free the thread pool.
+typedef void ufbx_thread_pool_free_fn(void *user, ufbx_thread_pool_context ctx);
+
+// Thread pool interface.
+// See functions above for more information.
+//
+// Hypothetical example of calls, where `UFBX_THREAD_GROUP_COUNT=2` for simplicity:
+//
+// run_fn(group=0, start_index=0, count=4) -> t0 := threaded { ufbx_thread_pool_run_task(0..3) }
+// run_fn(group=1, start_index=4, count=10) -> t1 := threaded { ufbx_thread_pool_run_task(4..10) }
+// wait_fn(group=0, max_index=4) -> wait_threads(t0)
+// run_fn(group=0, start_index=10, count=15) -> t0 := threaded { ufbx_thread_pool_run_task(10..14) }
+// wait_fn(group=1, max_index=10) -> wait_threads(t1)
+// wait_fn(group=0, max_index=15) -> wait_threads(t0)
+//
+typedef struct ufbx_thread_pool {
+ ufbx_thread_pool_init_fn *init_fn; // < Optional
+ ufbx_thread_pool_run_fn *run_fn; // < Required
+ ufbx_thread_pool_wait_fn *wait_fn; // < Required
+ ufbx_thread_pool_free_fn *free_fn; // < Optional
+ void *user;
+} ufbx_thread_pool;
+
+// Thread pool options.
+typedef struct ufbx_thread_opts {
+
+ // Thread pool interface.
+ // HINT: You can use `extra/ufbx_os.h` to provide a thread pool.
+ ufbx_thread_pool pool;
+
+ // Maximum of tasks to have in-flight.
+ // Default: 2048
+ size_t num_tasks;
+
+ // Maximum amount of memory to use for batched threaded processing.
+ // Default: 32MB
+ // NOTE: The actual used memory usage might be higher, if there are individual tasks
+ // that rqeuire a high amount of memory.
+ size_t memory_limit;
+
+} ufbx_thread_opts;
+
+// Flags to control nanimation evaluation functions.
+typedef enum ufbx_evaluate_flags UFBX_FLAG_REPR {
+
+ // Do not extrapolate past the keyframes.
+ UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION = 0x1,
+
+ UFBX_FLAG_FORCE_WIDTH(ufbx_evaluate_flags)
+} ufbx_evaluate_flags;
+
+// -- Main API
+
+// Options for `ufbx_load_file/memory/stream/stdio()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_load_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during loading
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final scene
+ ufbx_thread_opts thread_opts; // < Threading options
+
+ // Preferences
+ bool ignore_geometry; // < Do not load geometry datsa (vertices, indices, etc)
+ bool ignore_animation; // < Do not load animation curves
+ bool ignore_embedded; // < Do not load embedded content
+ bool ignore_all_content; // < Do not load any content (geometry, animation, embedded)
+
+ bool evaluate_skinning; // < Evaluate skinning (see ufbx_mesh.skinned_vertices)
+ bool evaluate_caches; // < Evaluate vertex caches (see ufbx_mesh.skinned_vertices)
+
+ // Try to open external files referenced by the main file automatically.
+ // Applies to geometry caches and .mtl files for OBJ.
+ // NOTE: This may be risky for untrusted data as the input files may contain
+ // references to arbitrary paths in the filesystem.
+ // NOTE: This only applies to files *implicitly* referenced by the scene, if
+ // you request additional files via eg. `ufbx_load_opts.obj_mtl_path` they
+ // are still loaded.
+ // NOTE: Will fail loading if any external files are not found by default, use
+ // `ufbx_load_opts.ignore_missing_external_files` to suppress this, in this case
+ // you can find the errors at `ufbx_metadata.warnings[]` as `UFBX_WARNING_MISSING_EXTERNAL_FILE`.
+ bool load_external_files;
+
+ // Don't fail loading if external files are not found.
+ bool ignore_missing_external_files;
+
+ // Don't compute `ufbx_skin_deformer` `vertices` and `weights` arrays saving
+ // a bit of memory and time if not needed
+ bool skip_skin_vertices;
+
+ // Skip computing `ufbx_mesh.material_parts[]` and `ufbx_mesh.face_group_parts[]`.
+ bool skip_mesh_parts;
+
+ // Clean-up skin weights by removing negative, zero and NAN weights.
+ bool clean_skin_weights;
+
+ // Read Blender materials as PBR values.
+ // Blender converts PBR materials to legacy FBX Phong materials in a deterministic way.
+ // If this setting is enabled, such materials will be read as `UFBX_SHADER_BLENDER_PHONG`,
+ // which means ufbx will be able to parse roughness and metallic textures.
+ bool use_blender_pbr_material;
+
+ // Don't adjust reading the FBX file depending on the detected exporter
+ bool disable_quirks;
+
+ // Don't allow partially broken FBX files to load
+ bool strict;
+
+ // Force ASCII parsing to use a single thread.
+ // The multi-threaded ASCII parsing is slightly more lenient as it ignores
+ // the self-reported size of ASCII arrays, that threaded parsing depends on.
+ bool force_single_thread_ascii_parsing;
+
+ // UNSAFE: If enabled allows using unsafe options that may fundamentally
+ // break the API guarantees.
+ ufbx_unsafe bool allow_unsafe;
+
+ // Specify how to handle broken indices.
+ ufbx_index_error_handling index_error_handling;
+
+ // Connect related elements even if they are broken. If `false` (default)
+ // `ufbx_skin_cluster` with a missing `bone` field are _not_ included in
+ // the `ufbx_skin_deformer.clusters[]` array for example.
+ bool connect_broken_elements;
+
+ // Allow nodes that are not connected in any way to the root. Conversely if
+ // disabled, all lone nodes will be parented under `ufbx_scene.root_node`.
+ bool allow_nodes_out_of_root;
+
+ // Allow meshes with no vertex position attribute.
+ // NOTE: If this is set `ufbx_mesh.vertex_position.exists` may be `false`.
+ bool allow_missing_vertex_position;
+
+ // Allow faces with zero indices.
+ bool allow_empty_faces;
+
+ // Generate vertex normals for a meshes that are missing normals.
+ // You can see if the normals have been generated from `ufbx_mesh.generated_normals`.
+ bool generate_missing_normals;
+
+ // Ignore `open_file_cb` when loading the main file.
+ bool open_main_file_with_default;
+
+ // Path separator character, defaults to '\' on Windows and '/' otherwise.
+ char path_separator;
+
+ // Maximum depth of the node hirerachy.
+ // Will fail with `UFBX_ERROR_NODE_DEPTH_LIMIT` if a node is deeper than this limit.
+ // NOTE: The default of 0 allows arbitrarily deep hierarchies. Be careful if using
+ // recursive algorithms without setting this limit.
+ uint32_t node_depth_limit;
+
+ // Estimated file size for progress reporting
+ uint64_t file_size_estimate;
+
+ // Buffer size in bytes to use for reading from files or IO callbacks
+ size_t read_buffer_size;
+
+ // Filename to use as a base for relative file paths if not specified using
+ // `ufbx_load_file()`. Use `length = SIZE_MAX` for NULL-terminated strings.
+ // `raw_filename` will be derived from this if empty.
+ ufbx_string filename;
+
+ // Raw non-UTF8 filename. Does not support NULL termination.
+ // `filename` will be derived from this if empty.
+ ufbx_blob raw_filename;
+
+ // Progress reporting
+ ufbx_progress_cb progress_cb;
+ uint64_t progress_interval_hint; // < Bytes between progress report calls
+
+ // External file callbacks (defaults to stdio.h)
+ ufbx_open_file_cb open_file_cb;
+
+ // How to handle geometry transforms in the nodes.
+ // See `ufbx_geometry_transform_handling` for an explanation.
+ ufbx_geometry_transform_handling geometry_transform_handling;
+
+ // How to handle unconventional transform inherit modes.
+ // See `ufbx_inherit_mode_handling` for an explanation.
+ ufbx_inherit_mode_handling inherit_mode_handling;
+
+ // How to perform space conversion by `target_axes` and `target_unit_meters`.
+ // See `ufbx_space_conversion` for an explanation.
+ ufbx_space_conversion space_conversion;
+
+ // How to handle pivots.
+ // See `ufbx_pivot_handling` for an explanation.
+ ufbx_pivot_handling pivot_handling;
+
+ // Retain the original transforms of empties when converting pivots.
+ bool pivot_handling_retain_empties;
+
+ // Axis used to mirror for conversion between left-handed and right-handed coordinates.
+ ufbx_mirror_axis handedness_conversion_axis;
+
+ // Do not change winding of faces when converting handedness.
+ bool handedness_conversion_retain_winding;
+
+ // Reverse winding of all faces.
+ // If `handedness_conversion_retain_winding` is not specified, mirrored meshes
+ // will retain their original winding.
+ bool reverse_winding;
+
+ // Apply an implicit root transformation to match axes.
+ // Used if `ufbx_coordinate_axes_valid(target_axes)`.
+ ufbx_coordinate_axes target_axes;
+
+ // Scale the scene so that one world-space unit is `target_unit_meters` meters.
+ // By default units are not scaled.
+ ufbx_real target_unit_meters;
+
+ // Target space for camera.
+ // By default FBX cameras point towards the positive X axis.
+ // Used if `ufbx_coordinate_axes_valid(target_camera_axes)`.
+ ufbx_coordinate_axes target_camera_axes;
+
+ // Target space for directed lights.
+ // By default FBX lights point towards the negative Y axis.
+ // Used if `ufbx_coordinate_axes_valid(target_light_axes)`.
+ ufbx_coordinate_axes target_light_axes;
+
+ // Name for dummy geometry transform helper nodes.
+ // See `UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES`.
+ ufbx_string geometry_transform_helper_name;
+
+ // Name for dummy scale helper nodes.
+ // See `UFBX_INHERIT_MODE_HANDLING_HELPER_NODES`.
+ ufbx_string scale_helper_name;
+
+ // Normalize vertex normals.
+ bool normalize_normals;
+
+ // Normalize tangents and bitangents.
+ bool normalize_tangents;
+
+ // Override for the root transform
+ bool use_root_transform;
+ ufbx_transform root_transform;
+
+ // Animation keyframe clamp threshold, only applies to specific interpolation modes.
+ double key_clamp_threshold;
+
+ // Specify how to handle Unicode errors in strings.
+ ufbx_unicode_error_handling unicode_error_handling;
+
+ // Retain the 'W' component of mesh normal/tangent/bitangent.
+ // See `ufbx_vertex_attrib.values_w`.
+ bool retain_vertex_attrib_w;
+
+ // Retain the raw document structure using `ufbx_dom_node`.
+ bool retain_dom;
+
+ // Force a specific file format instead of detecting it.
+ ufbx_file_format file_format;
+
+ // How far to read into the file to determine the file format.
+ // Default: 16kB
+ size_t file_format_lookahead;
+
+ // Do not attempt to detect file format from file content.
+ bool no_format_from_content;
+
+ // Do not attempt to detect file format from filename extension.
+ // ufbx primarily detects file format from the file header,
+ // this is just used as a fallback.
+ bool no_format_from_extension;
+
+ // (.obj) Try to find .mtl file with matching filename as the .obj file.
+ // Used if the file specified `mtllib` line is not found, eg. for a file called
+ // `model.obj` that contains the line `usemtl materials.mtl`, ufbx would first
+ // try to open `materials.mtl` and if that fails it tries to open `model.mtl`.
+ bool obj_search_mtl_by_filename;
+
+ // (.obj) Don't split geometry into meshes by object.
+ bool obj_merge_objects;
+
+ // (.obj) Don't split geometry into meshes by groups.
+ bool obj_merge_groups;
+
+ // (.obj) Force splitting groups even on object boundaries.
+ bool obj_split_groups;
+
+ // (.obj) Path to the .mtl file.
+ // Use `length = SIZE_MAX` for NULL-terminated strings.
+ // NOTE: This is used _instead_ of the one in the file even if not found
+ // and sidesteps `load_external_files` as it's _explicitly_ requested.
+ ufbx_string obj_mtl_path;
+
+ // (.obj) Data for the .mtl file.
+ ufbx_blob obj_mtl_data;
+
+ // The world unit in meters that .obj files are assumed to be in.
+ // .obj files do not define the working units. By default the unit scale
+ // is read as zero, and no unit conversion is performed.
+ ufbx_real obj_unit_meters;
+
+ // Coordinate space .obj files are assumed to be in.
+ // .obj files do not define the coordinate space they use. By default no
+ // coordinate space is assumed and no conversion is performed.
+ ufbx_coordinate_axes obj_axes;
+
+ uint32_t _end_zero;
+} ufbx_load_opts;
+
+// Options for `ufbx_evaluate_scene()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_evaluate_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during evaluation
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final scene
+
+ bool evaluate_skinning; // < Evaluate skinning (see ufbx_mesh.skinned_vertices)
+ bool evaluate_caches; // < Evaluate vertex caches (see ufbx_mesh.skinned_vertices)
+
+ // Evaluation flags.
+ // See `ufbx_evaluate_flags` for information.
+ uint32_t evaluate_flags;
+
+ // WARNING: Potentially unsafe! Try to open external files such as geometry caches
+ bool load_external_files;
+
+ // External file callbacks (defaults to stdio.h)
+ ufbx_open_file_cb open_file_cb;
+
+ uint32_t _end_zero;
+} ufbx_evaluate_opts;
+
+UFBX_LIST_TYPE(ufbx_const_uint32_list, const uint32_t);
+UFBX_LIST_TYPE(ufbx_const_real_list, const ufbx_real);
+
+typedef struct ufbx_prop_override_desc {
+ // Element (`ufbx_element.element_id`) to override the property from
+ uint32_t element_id;
+
+ // Property name to override.
+ ufbx_string prop_name;
+
+ // Override value, use `value.x` for scalars. `value_int` is initialized
+ // from `value.x` if zero so keep `value` zeroed even if you don't need it!
+ ufbx_vec4 value;
+ ufbx_string value_str;
+ int64_t value_int;
+} ufbx_prop_override_desc;
+
+UFBX_LIST_TYPE(ufbx_const_prop_override_desc_list, const ufbx_prop_override_desc);
+
+UFBX_LIST_TYPE(ufbx_const_transform_override_list, const ufbx_transform_override);
+
+typedef struct ufbx_anim_opts {
+ uint32_t _begin_zero;
+
+ // Animation layers indices.
+ // Corresponding to `ufbx_scene.anim_layers[]`, aka `ufbx_anim_layer.typed_id`.
+ ufbx_const_uint32_list layer_ids;
+
+ // Override layer weights, parallel to `ufbx_anim_opts.layer_ids[]`.
+ ufbx_const_real_list override_layer_weights;
+
+ // Property overrides.
+ // These allow you to override FBX properties, such as 'UFBX_Lcl_Rotation`.
+ ufbx_const_prop_override_desc_list prop_overrides;
+
+ // Transform overrides.
+ // These allow you to override individual nodes' `ufbx_node.local_transform`.
+ ufbx_const_transform_override_list transform_overrides;
+
+ // Ignore connected properties
+ bool ignore_connections;
+
+ ufbx_allocator_opts result_allocator; // < Allocator used to create the `ufbx_anim`
+
+ uint32_t _end_zero;
+} ufbx_anim_opts;
+
+// Specifies how to handle stepped tangents.
+typedef enum ufbx_bake_step_handling UFBX_ENUM_REPR {
+
+ // One millisecond default step duration, with potential extra slack for converting to `float`.
+ UFBX_BAKE_STEP_HANDLING_DEFAULT,
+
+ // Use a custom interpolation duration for the constant step.
+ // See `ufbx_bake_opts.step_custom_duration` and optionally `ufbx_bake_opts.step_custom_epsilon`.
+ UFBX_BAKE_STEP_HANDLING_CUSTOM_DURATION,
+
+ // Stepped keyframes are represented as keyframes at the exact same time.
+ // Use flags `UFBX_BAKED_KEY_STEP_LEFT` and `UFBX_BAKED_KEY_STEP_RIGHT` to differentiate
+ // between the primary key and edge limits.
+ UFBX_BAKE_STEP_HANDLING_IDENTICAL_TIME,
+
+ // Represent stepped keyframe times as the previous/next representable `double` value.
+ // Using this and robust linear interpolation will handle stepped tangents correctly
+ // without having to look at the key flags.
+ // NOTE: Casting these values to `float` or otherwise modifying them can collapse
+ // the keyframes to have the identical time.
+ UFBX_BAKE_STEP_HANDLING_ADJACENT_DOUBLE,
+
+ // Treat all stepped tangents as linearly interpolated.
+ UFBX_BAKE_STEP_HANDLING_IGNORE,
+
+ UFBX_ENUM_FORCE_WIDTH(ufbx_bake_step_handling)
+} ufbx_bake_step_handling;
+
+UFBX_ENUM_TYPE(ufbx_bake_step_handling, UFBX_BAKE_STEP_HANDLING, UFBX_BAKE_STEP_HANDLING_IGNORE);
+
+typedef struct ufbx_bake_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during loading
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final baked animation
+
+ // Move the keyframe times to start from zero regardless of the animation start time.
+ // For example, for an animation spanning between frames [30, 60] will be moved to
+ // [0, 30] in the baked animation.
+ // NOTE: This is in general not equivalent to subtracting `ufbx_anim.time_begin`
+ // from each keyframe, as this trimming is done exactly using internal FBX ticks.
+ bool trim_start_time;
+
+ // Samples per second to use for resampling non-linear animation.
+ // Default: 30
+ double resample_rate;
+
+ // Minimum sample rate to not resample.
+ // Many exporters resample animation by default. To avoid double-resampling
+ // keyframe rates higher or equal to this will not be resampled.
+ // Default: 19.5
+ double minimum_sample_rate;
+
+ // Maximum sample rate to use, this will remove keys if they are too close together.
+ // Default: unlimited
+ double maximum_sample_rate;
+
+ // Bake the raw versions of properties related to transforms.
+ bool bake_transform_props;
+
+ // Do not bake node transforms.
+ bool skip_node_transforms;
+
+ // Do not resample linear rotation keyframes.
+ // FBX interpolates rotation in Euler angles, so this might cause incorrect interpolation.
+ bool no_resample_rotation;
+
+ // Ignore layer weight animation.
+ bool ignore_layer_weight_animation;
+
+ // Maximum number of segments to generate from one keyframe.
+ // Default: 32
+ size_t max_keyframe_segments;
+
+ // How to handle stepped tangents.
+ ufbx_bake_step_handling step_handling;
+
+ // Interpolation duration used by `UFBX_BAKE_STEP_HANDLING_CUSTOM_DURATION`.
+ double step_custom_duration;
+
+ // Interpolation epsilon used by `UFBX_BAKE_STEP_HANDLING_CUSTOM_DURATION`.
+ // Defined as the minimum fractional decrease/increase in key time, ie.
+ // `time / (1.0 + step_custom_epsilon)` and `time * (1.0 + step_custom_epsilon)`.
+ double step_custom_epsilon;
+
+ // Flags passed to animation evaluation functions.
+ // See `ufbx_evaluate_flags`.
+ uint32_t evaluate_flags;
+
+ // Enable key reduction.
+ bool key_reduction_enabled;
+
+ // Enable key reduction for non-constant rotations.
+ // Assumes rotations will be interpolated using a spherical linear interpolation at runtime.
+ bool key_reduction_rotation;
+
+ // Threshold for reducing keys for linear segments.
+ // Default `0.000001`, use negative to disable.
+ double key_reduction_threshold;
+
+ // Maximum passes over the keys to reduce.
+ // Every pass can potentially halve the the amount of keys.
+ // Default: `4`
+ size_t key_reduction_passes;
+
+ uint32_t _end_zero;
+} ufbx_bake_opts;
+
+// Options for `ufbx_tessellate_nurbs_curve()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_tessellate_curve_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during tessellation
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final line curve
+
+ // How many segments tessellate each span in `ufbx_nurbs_basis.spans`.
+ size_t span_subdivision;
+
+ uint32_t _end_zero;
+} ufbx_tessellate_curve_opts;
+
+// Options for `ufbx_tessellate_nurbs_surface()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_tessellate_surface_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during tessellation
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final mesh
+
+ // How many segments tessellate each span in `ufbx_nurbs_basis.spans`.
+ // NOTE: Default is `4`, _not_ `ufbx_nurbs_surface.span_subdivision_u/v` as that
+ // would make it easy to create an FBX file with an absurdly high subdivision
+ // rate (similar to mesh subdivision). Please enforce copy the value yourself
+ // enforcing whatever limits you deem reasonable.
+ size_t span_subdivision_u;
+ size_t span_subdivision_v;
+
+ // Skip computing `ufbx_mesh.material_parts[]`
+ bool skip_mesh_parts;
+
+ uint32_t _end_zero;
+} ufbx_tessellate_surface_opts;
+
+// Options for `ufbx_subdivide_mesh()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_subdivide_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during subdivision
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final mesh
+
+ ufbx_subdivision_boundary boundary;
+ ufbx_subdivision_boundary uv_boundary;
+
+ // Do not generate normals
+ bool ignore_normals;
+
+ // Interpolate existing normals using the subdivision rules
+ // instead of generating new normals
+ bool interpolate_normals;
+
+ // Subdivide also tangent attributes
+ bool interpolate_tangents;
+
+ // Map subdivided vertices into weighted original vertices.
+ // NOTE: May be O(n^2) if `max_source_vertices` is not specified!
+ bool evaluate_source_vertices;
+
+ // Limit source vertices per subdivided vertex.
+ size_t max_source_vertices;
+
+ // Calculate bone influences over subdivided vertices (if applicable).
+ // NOTE: May be O(n^2) if `max_skin_weights` is not specified!
+ bool evaluate_skin_weights;
+
+ // Limit bone influences per subdivided vertex.
+ size_t max_skin_weights;
+
+ // Index of the skin deformer to use for `evaluate_skin_weights`.
+ size_t skin_deformer_index;
+
+ uint32_t _end_zero;
+} ufbx_subdivide_opts;
+
+// Options for `ufbx_load_geometry_cache()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_geometry_cache_opts {
+ uint32_t _begin_zero;
+
+ ufbx_allocator_opts temp_allocator; // < Allocator used during loading
+ ufbx_allocator_opts result_allocator; // < Allocator used for the final scene
+
+ // External file callbacks (defaults to stdio.h)
+ ufbx_open_file_cb open_file_cb;
+
+ // FPS value for converting frame times to seconds
+ double frames_per_second;
+
+ // Axis to mirror the geometry by.
+ ufbx_mirror_axis mirror_axis;
+
+ // Enable scaling `scale_factor` all geometry by.
+ bool use_scale_factor;
+
+ // Factor to scale the geometry by.
+ ufbx_real scale_factor;
+
+ uint32_t _end_zero;
+} ufbx_geometry_cache_opts;
+
+// Options for `ufbx_read_geometry_cache_TYPE()`
+// NOTE: Initialize to zero with `{ 0 }` (C) or `{ }` (C++)
+typedef struct ufbx_geometry_cache_data_opts {
+ uint32_t _begin_zero;
+
+ // External file callbacks (defaults to stdio.h)
+ ufbx_open_file_cb open_file_cb;
+
+ bool additive;
+ bool use_weight;
+ ufbx_real weight;
+
+ // Ignore scene transform.
+ bool ignore_transform;
+
+ uint32_t _end_zero;
+} ufbx_geometry_cache_data_opts;
+
+typedef struct ufbx_panic {
+ bool did_panic;
+ size_t message_length;
+ char message[UFBX_PANIC_MESSAGE_LENGTH];
+} ufbx_panic;
+
+// -- API
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Various zero/empty/identity values
+ufbx_abi_data const ufbx_string ufbx_empty_string;
+ufbx_abi_data const ufbx_blob ufbx_empty_blob;
+ufbx_abi_data const ufbx_matrix ufbx_identity_matrix;
+ufbx_abi_data const ufbx_transform ufbx_identity_transform;
+ufbx_abi_data const ufbx_vec2 ufbx_zero_vec2;
+ufbx_abi_data const ufbx_vec3 ufbx_zero_vec3;
+ufbx_abi_data const ufbx_vec4 ufbx_zero_vec4;
+ufbx_abi_data const ufbx_quat ufbx_identity_quat;
+
+// Commonly used coordinate axes.
+ufbx_abi_data const ufbx_coordinate_axes ufbx_axes_right_handed_y_up;
+ufbx_abi_data const ufbx_coordinate_axes ufbx_axes_right_handed_z_up;
+ufbx_abi_data const ufbx_coordinate_axes ufbx_axes_left_handed_y_up;
+ufbx_abi_data const ufbx_coordinate_axes ufbx_axes_left_handed_z_up;
+
+// Sizes of element types. eg `sizeof(ufbx_node)`
+ufbx_abi_data const size_t ufbx_element_type_size[UFBX_ELEMENT_TYPE_COUNT];
+
+// Version of the source file, comparable to `UFBX_HEADER_VERSION`
+ufbx_abi_data const uint32_t ufbx_source_version;
+
+
+// Practically always `true` (see below), if not you need to be careful with threads.
+//
+// Guaranteed to be `true` in _any_ of the following conditions:
+// - ufbx.c has been compiled using: GCC / Clang / MSVC / ICC / EMCC / TCC
+// - ufbx.c has been compiled as C++11 or later
+// - ufbx.c has been compiled as C11 or later with `<stdatomic.h>` support
+//
+// If `false` you can't call the following functions concurrently:
+// ufbx_evaluate_scene()
+// ufbx_free_scene()
+// ufbx_subdivide_mesh()
+// ufbx_tessellate_nurbs_surface()
+// ufbx_free_mesh()
+ufbx_abi bool ufbx_is_thread_safe(void);
+
+// Load a scene from a `size` byte memory buffer at `data`
+ufbx_abi ufbx_scene *ufbx_load_memory(
+ const void *data, size_t data_size,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Load a scene by opening a file named `filename`
+ufbx_abi ufbx_scene *ufbx_load_file(
+ const char *filename,
+ const ufbx_load_opts *opts, ufbx_error *error);
+ufbx_abi ufbx_scene *ufbx_load_file_len(
+ const char *filename, size_t filename_len,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Load a scene by reading from an `FILE *file` stream
+// NOTE: `file` is passed as a `void` pointer to avoid including <stdio.h>
+ufbx_abi ufbx_scene *ufbx_load_stdio(
+ void *file,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Load a scene by reading from an `FILE *file` stream with a prefix
+// NOTE: `file` is passed as a `void` pointer to avoid including <stdio.h>
+ufbx_abi ufbx_scene *ufbx_load_stdio_prefix(
+ void *file,
+ const void *prefix, size_t prefix_size,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Load a scene from a user-specified stream
+ufbx_abi ufbx_scene *ufbx_load_stream(
+ const ufbx_stream *stream,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Load a scene from a user-specified stream with a prefix
+ufbx_abi ufbx_scene *ufbx_load_stream_prefix(
+ const ufbx_stream *stream,
+ const void *prefix, size_t prefix_size,
+ const ufbx_load_opts *opts, ufbx_error *error);
+
+// Free a previously loaded or evaluated scene
+ufbx_abi void ufbx_free_scene(ufbx_scene *scene);
+
+// Increment `scene` refcount
+ufbx_abi void ufbx_retain_scene(ufbx_scene *scene);
+
+// Format a textual description of `error`.
+// Always produces a NULL-terminated string to `char dst[dst_size]`, truncating if
+// necessary. Returns the number of characters written not including the NULL terminator.
+ufbx_abi size_t ufbx_format_error(char *dst, size_t dst_size, const ufbx_error *error);
+
+// Query
+
+// Find a property `name` from `props`, returns `NULL` if not found.
+// Searches through `ufbx_props.defaults` as well.
+ufbx_abi ufbx_prop *ufbx_find_prop_len(const ufbx_props *props, const char *name, size_t name_len);
+ufbx_abi ufbx_prop *ufbx_find_prop(const ufbx_props *props, const char *name);
+
+// Utility functions for finding the value of a property, returns `def` if not found.
+// NOTE: For `ufbx_string` you need to ensure the lifetime of the default is
+// sufficient as no copy is made.
+ufbx_abi ufbx_real ufbx_find_real_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_real def);
+ufbx_abi ufbx_real ufbx_find_real(const ufbx_props *props, const char *name, ufbx_real def);
+ufbx_abi ufbx_vec3 ufbx_find_vec3_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_vec3 def);
+ufbx_abi ufbx_vec3 ufbx_find_vec3(const ufbx_props *props, const char *name, ufbx_vec3 def);
+ufbx_abi int64_t ufbx_find_int_len(const ufbx_props *props, const char *name, size_t name_len, int64_t def);
+ufbx_abi int64_t ufbx_find_int(const ufbx_props *props, const char *name, int64_t def);
+ufbx_abi bool ufbx_find_bool_len(const ufbx_props *props, const char *name, size_t name_len, bool def);
+ufbx_abi bool ufbx_find_bool(const ufbx_props *props, const char *name, bool def);
+ufbx_abi ufbx_string ufbx_find_string_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_string def);
+ufbx_abi ufbx_string ufbx_find_string(const ufbx_props *props, const char *name, ufbx_string def);
+ufbx_abi ufbx_blob ufbx_find_blob_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_blob def);
+ufbx_abi ufbx_blob ufbx_find_blob(const ufbx_props *props, const char *name, ufbx_blob def);
+
+// Find property in `props` with concatenated `parts[num_parts]`.
+ufbx_abi ufbx_prop *ufbx_find_prop_concat(const ufbx_props *props, const ufbx_string *parts, size_t num_parts);
+
+// Get an element connected to a property.
+ufbx_abi ufbx_element *ufbx_get_prop_element(const ufbx_element *element, const ufbx_prop *prop, ufbx_element_type type);
+
+// Find an element connected to a property by name.
+ufbx_abi ufbx_element *ufbx_find_prop_element_len(const ufbx_element *element, const char *name, size_t name_len, ufbx_element_type type);
+ufbx_abi ufbx_element *ufbx_find_prop_element(const ufbx_element *element, const char *name, ufbx_element_type type);
+
+// Find any element of type `type` in `scene` by `name`.
+// For example if you want to find `ufbx_material` named `Mat`:
+// (ufbx_material*)ufbx_find_element(scene, UFBX_ELEMENT_MATERIAL, "Mat");
+ufbx_abi ufbx_element *ufbx_find_element_len(const ufbx_scene *scene, ufbx_element_type type, const char *name, size_t name_len);
+ufbx_abi ufbx_element *ufbx_find_element(const ufbx_scene *scene, ufbx_element_type type, const char *name);
+
+// Find node in `scene` by `name` (shorthand for `ufbx_find_element(UFBX_ELEMENT_NODE)`).
+ufbx_abi ufbx_node *ufbx_find_node_len(const ufbx_scene *scene, const char *name, size_t name_len);
+ufbx_abi ufbx_node *ufbx_find_node(const ufbx_scene *scene, const char *name);
+
+// Find an animation stack in `scene` by `name` (shorthand for `ufbx_find_element(UFBX_ELEMENT_ANIM_STACK)`)
+ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack_len(const ufbx_scene *scene, const char *name, size_t name_len);
+ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack(const ufbx_scene *scene, const char *name);
+
+// Find a material in `scene` by `name` (shorthand for `ufbx_find_element(UFBX_ELEMENT_MATERIAL)`).
+ufbx_abi ufbx_material *ufbx_find_material_len(const ufbx_scene *scene, const char *name, size_t name_len);
+ufbx_abi ufbx_material *ufbx_find_material(const ufbx_scene *scene, const char *name);
+
+// Find a single animated property `prop` of `element` in `layer`.
+// Returns `NULL` if not found.
+ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop_len(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop, size_t prop_len);
+ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop);
+
+// Find all animated properties of `element` in `layer`.
+ufbx_abi ufbx_anim_prop_list ufbx_find_anim_props(const ufbx_anim_layer *layer, const ufbx_element *element);
+
+// Get a matrix that transforms normals in the same way as Autodesk software.
+// NOTE: The resulting normals are slightly incorrect as this function deliberately
+// inverts geometric transformation wrong. For better results use
+// `ufbx_matrix_for_normals(&node->geometry_to_world)`.
+ufbx_abi ufbx_matrix ufbx_get_compatible_matrix_for_normals(const ufbx_node *node);
+
+// Utility
+
+// Decompress a DEFLATE compressed buffer.
+// Returns the decompressed size or a negative error code (see source for details).
+// NOTE: You must supply a valid `retain` with `ufbx_inflate_retain.initialized == false`
+// but the rest can be uninitialized.
+ufbx_abi ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain);
+
+// Same as `ufbx_open_file()` but compatible with the callback in `ufbx_open_file_fn`.
+// The `user` parameter is actually not used here.
+ufbx_abi bool ufbx_default_open_file(void *user, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_info *info);
+
+// Open a `ufbx_stream` from a file.
+// Use `path_len == SIZE_MAX` for NULL terminated string.
+ufbx_abi bool ufbx_open_file(ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error);
+ufbx_unsafe ufbx_abi bool ufbx_open_file_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error);
+
+// NOTE: Uses the default ufbx allocator!
+ufbx_abi bool ufbx_open_memory(ufbx_stream *stream, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error);
+ufbx_unsafe ufbx_abi bool ufbx_open_memory_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error);
+
+// Animation evaluation
+
+// Evaluate a single animation `curve` at a `time`.
+// Returns `default_value` only if `curve == NULL` or it has no keyframes.
+ufbx_abi ufbx_real ufbx_evaluate_curve(const ufbx_anim_curve *curve, double time, ufbx_real default_value);
+ufbx_abi ufbx_real ufbx_evaluate_curve_flags(const ufbx_anim_curve *curve, double time, ufbx_real default_value, uint32_t flags);
+
+// Evaluate a value from bundled animation curves.
+ufbx_abi ufbx_real ufbx_evaluate_anim_value_real(const ufbx_anim_value *anim_value, double time);
+ufbx_abi ufbx_vec3 ufbx_evaluate_anim_value_vec3(const ufbx_anim_value *anim_value, double time);
+ufbx_abi ufbx_real ufbx_evaluate_anim_value_real_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags);
+ufbx_abi ufbx_vec3 ufbx_evaluate_anim_value_vec3_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags);
+
+// Evaluate an animated property `name` from `element` at `time`.
+// NOTE: If the property is not found it will have the flag `UFBX_PROP_FLAG_NOT_FOUND`.
+ufbx_abi ufbx_prop ufbx_evaluate_prop_len(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time);
+ufbx_abi ufbx_prop ufbx_evaluate_prop(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time);
+ufbx_abi ufbx_prop ufbx_evaluate_prop_flags_len(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time, uint32_t flags);
+ufbx_abi ufbx_prop ufbx_evaluate_prop_flags(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags);
+
+// Evaluate all _animated_ properties of `element`.
+// HINT: This function returns an `ufbx_props` structure with the original properties as
+// `ufbx_props.defaults`. This lets you use `ufbx_find_prop/value()` for the results.
+ufbx_abi ufbx_props ufbx_evaluate_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size);
+ufbx_abi ufbx_props ufbx_evaluate_props_flags(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size, uint32_t flags);
+
+// Flags to control `ufbx_evaluate_transform_flags()`.
+typedef enum ufbx_transform_flags UFBX_FLAG_REPR {
+
+ // Ignore parent scale helper.
+ UFBX_TRANSFORM_FLAG_IGNORE_SCALE_HELPER = 0x1,
+
+ // Ignore componentwise scale.
+ // Note that if you don't specify this, ufbx will have to potentially
+ // evaluate the entire parent chain in the worst case.
+ UFBX_TRANSFORM_FLAG_IGNORE_COMPONENTWISE_SCALE = 0x2,
+
+ // Require explicit components
+ UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES = 0x4,
+
+ // If `UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES`: Evaluate `ufbx_transform.translation`.
+ UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION = 0x10,
+ // If `UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES`: Evaluate `ufbx_transform.rotation`.
+ UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION = 0x20,
+ // If `UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES`: Evaluate `ufbx_transform.scale`.
+ UFBX_TRANSFORM_FLAG_INCLUDE_SCALE = 0x40,
+
+ // Do not extrapolate keyframes.
+ // See `UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION`.
+ UFBX_TRANSFORM_FLAG_NO_EXTRAPOLATION = 0x80,
+
+ UFBX_FLAG_FORCE_WIDTH(UFBX_TRANSFORM_FLAGS)
+} ufbx_transform_flags;
+
+// Evaluate the animated transform of a node given a time.
+// The returned transform is the local transform of the node (ie. relative to the parent),
+// comparable to `ufbx_node.local_transform`.
+ufbx_abi ufbx_transform ufbx_evaluate_transform(const ufbx_anim *anim, const ufbx_node *node, double time);
+ufbx_abi ufbx_transform ufbx_evaluate_transform_flags(const ufbx_anim *anim, const ufbx_node *node, double time, uint32_t flags);
+
+// Evaluate the blend shape weight of a blend channel.
+// NOTE: Return value uses `1.0` for full weight, instead of `100.0` that the internal property `UFBX_Weight` uses.
+ufbx_abi ufbx_real ufbx_evaluate_blend_weight(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time);
+ufbx_abi ufbx_real ufbx_evaluate_blend_weight_flags(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time, uint32_t flags);
+
+// Evaluate the whole `scene` at a specific `time` in the animation `anim`.
+// The returned scene behaves as if it had been exported at a specific time
+// in the specified animation, except that animated elements' properties contain
+// only the animated values, the original ones are in `props->defaults`.
+//
+// NOTE: The returned scene refers to the original `scene` so the original
+// scene cannot be freed until all evaluated scenes are freed.
+ufbx_abi ufbx_scene *ufbx_evaluate_scene(const ufbx_scene *scene, const ufbx_anim *anim, double time, const ufbx_evaluate_opts *opts, ufbx_error *error);
+
+// Create a custom animation descriptor.
+// `ufbx_anim_opts` is used to specify animation layers and weights.
+// HINT: You can also leave `ufbx_anim_opts.layer_ids[]` empty and only specify
+// overrides to evaluate the scene with different properties or local transforms.
+ufbx_abi ufbx_anim *ufbx_create_anim(const ufbx_scene *scene, const ufbx_anim_opts *opts, ufbx_error *error);
+
+// Free an animation returned by `ufbx_create_anim()`.
+ufbx_abi void ufbx_free_anim(ufbx_anim *anim);
+
+// Increase the animation reference count.
+ufbx_abi void ufbx_retain_anim(ufbx_anim *anim);
+
+// Animation baking
+
+// "Bake" an animation to linearly interpolated keyframes.
+// Composites the FBX transformation chain into quaternion rotations.
+ufbx_abi ufbx_baked_anim *ufbx_bake_anim(const ufbx_scene *scene, const ufbx_anim *anim, const ufbx_bake_opts *opts, ufbx_error *error);
+
+ufbx_abi void ufbx_retain_baked_anim(ufbx_baked_anim *bake);
+ufbx_abi void ufbx_free_baked_anim(ufbx_baked_anim *bake);
+
+ufbx_abi ufbx_baked_node *ufbx_find_baked_node_by_typed_id(ufbx_baked_anim *bake, uint32_t typed_id);
+ufbx_abi ufbx_baked_node *ufbx_find_baked_node(ufbx_baked_anim *bake, ufbx_node *node);
+
+ufbx_abi ufbx_baked_element *ufbx_find_baked_element_by_element_id(ufbx_baked_anim *bake, uint32_t element_id);
+ufbx_abi ufbx_baked_element *ufbx_find_baked_element(ufbx_baked_anim *bake, ufbx_element *element);
+
+// Evaluate baked animation `keyframes` at `time`.
+// Internally linearly interpolates between two adjacent keyframes.
+// Handles stepped tangents cleanly, which is not strictly necessary for custom interpolation.
+ufbx_abi ufbx_vec3 ufbx_evaluate_baked_vec3(ufbx_baked_vec3_list keyframes, double time);
+
+// Evaluate baked animation `keyframes` at `time`.
+// Internally spherically interpolates (`ufbx_quat_slerp()`) between two adjacent keyframes.
+// Handles stepped tangents cleanly, which is not strictly necessary for custom interpolation.
+ufbx_abi ufbx_quat ufbx_evaluate_baked_quat(ufbx_baked_quat_list keyframes, double time);
+
+// Poses
+
+// Retrieve the bone pose for `node`.
+// Returns `NULL` if the pose does not contain `node`.
+ufbx_abi ufbx_bone_pose *ufbx_get_bone_pose(const ufbx_pose *pose, const ufbx_node *node);
+
+// Materials
+
+// Find a texture for a given material FBX property.
+ufbx_abi ufbx_texture *ufbx_find_prop_texture_len(const ufbx_material *material, const char *name, size_t name_len);
+ufbx_abi ufbx_texture *ufbx_find_prop_texture(const ufbx_material *material, const char *name);
+
+// Find a texture for a given shader property.
+ufbx_abi ufbx_string ufbx_find_shader_prop_len(const ufbx_shader *shader, const char *name, size_t name_len);
+ufbx_abi ufbx_string ufbx_find_shader_prop(const ufbx_shader *shader, const char *name);
+
+// Map from a shader property to material property.
+ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings_len(const ufbx_shader *shader, const char *name, size_t name_len);
+ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings(const ufbx_shader *shader, const char *name);
+
+// Find an input in a shader texture.
+ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input_len(const ufbx_shader_texture *shader, const char *name, size_t name_len);
+ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input(const ufbx_shader_texture *shader, const char *name);
+
+// Math
+
+// Returns `true` if `axes` forms a valid coordinate space.
+ufbx_abi bool ufbx_coordinate_axes_valid(ufbx_coordinate_axes axes);
+
+// Vector math utility functions.
+ufbx_abi ufbx_vec3 ufbx_vec3_normalize(ufbx_vec3 v);
+
+// Quaternion math utility functions.
+ufbx_abi ufbx_real ufbx_quat_dot(ufbx_quat a, ufbx_quat b);
+ufbx_abi ufbx_quat ufbx_quat_mul(ufbx_quat a, ufbx_quat b);
+ufbx_abi ufbx_quat ufbx_quat_normalize(ufbx_quat q);
+ufbx_abi ufbx_quat ufbx_quat_fix_antipodal(ufbx_quat q, ufbx_quat reference);
+ufbx_abi ufbx_quat ufbx_quat_slerp(ufbx_quat a, ufbx_quat b, ufbx_real t);
+ufbx_abi ufbx_vec3 ufbx_quat_rotate_vec3(ufbx_quat q, ufbx_vec3 v);
+ufbx_abi ufbx_vec3 ufbx_quat_to_euler(ufbx_quat q, ufbx_rotation_order order);
+ufbx_abi ufbx_quat ufbx_euler_to_quat(ufbx_vec3 v, ufbx_rotation_order order);
+
+// Matrix math utility functions.
+ufbx_abi ufbx_matrix ufbx_matrix_mul(const ufbx_matrix *a, const ufbx_matrix *b);
+ufbx_abi ufbx_real ufbx_matrix_determinant(const ufbx_matrix *m);
+ufbx_abi ufbx_matrix ufbx_matrix_invert(const ufbx_matrix *m);
+
+// Get a matrix that can be used to transform geometry normals.
+// NOTE: You must normalize the normals after transforming them with this matrix,
+// eg. using `ufbx_vec3_normalize()`.
+// NOTE: This function flips the normals if the determinant is negative.
+ufbx_abi ufbx_matrix ufbx_matrix_for_normals(const ufbx_matrix *m);
+
+// Matrix transformation utilities.
+ufbx_abi ufbx_vec3 ufbx_transform_position(const ufbx_matrix *m, ufbx_vec3 v);
+ufbx_abi ufbx_vec3 ufbx_transform_direction(const ufbx_matrix *m, ufbx_vec3 v);
+
+// Conversions between `ufbx_matrix` and `ufbx_transform`.
+ufbx_abi ufbx_matrix ufbx_transform_to_matrix(const ufbx_transform *t);
+ufbx_abi ufbx_transform ufbx_matrix_to_transform(const ufbx_matrix *m);
+
+// Skinning
+
+// Get a matrix representing the deformation for a single vertex.
+// Returns `fallback` if the vertex is not skinned.
+ufbx_abi ufbx_matrix ufbx_catch_get_skin_vertex_matrix(ufbx_panic *panic, const ufbx_skin_deformer *skin, size_t vertex, const ufbx_matrix *fallback);
+ufbx_inline ufbx_matrix ufbx_get_skin_vertex_matrix(const ufbx_skin_deformer *skin, size_t vertex, const ufbx_matrix *fallback) {
+ return ufbx_catch_get_skin_vertex_matrix(NULL, skin, vertex, fallback);
+}
+
+// Resolve the index into `ufbx_blend_shape.position_offsets[]` given a vertex.
+// Returns `UFBX_NO_INDEX` if the vertex is not included in the blend shape.
+ufbx_abi uint32_t ufbx_get_blend_shape_offset_index(const ufbx_blend_shape *shape, size_t vertex);
+
+// Get the offset for a given vertex in the blend shape.
+// Returns `ufbx_zero_vec3` if the vertex is not a included in the blend shape.
+ufbx_abi ufbx_vec3 ufbx_get_blend_shape_vertex_offset(const ufbx_blend_shape *shape, size_t vertex);
+
+// Get the _current_ blend offset given a blend deformer.
+// NOTE: This depends on the current animated blend weight of the deformer.
+ufbx_abi ufbx_vec3 ufbx_get_blend_vertex_offset(const ufbx_blend_deformer *blend, size_t vertex);
+
+// Apply the blend shape with `weight` to given vertices.
+ufbx_abi void ufbx_add_blend_shape_vertex_offsets(const ufbx_blend_shape *shape, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight);
+
+// Apply the blend deformer with `weight` to given vertices.
+// NOTE: This depends on the current animated blend weight of the deformer.
+ufbx_abi void ufbx_add_blend_vertex_offsets(const ufbx_blend_deformer *blend, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight);
+
+// Curves/surfaces
+
+// Low-level utility to evaluate NURBS the basis functions.
+ufbx_abi size_t ufbx_evaluate_nurbs_basis(const ufbx_nurbs_basis *basis, ufbx_real u, ufbx_real *weights, size_t num_weights, ufbx_real *derivatives, size_t num_derivatives);
+
+// Evaluate a point on a NURBS curve given the parameter `u`.
+ufbx_abi ufbx_curve_point ufbx_evaluate_nurbs_curve(const ufbx_nurbs_curve *curve, ufbx_real u);
+
+// Evaluate a point on a NURBS surface given the parameter `u` and `v`.
+ufbx_abi ufbx_surface_point ufbx_evaluate_nurbs_surface(const ufbx_nurbs_surface *surface, ufbx_real u, ufbx_real v);
+
+// Tessellate a NURBS curve into a polyline.
+ufbx_abi ufbx_line_curve *ufbx_tessellate_nurbs_curve(const ufbx_nurbs_curve *curve, const ufbx_tessellate_curve_opts *opts, ufbx_error *error);
+
+// Tessellate a NURBS surface into a mesh.
+ufbx_abi ufbx_mesh *ufbx_tessellate_nurbs_surface(const ufbx_nurbs_surface *surface, const ufbx_tessellate_surface_opts *opts, ufbx_error *error);
+
+// Free a line returned by `ufbx_tessellate_nurbs_curve()`.
+ufbx_abi void ufbx_free_line_curve(ufbx_line_curve *curve);
+
+// Increase the refcount of the line.
+ufbx_abi void ufbx_retain_line_curve(ufbx_line_curve *curve);
+
+// Mesh Topology
+
+// Find the face that contains a given `index`.
+// Returns `UFBX_NO_INDEX` if out of bounds.
+ufbx_abi uint32_t ufbx_find_face_index(ufbx_mesh *mesh, size_t index);
+
+// Triangulate a mesh face, returning the number of triangles.
+// NOTE: You need to space for `(face.num_indices - 2) * 3 - 1` indices!
+// HINT: Using `ufbx_mesh.max_face_triangles * 3` is always safe.
+ufbx_abi uint32_t ufbx_catch_triangulate_face(ufbx_panic *panic, uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face);
+ufbx_abi uint32_t ufbx_triangulate_face(uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face);
+
+// Generate the half-edge representation of `mesh` to `topo[mesh->num_indices]`
+ufbx_abi void ufbx_catch_compute_topology(ufbx_panic *panic, const ufbx_mesh *mesh, ufbx_topo_edge *topo, size_t num_topo);
+ufbx_abi void ufbx_compute_topology(const ufbx_mesh *mesh, ufbx_topo_edge *topo, size_t num_topo);
+
+// Get the next/previous edge around a vertex
+// NOTE: Does not return the half-edge on the opposite side (ie. `topo[index].twin`)
+
+// Get the next half-edge in `topo`.
+ufbx_abi uint32_t ufbx_catch_topo_next_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index);
+ufbx_abi uint32_t ufbx_topo_next_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index);
+
+// Get the previous half-edge in `topo`.
+ufbx_abi uint32_t ufbx_catch_topo_prev_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index);
+ufbx_abi uint32_t ufbx_topo_prev_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index);
+
+// Calculate a normal for a given face.
+// The returned normal is weighted by face area.
+ufbx_abi ufbx_vec3 ufbx_catch_get_weighted_face_normal(ufbx_panic *panic, const ufbx_vertex_vec3 *positions, ufbx_face face);
+ufbx_abi ufbx_vec3 ufbx_get_weighted_face_normal(const ufbx_vertex_vec3 *positions, ufbx_face face);
+
+// Generate indices for normals from the topology.
+// Respects smoothing groups.
+ufbx_abi size_t ufbx_catch_generate_normal_mapping(ufbx_panic *panic, const ufbx_mesh *mesh,
+ const ufbx_topo_edge *topo, size_t num_topo,
+ uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth);
+ufbx_abi size_t ufbx_generate_normal_mapping(const ufbx_mesh *mesh,
+ const ufbx_topo_edge *topo, size_t num_topo,
+ uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth);
+
+// Compute normals given normal indices.
+// You can use `ufbx_generate_normal_mapping()` to generate the normal indices.
+ufbx_abi void ufbx_catch_compute_normals(ufbx_panic *panic, const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions,
+ const uint32_t *normal_indices, size_t num_normal_indices,
+ ufbx_vec3 *normals, size_t num_normals);
+ufbx_abi void ufbx_compute_normals(const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions,
+ const uint32_t *normal_indices, size_t num_normal_indices,
+ ufbx_vec3 *normals, size_t num_normals);
+
+// Subdivide a mesh using the Catmull-Clark subdivision `level` times.
+ufbx_abi ufbx_mesh *ufbx_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *opts, ufbx_error *error);
+
+// Free a mesh returned from `ufbx_subdivide_mesh()` or `ufbx_tessellate_nurbs_surface()`.
+ufbx_abi void ufbx_free_mesh(ufbx_mesh *mesh);
+
+// Increase the mesh reference count.
+ufbx_abi void ufbx_retain_mesh(ufbx_mesh *mesh);
+
+// Geometry caches
+
+// Load geometry cache information from a file.
+// As geometry caches can be massive, this does not actually read the data, but
+// only seeks through the files to form the metadata.
+ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache(
+ const char *filename,
+ const ufbx_geometry_cache_opts *opts, ufbx_error *error);
+ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache_len(
+ const char *filename, size_t filename_len,
+ const ufbx_geometry_cache_opts *opts, ufbx_error *error);
+
+// Free a geometry cache returned from `ufbx_load_geometry_cache()`.
+ufbx_abi void ufbx_free_geometry_cache(ufbx_geometry_cache *cache);
+// Increase the geometry cache reference count.
+ufbx_abi void ufbx_retain_geometry_cache(ufbx_geometry_cache *cache);
+
+// Read a frame from a geometry cache.
+ufbx_abi size_t ufbx_read_geometry_cache_real(const ufbx_cache_frame *frame, ufbx_real *data, size_t num_data, const ufbx_geometry_cache_data_opts *opts);
+ufbx_abi size_t ufbx_read_geometry_cache_vec3(const ufbx_cache_frame *frame, ufbx_vec3 *data, size_t num_data, const ufbx_geometry_cache_data_opts *opts);
+// Sample the a geometry cache channel, linearly blending between adjacent frames.
+ufbx_abi size_t ufbx_sample_geometry_cache_real(const ufbx_cache_channel *channel, double time, ufbx_real *data, size_t num_data, const ufbx_geometry_cache_data_opts *opts);
+ufbx_abi size_t ufbx_sample_geometry_cache_vec3(const ufbx_cache_channel *channel, double time, ufbx_vec3 *data, size_t num_data, const ufbx_geometry_cache_data_opts *opts);
+
+// DOM
+
+// Find a DOM node given a name.
+ufbx_abi ufbx_dom_node *ufbx_dom_find_len(const ufbx_dom_node *parent, const char *name, size_t name_len);
+ufbx_abi ufbx_dom_node *ufbx_dom_find(const ufbx_dom_node *parent, const char *name);
+
+// Utility
+
+// Generate an index buffer for a flat vertex buffer.
+// `streams` specifies one or more vertex data arrays, each stream must contain `num_indices` vertices.
+// This function compacts the data within `streams` in-place, writing the deduplicated indices to `indices`.
+ufbx_abi size_t ufbx_generate_indices(const ufbx_vertex_stream *streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error);
+
+// Thread pool
+
+// Run a single thread pool task.
+// See `ufbx_thread_pool_run_fn` for more information.
+ufbx_unsafe ufbx_abi void ufbx_thread_pool_run_task(ufbx_thread_pool_context ctx, uint32_t index);
+
+// Get or set an arbitrary user pointer for the thread pool context.
+// `ufbx_thread_pool_get_user_ptr()` returns `NULL` if unset.
+ufbx_unsafe ufbx_abi void ufbx_thread_pool_set_user_ptr(ufbx_thread_pool_context ctx, void *user_ptr);
+ufbx_unsafe ufbx_abi void *ufbx_thread_pool_get_user_ptr(ufbx_thread_pool_context ctx);
+
+// -- Inline API
+
+// Utility functions for reading geometry data for a single index.
+ufbx_abi ufbx_real ufbx_catch_get_vertex_real(ufbx_panic *panic, const ufbx_vertex_real *v, size_t index);
+ufbx_abi ufbx_vec2 ufbx_catch_get_vertex_vec2(ufbx_panic *panic, const ufbx_vertex_vec2 *v, size_t index);
+ufbx_abi ufbx_vec3 ufbx_catch_get_vertex_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index);
+ufbx_abi ufbx_vec4 ufbx_catch_get_vertex_vec4(ufbx_panic *panic, const ufbx_vertex_vec4 *v, size_t index);
+
+// Utility functions for reading geometry data for a single index.
+ufbx_inline ufbx_real ufbx_get_vertex_real(const ufbx_vertex_real *v, size_t index) { ufbx_assert(index < v->indices.count); return v->values.data[(int32_t)v->indices.data[index]]; }
+ufbx_inline ufbx_vec2 ufbx_get_vertex_vec2(const ufbx_vertex_vec2 *v, size_t index) { ufbx_assert(index < v->indices.count); return v->values.data[(int32_t)v->indices.data[index]]; }
+ufbx_inline ufbx_vec3 ufbx_get_vertex_vec3(const ufbx_vertex_vec3 *v, size_t index) { ufbx_assert(index < v->indices.count); return v->values.data[(int32_t)v->indices.data[index]]; }
+ufbx_inline ufbx_vec4 ufbx_get_vertex_vec4(const ufbx_vertex_vec4 *v, size_t index) { ufbx_assert(index < v->indices.count); return v->values.data[(int32_t)v->indices.data[index]]; }
+
+ufbx_abi ufbx_real ufbx_catch_get_vertex_w_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index);
+ufbx_inline ufbx_real ufbx_get_vertex_w_vec3(const ufbx_vertex_vec3 *v, size_t index) { ufbx_assert(index < v->indices.count); return v->values_w.count > 0 ? v->values_w.data[(int32_t)v->indices.data[index]] : 0.0f; }
+
+// Functions for converting an untyped `ufbx_element` to a concrete type.
+// Returns `NULL` if the element is not that type.
+ufbx_abi ufbx_unknown *ufbx_as_unknown(const ufbx_element *element);
+ufbx_abi ufbx_node *ufbx_as_node(const ufbx_element *element);
+ufbx_abi ufbx_mesh *ufbx_as_mesh(const ufbx_element *element);
+ufbx_abi ufbx_light *ufbx_as_light(const ufbx_element *element);
+ufbx_abi ufbx_camera *ufbx_as_camera(const ufbx_element *element);
+ufbx_abi ufbx_bone *ufbx_as_bone(const ufbx_element *element);
+ufbx_abi ufbx_empty *ufbx_as_empty(const ufbx_element *element);
+ufbx_abi ufbx_line_curve *ufbx_as_line_curve(const ufbx_element *element);
+ufbx_abi ufbx_nurbs_curve *ufbx_as_nurbs_curve(const ufbx_element *element);
+ufbx_abi ufbx_nurbs_surface *ufbx_as_nurbs_surface(const ufbx_element *element);
+ufbx_abi ufbx_nurbs_trim_surface *ufbx_as_nurbs_trim_surface(const ufbx_element *element);
+ufbx_abi ufbx_nurbs_trim_boundary *ufbx_as_nurbs_trim_boundary(const ufbx_element *element);
+ufbx_abi ufbx_procedural_geometry *ufbx_as_procedural_geometry(const ufbx_element *element);
+ufbx_abi ufbx_stereo_camera *ufbx_as_stereo_camera(const ufbx_element *element);
+ufbx_abi ufbx_camera_switcher *ufbx_as_camera_switcher(const ufbx_element *element);
+ufbx_abi ufbx_marker *ufbx_as_marker(const ufbx_element *element);
+ufbx_abi ufbx_lod_group *ufbx_as_lod_group(const ufbx_element *element);
+ufbx_abi ufbx_skin_deformer *ufbx_as_skin_deformer(const ufbx_element *element);
+ufbx_abi ufbx_skin_cluster *ufbx_as_skin_cluster(const ufbx_element *element);
+ufbx_abi ufbx_blend_deformer *ufbx_as_blend_deformer(const ufbx_element *element);
+ufbx_abi ufbx_blend_channel *ufbx_as_blend_channel(const ufbx_element *element);
+ufbx_abi ufbx_blend_shape *ufbx_as_blend_shape(const ufbx_element *element);
+ufbx_abi ufbx_cache_deformer *ufbx_as_cache_deformer(const ufbx_element *element);
+ufbx_abi ufbx_cache_file *ufbx_as_cache_file(const ufbx_element *element);
+ufbx_abi ufbx_material *ufbx_as_material(const ufbx_element *element);
+ufbx_abi ufbx_texture *ufbx_as_texture(const ufbx_element *element);
+ufbx_abi ufbx_video *ufbx_as_video(const ufbx_element *element);
+ufbx_abi ufbx_shader *ufbx_as_shader(const ufbx_element *element);
+ufbx_abi ufbx_shader_binding *ufbx_as_shader_binding(const ufbx_element *element);
+ufbx_abi ufbx_anim_stack *ufbx_as_anim_stack(const ufbx_element *element);
+ufbx_abi ufbx_anim_layer *ufbx_as_anim_layer(const ufbx_element *element);
+ufbx_abi ufbx_anim_value *ufbx_as_anim_value(const ufbx_element *element);
+ufbx_abi ufbx_anim_curve *ufbx_as_anim_curve(const ufbx_element *element);
+ufbx_abi ufbx_display_layer *ufbx_as_display_layer(const ufbx_element *element);
+ufbx_abi ufbx_selection_set *ufbx_as_selection_set(const ufbx_element *element);
+ufbx_abi ufbx_selection_node *ufbx_as_selection_node(const ufbx_element *element);
+ufbx_abi ufbx_character *ufbx_as_character(const ufbx_element *element);
+ufbx_abi ufbx_constraint *ufbx_as_constraint(const ufbx_element *element);
+ufbx_abi ufbx_audio_layer *ufbx_as_audio_layer(const ufbx_element *element);
+ufbx_abi ufbx_audio_clip *ufbx_as_audio_clip(const ufbx_element *element);
+ufbx_abi ufbx_pose *ufbx_as_pose(const ufbx_element *element);
+ufbx_abi ufbx_metadata_object *ufbx_as_metadata_object(const ufbx_element *element);
+
+// Functions for interfacing with DOM lists
+ufbx_abi bool ufbx_dom_is_array(const ufbx_dom_node *node);
+ufbx_abi size_t ufbx_dom_array_size(const ufbx_dom_node *node);
+ufbx_abi ufbx_int32_list ufbx_dom_as_int32_list(const ufbx_dom_node *node);
+ufbx_abi ufbx_int64_list ufbx_dom_as_int64_list(const ufbx_dom_node *node);
+ufbx_abi ufbx_float_list ufbx_dom_as_float_list(const ufbx_dom_node *node);
+ufbx_abi ufbx_double_list ufbx_dom_as_double_list(const ufbx_dom_node *node);
+ufbx_abi ufbx_real_list ufbx_dom_as_real_list(const ufbx_dom_node *node);
+ufbx_abi ufbx_blob_list ufbx_dom_as_blob_list(const ufbx_dom_node *node);
+
+#ifdef __cplusplus
+}
+#endif
+
+// bindgen-disable
+
+#if UFBX_CPP11
+
+struct ufbx_string_view {
+ const char *data;
+ size_t length;
+
+ ufbx_string_view() : data(nullptr), length(0) { }
+ ufbx_string_view(const char *data_, size_t length_) : data(data_), length(length_) { }
+ UFBX_CONVERSION_TO_IMPL(ufbx_string_view)
+};
+
+ufbx_inline ufbx_scene *ufbx_load_file(ufbx_string_view filename, const ufbx_load_opts *opts, ufbx_error *error) { return ufbx_load_file_len(filename.data, filename.length, opts, error); }
+ufbx_inline ufbx_prop *ufbx_find_prop(const ufbx_props *props, ufbx_string_view name) { return ufbx_find_prop_len(props, name.data, name.length); }
+ufbx_inline ufbx_real ufbx_find_real(const ufbx_props *props, ufbx_string_view name, ufbx_real def) { return ufbx_find_real_len(props, name.data, name.length, def); }
+ufbx_inline ufbx_vec3 ufbx_find_vec3(const ufbx_props *props, ufbx_string_view name, ufbx_vec3 def) { return ufbx_find_vec3_len(props, name.data, name.length, def); }
+ufbx_inline int64_t ufbx_find_int(const ufbx_props *props, ufbx_string_view name, int64_t def) { return ufbx_find_int_len(props, name.data, name.length, def); }
+ufbx_inline bool ufbx_find_bool(const ufbx_props *props, ufbx_string_view name, bool def) { return ufbx_find_bool_len(props, name.data, name.length, def); }
+ufbx_inline ufbx_string ufbx_find_string(const ufbx_props *props, ufbx_string_view name, ufbx_string def) { return ufbx_find_string_len(props, name.data, name.length, def); }
+ufbx_inline ufbx_blob ufbx_find_blob(const ufbx_props *props, ufbx_string_view name, ufbx_blob def) { return ufbx_find_blob_len(props, name.data, name.length, def); }
+ufbx_inline ufbx_element *ufbx_find_prop_element(const ufbx_element *element, ufbx_string_view name, ufbx_element_type type) { return ufbx_find_prop_element_len(element, name.data, name.length, type); }
+ufbx_inline ufbx_element *ufbx_find_element(const ufbx_scene *scene, ufbx_element_type type, ufbx_string_view name) { return ufbx_find_element_len(scene, type, name.data, name.length); }
+ufbx_inline ufbx_node *ufbx_find_node(const ufbx_scene *scene, ufbx_string_view name) { return ufbx_find_node_len(scene, name.data, name.length); }
+ufbx_inline ufbx_anim_stack *ufbx_find_anim_stack(const ufbx_scene *scene, ufbx_string_view name) { return ufbx_find_anim_stack_len(scene, name.data, name.length); }
+ufbx_inline ufbx_material *ufbx_find_material(const ufbx_scene *scene, ufbx_string_view name) { return ufbx_find_material_len(scene, name.data, name.length); }
+ufbx_inline ufbx_anim_prop *ufbx_find_anim_prop(const ufbx_anim_layer *layer, const ufbx_element *element, ufbx_string_view prop) { return ufbx_find_anim_prop_len(layer, element, prop.data, prop.length); }
+ufbx_inline ufbx_prop ufbx_evaluate_prop(const ufbx_anim *anim, const ufbx_element *element, ufbx_string_view name, double time) { return ufbx_evaluate_prop_len(anim, element, name.data, name.length, time); }
+ufbx_inline ufbx_texture *ufbx_find_prop_texture(const ufbx_material *material, ufbx_string_view name) { return ufbx_find_prop_texture_len(material, name.data, name.length); }
+ufbx_inline ufbx_string ufbx_find_shader_prop(const ufbx_shader *shader, ufbx_string_view name) { return ufbx_find_shader_prop_len(shader, name.data, name.length); }
+ufbx_inline ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings(const ufbx_shader *shader, ufbx_string_view name) { return ufbx_find_shader_prop_bindings_len(shader, name.data, name.length); }
+ufbx_inline ufbx_shader_texture_input *ufbx_find_shader_texture_input(const ufbx_shader_texture *shader, ufbx_string_view name) { return ufbx_find_shader_texture_input_len(shader, name.data, name.length); }
+ufbx_inline ufbx_geometry_cache *ufbx_load_geometry_cache(ufbx_string_view filename, const ufbx_geometry_cache_opts *opts, ufbx_error *error) { return ufbx_load_geometry_cache_len(filename.data, filename.length, opts, error); }
+ufbx_inline ufbx_dom_node *ufbx_dom_find(const ufbx_dom_node *parent, ufbx_string_view name) { return ufbx_dom_find_len(parent, name.data, name.length); }
+
+#endif
+
+#if UFBX_CPP11
+
+template <typename T>
+struct ufbx_type_traits { enum { valid = 0 }; };
+
+template<> struct ufbx_type_traits<ufbx_scene> {
+ enum { valid = 1 };
+ static void retain(ufbx_scene *ptr) { ufbx_retain_scene(ptr); }
+ static void free(ufbx_scene *ptr) { ufbx_free_scene(ptr); }
+};
+
+template<> struct ufbx_type_traits<ufbx_mesh> {
+ enum { valid = 1 };
+ static void retain(ufbx_mesh *ptr) { ufbx_retain_mesh(ptr); }
+ static void free(ufbx_mesh *ptr) { ufbx_free_mesh(ptr); }
+};
+
+template<> struct ufbx_type_traits<ufbx_line_curve> {
+ enum { valid = 1 };
+ static void retain(ufbx_line_curve *ptr) { ufbx_retain_line_curve(ptr); }
+ static void free(ufbx_line_curve *ptr) { ufbx_free_line_curve(ptr); }
+};
+
+template<> struct ufbx_type_traits<ufbx_geometry_cache> {
+ enum { valid = 1 };
+ static void retain(ufbx_geometry_cache *ptr) { ufbx_retain_geometry_cache(ptr); }
+ static void free(ufbx_geometry_cache *ptr) { ufbx_free_geometry_cache(ptr); }
+};
+
+template<> struct ufbx_type_traits<ufbx_anim> {
+ enum { valid = 1 };
+ static void retain(ufbx_anim *ptr) { ufbx_retain_anim(ptr); }
+ static void free(ufbx_anim *ptr) { ufbx_free_anim(ptr); }
+};
+
+template<> struct ufbx_type_traits<ufbx_baked_anim> {
+ enum { valid = 1 };
+ static void retain(ufbx_baked_anim *ptr) { ufbx_retain_baked_anim(ptr); }
+ static void free(ufbx_baked_anim *ptr) { ufbx_free_baked_anim(ptr); }
+};
+
+class ufbx_deleter {
+public:
+ template <typename T>
+ void operator()(T *ptr) const {
+ static_assert(ufbx_type_traits<T>::valid, "ufbx_deleter() unsupported for type");
+ ufbx_type_traits<T>::free(ptr);
+ }
+};
+
+// RAII wrapper over refcounted ufbx types.
+
+// Behaves like `std::unique_ptr<T>`.
+template <typename T>
+class ufbx_unique_ptr {
+ T *ptr;
+ using traits = ufbx_type_traits<T>;
+ static_assert(ufbx_type_traits<T>::valid, "ufbx_unique_ptr unsupported for type");
+public:
+ ufbx_unique_ptr() noexcept : ptr(nullptr) { }
+ explicit ufbx_unique_ptr(T *ptr_) noexcept : ptr(ptr_) { }
+ ufbx_unique_ptr(ufbx_unique_ptr &&ref) noexcept : ptr(ref.ptr) { ref.ptr = nullptr; }
+ ~ufbx_unique_ptr() { traits::free(ptr); }
+
+ ufbx_unique_ptr &operator=(ufbx_unique_ptr &&ref) noexcept {
+ if (&ref == this) return *this;
+ ptr = ref.ptr;
+ ref.ptr = nullptr;
+ return *this;
+ }
+
+ void reset(T *new_ptr=nullptr) noexcept {
+ traits::free(ptr);
+ ptr = new_ptr;
+ }
+
+ void swap(ufbx_unique_ptr &ref) noexcept {
+ T *tmp = ptr;
+ ptr = ref.ptr;
+ ref.ptr = tmp;
+ }
+
+ T &operator*() const noexcept { return *ptr; }
+ T *operator->() const noexcept { return ptr; }
+ T *get() const noexcept { return ptr; }
+ explicit operator bool() const noexcept { return ptr != nullptr; }
+};
+
+// Behaves like `std::shared_ptr<T>` except uses ufbx's internal reference counting,
+// so it is half the size of a standard `shared_ptr` but might be marginally slower.
+template <typename T>
+class ufbx_shared_ptr {
+ T *ptr;
+ using traits = ufbx_type_traits<T>;
+ static_assert(ufbx_type_traits<T>::valid, "ufbx_shared_ptr unsupported for type");
+public:
+
+ ufbx_shared_ptr() noexcept : ptr(nullptr) { }
+ explicit ufbx_shared_ptr(T *ptr_) noexcept : ptr(ptr_) { }
+ ufbx_shared_ptr(const ufbx_shared_ptr &ref) noexcept : ptr(ref.ptr) { traits::retain(ref.ptr); }
+ ufbx_shared_ptr(ufbx_shared_ptr &&ref) noexcept : ptr(ref.ptr) { ref.ptr = nullptr; }
+ ~ufbx_shared_ptr() { traits::free(ptr); }
+
+ ufbx_shared_ptr &operator=(const ufbx_shared_ptr &ref) noexcept {
+ if (&ref == this) return *this;
+ traits::free(ptr);
+ traits::retain(ref.ptr);
+ ptr = ref.ptr;
+ return *this;
+ }
+
+ ufbx_shared_ptr &operator=(ufbx_shared_ptr &&ref) noexcept {
+ if (&ref == this) return *this;
+ ptr = ref.ptr;
+ ref.ptr = nullptr;
+ return *this;
+ }
+
+ void reset(T *new_ptr=nullptr) noexcept {
+ traits::free(ptr);
+ ptr = new_ptr;
+ }
+
+ void swap(ufbx_shared_ptr &ref) noexcept {
+ T *tmp = ptr;
+ ptr = ref.ptr;
+ ref.ptr = tmp;
+ }
+
+ T &operator*() const noexcept { return *ptr; }
+ T *operator->() const noexcept { return ptr; }
+ T *get() const noexcept { return ptr; }
+ explicit operator bool() const noexcept { return ptr != nullptr; }
+};
+
+#endif
+// bindgen-enable
+
+// -- Properties
+
+// Names of common properties in `ufbx_props`.
+// Some of these differ from ufbx interpretations.
+
+// Local translation.
+// Used by: `ufbx_node`
+#define UFBX_Lcl_Translation "Lcl Translation"
+
+// Local rotation expressed in Euler degrees.
+// Used by: `ufbx_node`
+// The rotation order is defined by the `UFBX_RotationOrder` property.
+#define UFBX_Lcl_Rotation "Lcl Rotation"
+
+// Local scaling factor, 3D vector.
+// Used by: `ufbx_node`
+#define UFBX_Lcl_Scaling "Lcl Scaling"
+
+// Euler rotation interpretation, used by `UFBX_Lcl_Rotation`.
+// Used by: `ufbx_node`, enum value `ufbx_rotation_order`.
+#define UFBX_RotationOrder "RotationOrder"
+
+// Scaling pivot: point around which scaling is performed.
+// Used by: `ufbx_node`.
+#define UFBX_ScalingPivot "ScalingPivot"
+
+// Scaling pivot: point around which rotation is performed.
+// Used by: `ufbx_node`.
+#define UFBX_RotationPivot "RotationPivot"
+
+// Scaling offset: translation added after scaling is performed.
+// Used by: `ufbx_node`.
+#define UFBX_ScalingOffset "ScalingOffset"
+
+// Rotation offset: translation added after rotation is performed.
+// Used by: `ufbx_node`.
+#define UFBX_RotationOffset "RotationOffset"
+
+// Pre-rotation: Rotation applied _after_ `UFBX_Lcl_Rotation`.
+// Used by: `ufbx_node`.
+// Affected by `UFBX_RotationPivot` but not `UFBX_RotationOrder`.
+#define UFBX_PreRotation "PreRotation"
+
+// Post-rotation: Rotation applied _before_ `UFBX_Lcl_Rotation`.
+// Used by: `ufbx_node`.
+// Affected by `UFBX_RotationPivot` but not `UFBX_RotationOrder`.
+#define UFBX_PostRotation "PostRotation"
+
+// Controls whether the node should be displayed or not.
+// Used by: `ufbx_node`.
+#define UFBX_Visibility "Visibility"
+
+// Weight of an animation layer in percentage (100.0 being full).
+// Used by: `ufbx_anim_layer`.
+#define UFBX_Weight "Weight"
+
+// Blend shape deformation weight (100.0 being full).
+// Used by: `ufbx_blend_channel`.
+#define UFBX_DeformPercent "DeformPercent"
+
+#if defined(_MSC_VER)
+ #pragma warning(pop)
+#elif defined(__clang__)
+ #pragma clang diagnostic pop
+#elif defined(__GNUC__)
+ #pragma GCC diagnostic pop
+#endif
+
+#endif
diff --git a/website/fonts/Inter-Regular.ttf b/website/fonts/Inter-Regular.ttf
new file mode 100644
index 00000000..b7aaca8d
Binary files /dev/null and b/website/fonts/Inter-Regular.ttf differ
diff --git a/website/fonts/Inter-SemiBold.ttf b/website/fonts/Inter-SemiBold.ttf
new file mode 100644
index 00000000..47f8ab1d
Binary files /dev/null and b/website/fonts/Inter-SemiBold.ttf differ
diff --git a/website/fonts/OFL.txt b/website/fonts/OFL.txt
new file mode 100644
index 00000000..9b2ca37b
--- /dev/null
+++ b/website/fonts/OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/website/img/favicon-64.png b/website/img/favicon-64.png
new file mode 100644
index 00000000..1495e49a
Binary files /dev/null and b/website/img/favicon-64.png differ
diff --git a/website/img/icon-256.png b/website/img/icon-256.png
new file mode 100644
index 00000000..d0307194
Binary files /dev/null and b/website/img/icon-256.png differ
diff --git a/website/img/logo.svg b/website/img/logo.svg
new file mode 100644
index 00000000..d22e2aad
--- /dev/null
+++ b/website/img/logo.svg
@@ -0,0 +1,39 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="#23232a"/>
+ <stop offset="1" stop-color="#0e0e11"/>
+ </linearGradient>
+ <radialGradient id="clay" cx="0.36" cy="0.32" r="0.78">
+ <stop offset="0" stop-color="#ffd2a6"/>
+ <stop offset="0.38" stop-color="#f6a05a"/>
+ <stop offset="0.8" stop-color="#d5602a"/>
+ <stop offset="1" stop-color="#a3401b"/>
+ </radialGradient>
+ <radialGradient id="glow" cx="0.5" cy="0.5" r="0.5">
+ <stop offset="0" stop-color="#f28c3c" stop-opacity="0.45"/>
+ <stop offset="1" stop-color="#f28c3c" stop-opacity="0"/>
+ </radialGradient>
+ <linearGradient id="groove" x1="0" y1="0" x2="1" y2="0">
+ <stop offset="0" stop-color="#7a2d10" stop-opacity="0"/>
+ <stop offset="0.25" stop-color="#7a2d10" stop-opacity="0.85"/>
+ <stop offset="0.75" stop-color="#7a2d10" stop-opacity="0.85"/>
+ <stop offset="1" stop-color="#7a2d10" stop-opacity="0"/>
+ </linearGradient>
+ </defs>
+ <rect x="16" y="16" width="480" height="480" rx="108" fill="url(#bg)"/>
+ <rect x="16.5" y="16.5" width="479" height="479" rx="107.5" fill="none" stroke="#ffffff" stroke-opacity="0.07" stroke-width="1"/>
+ <circle cx="256" cy="276" r="190" fill="url(#glow)"/>
+ <!-- the clay form -->
+ <path d="M256 104c92 0 150 66 150 160 0 86-62 150-150 150s-150-64-150-150c0-94 58-160 150-160z" fill="url(#clay)"/>
+ <!-- a carved "S" stroke: the brush mark and the initial -->
+ <path d="M318 176c-22-20-46-28-72-26-36 3-60 26-56 56 4 28 30 40 64 50 34 10 62 24 64 56 3 34-26 58-64 60-30 2-54-8-74-28"
+ fill="none" stroke="#6f2a0f" stroke-opacity="0.9" stroke-width="30" stroke-linecap="round"/>
+ <path d="M318 176c-22-20-46-28-72-26-36 3-60 26-56 56 4 28 30 40 64 50 34 10 62 24 64 56 3 34-26 58-64 60-30 2-54-8-74-28"
+ fill="none" stroke="#3f1606" stroke-opacity="0.55" stroke-width="12" stroke-linecap="round" transform="translate(3 4)"/>
+ <path d="M322 168c-22-20-46-29-74-27-38 3-64 28-60 60" fill="none" stroke="#ffe6cc" stroke-opacity="0.6"
+ stroke-width="5" stroke-linecap="round" transform="translate(-6 -8)"/>
+ <!-- forge spark -->
+ <path d="M392 92l9 29 29 9-29 9-9 29-9-29-29-9 29-9z" fill="#ffd9ad"/>
+ <circle cx="392" cy="130" r="22" fill="#ffd9ad" opacity="0.18"/>
+</svg>
diff --git a/website/img/social-preview.png b/website/img/social-preview.png
new file mode 100644
index 00000000..7a0ffaea
Binary files /dev/null and b/website/img/social-preview.png differ
diff --git a/website/img/teddy-3d.png b/website/img/teddy-3d.png
new file mode 100644
index 00000000..800d6fbe
Binary files /dev/null and b/website/img/teddy-3d.png differ
diff --git a/website/img/teddy-sketch.png b/website/img/teddy-sketch.png
new file mode 100644
index 00000000..d1b02320
Binary files /dev/null and b/website/img/teddy-sketch.png differ
diff --git a/website/index.html b/website/index.html
new file mode 100644
index 00000000..9f9d35c4
--- /dev/null
+++ b/website/index.html
@@ -0,0 +1,269 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>SculptForge</title>
+ <meta name="description" content="Free, open-source digital sculpting for Linux, macOS and Windows, with game-ready pipelines, Send to Unreal, Gaussian splats, OpenUSD and bring-your-own AI.">
+ <meta name="theme-color" content="#111114">
+ <link rel="icon" type="image/png" href="img/favicon-64.png">
+ <link rel="apple-touch-icon" href="img/icon-256.png">
+ <meta property="og:type" content="website">
+ <meta property="og:title" content="SculptForge - open-source digital sculpting">
+ <meta property="og:description" content="Sculpt like you already do. Ship to Unreal, glTF and USD. Bring your own AI - even fully local.">
+ <meta property="og:image" content="https://islandmed.github.io/SculptForge/img/social-preview.png">
+ <meta property="og:url" content="https://islandmed.github.io/SculptForge/">
+ <meta name="twitter:card" content="summary_large_image">
+ <link rel="stylesheet" href="style.css">
+</head>
+<body>
+ <header class="nav">
+ <div class="wrap nav-inner">
+ <a class="brand" href="#top"><img src="img/logo.svg" alt="" width="34" height="34"><span>SculptForge</span></a>
+ <nav aria-label="Main">
+ <a href="#features">Features</a>
+ <a href="#demos">Demos</a>
+ <a href="#download">Download</a>
+ <a href="https://github.com/islandmed/SculptForge#readme">Docs</a>
+ <a class="gh" href="https://github.com/islandmed/SculptForge">GitHub</a>
+ </nav>
+ </div>
+ </header>
+
+ <main id="top">
+ <section class="hero">
+ <div class="wrap hero-grid">
+ <div class="hero-copy">
+ <p class="eyebrow">Free &amp; open source · GPL-3.0</p>
+ <h1><span class="nowrap">Sculpt it.</span> <span class="nowrap">Forge it.</span><br><span class="accent">Ship it.</span></h1>
+ <p class="lede">Digital sculpting for Linux, macOS and Windows, with ZBrush-style brushes, one-click
+ game-ready LODs, <strong>Send to Unreal</strong>, Gaussian splats and OpenUSD. Optional AI tools use
+ the model <em>you</em> choose, including free and fully local ones.</p>
+ <div class="ctas">
+ <a class="btn primary" href="#download">Download</a>
+ <a class="btn" href="https://github.com/islandmed/SculptForge">View on GitHub</a>
+ </div>
+ <ul class="pills" aria-label="Highlights">
+ <li>No account</li><li>No telemetry</li><li>Windows · macOS · Linux</li><li>Offline-first</li>
+ </ul>
+ </div>
+ <figure class="hero-video">
+ <video src="media/sculpt.mp4" poster="media/poster-sculpt.jpg" autoplay muted loop playsinline preload="metadata"
+ aria-label="Sculpting a creature head with symmetry in SculptForge"></video>
+ <figcaption>Real recording of SculptForge, scripted demo at 1080p.</figcaption>
+ </figure>
+ </div>
+ </section>
+
+ <section id="features" class="section">
+ <div class="wrap">
+ <h2>Everything a sculptor needs, nothing in the way</h2>
+ <p class="section-lede">A focused sculpting app that starts instantly, works offline and fits straight into
+ game and animation pipelines.</p>
+ <div class="grid">
+ <article class="card">
+ <h3>Sculpt the way you already do</h3>
+ <p>Standard, Clay, Move, Inflate, Crease, Flatten, Pinch and Smooth, with symmetry, tablet pressure,
+ ZBrush-style navigation, unlimited undo, subdivision and voxel remesh.</p>
+ </article>
+ <article class="card">
+ <h3>Brush Lab: describe a brush</h3>
+ <p>"Dry cracked mud." "Overlapping dragon scales." An AI turns words into a brush recipe you can tweak
+ with sliders. Works with Claude or any OpenAI-compatible endpoint, including local Ollama.</p>
+ </article>
+ <article class="card">
+ <h3>Generate 3D from an image or text</h3>
+ <p>Reconstruct a full, sculptable model from a sketch, a piece of concept art or a description, for
+ free through Hunyuan3D, TRELLIS.2 and Stable Fast 3D on Hugging Face, or with fal.ai or Meshy.</p>
+ </article>
+ <article class="card">
+ <h3>Game &amp; animation ready</h3>
+ <p>Sculpt layers become blend shapes and morph targets. Make a whole LOD chain in one click.
+ Blend shapes survive on every level.</p>
+ </article>
+ <article class="card">
+ <h3>Send to Unreal</h3>
+ <p>One click imports or updates your asset in a running Unreal Editor, on this computer or another
+ one on your network. Static meshes come with LODs, skeletal meshes with morph targets.</p>
+ </article>
+ <article class="card">
+ <h3>Gaussian splats</h3>
+ <p>Load phone captures as a sculpting reference, turn them into watertight meshes, or turn your
+ sculpt into splats. Supports PLY, .splat, glTF KHR_gaussian_splatting and OpenUSD.</p>
+ </article>
+ <article class="card">
+ <h3>Open standards</h3>
+ <p>FBX, glTF/GLB, OpenUSD (USDA/USDZ), OBJ and PLY. Exports are checked with the Khronos glTF
+ validator and Pixar's OpenUSD tools.</p>
+ </article>
+ <article class="card">
+ <h3>Scriptable, and agent-ready</h3>
+ <p><code>sculptforge-cli</code> runs any operation headless for build farms. Its built-in MCP server
+ lets Claude Code, Claude Desktop or any MCP client sculpt, convert and export.</p>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <section id="demos" class="section alt">
+ <div class="wrap">
+ <h2>See it in action</h2>
+ <p class="section-lede">Every clip is a real, unedited recording of the app, made with its built-in demo
+ recorder. Waits for AI models are sped up and labelled on screen.</p>
+
+ <div class="demo">
+ <video src="media/brush-lab.mp4" poster="media/poster-brush-lab.jpg" controls muted playsinline preload="none"></video>
+ <div>
+ <h3>Brush Lab, powered by a local AI</h3>
+ <p>Type "dry cracked mud", and a small open model running on the same machine designs the brush. Then
+ ask for "deeper cracks, sharper edges". Nothing leaves your computer.</p>
+ </div>
+ </div>
+
+ <div class="demo reverse">
+ <figure class="pair">
+ <img src="img/teddy-sketch.png" alt="A simple line sketch of a teddy bear" loading="lazy">
+ <span class="arrow" aria-hidden="true">→</span>
+ <img src="img/teddy-3d.png" alt="The teddy bear reconstructed as a full 3D model" loading="lazy">
+ </figure>
+ <div>
+ <h3>From a sketch to a sculptable model in about 20 seconds</h3>
+ <p>A quick drawing became a full 3D model, with separate ears, arms and legs, a back and real depth.
+ It was made with the free Hunyuan3D 2.1 model, then voxel-remeshed into one clean surface ready
+ to sculpt. You can also type a description instead of using an image.</p>
+ </div>
+ </div>
+
+ <div class="demo">
+ <video src="media/game-ready.mp4" poster="media/poster-game-ready.jpg" controls muted playsinline preload="none"></video>
+ <div>
+ <h3>Blend shapes, LODs and Unreal</h3>
+ <p>Sculpt an expression on its own layer and play it back. Generate a LOD chain and inspect each
+ level, then send a static mesh with LODs, or a skeletal mesh with morph targets, to Unreal Engine.</p>
+ </div>
+ </div>
+
+ <div class="demo reverse">
+ <video src="media/splats.mp4" poster="media/poster-splats.jpg" controls muted playsinline preload="none"></video>
+ <div>
+ <h3>Gaussian splats, both ways</h3>
+ <p>Turn a sculpt into Gaussian splats for web viewers and engines, and turn splat captures into
+ watertight meshes in under a second.</p>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="section">
+ <div class="wrap two-col">
+ <div>
+ <h2>Your AI, your choice</h2>
+ <p>Every AI feature is optional and talks directly to the service you pick. SculptForge has no servers,
+ no account and no telemetry.</p>
+ <ul class="checks">
+ <li><strong>Local models</strong> (Ollama, LM Studio) for brush design. They're free, private and
+ work offline.</li>
+ <li><strong>Free cloud models</strong> on Hugging Face for image and text to 3D.</li>
+ <li><strong>Your own keys</strong> for Claude, fal.ai or Meshy when you want more.</li>
+ </ul>
+ <p class="fine">Each model has its own licence. For example, Tencent's Hunyuan3D isn't licensed for use
+ in the EU, UK or South Korea.
+ <a href="https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md">See the AI services and privacy guide</a>.</p>
+ </div>
+ <div>
+ <h2>How it compares</h2>
+ <div class="table-wrap">
+ <table class="compare">
+ <thead><tr><th></th><th>SculptForge</th><th>ZBrush</th><th>Blender</th><th>Nomad</th></tr></thead>
+ <tbody>
+ <tr><td>Price</td><td class="yes">Free</td><td>Subscription</td><td class="yes">Free</td><td>Paid</td></tr>
+ <tr><td>Open source</td><td class="yes">GPL</td><td>No</td><td class="yes">GPL</td><td>No</td></tr>
+ <tr><td>Native Linux</td><td class="yes">Yes</td><td>No</td><td class="yes">Yes</td><td>No</td></tr>
+ <tr><td>Send to Unreal</td><td class="yes">Built in</td><td>Plugin</td><td>Add-on</td><td>No</td></tr>
+ <tr><td>Image / text to 3D</td><td class="yes">Built in</td><td>No</td><td>Add-ons</td><td>No</td></tr>
+ <tr><td>Gaussian splats</td><td class="yes">Built in</td><td>No</td><td>Add-ons</td><td>No</td></tr>
+ <tr><td>AI agent control (MCP)</td><td class="yes">Built in</td><td>No</td><td>Add-ons</td><td>No</td></tr>
+ </tbody>
+ </table>
+ </div>
+ <p class="fine">SculptForge is young. It doesn't yet have retopology, UVs or texture painting.
+ <a href="https://github.com/islandmed/SculptForge/blob/main/ROADMAP.md">See the roadmap</a>.</p>
+ </div>
+ </div>
+ </section>
+
+ <section id="download" class="section alt">
+ <div class="wrap">
+ <h2>Download</h2>
+ <p class="section-lede">Version 0.1.0. All builds come from the
+ <a href="https://github.com/islandmed/SculptForge/releases/latest">latest GitHub release</a>, with
+ SHA-256 checksums.</p>
+ <div class="downloads">
+ <a class="dl" href="https://github.com/islandmed/SculptForge/releases/latest">
+ <strong>Windows</strong><span>10 / 11 · installer or portable .zip</span></a>
+ <a class="dl" href="https://github.com/islandmed/SculptForge/releases/latest">
+ <strong>macOS</strong><span>11+ · Apple Silicon &amp; Intel · .dmg</span></a>
+ <a class="dl" href="https://github.com/islandmed/SculptForge/releases/latest">
+ <strong>Ubuntu / Debian</strong><span>.deb · x86_64 &amp; ARM64</span></a>
+ <a class="dl" href="https://github.com/islandmed/SculptForge/releases/latest">
+ <strong>Fedora / RHEL 9+</strong><span>.rpm · x86_64 &amp; ARM64</span></a>
+ <a class="dl" href="https://github.com/islandmed/SculptForge/releases/latest">
+ <strong>Any Linux</strong><span>AppImage · runs anywhere</span></a>
+ <div class="dl static">
+ <strong>Arch Linux</strong><span><code>yay -S sculptforge</code></span></div>
+ </div>
+ <p class="fine">The builds aren't code-signed yet. On macOS, right-click the app and choose <em>Open</em>
+ the first time. On Windows, if SmartScreen appears, choose <em>More info → Run anyway</em>.
+ You can also <a href="https://github.com/islandmed/SculptForge#building">build from source</a>.</p>
+ </div>
+ </section>
+
+ <section class="section">
+ <div class="wrap faq">
+ <h2>Questions</h2>
+ <details><summary>Is it really free? Can I sell what I make?</summary>
+ <p>Yes. SculptForge is free under the GPL-3.0, and you own everything you sculpt with it. The GPL
+ covers the program's source code, not your models. If you use an AI model to generate a starting
+ point, that model's licence also applies (see the AI services guide).</p></details>
+ <details><summary>Do I need AI to use it?</summary>
+ <p>No. Sculpting, layers, LODs, remeshing, file formats and Send to Unreal all work offline with no AI
+ at all. The AI tools are extras you can switch to a local model or simply ignore.</p></details>
+ <details><summary>Which Unreal versions work with Send to Unreal?</summary>
+ <p>It targets Unreal Engine 5. It uses Unreal's built-in Python remote execution, so you only enable
+ the Python plugin and tick "Enable Remote Execution"; there's nothing to install in your project.
+ You can always export an Unreal-ready FBX instead.</p></details>
+ <details><summary>Is it a ZBrush replacement?</summary>
+ <p>Not yet, and it isn't affiliated with ZBrush. It covers core sculpting and pipeline work, and adds
+ things ZBrush doesn't have. Multiresolution, masking, retopology and texture painting are on the
+ roadmap.</p></details>
+ <details><summary>How can I help?</summary>
+ <p>Try it, report bugs, share brushes, and send pull requests. See
+ <a href="https://github.com/islandmed/SculptForge/blob/main/CONTRIBUTING.md">CONTRIBUTING.md</a>.</p></details>
+ </div>
+ </section>
+ </main>
+
+ <footer class="footer">
+ <div class="wrap footer-grid">
+ <div>
+ <a class="brand" href="#top"><img src="img/logo.svg" alt="" width="28" height="28"><span>SculptForge</span></a>
+ <p class="fine">Copyright © 2026 The SculptForge contributors.<br>Licensed under the
+ <a href="https://github.com/islandmed/SculptForge/blob/main/LICENSE">GNU GPL v3.0 or later</a>.</p>
+ </div>
+ <div class="links">
+ <a href="https://github.com/islandmed/SculptForge">Source code</a>
+ <a href="https://github.com/islandmed/SculptForge/blob/main/THIRD_PARTY_NOTICES.md">Third-party notices</a>
+ <a href="https://github.com/islandmed/SculptForge/blob/main/docs/ai-services.md">AI services &amp; privacy</a>
+ <a href="https://github.com/islandmed/SculptForge/blob/main/SECURITY.md">Security</a>
+ <a href="https://github.com/islandmed/SculptForge/blob/main/CODE_OF_CONDUCT.md">Code of conduct</a>
+ </div>
+ <p class="fine trademarks">SculptForge is an independent project, not affiliated with or endorsed by Maxon,
+ Epic Games, Autodesk, Pixar, the Khronos Group, Hugging Face, Tencent, Microsoft, Stability AI,
+ Anthropic, fal or Meshy. ZBrush is a trademark of Maxon. Unreal and Unreal Engine are trademarks of Epic
+ Games, Inc. FBX is a trademark of Autodesk, Inc. glTF is a trademark of the Khronos Group Inc. All other
+ trademarks belong to their owners. The site uses the Inter typeface (SIL Open Font License), self-hosted,
+ with no trackers and no cookies.</p>
+ </div>
+ </footer>
+</body>
+</html>
diff --git a/website/media/brush-lab.mp4 b/website/media/brush-lab.mp4
new file mode 100644
index 00000000..617fb33c
Binary files /dev/null and b/website/media/brush-lab.mp4 differ
diff --git a/website/media/game-ready.mp4 b/website/media/game-ready.mp4
new file mode 100644
index 00000000..ba74b4db
Binary files /dev/null and b/website/media/game-ready.mp4 differ
diff --git a/website/media/poster-brush-lab.jpg b/website/media/poster-brush-lab.jpg
new file mode 100644
index 00000000..8059b2ee
Binary files /dev/null and b/website/media/poster-brush-lab.jpg differ
diff --git a/website/media/poster-game-ready.jpg b/website/media/poster-game-ready.jpg
new file mode 100644
index 00000000..fed86ad7
Binary files /dev/null and b/website/media/poster-game-ready.jpg differ
diff --git a/website/media/poster-sculpt.jpg b/website/media/poster-sculpt.jpg
new file mode 100644
index 00000000..e3a43876
Binary files /dev/null and b/website/media/poster-sculpt.jpg differ
diff --git a/website/media/poster-splats.jpg b/website/media/poster-splats.jpg
new file mode 100644
index 00000000..d1c27d78
Binary files /dev/null and b/website/media/poster-splats.jpg differ
diff --git a/website/media/screenshot-brush-lab.jpg b/website/media/screenshot-brush-lab.jpg
new file mode 100644
index 00000000..774d57ee
Binary files /dev/null and b/website/media/screenshot-brush-lab.jpg differ
diff --git a/website/media/screenshot-game-ready.jpg b/website/media/screenshot-game-ready.jpg
new file mode 100644
index 00000000..5d92e46e
Binary files /dev/null and b/website/media/screenshot-game-ready.jpg differ
diff --git a/website/media/screenshot-sculpt.jpg b/website/media/screenshot-sculpt.jpg
new file mode 100644
index 00000000..8d7d0557
Binary files /dev/null and b/website/media/screenshot-sculpt.jpg differ
diff --git a/website/media/screenshot-splats.jpg b/website/media/screenshot-splats.jpg
new file mode 100644
index 00000000..c8a2ff43
Binary files /dev/null and b/website/media/screenshot-splats.jpg differ
diff --git a/website/media/sculpt.mp4 b/website/media/sculpt.mp4
new file mode 100644
index 00000000..f73bbef8
Binary files /dev/null and b/website/media/sculpt.mp4 differ
diff --git a/website/media/splats.mp4 b/website/media/splats.mp4
new file mode 100644
index 00000000..3520572d
Binary files /dev/null and b/website/media/splats.mp4 differ
diff --git a/website/style.css b/website/style.css
new file mode 100644
index 00000000..f5477c36
--- /dev/null
+++ b/website/style.css
@@ -0,0 +1,134 @@
+/* SculptForge website. No frameworks, no trackers. */
+@font-face { font-family: "Inter"; src: url("fonts/Inter-Regular.ttf") format("truetype"); font-weight: 400; font-display: swap; }
+@font-face { font-family: "Inter"; src: url("fonts/Inter-SemiBold.ttf") format("truetype"); font-weight: 600 700; font-display: swap; }
+
+:root {
+ --bg: #0f0f12;
+ --bg-alt: #15151a;
+ --panel: #1b1b21;
+ --border: #2a2a31;
+ --text: #ececf1;
+ --muted: #a3a3ad;
+ --accent: #f28c3c;
+ --accent-2: #ffb06a;
+ --radius: 14px;
+ --wrap: 1180px;
+}
+
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; }
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--text);
+ font: 400 17px/1.6 "Inter", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased;
+}
+img, video { max-width: 100%; display: block; }
+a { color: var(--accent-2); text-decoration: none; }
+a:hover { text-decoration: underline; }
+code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: #24242b; padding: 0.1em 0.35em; border-radius: 6px; }
+h1, h2, h3 { line-height: 1.15; margin: 0 0 0.5em; letter-spacing: -0.01em; }
+h1 { font-size: clamp(2.3rem, 4.2vw, 3.5rem); font-weight: 700; }
+h2 { font-size: clamp(1.7rem, 3vw, 2.4rem); font-weight: 700; }
+h3 { font-size: 1.15rem; font-weight: 600; }
+p { margin: 0 0 1em; }
+
+.wrap { max-width: var(--wrap); margin: 0 auto; padding: 0 24px; }
+
+/* Navigation */
+.nav { position: sticky; top: 0; z-index: 10; background: rgba(15, 15, 18, 0.82); backdrop-filter: blur(10px);
+ border-bottom: 1px solid var(--border); }
+.nav-inner { display: flex; align-items: center; justify-content: space-between; height: 64px; }
+.brand { display: flex; align-items: center; gap: 10px; color: var(--text); font-weight: 600; font-size: 1.1rem; }
+.brand:hover { text-decoration: none; }
+.nav nav { display: flex; gap: 22px; align-items: center; }
+.nav nav a { color: var(--muted); font-size: 0.95rem; }
+.nav nav a:hover { color: var(--text); text-decoration: none; }
+.nav nav a.gh { color: var(--text); border: 1px solid var(--border); padding: 6px 14px; border-radius: 999px; }
+
+/* Hero */
+.hero { padding: 72px 0 56px; background: radial-gradient(1200px 600px at 15% -10%, rgba(242, 140, 60, 0.16), transparent 60%); }
+.hero-grid { display: grid; grid-template-columns: 1.05fr 1.2fr; gap: 48px; align-items: center; }
+.eyebrow { color: var(--accent-2); font-weight: 600; font-size: 0.85rem; letter-spacing: 0.08em; text-transform: uppercase; }
+.nowrap { white-space: nowrap; }
+.accent { background: linear-gradient(90deg, var(--accent), var(--accent-2)); -webkit-background-clip: text; background-clip: text; color: transparent; }
+.lede { color: #cfcfd6; font-size: 1.12rem; max-width: 34em; }
+.ctas { display: flex; gap: 12px; margin: 28px 0 22px; flex-wrap: wrap; }
+.btn { display: inline-block; padding: 12px 22px; border-radius: 999px; border: 1px solid var(--border); color: var(--text);
+ font-weight: 600; background: var(--panel); }
+.btn:hover { text-decoration: none; border-color: #3a3a44; }
+.btn.primary { background: linear-gradient(180deg, #f6994d, #e2742a); border-color: transparent; color: #1a0d04; }
+.btn.primary:hover { filter: brightness(1.06); }
+.pills { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; padding: 0; margin: 0; }
+.pills li { font-size: 0.82rem; color: var(--muted); border: 1px solid var(--border); border-radius: 999px; padding: 4px 12px; }
+.hero-video { margin: 0; }
+.hero-video video { width: 100%; border-radius: var(--radius); border: 1px solid var(--border);
+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.02); background: #000; }
+.hero-video figcaption { color: var(--muted); font-size: 0.8rem; margin-top: 10px; text-align: center; }
+
+/* Sections */
+.section { padding: 88px 0; }
+.section.alt { background: var(--bg-alt); border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
+.section-lede { color: var(--muted); max-width: 46em; margin-bottom: 40px; }
+
+.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px; }
+.card { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 22px; }
+.card h3 { color: #fff; }
+.card p { color: var(--muted); font-size: 0.95rem; margin: 0; }
+
+.demo { display: grid; grid-template-columns: 1.4fr 1fr; gap: 40px; align-items: center; margin-bottom: 64px; }
+.demo:last-child { margin-bottom: 0; }
+.demo.reverse > :first-child { order: 2; }
+.demo video { width: 100%; border-radius: var(--radius); border: 1px solid var(--border); background: #000; }
+.demo p { color: var(--muted); }
+.pair { display: flex; align-items: center; gap: 14px; margin: 0; background: #1f1f25; border: 1px solid var(--border);
+ border-radius: var(--radius); padding: 16px; }
+.pair img { width: calc(50% - 24px); border-radius: 10px; background: #fff; }
+.pair img + .arrow + img { background: transparent; }
+.pair .arrow { font-size: 1.8rem; color: var(--accent); }
+
+.two-col { display: grid; grid-template-columns: 1fr 1.2fr; gap: 56px; }
+.checks { padding-left: 1.2em; color: #cfcfd6; }
+.checks li { margin-bottom: 0.6em; }
+.fine { color: var(--muted); font-size: 0.85rem; }
+.table-wrap { overflow-x: auto; }
+.compare { width: 100%; border-collapse: collapse; font-size: 0.92rem; }
+.compare th, .compare td { padding: 10px 12px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; }
+.compare th { color: var(--muted); font-weight: 600; }
+.compare th:nth-child(2), .compare td:nth-child(2) { background: rgba(242, 140, 60, 0.07); }
+.compare .yes { color: #fff; font-weight: 600; }
+
+.downloads { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; margin-bottom: 18px; }
+.dl { display: flex; flex-direction: column; gap: 4px; background: var(--panel); border: 1px solid var(--border);
+ border-radius: var(--radius); padding: 18px 20px; color: var(--text); }
+.dl:hover { text-decoration: none; border-color: var(--accent); }
+.dl span { color: var(--muted); font-size: 0.9rem; }
+.dl.static:hover { border-color: var(--border); }
+
+.faq details { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px 20px; margin-bottom: 10px; }
+.faq summary { cursor: pointer; font-weight: 600; }
+.faq details p { color: var(--muted); margin: 12px 0 0; }
+
+.footer { border-top: 1px solid var(--border); padding: 48px 0; }
+.footer-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
+.footer .links { display: flex; flex-direction: column; gap: 8px; align-items: flex-end; }
+.footer .links a { color: var(--muted); font-size: 0.9rem; }
+.footer .trademarks { grid-column: 1 / -1; margin-top: 8px; }
+
+@media (max-width: 960px) {
+ .hero-grid, .two-col, .demo { grid-template-columns: 1fr; }
+ .demo.reverse > :first-child { order: 0; }
+ .grid { grid-template-columns: repeat(2, 1fr); }
+ .downloads { grid-template-columns: repeat(2, 1fr); }
+}
+@media (max-width: 620px) {
+ .nav nav a:not(.gh) { display: none; }
+ .grid, .downloads, .footer-grid { grid-template-columns: 1fr; }
+ .footer .links { align-items: flex-start; }
+ .section { padding: 64px 0; }
+ .hero { padding-top: 40px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ html { scroll-behavior: auto; }
+}