Compare commits

...
497 Commits
Author SHA1 Message Date
Afonso JanuárioandKim Kulling 17ec36b247 Fix heap-buffer-overflow reading MD2 skin names (#6832)
* Fix heap-buffer-overflow reading MD2 skin names

The skin name field in an MD2 file is a fixed 64-byte buffer copied
straight from the file, with nothing guaranteeing it actually contains
a NUL terminator. If a malformed or crafted file fills those 64 bytes
with non-zero data right up against the end of the file, strlen() on
that field walks straight past the end of the read buffer looking for
a terminator that isn't there.

Bounded the scan with strnlen() capped at one less than the field's
size instead, the same approach MDCLoader already uses for its own
fixed-size name fields. Added a regression test with a hand-built MD2
file that reproduces the crash under ASan on the old code and imports
cleanly with the fix.

* Refactor MD2Loader.cpp for code clarity

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-08 15:59:55 +02:00
Turo Lamminen de6d25fd5a Fix Collada animation memory leak 2026-09-08 14:35:01 +03:00
Turo Lamminen 42631e32da Make Collada Animation type movable but not copyable 2026-09-08 14:35:01 +03:00
Turo Lamminen 1afbdefcb5 Replace explicit iterator types with auto 2026-09-08 14:35:01 +03:00
Turo Lamminen c19fcb0b02 Add FIXMEs about a memory leak 2026-09-08 14:35:01 +03:00
Turo Lamminen bdfee7bc24 Add more collada tests 2026-09-08 14:35:01 +03:00
Turo Lamminen d317cc946c Revert "Only build collada test when importer/exporter is build (#6411)"
It disabled Collada tests unconditionally even when the importer was enabled.

This reverts commit 4d197881ff.
2026-09-08 14:35:01 +03:00
Pengfei Li 630f614a56 Support normalized morph weights and quaternion (#6732)
* assimp: support normalized morph weights and quaternion

* assimp: fix code AI suggestions

* assimp: AI review comments

* assimp: review comments

* assimp: format
2026-09-08 14:15:36 +03:00
alhudaandKim Kulling 7555cc90df bound md5 weight index in remaining mesh loops (#6685)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-06 13:26:30 +02:00
81cc98f321 Fix BatchLoader ownership after polling shared scenes (#6824)
* Fix BatchLoader ownership after polling shared scenes

* Refactor BaseImporter.cpp for clarity and consistency

* Improve documentation for BaseImporter class

* Updated comment formatting and added brief description for BaseImporter class.

---------

Co-authored-by: Darren Carreras <283775510+carrerasdarren-cell@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-04 22:01:50 +02:00
thedestroyer4312andKim Kulling a5687d7fff Document PyAssimp build and PyPI release steps. (#6795)
Add a release optional extra for build and twine, and README notes on
version bumps and pure-Python wheel limits.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-04 00:17:19 +02:00
Houssem AchouriandKim Kulling f9701a691c fix(GLTF): in the importers, use the bufferView name as the embedded image file name if the image name is empty. (#6251)
* fix(GLTF): in the importers, use the bufferView name as the embedded image file name if the image name is empty.

* Update glTF2Importer.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-03 23:58:21 +02:00
metsw24-maxandKim Kulling 7447a33c14 bounds validation, overflow protection, and RAII memory safety (#6637)
* bounds validation, overflow protection, and RAII memory safety

* MMD: allow empty PMX strings and use explicit UTF-8 length

* Update MMDPmxParser.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-03 21:51:44 +02:00
19f7386d73 Fix binary STL import on big-endian hosts (#6661)
* Fix binary STL import on big-endian hosts

Binary STL stores its facet count, geometry floats and per-facet
attribute field little-endian on disk. STLLoader read them host-endian,
so on a big-endian host the facet count decoded to garbage, the
84 + faceCount*50 == fileSize check in IsBinarySTL failed, and the file
was rejected with "Failed to determine STL storage representation".

Byte-swap the on-disk values with AI_SWAP4 / AI_SWAP2. These expand to
nothing on little-endian builds, so there is no change there. This
mirrors STLExporter, which already uses AI_SWAP4 to write the same
fields; only the read side was missing.

The four repeated read-and-convert blocks in the facet loop are folded
into a ReadBinaryVec3 helper, which is what SonarCloud was flagging as
duplicated new code. The loader is a little shorter as a result.

Adds importBinarySTLFromFileTest, which imports the existing
Spider_binary.stl and asserts the facet and vertex counts plus the first
facet's normal and vertex, so both the count path and the float path are
covered.

Fixes #5509

Signed-off-by: Scott <scottbphone12@gmail.com>

* STL: read binary facets through a byte cursor

The binary facet record is 50 bytes, so every other facet starts on an odd
offset. Casting that to aiVector3f* forms a pointer to a misaligned address,
which is undefined behaviour under -fsanitize=alignment even though the memcpy
through it would be fine. The undefined-behavior-sanitizer job caught it at
STLLoader.cpp:405 with a concrete address ending in 6.

The cursor is now a plain byte pointer and the typed pointer is gone, so no
misaligned aiVector3f* is ever formed.

Signed-off-by: Scott <scottbphone12@gmail.com>

---------

Signed-off-by: Scott <scottbphone12@gmail.com>
Co-authored-by: Scott <scottbphone12@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-02 21:01:40 +02:00
zayeem shaikhandKim Kulling bb1aac0811 guard x mesh texcoord read against undersized fvfdata uv array (#6818)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-02 16:32:28 +02:00
Fstar c76f95b89e Fix KHR_texture_basisu metadata in glTF2 export (#6822)
* Fix BasisU texture metadata in glTF2 export

* Restrict BasisU extension to KTX2 images

* Use init statement for BasisU path check
2026-09-02 10:32:32 +02:00
Turo Lamminen fa1c0a52a1 Re-enable IRR tests which previously leaked memory 2026-09-01 19:07:01 +03:00
Turo Lamminen 230fe9cc32 Use unique_ptr for IRR materials 2026-09-01 19:07:01 +03:00
Turo Lamminen 818be589c2 Replace memcpys with loop and assignment 2026-09-01 19:07:01 +03:00
Turo Lamminen 48c5224308 Use unique_ptr for IRR nodes 2026-09-01 19:07:01 +03:00
Turo Lamminen 0ea41fdb04 Rearrange code 2026-09-01 19:07:01 +03:00
Turo Lamminen 2a51f16a0c Split an assignment 2026-09-01 19:07:01 +03:00
Turo Lamminen 843aeb936b Remove useless casts 2026-09-01 19:07:01 +03:00
Turo Lamminen d6c8193155 Replace explicit types with auto 2026-09-01 19:07:01 +03:00
Turo Lamminen c6b96aa8da Re-enable IRR tests and add more of them 2026-09-01 19:07:01 +03:00
ecf2c3e5cc Fix @param names in the public headers that do not match the signatures (#6819)
Assisted-by: Claude:claude-opus-5

Co-authored-by: Dmitry Rantovov <rantovov5@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-09-01 13:37:57 +02:00
zayeem shaikh a47827a28a Fix lwo face index underflow when the point list is empty (#6814) 2026-08-30 00:35:22 +03:00
uwezkhanandKim Kulling 66c592c3f4 Add overflow checks for texture allocations in binary importers (#6618)
* Add overflow checks for texture allocations in binary importers

* updated

* updated

* memory management to improve exception safety

* updated

* updated

* Prevent texture allocation overflow in ReadBinaryTexture

* updated

* Harden texture loading and modernize memory management

* update

* updated

* Verify read length for assbin texture data

Restore ReadBinaryTexture to a single, well-formed path after the
master merge and check the return value of stream->Read for both the
compressed and uncompressed texture buffers, throwing on a short read
instead of leaving partially initialized texels.

* Fix merge fallout and static analysis findings in texture read paths

The master merge left delete[] calls on std::vector buffers and
Close() calls on a managed stream in the Assbin compressed path,
which broke the build. Remove those along with the always-false
uLongf > SIZE_MAX comparisons flagged by static analysis.

Value-initialize the scene pointer arrays so a mid-read failure
cannot free indeterminate pointers, and fill the M3D texel buffer
directly instead of going through a temporary vector and std::copy.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-28 11:23:19 +02:00
Kim KullingandKim Kulling 80a33d6a40 Fix duplicated line (#6817)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2026-08-27 09:23:40 +02:00
Kim Kulling 8a758657cc Fix loop condition to prevent out-of-bounds access (#6816)
* Fix loop condition to prevent out-of-bounds access

* Update STEPFileReader.cpp
2026-08-26 23:43:16 +02:00
MakerYuichianddoraemon2200 b32b930a79 fix(gltf2): fail fast on incomplete sparse accessors (#6810) (#6812)
* test: add malformed gltf sparse accessor reproduction assets

* fix(gltf2): fail fast on incomplete sparse accessors (#6810)

* fix(gltf2): validate sparse pointer arrays before evaluation

* test(gltf2): add regression unit test for incomplete sparse accessor

---------

Co-authored-by: doraemon2200 <106516578+doraemon2200@users.noreply.github.com>
2026-08-26 10:34:31 +02:00
carrerasdarren-cellandDarren Carreras 45304c5b2b Fix glTF object type error logging (#6813)
Co-authored-by: Darren Carreras <283775510+carrerasdarren-cell@users.noreply.github.com>
2026-08-25 09:06:33 +02:00
dependabot[bot]andKim Kulling 0913648183 Bump actions/setup-python from 5 to 7 (#6808)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5 to 7.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v5...v7)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-24 13:32:18 +02:00
dependabot[bot] 58afeedc1c Bump actions/download-artifact from 7 to 8 (#6809)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-24 12:53:44 +02:00
87b6d35261 fix anim problem in fbx exporter (#6754)
* fix fbx rot anim error caused by Euler Angles Gimbal Lock problem and angle cross border problem like 179° to -179°

* fbx anim curve set interp type

* fbx skin bind-matrix export improve

* fix unknown file extension of embedded texture in fbx exporter

* fix compile error for some compiler

* Update code/AssetLib/FBX/FBXExporter.cpp

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: lclyy <lclyy@qq.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-24 09:33:48 +02:00
Turo Lamminen 394041fff1 Miscellaneous fixes (#6801)
* Add missing include

* Fix uninitialized member variables in Blender statistics

* Remove unnecessary temporary variable

* Add more RAW import unit tests

Some are disabled because they're currently broken

* Add braces to else

* Split a compound assignment

* Fix memory leak and validation failures in RAW importer

* Enable tests for fixed RAW files

* Fix memory leak in AMF importer

* Enable tests for fixed AMF files

* Split an increment out of a dereference

* Use unique_ptr for AMF NodeArray

* Add braces

* Split an increment out of a dereference

* Use unique_ptr for AMF MeshArray

* Store AMF child nodes with unique_ptr

* Reduce scope of variables
2026-08-24 08:58:34 +02:00
zayeem shaikh 21bea12f12 fix csm $points heap overflow when a channel drops a sample 2026-08-22 20:27:39 +03:00
alb3e3andAlbert ae786a689e MDL: reject non-positive skin dimensions and use size_t multiplication (#6798)
CreateTextureARGB8_3DGS_MDL3() computed

  const size_t len = pcHeader->skinwidth * pcHeader->skinheight;

with signed int32 operands.  When the product exceeds INT32_MAX (e.g.
skinwidth=50000, skinheight=43000 → 2 150 000 000 > 2 147 483 647) the
multiplication is undefined behaviour that UBSan flags as signed-integer
overflow (OSS-Fuzz issue #6793, crash state CreateTextureARGB8_3DGS_MDL3
→ InternReadFile_Quake1 → InternReadFile).

Fix:
* Reject non-positive dimensions before computing len; the existing
  VALIDATE_FILE_SIZE and the unsigned-overflow guard at mWidth/mHeight
  both assume positive values anyway.
* Cast both operands to size_t so the multiply is done in 64-bit and
  cannot overflow on any supported platform.
* Add an explicit AI_MAX_ALLOC(aiTexel) guard before the allocation so a
  malformed file cannot request an unreasonably large heap block.

Add a unit test (Quake1MDL3SkinDimensionOverflow) that feeds a crafted
IDPO buffer with the overflowing dimensions and asserts the importer
returns nullptr rather than triggering UBSan.

Fixes #6793

Assisted-by: Claude Code:claude-sonnet-4-6

Co-authored-by: Albert <albert@beneat.co>
2026-08-21 15:46:59 +02:00
thedestroyer4312andKim Kulling b742a483e2 [PyAssimp] Add Tests, Add CI, Cleanup for Basic 6.0.0 Release (#6782)
* Add pytest and GitHub Actions for PyAssimp.

Run a small smoke suite against the ctypes bindings on Python 3.10-3.14.
Build libassimp once and reuse it so the matrix only installs and tests.

* Add public API tests and pytest 9 config.

Cover load() from path and file object, error cases, scene graph
resolution, and material properties. Use native [tool.pytest] TOML
configuration.

* Use pytest 9 strict mode for PyAssimp tests.

Replace addopts flags with the native strict = true setting.

* Fix PyAssimp drift against current C headers.

Add Camera.mOrthographicWidth, repair process-flag trailing commas,
refresh aiTextureType constants, and cover them with unit tests.

* Trim PyAssimp tests to a minimal core API suite.

Keep path/file load, error, and the three header-drift checks only.

* Restore hex style for PyAssimp texture type constants.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-20 13:40:15 +02:00
Mohamed NathooandKim Kulling 2313611365 Fix icon path in assimp_cmd resource file after refactor in commit: 1a810a922b (#6764)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-20 00:25:52 +02:00
Thomas PetazzoniandKim Kulling 76ec41ed71 CMakeLists.txt: make it possible to install tests (#6776)
In cross-compilation contexts, running tests needs to be done on the
target machine, for which assimp was cross-compiled. This is currently
not possible as the unit tests are not installed, and remain inside
the source tree... which is not available on the target platform after
assimp has been installed.

To make it possible to run tests on the target platform, this commit
adds a new ASSIMP_INSTALL_TESTS, which allows to install tests. By
default it is set to OFF, preserving existing behavior.

However, if it is set to ON, then:

- The test/unit binary will be installed as /usr/bin/assimp-unit on
  the target

- The models will be installed in /usr/share/assimp/models and
  /usr/share/assimp-models-nonbsd

- The test/unit binary will be compiled with the right paths to the
  models

On a Buildroot-generated system, this allows to successfully run the
test suite:

```
 Welcome to Buildroot
 buildroot login: root
 # assimp-unit
 [...]
 [----------] Global test environment tear-down
 [==========] 584 tests from 114 test suites ran. (42484 ms total)
 [  PASSED  ] 584 tests.
 # echo $?
 0
 #
```

Signed-off-by: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-19 10:31:47 +02:00
thedestroyer4312andKim Kulling 072692150a Drop python 2 compatibility from pyassimp (#6778)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-18 21:54:32 +02:00
alb3e3andKim Kulling ba8f4f4564 Fix out-of-bounds copy of the uv transformation property (#6748)
* Add texture transform tests for the uv transformation property

Covers the regular property and a property whose data is shorter than an
aiUVTransform. The latter trips the ai_assert on master; with asserts
disabled the memcpy reads 20 bytes out of the shorter property.

Export TextureTransformStep so the tests can drive the step directly, as
is already done for the other post-processing steps under test.

Assisted-by: Claude Code (Claude Opus 5)

* Fix out-of-bounds copy of the uv transformation property

TextureTransformStep::Execute() copied five floats through
&info.mTranslation.x, which writes past that member and over the two
following members of the aiUVTransform base - undefined behaviour that a
sanitizer flags as an intra-object overflow (assimp#6733). The size was
also hard-coded to sizeof(float) * 5, so it read the wrong amount when
ai_real is double, and the source length was only checked by an
ai_assert that is compiled out in release builds.

Copy into a complete aiUVTransform of the correct size instead and skip
properties whose data is too short.

Assisted-by: Claude Code (Claude Opus 5)

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-17 14:21:25 +02:00
carrerasdarren-cell eb21a7c498 HMP: bound external texture name parsing (#6777)
Reject external texture names that are not null-terminated within the loaded file, and preserve correct cursor advancement when long names are truncated for aiString storage. Add a regression fixture for OSS-Fuzz issue 487902914.

Assisted-by: OpenAI Codex
2026-08-16 21:02:02 +02:00
Zac Zhuo ZhangandKim Kulling bb7140123a DXF: add support for POINT entities (#6743)
* DXF: add support for POINT entities
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-13 21:43:23 +02:00
alhudaandKim Kulling fe1965b3e7 bound vertex index when reading normals in q3d importer (#6703)
* bound vertex index when reading normals in q3d importer

* Q3D: normalise full face-normal cross product

Signed-off-by: Alhuda Khan <al.hudz.k@gmail.com>

---------

Signed-off-by: Alhuda Khan <al.hudz.k@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-12 21:28:15 +02:00
alb3e3andKim Kulling f0013bd3a6 Harden MDL importer metadata parsing (#6726)
* Harden MDL metadata parsing

Assisted-by: OpenAI Codex

* Reduce MDL hardening static-analysis noise

* Address MDL hardening Sonar findings

* Deduplicate MDL7 ASCII effect validation

Assisted-by: OpenAI Codex

* Address MDL metadata review bounds

* Address MDL loader naming nit

Assisted-by: OpenAI Codex

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-12 00:02:52 +02:00
zayeem shaikhandKim Kulling 23fac9e7de don't step past the terminator in TokenMatchI (#6737)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-11 22:43:32 +02:00
alb3e3andKim Kulling 78672c5da2 Bounds-check SIB UV point counts against the face (#6755)
* Bounds-check SIB UV point counts against the face

ReadUVs() read a per-face point count straight from the UV ('FTVS')
chunk and looped that many times over the face's index data, without
checking it against the number of points the face was actually built
with in ReadFaces(). A UV chunk claiming more points than its face has
walks the index cursor past the end of the face's data and off the end
of mesh->idx, an out-of-bounds read (and a subsequent out-of-bounds
write into mesh->uv via the garbage index).

The face's real point count is stored at mesh->idx[faceStart[faceIdx]];
reject a UV chunk that exceeds it.

AddressSanitizer on origin/master before the fix:

  ERROR: AddressSanitizer: heap-buffer-overflow READ of size 4
    #0 ReadUVs           code/AssetLib/SIB/SIBImporter.cpp:273
    allocated by ReadFaces code/AssetLib/SIB/SIBImporter.cpp:236

Added a regression test that reproduces it from an 0x4c-byte file.

* Release SIB scene data when parsing fails

The importer collects materials, meshes and lights in a local struct and
hands the pointers to the aiScene once parsing has finished. When
parsing throws - which the new regression test now makes happen - none
of them are released, which the CI leak checker reports as

    SUMMARY: AddressSanitizer: 1132 byte(s) leaked in 4 allocation(s)

Delete whatever is still held in the struct when it goes out of scope,
and clear the lists once the scene has taken ownership so nothing is
deleted twice.

Assisted-by: Claude Code (Claude Opus 5)

* Make the SIB parse state non-copyable

The struct now owns the materials, meshes and lights it collects until
InternReadFile() hands them to the aiScene, and it deletes whatever is
left when it goes out of scope. Copying it would therefore give the same
pointers to two destructors.

Nothing copies it today - it is a single local in InternReadFile() - so
this only pins down the invariant that the destructor introduced.

Assisted-by: Claude Code (Claude Opus 5)

* test: rename UvPointCountExceedingFace to PascalCase (CodeRabbit nit)

* Refactor SIBImporter.cpp for improved readability

* Refactor variable declarations to use const

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-11 10:48:47 +02:00
Scott Thomas 50d767984e Fix mdl buffer overflow issue 6633 (#6759)
* validate frame size before accessing data

* add security bot suggestions to calculate frame span
2026-08-10 14:33:03 +02:00
Kim Kulling ff7b4ca04c Add null check in RateRepresentationPredicate (#6763)
* Add null check in RateRepresentationPredicate

Added null check for IfcRepresentation in Rate function.

* Add null check for IfcRepresentation and use type alias
2026-08-09 18:24:06 +02:00
Turo Lamminen aa9f632183 Fix C++ 23 compatibility issue
The old comparison is ambiguous in C++ 23 and later
2026-08-08 22:00:09 +03:00
3a38cd1e87 GenBoundingBoxes: fix AABB for meshes with coordinates beyond +/-999999 (#6756)
* GenBoundingBoxes: fix AABB for meshes with coordinates beyond +/-999999

The min/max accumulators were initialized with +/-999999 sentinel values.
Meshes with any coordinate beyond that range (e.g. projected geographic
coordinate systems like Swiss LV95 with eastings around 2.6e6, or
millimeter-unit CAD files) produced wildly wrong bounding boxes because
the accumulators never moved past the sentinels.

Initialize with std::numeric_limits<ai_real>::max() instead, and skip
meshes without vertices so their AABB stays at the default zero value
rather than being filled with sentinels.

Assisted-by: Claude
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Address review: kMaxVal/kOffset naming, negative-offset and empty-mesh coverage

Assisted-by: Claude
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Address review: PascalCase test names

Assisted-by: Claude
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-05 09:25:09 +02:00
alb3e3andKim Kulling bf9dabb617 Fix heap-buffer-overflow write in MD5 MakeDataUnique (#6718)
* Fix heap-buffer-overflow write in MD5 MakeDataUnique

MakeDataUnique() resized the vertex array to faces*3 but started the
append cursor (iNewIndex) at the original vertex count. When a malformed
MD5MESH declares more vertices than triangle corners -- or leaves some
vertices unreferenced -- iNewIndex runs past faces*3 and the first
duplicate write `mVertices[iNewIndex] = ...` overflows the heap buffer
(ASan: heap-buffer-overflow WRITE of size 16 at MD5Loader.cpp:251).

Size the array to the real worst case (numOrigVerts + faces*3) and trim
to the produced count afterwards. Also validate face indices against the
original vertex count -- the value abHad is sized to -- instead of the
resized array, which closes a matching out-of-bounds read of abHad, and
guard the weights-per-vertex estimate against a zero vertex count.

Well-formed files import identically (the array is trimmed back to the
same count); malformed files now fail cleanly or import safely.

Found with AddressSanitizer + libFuzzer.

Assisted-by: Claude (Anthropic)

* Guard MD5 duplicate vertex sizing

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-04 16:47:33 +02:00
Jeevan Mohan PawarandKim Kulling f39a983ab0 Fix OFF face count validation (#6757)
* Fix OFF face count validation
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-04 10:45:11 +02:00
metsw24-maxandKim Kulling a8278e3ad9 Fix OOM and heap buffer overflow in OFF parser (#6668)
* Fix OOM and heap buffer overflow in OFF parser

* Derive OFF size check from vertex dimensions, tidy includes and tests

The minimum-file-size check assumed 3D vertex lines, which could reject
valid compact 1D/2D nOFF files. Compute the per-vertex minimum from the
declared dimensions instead and add a 2D nOFF regression test.

Also reorder includes to match the project convention, drop strlen from
the new tests (flagged as security hotspots by the Sonar quality gate),
and revert the unrelated test/CMakeLists.txt changes.

* Update OFFLoader.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-08-02 18:31:57 +03:00
zayeem shaikh a472362d33 check 32-bit overflow in MDC ValidateSurfaceHeader frame checks 2026-08-01 19:38:20 +03:00
zayeem shaikhandKim Kulling ea118b1c1c bound face uv and color indices in ase BuildUniqueRepresentation (#6752)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-29 15:36:19 +02:00
alb3e3andKim Kulling 4229c79f60 Reject MD5 element indices that wrap when the container is grown (#6749)
* Add regression tests for overflowing MD5 element indices

Three crafted .md5mesh files use 4294967295 as the vert, tri and weight
index. On master each one resizes the target container to zero and then
indexes it with the original value.

Assisted-by: Claude Code (Claude Opus 5)

* Reject MD5 element indices that wrap when the container is grown

The mesh parser grew its vertex, face and weight containers with
resize(idx + 1) using the file-supplied index. strtoul10() does not
check for overflow, so an index of 0xffffffff makes idx + 1 wrap to
zero: the container is emptied and then addressed with the original
index, which reads and writes out of bounds (assimp#6710).

Move the three sites onto a shared helper that rejects the wrapping
index and does the arithmetic in size_t.

Assisted-by: Claude Code (Claude Opus 5)

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-29 14:44:12 +02:00
alb3e3andKim Kulling bd301ee4d1 Fix double-free copying meshes with sparse or empty UV/color channels (fixes #6620) (#6751)
* Add regression test for aliased mesh channels in SceneCombiner::Copy

Copying a mesh with a populated UV/color channel that is either not the
first channel or belongs to a mesh reporting zero vertices must give the
copy its own buffers. On master the copy aliases the source arrays, so
destroying both double-frees them (assimp/assimp#6620). The test asserts
the pointers differ; it also trips AddressSanitizer without the fix.

Assisted-by: Claude Code (Claude Opus 5)

* Fix double-free when copying meshes with sparse or empty UV/color channels

SceneCombiner::Copy(aiMesh) flat-copies the mesh and then reallocates
each array so the copy owns its own storage. UV and color channels were
reallocated with 'while (HasTextureCoords(n))' / 'while (HasVertexColors(n))'.
aiMesh::HasTextureCoords(n) returns false once mTextureCoords[n] is null
*or* mNumVertices == 0, so the loop stopped at the first empty channel and
skipped every channel of a zero-vertex mesh. Those channels kept the
flat-copied pointer into the source mesh, and because the destructor frees
every non-null channel of all AI_MAX_NUMBER_OF_* slots, they were freed
twice (assimp/assimp#6620).

A PLY imported with aiProcess_JoinIdenticalVertices reaches exactly this
state (mNumVertices == 0 with mTextureCoords[0] still allocated), so
importing it and passing the scene to Exporter::ExportToBlob double-frees.

Reallocate every populated UV and color channel unconditionally, matching
what the destructor frees.

Assisted-by: Claude Code (Claude Opus 5)

* Fix indentation and structure in SceneCombiner.cpp

* Refactor logging and null checks in SceneCombiner

Updated logging messages to use ASSIMP_LOG_ERROR for error cases and improved null pointer checks for prefix parameters.

* Update SceneCombiner.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-29 13:37:37 +02:00
PichasandKim Kulling a939f24795 Cleanup the aiColor3D type (#6556)
* initial commit

* Update documentation comments for clarity

* Enhance aiColor3D equality operator for clarity

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-15 14:56:26 +02:00
Daniel Pohl 28c894cc69 Fix collada animation clips (#6589)
* Update ColladaParser.cpp

* add in coderabbitai

* fix typo

* remove triple nested

* merge if

* variable name
2026-07-14 22:48:40 +03:00
Kim Kulling ff2ed44f2b Refactor JavaIOStream constructor parameter names 2026-07-14 22:24:01 +03:00
Kim Kulling e77081df25 Refactor JNI_LOG definition for clarity
Removed duplicate JNI_LOG definition and included it at the top.
2026-07-14 22:24:01 +03:00
Kim Kulling 0acf0e6fed Update print statement from 'Hello' to 'Goodbye' 2026-07-14 22:24:01 +03:00
metsw24-max a28927083f validate mesh face buffer allocation arithmetic 2026-07-14 22:24:01 +03:00
Alb3e3 924bb602e3 LWO: remove stray comment terminator in LWOLoader.h
The comment refactor left a dangling '*/' after the DoRecursiveVMAPAssignment
doc block was converted from /** ... */ to /// line comments. A bare '*/' in
code is a syntax error (expected unqualified-id before '/' token) and broke
the build on every platform. Remove the orphaned terminator.
2026-07-14 21:30:13 +03:00
Kim Kulling 0f6bcfe7ac Refactor comments in LWOLoader.h
Removed unnecessary comments and added brief descriptions to function declarations.
2026-07-14 21:30:13 +03:00
Alb3e3 c39d8c15db Fix heap-buffer-overflow in LWO2 variable-sized index reader
ReadVSizedIntLWO2() advanced the file cursor by 2-4 bytes without ever
checking it against the end of the file buffer. A malformed LWO2 file
whose polygon index count runs past the end of the chunk makes the
reader walk off the heap allocation, producing an out-of-bounds read.
The unchecked helper is reached from all of its call sites, e.g.
CountVertsAndFacesLWO2() -> ReadVSizedIntLWO2().

Guard every byte read against mFileBufferEnd and raise a
DeadlyImportError on truncated input. Well-formed files are unaffected;
malformed files now fail cleanly instead of reading out of bounds.

Found with AddressSanitizer + libFuzzer.

Assisted-by: Claude (Anthropic)
2026-07-14 21:30:13 +03:00
zayeem shaikh 09883e0831 Bound cut frame indices in MD5 camera loader (#6723)
* bound cut frame indices in MD5 camera loader

Signed-off-by: zayeem shaikh <zayeem@bugqore.com>

* MD5: validate camera cut ranges before allocating animations

Signed-off-by: zayeem shaikh <zayeem@bugqore.com>

* MD5: use auto for cut range iterator

---------

Signed-off-by: zayeem shaikh <zayeem@bugqore.com>
2026-07-14 21:12:06 +03:00
zayeem shaikhandKim Kulling f846999003 Validate iqm header offsets and counts before use (#6731)
* validate iqm header offsets and counts before use

* validate triangle vertex indices and harden vertex-array bounds against overflow

Signed-off-by: zayeem shaikh <zayeem@bugqore.com>

* Update copyright year and improve code formatting

Updated copyright year from 2021 to 2026 and improved code formatting for better readability.

---------

Signed-off-by: zayeem shaikh <zayeem@bugqore.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-14 20:49:52 +03:00
PGZXBandKim Kulling f1de01d68e Fix heap-buffer-overflow in MakeVerboseFormatProcess::MakeVerboseFormat during export (#6475)
* Fix heap-buffer-overflow in MakeVerboseFormatProcess::MakeVerboseFormat during export

* Implement null checks in MakeVerboseFormatProcess

Added null checks for scene and mesh normals, tangents, and bitangents.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-10 11:20:12 +02:00
jmestwa-coderandKim Kulling 775300f958 validate aiString length to prevent out-of-bounds read/write (#6599)
* validate aiString length to prevent out-of-bounds read/write

* restore license header and fix expected test error message after merge

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-09 21:16:54 +02:00
Vitaly OvchinnikovandKim Kulling cc4d6a54e2 OBJ.MTL: avoid possible conflict between anisotropy and adobe_xxx params (#6282)
* OBJ.MTL: avoid possible conflicts between anisotropy and adobe_xxx parameters in OBJ MTL parser
* Change BUFFERSIZE to constexpr and add new methods
---------
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-09 16:27:17 +02:00
Turo Lamminen bcc62230fc Export pugixml symbols from assimp library 2026-07-08 14:55:59 +03:00
Turo Lamminen c737b17667 Update pugixml to 1.16 2026-07-08 14:55:59 +03:00
Kim KullingandKim Kulling 1a810a922b Refactoring/cleanup tools (#6724)
* Refactor tools

* Introduce tangents visualisation

* Add tangents rendering

* Introduce class AssimpViewer

* Some refactorings

* Use regset function

* Some refactorings

* Add missing doc

* Reformat code

* Refactor Wireframe conditionals for clarity

* FIx more findings

* Replace strcpy by strncpy

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2026-07-07 18:01:07 +02:00
3edb902014 Fix two compiler warnings (#6669)
* Fix two compiler warnings

With GCC 16:
```
/assimp/code/AssetLib/MS3D/MS3DLoader.cpp:633:28: error: variable ‘qu’ set but not used [-Werror=unused-but-set-variable=]
  633 |                 aiQuatKey* qu = nd->mRotationKeys;

```

and also (with GCC 13)

```
In file included from /build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/Common/StbCommon.h:116,
                 from /build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/Common/Assimp.cpp:1314:
In function 'int stbi__compute_transparency16(stbi__png*, stbi__uint16*, int)',
    inlined from 'int stbi__parse_png_file(stbi__png*, int, int)' at /build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/../contrib/stb/stb_image.h:5217:52:
/build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/../contrib/stb/stb_image.h:4943:15: error: 'tc16[0]' may be used uninitialized [-Werror=maybe-uninitialized]
 4943 |          p[1] = (p[0] == tc[0] ? 0 : 65535);
      |          ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/../contrib/stb/stb_image.h: In function 'int stbi__parse_png_file(stbi__png*, int, int)':
/build/jenkins/workspace/lcg_mr_pipeline/build/externals/assimp-6.0.5/src/assimp/6.0.5/code/../contrib/stb/stb_image.h:5082:17: note: 'tc16[0]' was declared here
 5082 |    stbi__uint16 tc16[3];
      |                 ^~~~
```

* Update MS3DLoader.cpp

---------

Co-authored-by: Juan Miguel Carceller <jmcarcell@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
Co-authored-by: Turo Lamminen <turol@users.noreply.github.com>
2026-07-04 03:30:11 +03:00
netliomax25-codeandKim Kulling 4b0dea0349 Harden aiGetMaterialString against malformed serialized string proper… (#6680)
* Harden aiGetMaterialString against malformed serialized string properties

* Use aiString::Set for key in material string test helper

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-03 10:45:18 +02:00
Arthur ChanandKim Kulling e2fd15f8f7 OSS-Fuzz: Add new postprocessing fuzzer (#6695)
Signed-off-by: Arthur Chan <arthur.chan@adalogics.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-02 15:32:23 +02:00
Sidhartha kumarandKim Kulling a20c3a29be Fix #6614: Validate file-controlled indices in HL1 read_meshes (#6699)
* Fix #6614: Validate file-controlled indices in HL1 read_meshes

* Refactor: extract validation helpers and use get_buffer_data for tricmds

- Replace inline bounds checks with reusable static helpers:
  validate_index(), validate_bone_index(), advance_mesh_command_offset(),
  validate_mesh_command_vertex_count()
- Replace reinterpret_cast-based pointer arithmetic with
  get_buffer_data<T>() for tri-command walking (fixes SonarQube S3630)
- Use validated texture_index for mMaterialIndex assignment
- Value-initialize mMeshes array to nullptr

* Update HL1MDLLoader.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-02 11:05:54 +02:00
AutoJanitorandKim Kulling 16c50d7b53 Collada: read <input> offset without aliasing into size_t (#6715)
ReadInputChannel read the per-index <input> "offset" attribute by
casting channel.mOffset (a size_t) to unsigned int& and writing the
4-byte value through it. On big-endian hosts that 4-byte write lands in
the high word of the 8-byte size_t, so offset="1" became 4294967296,
numOffsets exploded, and importing the file failed (std::bad_alloc, or
the "Expected different index count in <p> element" error, #4788).

Read into a real unsigned int and assign, which is correct on both
endiannesses.

Verified on POWER8: cube_triangulate.dae fails to import on big-endian
ppc64 before this change and imports correctly after; little-endian
(ppc64le and x86_64) is unchanged.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-02 09:49:35 +02:00
dependabot[bot]andKim Kulling e86df1f8b1 Bump actions/cache from 5 to 6 (#6722)
Bumps [actions/cache](https://github.com/actions/cache) from 5 to 6.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-07-01 11:18:03 +02:00
Davide Masserut 831ab409d2 Add 3mf production extension support (#6721)
* Add 3MF Production Extension support to the importer

The 3MF Production Extension lets a package split its model data across
multiple .model parts inside the ZIP container. Build <item> and
<component> elements reference objects in other parts via a "p:path"
attribute, and "objectid" then indexes into that referenced part.

Real production packages previously failed to load any geometry: the
importer only opened the root model part and keyed resources by a single
global id. Because object ids are only unique within a part (producers
routinely reuse id="1" across files), resources are now scoped per part.

- D3MFOpcPackage: expose the normalized root part path and allow opening
  arbitrary model parts on demand (OpenPart/CloseStream), plus a shared
  path-normalization helper; quiet warnings for referenced .model/.rels.
- XmlSerializer: scope resources per file (mResourcesByFile), parse each
  part via ReadModel, eagerly load referenced parts before storing
  materials (keeps material indices valid under ValidateDataStructure),
  and resolve build items / components by (file, objectid).
- Aggregate meshes from every loaded part into the scene.

Tests: cube_gears_prod_req.3mf (build-item paths, 17 meshes from 17 parts
all using objectid=1) and a synthetic production_components.3mf
(component paths into two parts both using objectid=1, 2 meshes).

Assisted-by: Claude Code (Claude Opus 4.8)

* Document 3MF test model fixtures

Add a README documenting the provenance, licensing, and purpose of the
.3mf fixtures in test/models/3MF/, following the existing per-directory
README convention (AMF, USD, X3D, WRL). Notably records the BSD-2-Clause
source of cube_gears_prod_req.3mf (3MF Consortium production sample).

Assisted-by: Claude Code (Claude Opus 4.8)
2026-06-29 13:11:00 +02:00
SABITHSAHEBandKim Kulling 49fa5d051e Prevent out-of-bounds access from invalid weight bone references (#6700)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-26 22:15:09 +02:00
alhudaandKim Kulling 50cd1ef381 bound 3mf property and vertex indices in xmlserializer (#6709)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-25 21:22:53 +02:00
mosfet80andKim Kulling 3be4095a48 Update Hunter version to 0.26.10 (#6696)
CMake 4+ support set CMAKE_POLICY_VERSION_MINIMUM=3.5

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-24 13:59:37 +02:00
dependabot[bot]andKim Kulling 818f73f99a Bump actions/checkout from 6 to 7 (#6713)
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-23 21:38:00 +02:00
jasonmli8andKim Kulling 5f1ba0eec4 Validate inverseBindMatrices in glTF 2.0 (#6688)
* Validate inverseBindMatrices in glTF 2.0

Add additional validation when parsing glTF assets, checking accessor associated with skin inverseBindMatrices for contraints specified by the glTF spec. This includes asseting a 4x4 matrix type, floating-point component type, count < number of joints, and last row is [0.0, 0.0, 0.0, 1.0].

Fixes #6612

Signed-off-by: Jason Li <jasonmli@amazon.de>

* Enhance validation for inverseBindMatrices accessor

Added validation for inverseBindMatrices size and stride.

---------

Signed-off-by: Jason Li <jasonmli@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-22 21:25:37 +02:00
alhudaandKim Kulling 4073e1fd09 bound edge index in ndo face edge walk (#6706)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-22 16:29:51 +02:00
SAUD SATOPAYandKim Kulling 381b82cb2b B3D: validate chunk size against buffer and parent chunk (#6705)
ReadChunk() pushed _pos + sz onto the chunk stack using an unvalidated, attacker-controlled size. As a result ChunkSize() (computed as _stack.back() - _pos) could either report a value far larger than the remaining file, or underflow to a huge size_t when a nested chunk overran its parent. The element counts derived from ChunkSize() in ReadVRTS() and ReadTRIS() then drove unbounded _vertices.resize() / new aiFace[] allocations on crafted .b3d input.

Validate each chunk's extent at the ReadChunk() chokepoint (it must fit within the file and within its enclosing chunk) and make ChunkSize() underflow-safe, hardening every downstream chunk consumer at once.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-22 15:32:51 +02:00
Sidhartha kumarandKim Kulling e04b60f615 MD5: guard null mIndices and fix index-check off-by-one in MakeDataUnique (#6701)
* MD5: guard null mIndices and fix index-check off-by-one in MakeDataUnique

* Refactor MD5Importer to initialize flags separately

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-18 21:14:59 +02:00
alhuda f3e5f003b3 bound skin weight vertex index in x importer (#6698) 2026-06-15 08:39:31 +02:00
jasonmli8andKim Kulling 0a343958b1 Fix ASE importing (#6686)
* Fix ASE .Target node addition

When adding a new .Target node, shift performed to existing mChildren would overwrite entries before they were copied. This results in mChildren duplicating or losing elements. This change porperly shifts the nodes in the array.

Fixes #6617

Signed-off-by: Jason Li <jasonmli@amazon.de>

* Delete dummy mesh before discarding in ASEImporter

Properly delete meshes to be skipped when creating output mesh list. mColors[2] is also used as a temporary pointer that gets cleaned up later, so deletion is defered.

Signed-off-by: Jason Li <jasonmli@amazon.de>

---------

Signed-off-by: Jason Li <jasonmli@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-12 16:33:34 +02:00
Arthur ChanandKim Kulling 71b00a5df3 OSS-Fuzz: Add new fuzzer targets roundtrip process (#6693)
Signed-off-by: Arthur Chan <arthur.chan@adalogics.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-12 14:33:03 +02:00
Alejandro GonzálezandKim Kulling b3c7df7419 FVFData support for multiple UV Sets (#6689)
* FVFData support for multiple UV Sets
---------
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-11 21:47:18 +02:00
Kim Kulling 255c01edea Add star history section to Readme (#6692)
Added star history chart section to the README.
2026-06-11 21:02:26 +02:00
Kim Kulling f59cf099d5 Add check for empty vertex positions before memcpy (#6691)
- closes https://github.com/assimp/assimp/issues/5958
2026-06-10 21:50:54 +02:00
Kim Kulling abc3784e39 Correct material index handling in XFileImporter (#6684)
* Correct material index handling in XFileImporter
2026-06-09 13:20:23 +02:00
alhudaandalhudz 303be98031 reject md2 files with zero vertex count (#6682)
Co-authored-by: alhudz <al.hudz.k@gmail.com>
2026-06-08 16:33:47 +02:00
alhudaandalhudz a7b0dd2777 fix off-by-one face index check in lwo importers (#6679)
Co-authored-by: alhudz <al.hudz.k@gmail.com>
2026-06-07 21:12:29 +02:00
Matthew PohlmannandKim Kulling ace8c310f5 Fix aiGetMaterialProperty in the presence of material keys that are prefixes of other keys (#6603)
* Fix aiGetMaterialProperty in the presence of material keys that are prefixes of other keys

* Revert to using strncmp but use AI_MAXLEN as our max length. Since aiString can never be longer than this we'll either:
1. Finish comparing before AI_MAXLEN
2. Stop comparing after AI_MAXLEN and consider the strings "equal" even if "pKey" is longer

This feels like a reasonable compromise to avoid malformed (non zero terminated) strings since I wouldn't expect a property name to be 1024 characters long.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-04 13:18:27 +02:00
8874ef595b fix oob vertex index check in unreal importer (#6677)
Co-authored-by: alhudz <al.hudz.k@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-04 13:04:55 +02:00
Sai Asish YandKim Kulling eb84eec580 fix: prevent heap buffer overflow in CSM loader on non-positive frame range (#6649)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-04 11:30:46 +02:00
Pichas afc8a101f6 add impl (#6674) 2026-06-04 11:08:11 +02:00
Sai Asish Y 24bd7ee6f6 Fix glTF2 ImportEmbeddedTextures NULL deref when mimeType lacks '/' (#6645)
ImportEmbeddedTextures did strchr(mimeType, '/') + 1 and then null-checked
the offset pointer, so a mimeType without a slash produced the bogus address
0x1 and the subsequent strncmp dereferenced it. Check the strchr result
before applying the offset.

Fixes #6608

Signed-off-by: SAY-5 <say.apm35@gmail.com>
2026-06-03 13:57:05 +02:00
uwezkhanandKim Kulling b559be0281 Assbin: Validate mesh and texture allocation sizes (#6641)
* Assbin: Validate mesh and texture allocation sizes
---------
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-02 15:23:20 +02:00
joseph-moore-COandKim Kulling 1962da5ac4 Use raw string for regex with invalid escape sequence (#6640)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-02 12:49:28 +02:00
Silvio TraversaroandKim Kulling 9a486a72e4 Require C++17 for public headers in CMakeLists (#6627)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-02 11:21:24 +02:00
DavidKorczynskiandKim Kulling 626219cdd3 Fuzz: add harnesses to be consumed by OSS-Fuzz (#6636)
Adds multiple format specific harnesses to be consumed by OSS-Fuzz. Some
changes are needed in OSS-Fuzz's build.sh which will follow once merged.

The main goal is to increase coverage and I have verified locally that
indeed the coverage is increased in the dedicated formats relative to a
recent OSS-Fuzz coverage report e.g.
https://storage.googleapis.com/oss-fuzz-coverage/assimp/reports/20260504/linux/report.html

Signed-off-by: David Korczynski <david@adalogics.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-06-01 16:45:57 +02:00
mosfet80 cac67afe47 Update Hunter version to 0.26.9 (#6676)
fix CMake 4+ compatibility
2026-06-01 16:03:23 +02:00
Steve M be3d938e3e Merge pull request #6673 from assimp/revert-6549-fix-memory-leak-for-usd-importer
Revert "Fix memory leak for USD importer"
2026-05-29 16:48:13 -07:00
Steve M 8bbcddf668 Revert "Fix memory leak for USD importer (#6549)"
This reverts commit 29df28d7d3.
2026-05-29 16:39:27 -07:00
jasonmli8andKim Kulling b735327016 Fix CVE-2025-70069 (#6664)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-28 15:27:00 +02:00
jasonmli8andKim Kulling 2ffbe3c13d Fix CVE-2025-70070 (#6665)
* Fix CVE-2025-70070

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-27 22:11:23 +02:00
jasonmli8andKim Kulling 29fdb3e7a7 Fix CVE-2025-70071 (#6666)
* Fix CVE-2025-70071

* Use 'auto' for full_length variable declaration

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-27 13:25:05 +02:00
Sai Asish YandKim Kulling d24b85319b Fix glTF2 ImportAnimations null deref on invalid target node (#6646)
* fix(glTF2): guard against null target node in ImportAnimations

If a glTF2 animation channel references a node index whose LazyDict slot
is null (e.g. animations defined without a matching nodes array),
r.nodes[i] dereferences a null pointer and crashes. Validate the Ref
before indexing and skip the channel with a warning. Resolves #6611.

* fix(glTF2): use raw pointer to clarify null check in ImportAnimations

Extract nodePtr from Ref<Node> before the null guard so the checker has
a direct pointer variable rather than operator->() in the condition,
avoiding a Sonar reliability flag on the indirect dereference pattern.

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>

---------

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-26 21:31:36 +02:00
jasonmli8 e8651c3521 Fix CVE-2025-70072 (#6667)
- Validate the number of indices before accessing them.
2026-05-25 18:09:25 +02:00
metsw24-maxandKim Kulling 0404c8758c Migrate OBJ parser from fixed-size stack buffer to std::string (#6654)
* Migrate OBJ parser from fixed-size stack buffer to std::string
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-19 19:00:38 +02:00
metsw24-max e7aeaf0632 replace unsafe strncpy with aiString::Set() in five asset loaders (#6652) 2026-05-15 19:11:05 +02:00
Kim Kulling e1e015672a add fxb mapping to export (#6644) 2026-05-12 21:00:49 +02:00
Kim Kulling 116c96c46d Update AGENTS.md with memory guideline (#6639)
* Update AGENTS.md with memory guideline

Added a reminder for agents to never answer from memory.

* Update AGENTS.md

* Fix typo in 'Methology' to 'Methodology'
2026-05-08 14:13:00 +02:00
metsw24-maxandKim Kulling 531f73597e Prevent Heap Buffer Overflow in MaterialSystem String Assignments (#6628)
* Prevent Heap Buffer Overflow in MaterialSystem String Assignments

* Log warning for truncated material property key

Add warning log for key length exceeding AI_MAXLEN.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-05-07 15:28:34 +02:00
392a658f9c Bugfix/sparky kitty studios (#6623)
* Fixed regression that scrambled FBX blendshape order.

* Merge master to this branch

---------

Co-authored-by: Lux <lxw404@gmail.com>
Co-authored-by: Lux <52231149+lxw404@users.noreply.github.com>
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2026-04-30 11:15:09 +02:00
uwezkhanandKim Kulling 11a5d1b8ef Fix out-of-bounds read in StreamReader::IncPtr (#6600)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-29 13:24:29 +02:00
uwezkhanandKim Kulling 9e56e52252 Fix integer truncation in StreamReader size calculations (#6601)
* Fix integer truncation in StreamReader size calculations
* improves type clarity and avoids implicit conversions by replacing C-style casts with static_cast

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-29 08:27:50 +02:00
uwezkhanandKim Kulling 86ae4876fb Hardening aiString deserialization in AssbinLoader to prevent stack b… (#6606)
* Hardening aiString deserialization in AssbinLoader to prevent stack buffer overflow

* Simplify string read error handling in AssbinLoader

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-28 14:44:07 +02:00
fb9a58735d M3D: fix overflow (#6610)
* M3D: fix overflow

---------

Co-authored-by: Kazuki Y <6259214+kazu0617@users.noreply.github.com>
Co-authored-by: kazu0617 <kazu0617@protonmail.com>
2026-04-27 11:35:28 +02:00
Matthew PohlmannandKim Kulling 25a1318534 Fix glTF2 occlusion strength import/export and normal scale export (#6602)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-23 14:20:06 +02:00
Matthew Pohlmann ede83d7fe2 glTF2: Fix extracting interleaved buffer data (#6605)
* Fix extracting interleaved buffers

* Fix some issues noted by coderabbit:
- Remove narrowing cast from size_t to unsigned int
- Validate accessor count is <= space in buffer (maxCount)
- Ensure remapped indices only access data valid for this accessor by checking count and not maxCount
2026-04-23 14:02:06 +02:00
dependabot[bot] 17c12da558 Bump softprops/action-gh-release from 2 to 3 (#6597)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 2 to 3.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v2...v3)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-14 14:04:53 +02:00
James SharamandKim Kulling de77101866 Fix for CanRead function for FBXImporter (#6158)
* Fixed CanRead function for FBXImporter, which is important when reading from memory

* Update FBXImporter.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-07 10:52:24 +02:00
158da57515 Fixed a container-overflow vulnerability in Assimp::ColladaLoader::BuildMeshesForNode (#6575)
The root cause was an unchecked access to the `newMats` vector using `matIdx`.
When a material name (`meshMaterial`) is not found in `mMaterialIndexByName`,
`matIdx` defaults to 0.  If `newMats` is empty (which happens if the material
library is empty or failed to load), accessing `newMats[0]` results in a
container-overflow.

The fix involves adding a bounds check `matIdx < newMats.size()` to the
condition guarding the access to `newMats`. Additionally, based on maintainer
feedback, I added a warning log `ASSIMP_LOG_WARN` when the index is out of
bounds, to inform the user about the missing material definition or broken
reference.

I verified the fix using the provided reproduction command. The
container-overflow is no longer triggered. I also built and ran the unit tests.
Since `bin/unit` was missing, I manually built the unit tests using
`cmake.real` and `ninja` in `/src/assimp/build_tests` with
`ASSIMP_BUILD_TESTS=ON`, `ASSIMP_BUILD_ZLIB=ON`, and
`ASSIMP_WARNINGS_AS_ERRORS=OFF` (to bypass a gtest compilation warning), and
updated `run_tests.sh` to point to the built binary. All 584 tests passed.

Fixes: https://issues.oss-fuzz.com/issues/483102958

Signed-off-by: Bill Wendling <morbo@google.com>
Co-authored-by: CodeMender <codemender-patching@google.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-06 17:31:59 +02:00
021bbff3e5 Feature/rust bindings: Exterimental bindings (#6467)
* Add files for assimp rust wrapper

* Fix bindgen usage.

* Add missing includes for the rust bindings.

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update build.rs

* Fix formatting in Cargo.toml

* Remove generated file

---------

Co-authored-by: Kim Kulling <kullingk@LDED5178.corp.draeger.global>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-04-06 16:34:15 +02:00
9c10e7d2b5 test: use epsilon comparison for FMA-sensitive API tests (#6591)
When compiling with -march=znver4 (or any arch with FMA), GCC's default
-ffp-contract=fast contracts a*b+c into FMA opportunistically. The same
inline math function compiled in the shared library and in the test
binary can get different FMA contraction decisions due to different
optimization contexts, producing bit-different FP results.

Three API tests compare C++ direct calls (inlined into test TU) against
C API wrapper calls (through libassimp.so) using EXPECT_EQ (bit-exact),
which fails when the compiler contracts differently across TUs.

Verified via disassembly: the library uses vfnmadd FMA instructions
(3 roundings) while the test binary uses separate vmulss+vsubss
(6 roundings) for the same computation.

Replace EXPECT_EQ with Equal(epsilon) for the three affected tests:
- aiMatrix3FromToTest: use machine epsilon (~1.19e-7)
- aiMatrix4FromToTest: use machine epsilon (~1.19e-7)
- aiQuaternionFromNormalizedQuaternionTest: use 1e-4 because FMA
  differences in 1.0-x*x-y*y-z*z can flip a near-zero residual's sign,
  causing w=0 vs w=sqrt(tiny)≈1e-4

Fixes #6246

Co-authored-by: Chris de Claverie <declaverie@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-01 19:16:58 +02:00
dimonpandKim Kulling 048becec92 Fix linkage issue for ai_epsilon in C++20 modules (#6592)
* Add inline to ai_epsilon to avoid ODR violations
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-04-01 09:36:11 +02:00
Kim Kulling 8ff005570a Bugfix/fix unittest for cla7aye15 i4nd fix skipspaces (#6590)
* Fix conditional check in SkipSpaces function to prevent out-of-bound access.

The `SkipSpaces` function's condition was updated to ensure that the pointer check `in != end` is evaluated before dereferencing the pointer. This change prevents potential out-of-bound access when the input pointer reaches the end.

* Avoid input is wrong

* Fix all in != end

* Fix some minor bugs

* Change size to capacity

* Obj: Fix unittest
2026-03-24 21:23:38 +01:00
copycdandKim Kulling fcb1702162 + An error occurs when it is 0 (#6544)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-03-17 00:33:49 +01:00
EasyT_TandKim Kulling b5f567bd3a Fix animations for B3DImporter (#6547)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-03-16 19:00:36 +01:00
Shutd0wnsandKim Kulling 1569f6a9e0 Fixed logic for finding min/max for glTF2Exporter (#6552)
Fixes bug introduced in d1b73df, where min was always set to DBL_MIN

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-03-16 16:43:30 +01:00
Pichas 29df28d7d3 Fix memory leak for USD importer (#6549)
* initial commit

* remove unused function
2026-03-14 23:57:22 +01:00
dependabot[bot]andKim Kulling b10b8ab99a Bump actions/upload-artifact from 6 to 7 (#6551)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-03-12 16:00:25 +01:00
Matthew Suozzo b2852bc49b glTF2: Fix heap-buffer-overflow in GetVertexColorsForType (#6558)
The `GetVertexColorsForType` function previously used `input->count`
(the total number of elements in the accessor) to allocate the output
array and bound the conversion loop. However, when a
`vertexRemappingTable` is provided, `ExtractData` extracts a subset of
elements matching the size of the remapping table rather than the full
accessor count.

In cases where the remapping table was smaller than the accessor count
(including empty tables), the subsequent loop would perform
out-of-bounds reads on the `colors` buffer allocated by `ExtractData`.

This fix captures the actual number of elements extracted by
`ExtractData` and uses this value for the output allocation and loop
iteration, ensuring memory safety when vertex remapping is active.

Verified with ASan and existing unit tests.
2026-03-11 15:53:34 +01:00
Kim Kulling e70199446d Refactor material system (#6563)
* Refactor material system

* Fix sonarqube finding
2026-03-08 23:40:09 +01:00
Kim Kulling dc54c9fdea [Draft] Create AI Tool Use Policy for contributors (#6553)
Added a comprehensive AI Tool Use Policy outlining guidelines for contributors on using AI tools, ensuring human oversight and accountability in contributions.
- closes https://github.com/assimp/assimp/issues/6538
2026-03-08 21:27:08 +01:00
Kim Kulling 38f3e8d98b Add agents file. (#6562) 2026-03-07 00:42:53 +01:00
Steve Mandtellypresence 8a073f7cb4 Apply codeRabbit suggested fix(es) from assimp PR #6548 (#6557)
Co-authored-by: tellypresence <info@tellypresence.com>
2026-03-06 12:44:08 +01:00
Kim Kulling 553fbc1fdb LWO: Fix negative iterator access, ptr was before begin (#6555) 2026-03-05 23:48:33 +01:00
dependabot[bot] e13e0b5b7d Bump actions/download-artifact from 7 to 8 (#6550)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 20:16:21 +01:00
Kim Kulling 929bff1830 Ply: Fix ply triangle-strip parsing. (#6548) 2026-02-28 21:56:02 +01:00
EarendelArcandKim Kulling 8ef1461cb8 glTF2: Preserve interpolation type and CubicSpline tangent data in animation keys (#6543)
fix(gltf2): preserve interpolation type and CubicSpline tangents

The glTF2 importer previously ignored the mInterpolation field and discarded
CubicSpline tangent data, leading to incorrect animation playback.

- Implement MapInterpolation() to map glTF2 interpolation types to Assimp.
- Set mInterpolation for all aiVectorKey and aiQuatKey instances.
- For CUBICSPLINE samplers, store [in-tangent, value, out-tangent] triplets
  (N x 3 keys) instead of discarding tangents.
- Fixes rendering consistency for InterpolationTest.glb where STEP, LINEAR,
  and CUBICSPLINE rows previously rendered identically.

Affected channels: mPositionKeys, mRotationKeys, mScalingKeys.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-26 15:33:03 +01:00
Kim Kulling 10be273aea Update supported version in SECURITY.md (#6459)
* Update supported version in SECURITY.md

- Preparation for bugfix release v6.0.5

* Update CMakeLists.txt

* Update aiGetVersionPatch test to expect version 5
2026-02-25 11:13:44 +01:00
Carter RennickandKim Kulling 3e672ff856 Fixed compiler error on platforms where unsigned int is not 32 bit (#6541)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-23 21:26:18 +01:00
3e188e6768 HL1MDLLoader: fix segfault in destructors (#6537)
In `HL1MDLLoader::read_animations`, the arrays for `scene_->mAnimations`
and `scene_animation->mChannels` were allocated using `new T*[count]`.
This performs default initialization, which leaves the pointer elements
with indeterminate (garbage) values.

If an exception (such as a `DeadlyImportError` from malformed input) is
thrown during the loop populating these arrays, the `aiScene` or
`aiAnimation` destructors are invoked during stack unwinding. These
destructors iterate through the allocated arrays and call `delete` on
each element. Because the arrays contained garbage values for indices
not yet reached by the loader, the destructor attempted to delete
invalid memory addresses, leading to a segmentation fault.

This patch changes the allocations to use value-initialization (`new
T*[count]()`), ensuring all pointers are initialized to `nullptr`. Since
`delete nullptr` is a safe no-op, the destructors can now safely clean
up partially initialized objects during an exception.

Fixes: https://issues.oss-fuzz.com/issues/483188619

Co-authored-by: CodeMender <codemender-patching@google.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-22 21:27:05 +01:00
21607dfb75 Obj: Fix heap-buffer-overflow in getFace via vertical tabs (#6540)
The `ObjFileParser::getFace` method failed to recognize the vertical tab
character (`\v`, 0x0b) as a separator. While the `IsSpaceOrNewLine`
utility handles most whitespace (space, tab, CR, LF, FF), it excludes
`\v`.

When encountering a vertical tab, the parser fell through to an `else`
block that calls `::atoi(&(*m_DataIt))`. Because `atoi` treats `\v` as
whitespace per the C standard, it skips the character and continues
reading. If `\v` is located at the end of the buffer (e.g., followed by
a newline at the buffer boundary), `atoi` can read past the allocated
memory, triggering a heap-buffer-overflow.

This fix explicitly checks for `\v` and treats it as a separator,
resetting the position counter and preventing the invalid `atoi` call.

Verified with AddressSanitizer and confirmed that all 584 existing unit
tests pass.

Fixes: https://issues.oss-fuzz.com/issues/476180586

Signed-off-by: Bill Wendling <morbo@google.com>
Co-authored-by: Meder Kydyraliev <meder@google.com>
Co-authored-by: CodeMender <codemender-patching@google.com>
2026-02-21 19:19:02 +01:00
970f8691dd FBXExporter: Fix stack-use-after-scope in WriteObjects (#6472)
The FBX exporter was unconditionally dereferencing a map iterator (`tp_elem`)
even when the key was not found (i.e., `tp_elem == tpath_by_image.end()`).
This resulted in a stack-use-after-scope error when accessing `tp_elem->second`
to populate "FileName" and "RelativeFilename" nodes, as dereferencing the
end iterator of the map accessed invalid stack memory (the map's sentinel).

The code already correctly initialized a local `tfile_path` variable based
on whether the iterator was valid. This patch updates the `AddChild` calls
to use `tfile_path` instead of dereferencing the potentially invalid iterator.


Fixes: https://issues.oss-fuzz.com/issues/465494996

Co-authored-by: CodeMender <codemender-patching@google.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-17 19:16:53 +01:00
8acd2c964e glTF2: Fix heap-buffer-overflow in Accessor validation and size calculation (#6473)
* glTF2: Fix heap-buffer-overflow in Accessor validation and size calculation

This patch fixes a heap-buffer-overflow in
`glTF2::Accessor::ExtractData` caused by incorrect bounds validation and
available size reporting.

The vulnerability stemmed from two issues in `glTF2Asset.inl`:

1.  **Underestimated validation in `Accessor::Read`**: The logic used
    `GetBytesPerComponent() * count` to validate the required buffer
    size. This failed to account for the actual `stride`, allowing
    accessors to pass validation even if their total footprint
    (including stride) exceeded the buffer view.
2.  **Incorrect size reporting in `Accessor::GetMaxByteSize`**: The
    function returned the total `bufferView->byteLength` while ignoring
    the `byteOffset`. Since the accessor data starts at `byteOffset`,
    the actual available space is `byteLength - byteOffset`. This led
    `ExtractData` to permit reads that extended beyond the end of the
    allocated buffer.

Changes:
*   Modified `Accessor::Read` to use `GetStride() * count` for length
    validation.
*   Updated `Accessor::GetMaxByteSize` to correctly return
    `bufferView->byteLength - byteOffset` for standard accessors and
    `sparse->data.size()` for sparse accessors.

Co-authored-by: CodeMender <codemender-patching@google.com>
Fixes: https://issues.oss-fuzz.com/issues/483102963

* address comment

---------

Co-authored-by: CodeMender <codemender-patching@google.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-17 10:57:40 +01:00
ZhangJYandKim Kulling b4c7912d21 Fix heap-buffer-overflow in OpenGEXImporter::handleIndexArrayNode() (#6470)
The mColors[0] array was allocated with m_numColors elements but
indexed up to mNumVertices (= numFaces * 3), causing an out-of-bounds
write when the color count is less than the vertex count.

Allocate mColors[0] with mNumVertices (matching mNormals and
mTextureCoords), and add a bounds check on idx before reading
from the source color array.

Fixes #6468

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-10 23:19:12 +01:00
Kim Kulling e38451ff6c Add developer quickstart section to Readme (#6474)
* Add developer quickstart section to Readme

-Added a quickstart guide for developers to clone and build the project.
- closes https://github.com/assimp/assimp/issues/6469

* Change headings from H3 to H2 in Readme.md
2026-02-10 20:26:07 +01:00
Kyungjoon KoandKim Kulling 36c3a19aa8 Fix invalid verifying in OpenDDLParser::parseStringLiteral (#6314)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-02-06 13:34:23 +01:00
peng 5c5ae38934 LWO: Fix heap buffer overflow in LWOImporter::GetS0 (#6451)
* LWO: Fix heap buffer overflow in LWOImporter::GetS0
* Add strict buffer boundary checks to prevent out-of-bounds reads on malformed or unterminated strings.
Fixes #6169 (CVE-2025-5167)
2026-02-03 19:21:06 +01:00
pengandKim Kulling 18798f150d MDL: Fix heap buffer overflow in MDLImporter frame parsing (#6456)
Add buffer boundary checks before reading frame data to prevent out-of-bounds reads on malformed MDL files.
Fixes #6172 (CVE-2025-5200)

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-01-29 21:10:18 +01:00
peng ae6633ef8a Fix AC3DImporter heap-buffer-overflow by validating mesh vertex bounds (#6458)
Add validations check in AC3DImporter::ConvertObjectSection to ensure that writing TriangleStrip vertex data does not exceed mesh->mNumVertices allocation.
Fixes #6015 (CVE-2025-2754)
Fixes #6018 (CVE-2025-2756)

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
2026-01-28 21:33:55 +01:00
Kim Kulling e0b52347c6 Update copyright year and project version (#6454)
* Update copyright year and project version

- Fixes version in lib

* Update copyright year to 2026

* Update copyright year to 2026 in Version.cpp

* Update copyright year and version patch test

* Fix copyright year

* Adapt copyrights
2026-01-24 21:57:37 +01:00
Nicky Kitchingman d5091bbb71 Fix some recently implemented comparisons of token strings (#6452)
* Fix some recently implemented comparisons of token strings. Previously, the `keyword` included the following space along with the token, which broke the string comparison using the equality operator.

* Rename `getEndOfToken` -> `getNextDelimiter`, to reflect the actual usage
2026-01-22 11:34:08 +01:00
pengandKim Kulling cf7b652190 MD3: Fix MD3Importer surface header bounds checks to prevent heap overflow (#6441)
Improve bounds checks in MD3Importer::ValidateSurfaceHeaderOffsets to prevent pcSurf from accessing data outside the MD3 buffer (fixes #6070, CVE-2025-3549).

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-01-20 00:29:27 +01:00
tyler92 129c1333e6 MDL/HL1: bounds-checked buffers and safer parsing (#6445) 2026-01-19 21:25:09 +01:00
pengandKim Kulling d1e6bcff6b MDC: Fix MDCImporter surface header bounds and endianness checks (#6440)
- Validate ulOffsetEnd in MDCImporter::ValidateSurfaceHeader to
  prevent pcSurface2 from moving past the MDC buffer(fixes #6167, CVE-2025-5165).
- Apply AI_SWAP4 to ulOffsetShaders before using it in bounds checks.

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-01-15 13:23:54 +01:00
Vitaly OvchinnikovandKim Kulling d8a9074cd0 OBJ: avoid extra scanning while reading faces in ObjFileParser.cpp (#6281)
* obj: avoid extra scanning while reading faces

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-01-14 16:43:36 +01:00
tyler92 1ce99b9cf7 MD5: Fix uninitialized pointer dereference for file with invalid vertex index (#6439)
A segmentation fault occurred while parsing an MD5 file that contains an invalid vertex index.
The issue was caused by mScene->mMaterials not being kept in sync with mScene->mNumMaterials.
As a result, the aiScene destructor could call delete on uninitialized pointers. This patch
ensures that mScene->mNumMaterials always matches the actual contents of the mScene->mMaterials
array. That way, if an exception is thrown during file import, delete is only called for
properly allocated aiMaterial objects.
2026-01-12 15:08:31 +01:00
LP 522c703bb9 fuzz: Fix memory leak in ForceFormat helper (#6435)
The ForceFormat function unregisters importers from the Importer
but doesn't delete them, causing memory leaks detected by ASan
during OSS-Fuzz check_build.

When UnregisterLoader is called, the importer is removed from the
internal list but the memory is not freed. Since the Importer
originally allocated these objects and we're removing them from
its management, we must delete them explicitly.

Also include BaseImporter.h to ensure complete type information
is available for proper deletion.

This fixes OSS-Fuzz check_build failures for all format-specific
fuzzers (obj, gltf, glb, fbx, collada, stl).
2026-01-09 11:02:21 +01:00
peng 17318b02cf MDC: Fix heap OOB read by validating vertex buffer boundaries (#6168) (#6438)
- Add explicit boundary checks for pcVerts and pcCVerts arrays in MDCImporter.
- Prevents heap out-of-bounds reads with malformed or truncated files.
- Fixes CVE-2025-5166.

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
2026-01-09 08:59:22 +01:00
pengandKim Kulling ac8eac60a5 MDL: Fix synctype validation in MDLImporter to prevent OOB (#6437)
* MDL: Validate synctype > 0 in MDL 3/4/5 loader to prevent OOB access (#6170)

Signed-off-by: mapengyuan <mapengyuan@xfusion.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2026-01-07 10:50:12 +01:00
Kim Kulling c234aa28c6 Add CHANGES.md file (#6436) 2026-01-03 22:32:33 +01:00
LPandKim Kulling ae6f477604 Fuzzing: Add OSS-Fuzz integration and multiple format-specific fuzzers (#6429)
* fuzz: Add OSS-Fuzz integration and multiple format-specific fuzzers

* fuzz: Add GLB fuzzer and fix null pointer issue

- Add null check for mFileExtensions in ForceFormat() to prevent
  undefined behavior when the field is null
- Fix misleading comment in gltf fuzzer (only covers text format)
- Add separate GLB fuzzer for binary glTF format coverage
- Update OSS-Fuzz build script to include GLB fuzzer with corpus

* Add copyright and licensing information

Added licensing information and copyright notice to fuzzer_common.h

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-12-23 19:31:27 +01:00
hankarun 0fb7c4a439 Feature: Add EXT_texture_webp extension to glb importer (#6431)
* Add EXT_texture_webp extension texture read for glb file format.
2025-12-22 12:44:18 +01:00
ljgdsq 8c0ab23470 Fix UTF-8 flag check in CMakeLists.txt (#6432) 2025-12-21 18:19:10 +01:00
Kim KullingandKim Kulling f4980c455c Test against possible nullptr dereferencing (#6430)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-12-18 11:26:13 +01:00
dependabot[bot]andKim Kulling c58496185d Bump actions/cache from 4 to 5 (#6425)
Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-12-16 12:56:08 +01:00
dependabot[bot]andKim Kulling a438bbb271 Bump actions/upload-artifact from 5 to 6 (#6426)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-12-16 11:43:03 +01:00
dependabot[bot] 0373bbede8 Bump actions/download-artifact from 6 to 7 (#6427)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-16 11:22:14 +01:00
Kim Kulling c0b8cfaf41 Add closing brace to CMakePresets.json (#6424)
* Add closing braces to CMakePresets.json
2025-12-14 10:38:31 +01:00
Kim Kulling 5245511f1d Add new CMake preset for static build with double precision (#6414)
- Add static build preset
- Add build all preset
2025-12-13 09:58:49 +01:00
Matt PennyandKim Kulling e3b13a48a9 Fix incorrect FBX connection order (#6421)
PR #6120 fixed a macro which previously prevented std::unordered_multimap
from being used during FBX import when compiled with GCC.

This caused FBX::Element properties to be stored in arbitrary order,
but the order of connections ("C" properties) in FBX files matters.
The main issue I saw was incorrect materials.

This changes the type of FBX::ElementMap to always use std::multimap
(i.e., ordered). This was the behavior for years under GCC while the
broken macro was in use. Unordered containers are still used elsewhere
in the FBX importer to benefit from their performance.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-12-11 21:42:45 +01:00
Kim Kulling 9481ce8db9 Delete tools/coverity/assimp_modeling.cpp (#6422) 2025-12-10 16:38:09 +01:00
Kim Kulling 3761ee65c2 Update project details in Doxyfile (#6420) 2025-12-10 08:52:46 +01:00
Kim Kulling 75386282c1 Delete cmake-modules/FindDevIL.cmake (#6418) 2025-12-10 00:03:00 +01:00
Kim Kulling c087c20e8b Update stb_image.h to version 2.30 (#6419) 2025-12-09 23:52:34 +01:00
Kim Kulling 7d1fa60aa3 Implement overflow check in Q3DLoader (#6417)
* Implement overflow check in Q3DLoader
2025-12-09 23:28:44 +01:00
Kim KullingandKim Kulling 6ef6d84a7e Revert buggy PR (#6415)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-12-09 20:57:36 +01:00
Paul Zander 4d197881ff Only build collada test when importer/exporter is build (#6411)
See-also: https://bugs.gentoo.org/962559

Signed-off-by: Paul Zander <negril.nx+gentoo@gmail.com>
2025-12-05 19:57:44 +01:00
Kim Kulling 10cd8982b0 Update copyright year in materialgen.py (#6410)
* Update copyright year in materialgen.py

* Update copyright year in structsgen.py
2025-12-04 14:24:42 +01:00
+18 ac0cfc8d9c Feature/pjoe fix fbx export (#6405)
* fix: texture paths issues with fbx export

* Update LICENSE (#6327)

* FBX: Fix offset calculation by adding cursor check (#6337)

- closes https://github.com/assimp/assimp/issues/6336

* [CMake] -l (#6329)

- Fix zlib linkage.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Add null check for aiNode in AddNode method (#6348)

- Added null check for node in AddNode function.
- closes https://github.com/assimp/assimp/issues/6347

* fix large glb reading by providing a proper helper for reading size_t type (#6307)

Co-authored-by: Vitaly Ovchinnikov <v@ovch.ru>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Updated doc/Preamble.txt & SECURITY.md (#6338)

* Update LICENSE

* Update Preamble.txt

* Update SECURITY.md

* Remove GitHub's default comment

* Better README! Fixed discord link as well (#6351)

* Better README!

* PyAssimp: Re-add 'aiProcess_Triangulate' (#6335)

apparently, b9bfac0418 accidentally
removed a couple of lines with a botched copy'n'paste.

Co-authored-by: IOhannes m zmölnig <zmoelnig@umlautT.umlaeute.mur.at>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Fixed Build.md (#6354)

* Fixed itch.io spelling from itchi.io

* Fix hasTangentsAndBitangents method in AiMesh.java (#6345)

original code m_tangents != null && m_tangents != null; triggers error prone

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Added tangent handedness to glTF export (#6322)

* Added tangent handedness to glTF export

* Restore merging of near-identical vertices for JoinIdenticalVertices (#6278)

* Restore merging of near-identical vertices for JoinIdenticalVertices

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Add BOM skip and fix mtl parsing (#6253)

* Add BOM skip and fix mtl parsing
* Remove old code
* Fix #5635
* Add all attributes to ObjFileData
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Clone meshlab/tinyusdz repos in default location (#6239)

* Leave FETCHCONTENT_BASE_DIR as default to avoid target platform generated build file conflicts

* Attempt address sonarCloud complaint about generic-looking include file (bare "Parser.h")

---------

Co-authored-by: tellypresence <info@tellypresence.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Fix an invalid offsetof warning-as-error (#6359)

The code already disables the warning on clang. It's also caused on
GCC in some circumstances (particularly when building with
-D_GLIBCXX_DEBUG).

* Add unit test for subdivision modifier on Blender importer (#5345)

* Add unit test for subdivision modifier on Blender importer

Blend file is composed of default cube with subdivision modifier applied
and same cube with subdivision modifier.

* Update utBlenderImportExport.cpp

Fix compiler warning.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Change strcpy to strncpy for format hint safety (#6365)

* Update default material name handling (#6366)

* Replace strcpy by strncpy

* Bugfix/fix sonarcube findings (#6369)

* Fix sonarcube findings.
---------
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>

* Update texture output format in AssxmlFileWriter (#6372)

* Update texture output format in AssxmlFileWriter

* Collada: Fix overflow in CopyVertex (#6374)

* Fix overflow in CopyVertex

* COB: fix validation for ascii header (#6376)

* COB: fix validation for ascii header

* MD5: Fix face index allocation in MD5Parser (#6380)

- Ensure face indices are properly allocated and resized.
- closes https://github.com/assimp/assimp/issues/6379

* Removed unnecessary copy constructor declaration in aiVector3t (#6384)

* Removed unnecessary copy constructor declaration in aiVector3t
* Added copy constructor back in aiVector3t
* Added explicit declaration of assignment operator in aiVector3t

* Bump actions/upload-artifact from 4 to 5 (#6383)

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Bump actions/download-artifact from 5 to 6 (#6382)

Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Made the README more tidy & fix Build.md (#6371)

* Update LICENSE

* Update Preamble.txt

* Update SECURITY.md

* Remove GitHub's default comment

* Better README!

* Fix discord link! Boom, that's how it's done

* Fixed itch.io spelling from itchi.io

* Make README more tidy :)

AR is back! Anyways, I'm working on my horror game & making devlogs so I don't have time to write. Here's a small summary:
- Just placed the dir structure information correctly in one place so the README looks tidy.

* Add international download link for Visual Studio

* Fix out-of-range access cause of aiProcess_GenNormals : array size inconsistency of members of mesh after process (#6332)

* Fix aiProcess_GenNormals process: copy members of mesh corresponding with additional vertices

* Fix aiProcess_GenNormals process: Refoctoring

* refactoring: fix SonarQube Issue

* Update GenFaceNormalsProcess.cpp: fix small findings

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Fix Heap-buffer-overflow in Q3DImporter::InternReadFile (#6370)

Checks if multiplying texture width and height would overflow before
performing the operation. This avoids incorrect memory allocations and
potential crashes with very large textures.

Fixes #6358

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Revert "Refactoring: use using types (#6266)" (#6324)

* Revert "Refactoring: use using types (#6266)"

* fix: write textures to folder of PBRT file (#6099)

* fix: write textures to folder of PBRT file

* Refactor condition checks for empty vectors (#6385)

* Refactor based on SonarCube.

* Fix sonarcube stuff (#6387)

* Fix sonarcube stuff

* Update contact email for reporting vulnerabilities (#6389)

* [PyAssimp] Create `pyproject.toml` (#6378)

* Create pyproject.toml

* glTF2: Avoid lookups for generating IDs (#6120)

* glTF2: Reduce lookups for generating IDs
- closes https://github.com/assimp/assimp/issues/5661

* Refactor string checks and variable declarations (#6392)

* Refactor string checks and variable declarations

* Change string check from contains to find

* Fix syntax error in mesh node creation loop

* Fix the doxygen documentation from public headers (#6394)

* Add documentation comments to DeboneProcess.h

* Added static cast for conversion from uLong to unsigned int for compiler error (#6393)

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Reorganize code top prevent security warning. (#6395)

* Reorganize code to prevent security warning.

* Fix linkage (#6388)

* Fix linkage when all importers aren't part of the build.

* Update LineSplitter.h (#6396)

* Added missing scene extras properties for glTF2Importer (#6397)

* WiP. Passing USD prims along with render nodes to look for USD references. Save reference path to metaData['ref'] (#5807)

Signed-off-by: AMZN-Gene <genewalt@amazon.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Bump actions/checkout from 5 to 6 (#6401)

Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

* Update Readme.md (#6402)

* Update Readme.md

- Reorganize readme for code structure

* Update Readme.md

* Delete test/other/streamload.py (#6403)

* Update Readme.md

- Reorganize readme for code structure

* Update Readme.md

* Delete test/other/streamload.py

* Delete test/regression directory

* Update AndroidJNIIOSystem.cpp

* Update BundledAssetIOSystem.cpp

* Fixed DXFHelper using float instead of ai_real (#6404)

* Fixed DXFHelper using float instead of ai_real

* fixed cmake presets

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: AMZN-Gene <genewalt@amazon.com>
Co-authored-by: Pelle Johnsen <pelle.johnsen@gmail.com>
Co-authored-by: AbdulRehman <ardev1.deverson@proton.me>
Co-authored-by: Steven French <95558717+ZeunO8@users.noreply.github.com>
Co-authored-by: Vitaly Ovchinnikov <vitaly.ovchinnikov@gmail.com>
Co-authored-by: Vitaly Ovchinnikov <v@ovch.ru>
Co-authored-by: umläute <umlaeute@users.noreply.github.com>
Co-authored-by: IOhannes m zmölnig <zmoelnig@umlautT.umlaeute.mur.at>
Co-authored-by: fifth_light <liu-yu-jie@foxmail.com>
Co-authored-by: Luca Della Vedova <lucadv@intrinsic.ai>
Co-authored-by: Matt Penny <mwpenny@users.noreply.github.com>
Co-authored-by: Paul Bauriegel <paul.bauriegel@web.de>
Co-authored-by: Steve M <madsen.steve@yahoo.com>
Co-authored-by: tellypresence <info@tellypresence.com>
Co-authored-by: Sami Liedes <sami.liedes@iki.fi>
Co-authored-by: Alexandre Avenel <avenel.alexandre@gmail.com>
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
Co-authored-by: EddieBreeg <eddiebreeg0@protonmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: sSsA01 <59872472+Riv1s-sSsA01@users.noreply.github.com>
Co-authored-by: Jan Grulich <jgrulich@redhat.com>
Co-authored-by: Jan Honsbrok <jan.honsbrok@gmail.com>
Co-authored-by: thedestroyer4312 <trevortsai1@gmail.com>
Co-authored-by: Jerome St-Louis <jerome@ecere.com>
Co-authored-by: John Curley <johndanielcurley@gmail.com>
Co-authored-by: Orleonn <76880668+Orleonn@users.noreply.github.com>
Co-authored-by: Gene Walters <32776221+AMZN-Gene@users.noreply.github.com>
Co-authored-by: JakobPer <JakobPer@protonmail.com>
2025-12-01 14:17:45 +01:00
JakobPerandKim Kulling 11272f13bd Fixed DXFHelper using float instead of ai_real (#6404)
* Fixed DXFHelper using float instead of ai_real

* fixed cmake presets

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-30 22:01:11 +01:00
Kim Kulling f588492ab5 Delete test/other/streamload.py (#6403)
* Update Readme.md

- Reorganize readme for code structure

* Update Readme.md

* Delete test/other/streamload.py

* Delete test/regression directory

* Update AndroidJNIIOSystem.cpp

* Update BundledAssetIOSystem.cpp
2025-11-28 22:18:00 +01:00
Kim Kulling f635984770 Update Readme.md (#6402)
* Update Readme.md

- Reorganize readme for code structure

* Update Readme.md
2025-11-26 22:17:21 +01:00
dependabot[bot]andKim Kulling 0b30e3b343 Bump actions/checkout from 5 to 6 (#6401)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-24 23:42:57 +01:00
Gene WaltersandKim Kulling a989b30b58 WiP. Passing USD prims along with render nodes to look for USD references. Save reference path to metaData['ref'] (#5807)
Signed-off-by: AMZN-Gene <genewalt@amazon.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-24 21:26:46 +01:00
Orleonn ab28db52f0 Added missing scene extras properties for glTF2Importer (#6397) 2025-11-18 15:58:41 +01:00
Kim Kulling c4812fcc47 Update LineSplitter.h (#6396) 2025-11-17 08:56:49 +01:00
Kim Kulling 19108dff6a Fix linkage (#6388)
* Fix linkage when all importers aren't part of the build.
2025-11-16 20:05:50 +01:00
Kim Kulling 05a4fb57f1 Reorganize code top prevent security warning. (#6395)
* Reorganize code to prevent security warning.
2025-11-15 12:16:56 +01:00
John CurleyandKim Kulling a53807a02a Added static cast for conversion from uLong to unsigned int for compiler error (#6393)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-15 08:53:24 +01:00
Kim Kulling 1cc7f2ba74 Fix the doxygen documentation from public headers (#6394)
* Add documentation comments to DeboneProcess.h
2025-11-14 22:05:08 +01:00
Kim Kulling e98ec7b2d3 Refactor string checks and variable declarations (#6392)
* Refactor string checks and variable declarations

* Change string check from contains to find

* Fix syntax error in mesh node creation loop
2025-11-14 00:18:35 +01:00
Jerome St-Louis 0be7cdd6db glTF2: Avoid lookups for generating IDs (#6120)
* glTF2: Reduce lookups for generating IDs
- closes https://github.com/assimp/assimp/issues/5661
2025-11-13 10:50:26 +01:00
thedestroyer4312 c6f997b584 [PyAssimp] Create pyproject.toml (#6378)
* Create pyproject.toml
2025-11-11 09:31:51 +01:00
Kim Kulling 3e2e3c9b12 Update contact email for reporting vulnerabilities (#6389) 2025-11-11 08:52:23 +01:00
Kim Kulling 34cda45471 Fix sonarcube stuff (#6387)
* Fix sonarcube stuff
2025-11-10 23:29:03 +01:00
Kim Kulling a4b8943533 Refactor condition checks for empty vectors (#6385)
* Refactor based on SonarCube.
2025-11-07 16:07:39 +01:00
Jan Honsbrok 0996221017 fix: write textures to folder of PBRT file (#6099)
* fix: write textures to folder of PBRT file
2025-11-05 08:24:41 +01:00
Luca Della Vedova 672594c230 Revert "Refactoring: use using types (#6266)" (#6324)
* Revert "Refactoring: use using types (#6266)"
2025-11-04 15:10:45 +01:00
Jan GrulichandKim Kulling 0978918f71 Fix Heap-buffer-overflow in Q3DImporter::InternReadFile (#6370)
Checks if multiplying texture width and height would overflow before
performing the operation. This avoids incorrect memory allocations and
potential crashes with very large textures.

Fixes #6358

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-04 10:09:13 +01:00
sSsA01andKim Kulling 8e35cb1a9f Fix out-of-range access cause of aiProcess_GenNormals : array size inconsistency of members of mesh after process (#6332)
* Fix aiProcess_GenNormals process: copy members of mesh corresponding with additional vertices

* Fix aiProcess_GenNormals process: Refoctoring

* refactoring: fix SonarQube Issue

* Update GenFaceNormalsProcess.cpp: fix small findings

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-11-01 21:15:17 +01:00
AR ea249be466 Made the README more tidy & fix Build.md (#6371)
* Update LICENSE

* Update Preamble.txt

* Update SECURITY.md

* Remove GitHub's default comment

* Better README!

* Fix discord link! Boom, that's how it's done

* Fixed itch.io spelling from itchi.io

* Make README more tidy :)

AR is back! Anyways, I'm working on my horror game & making devlogs so I don't have time to write. Here's a small summary:
- Just placed the dir structure information correctly in one place so the README looks tidy.

* Add international download link for Visual Studio
2025-10-31 17:12:12 +01:00
dependabot[bot] 276d3e998f Bump actions/download-artifact from 5 to 6 (#6382)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-30 11:06:22 +01:00
dependabot[bot]andKim Kulling b2d5fa201a Bump actions/upload-artifact from 4 to 5 (#6383)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-10-29 20:34:33 +01:00
EddieBreeg 95f09deaae Removed unnecessary copy constructor declaration in aiVector3t (#6384)
* Removed unnecessary copy constructor declaration in aiVector3t
* Added copy constructor back in aiVector3t
* Added explicit declaration of assignment operator in aiVector3t
2025-10-29 10:58:34 +01:00
Kim Kulling e778c84cd6 MD5: Fix face index allocation in MD5Parser (#6380)
- Ensure face indices are properly allocated and resized.
- closes https://github.com/assimp/assimp/issues/6379
2025-10-24 10:15:01 +02:00
Kim Kulling 5f7c06a71e COB: fix validation for ascii header (#6376)
* COB: fix validation for ascii header
2025-10-23 22:44:54 +02:00
Kim Kulling 7dcf6a8984 Collada: Fix overflow in CopyVertex (#6374)
* Fix overflow in CopyVertex
2025-10-19 23:13:59 +02:00
Kim Kulling cc6ab1408f Update texture output format in AssxmlFileWriter (#6372)
* Update texture output format in AssxmlFileWriter
2025-10-17 11:24:38 +02:00
Kim KullingandKim Kulling f544f9c217 Bugfix/fix sonarcube findings (#6369)
* Fix sonarcube findings.
---------
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-10-14 00:01:50 +02:00
Kim Kulling 194da5b2fd Update default material name handling (#6366)
* Replace strcpy by strncpy
2025-10-07 20:25:24 +02:00
Kim Kulling f28a96121d Change strcpy to strncpy for format hint safety (#6365) 2025-10-02 16:31:00 +02:00
Alexandre AvenelandKim Kulling 6401aa9744 Add unit test for subdivision modifier on Blender importer (#5345)
* Add unit test for subdivision modifier on Blender importer

Blend file is composed of default cube with subdivision modifier applied
and same cube with subdivision modifier.

* Update utBlenderImportExport.cpp

Fix compiler warning.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-29 21:22:56 +02:00
Sami Liedes 1894bfb22c Fix an invalid offsetof warning-as-error (#6359)
The code already disables the warning on clang. It's also caused on
GCC in some circumstances (particularly when building with
-D_GLIBCXX_DEBUG).
2025-09-28 20:30:59 +02:00
b8133b04c7 Clone meshlab/tinyusdz repos in default location (#6239)
* Leave FETCHCONTENT_BASE_DIR as default to avoid target platform generated build file conflicts

* Attempt address sonarCloud complaint about generic-looking include file (bare "Parser.h")

---------

Co-authored-by: tellypresence <info@tellypresence.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-23 11:34:13 +02:00
Paul BauriegelandKim Kulling 709fe3c3d0 Add BOM skip and fix mtl parsing (#6253)
* Add BOM skip and fix mtl parsing
* Remove old code
* Fix #5635
* Add all attributes to ObjFileData
---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-22 11:20:24 +02:00
Matt PennyandKim Kulling 489c8d565b Restore merging of near-identical vertices for JoinIdenticalVertices (#6278)
* Restore merging of near-identical vertices for JoinIdenticalVertices

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-21 10:57:17 +02:00
Luca Della Vedova 0581ed5f11 Added tangent handedness to glTF export (#6322)
* Added tangent handedness to glTF export
2025-09-18 14:10:41 +02:00
fifth_lightandKim Kulling 5c568616ec Fix hasTangentsAndBitangents method in AiMesh.java (#6345)
original code m_tangents != null && m_tangents != null; triggers error prone

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-18 10:09:43 +02:00
AbdulRehman 45cb880835 Fixed Build.md (#6354)
* Fixed itch.io spelling from itchi.io
2025-09-18 09:34:55 +02:00
dd98d4aea3 PyAssimp: Re-add 'aiProcess_Triangulate' (#6335)
apparently, b9bfac0418 accidentally
removed a couple of lines with a botched copy'n'paste.

Co-authored-by: IOhannes m zmölnig <zmoelnig@umlautT.umlaeute.mur.at>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-17 10:23:37 +02:00
AbdulRehman 01ac320de8 Better README! Fixed discord link as well (#6351)
* Better README!
2025-09-17 08:16:38 +02:00
AbdulRehman a815a78433 Updated doc/Preamble.txt & SECURITY.md (#6338)
* Update LICENSE

* Update Preamble.txt

* Update SECURITY.md

* Remove GitHub's default comment
2025-09-10 13:59:00 +02:00
69f8eb21fd fix large glb reading by providing a proper helper for reading size_t type (#6307)
Co-authored-by: Vitaly Ovchinnikov <v@ovch.ru>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-09 14:27:17 +02:00
Kim Kulling 72b9939b9f Add null check for aiNode in AddNode method (#6348)
- Added null check for node in AddNode function.
- closes https://github.com/assimp/assimp/issues/6347
2025-09-09 14:10:07 +02:00
Steven FrenchandKim Kulling 4c8a3bd39c [CMake] -l (#6329)
- Fix zlib linkage.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-09-04 09:32:37 +02:00
Kim Kulling 8ef3838beb FBX: Fix offset calculation by adding cursor check (#6337)
- closes https://github.com/assimp/assimp/issues/6336
2025-08-28 11:48:38 +02:00
AbdulRehman 441884387f Update LICENSE (#6327) 2025-08-27 20:16:18 +02:00
Pranav PandKim Kulling f7bbf6dc15 Fix endiannes issues regarding floats on s390x (#6276) (#6277)
* Fix endiannes issues regarding floats on s390x (#6276)

* Fix CI Warnings

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-26 15:34:33 +02:00
Kyungjoon KoandKim Kulling aadd49311a Fix OOB read in OpenDDLParser::parsePrimitiveDataType (#6315)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-25 15:03:00 +02:00
dependabot[bot]andKim Kulling 3f107bebf2 Bump actions/download-artifact from 4 to 5 (#6319)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-22 20:26:58 +02:00
Sergei TrofimovichandKim Kulling a38ec50fd3 test/unit/utProfiler.cpp: fix gcc-16 build failure (#6267)
* test/unit/utProfiler.cpp: fix `gcc-16` build failure

Upcoming `gcc-16` improved detection of unused variables as:

    test/unit/utProfiler.cpp: In member function 'virtual void utProfiler_addRegion_success_Test::TestBody()':
    test/unit/utProfiler.cpp:71:22: error: variable 'j' set but not used [-Werror=unused-but-set-variable=]
       71 |         volatile int j=0;
          |                      ^

The change is intentional accoring to Andrew Pinsi and is not a faalse positive.

* Update utProfiler.cpp: Remove dead code

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-21 10:15:01 +02:00
Dongge LiuandKim Kulling 4c42db1805 Fixed a heap-use-after-free in SortByPTypeProcess. (#6326)
The process incorrectly deleted original meshes from the scene when cleaning up after an error if those meshes had been added to its output list (outMeshes). The fix ensures proper ownership transfer by nullifying the original mesh pointer in the scene (pScene->mMeshes[i] = nullptr;) when the mesh is moved to outMeshes. This prevents the scene destructor from attempting to delete the mesh again later, while allowing the error cleanup path in SortByPTypeProcess to correctly delete all meshes it owns (both newly created and transferred originals).

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-21 09:31:15 +02:00
dependabot[bot] 26e2372882 Bump actions/checkout from 4 to 5 (#6328)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-20 12:50:30 +02:00
Dongge LiuandKim Kulling 36b004e286 Fixed a heap-buffer-overflow in the Half-Life 1 MDL loader. (#6321)
The loader attempted to read the MDL header without verifying if the input buffer was large enough.
Added a check in MDLImporter::InternReadFile_HL1 to ensure the buffer size is sufficient before proceeding with loading.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-18 09:29:45 +03:00
Kyungjoon KoandKim Kulling 3a0ee8792f Fix OOB read (2) in OpenDDLParser::parsePrimitiveDataType (#6316)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-14 13:51:07 +03:00
Kyungjoon KoandKim Kulling e3f9cf5564 Fix OOB read in OpenDDLParser::parseReference (#6317)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-08-10 14:48:27 +03:00
Kyungjoon Ko 6d7ea78792 Fix SEGV write in Assimp::SortByPTypeProcess::Execute (#6318)
* Fix OOB Write in Assimp::SortByPTypeProcess::Execute
2025-08-10 11:45:30 +03:00
Dongge Liu 13316790aa Fixed a container-overflow error (#6298)
* Fixed a container-overflow error in `ODDLParser::OpenDDLParser::parseIntegerLiteral` by swapping the order of conditions in a while loop to ensure the end-of-buffer check happens before dereferencing the pointer. This prevents reading past the end of the buffer when lookForNextToken returns the end pointer.

https://oss-fuzz.com/testcase-detail/4980126616780800
https://issues.oss-fuzz.com/issues/42527625

* Update OpenDDLParser.cpp
2025-08-02 21:25:40 +02:00
Kim KullingandKim Kulling 9255412906 Add CMakePreset file (#6295)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-07-30 13:53:21 +02:00
sSsA01andKim Kulling 8355e0c4bc Fix to fail in the function fast_atoreal_move when the flag ASSIMP_DOUBLE_PRESICION is enabled (#6250)
* Refix export fbx PolygonVertexIndex

* Fix the function ColladaParser::ReadEffectColor when the flag ASSIMP_DOUBLE_PRESICION is enabled

* Fix the static function ReadLight in ColladaParser when the flag ASSIMP_DOUBLE_PRESICION is enabled

* Refactor of the call of the function fast_atoreal_move to the member of aiColor3D

* Fix the call of the function fast_atoreal_move when the flag ASSIMP_DOUBLE_PRESICION is enabled and and refactor

* Fix the call of the function fast_atoreal_move when the flag ASSIMP_DOUBLE_PRESICION is enabled

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-07-29 14:19:50 +02:00
DIGITAL IMAGE DESIGNandKim Kulling 6fa9d09a97 AC: Support Double-Sided Faces (#6252)
* AC: Support Double-Sided Faces

The AC format marks double-sided SURF elements with the 0x20 flag, which Assimp ignored. This commit adds support for double-sided faces.

On encountering a double-sided face via the flag mentioned above, the front face is generated as usual but is then duplicated. The winding order of the duplicate is flipped to form a back face. Vertices are duplicated too so that back faces work correctly with normal vector generation and face smoothing.

* Add test file

* Simplify test case

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-07-29 13:09:30 +02:00
Kim KullingandKim Kulling 9f4e7c6d8d Refactoring: use using types (#6266)
* Refactoring: use using types

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-07-28 17:00:45 +02:00
Kim Kulling 59bc03d931 X3D: Fix invalid vector::back usage (#6283)
* X3D: Fix invalid vector::back usage
2025-07-25 15:01:16 +02:00
Panthuncia edcb350129 Update Build.md (#6273)
Update build instructions to include information about USD importer special-case to ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT, and about ASSIMP_BUILD_USD_IMPORTER.
2025-07-22 21:08:33 +02:00
a79dc358cf Add windows clang to CI (#5537)
- Add windows clang build step
- Closes https://github.com/assimp/assimp/issues/5519


Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
Co-authored-by: Kim Kulling <kullingk@LDED5178.corp.draeger.global>
2025-07-16 16:43:20 +02:00
Kim Kulling db0bde758e Update Readme.md (#6245) 2025-07-02 14:35:32 +02:00
Kim Kulling b447485c06 Fix sonarcube findings (#6242)
* Fix sonarcube findings

* Fix review findings
2025-06-28 18:56:28 +02:00
sSsA01andKim Kulling 4c61ca3af5 Refix export fbx PolygonVertexIndex (#6240)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-27 11:30:04 +02:00
HandsomeXiandKim Kulling 4b6cc8c28a bugfix: Fixed the memory leak when texture transforming (#6236) (#6237)
* bugfix: Fixed the memory leak when texture transforming (#6236)

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-26 10:53:08 +02:00
Kim Kulling d99f9bd2f7 Refactoring: Add nupptr-checks (#6241) 2025-06-26 00:09:02 +02:00
Kim Kulling b2afe717d3 Update Importer.hpp (#6235)
- Add doc for out-of-memory exception
- closes https://github.com/assimp/assimp/issues/5173
2025-06-21 13:33:15 +02:00
NSGandKim Kulling ad6e8e210a Fix: export fbx wrong to_ktime in FBXExporter.cpp (#6105)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-17 08:23:21 +02:00
Kim Kulling fb375dd8c0 Prepare 6.0.2 (#6231) 2025-06-08 21:50:39 +02:00
sSsA01andKim Kulling a95addfc4a Fix the function "aiGetMaterialColor" when the flag ASSIMP_DOUBLE_PRECISION is enabled. (#6090)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-08 14:25:47 +02:00
Kim Kulling 2d8c09b60f Update SECURITY.md (#6230)
* Update SECURITY.md

* Update SECURITY.md
2025-06-08 14:14:24 +02:00
357b5baabb fix-CVE-2025-3158: closes #6023 Fixes CVE-2025-3158: Heap-based Buffer Overflow in Assimp::LWO::AnimResolver::UpdateAnimRangeSetup (#6222)
- changed loop-condition to reflect the fact that m must be smaller than n

Co-authored-by: Vinz Spring <vinzs@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-08 14:02:04 +02:00
269987085f Fixes CVE-2025-2750: out of bounds write by assigning to wrong array element count tracking (closes #6011) (#6225)
description:
- The current implementation has faulty reallocation logic when parsing a CSM file
- Issue 1
    - https://github.com/assimp/assimp/blob/4ad1d2aa3086517816716a50aa122342806736f9/code/AssetLib/CSM/CSMLoader.cpp#L205
    - By assigning s->mNumPositionKeys = alloc*2 right before resizing the buffer, making s->mNumPositionKeys equivalent to the
      max number of aiVectorKey that can be stored in s->mPositionKeys
    - the code later attempts to get the next write location by doing: aiVectorKey* sub = s->mPositionKeys + s->mNumPositionKeys;
    - this points to the end of the array, not after the last element in the array
- Issue 2
    - https://github.com/assimp/assimp/blob/4ad1d2aa3086517816716a50aa122342806736f9/code/AssetLib/CSM/CSMLoader.cpp#L178-L184
    - if the CSM file does not declare last frame data, then mPositionKeys will never be initialized

fix:
- we preserve s->mNumPositionKeys to still contain the actual number of aiVectorKeys and ensure that we will not write out of bounds
- we initialize mPositionKeys with a default value and if we find last frame info, we just re-initialize it

Co-authored-by: Vinz Spring <vinzs@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-08 13:46:39 +02:00
5be336779d Fixes CVE-2025-2757: Heap-based Buffer Overflow in AI_MD5_PARSE_STRING_IN_QUOTATION (closes #6019) (#6223)
description:
- heap buffer overflow in AI_MD5_PARSE_STRING_IN_QUOTATION. An attacker could potentially exploit the vulnerability to cause a remote code execution,
  if they can trick the victim into running assimp on a malformed MD5 file

fix:
- truncated the string to the maximum supported length, mitigating overflow

Co-authored-by: Vinz Spring <vinzs@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-08 13:38:05 +02:00
177797c77b Fixes CVE-2025-2751: Out-of-bounds Read in Assimp::CSMImporter::InternReadFile (closes #6012) (#6224)
description:
issue:
- https://github.com/assimp/assimp/blob/4ad1d2aa3086517816716a50aa122342806736f9/code/AssetLib/CSM/CSMLoader.cpp#L274C1-L275C1
- sometimes the code tried to construct a new 4x4 matrix from a nullptr, thus reading out of bounds

fix:
- added nullptr check
- added array count check
- added default fallback init to identity matrix

Co-authored-by: Vinz Spring <vinzs@amazon.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-08 12:10:12 +02:00
c1d6226c06 Update/update pugi xml (#6229)
* update pugixml

Improvements:

Many xml_attribute:: and xml_node:: functions now transparently support std::string_view and std::string when C++17 support is detected.
CMake improvements:

Improve pkg-config file generation for NixOS
PUGIXML_BUILD_APPLE_FRAMEWORK CMake option can be used to build pugixml as .xcframework
PUGIXML_INSTALL CMake option can be used to disable installation targets
Compatibility improvements:

Fix clang/gcc warnings -Wzero-as-null-pointer-constant, -Wuseless-cast, -Wshorten-64-to-32
Fix unreferenced function warnings in PUGIXML_NO_STL configuration
Fix CMake 3.31 deprecation warnings
Stop using deprecated throw() when noexcept is available

Improvements:

xml_attribute::set_name and xml_node::set_name now have overloads that accept pointer to non-null-terminated string and size
Implement parse_merge_pcdata parsing mode in which PCDATA contents is merged into a single node when original document had comments that were skipped during parsing
xml_document::load_file now returns a more consistent error status when given a path to a folder
Bug fixes:

Fix assertion in XPath number→string conversion when using non-English locales
Fix PUGIXML_STATIC_CRT CMake option to correctly select static CRT when using MSVC and recent CMake
Compatibility improvements:

Fix GCC 2.95/3.3 builds
Fix CMake 3.27 deprecation warnings
Fix XCode 14 sprintf deprecation warning when compiling in C++03 mode
Fix clang/gcc warnings -Wweak-vtables, -Wreserved-macro-identifier

* Update CMakeLists.txt

* pugixml: upgrade to v1.15

* pugixml: Add export directives for non-windows platforms

* pugixml: replace NULL by nullptr.

---------

Co-authored-by: Andrea <realeandrea@yahoo.it>
Co-authored-by: mosfet80 <10235105+mosfet80@users.noreply.github.com>
2025-06-08 02:12:05 +02:00
Jackson LevittandKim Kulling 8621d52430 Updated Inner Cone formula for Spot Lights in GLTF (#6078)
Updated the Inner Cone formula such that exponent values of 0 result in no inner cone and large exponent values result in a inner cone being most of the cone angle-wise.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-05 09:41:30 +02:00
sSsA01andKim Kulling 5d39661751 fix compile error caused by PR #6087 when ASSIMP_DOUBLE_PRESICION is enabled (#6091)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-05 09:15:47 +02:00
sSsA01andKim Kulling a98ffe6c6f Fix export fbx: Wrong Materials in LayerElementMaterial if a node contains multi meshes (#6103)
* fix export fbx wrong Materials index in LayerElementMaterial

* Refix export fbx wrong Materials index in LayerElementMaterial. Materials index should be the order of Materials in connections of the Model node.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-06-05 09:05:36 +02:00
Kim Kulling b3a47a68fa Version: Adapt version (#6212)
* Version: Adapt version

- closes https://github.com/assimp/assimp/issues/6204

* Update utVersion.cpp
2025-06-02 10:54:32 +02:00
NSGandKim Kulling c4515f53ca Fix: Add "preservePivots" condition when importing FBX animation (#6115)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-31 14:41:25 +02:00
7eb6b0c3db fix: closes #6069 CVE-2025-3196 (#6154)
* fix: closes #6069 CVE-2025-3196

* fix: updated patch for upstream symbol names

* fix: warning C4267

---------

Co-authored-by: Vinz Jarl Valentin Spring <vinzs@amazon.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
Co-authored-by: Vinz Spring <contact@vinzspring.de>
2025-05-31 14:27:10 +02:00
sSsA01andKim Kulling 7b38feb8a7 Fix export fbx PolygonVertexIndex (#6102)
* fix export fbx vertex index

* refactoring: remove unnecessary casts

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-31 13:49:58 +02:00
yurik b97308683b Fix a bug in importing binary PLY file (#1) (#6060)
* Correct IOStreamBuffer<T>::getNextLine() to prevent skipping too many '\n', which could be part of the BINARY part
* Add a regression test
2025-05-31 09:05:44 +02:00
deccerandKim Kulling 4ad1d2aa30 Fix HUNTER_ERROR_PAGE (#6200)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-27 13:09:35 +02:00
4535ff9d6e Annotate w/C++17 "fallthrough" (#6143)
Co-authored-by: tellypresence <info@tellypresence.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-27 11:14:29 +02:00
Martin MirchevandKim Kulling 18465fbb24 Add clamping logic (#6149)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-26 10:16:10 +02:00
Peter LemanskiandKim Kulling d2aed87f5e Fix issue compiling when assimp added as subdirectory and parent project defines /utf-8 compile flag (#6186)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-23 12:54:03 +02:00
crasongandKim Kulling 315075c4a6 Add Missing Strings to aiTextureTypeToString (#6188)
Anisotropy and gltf metallic roughness were missing strings

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-22 23:25:34 +02:00
Jan HonsbrokandKim Kulling 4f3a759a05 fix: missing OS separator in outfile (#6098)
The outfile was missing an OS separator when a PBRT file was exported in a path that was not the current directory.
Writing to /foo/bar.pbrt was writing to foobar.pbrt instead.
mPath and mFile are now handled like it's described in PbrtExporter.h

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-20 15:33:13 +02:00
mosfet80andKim Kulling 3e8673b14d update draco lib (#6094)
Version 1.5.7 release:
Using the versioned www.gstatic.com WASM and Javascript decoders continues
to be recommended. To use v1.5.7, use this URL:
https://www.gstatic.com/draco/versioned/decoders/1.5.7/*
Added support for normalized attributes to Emscripten encoder API.
Bug fixes.
Security fixes.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-18 20:51:46 +02:00
Kim KullingandKim Kulling 1933313ec8 Unreal refactorings (#6182)
* Unreal refactorings

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-05-16 14:18:37 +02:00
Kim Kulling 696771d576 Doc: add C++ / c minimum (#6187)
- closes https://github.com/assimp/assimp/issues/3370
2025-05-16 11:34:54 +02:00
Julian KnodtandKim Kulling 2c77d2555b [#5983] Fix bugs introduced in fbx export (#6000)
There were some typos and incorrect offsets in a previous PR. This fixes part of it, correctly exporting the UV.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-16 10:22:01 +02:00
Martin MirchevandKim Kulling ed89a02fff Fix out-of-bounds dereferencing (#6150)
* Fix out-of-bounds dereferencing

* Fix: Add log error entry.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-16 09:07:04 +02:00
Xavier BonaventuraandKim Kulling b40e41f9c3 Update contrib/zip to fix data loss warning (#6152)
Without these changes, the warning "Type conversion may result in loss of data" might be triggered because `i` is of type `ssize_t` but the type of the parameter is `mz_uint` that is an alias for `unsinged int`.
This was already fixed in the original repository
see
https://github.com/kuba--/zip/blob/d7a2252a537926cbdef8512741a322a183fcfd09/src/zip.c#L481C49-L481C58
and
https://github.com/kuba--/zip/blob/d7a2252a537926cbdef8512741a322a183fcfd09/src/zip.c#L538

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-15 08:50:44 +02:00
Kim KullingandKim Kulling 9d9a80739d Fix: Fix leak when sortbyp failes with exception (#6166)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-05-14 11:43:12 +02:00
64073458bd Fix warning abut inexistent warning (#6153)
These warnings are not existing before Visual Studio 2015

Fixes #6151

Co-authored-by: Xavier Bonaventura <xavier.bonaventura@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-13 20:37:42 +02:00
mnml_andKim Kulling b9bfac0418 add missing constants (#6116)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-11 21:11:54 +02:00
copycd 536cd59807 + Only up to recognizing the KTX2 compressed image as a texture object is handled. (#6139) 2025-05-08 21:28:30 +02:00
Kim Kulling 327afe0183 Fix crashes (#6138) 2025-05-07 23:40:53 +02:00
Kim KullingandKim Kulling 2056679e98 Fix: Support uint16 indices in OpenGEX as well (#6137)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-05-07 10:15:54 +02:00
Qingyou ZhaoandKim Kulling af352d6f7c Fix a bug where string erases throws out of range (#6135)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-06 23:33:28 +02:00
Qingyou Zhao 0dafa03ff8 Fix a out of bound buffer access in ParsingUtils GetNextLine (#6134) 2025-05-06 07:48:09 +02:00
Kim KullingandKim Kulling d1b73dffec Replace exception by error in log (#6133)
* Replace exception by error in log

* Separate tests for new behaviour

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-05-05 14:07:52 +02:00
kiroandKim Kulling b0e0ce5a28 support for cmake findpackage module mode (#6121)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-04 13:17:56 +02:00
Kim KullingandKim Kulling 0c02313893 Refactor (#6127)
* Refactor 3DS

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-05-03 11:46:10 +02:00
Matthias MöllerandKim Kulling 9182879e1f fix: possible Heap-based Buffer Overflow in ConvertToUTF8 function (#6122)
* fix: possible Heap-based Buffer Overflow in ConvertToUTF8 function

* Update BaseImporter.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-05-03 10:40:59 +02:00
Kim Kulling 275eca9535 Bugfix: Handling no of texture coordinates correctly (#6124)
- If the mesh supports more than 2 texture coordinates this was not handled correctly. Now the code will be able to deal with 2 or 3 coords and throws an exception if this value gets invalid.
- closes https://github.com/assimp/assimp/issues/3829
2025-04-29 20:03:58 +02:00
yuri@FreeBSD cb56793e16 fix: Fix build on armv6/armv7 (#6123) 2025-04-27 21:27:45 +02:00
sSsA01andKim Kulling ac5988422a Refactoring of PR #6092 (#6101)
* Fix fbx export. Nodes "LayerElementNormal" and "LayerElementColor" should be written only when actual data are exported.

* Update FBXExporter.cpp

- Fix intentions
- use empty instead of size for checking data exists

* refactoring

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-04-16 09:52:13 +02:00
Kim Kulling 4ee7b9d98d Use unique pointer to fix possible leak (#6104) 2025-04-15 21:51:05 +02:00
sSsA01 e68ea14f56 Not to export empty "LayerElementNormal" or "LayerElementColor" nodes to fbx (#6092)
* Fix fbx export. Nodes "LayerElementNormal" and "LayerElementColor" should be written only when actual data are exported.
2025-04-14 15:20:31 +02:00
Kim Kulling 2f3e72413f Bugfix/ensure collada parsing works issue 1488 (#6087)
* Add text to ensure that float parsing in colladata works right
2025-04-10 15:30:12 +02:00
Kim Kulling 0ae66d2703 Fix set (#6073)
* Fix set

* Fix: Fix implicite cast from size_t to uint32_t
2025-04-08 13:14:10 +02:00
Alexelnet e27204c27a Renamed and inlined hasSkeletons() to HasSkeletons() to match the other Has*() methods. (#6072) 2025-04-01 15:07:04 +02:00
55e6359436 More constexpr (#6066)
Co-authored-by: Krishty <krishty@krishty.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-27 15:08:21 +01:00
b57f7d367c Harmonize Importer #includes (#6065)
* Harmonize Importer #includes

Some importers referred to their headers via `#include "AssetLib/[format]/[header.h"`, others via `#include "[header].h"`, others mixed both (e.g. IRR). This is a matter of taste, but it should at least be done the same way everywhere.

Most importers seem to prefer `#include "[header].h"`, so this commit enforces it.

Cross-referencing files from other importers is still done through `AssetLib/[format]`.

Assimp headers are not affected and I would advise against changing them, as this could lead to subtle collisions with user includes.

* went one too far

---------

Co-authored-by: Krishty <krishty@krishty.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-27 11:13:44 +01:00
88959b2be7 Fix Whitespace (#6063)
* Fix Whitespace

No functional changes. This commit removes trailing spaces, undesired line breaks, and formatting screwups.

* Remove more useless line breaks in license (500 out of 630 license copies do NOT use double line breaks here)

---------

Co-authored-by: Krishty <krishty@krishty.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-26 00:12:55 +01:00
lelielandKim Kulling 79cba055b9 feat: created the aiGetStringC_Str() function. (#6059)
* feat: created the aiGetStringC_Str() function.

The C++ Interface's function C_Str() from the aiString struct was missing an equivalent function for the C Interface.

* changed the first parameter of the aiGetStringC_Str function to be const.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-25 22:03:52 +01:00
ac0b19a771 Remove Redundant virtual (#6064)
The `override` keyword only applies to virtual functions. Specifying `virtual` again is useless.

Co-authored-by: Krishty <krishty@krishty.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-25 21:00:43 +01:00
cbf279d522 Fix Cinema4D Import (#6062)
#5623 broke the Cinema4D import by forgetting to rename a constant. This commit fixes the invalid name.

Co-authored-by: Krishty <krishty@krishty.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-24 21:32:10 +01:00
Zhang YuntongandKim Kulling d307c9f1d7 NDO: Fix possible overflow access (#6055)
* NDO: Fix possible overflow access
- closes https://issues.oss-fuzz.com/issues/372765427

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-24 21:21:32 +01:00
Kim Kulling e2ee7d2c71 [draft] Check the hunter build (#6061)
- closes https://github.com/assimp/assimp/issues/5373
2025-03-21 20:08:43 +01:00
Steve Mandtellypresence 5a1cc9ec60 Update tinyusdz git hash (fix USD animation) (#6034)
* Update tinyusdz

* Improve reference screenshots

* Add .csm reference screenshot

* Bump version

---------

Co-authored-by: tellypresence <praktique-tellypresence@yahoo.com>
2025-03-17 20:47:28 +01:00
a93b9f8c80 [OpenGEX] disable partial implementation of light import (causes model load failure) (#6044)
* Disable OpenGEX lights and cameras which are suspected of causing model load failure

* Revert changes to camera import

---------

Co-authored-by: tellypresence <praktique-tellypresence@yahoo.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-03-16 13:32:17 +01:00
Kim Kulling 2690e354da CMS: Fix possible overflow access (#6052)
- closes https://github.com/assimp/assimp/issues/6010
2025-03-13 21:10:49 +01:00
Kim Kulling e8a6286542 ASE: Use correct vertex container (#6051)
- closes https://github.com/assimp/assimp/issues/6024
2025-03-13 16:23:36 +01:00
Kim KullingandCopilot Autofix powered by AI 2194944a25 Potential fix for code scanning alert no. 63: Potential use after free (#6050)
- Ensure that code scanner will identify pointer as already released.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-03-13 11:26:18 +01:00
Kim Kulling 4b8f55cc00 Bugfix: Fix possible nullptr dereferencing (#6049)
* Bugfix: Fix possible nullptr dereferencing
2025-03-13 11:04:25 +01:00
Kim Kulling d2c6e64a11 Fix: Avoid override in line parsing (#6048)
* Fix: Avoid override in line parsing

- closes https://github.com/assimp/assimp/issues/6026

* Update ParsingUtils.h
2025-03-13 10:17:43 +01:00
Kim Kulling bcf11c252a MDL: Fix overflow check (#6047) 2025-03-13 00:07:41 +01:00
Kim Kulling 7f2c9d7b88 MDL: Limit max texture sizes (#6046)
- closes https://github.com/assimp/assimp/issues/6022
2025-03-12 21:37:25 +01:00
Kim Kulling 7c705fde41 ASE: Fix possible out of bound access. (#6045) 2025-03-12 21:12:02 +01:00
Kim Kulling c1eedbba8e Fix: Let OpenGEX accept color3 types (#6040)
- will set alpha channel to 1.0f, if no alpha channel was found.
- closes https://github.com/assimp/assimp/issues/6039
2025-03-12 11:05:37 +01:00
T.Yamada f398a70163 Use std::copy to copy array and remove user destructor to make sure is_trivially_copyable in order to avoid -Wno-error=nontrivial-memcall (#6029)
Use std::copy to copy array and remove user destructor to make sure is_trivially_copyable in order to avoid -Wno-error=nontrivial-memcall (#6029)
2025-03-11 15:09:10 +01:00
UnionTech-Software 70459b4d1f Fix memory leak in OpenGEXImporter (#6036) 2025-03-10 16:24:26 +01:00
Kim Kulling 45898eee55 Refactorings: glTF cleanups (#6028) 2025-03-05 21:37:47 +01:00
Kim Kulling f52fcb6052 Obj: remove smooth-normals postprocessing (#6031)
- closes https://github.com/assimp/assimp/issues/5514
2025-03-03 09:44:35 +01:00
Kim Kulling 2bce77f909 IFC: Remove redundand check (#6006)
- closes https://github.com/assimp/assimp/issues/5798
2025-02-22 21:34:51 +01:00
Kim Kulling 5d716b8fe0 Bugfix/fix mingw issue 5975 (#6005)
* MDL: Ensure alignment of bool vector
2025-02-20 21:20:11 +01:00
fishguy6564 b58afb7b83 Fixing PyAssimp misalignment errors with certain structures (#6001)
* Fixed misaligned structures in PyAssimp

* Added documentation on missing aiBone fields
2025-02-17 20:41:07 +01:00
StefanandKim Kulling 7945359a5c Use ear-cutting library for triangulation (#5977)
* Use ear-cutting library for triangulation

Fixes #3609
Fixes #3019
Fixes #1136

* Fix typo

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-02-13 11:24:59 +01:00
Kim Kulling 9bb6f2e1b8 Use correct data type for animation key (#5998) 2025-02-12 00:26:01 +01:00
Kim Kulling 7efb98db27 Doc: Separate viewer (#5995) 2025-02-07 21:17:59 +01:00
Kim Kulling f967e76493 Update Readme.md: Add new viewer (#5991)
- Add the Qt5 Modelviewer to the readme
2025-02-05 13:49:17 +01:00
mosfet80andKim Kulling d41511bf8a Update STEPFileReader.cpp (#5973)
Clean code

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-02-03 11:27:31 +01:00
Kim Kulling 53b5dba4df Doc: Make hint clearer (#5988)
-closes https://github.com/assimp/assimp/issues/5981
2025-01-31 09:53:13 +01:00
Spencer EvansandKim Kulling 9f3cd51a87 corrected postprocess FlipUVs flag documentation x coord (#5978)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-26 21:08:46 +01:00
bc47836a8f fix: reduce gltf2 export time (#5972)
* fix: reduce gltf2 export time

* fix: use std::less<> in std::map

---------

Co-authored-by: huangxinchuang <huangxinchuang@pointcode.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-25 21:50:33 +01:00
Steve MandSteve M 2aac984fa3 Add gltf metallic-roughness texture type (#5968)
* Introduce gltf metallic-roughness texture type

* Add to unit test, add doc citation

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2025-01-24 21:08:29 +01:00
PichasandKim Kulling 31f0dcb4d1 add EXCLUDE_FROM_ALL (#5959)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-22 16:28:43 +01:00
tyler92andKim Kulling f13197921b Fix heap buffer overflow in PLY parser (#5956)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-22 15:18:56 +01:00
Mike Chemistruck d91e0e4f42 Add POST_BUILD option to ADD_CUSTOM_COMMAND (#5962)
This commit fixes a set of warnings from the latest version of CMake:

(ADD_CUSTOM_COMMAND):
  Exactly one of PRE_BUILD, PRE_LINK, or POST_BUILD must be given.  Assuming
  POST_BUILD to preserve backward compatibility.

  Policy CMP0175 is not set: add_custom_command() rejects invalid arguments.
  Run "cmake --help-policy CMP0175" for policy details.  Use the cmake_policy
  command to set the policy and suppress this warning.
This warning is for project developers.  Use -Wno-dev to suppress it.
2025-01-22 11:41:11 +01:00
ba4455c9c0 Added GLTF Extension KHR_materials_anisotropy (#5950)
* added gltf extension KHR_materials_anisotropy

* Update glTF2Importer.cpp

---------

Co-authored-by: lutz.hoeren <lutz.hoeren@redplant.de>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-21 00:02:46 +01:00
Kim Kulling 79d451bf4b Avoid exporting all primitives, which are not triangles. (#5964) 2025-01-17 19:28:12 +01:00
BurntRanchandKim Kulling 2a0969d4d9 Add customExtension support to the scene (#5954)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-17 16:09:23 +01:00
David Campos RodríguezandKim Kulling 1e44036c36 Prefix MTL textures with the MTL directory path (#5928)
* Prefix MTL textures with the MTL directory path.

Path to textures defined in MTL files are relative to the MTL
file rather than to the OBJ, so we need to prefix them with the
MTL file directory path.

* Adding test issue 2355

* Trying to fix for Windows when file has Linux path

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-15 10:03:32 +01:00
Engin ManapandKim Kulling 2f6dcdfd72 Assimp master head fixes for failure to compile (#5899)
* Fix unknown pragma error on msys2 mingw

* Fix missing assignment operator on msys2 mingw

Default is omitted by compiler because custom copy constructor

* Fix redefinition of _1 and _2 error on msys2 mingw

fix is converting it to lambda as clang is claiming that is
preferred

* Fix strncpy warnings about truncation

* Fix missing assignment operator error on clang

* Update glTFImporter.cpp

* Update glTF2Importer.cpp

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-14 14:23:02 +01:00
Julian KnodtandKim Kulling e722420907 [FBX] Allow export multi materials per node (#5888)
* [FBX] Allow export multi materials per node

Previously it was assumed that each node would export a single material. This removes that
assumption, and also allows for exporting multiple meshes with a single node. Previously they
would each be seprated into their own node.

* Support for animations with multiple meshes too

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-14 11:37:16 +01:00
8e44b40df4 [AMF] Fix texture mapping (#5949)
* Fix texture mapping

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-12 23:04:10 +01:00
Kim Kulling 5aa38fe3cd Update OpenDDLParser.cpp (#5953) 2025-01-10 18:28:22 +01:00
tyler92 0834fed661 Add aiProcess_ValidateDataStructure flag to the fuzzer (#5951) 2025-01-10 13:07:11 +01:00
f2c6aa15ed Add arm64-simulator support to iOS build script (#5920)
Co-authored-by: Dwayne Coussement <dwayne.coussement@showpad.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-08 14:34:05 +01:00
Kim KullingandKim Kulling 5fa7b8ceb9 Bugfix/cosmetic code cleanup (#5947)
* Refactorings: Code cleanups

* More cosmetic changes

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-01-07 23:32:50 +01:00
Kim KullingandKim Kulling d386309af9 Fix unittest path (#5948)
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2025-01-06 23:03:59 +01:00
Jackson Levitt 2f40a77ae1 Updated Material.cpp to add missing cases (#5945) 2025-01-06 13:02:55 +01:00
David Campos RodríguezandKim Kulling a4d8a5fec3 AssbinImporter::ReadInternFile now closes stream before throwing (#5927)
While one of the throws in the function did indeed close the open stream,
several didn't.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-03 21:38:27 +01:00
stekap000 bbeb515421 pragma warning bug fix when using g++ on windows (#5943) 2025-01-03 19:50:18 +01:00
tyler92 437b484070 Fix heap buffer overflow in HMP loader (#5939) 2025-01-01 17:40:18 +01:00
tyler92andKim Kulling d70606bfb6 Verify negative values in Quake1 MDL header (#5940)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2025-01-01 01:55:05 +01:00
69558d8889 Introduce VRML format (.wrl and .x3dv) 3D model support (#5857)
- Introduce VRML format (.wrl and .x3dv) 3D model support
- Add samples
---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-30 11:56:18 +01:00
tyler92andKim Kulling 5e091572d5 Fix stack overflow in LWS loader (#5941)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-30 11:15:50 +01:00
David Campos RodríguezandKim Kulling ab5b32ecc7 Fix docs for aiImportFileExWithProperties. (#5925)
The docs talked about the importer, but no importer exists in the
context of calling this function. It seems like the docs may have been
accidentally copied from somewhere else.
I copied the docs from another import function within the same file.
This seems reasonable because the implementations of both functions
suggest they work the same way: the function creates the importer and
sets it into the scene private data so that the later release call can
release the importer.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-29 20:23:02 +01:00
tyler92andKim Kulling 7bd54e3604 Disable logs for fuzzer by default (#5938)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-25 20:19:42 +01:00
Julian KnodtandKim Kulling 258cdfd2bc Export tangents in GLTF (#5900)
Previously tangents were not being exported. If they are present, they should also be properly
exported.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-23 21:57:13 +01:00
David Campos RodríguezandKim Kulling 016be03c3d glTF importers: Avoid strncpy truncating away the ' \0' character (#5931)
* Fixing building errors from job https://github.com/assimp/assimp/actions/runs/12403918024/job/34628244451?pr=5928

* Adding some asserts for future mantainability, although a bit paranoic maybe

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-23 16:55:17 +01:00
Kim Kulling 1ce3164bc2 Bug/evaluate matrix4x4 access (#5936)
* Add test for 3x3 matrices and 4x4 matrix access
2024-12-23 16:33:37 +01:00
Kim Kulling 9f3a7e95ab Fix: Fix name collision (#5937)
* Fix: Fix name collision

* Fix: Fix possible override

* Fix: Use reentrant providing time function

* Fix: Fix override

* Update AssbinFileWriter.cpp

Revert, not portable.

* Update AssxmlFileWriter.cpp

Revert asctime_r, not portable.
2024-12-23 12:23:42 +01:00
tyler92andKim Kulling ecc8a1c869 Fix buffer overflow in MD5Parser::SkipSpacesAndLineEnd (#5921)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-17 18:57:54 +01:00
Sebastian SchäferandKim Kulling 2090508c34 Fix parsing of comments at the end of lines for tokens with variable number of elements. (#5890) (#5891)
* Fix parsing of comments at the end of lines for tokens with variable number of elements. (#5890)

* Fixed Quality Gate issues.

Reduced nesting of the break statements.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-17 18:17:02 +01:00
tyler92andKim Kulling 2b773f0f5a Fix heap-buffer-overflow in OpenDDLParser (#5919)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-16 22:48:45 +01:00
Stefan 7a114059cd Replace C# port with maintained fork (#5922) 2024-12-16 13:02:15 +01:00
saceredaandKim Kulling 862abe410b Fixed warnings (#5903)
* Fixed conversion warning when compiling without ASSIMP_DOUBLE_PRECISION. Fixed size() <> unsigned warnings

* Fix: Review finding

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-12 20:58:08 +01:00
Gene Walters 76d22e5fbe USD updates: properly place meshes into nodes (instead of all meshes getting added to the rool node). Adding animation framerate. (#5915)
Signed-off-by: AMZN-Gene <genewalt@amazon.com>
2024-12-11 16:32:40 +01:00
tyler92andKim Kulling f12e521986 Fix use after free in the CallbackToLogRedirector (#5918)
The heap-use-after-free vulnerability occurs in the
CallbackToLogRedirector function. During the process of logging,
a previously freed memory region is accessed, leading to a
use-after-free condition. This vulnerability stems from incorrect
memory management, specifically, freeing a log stream and then
attempting to access it later on.

This patch sets NULL value for The DefaultStream global pointer.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-11 11:17:14 +01:00
Kim Kulling 28ebc8452b Fix: Fix build for mingw10 (#5916)
- closes https://github.com/assimp/assimp/issues/5827
2024-12-10 23:40:02 +01:00
Kursat AktasandKim Kulling 46c26eda5a Introducing assimp Guru on Gurubase.io (#5887)
Signed-off-by: Kursat Aktas <kursat.ce@gmail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-05 22:54:43 +01:00
Elijah NicolandKim Kulling bddc374b5a Validate mesh in WriteMesh before AttributeBegin call (#5884)
If mesh is validated after AttributeBegin call, then
the AttributeBegin is never closed with an
AttributeEnd, causing problems in pbrt.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-05 11:10:46 +01:00
HandsomeXiandKim Kulling 164a5ae8cf bugfix: Fixed the issue that draco compressed gltf files cannot be loaded normally (#5882) (#5883)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-04 22:03:57 +01:00
Julian KnodtandKim Kulling ff61095928 Blendshape export float & same # verts (#5775)
Previously it was possible that the number of vertices between the mesh and morph mesh varied.
This may have caused problems in tools like Blender, and this ensures there's a 1-1
correspondence between vertices.

In addition, exporting doubles broke meshlab on import, so now it exports floats.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-02 23:04:44 +01:00
Julian KnodtandKim Kulling ca17cdc1f9 Do not create GLTF Mesh if no faces (#5878)
Previously GLTF meshes were created even if there were no faces, which lead to GLTFs which were not technically valid.

I believe this fixes the problem I was encountering, but I've not been able to test it because of some Mac compile errors. Will test on a windows machine at some point.

Fixes #5868

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-01 21:21:08 +01:00
StefanandKim Kulling 739ebfd207 Synchronize DefaultLogger (#5898)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-12-01 20:35:24 +01:00
72c51a9997 Convert float to ai_real, (#5902)
Co-authored-by: ali turan <ali.turan@simsoft.com.tr>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-29 20:54:24 +01:00
2493deff37 USD Keyframe Animations (#5856)
USD Keyframe Animations

Signed-off-by: AMZN-Gene <genewalt@amazon.com>
Signed-off-by: Gene Walters <genewalt@amazon.com>
Co-authored-by: Kazuki Y <6259214+kazu0617@users.noreply.github.com>
Co-authored-by: kazu0617 <kazu0617@protonmail.com>
Co-authored-by: Kim Kulling <kim.kulling@googlemail.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-28 21:29:58 +01:00
12f3309996 Simplify JoinVerticesProcess (#5895)
Previously JoinVertices had a lot of extra complexity, simplify it greatly.

Co-authored-by: Julian Knodt <julianknodt@Julians-Air-2.attlocal.net>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-27 22:53:27 +01:00
StefanandKim Kulling 02d3887e9a Add CI to automatically build and attach binaries to releases (#5892)
* Add CI to automatically build and attach binaries to releases

* Correctly label arm64 MacOS and add x64 variation

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-26 22:57:44 +01:00
mosfet80andKim Kulling 09f6a5e136 Update cpp-pm / hunter (#5885)
OpenCV and dependencies update to v4.10.0-p0

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-25 21:58:33 +01:00
Kim Kulling 5f100a0984 Obj: fix nullptr access. (#5894) 2024-11-25 19:58:58 +01:00
Kim Kulling 795d4897db Readme.md: Add sonarcube q batch (#5893)
- Add sonarcube quality badge
2024-11-25 14:48:12 +01:00
Kim Kulling 6fad13c82b Cleanup: Delete code/.editorconfig (#5889) 2024-11-22 11:38:51 +01:00
Julian KnodtandKim Kulling 48bd7c3e22 Check that mMaterials not null before access (#5874)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-20 23:26:07 +01:00
Matt IselinandKim Kulling c867ddbc04 Fix potential uninitialized variable in clipper (#5881)
* Fix potential uninitialized variable in clipper

* Clipper: Fix second parameter as well.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-19 23:31:47 +01:00
Kim Kulling 41cc2f66a4 Remove strcpy. (#5802)
* Remove strcpy.

* Sonarcube: Add more strcpy replacements

* BlenderLoader: Replace strncpy by memcpy
2024-11-18 16:54:58 +01:00
Kim Kulling f5fb8ff842 Material: Fix sonarcube finding (#5880)
* Material: Fix sonarcube finding

- Use nullptr instead of 0x0 to simulate NULL.

* Material: Use NULL for c-code
2024-11-18 14:31:35 +01:00
Kim Kulling c9bbbcf633 Material: Fix the build for c compiler (#5879)
- Mark inlined functions as static inline to fix the linkage for c compilers
- closes https://github.com/assimp/assimp/issues/5875
2024-11-18 09:36:32 +01:00
David Campos RodríguezandKim Kulling e7a6d33365 Try to resolve image paths by replacing backslashes or forward slashes in EmbedTexturesProcess (#5844)
* Try to resolve image paths by replacing backslashes.

* Some changes suggested by CI

* Removed usage of <filesystem>.

* Removing usage of C++20/C++23 features

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-14 21:10:03 +01:00
Kim Kulling 9723b3554b Obj: Fix Sonarcube findings (#5873)
* Obj: Fix Sonarcube findings
2024-11-11 13:06:51 +01:00
f7bb1bc170 Add reference screenshots for complex bundled test 3D model files (#5822)
Feature: Add reference screenshots for complex bundled test 3D model files

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-08 16:09:00 +01:00
jwblaandKim Kulling 9694f7e8e4 Update CMakeLists.txt to fix gcc/clang++ issue (#5863)
This resolves an issue where using GCC as your C compiler but, say, clang++ as your CXX compiler produces
`error: unknown warning option '-Wno-dangling-reference' [-Werror,-Wunknown-warning-option]`

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-06 11:34:21 +01:00
Marco Feuerstein 6520354a58 Fix use of uninitialized value. (#5867)
If the stat command fails, statbuf is uninitialized.
2024-11-06 10:54:14 +01:00
Tobias Rittig, Ph.D.andKim Kulling e06b80f6b0 +Add vertex duplication during face normal generation (#5805)
* +Add vertex duplication during face normal generation
`aiProcess_GenNormals` PostProcess now duplicates vertices if they are referenced by more than one polygon which results in the correct faceted appearance.

* Update GenFaceNormalsProcess.cpp

- Fix old spellings
- Use static_cast instead of c-style casts

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-11-02 09:03:59 +01:00
Steve MandSteve M 401279e2f9 Update tinyusdz (#5849)
* Update tinyusdz to latest git commit

* Update patch file

* Bump to latest tinyusdz version

* Remove unused var (fix broken build for clients treating warnings-as-errors)

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-11-01 11:33:50 +01:00
Gene Walters 7634cf84ca USD Skinned Mesh (#5812)
USD: Skinned Mesh support
2024-10-31 21:48:28 +01:00
Gene WaltersandKim Kulling ec563823b6 Cleanup unit tests that export files by making sure those files are deleted once the unit test is complete. Moved logging from a .txt to a .log file so that git ignores the files (#5852)
Signed-off-by: AMZN-Gene <genewalt@amazon.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-30 10:39:44 +01:00
Kim Kulling 287d7ec213 Readme: Add project activity view item (#5854)
- Experimental view to mak the current activity in the project more visible and transparent
- Will create a more easy to get view onto the base activities like issues, PR and contributors
2024-10-30 10:26:48 +01:00
8d5cc3c5d5 Fix issue 5816 (cone.nff load failure): repair faulty line in 3D model file (#5817)
* Add missing numeric value

* Remove superfluous intermediate folder

* Add reference image

* Update path to match superfluous "NFF" removal

* Move reference screenshot to subfolder

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-30 00:13:17 +01:00
e699d23559 Store current exception when caught in ASSIMP_CATCH_GLOBAL_EXCEPTIONS (#5810)
In all other instances where we set mErrorString inside a catch block
we also set mException. I think that this was an oversight.

Co-authored-by: Michael Schmitt <michael.schmitt@visometry.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-29 10:59:37 +01:00
mosfet80andKim Kulling 53d4663f29 Update hunter (#5831)
changelog:
https://github.com/cpp-pm/hunter/releases

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-24 11:04:49 +02:00
Steve MandSteve M f6c62605c7 Simplify re-enabling M3D build support (#5835)
* Use CMake options to control M3D source compilation

* Revert .cpp file changes (better to treat them as external 3rd party code)

* Improve documentation

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-23 19:46:23 +02:00
mosfet80andKim Kulling 720eae1396 Update inno_setup-actions (#5833)
changelog:
https://github.com/Minionguyjpro/Inno-Setup-Action/releases

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-22 16:15:28 +02:00
Steve MandSteve M e4ef89182d Add unit tests for X3D models which were broken at 5 Oct 2020 commit 3b9d4cf (#5828)
* Add nascent tests against models broken by 5 Oct 2020 commit 3b9d4cf

* Temporarily disable chevy unit test (CI failing)

* Fix unit test assert value

* Swap actual/expected values and add correct value NE asserts

* Fix correct mesh count (indices 0-99 = 100 meshes)

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-20 23:14:26 +02:00
Steve MandSteve M fffce70fce Fix issue 2889 (molecule_ascii.cob load failure): change integers to floating point values in color triplets (#5819)
* Convert integer values to floating point

* Add reference screenshot

* Restore assert to expect pass instead of fail

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-19 19:20:49 +02:00
Qingyou ZhaoandKim Kulling a383cb1ff7 Fix a bug in the assbin loader that reads uninitialized memory (#5801)
* Fix a bug in the assbin loader that reads uninitialized memory

* Address review comment

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-10-18 20:41:47 +02:00
chefrolle695 4b9ac76815 Fixed bug in DefaultLogger::set: (#5826)
assigning s_pNullLogger to the parameter "logger" is definitely wrong.
However, custom logger previously set from user must not be deleted.
The user itself must handle allocation / deallocation.
2024-10-17 21:14:14 +02:00
Steve MandSteve M 2591d0e490 Fix broken normals: restore lines removed in commit cb22d53 of 4 May 2023 (#5824)
Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-15 23:42:07 +02:00
Steve MandSteve M ce0a50ec21 Fix FBX animation bug introduced with 24 Mar 2020 commit 14b8d12 (revert conditional to prior state) (#5815)
Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-14 11:24:27 +02:00
Pichas 811bf2df15 Fix issue 5767: Can't load USD from memory (#5818)
* initial commit

* fix element size
2024-10-13 21:11:45 +02:00
Steve MandSteve M cb4e663138 Restore 4x4 matrix functionn param and assignment prior to change in commit 168ae22 of 27 Oct 2019 (#5813)
Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-10-12 12:49:10 +02:00
Kim Kulling 9934a8d1cc Bugfix/installer add missing images (#5803)
* Installer: fix images for installer

* Installer: Add missing image
2024-10-08 08:29:08 +02:00
Kim Kulling 56ea25f9eb Installer: fix images for installer (#5800) 2024-10-07 23:14:11 +02:00
Kim Kulling ecdf8d24b8 SplitLargeMeshes: Fix crash (#5799)
- Fix nullptr access when rootnode of the scene is a nullptr. This can happen even if the scene stores any kind of meshes. closes https://github.com/assimp/assimp/issues/5791
2024-10-07 10:30:45 +02:00
Kim Kulling 1d99895e91 Update Readme.md (#5797)
Remove deprecated chat service
2024-10-02 10:47:55 +02:00
Kim Kulling 97257a3bcc Update Build.md (#5796)
- Update build from scratch with tools enabled
- Add itchi.io links
2024-09-25 09:05:37 +02:00
Julian KnodtandKim Kulling 17399d198f FBX Blendshapes: Do not require normals (#5776)
Some blendshapes don't have normal transformations, but Assimp currently requires that normals
be present. This removes that, and won't populate the normal field.

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-24 08:07:18 +02:00
Kim Kulling f63625256c Update CMakeLists.txt (#5782)
- Disable function without a prototype for clang
2024-09-17 09:41:37 +02:00
PichasandKim Kulling f4c7606faf fix no_valid_proc (#5774)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-16 09:17:22 +02:00
Kim Kulling 66187a77cf Update dll_symbol.h (#5781)
- fix compile switch
- closes https://github.com/assimp/assimp/issues/5777
2024-09-15 20:44:32 +02:00
PatrickD 5c7acc968b Fix naming in aiMaterial comment (#5780) 2024-09-13 14:24:09 +02:00
Lux f81ea6986c Restored absolute transform calculation due to https://github.com/assimp/assimp/pull/5349 which requires this now. (#5751) 2024-09-11 10:11:15 +02:00
dataislandandKim Kulling ab12e8d8ba Fix stack overflow (#5764)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-10 23:15:31 +02:00
dataislandandKim Kulling 3bd98611d7 Fix buffer overflow in MD3Loader (#5763)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-10 22:10:36 +02:00
dataislandandKim Kulling d468e633b1 Fix invalid access (#5765)
* Fix invalid access

* Update SortByPTypeProcess.cpp

Some smaller refactorings.

* Update SortByPTypeProcess.cpp

Small refactorings.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-10 09:12:01 +02:00
Kim Kulling 4024726eca Fix leak (#5762)
* Fix leak

* Update utLogger.cpp
2024-09-07 21:02:34 +02:00
Kim KullingandKim Kulling cd0ef869e3 Kimkulling/mark blender versions as not supported (#5370)
* Cleanup defs + add deprecated macro

* Remove empty line

* Remove dead code

---------

Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2024-09-05 23:40:19 +02:00
RichardTeaandKim Kulling ed3fccd5db Add option to ignore FBX custom axes (#5754)
AI_CONFIG_IMPORT_FBX_IGNORE_UP_DIRECTION
Default false

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-05 21:03:26 +02:00
Matthias MöllerandKim Kulling ff2dc2fb2e Prevents PLY from parsing duplicate properties (#5743)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-09-04 11:54:24 +02:00
Tobias Rittig, Ph.D. f69e55058d Allow usage of pugixml from a superproject (#5752)
When using CMake subprojects with an existing build of pugixml
this prevents Assimp from using its own copy.
2024-09-03 21:45:30 +02:00
RichardTea c1ffbfec06 Zero-length mChildren arrays should be nullptr (#5749)
- Children: Don't allocate a zero-length array
- aiNode::mChildren should be left nullptr instead.
2024-09-03 10:26:27 +02:00
Kim Kulling c35200e38e prepare v5.4.3 (#5741)
* prepare v5.4.3

- Increase patch level

* Update utVersion.cpp

Fix version test
2024-08-30 20:35:01 +02:00
Kim Kulling 1e09642382 Ply-Importer: Fix vulnerability (#5739) 2024-08-30 19:43:39 +02:00
Kim Kulling edaf87f186 Update ccpp.yml (#5740)
- Add ccache to build
2024-08-30 19:29:32 +02:00
Olivier ChafikandKim Kulling 88340d0ce0 build: Add ccache support (#5686)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-30 13:22:54 +02:00
FavandKim Kulling 5e912e68da Update glTF2AssetWriter.inl (#5647)
The total length is incorrect when exporting gltf2

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 23:55:18 +02:00
Vincent FazioandKim Kulling ae0ff8a88a Update PyAssimp structs with Skeleton & SkeletonBone members (#5734)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 23:45:35 +02:00
Aliaksandr KasmachouandKim Kulling 924106188e feat: add option for creating XCFramework and configure minimum iOS target (#5648)
* feat: add option for creating XCFramework and configure minimum iOS target with a build parameter

* style: update indents for iOS bash script

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 23:05:32 +02:00
HaixiandKim Kulling 389bdedda7 FBX: add metadata as properties (#5675)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 21:38:34 +02:00
Olivier ChafikandKim Kulling f39f53e860 Fix casting typo in D3MFExporter::writeBaseMaterials (color channels < 1.0f were zeroed out) (#5681)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 21:27:13 +02:00
OGAWA KenIchiandKim Kulling 11daaf79a5 Fix to judge 'multi-configuration' correctly (#5720)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 21:09:17 +02:00
Matthias MöllerandKim Kulling 3e7e4c8c52 Fix potential memory leak in SceneCombiner for LWS/IRR/MD3 loader (#5721)
* fix potential memory leak in scenecombiner

* also cleansup srclist

* de-duplicates before deleting

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-29 11:21:59 +02:00
Vincent Fazio 4338817ca2 Fix copying private data when source pointer is NULL (#5733) 2024-08-29 00:13:40 +02:00
dependabot[bot]andKim Kulling fd7ad4a9d8 Bump softprops/action-gh-release from 1 to 2 (#5730)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-27 21:47:37 +02:00
dependabot[bot] a7a424e0a7 Bump actions/upload-artifact from 1 to 4 (#5731)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 1 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v1...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-27 13:04:32 +02:00
dependabot[bot] f0ca4df704 Bump actions/download-artifact from 1 to 4 (#5732)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 1 to 4.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v1...v4)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-27 10:36:13 +02:00
imdongyeandKim Kulling d32370ff12 fix GetShortFilename function (#5728)
when blender export fbx then embedded texture path have slash and back slash.
so GetShortFilename have to check both types of slashes

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-25 17:11:19 +02:00
SanchikuuusandKim Kulling 12ed0286e4 Added more Maya materials (#5101)
* Added more Maya materials

Added Maya materials to list and add setting texture properties for getting lost textures to mesh

* Update utMaterialSystem.cpp

Now new enumerators are handled by a case label in utMaterialSystem.cpp

* Update material.h

- Fix tests: use the correct max material parameter

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-24 11:29:47 +02:00
bb9db8409f Sparky kitty studios master (#5727)
* upload contains "windows" in GH Actions

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* buildする方についてwindows-msvcのついている方にした

この二つ、何の違いがあるかいまいち理解してない…
clでビルドするかhunterでビルドするかの違い?

* upload/release対象のartifactを修正

追加当時のIssueを参考に修正(当時はHunterなかったっぽい)
https://github.com/assimp/assimp/commit/a9a0c3093226a23eb7558539bc6ebe5bcb98442b

* fix ccpp.yml -- fix matrix.name check for artifact

* fix ccpp.yml - build both hunter or not

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Update ccpp.yml

* Fix verbose string + refactorings

* Revert "Fix verbose string + refactorings"

This reverts commit 824db16a68.

* Fix verbose string + refactorings

---------

Co-authored-by: Kazuki Y <6259214+kazu0617@users.noreply.github.com>
Co-authored-by: kazu0617 <kazu0617@protonmail.com>
Co-authored-by: Kim Kulling <kim.kulling@draeger.com>
2024-08-22 11:09:14 +02:00
saceredaandKim Kulling d83904e3ee Expose aiGetEmbeddedTexture to C-API (#5382)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-21 21:15:57 +02:00
Kim Kulling bc6710a116 Fix leak in loader (#5718)
* Fix leak in loader

 Closes https://github.com/assimp/assimp/issues/5717

* Free generated mesh on importer destruction.
2024-08-17 13:49:09 +02:00
OGAWA KenIchi 10e97b2f4a Fix MSVC build error (#5716)
* add compile option /source-charset:utf-8
2024-08-16 19:33:09 +02:00
Steve MandSteve M d95a5c60ef Revert variable name (fix broken build on android) (#5715)
Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-08-14 12:13:49 +02:00
Matthias MöllerandKim Kulling 12cdbb712c Fixes possible out-of-bound read in findDegenerate (#5679)
This is possible, if the option "aiProcess_ValidateDataStructure" is deactivated as postprocessing step, but the option "aiProcess_FindDegenerates" is activated and the mesh contains invalid data structures

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 16:24:43 +02:00
Måns AndersenandKim Kulling b992ff278b Remove recursive include (#5705)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 16:14:31 +02:00
Måns AndersenandKim Kulling 9485d49e93 include Exceptional.h in 3DSExporter.cpp (#5707)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 11:17:45 +02:00
RichardTeaandKim Kulling f950f61a52 Use DRACO_GLTF_BITSTREAM (#5709)
Replaces deprecated DRACO_GLTF cmake option

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 10:09:28 +02:00
RichardTeaandKim Kulling afe06f2298 Fix MSVC PDBs and permit them to be disabled if required (#5710)
* Revert "Remove /Zi compiler flag for MSVC, release config"

This reverts commit 9e1de3ec6e.

* Allow MSVC PDB creation to be disabled

Turn off ASSIMP_INSTALL_PDB to disable PDB creation

* Whitespace cleanup

Assimp uses spaces in cmakelists, not tabs

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 09:53:33 +02:00
mkuritsuandKim Kulling d41b6b253d Added AND condition in poly2tri dll_symbol.h to only define macros fo… (#5693)
* Added ADD condition in poly2tri dll_symbol.h to only define macros for dynamic library linking if assimp is ordered to build as DLL

* Reverted last commit to handle this issue in a better way.

* added P2T_STATIC_EXPORTS to compile definitions when building assimp as DLL

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-13 09:39:53 +02:00
Nathan V. Morrical 09b981d943 fixing static build (#5713) 2024-08-13 09:23:14 +02:00
KimbattandKim Kulling 48c3a0ec46 FBX exporter - handle multiple vertex color channels (#5695)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-08-07 22:43:02 +02:00
Kim Kulling a37d748c17 Update DefaultIOSystem.cpp (#5697)
- closes https://github.com/assimp/assimp/issues/5678
2024-08-02 18:28:29 +02:00
Kim Kulling e63d3ed8e7 Make coord transfor for hs1 files optional (#5687)
* Make coord transfor for hs1 files optional

* Add config switch for HS1 transformation transformation
2024-07-31 18:39:39 +02:00
Kim Kulling 104a70f845 Return false instead of crash (#5685)
- Return false instead of crash
- closes https://github.com/assimp/assimp/issues/5684
2024-07-23 16:32:11 +02:00
Florian BornandKim Kulling 76de7cedf4 A fuzzed stride could cause the max count to become negative and hence wrap around uint (#5414)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-07-23 16:17:54 +02:00
JensEhrhardt-eOPUS c55158cd82 CalcTangents: zero vector is invalid for tangent/bitangent (#5432)
* CalcTangents: zero vector is invalid for tangent/bitangent
2024-07-23 13:13:12 +02:00
Kim Kulling 571ba09dc7 Mosfet80 updatedpoli2tri (#5682)
* updated poli2tri library to last version
2024-07-23 10:41:43 +02:00
Kim Kulling db19f62a0c Merge branch 'master' of https://github.com/assimp/assimp 2024-07-22 09:11:17 +02:00
Stoyan GaydarovandKim Kulling 5d5e0bad3c Fix a fuzz test heap buffer overflow in mdl material loader (#5658)
Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-07-19 21:48:10 +02:00
Kim Kulling 9cf03b4ddc Introduce interpolation mode to vectro and quaternion keys (#5674)
* Introduce interpolation mode to vectro and quaternion keys

* Update USDLoader.cpp

Fix review finding

* Update USDLoader.h

Fix review finding,
2024-07-18 23:54:31 +02:00
Vincent Fazio 91e93578c7 Update Python structs with missing fields (#5673) 2024-07-17 21:25:16 +02:00
Kim Kulling da281b7f48 Introduce interpolation mode to vectro and quaternion keys 2024-07-17 15:49:17 +02:00
Kim Kulling 35e4f1bf64 Kimkulling/fix double precision tests (#5660)
* Make color single precision

* Fix the unittests for double precision

* Fix merge issues

* Fix issues with Vertex + Color4

* Fix vertex operator, some tests are still red.
2024-07-12 14:37:49 +02:00
Steve MandSteve M 0cb1693689 [USD] Integrate "tinyusdz" project (#5628)
* Squash development commits for PR

* Fix failing build on armeabi-v7a via android NDK

* Update with blendshape support

* Migrate to auto-cloning and patching tinyusdz (instead of manually copying files)

* Update to latest rendermesh-refactor branch commit

* Remove tracked file

* Update to use recent commit to "dev" branch

"rendermesh-refactor" was merged to "dev" around 9 May 2024 but merge
was not obvious from commit messages

* Add UNUSED() macro

(cherry picked from commit d89fe8f034c353cc5cc5b3ac78cd8845e006de38)

* Update tinyusdz branch

* Prevent per-ABI (x86, x86_64 etc) clone on android

* Add verbose logging cmake option

* Fix macro and patch

* Address compiler warnings

* Address compiler warnings

* Address compiler warnings

* Attempt prevent re-clone/re-patch once downloaded by any ABI build

* Disable tinyusdz clone/build by default

assimp github PR auto-CI checks clone/build the tinyusdz code, and reject PR
due to compiler warnings in the 3rd party external tinyusdz project

---------

Co-authored-by: Steve M <praktique-tellypresence@yahoo.com>
2024-07-12 13:25:35 +02:00
Kim Kulling d3bec44990 Update Readme.md (#5665) 2024-07-11 14:19:09 +02:00
Kim Kulling b0aae04801 Update Readme.md (#5663)
- Add a discord invitation
2024-07-11 10:30:42 +02:00
Stepan HrbekandKim Kulling 206839d4f2 Allow empty slots in mTextureCoords (#5636)
* Allow empty slots in aiMesh::mTextureCoords.
1.Explicitly say in documentation that empty slots are allowed (it was unclear).
2.Change GetNumUVChannels() implementation to allow empty slots.
3.Revert fraction of 2da2835b29 where empty slots are detected and error logged.

* Fix #5632 by reverting fraction of d6aacefa1e where Collada texcoords are renumbered to avoid empty slots.

---------

Co-authored-by: Kim Kulling <kimkulling@users.noreply.github.com>
2024-07-10 09:01:53 +02:00
Kim Kulling 193f2c5d87 Fix compile warning (#5657) 2024-07-08 17:09:17 +02:00
Kim Kulling bff00b15f1 Replace raw pointers by std::string (#5656)
* Replace raw pointers by std::string
2024-07-06 13:59:02 +02:00
Matthias Möller d5cb1fe01f Fix potential heapbuffer overflow in md5 parsing (#5652) 2024-07-06 08:27:05 +02:00
Kim Kulling fe6e25080b Docker: Fix security finding (#5655)
- Use --no-install-recommends to avoid getting more deps than needed
2024-07-05 13:43:50 +02:00
1168 changed files with 40439 additions and 17924 deletions
+1 -1
View File
@@ -70,7 +70,7 @@ IncludeCategories:
- Regex: '^<.*'
Priority: 3
# IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentCaseLabels: false
#IndentPPDirectives: AfterHash
IndentWidth: 4
# IndentWrappedFunctionNames: false
+165 -70
View File
@@ -7,16 +7,149 @@ on:
branches: [ master ]
permissions:
contents: read # to fetch code (actions/checkout)
contents: write # to fetch code (actions/checkout),and release
jobs:
job:
build:
name: ${{ matrix.name }}-build-and-test
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
name: [ubuntu-latest-g++, macos-latest-clang++, windows-latest-cl.exe, ubuntu-latest-clang++]
name: [ubuntu-latest-g++, macos-latest-clang++, windows-latest-cl.exe, windows-latest-clang.exe, ubuntu-latest-clang++]
# For Windows msvc, for Linux and macOS let's use the clang compiler, use gcc for Linux.
include:
- name: windows-latest-clang.exe
os: windows-latest
cxx: clang++.exe
cc: clang.exe
- name: windows-latest-cl.exe
os: windows-latest
cxx: cl.exe
cc: cl.exe
- name: windows-hunter-latest-cl.exe
os: windows-latest
cxx: cl.exe
cc: cl.exe
- name: ubuntu-latest-clang++
os: ubuntu-latest
cxx: clang++
cc: clang
- name: macos-latest-clang++
os: macos-latest
cxx: clang++
cc: clang
- name: ubuntu-latest-g++
os: ubuntu-latest
cxx: g++
cc: gcc
steps:
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2
- uses: actions/checkout@v7
with:
submodules: true
- uses: lukka/get-cmake@latest
- uses: ilammy/msvc-dev-cmd@v1
- name: Set Compiler Environment
uses: lukka/set-shell-env@v1
with:
CXX: ${{ matrix.cxx }}
CC: ${{ matrix.cc }}
- name: Cache DX SDK
id: dxcache
if: contains(matrix.name, 'windows')
uses: actions/cache@v6
with:
path: '${{ github.workspace }}/DX_SDK'
key: ${{ runner.os }}-DX_SDK
restore-keys: |
${{ runner.os }}-DX_SDK
- name: Download DXSetup
if: contains(matrix.name, 'windows-latest-cl.exe') && steps.dxcache.outputs.cache-hit != 'true'
run: |
curl -s -o DXSDK_Jun10.exe --location https://download.microsoft.com/download/A/E/7/AE743F1F-632B-4809-87A9-AA1BB3458E31/DXSDK_Jun10.exe
cmd.exe /c start /wait .\DXSDK_Jun10.exe /U /O /F /S /P "${{ github.workspace }}\DX_SDK"
- name: Set Windows specific CMake arguments
if: contains(matrix.name, 'windows-latest-cl.exe')
id: windows_extra_cmake_args
run: echo ":set-output name=args::=-DASSIMP_BUILD_ASSIMP_TOOLS=1 -DASSIMP_BUILD_ASSIMP_VIEW=1" >> $GITHUB_OUTPUT
- name: Set Hunter specific CMake arguments
if: contains(matrix.name, 'hunter')
id: hunter_extra_cmake_args
run: echo "args=-DBUILD_SHARED_LIBS=OFF -DASSIMP_HUNTER_ENABLED=ON -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/cmake/polly/${{ matrix.toolchain }}.cmake" >> $GITHUB_OUTPUT
- name: configure and build
uses: lukka/run-cmake@v3
env:
DXSDK_DIR: '${{ github.workspace }}/DX_SDK'
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
cmakeAppendedArgs: '-GNinja -DCMAKE_BUILD_TYPE=Release ${{ steps.windows_extra_cmake_args.outputs.args }} ${{ steps.hunter_extra_cmake_args.outputs.args }}'
buildWithCMakeArgs: '--parallel 24 -v'
buildDirectory: '${{ github.workspace }}/build/'
- name: Exclude certain tests in Hunter specific builds
if: contains(matrix.name, 'hunter')
id: hunter_extra_test_args
run: echo "args=--gtest_filter=-utOpenGEXImportExport.Importissue1340_EmptyCameraObject:utColladaZaeImportExport.importBlenFromFileTest" >> $GITHUB_OUTPUT
- name: test
run: cd build/bin && ./unit ${{ steps.hunter_extra_test_args.outputs.args }}
shell: bash
- uses: actions/upload-artifact@v7
if: matrix.name == 'windows-msvc'
with:
name: 'assimp-bins-${{ matrix.name }}'
path: build/bin/assimp*.exe
- uses: marvinpinto/action-automatic-releases@latest
if: contains(matrix.name, 'windows-msvc-hunter')
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "master"
prerelease: true
title: "AutoRelease"
files: |
build/bin/assimp*.exe
create-release:
needs: [build]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
steps:
- id: create-release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: '${{secrets.GITHUB_TOKEN}}'
with:
tag_name: '${{github.ref}}'
release_name: 'Release ${{github.ref}}'
draft: false
prerelease: true
- run: |
echo '${{steps.create-release.outputs.upload_url}}' > release_upload_url.txt
- uses: actions/upload-artifact@v7
with:
name: create-release
path: release_upload_url.txt
upload-release:
strategy:
matrix:
name: [ubuntu-latest-g++, macos-latest-clang++, windows-latest-cl.exe, ubuntu-latest-clang++, ubuntu-gcc-hunter, macos-clang-hunter, windows-msvc-hunter]
# For Windows msvc, for Linux and macOS let's use the clang compiler, use gcc for Linux.
include:
- name: windows-latest-cl.exe
@@ -35,71 +168,33 @@ jobs:
os: ubuntu-latest
cxx: g++
cc: gcc
- name: ubuntu-gcc-hunter
os: ubuntu-latest
toolchain: ninja-gcc-cxx17-fpic
- name: macos-clang-hunter
os: macos-latest
toolchain: ninja-clang-cxx17-fpic
- name: windows-msvc-hunter
os: windows-latest
toolchain: ninja-vs-win64-cxx17
needs: [create-release]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: lukka/get-cmake@latest
- uses: ilammy/msvc-dev-cmd@v1
- name: Set Compiler Environment
uses: lukka/set-shell-env@v1
with:
CXX: ${{ matrix.cxx }}
CC: ${{ matrix.cc }}
- name: Cache DX SDK
id: dxcache
if: contains(matrix.name, 'windows')
uses: actions/cache@v4
with:
path: '${{ github.workspace }}/DX_SDK'
key: ${{ runner.os }}-DX_SDK
restore-keys: |
${{ runner.os }}-DX_SDK
- name: Download DXSetup
if: contains(matrix.name, 'windows') && steps.dxcache.outputs.cache-hit != 'true'
run: |
curl -s -o DXSDK_Jun10.exe --location https://download.microsoft.com/download/A/E/7/AE743F1F-632B-4809-87A9-AA1BB3458E31/DXSDK_Jun10.exe
cmd.exe /c start /wait .\DXSDK_Jun10.exe /U /O /F /S /P "${{ github.workspace }}\DX_SDK"
- name: Set Windows specific CMake arguments
if: contains(matrix.name, 'windows')
id: windows_extra_cmake_args
run: echo "::set-output name=args::-DASSIMP_BUILD_ASSIMP_TOOLS=1 -DASSIMP_BUILD_ASSIMP_VIEW=1 -DASSIMP_BUILD_ZLIB=1"
- name: Set Hunter specific CMake arguments
if: contains(matrix.name, 'hunter')
id: hunter_extra_cmake_args
run: echo "::set-output name=args::-DBUILD_SHARED_LIBS=OFF -DASSIMP_HUNTER_ENABLED=ON -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/cmake/polly/${{ matrix.toolchain }}.cmake"
- name: configure and build
uses: lukka/run-cmake@v3
env:
DXSDK_DIR: '${{ github.workspace }}/DX_SDK'
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
cmakeAppendedArgs: '-GNinja -DCMAKE_BUILD_TYPE=Release ${{ steps.windows_extra_cmake_args.outputs.args }} ${{ steps.hunter_extra_cmake_args.outputs.args }}'
buildWithCMakeArgs: '--parallel 24 -v'
buildDirectory: '${{ github.workspace }}/build/'
- name: Exclude certain tests in Hunter specific builds
if: contains(matrix.name, 'hunter')
id: hunter_extra_test_args
run: echo "::set-output name=args::--gtest_filter=-utOpenGEXImportExport.Importissue1340_EmptyCameraObject:utColladaZaeImportExport.importBlenFromFileTest"
- name: test
run: cd build/bin && ./unit ${{ steps.hunter_extra_test_args.outputs.args }}
shell: bash
- uses: actions/upload-artifact@v4
if: matrix.name == 'windows-msvc'
with:
name: 'assimp-bins-${{ matrix.name }}-${{ github.sha }}'
path: build/bin
- uses: softprops/action-gh-release@v3
with:
name: create-release
- id: upload-url
run: |
echo "url=$(cat create-release/release_upload_url.txt)" >> $GITHUB_OUTPUT
- uses: actions/download-artifact@v8
with:
name: 'assimp-bins-${{ matrix.name }}-${{ github.sha }}'
- uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: '${{secrets.GITHUB_TOKEN}}'
with:
files: |
*.zip
+52
View File
@@ -0,0 +1,52 @@
name: Build and Publish Prebuilt Binaries
on:
release:
types: [created]
jobs:
build:
name: ${{ matrix.name }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- name: windows-x64
os: windows-latest
arch: x64
- name: windows-x86
os: windows-latest
arch: x86
cmake_args: -A Win32
- name: macos-x64
os: macos-13
- name: macos-arm64
os: macos-latest
- name: linux-x64
os: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: lukka/get-cmake@latest
- uses: ilammy/msvc-dev-cmd@v1
with:
arch: ${{ matrix.arch }}
- name: Build
run: |
cmake -B build -S . ${{ matrix.cmake_args }} -DCMAKE_BUILD_TYPE=Release -DASSIMP_BUILD_TESTS=OFF
cmake --build build --config Release
- uses: TheDoctor0/zip-release@0.7.6
with:
filename: ${{ matrix.name }}-${{ github.event.release.tag_name }}.zip
directory: build/bin/
- uses: softprops/action-gh-release@v3
with:
files: build/bin/${{ matrix.name }}-${{ github.event.release.tag_name }}.zip
append_body: true
fail_on_unmatched_files: true
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
dry-run: false
language: c++
- name: Upload Crash
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
buildDirectory: '${{ github.workspace }}/build/'
- name: Compile .ISS to .EXE Installer
uses: Minionguyjpro/Inno-Setup-Action@v1.2.2
uses: Minionguyjpro/Inno-Setup-Action@v1.2.5
with:
path: packaging/windows-innosetup/script_x64.iss
options: /O+
+72
View File
@@ -0,0 +1,72 @@
name: PyAssimp
on:
push:
branches: [ master ]
paths:
- "port/PyAssimp/**"
- ".github/workflows/pyassimp.yml"
pull_request:
branches: [ master ]
paths:
- "port/PyAssimp/**"
- ".github/workflows/pyassimp.yml"
permissions:
contents: read # to fetch code (actions/checkout)
jobs:
build-lib:
name: ubuntu-latest-build-libassimp
runs-on: ubuntu-latest
steps:
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2
- uses: actions/checkout@v7
with:
submodules: true
- uses: lukka/get-cmake@latest
- name: configure and build
run: |
cmake -S . -B build -GNinja -DCMAKE_BUILD_TYPE=Release -DASSIMP_BUILD_TESTS=OFF -DASSIMP_BUILD_ASSIMP_TOOLS=OFF
cmake --build build --parallel --target assimp
shell: bash
- uses: actions/upload-artifact@v7
with:
name: libassimp
path: build/bin/libassimp.so*
if-no-files-found: error
test:
name: ubuntu-latest-python-${{ matrix.python-version }}
needs: build-lib
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
- uses: actions/download-artifact@v8
with:
name: libassimp
path: build/bin
- name: test
working-directory: port/PyAssimp
env:
LD_LIBRARY_PATH: ${{ github.workspace }}/build/bin
run: |
python -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest -q
shell: bash
+3 -3
View File
@@ -14,7 +14,7 @@ jobs:
name: adress-sanitizer
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: lukka/get-cmake@latest
- uses: lukka/set-shell-env@v1
with:
@@ -38,7 +38,7 @@ jobs:
name: undefined-behavior-sanitizer
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: lukka/get-cmake@latest
- uses: lukka/set-shell-env@v1
with:
@@ -62,7 +62,7 @@ jobs:
name: printf-sanitizer
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: run scan_printf script
run: ./scripts/scan_printf.sh
+8
View File
@@ -61,6 +61,8 @@ test/readlinetest*
# Python
__pycache__
.venv/
*.egg-info/
*.log
*.vcxproj
*.filters
@@ -120,3 +122,9 @@ tools/assimp_qt_viewer/ui_mainwindow.h
#Generated directory
generated/*
# 3rd party cloned repos/tarballs etc
# meshlab repo, automatically cloned via CMake (to gain 2 source files for VRML file format conversion)
contrib/meshlab/autoclone
# tinyusdz repo, automatically cloned via CMake
contrib/tinyusdz/autoclone
+210
View File
@@ -0,0 +1,210 @@
# AGENTS.md - Agent Guidelines for Assimp
This document provides guidelines for AI agents working on the Assimp codebase.
## Methodology
Never answer from memory. First try it and then show the results.
## Project Overview
Assimp (Open Asset Import Library) is a C++ library that loads various 3D file formats into a shared, in-memory format. It supports 40+ import formats and several export formats.
## Build Commands
### Basic Build (CMake + Ninja recommended)
```bash
# Configure with CMake
cmake -G Ninja -DASSIMP_BUILD_TESTS=ON -DASSIMP_WARNINGS_AS_ERRORS=ON -S . -B build
# Build
cmake --build build
```
### Key CMake Options
- `-DASSIMP_BUILD_TESTS=ON` - Build unit tests (default ON)
- `-DASSIMP_WARNINGS_AS_ERRORS=ON` - Treat warnings as errors (default ON)
- `-DASSIMP_BUILD_ASSIMP_TOOLS=ON` - Build command-line tools
- `-DASSIMP_BUILD_SAMPLES=ON` - Build sample applications
- `-DASSIMP_DOUBLE_PRECISION=ON` - Use double precision for calculations
- `-DASSIMP_NO_EXPORT=ON` - Disable export functionality
- `-DBUILD_SHARED_LIBS=OFF` - Build static library
### Running Tests
#### Run All Tests
```bash
# Using ctest
cd build && ctest
# Or run unit directly
./build/unit
```
#### Run Single Test
```bash
# Using ctest with filter
cd build && ctest -R "TestName"
# Or run unit with filter
./build/unit --gtest_filter="TestSuiteName.TestName"
```
For example:
```bash
./build/unit --gtest_filter="utObjImportExport.*"
./build/unit --gtest_filter="utMaterialSystem.*"
```
#### Test Directory
Tests are located in `test/unit/` and use Google Test. Test files are named `ut<Feature>.cpp`.
## Code Style
### Formatting
- **Use clang-format** before committing. Run: `clang-format -i <file>`
- The project uses a `.clang-format` file at the root with LLVM-based style
- Key settings:
- Indent width: 4 spaces
- Tab width: 4, UseTab: Never
- ColumnLimit: 0 (no line length limit)
- BreakConstructorInitializers: AfterColon
- AccessModifierOffset: -4
### Header File Organization
```cpp
// Order of includes (use clang-format to enforce):
// 1. Module's own header
// 2. Other assimp headers (assimp/*)
// 3. External headers (contrib/*)
// 4. Standard library headers
// 5. System headers
#include "Common/Importer.h"
#include <assimp/version.h>
#include <assimp/config.h>
#include "../contrib/some_lib/some.h"
#include <vector>
#include <string>
```
### Naming Conventions
- **Classes/Types**: PascalCase (e.g., `Importer`, `aiScene`)
- **Functions**: PascalCase (e.g., `ReadFile`, `GetExtension`)
- **Variables**: camelCase (e.g., `scene`, `importStep`)
- **Constants**: kCamelCase or UPPER_SNAKE_CASE (e.g., `kMaxVertices`)
- **Member variables**: Often prefixed with `m_` (e.g., `mScene`)
- **Static variables**: Often prefixed with `s_`
### File Naming
- **Header files**: PascalCase (e.g., `Importer.h`, `ScenePrivate.h`)
- **Source files**: PascalCase (e.g., `Importer.cpp`)
- **Test files**: Prefixed with `ut` (e.g., `utObjImportExport.cpp`)
### C++ Guidelines
#### Language Standard
- Minimum: C++17
- Use modern C++ features (smart pointers, constexpr, etc.)
#### Error Handling
- Use exceptions for recoverable errors (derived from `std::exception`)
- Use `ai_assert` for debugging assertions in code
- Return error codes from C API functions
#### Classes
- Use `ai_enable_erasing` pattern for optional features
- Use PImpl idiom for ABI stability where appropriate
#### Memory Management
- Use smart pointers (`std::unique_ptr`, `std::shared_ptr`)
- Prefer RAII patterns
- Document ownership semantics in function comments
### Importers/Exporters
#### Structure
Each importer typically has:
1. Header in `code/AssetLib/<Format>/`
2. Implementation in `code/AssetLib/<Format>/`
3. Registration in `code/Common/ImporterRegistry.cpp`
4. Unit tests in `test/unit/ImportExport/`
#### Registration
```cpp
void GetImporterInstanceList(std::vector<BaseImporter*>& out);
// Add to registry
out.push_back(new MyFormatImporter());
```
### Post-Processing
- Located in `code/PostProcessing/`
- Each process inherits from `BaseProcess`
- Implement `ExecuteOnScene` method
### Documentation
- Use Doxygen-style comments for public APIs
- Example:
```cpp
/// <summary>
/// Loads a file from disk.
/// </summary>
/// <param name="pFile">Path to the file.</param>
/// <returns>Pointer to the imported scene.</returns>
aiScene* Importer::ReadFile(const char* pFile);
```
### Contributing
1. Create a fork of assimp
2. Create a branch for your feature/fix
3. Run `clang-format` on modified files
4. Ensure tests pass
5. Open a PR against `master` branch
## Directory Structure
```
code/
AssetLib/ - Importers and exporters
CApi/ - C API wrapper
Common/ - Shared utilities
Geometry/ - Geometry processing
Material/ - Material handling
PostProcessing/ - Mesh post-processing
include/ - Public headers (assimp/)
test/
unit/ - Unit tests
models/ - Test 3D models
test/ - Test data (non-BSD licensed)
contrib/ - Third-party libraries
```
## CI/CD
The project runs CI on GitHub Actions:
- Builds on Linux and Windows
- Runs tests including memory leak detection
- Checks compiler warnings
## Common Tasks
### Adding a New Importer
1. Create `code/AssetLib/<Format>/<Format>Importer.h`
2. Create `code/AssetLib/<Format>/<Format>Importer.cpp`
3. Register in `code/Common/ImporterRegistry.cpp`
4. Add tests in `test/unit/ImportExport/`
5. Add to CMakeLists.txt if needed
### Running Specific Test Suite
```bash
# Test specific importer
./build/unit --gtest_filter="utglTF2ImportExport.*"
# Test post-processing
./build/unit --gtest_filter="utTriangulate.*"
# Test math operations
./build/unit --gtest_filter="utMatrix4x4.*"
```
+172
View File
@@ -0,0 +1,172 @@
# Asset-Importer-Lib AI Tool Use Policy
## Policy
Assimp's policy is that contributors can use whatever tools they would like to
craft their contributions, but there must be a **human in the loop**.
**Contributors must read and review all LLM-generated code or text before they
ask other project members to review it.** The contributor is always the author
and is fully accountable for their contributions. Contributors should be
sufficiently confident that the contribution is high enough quality that asking
for a review is a good use of scarce maintainer time, and they should be **able
to answer questions about their work** during review.
We expect that new contributors will be less confident in their contributions,
and our guidance to them is to **start with small contributions** that they can
fully understand to build confidence. We aspire to be a welcoming community
that helps new contributors grow their expertise, but learning involves taking
small steps, getting feedback, and iterating. Passing maintainer feedback to an
LLM doesn't help anyone grow, and does not sustain our community.
Contributors are expected to **be transparent and label contributions that
contain substantial amounts of tool-generated content**. Our policy on
labelling is intended to facilitate reviews, and not to track which parts of
Assimp are generated. Contributors should note tool usage in their pull request
description, commit message, or wherever authorship is normally indicated for
the work. For instance, use a commit message trailer like Assisted-by: <name of
code assistant>. This transparency helps the community develop best practices
and understand the role of these new tools.
This policy includes, but is not limited to, the following kinds of
contributions:
- Code, usually in the form of a pull request
- RFCs or design proposals
- Issues or security vulnerabilities
- Comments and feedback on pull requests
## Details
To ensure sufficient self review and understanding of the work, it is strongly
recommended that contributors write PR descriptions themselves (if needed,
using tools for translation or copy-editing). The description should explain
the motivation, implementation approach, expected impact, and any open
questions or uncertainties to the same extent as a contribution made without
tool assistance.
AI tools must not be used to fix GitHub issues labelled [`good first
issue`][good-first-issue]. These issues are generally not urgent, and are
intended to be learning opportunities for new contributors to get familiar with
the codebase. Whether you are a newcomer or not, fully automating the process
of fixing this issue squanders the learning opportunity and doesn't add much
value to the project. **Using AI tools to fix issues labelled as "good first
issues" is forbidden**.
[good-first-issue]: https://github.com/llvm/llvm-project/issues/?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22
## Extractive Contributions
The reason for our "human-in-the-loop" contribution policy is that processing
patches, PRs, RFCs, and comments to Assimp is not free -- it takes a lot of
maintainer time and energy to review those contributions! Sending the
unreviewed output of an Assimp to open source project maintainers *extracts* work
from them in the form of design and code review, so we call this kind of
contribution an "extractive contribution".
Our **golden rule** is that a contribution should be worth more to the project
than the time it takes to review it. These ideas are captured by this quote
from the book [Working in Public][public] by Nadia Eghbal:
[public]: https://press.stripe.com/working-in-public
> \"When attention is being appropriated, producers need to weigh the costs and
> benefits of the transaction. To assess whether the appropriation of attention
> is net-positive, it's useful to distinguish between *extractive* and
> *non-extractive* contributions. Extractive contributions are those where the
> marginal cost of reviewing and merging that contribution is greater than the
> marginal benefit to the project's producers. In the case of a code
> contribution, it might be a pull request that's too complex or unwieldy to
> review, given the potential upside.\" \-- Nadia Eghbal
Prior to the advent of LLMs, open source project maintainers would often review
any and all changes sent to the project simply because posting a change for
review was a sign of interest from a potential long-term contributor. While new
tools enable more development, it shifts effort from the implementor to the
reviewer, and our policy exists to ensure that we value and do not squander
maintainer time.
Reviewing changes from new contributors is part of growing the next generation
of contributors and sustaining the project. We want the LLVM project to be
welcoming and open to aspiring compiler engineers who are willing to invest
time and effort to learn and grow, because growing our contributor base and
recruiting new maintainers helps sustain the project over the long term. Being
open to contributions and [liberally granting commit access][commit-access]
is a big part of how LLVM has grown and successfully been adopted all across
the industry. We therefore automatically post a greeting comment to pull
requests from new contributors and encourage maintainers to spend their time to
help new contributors learn.
[commit-access]: https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access
## Handling Violations
If a maintainer judges that a contribution doesn't comply with this policy,
they should paste the following response to request changes:
This PR doesn't appear to comply with our policy on tool-generated content,
and requires additional justification for why it is valuable enough to the
project for us to review it. Please see our developer policy on
AI-generated contributions: http://llvm.org/docs/AIToolPolicy.html
The best ways to make a change less extractive and more valuable are to reduce
its size or complexity or to increase its usefulness to the community. These
factors are impossible to weigh objectively, and our project policy leaves this
determination up to the maintainers of the project, i.e. those who are doing
the work of sustaining the project.
If or when it becomes clear that a GitHub issue or PR is off-track and not
moving in the right direction, maintainers should apply the `extractive` label
to help other reviewers prioritize their review time.
If a contributor fails to make their change meaningfully less extractive,
maintainers should escalate to the relevant moderation or admin team for the
space (GitHub, Discourse, Discord, etc) to lock the conversation.
## Copyright
Artificial intelligence systems raise many questions around copyright that have
yet to be answered. Our policy on AI tools is similar to our copyright policy:
Contributors are responsible for ensuring that they have the right to
contribute code under the terms of our license, typically meaning that either
they, their employer, or their collaborators hold the copyright. Using AI tools
to regenerate copyrighted material does not remove the copyright, and
contributors are responsible for ensuring that such material does not appear in
their contributions. Contributions found to violate this policy will be removed
just like any other offending contribution.
## Examples
Here are some examples of contributions that demonstrate how to apply
the principles of this policy:
- [This PR][alive-pr] contains a proof from Alive2, which is a strong signal of
value and correctness.
- This [generated documentation][gsym-docs] was reviewed for correctness by a
human before being posted.
[alive-pr]: https://github.com/llvm/llvm-project/pull/142869
[gsym-docs]: https://discourse.llvm.org/t/searching-for-gsym-documentation/85185/2
## References
Our policy was informed by experiences in other communities:
- [Fedora Council Policy Proposal: Policy on AI-Assisted Contributions (fetched
2025-10-01)][fedora]: Some of the text above was copied from the Fedora
project policy proposal, which is licensed under the [Creative Commons
Attribution 4.0 International License][cca]. This link serves as attribution.
- [Rust draft policy on burdensome PRs][rust-burdensome]
- [Seth Larson's post][security-slop]
on slop security reports in the Python ecosystem
- The METR paper [Measuring the Impact of Early-2025 AI on Experienced
Open-Source Developer Productivity][metr-paper].
- [QEMU bans use of AI content generators][qemu-ban]
- [Slop is the new name for unwanted AI-generated content][ai-slop]
[fedora]: https://communityblog.fedoraproject.org/council-policy-proposal-policy-on-ai-assisted-contributions/
[cca]: https://creativecommons.org/licenses/by/4.0/
[rust-burdensome]: https://github.com/rust-lang/compiler-team/issues/893
[security-slop]: https://sethmlarson.dev/slop-security-reports
[metr-paper]: https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/
[qemu-ban]: https://www.qemu.org/docs/master/devel/code-provenance.html#use-of-ai-content-generators
[ai-slop]: https://simonwillison.net/2024/May/8/slop/
+47 -46
View File
@@ -1,36 +1,12 @@
# Build / Install Instructions
## Install on all platforms using vcpkg
You can download and install assimp using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
```bash
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install assimp
```
The assimp port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
## Install on Ubuntu
You can install the Asset-Importer-Lib via apt:
```
sudo apt-get update
sudo apt-get install libassimp-dev
```
## Install pyassimp
You need to have pip installed:
```
pip install pyassimp
```
## Manual build instructions
### Install CMake
Asset-Importer-Lib can be built for a lot of different platforms. We are using cmake to generate the build environment for these via cmake. So you have to make sure that you have a working cmake-installation on your system. You can download it at https://cmake.org/ or for linux install it via
```bash
sudo apt-get install cmake
```
### Install prerequisites
You need to install
* cmake
* Your compiler (must support C++17 and C99 at least)
* For Windows
* DX-SDK 9 if you want to use our 3D-Viewer
### Get the source
Make sure you have a working git-installation. Open a command prompt and clone the Asset-Importer-Lib via:
@@ -38,16 +14,23 @@ Make sure you have a working git-installation. Open a command prompt and clone t
git clone https://github.com/assimp/assimp.git
```
### Build from source:
* For *assimp.lib* without any tools:
```bash
cd assimp
cmake CMakeLists.txt
cmake CMakeLists.txt
cmake --build .
```
* For assimp with the common tools like *assimp-cmd*
```bash
cd assimp
cmake CMakeLists.txt -DASSIMP_BUILD_ASSIMP_TOOLS=ON
cmake --build .
```
Note that by default this builds a shared library into the `bin` directory. If you want to build it as a static library see the build options at the bottom of this file.
### Build instructions for Windows with Visual-Studio
First, you have to install Visual-Studio on your windows-system. You can get the Community-Version for free here: https://visualstudio.microsoft.com/de/downloads/
First, you have to install Visual-Studio on your windows-system. You can get the Community-Version for free [here](https://visualstudio.microsoft.com/downloads/)
To generate the build environment for your IDE open a command prompt, navigate to your repo and type:
```bash
cmake CMakeLists.txt
@@ -57,19 +40,8 @@ This will generate the project files for the visual studio. All dependencies use
### Build instructions for Windows with UWP
See <https://stackoverflow.com/questions/40803170/cmake-uwp-using-cmake-to-build-universal-windows-app>
### Build instructions for Linux / Unix
Open a terminal and got to your repository. You can generate the makefiles and build the library via:
```bash
cmake CMakeLists.txt
make -j4
```
The option -j describes the number of parallel processes for the build. In this case make will try to use 4 cores for the build.
If you want to use an IDE for linux you can try QTCreator for instance.
### Build instructions for MinGW
Older versions of MinGW's compiler (e.g. 5.1.0) do not support the -mbig_obj flag
Older versions of MinGW's compiler (e.g. 5.1.0) do not support the -mbig_obj flag
required to compile some of assimp's files, especially for debug builds.
Version 7.3.0 of g++-mingw-w64 & gcc-mingw-w64 appears to work.
@@ -95,7 +67,7 @@ The cmake-build-environment provides options to configure the build. The followi
- **ASSIMP_NO_EXPORT (default OFF)**: Disable Assimp's export functionality.
- **ASSIMP_BUILD_ZLIB (default OFF)**: Build our own zlib.
- **ASSIMP_BUILD_ALL_EXPORTERS_BY_DEFAULT (default ON)**: Build Assimp with all exporters enabled.
- **ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT (default ON)**: Build Assimp with all importers enabled.
- **ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT (default ON)**: Build Assimp with (most) importers enabled. Currently, USD importer is not included. See ASSIMP_BUILD_USD_IMPORTER.
- **ASSIMP_BUILD_ASSIMP_TOOLS (default OFF)**: If the supplementary tools for Assimp are built in addition to the library.
- **ASSIMP_BUILD_SAMPLES (default OFF)**: If the official samples are built as well (needs Glut).
- **ASSIMP_BUILD_TESTS (default ON)**: If the test suite for Assimp is built in addition to the library.
@@ -111,3 +83,32 @@ The cmake-build-environment provides options to configure the build. The followi
- **USE_STATIC_CRT (default OFF)**: Link against the static MSVC runtime libraries.
- **ASSIMP_BUILD_DRACO (default OFF)**: Build Draco libraries. Primarily for glTF.
- **ASSIMP_BUILD_ASSIMP_VIEW (default ON, if DirectX found, OFF otherwise)**: Build Assimp view tool (requires DirectX).
- **ASSIMP_BUILD_USD_IMPORTER (default OFF, requires ASSIMP_WARNINGS_AS_ERRORS to be OFF)**: Build USD importer, defaults to off for CI purposes
### Install prebuild binaries
## Install on all platforms using vcpkg
You can download and install assimp using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
```bash
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install assimp
```
The assimp port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
### Install on Ubuntu
You can install the Asset-Importer-Lib via apt:
```
sudo apt-get update
sudo apt-get install libassimp-dev
```
### Install pyassimp
You need to have pip installed:
```
pip install pyassimp
```
### Get the SDK from itch.io
Just check [itch.io](https://kimkulling.itch.io/the-asset-importer-lib)
-607
View File
@@ -1,607 +0,0 @@
----------------------------------------------------------------------
CHANGELOG
----------------------------------------------------------------------
4.1.0 (2017-12):
- FEATURES:
- Export 3MF ( experimental )
- Import / Export glTF 2
- Introduce new zib-lib to eb able to export zip-archives
- FIXES/HOUSEKEEPING:
- Added missing include to stdlib.h and remove load library call
- Fix install for builds with MSVC compiler and NMake.
- Update list of supported file formats.
- Add TriLib to the official list of supported ports.
- Re-enabling PACK_STRUCT for MDL files.
- Use std.::unique_ptr
- Update D3MFExporter.h
- Update MD3Loader.cpp, using index
- Fix all warnings on MSVC14
- Copy assimp dll to unit folder on windows
- Update jvm port supported formats
- Add support for building Mac OS X Framework bundles
- Check for nullptr dereferencing before copying scene data
- Update ValidateDataStructure.h, typo
- Enable data structure validation in cases where it doesn't cause failures
- Remove some dead assignments
- fast_atof: Silence some uninitialized variable warnings
- Check for area test if the face is a triangle.
- Set mNumUVComponents to 0 when deleting texture coordinate sets
- Only scale the root node because this will rescale all children nodes as well.
- Issue 1514: Fix frame pointer arithmetic
- Prevent failing stringstream to crash the export process
- powf -> pow
- add Defines.h to include folder for install.
- Android:
- Fix android build
- Fix assimp for cross compile for android
- Use define for D_FILE_OFFSET_BITS only for not-android systems.
- FBX:
- Fix handling with embedded textures
- FBX 7500 Binary reading
- Remove dead assignment
- Fix export of deleted meshes; Add LazyDict::Remove method
- Log an error instead of letting the fbx-importer crash. ( issue 213 )
- Replace bad pointer casting with memcpy
- Remove useless const qualifier from return value
- Add explicit instantiation of log_prefix so other FBX source files can see it
- add missing inversion of postrotation matrix for fbx.
- FIReader: Silence uninitialized variable warning
- Update version check in FBX reader to check for version >= 7500
- Use actual min/max of anim keys when start/stop time is missing
- GLTF1:
- Fix output of glTF 1 version string
- Fix delete / delete[] mismatch in glTFAsset
- Don’t ignore rgba(1,1,1,1) color properties
- glTF2 primitives fixes
- Don’t ignore rgba(1,1,1,1) color properties
- Fix delete / delete[] mismatch in glTFAsset
- Remove KHR_binary_glTF code
- glTF nodes can only hold one mesh. this simply assigns to and check’s a Node’s Mesh
- version in glb header is stored as uint32_t
- GLTF2:
- node name conflict fix
- Fix transform matrices multiplication order
- Preserve node names when importing
- Add support for tangents in import
- Fix typo on gltf2 camera parameters
- Moved byteStride from accessor to bufferView
- Implemented reading binary glTF2 (glb) files
- Fix signed/unsigned warning
- Add postprocess step for scaling
- Fix shininess to roughness conversion
- Prefer “BLEND” over “MASK” as an alphaMode default
- Approximate specularity / glossiness in metallicRoughness materials
- Diffuse color and diffuse texture import and export improvements
- Addressed some mismatched news/deletes caused by the new glTF2 sources.
- Fix delete / delete[] mismatches in glTF2 importer
- use correct name of exporter to gltf2
- Fix possible infinite loop when exporting to gltf2
- Fix glTF2::Asset::FindUniqueID() when the input string is >= 256 chars
- Fix glTF2 alphaMode storage and reading
- Fix glTF 2.0 multi-primitive support
- Load gltf .bin files from correct directory
- Add support for importing both glTF and glTF2 files
- ampler improvements; Add new LazyDict method
- Changes to GLTF2 materials
- Remove Light, Technique references
- Start removing materials common, and adding pbrSpecularGlossiness
- Use !ObjectEmpty() vs. MemberCount() > 0
- Working read, import, export, and write of gltf2 (pbr) material
- Check in gltf2 models to test directory
- Remove un-needed test models
- Start managing and importing gltf2 pbr materials
- Update glTF2 Asset to use indexes
- Duplicate gltfImporter as gltf2Importer; Include glTF2 importer in CMake List
- glTF2: Fix animation export
- use opacity for diffuse alpha + alphaMode
- STL:
- Restore import of multi mesh binary STLs
- Blender:
- Silence warning about uninitialized member
- MDLImporter:
- Don't take address of packed struct member
- assimp_cmd:
- Fix strict-aliasing warnings
- Open3DGC:
- Fix strict-aliasing warnings
- Add assertions to silence static analyzer warnings
- Remove redundant const qualifiers from return types
- Fix some uninitialized variable warnings
- Remove OPEN3DGC and compression references
- unzip:
- Remove dead assignment
- Bail on bad compression method
- Fix possibly uninitialized variables
- clipper:
- Add assertion to silence a static analyzer warning
- OpenDDLExport:
- Reduce scope of a variable
- Remove dead variable
- Remove dead assignment
- Fix another potential memory leak
- X3DImporter:
- Add assertions to silence static analyzer warnings
- Add missing unittest
- Workaround for buggy Android NDK (issue #1361)
- TerragenLoader:
- Remove unused variable
- SIBImporter:
- Add assertions to silence static analyzer warnings
- IFC:
- Remove dead code
- Add explicit instantiation of log_prefix so IFCMaterial.cpp can see it
- PLY:
- Remove dead assignment and reduce scope of a variable
- fix vertex attribute lookup.
- OpenGEX:
- Add assertion to silence a static analyzer warning
- Fix for TextureFile with number in file name
- Return early when element is TextureFile
- NFF:
- Add assertions to silence static analyzer warnings
- Split up some complicated assignments
- Raw: Fix misleading indentation warning
- Reduce scope of a variable
- LWO
- Reduce scope of a variable
- IRRLoader:
- Fix confusing boolean casting
- AssbinExporter:
- Add assertion to silence a static analyzer warning
- ASE:
- Add assertion to silence a static analyzer warning
- AMFImporter:
- Add assertion to silence a static analyzer warning
- Add a block
- OptimizeGraph:
- Fix possible null pointer dereference
- RemoveRedundantMaterials:
- Add assertion to silence a static analyzer warning
- ImproveCacheLocality:
- Add assertion to silence a static analyzer warning
- RemoveRedundantMaterials:
- Set pointer to nullptr after deleting it
- Travis:
- Disable unit tests in scan-build config
- Move slower builds earlier to improve parallelization
- Add static analysis to build
- Remove unused branch rule for travis.
- Add Clang UBSan build configuration
- Treat warnings as errors, without typos this time
- Unittests:
- Add VS-based source groups for the unittests.
- Collada:
- export <library_animations> tag
- Update ColladaExporter.cpp
- Silence uninitialized variable warning
- Add support for line strip primitives
- Obj Wavefront:
- check in exporting against out-of-bounds-access .
- Issue 1351: use correct name for obj-meshname export for groups.
- fix mem-lead: face will be not released in case of an error.
- Anatoscope obj exporter nomtl
- Raise exception when obj file contains invalid face indices
- Added alternative displacement texture token in OBJ MTL material.
- Obj: rename attribute from exporter.
- Fix OBJ discarding all material names if the material library is missing
- Step:
- use correct lookup for utf32
- MD2:
- Fix MD2 frames containing garbage
- STL
- add missing const.
- Fix memory-alignment bug.
- Fix issue 104: deal with more solids in one STL file.
- CMake
- Fix issue 213: use correct include folder for assimp
- Doxygen
- Fix issue 1513: put irrXML onto exclucde list for doxygen run
- PyAssimp:
- Search for libassimp.so in LD_LIBRARY_PATH if available.
- Fix operator precedence issue in header check
- Split setup.py into multiple lines
- Detect if Anaconda and fixed 3d_viewer for Python 3
- created a python3 version of the 3dviewer and fixed the / = float in py3
- Blender:
- Fix invalid access to mesh array when the array is empty.
- Fix short overflow.
- Silence warning about inline function which is declared but not defined
- JAssimp
- Changed license header for IHMC contributions from Apache 2.0 to BSD
- Add Node metadata to the Jassmip Java API
- Added supported for custom IO Systems in Java. Implemented ClassLoader IO System
- Added a link to pure jvm assimp port
- Clang sanitizer:
- Undefined Behavior sanitizer
- Fixed a divide by zero error in IFCBoolean that was latent, but nevertheless a bug
- B3DImporter:
- Replace bad pointer casting with memcpy
- AppVeyor:
- Cleanup and Addition of VS 2017 and running Tests
- Fixed File Size reported as 0 in tests that use temporary files
- x86 isn't a valid VS platform. Win32 it is, then.
- Replaced the worker image name, which doesn't work as generator name, with a manually created generator name.
- Cleaned up appveyor setup, added VS 2017 to the build matrix and attempted to add running of tests.
- Treat warnings as errors on Appveyor
- Disable warning 4351 on MSVC 2013
- OpenGEXImporter:
- Copy materials to scene
- Store RefInfo in unique_ptr so they get automatically cleaned up
- Fix IOStream leak
- Store ChildInfo in unique_ptr so they get automatically cleaned up
- improve logging to be able to detect error-prone situations.
- AMFImporter:
- Fix memory leak
- UnrealLoader:
- Fix IOStream leak
- Upgrade RapidJSON to get rid of a clang warning
- zlib:
- Update zlib contribution
- Removed unnecessary files from zlib contribution
- Replaced unsigned long for the crc table to z_crc_t, to match what is returned by get-crc_table
- MakeVerboseFormat:
- Fix delete / delete[] mismatches in MakeVerboseFormat
- MaterialSystem:
- Fix out-of-bounds read in MaterialSystem unit test
- SIB:
- Added support for SIB models from Silo 2.5
- AssbinExporter:
- Fix strict aliasing violation
- Add Write specialization for aiColor3D
- DefaultLogger:
- Whitespace cleanup to fix GCC misleading indentation warning
- MDP:
- Fix encoding issues.
- PreTransformVertices:
- fix name lost in mesh and nodes when load with flag
- C4D:
- Fixes for C4D importer
- Unzip:
- Latest greatest.
4.0.1 (2017-07-28)
- FIXES/HOUSEKEEPING:
- fix version test.
- Not compiling when using ASSIMP_DOUBLE_PRECISION
- Added support for python3
- Check if cmake is installed with brew
- Low performance in OptimizeMeshesProcess::ProcessNode with huge numbers of meshes
- Elapsed seconds not shown correctly
- StreamReader: fix out-of-range exception
- PPdPmdParser: fix compilation for clang
4.0.0 (2017-07-18)
FEATURES:
- Double precision support provided ( available via cmake option )
- QT-Widget based assimp-viewer ( works for windows, linux, osx )
- Open3DGC codec supported by glFT-importer
- glTF: Read and write transparency values
- Add Triangulate post-processing step to glTF exporters
- Update rapidjson to v1.0.2
- Added method to append new metadata to structure
- Unittests: intoduce a prototype model differ
- X3D support
- AMF support
- Lugdunum3D support
- Obj-Importer: obj-homogeneous_coords support
- Obj-Importer: new streaming handling
- Added support for 64 bit version header introduced in FbxSdk2016
- Travis: enable coverall support.
- PyAssimp: New version of the pyASSIMP 3D viewer, with much improved 3D controls
- Morph animation support for collada
- Added support for parameters Ni and Tf in OBJ/MTL file format
- aiScene: add method to add children
- Added new option to IFC importer to control tessellation angle + removed unused IFC option
- aiMetaData: introduce aiMetaData::Dealloc
- Samples: add a DX11 example
- travis ci: test on OXS ( XCode 6.3 ) as well
- travis ci: enable sudo support.
- openddlparser: integrate release v0.4.0
- aiMetaData: Added support for metadata in assbin format
FIXES/HOUSEKEEPING:
- Introduce usage of #pragma statement
- Put cmake-scripts into their own folder
- Fix install pathes ( issue 938 )
- Fix object_compare in blender importer( issue 946 )
- Fix OSX compilation error
- Fix unzip path when no other version was found ( issue 967 )
- Set _FILE_OFFSET_BITS=64 for 32-bit linux ( issue 975 )
- Fix constructor for radjson on OSX
- Use Assimp namespace to fix build for big-endian architectures
- Add -fPIC to C Flags for 64bit linux Shared Object builds
- MDLLoader: fix resource leak.
- MakeVerboseFormat: fix invalid delete statement
- IFC: fix possible use after free access bug
- ComputeUVMappingprocess: add missing initialization for scalar value
- Fix invalid release of mat + mesh
- IrrImporter: Fix release functions
- Split mesh before exporting gltf ( issue 995 )
- 3MFImporter: add source group for visual studio
- IFC: Switch generated file to 2 files to fix issue related to <mingw4.9 ( Thanks Qt! )
- ObjImporter: fix test for vertices import
- export scene combiner ( issues177 )
- FBX: make lookup test less strict ( issues 994 )
- OpenGEX-Importer: add import of vertex colors ( issue 954 )
- fix bug when exporting mRotationKeys data
- fix mingw build (mingw supports stat64 nowadays)
- cfileio: fix leaks by not closing files in the destructor
- Fix OBJ parser mtllib statement parsing bug.
- Q3BSP-Importer: remove dead code
- Fix BlenderDNA for clang cross compiler.
- ScenePreprocessor: fix invalid index counter.
- Fix compiler warnings ( issue 957 )
- Fix obj .mtl file loading
- Fixed a compile error on MSVC14 x64 caused by the /bigobj flag failing to be set for the 1 and 2-suffixed versions introduced in commit 0a25b076b8968b7ea2aa96d7d1b4381be2d72ce6
- Fixed build warnings on MSVC14 x64
- Remove scaling of specular exponent in OBJFileImporter.cpp
- use ai_assert instead of assert ( issue 1076 )
- Added a preprocessor definition for MSVC to silence safety warnings regarding C library functions. This addresses all warnings for MSVC x86 and x64 when building zlib, tools and viewer as a static lib
- fix parsing of texture name ( issue 899 )
- add warning when detecting invalid mat definition ( issue 1111 )
- copy aiTexture type declaration instead of using decltype for declaration to fix iOS build( issue 1101 )
- FBX: Add additional material properties
- FBX: Correct camera position and clip planes
- FBX: Add correct light locations and falloff values
- fix typo ( issue 1141 )
- Fix collada export. Don't duplicate TEXCOORD/NORMALS/COLORS in <vertices> and <polylist> ( issue 1084 )
- OBJParser: set material index when changing current material
- OBJ: check for null mesh before updating material index
- add vertex color export support ( issue 809 )
- Fix memory leak in Collada importer ( issue 1169 )
- add stp to the list of supported extensions for step-files ( issue 1183 )
- fix clang build ( Issue-1169 )
- fix for FreeBSD
- Import FindPkgMacros to main CMake Configuration
- Extended support for tessellation parameter to more IFC shapes
- defensice handling of utf-8 decode issues ( issue 1211 )
- Fixed compiler error on clang 4.0 running on OSX
- use test extension for exported test files ( issue 1228 )
- Set UVW index material properties for OBJ files
- Fixed no member named 'atop' in global namespace issue for Android NDK compilation
- Apply mechanism to decide use for IrrXML external or internal
- Fix static init ordering bug in OpenGEX importer
- GLTF exporter: ensure animation accessors have same count
- GLTF exporter: convert animation time from ticks to seconds
- Add support for reading texture coordinates from PLY meshes with properties named 'texture_u' and 'texture_v'
- Added TokensForSearch in BlenderLoader to allow CanRead return true for in-memory files.
- fix wrong delete ( issue 1266 )
- OpenGEX: fix invalid handling with color4 token ( issue 1262 )
- LWOLoader: fix link in loader description
- Fix error when custom CMAKE_C_FLAGS is specified
- Fast-atof: log overflow errors
- Obj-Importer: do not break when detecting an overflow ( issue 1244 )
- Obj-Importer: fix parsing of multible line data definitions
- Fixed bug where IFC models with multiple IFCSite only loaded 1 site instead of the complete model
- PLYImporter: - optimize memory and speed on ply importer / change parser to use a file stream - manage texture path in ply
import - manage texture coords on faces in ply import - correction on point cloud faces generation
- Utf8: integrate new lib ( issue 1158 )
- fixed CMAKE_MODULE_PATH overwriting previous values
- OpenGEX: Fixed bug in material color processing ( issue 1271 )
- SceneCombiner: move header for scenecombiner to public folder.
- GLTF exporter: ensure buffer view byte offsets are correctly aligned
- X3D importer: Added EXPORT and IMPORT to the list of ignored XML tags
- X3D Exporter: fixed missing attributes
- X3D importer: Fixed import of normals for the single index / normal per vertex case
- X3D importer: Fixed handling of inlined files
- X3D importer: fixed whitespace handling (issue 1202)
- X3D importer: Fixed iterator on MSVC 2015
- X3D importer: Fixed problems with auto, override and regex on older compilers
- X3D importer: Fixed missing header file
- X3D importer: Fixed path handling
- X3D importer: Implemented support for binary X3D files
- fix build without 3DS ( issue 1319 )
- pyassimp: Fixed indices for IndexedTriangleFanSet, IndexedTriangleSet and IndexedTriangleStripSet
- Fixes parameters to pyassimp.load
- Obj-Importe: Fixed texture bug due simultaneously using 'usemtl' and 'usemap' attributes
- check if all exporters are disabled ( issue 1320 )
- Remove std functions deprecated by C++11.
- X-Importer: make it deal with lines
- use correct path for compilers ( issue 1335 )
- Collada: add workaround to deal with polygon with holes
- update python readme
- Use unique node names when loading Collada files
- Fixed many FBX bugs
API COMPATIBILITY:
- Changed ABI-compatibility to v3.3.1, please rebuild your precompiled libraries ( see issue 1182 )
- VS2010 outdated
3.3.1 (2016-07-08)
FIXES/HOUSEKEEPING:
- Setup of default precision for 17 exporters
- Fix xcode project files
- Fix BlenderTesselator: offsetof operator
- Invalid version in cmake file
- Update pstdint.h to latest greatest
3.3.0 (2016-07-05)
FEATURES:
- C++11 support enabled
- New regression-test-UI
- Experimental glTF-importer support
- OpenGEX: add support for cameras and lights
- C4D: update to latest Melange-SDK
- Add a gitter channel
- Coverity check enabled
- Switch to <...> include brackets for public headers
- Enable export by pyAssimp
- CI: check windows build
- Add functionality to perform a singlepost-processing step
- many more, just check the history
FIXES/HOUSEKEEPING:
- Fix of many resource leaks in unittests and main lib
- Fix iOS-buildfor X64
- Choosing zlib manually for cmake
- many more, just check the history
3.2.1 (2016-010-10)
FEATURES:
- Updated glTF exporter to meet 1.0 specification.
FIXES/HOUSEKEEPING:
- Fixed glTF Validator errors for exported glTF format.
ISSUES:
- Hard coded sampler setting for
- magFilter
- minFilter
- void* in ExportData for accessor max and min.
3.2.0 (2015-11-03)
FEATURES:
- OpenDDL-Parser is part of contrib-source.
- Experimental OpenGEX-support
- CI-check for linux and windows
- Coverity check added
- New regression testsuite.
FIXES/HOUSEKEEPING:
- Hundreds of bugfixes in all parts of the library
- Unified line endings
API COMPATIBILITY:
- Removed precompiled header to increase build speed for linux
3.1.1 (2014-06-15)
FEATURES:
- Support for FBX 2013 and newer, binary and ASCII (this is partly
work from Google Summer of Code 2012)
- Support for OGRE binary mesh and skeleton format
- Updated BLEND support for newer Blender versions
- Support for arbitrary meta data, used to hold FBX and DAE metadata
- OBJ Export now produces smaller files
- Meshes can now have names, this is supported by the major importers
- Improved IFC geometry generation
- M3 support has been removed
FIXES/HOUSEKEEPING:
- Hundreds of bugfixes in all parts of the library
- CMake is now the primary build system
API COMPATIBILITY:
- 3.1.1 is not binary compatible to 3.0 due to aiNode::mMetaData
and aiMesh::mName
- Export interface has been cleaned up and unified
- Other than that no relevant changes
3.0 (2012-07-07)
FEATURES:
- new export interface similar to the import API.
- Supported export formats: Collada, OBJ, PLY and STL
- added new import formats: XGL/ZGL, M3 (experimental)
- new postprocessing steps: Debone
- vastly improved IFC (Industry Foundation Classes) support
- introduced API to query importer meta information (such as supported
format versions, full name, maintainer info).
- reworked Ogre XML import
- C-API now supports per-import properties
FIXES/HOUSEKEEPING:
- hundreds of bugfixes in all parts of the library
- unified naming and cleanup of public headers
- improved CMake build system
- templatized math library
- reduce dependency on boost.thread, only remaining spot
is synchronization for the C logging API
API COMPATIBILITY:
- renamed headers, export interface, C API properties and meta data
prevent compatibility with code written for 2.0, but in
most cases these can be easily resolved
- Note: 3.0 is not binary compatible with 2.0
2.0 (2010-11-21)
FEATURES:
- Add support for static Blender (*.blend) scenes
- Add support for Q3BSP scenes
- Add a windows-based OpenGL sample featuring texturing & basic materials
- Add an experimental progress feedback interface.
- Vastly improved performance (up to 500%, depending on mesh size and
spatial structure) in some expensive postprocessing steps
- AssimpView now uses a reworked layout which leaves more space
to the scene hierarchy window
- Add C# bindings ('Assimp.NET')
- Keep BSD-licensed and otherwise free test files in separate
folders (./test/models and ./test/models-nonbsd).
FIXES:
- Many Collada bugfixes, improve fault tolerance
- Fix possible crashes in the Obj loader
- Improve the Ogre XML loader
- OpenGL-sample now works with MinGW
- Fix Importer::FindLoader failing on uppercase file extensions
- Fix flawed path handling when locating external files
- Limit the maximum number of vertices, faces, face indices and
weights that Assimp is able to handle. This is to avoid
crashes due to overflowing counters.
- Updated XCode project files
- Further CMAKE build improvements
API CHANGES:
- Add data structures for vertex-based animations (These are not
currently used, however ...)
- Some Assimp::Importer methods are const now.
1.1 (2010-04-17)
This is the list of relevant changes from the 1.0 (r412) release to 1.1 (r700).
FEATURES:
- Vastly improved Collada support
- Add MS3D (Milkshape 3D) support
- Add support for Ogre XML static meshes
- Add experimental COB (TrueSpace) support
- Automatic test suite to quickly locate regressions
- D bindings (`dAssimp`)
- Python 2.n bindings (`PyAssimp`)
- Add basic support for Unicode input files (utf8, utf16 and utf32)
- Add further utilities to the `assimp` tool (xml/binary dumps, quick file stats)
- Switch to a CMAKE-based build system including an install target for unix'es
- Automatic evaluation of subdivision surfaces for some formats.
- Add `Importer::ReadFileFromMemory` and the corresponding C-API `aiReadFileFromMemory`
- Expose further math utilities via the C-API (i.e. `aiMultiplyMatrix4`)
- Move noboost files away from the public include directory
- Many, many bugfixes and improvements in existing loaders and postprocessing steps
- Documentation improved and clarified in many places.
- Add a sample on using Assimp in conjunction with OpenGL
- Distribution/packaging: comfortable SDK installer for Windows
- Distribution/packaging: improved release packages for other architectures
CRITICAL FIXES:
- Resolve problems with clashing heap managers, STL ABIs and runtime libraries (win32)
- Fix automatic detection of file type if no file extension is given
- Improved exception safety and robustness, prevent leaking of exceptions through the C interface
- Fix possible heap corruption due to material properties pulled in incorrectly
- Avoid leaking in certain error scenarios
- Fix 64 bit compatibility problems in some loaders (i.e. MDL)
BREAKING API CHANGES:
- None -
MINOR API BEHAVIOUR CHANGES:
- Change quaternion orientation to suit to the more common convention (-w).
- aiString is utf8 now. Not yet consistent, however.
+3961
View File
File diff suppressed because it is too large Load Diff
+174 -93
View File
@@ -1,6 +1,6 @@
# Open Asset Import Library (assimp)
# ----------------------------------------------------------------------
# Copyright (c) 2006-2024, assimp team
# Copyright (c) 2006-2026, assimp team
#
# All rights reserved.
#
@@ -34,28 +34,86 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#----------------------------------------------------------------------
# Enable Clang unsafe buffer usage warning for memory safety
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wunsafe-buffer-usage)
endif()
SET(CMAKE_POLICY_DEFAULT_CMP0012 NEW)
SET(CMAKE_POLICY_DEFAULT_CMP0074 NEW)
SET(CMAKE_POLICY_DEFAULT_CMP0092 NEW)
CMAKE_MINIMUM_REQUIRED( VERSION 3.22 )
# Disabled importers: m3d for 5.1 or later
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_M3D_IMPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_M3D_EXPORTER)
#================================================================================#
# Model formats not enabled by default
#
# 3rd party projects may not adhere to strict standards enforced by assimp,
# in which case those formats must be opt-in; otherwise the 3rd party code
# would fail assimp CI checks
#================================================================================#
# M3D format import support (assimp integration no longer supported by M3D format author)
# User may override these in their CMake script to provide M3D import/export support
# (M3D importer/exporter was disabled for assimp release 5.1 or later)
OPTION(ASSIMP_BUILD_M3D_IMPORTER "Enable M3D file import" off)
OPTION(ASSIMP_BUILD_M3D_EXPORTER "Enable M3D file export" off)
# Experimental USD importer: disabled, need to opt-in
# Note: assimp github PR automatic checks will fail the PR due to compiler warnings in
# the external, 3rd party tinyusdz code which isn't technically part of the PR since it's
# auto-cloned during build; so MUST disable the feature or the PR will be rejected
OPTION(ASSIMP_BUILD_USD_IMPORTER "Enable USD file import" off)
OPTION(ASSIMP_BUILD_USD_VERBOSE_LOGS "Enable verbose USD import debug logging" off)
# VRML (.wrl/.x3dv) file import support by leveraging X3D importer and 3rd party file
# format converter to convert .wrl/.x3dv files to X3D-compatible .xml
# (Need to make this opt-in because 3rd party code triggers lots of CI code quality warnings)
OPTION(ASSIMP_BUILD_VRML_IMPORTER "Enable VRML (.wrl/.x3dv) file import" off)
#--------------------------------------------------------------------------------#
# Internal impl for optional model formats
#--------------------------------------------------------------------------------#
# Internal/private M3D logic
if (NOT ASSIMP_BUILD_M3D_IMPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_M3D_IMPORTER)
endif () # if (not ASSIMP_BUILD_M3D_IMPORTER)
if (NOT ASSIMP_BUILD_M3D_EXPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_M3D_EXPORTER)
endif () # if (not ASSIMP_BUILD_M3D_EXPORTER)
# Internal/private VRML logic
if (NOT ASSIMP_BUILD_VRML_IMPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_VRML_IMPORTER)
endif () # if (not ASSIMP_BUILD_VRML_IMPORTER)
#================================================================================#
option(ASSIMP_BUILD_USE_CCACHE "Use ccache to speed up compilation." on)
IF(ASSIMP_BUILD_USE_CCACHE)
find_program(CCACHE_PATH ccache)
IF (CCACHE_PATH)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ${CCACHE_PATH})
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ${CCACHE_PATH})
ENDIF()
ENDIF()
# Toggles the use of the hunter package manager
option(ASSIMP_HUNTER_ENABLED "Enable Hunter package manager support" OFF)
IF(ASSIMP_HUNTER_ENABLED)
include("cmake-modules/HunterGate.cmake")
HunterGate(
URL "https://github.com/cpp-pm/hunter/archive/v0.25.5.tar.gz"
SHA1 "a20151e4c0740ee7d0f9994476856d813cdead29"
URL "https://github.com/cpp-pm/hunter/archive/v0.26.10.tar.gz"
SHA1 "3d904b93ba684f0e671a2d44969a1a127abe3e66"
)
add_definitions(-DASSIMP_USE_HUNTER)
ADD_DEFINITIONS(-DASSIMP_USE_HUNTER)
ENDIF()
PROJECT(Assimp VERSION 5.4.1)
PROJECT(Assimp VERSION 6.0.5
LANGUAGES C CXX
DESCRIPTION "Open Asset Import Library (Assimp) is a library to import various well-known 3D model formats in a uniform manner."
)
# All supported options ###############################################
@@ -95,6 +153,10 @@ OPTION ( ASSIMP_BUILD_TESTS
"If the test suite for Assimp is built in addition to the library."
ON
)
OPTION ( ASSIMP_INSTALL_TESTS
"If the test suite for Assimp should be installed."
OFF
)
OPTION ( ASSIMP_COVERALLS
"Enable this to measure test coverage."
OFF
@@ -147,7 +209,7 @@ IF (WIN32)
IF(MSVC)
OPTION( ASSIMP_INSTALL_PDB
"Install MSVC debug files."
"Create MSVC debug symbol files and add to Install target."
ON )
IF(NOT (MSVC_VERSION LESS 1900))
# Multibyte character set has been deprecated since at least MSVC2015 (possibly earlier)
@@ -197,7 +259,7 @@ SET (ASSIMP_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
SET (ASSIMP_VERSION_MINOR ${PROJECT_VERSION_MINOR})
SET (ASSIMP_VERSION_PATCH ${PROJECT_VERSION_PATCH})
SET (ASSIMP_VERSION ${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH})
SET (ASSIMP_SOVERSION 5)
SET (ASSIMP_SOVERSION 6)
SET( ASSIMP_PACKAGE_VERSION "0" CACHE STRING "the package-specific version used for uploading the sources" )
set(CMAKE_CXX_STANDARD 17)
@@ -257,13 +319,24 @@ IF( UNIX )
ENDIF()
ENDIF()
IF(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND WIN32)
ADD_DEFINITIONS( -D_SCL_SECURE_NO_WARNINGS )
ADD_DEFINITIONS( -D_CRT_SECURE_NO_WARNINGS )
ENDIF()
IF( MSVC OR "${CMAKE_CXX_SIMULATE_ID}" MATCHES "MSVC") # clang with MSVC ABI
ADD_DEFINITIONS( -D_SCL_SECURE_NO_WARNINGS )
ADD_DEFINITIONS( -D_CRT_SECURE_NO_WARNINGS )
endif ()
# Grouped compiler settings ########################################
IF ((CMAKE_C_COMPILER_ID MATCHES "GNU") AND NOT MINGW AND NOT HAIKU)
IF(NOT ASSIMP_HUNTER_ENABLED)
SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
ENDIF()
IF(CMAKE_CXX_COMPILER_VERSION GREATER_EQUAL 13)
IF(CMAKE_CXX_COMPILER_VERSION GREATER_EQUAL 13 AND CMAKE_CXX_COMPILER_ID MATCHES "GNU")
MESSAGE(STATUS "GCC13 detected disabling \"-Wdangling-reference\" in Cpp files as it appears to be a false positive")
ADD_COMPILE_OPTIONS("$<$<COMPILE_LANGUAGE:CXX>:-Wno-dangling-reference>")
ENDIF()
@@ -284,22 +357,31 @@ ELSEIF(MSVC)
ELSE() # msvc
ADD_COMPILE_OPTIONS(/MP /bigobj)
ENDIF()
# disable "elements of array '' will be default initialized" warning on MSVC2013
IF(MSVC12)
ADD_COMPILE_OPTIONS(/wd4351)
ADD_COMPILE_OPTIONS(/wd4351)
ENDIF()
# supress warning for double to float conversion if Double precision is activated
ADD_COMPILE_OPTIONS(/wd4244)
ADD_COMPILE_OPTIONS(/wd4244)
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /D_DEBUG /Zi /Od")
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
SET(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG:FULL /PDBALTPATH:%_PDB% /OPT:REF /OPT:ICF")
# Allow user to disable PDBs
if(ASSIMP_INSTALL_PDB)
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi")
SET(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG:FULL /PDBALTPATH:%_PDB% /OPT:REF /OPT:ICF")
elseif((GENERATOR_IS_MULTI_CONFIG) OR (CMAKE_BUILD_TYPE MATCHES Release))
message("-- MSVC PDB generation disabled. Release binary will not be debuggable.")
endif()
if(NOT CMAKE_CXX_FLAGS MATCHES "/utf-8")
# Source code is encoded in UTF-8
ADD_COMPILE_OPTIONS(/source-charset:utf-8)
endif()
ELSEIF (CMAKE_CXX_COMPILER_ID MATCHES "Clang" )
IF(NOT ASSIMP_HUNTER_ENABLED)
SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
ENDIF()
SET(CMAKE_CXX_FLAGS "-fvisibility=hidden -fno-strict-aliasing -Wall -Wno-long-long ${CMAKE_CXX_FLAGS}" )
SET(CMAKE_C_FLAGS "-fno-strict-aliasing ${CMAKE_C_FLAGS}")
SET(CMAKE_CXX_FLAGS "-Wno-deprecated-non-prototype -fvisibility=hidden -fno-strict-aliasing -Wall -Wno-long-long ${CMAKE_CXX_FLAGS}" )
SET(CMAKE_C_FLAGS "-Wno-deprecated-non-prototype -fno-strict-aliasing ${CMAKE_C_FLAGS}")
ELSEIF( MINGW )
IF (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0)
message(FATAL_ERROR "MinGW is too old to be supported. Please update MinGW and try again.")
@@ -330,7 +412,7 @@ ENDIF()
IF (ASSIMP_COVERALLS)
MESSAGE(STATUS "Coveralls enabled")
INCLUDE(Coveralls)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
@@ -338,7 +420,7 @@ ENDIF()
IF (ASSIMP_ASAN)
MESSAGE(STATUS "AddressSanitizer enabled")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address")
ENDIF()
@@ -422,20 +504,20 @@ ENDIF()
set(GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated")
IF(ASSIMP_HUNTER_ENABLED)
set(CONFIG_INSTALL_DIR "lib/cmake/${PROJECT_NAME}")
set(CMAKE_CONFIG_TEMPLATE_FILE "cmake-modules/assimp-hunter-config.cmake.in")
set(NAMESPACE "${PROJECT_NAME}::")
set(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets")
set(VERSION_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}ConfigVersion.cmake")
set(PROJECT_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}Config.cmake")
SET(CONFIG_INSTALL_DIR "lib/cmake/${PROJECT_NAME}")
SET(CMAKE_CONFIG_TEMPLATE_FILE "cmake-modules/assimp-hunter-config.cmake.in")
SET(NAMESPACE "${PROJECT_NAME}::")
SET(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets")
SET(VERSION_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}ConfigVersion.cmake")
SET(PROJECT_CONFIG "${GENERATED_DIR}/${PROJECT_NAME}Config.cmake")
ELSE()
set(CONFIG_INSTALL_DIR "${ASSIMP_LIB_INSTALL_DIR}/cmake/assimp-${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}")
set(CMAKE_CONFIG_TEMPLATE_FILE "cmake-modules/assimp-plain-config.cmake.in")
SET(CONFIG_INSTALL_DIR "${ASSIMP_LIB_INSTALL_DIR}/cmake/assimp-${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}")
SET(CMAKE_CONFIG_TEMPLATE_FILE "cmake-modules/assimp-plain-config.cmake.in")
string(TOLOWER ${PROJECT_NAME} PROJECT_NAME_LOWERCASE)
set(NAMESPACE "${PROJECT_NAME_LOWERCASE}::")
set(TARGETS_EXPORT_NAME "${PROJECT_NAME_LOWERCASE}Targets")
set(VERSION_CONFIG "${GENERATED_DIR}/${PROJECT_NAME_LOWERCASE}ConfigVersion.cmake")
set(PROJECT_CONFIG "${GENERATED_DIR}/${PROJECT_NAME_LOWERCASE}Config.cmake")
SET(NAMESPACE "${PROJECT_NAME_LOWERCASE}::")
SET(TARGETS_EXPORT_NAME "${PROJECT_NAME_LOWERCASE}Targets")
SET(VERSION_CONFIG "${GENERATED_DIR}/${PROJECT_NAME_LOWERCASE}ConfigVersion.cmake")
SET(PROJECT_CONFIG "${GENERATED_DIR}/${PROJECT_NAME_LOWERCASE}Config.cmake")
ENDIF()
set(INCLUDE_INSTALL_DIR "include")
@@ -452,20 +534,20 @@ configure_package_config_file(
INSTALL_DESTINATION "${CONFIG_INSTALL_DIR}"
)
if(ASSIMP_INSTALL)
install(
IF(ASSIMP_INSTALL)
INSTALL(
FILES "${PROJECT_CONFIG}" "${VERSION_CONFIG}"
DESTINATION "${CONFIG_INSTALL_DIR}"
COMPONENT ${LIBASSIMP-DEV_COMPONENT}
)
install(
INSTALL(
EXPORT "${TARGETS_EXPORT_NAME}"
NAMESPACE "${NAMESPACE}"
DESTINATION "${CONFIG_INSTALL_DIR}"
COMPONENT ${LIBASSIMP-DEV_COMPONENT}
)
endif()
ENDIF()
IF( ASSIMP_BUILD_DOCS )
ADD_SUBDIRECTORY(doc)
@@ -478,9 +560,9 @@ IF(ASSIMP_HUNTER_ENABLED)
find_package(ZLIB CONFIG REQUIRED)
add_definitions(-DASSIMP_BUILD_NO_OWN_ZLIB)
set(ZLIB_FOUND TRUE)
set(ZLIB_LIBRARIES ZLIB::zlib)
set(ASSIMP_BUILD_MINIZIP TRUE)
SET(ZLIB_FOUND TRUE)
SET(ZLIB_LIBRARIES ZLIB::zlib)
SET(ASSIMP_BUILD_MINIZIP TRUE)
ELSE()
# If the zlib is already found outside, add an export in case assimpTargets can't find it.
IF( ZLIB_FOUND AND ASSIMP_INSTALL)
@@ -507,8 +589,8 @@ ELSE()
# https://github.com/madler/zlib/issues/41#issuecomment-125848075
# Also prevents these options from "polluting" the cmake options if assimp is being
# included as a submodule.
set( ASM686 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE )
set( AMD64 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE )
SET(ASM686 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE )
SET(AMD64 FALSE CACHE INTERNAL "Override ZLIB flag to turn off assembly" FORCE )
# compile from sources
ADD_SUBDIRECTORY(contrib/zlib)
@@ -519,7 +601,7 @@ ELSE()
SET(ASSIMP_BUILD_MINIZIP 1)
ELSE()
ADD_DEFINITIONS(-DASSIMP_BUILD_NO_OWN_ZLIB)
SET(ZLIB_LIBRARIES_LINKED -lz)
SET(ZLIB_LIBRARIES_LINKED -l${ZLIB_LIBRARIES})
ENDIF()
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR})
ENDIF()
@@ -531,7 +613,7 @@ IF( NOT IOS )
ELSE ()
IF( NOT BUILD_SHARED_LIBS )
IF( NOT ASSIMP_BUILD_MINIZIP )
use_pkgconfig(UNZIP minizip)
USE_PKGCONFIG(UNZIP minizip)
ENDIF()
ENDIF ()
ENDIF ()
@@ -614,48 +696,48 @@ IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
"${C4D_LIB_BASE_PATH}/release/libcinewarelib.a"
"${C4D_LIB_BASE_PATH}/release/libjpeglib.a"
)
ELSE ()
ELSE()
MESSAGE( FATAL_ERROR
"C4D is currently only available on Windows and macOS with Cineware SDK installed in contrib/Cineware"
)
ENDIF ()
ENDIF()
ELSE ()
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER )
ENDIF ()
if(ASSIMP_BUILD_DRACO_STATIC)
set(ASSIMP_BUILD_DRACO ON)
endif()
IF(ASSIMP_BUILD_DRACO_STATIC)
SET(ASSIMP_BUILD_DRACO ON)
ENDIF()
# Draco requires cmake 3.12
IF (DEFINED CMAKE_VERSION AND "${CMAKE_VERSION}" VERSION_LESS "3.12")
message(NOTICE "draco requires cmake 3.12 or newer, cmake is ${CMAKE_VERSION} . Draco is disabled")
MESSAGE(NOTICE "draco requires cmake 3.12 or newer, cmake is ${CMAKE_VERSION} . Draco is disabled")
SET ( ASSIMP_BUILD_DRACO OFF CACHE BOOL "Disabled: Draco requires newer cmake" FORCE )
ELSE()
OPTION ( ASSIMP_BUILD_DRACO "If the Draco libraries are to be built. Primarily for glTF" OFF )
IF ( ASSIMP_BUILD_DRACO )
# Primarily for glTF v2
# Enable Draco glTF feature set
set(DRACO_GLTF ON CACHE BOOL "" FORCE)
SET(DRACO_GLTF_BITSTREAM ON CACHE BOOL "" FORCE)
# Disable unnecessary or omitted components
set(DRACO_JS_GLUE OFF CACHE BOOL "" FORCE)
set(DRACO_WASM OFF CACHE BOOL "" FORCE)
set(DRACO_MAYA_PLUGIN OFF CACHE BOOL "" FORCE)
set(DRACO_UNITY_PLUGIN OFF CACHE BOOL "" FORCE)
set(DRACO_TESTS OFF CACHE BOOL "" FORCE)
SET(DRACO_JS_GLUE OFF CACHE BOOL "" FORCE)
SET(DRACO_WASM OFF CACHE BOOL "" FORCE)
SET(DRACO_MAYA_PLUGIN OFF CACHE BOOL "" FORCE)
SET(DRACO_UNITY_PLUGIN OFF CACHE BOOL "" FORCE)
SET(DRACO_TESTS OFF CACHE BOOL "" FORCE)
IF(ASSIMP_HUNTER_ENABLED)
hunter_add_package(draco)
find_package(draco CONFIG REQUIRED)
set(draco_LIBRARIES draco::draco)
SET(draco_LIBRARIES draco::draco)
ELSE()
# Draco 1.4.1 has many warnings and will not build with /WX or -Werror
# See https://github.com/google/draco/issues/672
# and https://github.com/google/draco/issues/673
IF(MSVC)
set(DRACO_CXX_FLAGS "/W0")
SET(DRACO_CXX_FLAGS "/W0")
ELSE()
list(APPEND DRACO_CXX_FLAGS
LIST(APPEND DRACO_CXX_FLAGS
"-Wno-bool-compare"
"-Wno-comment"
"-Wno-maybe-uninitialized"
@@ -663,30 +745,30 @@ ELSE()
"-Wno-unused-local-typedefs"
)
if(NOT ASSIMP_BUILD_DRACO_STATIC)
IF(NOT ASSIMP_BUILD_DRACO_STATIC)
# Draco 1.4.1 does not explicitly export any symbols under GCC/clang
list(APPEND DRACO_CXX_FLAGS
LIST(APPEND DRACO_CXX_FLAGS
"-fvisibility=default"
)
endif()
ENDIF()
ENDIF()
# Don't build or install all of Draco by default
ADD_SUBDIRECTORY( "contrib/draco" EXCLUDE_FROM_ALL )
if(ASSIMP_BUILD_DRACO_STATIC)
IF(ASSIMP_BUILD_DRACO_STATIC)
set_property(DIRECTORY "contrib/draco" PROPERTY BUILD_SHARED_LIBS OFF)
endif()
ENDIF()
if(MSVC OR WIN32)
set(draco_LIBRARIES "draco")
else()
if(ASSIMP_BUILD_DRACO_STATIC)
set(draco_LIBRARIES "draco_static")
else()
set(draco_LIBRARIES "draco_shared")
endif()
endif()
IF(MSVC OR WIN32)
SET(draco_LIBRARIES "draco")
ELSE()
IF(ASSIMP_BUILD_DRACO_STATIC)
SET(draco_LIBRARIES "draco_static")
ELSE()
SET(draco_LIBRARIES "draco_shared")
ENDIF()
ENDIF()
# Don't build the draco command-line tools by default
set_target_properties(draco_encoder draco_decoder PROPERTIES
@@ -704,10 +786,10 @@ ELSE()
TARGET_USE_COMMON_OUTPUT_DIRECTORY(draco_encoder)
TARGET_USE_COMMON_OUTPUT_DIRECTORY(draco_decoder)
set(draco_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/contrib/draco/src")
SET(draco_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/contrib/draco/src")
# This is probably wrong
if (ASSIMP_INSTALL)
IF (ASSIMP_INSTALL)
INSTALL( TARGETS ${draco_LIBRARIES}
EXPORT "${TARGETS_EXPORT_NAME}"
LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR}
@@ -717,7 +799,7 @@ ELSE()
COMPONENT ${LIBASSIMP_COMPONENT}
INCLUDES DESTINATION include
)
endif()
ENDIF()
ENDIF()
ENDIF()
ENDIF()
@@ -850,24 +932,23 @@ if(WIN32)
IF(MSVC12 OR MSVC14 OR MSVC15 )
ADD_CUSTOM_TARGET(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM)
IF(CMAKE_GENERATOR MATCHES "^Visual Studio")
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ELSE()
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
ADD_CUSTOM_COMMAND(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ENDIF()
ENDIF()
ENDIF ()
+53
View File
@@ -0,0 +1,53 @@
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3,
"minor": 20,
"patch": 0
},
"configurePresets": [
{
"name": "assimp",
"binaryDir": "${sourceDir}",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"ASSIMP_BUILD_ASSIMP_TOOLS": "OFF"
}
},
{
"name": "assimp_static",
"binaryDir": "${sourceDir}",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"BUILD_SHARED_LIBS": "OFF",
"ASSIMP_BUILD_ASSIMP_TOOLS": "OFF",
"ASSIMP_DOUBLE_PRECISION": "ON"
}
},
{
"name": "assimp_double_precision",
"binaryDir": "${sourceDir}",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"ASSIMP_BUILD_ASSIMP_TOOLS": "OFF",
"ASSIMP_DOUBLE_PRECISION": "ON"
}
},
{
"name": "assimp_with_tools",
"binaryDir": "${sourceDir}",
"cacheVariables": {
"ASSIMP_BUILD_ASSIMP_TOOLS": "ON"
}
},
{
"name": "assimp_all",
"binaryDir": "${sourceDir}",
"cacheVariables": {
"ASSIMP_BUILD_ASSIMP_TOOLS": "ON",
"ASSIMP_BUILD_SAMPLES": "ON",
"ASSIMP_BUILD_DOCS": "ON"
}
}
]
}
+2 -2
View File
@@ -60,7 +60,7 @@ The GUY who performed some of the CSM mocaps.
Contributed fixes for the documentation and the doxygen markup
- Zhao Lei
Contributed several bugfixes fixing memory leaks and improving float parsing
Contributed several bugfixes fixing memory leaks and improving float parsing
- sueastside
Updated PyAssimp to the latest Assimp data structures and provided a script to keep the Python binding up-to-date.
@@ -129,7 +129,7 @@ Contributed a patch to fix the VertexTriangleAdjacency postprocessing step.
Contributed the Debian build fixes ( architecture macro ).
- gellule
Several LWO and LWS fixes (pivoting).
Several LWO and LWS fixes (pivoting).
- Marcel Metz
GCC/Linux fixes for the SimpleOpenGL sample.
+8 -13
View File
@@ -1,22 +1,17 @@
FROM ubuntu:22.04
FROM gcc:1.5.1.0
RUN apt-get update && apt-get install -y ninja-build \
git cmake build-essential software-properties-common
RUN apt-get update \
apt-get install --no-install-recommends -y ninja-build cmake zlib1g-dev
RUN add-apt-repository ppa:ubuntu-toolchain-r/test && apt-get update
WORKDIR /app
WORKDIR /opt
RUN apt install zlib1g-dev
COPY . .
# Build Assimp
RUN git clone https://github.com/assimp/assimp.git /opt/assimp
WORKDIR /opt/assimp
RUN git checkout master \
&& mkdir build && cd build && \
RUN mkdir build && cd build && \
cmake -G 'Ninja' \
-DCMAKE_BUILD_TYPE=Release \
-DASSIMP_BUILD_ASSIMP_TOOLS=ON \
.. && \
ninja -j4 && ninja install
CMD ["/app/build/bin/unit"]
+4 -4
View File
@@ -1,17 +1,17 @@
========================================================================
Open Asset Import Library (assimp) INSTALL
Open Asset Import Library (assimp) INSTALL
========================================================================
------------------------------
Getting the documentation
------------------------------
A regularly-updated copy is available at
A regularly-updated copy is available at
https://assimp-docs.readthedocs.io/en/latest/
------------------------------
Building Assimp
Building Assimp
------------------------------
Just check the build-instructions which you can find here: https://github.com/assimp/assimp/blob/master/Build.md
+1 -1
View File
@@ -1,6 +1,6 @@
Open Asset Import Library (assimp)
Copyright (c) 2006-2021, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
+66 -51
View File
@@ -1,86 +1,104 @@
Open Asset Import Library (assimp)
==================================
Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
Open Asset Import Library is a library that loads various 3D file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
### Current project status ###
[![Financial Contributors on Open Collective](https://opencollective.com/assimp/all/badge.svg?label=financial+contributors)](https://opencollective.com/assimp)
## Current project status
![C/C++ CI](https://github.com/assimp/assimp/workflows/C/C++%20CI/badge.svg)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/9973693b7bdd4543b07084d5d9cf4745)](https://www.codacy.com/gh/assimp/assimp/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=assimp/assimp&amp;utm_campaign=Badge_Grade)
[![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=assimp_assimp&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=assimp_assimp)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/assimp/assimp.svg)](http://isitmaintained.com/project/assimp/assimp "Average time to resolve an issue")
[![Percentage of issues still open](http://isitmaintained.com/badge/open/assimp/assimp.svg)](http://isitmaintained.com/project/assimp/assimp "Percentage of issues still open")
[![Gurubase](https://img.shields.io/badge/Gurubase-Ask%20assimp%20Guru-006BFF)](https://gurubase.io/g/assimp)
[![Financial Contributors on Open Collective](https://opencollective.com/assimp/all/badge.svg?label=financial+contributors)](https://opencollective.com/assimp)
<br>
## Star History
APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS.
[![Star History Chart](https://api.star-history.com/chart?repos=assimp/assimp&type=date&legend=top-left)](https://www.star-history.com/?repos=assimp%2Fassimp&type=date&legend=top-left)
APIs are provided for C and C++. Various bindings exist to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS.
Additionally, assimp features various __mesh post-processing tools__: normals and tangent space generation, triangulation, vertex cache locality optimization, removal of degenerate primitives and duplicate vertices, sorting by primitive type, merging of redundant materials and many more.
### Documentation ###
Read [our latest documentation](https://assimp-docs.readthedocs.io/en/latest/).
## Project activity
![Alt](https://repobeats.axiom.co/api/embed/997f84e5f9fcf772da1e687f3a4f3a8afdbf4cf0.svg "Repobeats analytics image")
### Pre-built binaries ###
Download binaries from [our Itchi Projectspace](https://kimkulling.itch.io/the-asset-importer-lib).
## Developer quickstart
```bash
git clone https://github.com/assimp/assimp
cd assimp
cmake -G Ninja -DASSIMP_BUILD_TESTS=off -DASSIMP_INSTALL=off -S . -B build
cd build
ninja
```
### Test data ###
Clone [our model database](https://github.com/assimp/assimp-mdb).
## Documentation
Read [our latest documentation](https://the-asset-importer-lib-documentation.readthedocs.io/en/latest/).
### Communities ###
## Pre-built binaries
Download binaries from [our Itch Projectspace](https://kimkulling.itch.io/the-asset-importer-lib).
## Test data
Clone [our model database for testing purposes](https://github.com/assimp/assimp-mdb).
## Communities
- Ask questions at [the Assimp Discussion Board](https://github.com/assimp/assimp/discussions).
- Find us on [discord](https://discord.gg/kKazXMXDy2)
- Ask [the Assimp community on Reddit](https://www.reddit.com/r/Assimp/).
- Ask on [StackOverflow with the assimp-tag](http://stackoverflow.com/questions/tagged/assimp?sort=newest).
- Nothing has worked? File a question or an issue-report at [The Assimp-Issue Tracker](https://github.com/assimp/assimp/issues)
- Ask on [StackOverflow with the assimp-tag](http://stackoverflow.com/questions/tagged/assimp?sort=newest).
- Nothing has worked? File a question or an issue report at [The Assimp-Issue Tracker](https://github.com/assimp/assimp/issues)
And we also have a Gitter-channel:Gitter [![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)<br>
#### Supported file formats ####
## Supported file formats
See [the complete list of supported formats](https://github.com/assimp/assimp/blob/master/doc/Fileformats.md).
### Building ###
## Building
Start by reading [our build instructions](https://github.com/assimp/assimp/blob/master/Build.md). We are available in vcpkg, and our build system is CMake; if you used CMake before there is a good chance you know what to do.
### Ports ###
## Ports
* [Android](port/AndroidJNI/README.md)
* [Python](port/PyAssimp/README.md)
* [.NET](https://bitbucket.org/Starnick/assimpnet/src/master/)
* [.NET](https://github.com/Saalvage/AssimpNetter)
* [Pascal](port/AssimpPascal/Readme.md)
* [Javascript (Alpha)](https://github.com/makc/assimp2json)
* [Javascript/Node.js Interface](https://github.com/kovacsv/assimpjs)
* [Unity 3d Plugin](https://ricardoreis.net/trilib-2/)
* [Unreal Engine Plugin](https://github.com/irajsb/UE4_Assimp/)
* [JVM](https://github.com/kotlin-graphics/assimp) Full jvm port (current [status](https://github.com/kotlin-graphics/assimp/wiki/Status))
* [JVM](https://github.com/kotlin-graphics/assimp) Full JVM port (current [status](https://github.com/kotlin-graphics/assimp/wiki/Status))
* [HAXE-Port](https://github.com/longde123/assimp-haxe) The Assimp-HAXE-port.
* [Rust](https://github.com/jkvargas/russimp)
### Other tools ###
[open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities.
## Other tools
[Qt5-ModelViewer](https://github.com/sharjith/ModelViewer-Qt5) is a powerful viewer based on Qt5 and Assimp's import and export abilities.<br>
[Assimp-Viewer](https://github.com/assimp/assimp_view) is an experimental implementation for an Asset-Viewer based on ImGUI and Assimp (experimental).
#### Repository structure ####
### Repository structure
Open Asset Import Library is implemented in C++. The directory structure looks like this:
/code Source code
/contrib Third-party libraries
/doc Documentation (doxysource and pre-compiled docs)
/fuzz Contains the test code for the Google Fuzzer project
/include Public header C and C++ header files
/scripts Scripts are used to generate the loading code for some formats
/port Ports to other languages and scripts to maintain those.
/test Unit- and regression tests, test suite of models
/tools Tools (old assimp viewer, command line `assimp`)
/samples A small number of samples to illustrate possible use cases for Assimp
```txt
code Source code
├── AssetLib/ The asset-importer and exporter lib
├── CApi/ C-API files
├── Common/ Common code used from all modules
├── Geometry/ Geometry utilities
├── Material/ Common materials
├── Pbrt/ Physical based materials
├── PostProcessing/ Post-processing steps
├── res Resouce files
contrib Third-party libraries
doc Documentation (Doxygen source and pre-compiled docs)
fuzz Contains the test code for the Google Fuzzer project
include Public header C and C++ header files
scripts Scripts are used to generate the loading code for some formats
port Ports to other languages and scripts to maintain those.
test Unit- and regression tests, test suite of models
├── headercheck Implements headerchecks
├── models-nonbsd Non-BSP licensed headers
├── models BSP-licensed models
├── unit Unit tests
tools Tools (old assimp viewer, command line `assimp`)
samples Small number of samples to illustrate possible use cases for Assimp
```
## Contributing
The source code is organized in the following way:
code/Common The base implementation for importers and the infrastructure
code/CApi Special implementations which are only used for the C-API
code/Geometry A collection of geometry tools
code/Material The material system
code/PBR An exporter for physical-based models
code/PostProcessing The post-processing steps
code/AssetLib/<FormatName> Implementation for import and export of the format
### Contributing ###
Contributions to assimp are highly appreciated. The easiest way to get involved is to submit
We would greatly appreciate for you to contribute to assimp. The easiest way to get involved is to submit
a pull request with your changes against the main repository's `master` branch.
## Contributors
@@ -102,16 +120,13 @@ Become a financial contributor and help us sustain our community. [[Contribute](
#### Organizations
Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/assimp/contribute)]
You can support the project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/assimp/contribute)]
<a href="https://opencollective.com/assimp/organization/0/website"><img src="https://opencollective.com/assimp/organization/0/avatar.svg"></a>
### License ###
## License ###
Our license is based on the modified, __3-clause BSD__-License.
An _informal_ summary is: do whatever you want, but include Assimp's license text with your product -
and don't sue us if our code doesn't work. Note that, unlike LGPLed code, you may link statically to Assimp.
For the legal details, see the `LICENSE` file.
### Why this name ###
Sorry, we're germans :-), no English native speakers ...
+4 -5
View File
@@ -2,15 +2,14 @@
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
The current version of Assimp that's being supported with security updates:
| Version | Supported |
| ------- | ------------------ |
| 5.2.4 | :white_check_mark: |
| 6.0.5 | :white_check_mark: |
## Reporting a Vulnerability
If you have found any security vulnerability you can contact us via
kim.kulling@googlemail.com
If you have found any security vulnerability you can contact us via
kim.kulling@assimp.org
+2 -3
View File
@@ -6,7 +6,7 @@
# Creates source debian files and manages library dependencies
#
# Features:
#
#
# - Automatically generates symbols and run-time dependencies from the build dependencies
# - Custom copy of source directory via CPACK_DEBIAN_PACKAGE_SOURCE_COPY
# - Simultaneous output of multiple debian source packages for each distribution
@@ -114,7 +114,6 @@ foreach(RELEASE ${CPACK_DEBIAN_DISTRIBUTION_RELEASES})
endif( CPACK_DEBIAN_BUILD_DEPENDS_${DISTRIBUTION_NAME_UPPER} )
endif( CPACK_DEBIAN_BUILD_DEPENDS_${DISTRIBUTION_NAME_UPPER}_${RELEASE_UPPER} )
file(APPEND ${DEBIAN_CONTROL} "\n"
"Standards-Version: 3.8.4\n"
"Homepage: ${CPACK_PACKAGE_VENDOR}\n"
@@ -173,7 +172,7 @@ foreach(RELEASE ${CPACK_DEBIAN_DISTRIBUTION_RELEASES})
endforeach(DEP ${CPACK_DEBIAN_PACKAGE_SUGGESTS})
endif( CPACK_DEBIAN_PACKAGE_SUGGESTS_${DISTRIBUTION_NAME_UPPER} )
endif( CPACK_DEBIAN_PACKAGE_SUGGESTS_${DISTRIBUTION_NAME_UPPER}_${RELEASE_UPPER} )
file(APPEND ${DEBIAN_CONTROL} "\n"
"Description: ${CPACK_PACKAGE_DISPLAY_NAME} ${CPACK_PACKAGE_DESCRIPTION_SUMMARY}\n"
"${DEB_LONG_DESCRIPTION}"
-72
View File
@@ -1,72 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindDevIL
# ---------
#
#
#
# This module locates the developer's image library.
# http://openil.sourceforge.net/
#
# This module sets:
#
# ::
#
# IL_LIBRARIES - the name of the IL library. These include the full path to
# the core DevIL library. This one has to be linked into the
# application.
# ILU_LIBRARIES - the name of the ILU library. Again, the full path. This
# library is for filters and effects, not actual loading. It
# doesn't have to be linked if the functionality it provides
# is not used.
# ILUT_LIBRARIES - the name of the ILUT library. Full path. This part of the
# library interfaces with OpenGL. It is not strictly needed
# in applications.
# IL_INCLUDE_DIR - where to find the il.h, ilu.h and ilut.h files.
# IL_FOUND - this is set to TRUE if all the above variables were set.
# This will be set to false if ILU or ILUT are not found,
# even if they are not needed. In most systems, if one
# library is found all the others are as well. That's the
# way the DevIL developers release it.
# TODO: Add version support.
# Tested under Linux and Windows (MSVC)
#include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
include(FindPackageHandleStandardArgs)
find_path(IL_INCLUDE_DIR il.h
PATH_SUFFIXES include IL
DOC "The path to the directory that contains il.h"
)
#message("IL_INCLUDE_DIR is ${IL_INCLUDE_DIR}")
find_library(IL_LIBRARIES
NAMES IL DEVIL
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the base il library."
)
#message("IL_LIBRARIES is ${IL_LIBRARIES}")
find_library(ILUT_LIBRARIES
NAMES ILUT
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the il (system?) utility library."
)
#message("ILUT_LIBRARIES is ${ILUT_LIBRARIES}")
find_library(ILU_LIBRARIES
NAMES ILU
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the il utility library."
)
#message("ILU_LIBRARIES is ${ILU_LIBRARIES}")
FIND_PACKAGE_HANDLE_STANDARD_ARGS(IL DEFAULT_MSG
IL_LIBRARIES IL_INCLUDE_DIR)
+5 -5
View File
@@ -26,7 +26,7 @@ if(WIN32) # The only platform it makes sense to check for DirectX SDK
getenv_path(DIRECTX_BASE)
# construct search paths
set(DirectX_PREFIX_PATH
set(DirectX_PREFIX_PATH
"${DXSDK_DIR}" "${ENV_DXSDK_DIR}"
"${DIRECTX_HOME}" "${ENV_DIRECTX_HOME}"
"${DIRECTX_ROOT}" "${ENV_DIRECTX_ROOT}"
@@ -66,7 +66,7 @@ if(WIN32) # The only platform it makes sense to check for DirectX SDK
find_library(DirectX_D3DCOMPILER_LIBRARY NAMES d3dcompiler HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
findpkg_finish(DirectX)
set(DirectX_LIBRARIES ${DirectX_LIBRARIES}
set(DirectX_LIBRARIES ${DirectX_LIBRARIES}
${DirectX_D3DX9_LIBRARY}
${DirectX_DXERR_LIBRARY}
${DirectX_DXGUID_LIBRARY}
@@ -82,7 +82,7 @@ if(WIN32) # The only platform it makes sense to check for DirectX SDK
get_filename_component(DirectX_LIBRARY_DIR "${DirectX_LIBRARY}" PATH)
message(STATUS "DX lib dir: ${DirectX_LIBRARY_DIR}")
find_library(DirectX_D3D11_LIBRARY NAMES d3d11 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
find_library(DirectX_D3DX11_LIBRARY NAMES d3dx11 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
find_library(DirectX_D3DX11_LIBRARY NAMES d3dx11 HINTS ${DirectX_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX_LIBPATH_SUFFIX})
if (DirectX_D3D11_INCLUDE_DIR AND DirectX_D3D11_LIBRARY)
set(DirectX_D3D11_FOUND TRUE)
set(DirectX_D3D11_INCLUDE_DIR ${DirectX_D3D11_INCLUDE_DIR})
@@ -92,8 +92,8 @@ if(WIN32) # The only platform it makes sense to check for DirectX SDK
${DirectX_DXGI_LIBRARY}
${DirectX_DXERR_LIBRARY}
${DirectX_DXGUID_LIBRARY}
${DirectX_D3DCOMPILER_LIBRARY}
)
${DirectX_D3DCOMPILER_LIBRARY}
)
endif ()
mark_as_advanced(DirectX_D3D11_INCLUDE_DIR DirectX_D3D11_LIBRARY DirectX_D3DX11_LIBRARY)
endif ()
+40 -12
View File
@@ -3,7 +3,7 @@ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(ASSIMP_ARCHITECTURE "32")
endif(CMAKE_SIZEOF_VOID_P EQUAL 8)
if(WIN32)
set(ASSIMP_ROOT_DIR CACHE PATH "ASSIMP root directory")
@@ -17,29 +17,29 @@ if(WIN32)
if(MSVC12)
set(ASSIMP_MSVC_VERSION "vc120")
elseif(MSVC14)
elseif(MSVC14)
set(ASSIMP_MSVC_VERSION "vc140")
endif(MSVC12)
if(MSVC12 OR MSVC14)
find_path(ASSIMP_LIBRARY_DIR
NAMES
assimp-${ASSIMP_MSVC_VERSION}-mt.lib
HINTS
${ASSIMP_ROOT_DIR}/lib${ASSIMP_ARCHITECTURE}
)
find_library(ASSIMP_LIBRARY_RELEASE assimp-${ASSIMP_MSVC_VERSION}-mt.lib PATHS ${ASSIMP_LIBRARY_DIR})
find_library(ASSIMP_LIBRARY_DEBUG assimp-${ASSIMP_MSVC_VERSION}-mtd.lib PATHS ${ASSIMP_LIBRARY_DIR})
set(ASSIMP_LIBRARY
set(ASSIMP_LIBRARY
optimized ${ASSIMP_LIBRARY_RELEASE}
debug ${ASSIMP_LIBRARY_DEBUG}
)
set(ASSIMP_LIBRARIES "ASSIMP_LIBRARY_RELEASE" "ASSIMP_LIBRARY_DEBUG")
FUNCTION(ASSIMP_COPY_BINARIES TargetDirectory)
ADD_CUSTOM_TARGET(AssimpCopyBinaries
COMMAND ${CMAKE_COMMAND} -E copy ${ASSIMP_ROOT_DIR}/bin${ASSIMP_ARCHITECTURE}/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${TargetDirectory}/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll
@@ -47,9 +47,37 @@ if(WIN32)
COMMENT "Copying Assimp binaries to '${TargetDirectory}'"
VERBATIM)
ENDFUNCTION(ASSIMP_COPY_BINARIES)
if (NOT TARGET ASSIMP)
set(INCLUDE_DIRS ${ASSIMP_ROOT_DIR}/include)
find_library(ASSIMP_LIB_DEBUG
NAMES assimp-${ASSIMP_MSVC_VERSION}-mtd.lib
PATHS ${ASSIMP_LIBRARY_DIR})
find_file(ASSIMP_DLL_DEBUG
NAMES assimp-${ASSIMP_MSVC_VERSION}-mtd.dll
PATHS ${ASSIMP_ROOT_DIR}/bin${ASSIMP_ARCHITECTURE})
find_library(ASSIMP_LIB_RELEASE
NAMES assimp-${ASSIMP_MSVC_VERSION}-mt.lib
PATHS ${ASSIMP_LIBRARY_DIR})
find_file(ASSIMP_DLL_RELEASE
NAMES assimp-${ASSIMP_MSVC_VERSION}-mt.dll
PATHS ${ASSIMP_ROOT_DIR}/bin${ASSIMP_ARCHITECTURE})
add_library(ASSIMP SHARED IMPORTED)
set_target_properties(ASSIMP PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${INCLUDE_DIRS}"
IMPORTED_IMPLIB_DEBUG ${ASSIMP_LIB_DEBUG}
IMPORTED_IMPLIB_RELEASE ${ASSIMP_LIB_RELEASE}
IMPORTED_LOCATION_DEBUG ${ASSIMP_DLL_DEBUG}
IMPORTED_LOCATION_RELEASE ${ASSIMP_DLL_RELEASE}
)
endif()
endif()
else(WIN32)
find_path(
@@ -81,5 +109,5 @@ else(WIN32)
message(FATAL_ERROR "Could not find asset importer library")
endif (assimp_FIND_REQUIRED)
endif (assimp_FOUND)
endif(WIN32)
+1 -1
View File
@@ -31,7 +31,7 @@ option(HUNTER_STATUS_PRINT "Print working status" ON)
option(HUNTER_STATUS_DEBUG "Print a lot info" OFF)
option(HUNTER_TLS_VERIFY "Enable/disable TLS certificate checking on downloads" ON)
set(HUNTER_ERROR_PAGE "https://docs.hunter.sh/en/latest/reference/errors")
set(HUNTER_ERROR_PAGE "https://hunter.readthedocs.io/en/latest/reference/errors")
function(hunter_gate_status_print)
if(HUNTER_STATUS_PRINT OR HUNTER_STATUS_DEBUG)
+3 -3
View File
@@ -9,14 +9,14 @@ MACRO(ADD_MSVC_PRECOMPILED_HEADER PrecompiledHeader PrecompiledSource SourcesVar
OBJECT_OUTPUTS "${PrecompiledBinary}")
# Do not consider .c files
foreach(fname ${Sources})
foreach(fname ${Sources})
GET_FILENAME_COMPONENT(fext ${fname} EXT)
if(fext STREQUAL ".cpp")
SET_SOURCE_FILES_PROPERTIES(${fname}
PROPERTIES COMPILE_FLAGS "/Yu\"${PrecompiledBinary}\" /FI\"${PrecompiledBinary}\" /Fp\"${PrecompiledBinary}\""
OBJECT_DEPENDS "${PrecompiledBinary}")
OBJECT_DEPENDS "${PrecompiledBinary}")
endif(fext STREQUAL ".cpp")
endforeach(fname)
endforeach(fname)
ENDIF(MSVC)
# Add precompiled header to SourcesVar
-8
View File
@@ -1,8 +0,0 @@
# See <http://EditorConfig.org> for details
[*.{h,hpp,c,cpp}]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_size = 4
indent_style = space
+76 -72
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -56,23 +56,27 @@ namespace Assimp {
static constexpr unsigned int NotSet = 0xcdcdcdcd;
using namespace D3DS;
// ------------------------------------------------------------------------------------------------
// Setup final material indices, generae a default material if necessary
// Setup final material indices, generate a default material if necessary
void Discreet3DSImporter::ReplaceDefaultMaterial() {
// Try to find an existing material that matches the
// typical default material setting:
// - no textures
// - diffuse color (in grey!)
// NOTE: This is here to workaround the fact that some
// NOTE: This is here to work-around the fact that some
// exporters are writing a default material, too.
unsigned int idx(NotSet);
for (unsigned int i = 0; i < mScene->mMaterials.size(); ++i) {
std::string s = mScene->mMaterials[i].mName;
auto s = mScene->mMaterials[i].mName;
for (char &it : s) {
it = static_cast<char>(::tolower(static_cast<unsigned char>(it)));
}
if (std::string::npos == s.find("default")) continue;
if (std::string::npos == s.find("default")) {
continue;
}
if (mScene->mMaterials[i].mDiffuse.r !=
mScene->mMaterials[i].mDiffuse.g ||
@@ -85,25 +89,22 @@ void Discreet3DSImporter::ReplaceDefaultMaterial() {
idx = i;
}
if (NotSet == idx) {
idx = (unsigned int)mScene->mMaterials.size();
idx = static_cast<unsigned int>(mScene->mMaterials.size());
}
// now iterate through all meshes and through all faces and
// find all faces that are using the default material
unsigned int cnt = 0;
for (std::vector<D3DS::Mesh>::iterator
i = mScene->mMeshes.begin();
i != mScene->mMeshes.end(); ++i) {
for (std::vector<unsigned int>::iterator
a = (*i).mFaceMaterials.begin();
a != (*i).mFaceMaterials.end(); ++a) {
for (auto i = mScene->mMeshes.begin(); i != mScene->mMeshes.end(); ++i) {
for (auto a = i->mFaceMaterials.begin(); a != i->mFaceMaterials.end(); ++a) {
// NOTE: The additional check seems to be necessary,
// some exporters seem to generate invalid data here
if (0xcdcdcdcd == (*a)) {
(*a) = idx;
if (NotSet == *a) {
*a = idx;
++cnt;
} else if ((*a) >= mScene->mMaterials.size()) {
(*a) = idx;
*a = idx;
ASSIMP_LOG_WARN("Material index overflow in 3DS file. Using default material");
++cnt;
}
@@ -111,7 +112,7 @@ void Discreet3DSImporter::ReplaceDefaultMaterial() {
}
if (cnt && idx == mScene->mMaterials.size()) {
// We need to create our own default material
D3DS::Material sMat("%%%DEFAULT");
Material sMat("%%%DEFAULT");
sMat.mDiffuse = aiColor3D(0.3f, 0.3f, 0.3f);
mScene->mMaterials.push_back(sMat);
@@ -121,17 +122,17 @@ void Discreet3DSImporter::ReplaceDefaultMaterial() {
// ------------------------------------------------------------------------------------------------
// Check whether all indices are valid. Otherwise we'd crash before the validation step is reached
void Discreet3DSImporter::CheckIndices(D3DS::Mesh &sMesh) {
for (std::vector<D3DS::Face>::iterator i = sMesh.mFaces.begin(); i != sMesh.mFaces.end(); ++i) {
void Discreet3DSImporter::CheckIndices(Mesh &sMesh) {
for (auto i = sMesh.mFaces.begin(); i != sMesh.mFaces.end(); ++i) {
// check whether all indices are in range
for (unsigned int a = 0; a < 3; ++a) {
if ((*i).mIndices[a] >= sMesh.mPositions.size()) {
ASSIMP_LOG_WARN("3DS: Vertex index overflow)");
(*i).mIndices[a] = (uint32_t)sMesh.mPositions.size() - 1;
(*i).mIndices[a] = static_cast<uint32_t>(sMesh.mPositions.size() - 1);
}
if (!sMesh.mTexCoords.empty() && (*i).mIndices[a] >= sMesh.mTexCoords.size()) {
ASSIMP_LOG_WARN("3DS: Texture coordinate index overflow)");
(*i).mIndices[a] = (uint32_t)sMesh.mTexCoords.size() - 1;
(*i).mIndices[a] = static_cast<uint32_t>(sMesh.mTexCoords.size() - 1);
}
}
}
@@ -139,7 +140,7 @@ void Discreet3DSImporter::CheckIndices(D3DS::Mesh &sMesh) {
// ------------------------------------------------------------------------------------------------
// Generate out unique verbose format representation
void Discreet3DSImporter::MakeUnique(D3DS::Mesh &sMesh) {
void Discreet3DSImporter::MakeUnique(Mesh &sMesh) {
// TODO: really necessary? I don't think. Just a waste of memory and time
// to do it now in a separate buffer.
@@ -150,7 +151,7 @@ void Discreet3DSImporter::MakeUnique(D3DS::Mesh &sMesh) {
vNew2.resize(sMesh.mFaces.size() * 3);
for (unsigned int i = 0, base = 0; i < sMesh.mFaces.size(); ++i) {
D3DS::Face &face = sMesh.mFaces[i];
Face &face = sMesh.mFaces[i];
// Positions
for (unsigned int a = 0; a < 3; ++a, ++base) {
@@ -167,10 +168,9 @@ void Discreet3DSImporter::MakeUnique(D3DS::Mesh &sMesh) {
// ------------------------------------------------------------------------------------------------
// Convert a 3DS texture to texture keys in an aiMaterial
void CopyTexture(aiMaterial &mat, D3DS::Texture &texture, aiTextureType type) {
void CopyTexture(aiMaterial &mat, Texture &texture, aiTextureType type) {
// Setup the texture name
aiString tex;
tex.Set(texture.mMapName);
aiString tex(texture.mMapName);
mat.AddProperty(&tex, AI_MATKEY_TEXTURE(type, 0));
// Setup the texture blend factor
@@ -178,7 +178,7 @@ void CopyTexture(aiMaterial &mat, D3DS::Texture &texture, aiTextureType type) {
mat.AddProperty<ai_real>(&texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type, 0));
// Setup the texture mapping mode
int mapMode = static_cast<int>(texture.mMapMode);
auto mapMode = static_cast<int>(texture.mMapMode);
mat.AddProperty<int>(&mapMode, 1, AI_MATKEY_MAPPINGMODE_U(type, 0));
mat.AddProperty<int>(&mapMode, 1, AI_MATKEY_MAPPINGMODE_V(type, 0));
@@ -197,13 +197,11 @@ void CopyTexture(aiMaterial &mat, D3DS::Texture &texture, aiTextureType type) {
// ------------------------------------------------------------------------------------------------
// Convert a 3DS material to an aiMaterial
void Discreet3DSImporter::ConvertMaterial(D3DS::Material &oldMat,
aiMaterial &mat) {
void Discreet3DSImporter::ConvertMaterial(Material &oldMat, aiMaterial &mat) {
// NOTE: Pass the background image to the viewer by bypassing the
// material system. This is an evil hack, never do it again!
if (0 != mBackgroundImage.length() && bHasBG) {
aiString tex;
tex.Set(mBackgroundImage);
if (mBackgroundImage.empty() && bHasBG) {
aiString tex(mBackgroundImage);
mat.AddProperty(&tex, AI_MATKEY_GLOBAL_BACKGROUND_IMAGE);
// Be sure this is only done for the first material
@@ -215,8 +213,7 @@ void Discreet3DSImporter::ConvertMaterial(D3DS::Material &oldMat,
oldMat.mAmbient.g += mClrAmbient.g;
oldMat.mAmbient.b += mClrAmbient.b;
aiString name;
name.Set(oldMat.mName);
aiString name(oldMat.mName);
mat.AddProperty(&name, AI_MATKEY_NAME);
// Material colors
@@ -226,10 +223,9 @@ void Discreet3DSImporter::ConvertMaterial(D3DS::Material &oldMat,
mat.AddProperty(&oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
// Phong shininess and shininess strength
if (D3DS::Discreet3DS::Phong == oldMat.mShading ||
D3DS::Discreet3DS::Metal == oldMat.mShading) {
if (Discreet3DS::Phong == oldMat.mShading || Discreet3DS::Metal == oldMat.mShading) {
if (!oldMat.mSpecularExponent || !oldMat.mShininessStrength) {
oldMat.mShading = D3DS::Discreet3DS::Gouraud;
oldMat.mShading = Discreet3DS::Gouraud;
} else {
mat.AddProperty(&oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
mat.AddProperty(&oldMat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
@@ -251,40 +247,41 @@ void Discreet3DSImporter::ConvertMaterial(D3DS::Material &oldMat,
// Shading mode
aiShadingMode eShading = aiShadingMode_NoShading;
switch (oldMat.mShading) {
case D3DS::Discreet3DS::Flat:
case Discreet3DS::Flat:
eShading = aiShadingMode_Flat;
break;
// I don't know what "Wire" shading should be,
// assume it is simple lambertian diffuse shading
case D3DS::Discreet3DS::Wire: {
case Discreet3DS::Wire: {
// Set the wireframe flag
unsigned int iWire = 1;
mat.AddProperty<int>((int *)&iWire, 1, AI_MATKEY_ENABLE_WIREFRAME);
}
[[fallthrough]];
case D3DS::Discreet3DS::Gouraud:
case Discreet3DS::Gouraud:
eShading = aiShadingMode_Gouraud;
break;
// assume cook-torrance shading for metals.
case D3DS::Discreet3DS::Phong:
case Discreet3DS::Phong:
eShading = aiShadingMode_Phong;
break;
case D3DS::Discreet3DS::Metal:
case Discreet3DS::Metal:
eShading = aiShadingMode_CookTorrance;
break;
// FIX to workaround a warning with GCC 4 who complained
// about a missing case Blinn: here - Blinn isn't a valid
// value in the 3DS Loader, it is just needed for ASE
case D3DS::Discreet3DS::Blinn:
case Discreet3DS::Blinn:
eShading = aiShadingMode_Blinn;
break;
}
int eShading_ = static_cast<int>(eShading);
const int eShading_ = eShading;
mat.AddProperty<int>(&eShading_, 1, AI_MATKEY_SHADING_MODEL);
// DIFFUSE texture
@@ -333,10 +330,11 @@ void Discreet3DSImporter::ConvertMeshes(aiScene *pcOut) {
aiString name;
// we need to split all meshes by their materials
for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(); i != mScene->mMeshes.end(); ++i) {
for (auto i = mScene->mMeshes.begin(); i != mScene->mMeshes.end(); ++i) {
std::unique_ptr<std::vector<unsigned int>[]> aiSplit(new std::vector<unsigned int>[mScene->mMaterials.size()]);
name.length = ASSIMP_itoa10(name.data, num++);
name.length = ASSIMP_itoa10(name.data, num);
++num;
unsigned int iNum = 0;
for (std::vector<unsigned int>::const_iterator a = (*i).mFaceMaterials.begin();
@@ -348,7 +346,7 @@ void Discreet3DSImporter::ConvertMeshes(aiScene *pcOut) {
if (aiSplit[p].empty()) {
continue;
}
aiMesh *meshOut = new aiMesh();
auto *meshOut = new aiMesh();
meshOut->mName = name;
meshOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
@@ -360,7 +358,7 @@ void Discreet3DSImporter::ConvertMeshes(aiScene *pcOut) {
avOutMeshes.push_back(meshOut);
// convert vertices
meshOut->mNumFaces = (unsigned int)aiSplit[p].size();
meshOut->mNumFaces = static_cast<unsigned int>(aiSplit[p].size());
meshOut->mNumVertices = meshOut->mNumFaces * 3;
// allocate enough storage for faces
@@ -408,8 +406,7 @@ void Discreet3DSImporter::ConvertMeshes(aiScene *pcOut) {
// ------------------------------------------------------------------------------------------------
// Add a node to the scenegraph and setup its final transformation
void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
D3DS::Node *pcIn, aiMatrix4x4 & /*absTrafo*/) {
void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut, D3DS::Node *pcIn, aiMatrix4x4 & /*absTrafo*/) {
std::vector<unsigned int> iArray;
iArray.reserve(3);
@@ -417,7 +414,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
// Find all meshes with the same name as the node
for (unsigned int a = 0; a < pcSOut->mNumMeshes; ++a) {
const D3DS::Mesh *pcMesh = (const D3DS::Mesh *)pcSOut->mMeshes[a]->mColors[0];
const auto *pcMesh = (const D3DS::Mesh *)pcSOut->mMeshes[a]->mColors[0];
ai_assert(nullptr != pcMesh);
if (pcIn->mName == pcMesh->mName)
@@ -426,7 +423,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
if (!iArray.empty()) {
// The matrix should be identical for all meshes with the
// same name. It HAS to be identical for all meshes .....
D3DS::Mesh *imesh = ((D3DS::Mesh *)pcSOut->mMeshes[iArray[0]]->mColors[0]);
auto *imesh = ((D3DS::Mesh *)pcSOut->mMeshes[iArray[0]]->mColors[0]);
// Compute the inverse of the transformation matrix to move the
// vertices back to their relative and local space
@@ -435,7 +432,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
mInvTransposed.Transpose();
aiVector3D pivot = pcIn->vPivot;
pcOut->mNumMeshes = (unsigned int)iArray.size();
pcOut->mNumMeshes = static_cast<unsigned int>(iArray.size());
pcOut->mMeshes = new unsigned int[iArray.size()];
for (unsigned int i = 0; i < iArray.size(); ++i) {
const unsigned int iIndex = iArray[i];
@@ -454,7 +451,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
// Handle negative transformation matrix determinant -> invert vertex x
if (imesh->mMat.Determinant() < 0.0f) {
/* we *must* have normals */
// we *must* have normals
for (pvCurrent = mesh->mVertices, t2 = mesh->mNormals; pvCurrent != pvEnd; ++pvCurrent, ++t2) {
pvCurrent->x *= -1.f;
t2->x *= -1.f;
@@ -481,7 +478,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
// Setup the name of the node
// First instance keeps its name otherwise something might break, all others will be postfixed with their instance number
if (pcIn->mInstanceNumber > 1) {
char tmp[12];
char tmp[12] = {'\0'};
ASSIMP_itoa10(tmp, pcIn->mInstanceNumber);
std::string tempStr = pcIn->mName + "_inst_";
tempStr += tmp;
@@ -494,7 +491,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
if (pcIn->aRotationKeys.size()) {
// FIX to get to Assimp's quaternion conventions
for (std::vector<aiQuatKey>::iterator it = pcIn->aRotationKeys.begin(); it != pcIn->aRotationKeys.end(); ++it) {
for (auto it = pcIn->aRotationKeys.begin(); it != pcIn->aRotationKeys.end(); ++it) {
(*it).mValue.w *= -1.f;
}
@@ -606,11 +603,11 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
}
// Allocate a new node anim and setup its name
aiNodeAnim *nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
auto *nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
nda->mNodeName.Set(pcIn->mName);
// POSITION keys
if (pcIn->aPositionKeys.size() > 0) {
if (!pcIn->aPositionKeys.empty()) {
nda->mNumPositionKeys = (unsigned int)pcIn->aPositionKeys.size();
nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
::memcpy(nda->mPositionKeys, &pcIn->aPositionKeys[0],
@@ -618,7 +615,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
}
// ROTATION keys
if (pcIn->aRotationKeys.size() > 0) {
if (!pcIn->aRotationKeys.empty()) {
nda->mNumRotationKeys = (unsigned int)pcIn->aRotationKeys.size();
nda->mRotationKeys = new aiQuatKey[nda->mNumRotationKeys];
@@ -634,7 +631,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
}
// SCALING keys
if (pcIn->aScalingKeys.size() > 0) {
if (!pcIn->aScalingKeys.empty()) {
nda->mNumScalingKeys = (unsigned int)pcIn->aScalingKeys.size();
nda->mScalingKeys = new aiVectorKey[nda->mNumScalingKeys];
::memcpy(nda->mScalingKeys, &pcIn->aScalingKeys[0],
@@ -643,11 +640,17 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene *pcSOut, aiNode *pcOut,
}
// Allocate storage for children
pcOut->mNumChildren = (unsigned int)pcIn->mChildren.size();
const auto size = static_cast<unsigned int>(pcIn->mChildren.size());
pcOut->mNumChildren = size;
if (size == 0) {
return;
}
pcOut->mChildren = new aiNode *[pcIn->mChildren.size()];
// Recursively process all children
const unsigned int size = static_cast<unsigned int>(pcIn->mChildren.size());
for (unsigned int i = 0; i < size; ++i) {
pcOut->mChildren[i] = new aiNode();
pcOut->mChildren[i]->mParent = pcOut;
@@ -680,7 +683,7 @@ void CountTracks(D3DS::Node *node, unsigned int &cnt) {
// Generate the output node graph
void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
pcOut->mRootNode = new aiNode();
if (0 == mRootNode->mChildren.size()) {
if (mRootNode->mChildren.empty()) {
//////////////////////////////////////////////////////////////////////////////
// It seems the file is so messed up that it has not even a hierarchy.
// generate a flat hiearachy which looks like this:
@@ -702,7 +705,8 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
// Build dummy nodes for all meshes
unsigned int a = 0;
for (unsigned int i = 0; i < pcOut->mNumMeshes; ++i, ++a) {
aiNode *pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
pcOut->mRootNode->mChildren[a] = new aiNode();
auto *pcNode = pcOut->mRootNode->mChildren[a];
pcNode->mParent = pcOut->mRootNode;
pcNode->mMeshes = new unsigned int[1];
pcNode->mMeshes[0] = i;
@@ -714,7 +718,7 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
// Build dummy nodes for all cameras
for (unsigned int i = 0; i < (unsigned int)mScene->mCameras.size(); ++i, ++a) {
aiNode *pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
auto *pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
pcNode->mParent = pcOut->mRootNode;
// Build a name for the node
@@ -723,7 +727,7 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
// Build dummy nodes for all lights
for (unsigned int i = 0; i < (unsigned int)mScene->mLights.size(); ++i, ++a) {
aiNode *pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
auto *pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
pcNode->mParent = pcOut->mRootNode;
// Build a name for the node
@@ -739,7 +743,7 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
// Allocate a primary animation channel
pcOut->mNumAnimations = 1;
pcOut->mAnimations = new aiAnimation *[1];
aiAnimation *anim = pcOut->mAnimations[0] = new aiAnimation();
auto *anim = pcOut->mAnimations[0] = new aiAnimation();
anim->mName.Set("3DSMasterAnim");
@@ -777,12 +781,12 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene *pcOut) {
// Convert all meshes in the scene and generate the final output scene.
void Discreet3DSImporter::ConvertScene(aiScene *pcOut) {
// Allocate enough storage for all output materials
pcOut->mNumMaterials = (unsigned int)mScene->mMaterials.size();
pcOut->mNumMaterials = static_cast<unsigned int>(mScene->mMaterials.size());
pcOut->mMaterials = new aiMaterial *[pcOut->mNumMaterials];
// ... and convert the 3DS materials to aiMaterial's
for (unsigned int i = 0; i < pcOut->mNumMaterials; ++i) {
aiMaterial *pcNew = new aiMaterial();
auto *pcNew = new aiMaterial();
ConvertMaterial(mScene->mMaterials[i], *pcNew);
pcOut->mMaterials[i] = pcNew;
}
@@ -791,17 +795,17 @@ void Discreet3DSImporter::ConvertScene(aiScene *pcOut) {
ConvertMeshes(pcOut);
// Now copy all light sources to the output scene
pcOut->mNumLights = (unsigned int)mScene->mLights.size();
pcOut->mNumLights = static_cast<unsigned int>(mScene->mLights.size());
if (pcOut->mNumLights) {
pcOut->mLights = new aiLight *[pcOut->mNumLights];
::memcpy(pcOut->mLights, &mScene->mLights[0], sizeof(void *) * pcOut->mNumLights);
memcpy(pcOut->mLights, &mScene->mLights[0], sizeof(void *) * pcOut->mNumLights);
}
// Now copy all cameras to the output scene
pcOut->mNumCameras = (unsigned int)mScene->mCameras.size();
pcOut->mNumCameras = static_cast<unsigned int>(mScene->mCameras.size());
if (pcOut->mNumCameras) {
pcOut->mCameras = new aiCamera *[pcOut->mNumCameras];
::memcpy(pcOut->mCameras, &mScene->mCameras[0], sizeof(void *) * pcOut->mNumCameras);
memcpy(pcOut->mCameras, &mScene->mCameras[0], sizeof(void *) * pcOut->mNumCameras);
}
}
+18 -24
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -52,6 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/StringComparison.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/Exceptional.h>
#include <assimp/IOSystem.hpp>
#include <memory>
@@ -76,33 +76,33 @@ class ChunkWriter {
public:
ChunkWriter(StreamWriterLE &writer, uint16_t chunk_type) :
writer(writer) {
chunk_start_pos = writer.GetCurrentPos();
mWriter(writer) {
mChunkStartPos = writer.GetCurrentPos();
writer.PutU2(chunk_type);
writer.PutU4((uint32_t)CHUNK_SIZE_NOT_SET);
}
~ChunkWriter() {
std::size_t head_pos = writer.GetCurrentPos();
std::size_t head_pos = mWriter.GetCurrentPos();
ai_assert(head_pos > chunk_start_pos);
const std::size_t chunk_size = head_pos - chunk_start_pos;
ai_assert(head_pos > mChunkStartPos);
const std::size_t chunk_size = head_pos - mChunkStartPos;
writer.SetCurrentPos(chunk_start_pos + SIZE_OFFSET);
writer.PutU4(static_cast<uint32_t>(chunk_size));
writer.SetCurrentPos(head_pos);
mWriter.SetCurrentPos(mChunkStartPos + SIZE_OFFSET);
mWriter.PutU4(static_cast<uint32_t>(chunk_size));
mWriter.SetCurrentPos(head_pos);
}
private:
StreamWriterLE &writer;
std::size_t chunk_start_pos;
StreamWriterLE &mWriter;
std::size_t mChunkStartPos;
};
// Return an unique name for a given |mesh| attached to |node| that
// preserves the mesh's given name if it has one. |index| is the index
// of the mesh in |aiScene::mMeshes|.
std::string GetMeshName(const aiMesh &mesh, unsigned int index, const aiNode &node) {
static const char underscore = '_';
static constexpr char underscore = '_';
char postfix[10] = { 0 };
ASSIMP_itoa10(postfix, index);
@@ -122,8 +122,7 @@ std::string GetMaterialName(const aiMaterial &mat, unsigned int index) {
char postfix[10] = { 0 };
ASSIMP_itoa10(postfix, index);
aiString mat_name;
if (AI_SUCCESS == mat.Get(AI_MATKEY_NAME, mat_name)) {
if (aiString mat_name; AI_SUCCESS == mat.Get(AI_MATKEY_NAME, mat_name)) {
return mat_name.C_Str() + underscore + postfix;
}
@@ -208,9 +207,6 @@ Discreet3DSExporter::Discreet3DSExporter(std::shared_ptr<IOStream> &outfile, con
}
}
// ------------------------------------------------------------------------------------------------
Discreet3DSExporter::~Discreet3DSExporter() = default;
// ------------------------------------------------------------------------------------------------
int Discreet3DSExporter::WriteHierarchy(const aiNode &node, int seq, int sibling_level) {
// 3DS scene hierarchy is serialized as in http://www.martinreddy.net/gfx/3d/3DS.spec
@@ -306,8 +302,7 @@ void Discreet3DSExporter::WriteMaterials() {
WriteColor(color);
}
aiShadingMode shading_mode = aiShadingMode_Flat;
if (mat.Get(AI_MATKEY_SHADING_MODEL, shading_mode) == AI_SUCCESS) {
if (aiShadingMode shading_mode = aiShadingMode_Flat; mat.Get(AI_MATKEY_SHADING_MODEL, shading_mode) == AI_SUCCESS) {
ChunkWriter chunk(writer, Discreet3DS::CHUNK_MAT_SHADING);
Discreet3DS::shadetype3ds shading_mode_out;
@@ -335,7 +330,7 @@ void Discreet3DSExporter::WriteMaterials() {
default:
shading_mode_out = Discreet3DS::Flat;
ai_assert(false);
};
}
writer.PutU2(static_cast<uint16_t>(shading_mode_out));
}
@@ -349,8 +344,7 @@ void Discreet3DSExporter::WriteMaterials() {
WritePercentChunk(f);
}
int twosided;
if (mat.Get(AI_MATKEY_TWOSIDED, twosided) == AI_SUCCESS && twosided != 0) {
if (int twosided; mat.Get(AI_MATKEY_TWOSIDED, twosided) == AI_SUCCESS && twosided != 0) {
ChunkWriter chunk(writer, Discreet3DS::CHUNK_MAT_TWO_SIDE);
writer.PutI2(1);
}
@@ -544,7 +538,7 @@ void Discreet3DSExporter::WriteFaceMaterialChunk(const aiMesh &mesh) {
// ------------------------------------------------------------------------------------------------
void Discreet3DSExporter::WriteString(const std::string &s) {
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
for (auto it = s.begin(); it != s.end(); ++it) {
writer.PutI1(*it);
}
writer.PutI1('\0');
+3 -4
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -63,10 +63,10 @@ namespace Assimp {
* @brief Helper class to export a given scene to a 3DS file.
*/
// ------------------------------------------------------------------------------------------------
class Discreet3DSExporter {
class Discreet3DSExporter final {
public:
Discreet3DSExporter(std::shared_ptr<IOStream> &outfile, const aiScene* pScene);
~Discreet3DSExporter();
~Discreet3DSExporter() = default;
private:
void WriteMeshes();
@@ -88,7 +88,6 @@ private:
using MeshesByNodeMap = std::multimap<const aiNode*, unsigned int>;
MeshesByNodeMap meshes;
};
} // Namespace Assimp
+5 -9
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -55,8 +54,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/qnan.h>
#include <cstdio> //sprintf
namespace Assimp {
namespace D3DS {
namespace Assimp::D3DS {
#include <assimp/Compiler/pushpack1.h>
@@ -365,14 +363,13 @@ struct Texture {
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
// ---------------------------------------------------------------------------
/** Helper structure representing a 3ds material */
struct Material {
//! Default constructor has been deleted
Material() :
mName(),
mDiffuse(ai_real(0.6), ai_real(0.6), ai_real(0.6)),
mDiffuse(0.6f, 0.6f, 0.6f),
mSpecularExponent(ai_real(0.0)),
mShininessStrength(ai_real(1.0)),
mShading(Discreet3DS::Gouraud),
@@ -385,7 +382,7 @@ struct Material {
//! Constructor with explicit name
explicit Material(const std::string &name) :
mName(name),
mDiffuse(ai_real(0.6), ai_real(0.6), ai_real(0.6)),
mDiffuse(0.6f, 0.6f, 0.6f),
mSpecularExponent(ai_real(0.0)),
mShininessStrength(ai_real(1.0)),
mShading(Discreet3DS::Gouraud),
@@ -581,7 +578,6 @@ struct Scene {
// Node* pcRootNode;
};
} // end of namespace D3DS
} // end of namespace Assimp
} // end of namespace Assimp::D3DS
#endif // AI_XFILEHELPER_H_INC
+179 -180
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -56,6 +56,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Assimp {
using namespace D3DS;
static constexpr aiImporterDesc desc = {
"Discreet 3DS Importer",
"",
@@ -75,7 +77,7 @@ static constexpr aiImporterDesc desc = {
// - computes its length
#define ASSIMP_3DS_BEGIN_CHUNK() \
while (true) { \
if (stream->GetRemainingSizeToLimit() < sizeof(Discreet3DS::Chunk)) { \
if (mStream->GetRemainingSizeToLimit() < sizeof(Discreet3DS::Chunk)) { \
return; \
} \
Discreet3DS::Chunk chunk; \
@@ -83,30 +85,30 @@ static constexpr aiImporterDesc desc = {
int chunkSize = chunk.Size - sizeof(Discreet3DS::Chunk); \
if (chunkSize <= 0) \
continue; \
const unsigned int oldReadLimit = stream->SetReadLimit( \
stream->GetCurrentPos() + chunkSize);
const unsigned int oldReadLimit = mStream->SetReadLimit( \
mStream->GetCurrentPos() + chunkSize);
// ------------------------------------------------------------------------------------------------
// End a parsing block
// Must follow at the end of each parsing block, reset chunk end marker to previous value
#define ASSIMP_3DS_END_CHUNK() \
stream->SkipToReadLimit(); \
stream->SetReadLimit(oldReadLimit); \
if (stream->GetRemainingSizeToLimit() == 0) \
mStream->SkipToReadLimit(); \
mStream->SetReadLimit(oldReadLimit); \
if (mStream->GetRemainingSizeToLimit() == 0) \
return; \
}
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
Discreet3DSImporter::Discreet3DSImporter() :
stream(), mLastNodeIndex(), mCurrentNode(), mRootNode(), mScene(), mMasterScale(), bHasBG(), bIsPrj() {
mStream(nullptr), mLastNodeIndex(), mCurrentNode(), mRootNode(), mScene(), mMasterScale(), bHasBG(), bIsPrj() {
// empty
}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool Discreet3DSImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
static const uint16_t token[] = { 0x4d4d, 0x3dc2 /*, 0x3daa */ };
static constexpr uint16_t token[] = { 0x4d4d, 0x3dc2 /*, 0x3daa */ };
return CheckMagicToken(pIOHandler, pFile, token, AI_COUNT_OF(token), 0, sizeof token[0]);
}
@@ -124,9 +126,7 @@ void Discreet3DSImporter::SetupProperties(const Importer * /*pImp*/) {
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void Discreet3DSImporter::InternReadFile(const std::string &pFile,
aiScene *pScene, IOSystem *pIOHandler) {
void Discreet3DSImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
auto theFile = pIOHandler->Open(pFile, "rb");
if (!theFile) {
throw DeadlyImportError("3DS: Could not open ", pFile);
@@ -138,14 +138,14 @@ void Discreet3DSImporter::InternReadFile(const std::string &pFile,
if (theStream.GetRemainingSize() < 16) {
throw DeadlyImportError("3DS file is either empty or corrupt: ", pFile);
}
this->stream = &theStream;
mStream = &theStream;
// Allocate our temporary 3DS representation
D3DS::Scene _scene;
Scene _scene;
mScene = &_scene;
// Initialize members
D3DS::Node _rootNode("UNNAMED");
Node _rootNode("UNNAMED");
mLastNodeIndex = -1;
mCurrentNode = &_rootNode;
mRootNode = mCurrentNode;
@@ -166,12 +166,12 @@ void Discreet3DSImporter::InternReadFile(const std::string &pFile,
// vectors from the smoothing groups we read from the
// file.
for (auto &mesh : mScene->mMeshes) {
if (mesh.mFaces.size() > 0 && mesh.mPositions.size() == 0) {
if (!mesh.mFaces.empty() && mesh.mPositions.empty()) {
throw DeadlyImportError("3DS file contains faces but no vertices: ", pFile);
}
CheckIndices(mesh);
MakeUnique(mesh);
ComputeNormalsWithSmoothingsGroups<D3DS::Face>(mesh);
ComputeNormalsWithSmoothingsGroups<Face>(mesh);
}
// Replace all occurrences of the default material with a
@@ -196,12 +196,12 @@ void Discreet3DSImporter::InternReadFile(const std::string &pFile,
AI_DEBUG_INVALIDATE_PTR(mRootNode);
AI_DEBUG_INVALIDATE_PTR(mScene);
AI_DEBUG_INVALIDATE_PTR(this->stream);
AI_DEBUG_INVALIDATE_PTR(mStream);
}
// ------------------------------------------------------------------------------------------------
// Applies a master-scaling factor to the imported scene
void Discreet3DSImporter::ApplyMasterScale(aiScene *pScene) {
void Discreet3DSImporter::ApplyMasterScale(const aiScene *pScene) {
// There are some 3DS files with a zero scaling factor
if (!mMasterScale)
mMasterScale = 1.0f;
@@ -223,14 +223,14 @@ void Discreet3DSImporter::ApplyMasterScale(aiScene *pScene) {
void Discreet3DSImporter::ReadChunk(Discreet3DS::Chunk *pcOut) {
ai_assert(pcOut != nullptr);
pcOut->Flag = stream->GetI2();
pcOut->Size = stream->GetI4();
pcOut->Flag = mStream->GetI2();
pcOut->Size = mStream->GetI4();
if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSize()) {
if (pcOut->Size - sizeof(Discreet3DS::Chunk) > mStream->GetRemainingSize()) {
throw DeadlyImportError("Chunk is too large");
}
if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSizeToLimit()) {
if (pcOut->Size - sizeof(Discreet3DS::Chunk) > mStream->GetRemainingSizeToLimit()) {
ASSIMP_LOG_ERROR("3DS: Chunk overflow");
}
}
@@ -241,8 +241,7 @@ void Discreet3DSImporter::SkipChunk() {
Discreet3DS::Chunk psChunk;
ReadChunk(&psChunk);
stream->IncPtr(psChunk.Size - sizeof(Discreet3DS::Chunk));
return;
mStream->IncPtr(psChunk.Size - sizeof(Discreet3DS::Chunk));
}
// ------------------------------------------------------------------------------------------------
@@ -259,7 +258,7 @@ void Discreet3DSImporter::ParseMainChunk() {
case Discreet3DS::CHUNK_MAIN:
ParseEditorChunk();
break;
};
}
ASSIMP_3DS_END_CHUNK();
#if defined(__clang__)
@@ -275,30 +274,29 @@ void Discreet3DSImporter::ParseMainChunk() {
// ------------------------------------------------------------------------------------------------
void Discreet3DSImporter::ParseEditorChunk() {
ASSIMP_3DS_BEGIN_CHUNK();
ASSIMP_3DS_BEGIN_CHUNK()
// get chunk type
switch (chunk.Flag) {
case Discreet3DS::CHUNK_OBJMESH:
case Discreet3DS::CHUNK_OBJMESH:
ParseObjectChunk();
break;
ParseObjectChunk();
// NOTE: In several documentations in the internet this
// chunk appears at different locations
case Discreet3DS::CHUNK_KEYFRAMER:
ParseKeyframeChunk();
break;
case Discreet3DS::CHUNK_VERSION: {
// print the version number
char buff[10];
ASSIMP_itoa10(buff, mStream->GetI2());
ASSIMP_LOG_INFO("3DS file format version: ", buff);
}
break;
// NOTE: In several documentations in the internet this
// chunk appears at different locations
case Discreet3DS::CHUNK_KEYFRAMER:
ParseKeyframeChunk();
break;
case Discreet3DS::CHUNK_VERSION: {
// print the version number
char buff[10];
ASSIMP_itoa10(buff, stream->GetI2());
ASSIMP_LOG_INFO("3DS file format version: ", buff);
} break;
};
ASSIMP_3DS_END_CHUNK();
ASSIMP_3DS_END_CHUNK()
}
// ------------------------------------------------------------------------------------------------
@@ -309,10 +307,10 @@ void Discreet3DSImporter::ParseObjectChunk() {
switch (chunk.Flag) {
case Discreet3DS::CHUNK_OBJBLOCK: {
unsigned int cnt = 0;
const char *sz = (const char *)stream->GetPtr();
const auto *sz = (const char *)mStream->GetPtr();
// Get the name of the geometry object
while (stream->GetI1())
while (mStream->GetI1())
++cnt;
ParseChunk(sz, cnt);
} break;
@@ -340,8 +338,8 @@ void Discreet3DSImporter::ParseObjectChunk() {
// Specifies the background image. The string should already be
// properly 0 terminated but we need to be sure
unsigned int cnt = 0;
const char *sz = (const char *)stream->GetPtr();
while (stream->GetI1())
auto *sz = (const char *)mStream->GetPtr();
while (mStream->GetI1())
++cnt;
mBackgroundImage = std::string(sz, cnt);
} break;
@@ -352,7 +350,7 @@ void Discreet3DSImporter::ParseObjectChunk() {
case Discreet3DS::CHUNK_MASTER_SCALE:
// Scene master scaling factor
mMasterScale = stream->GetF4();
mMasterScale = mStream->GetF4();
break;
};
ASSIMP_3DS_END_CHUNK();
@@ -379,15 +377,15 @@ void Discreet3DSImporter::ParseChunk(const char *name, unsigned int num) {
case Discreet3DS::CHUNK_LIGHT: {
// This starts a new light
aiLight *light = new aiLight();
auto *light = new aiLight();
mScene->mLights.push_back(light);
light->mName.Set(std::string(name, num));
// First read the position of the light
light->mPosition.x = stream->GetF4();
light->mPosition.y = stream->GetF4();
light->mPosition.z = stream->GetF4();
light->mPosition.x = mStream->GetF4();
light->mPosition.y = mStream->GetF4();
light->mPosition.z = mStream->GetF4();
light->mColorDiffuse = aiColor3D(1.f, 1.f, 1.f);
@@ -408,19 +406,19 @@ void Discreet3DSImporter::ParseChunk(const char *name, unsigned int num) {
case Discreet3DS::CHUNK_CAMERA: {
// This starts a new camera
aiCamera *camera = new aiCamera();
auto *camera = new aiCamera();
mScene->mCameras.push_back(camera);
camera->mName.Set(std::string(name, num));
// First read the position of the camera
camera->mPosition.x = stream->GetF4();
camera->mPosition.y = stream->GetF4();
camera->mPosition.z = stream->GetF4();
camera->mPosition.x = mStream->GetF4();
camera->mPosition.y = mStream->GetF4();
camera->mPosition.z = mStream->GetF4();
// Then the camera target
camera->mLookAt.x = stream->GetF4() - camera->mPosition.x;
camera->mLookAt.y = stream->GetF4() - camera->mPosition.y;
camera->mLookAt.z = stream->GetF4() - camera->mPosition.z;
camera->mLookAt.x = mStream->GetF4() - camera->mPosition.x;
camera->mLookAt.y = mStream->GetF4() - camera->mPosition.y;
camera->mLookAt.z = mStream->GetF4() - camera->mPosition.z;
ai_real len = camera->mLookAt.Length();
if (len < 1e-5) {
@@ -432,12 +430,12 @@ void Discreet3DSImporter::ParseChunk(const char *name, unsigned int num) {
camera->mLookAt /= len;
// And finally - the camera rotation angle, in counter clockwise direction
const ai_real angle = AI_DEG_TO_RAD(stream->GetF4());
const ai_real angle = AI_DEG_TO_RAD(mStream->GetF4());
aiQuaternion quat(camera->mLookAt, angle);
camera->mUp = quat.GetMatrix() * aiVector3D(0.0, 1.0, 0.0);
// Read the lense angle
camera->mHorizontalFOV = AI_DEG_TO_RAD(stream->GetF4());
camera->mHorizontalFOV = AI_DEG_TO_RAD(mStream->GetF4());
if (camera->mHorizontalFOV < 0.001f) {
camera->mHorizontalFOV = float(AI_DEG_TO_RAD(45.f));
}
@@ -463,34 +461,34 @@ void Discreet3DSImporter::ParseLightChunk() {
light->mType = aiLightSource_SPOT;
// We wouldn't need to normalize here, but we do it
light->mDirection.x = stream->GetF4() - light->mPosition.x;
light->mDirection.y = stream->GetF4() - light->mPosition.y;
light->mDirection.z = stream->GetF4() - light->mPosition.z;
light->mDirection.x = mStream->GetF4() - light->mPosition.x;
light->mDirection.y = mStream->GetF4() - light->mPosition.y;
light->mDirection.z = mStream->GetF4() - light->mPosition.z;
light->mDirection.Normalize();
// Now the hotspot and falloff angles - in degrees
light->mAngleInnerCone = AI_DEG_TO_RAD(stream->GetF4());
light->mAngleInnerCone = AI_DEG_TO_RAD(mStream->GetF4());
// FIX: the falloff angle is just an offset
light->mAngleOuterCone = light->mAngleInnerCone + AI_DEG_TO_RAD(stream->GetF4());
light->mAngleOuterCone = light->mAngleInnerCone + AI_DEG_TO_RAD(mStream->GetF4());
break;
// intensity multiplier
case Discreet3DS::CHUNK_DL_MULTIPLIER:
light->mColorDiffuse = light->mColorDiffuse * stream->GetF4();
light->mColorDiffuse = light->mColorDiffuse * mStream->GetF4();
break;
// light color
case Discreet3DS::CHUNK_RGBF:
case Discreet3DS::CHUNK_LINRGBF:
light->mColorDiffuse.r *= stream->GetF4();
light->mColorDiffuse.g *= stream->GetF4();
light->mColorDiffuse.b *= stream->GetF4();
light->mColorDiffuse.r *= mStream->GetF4();
light->mColorDiffuse.g *= mStream->GetF4();
light->mColorDiffuse.b *= mStream->GetF4();
break;
// light attenuation
case Discreet3DS::CHUNK_DL_ATTENUATE:
light->mAttenuationLinear = stream->GetF4();
light->mAttenuationLinear = mStream->GetF4();
break;
};
@@ -505,10 +503,10 @@ void Discreet3DSImporter::ParseCameraChunk() {
// get chunk type
switch (chunk.Flag) {
// near and far clip plane
case Discreet3DS::CHUNK_CAM_RANGES:
camera->mClipPlaneNear = stream->GetF4();
camera->mClipPlaneFar = stream->GetF4();
break;
case Discreet3DS::CHUNK_CAM_RANGES:
camera->mClipPlaneNear = mStream->GetF4();
camera->mClipPlaneFar = mStream->GetF4();
break;
}
ASSIMP_3DS_END_CHUNK();
@@ -555,14 +553,13 @@ void Discreet3DSImporter::InverseNodeSearch(D3DS::Node *pcNode, D3DS::Node *pcCu
// ------------------------------------------------------------------------------------------------
// Find a node with a specific name in the import hierarchy
D3DS::Node *FindNode(D3DS::Node *root, const std::string &name) {
Node *FindNode(Node *root, const std::string &name) {
if (root->mName == name) {
return root;
}
for (std::vector<D3DS::Node *>::iterator it = root->mChildren.begin(); it != root->mChildren.end(); ++it) {
D3DS::Node *nd = FindNode(*it, name);
if (nullptr != nd) {
for (auto it = root->mChildren.begin(); it != root->mChildren.end(); ++it) {
if (auto *nd = FindNode(*it, name); nullptr != nd) {
return nd;
}
}
@@ -580,7 +577,7 @@ bool KeyUniqueCompare(const T &first, const T &second) {
// ------------------------------------------------------------------------------------------------
// Skip some additional import data.
void Discreet3DSImporter::SkipTCBInfo() {
unsigned int flags = stream->GetI2();
unsigned int flags = mStream->GetI2();
if (!flags) {
// Currently we can't do anything with these values. They occur
@@ -591,19 +588,19 @@ void Discreet3DSImporter::SkipTCBInfo() {
}
if (flags & Discreet3DS::KEY_USE_TENS) {
stream->IncPtr(4);
mStream->IncPtr(4);
}
if (flags & Discreet3DS::KEY_USE_BIAS) {
stream->IncPtr(4);
mStream->IncPtr(4);
}
if (flags & Discreet3DS::KEY_USE_CONT) {
stream->IncPtr(4);
mStream->IncPtr(4);
}
if (flags & Discreet3DS::KEY_USE_EASE_FROM) {
stream->IncPtr(4);
mStream->IncPtr(4);
}
if (flags & Discreet3DS::KEY_USE_EASE_TO) {
stream->IncPtr(4);
mStream->IncPtr(4);
}
}
@@ -622,15 +619,15 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
// First of all: get the name of the object
unsigned int cnt = 0;
const char *sz = (const char *)stream->GetPtr();
auto *sz = (const char *)mStream->GetPtr();
while (stream->GetI1())
while (mStream->GetI1())
++cnt;
std::string name = std::string(sz, cnt);
// Now find out whether we have this node already (target animation channels
// are stored with a separate object ID)
D3DS::Node *pcNode = FindNode(mRootNode, name);
Node *pcNode = FindNode(mRootNode, name);
int instanceNumber = 1;
if (pcNode) {
@@ -646,10 +643,10 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
pcNode->mInstanceNumber = instanceNumber;
// There are two unknown values which we can safely ignore
stream->IncPtr(4);
mStream->IncPtr(4);
// Now read the hierarchy position of the object
uint16_t hierarchy = stream->GetI2() + 1;
uint16_t hierarchy = mStream->GetI2() + 1;
pcNode->mHierarchyPos = hierarchy;
pcNode->mHierarchyIndex = mLastNodeIndex;
@@ -678,8 +675,8 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
// This is the "real" name of a $$$DUMMY object
{
const char *sz = (const char *)stream->GetPtr();
while (stream->GetI1())
const char *sz = (const char *)mStream->GetPtr();
while (mStream->GetI1())
;
// If object name is DUMMY, take this one instead
@@ -698,16 +695,16 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
}
// Pivot = origin of rotation and scaling
mCurrentNode->vPivot.x = stream->GetF4();
mCurrentNode->vPivot.y = stream->GetF4();
mCurrentNode->vPivot.z = stream->GetF4();
mCurrentNode->vPivot.x = mStream->GetF4();
mCurrentNode->vPivot.y = mStream->GetF4();
mCurrentNode->vPivot.z = mStream->GetF4();
break;
// ////////////////////////////////////////////////////////////////////
// POSITION KEYFRAME
case Discreet3DS::CHUNK_TRACKPOS: {
stream->IncPtr(10);
const unsigned int numFrames = stream->GetI4();
mStream->IncPtr(10);
const unsigned int numFrames = mStream->GetI4();
bool sortKeys = false;
// This could also be meant as the target position for
@@ -720,16 +717,16 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
l->reserve(numFrames);
for (unsigned int i = 0; i < numFrames; ++i) {
const unsigned int fidx = stream->GetI4();
const unsigned int fidx = mStream->GetI4();
// Setup a new position key
aiVectorKey v;
v.mTime = (double)fidx;
SkipTCBInfo();
v.mValue.x = stream->GetF4();
v.mValue.y = stream->GetF4();
v.mValue.z = stream->GetF4();
v.mValue.x = mStream->GetF4();
v.mValue.y = mStream->GetF4();
v.mValue.z = mStream->GetF4();
// check whether we'll need to sort the keys
if (!l->empty() && v.mTime <= l->back().mTime)
@@ -759,11 +756,11 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
bool sortKeys = false;
std::vector<aiFloatKey> *l = &mCurrentNode->aCameraRollKeys;
stream->IncPtr(10);
const unsigned int numFrames = stream->GetI4();
mStream->IncPtr(10);
const unsigned int numFrames = mStream->GetI4();
l->reserve(numFrames);
for (unsigned int i = 0; i < numFrames; ++i) {
const unsigned int fidx = stream->GetI4();
const unsigned int fidx = mStream->GetI4();
// Setup a new position key
aiFloatKey v;
@@ -771,7 +768,7 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
// This is just a single float
SkipTCBInfo();
v.mValue = stream->GetF4();
v.mValue = mStream->GetF4();
// Check whether we'll need to sort the keys
if (!l->empty() && v.mTime <= l->back().mTime)
@@ -798,26 +795,26 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
// ////////////////////////////////////////////////////////////////////
// ROTATION KEYFRAME
case Discreet3DS::CHUNK_TRACKROTATE: {
stream->IncPtr(10);
const unsigned int numFrames = stream->GetI4();
mStream->IncPtr(10);
const unsigned int numFrames = mStream->GetI4();
bool sortKeys = false;
std::vector<aiQuatKey> *l = &mCurrentNode->aRotationKeys;
l->reserve(numFrames);
for (unsigned int i = 0; i < numFrames; ++i) {
const unsigned int fidx = stream->GetI4();
const unsigned int fidx = mStream->GetI4();
SkipTCBInfo();
aiQuatKey v;
v.mTime = (double)fidx;
// The rotation keyframe is given as an axis-angle pair
const float rad = stream->GetF4();
const float rad = mStream->GetF4();
aiVector3D axis;
axis.x = stream->GetF4();
axis.y = stream->GetF4();
axis.z = stream->GetF4();
axis.x = mStream->GetF4();
axis.y = mStream->GetF4();
axis.z = mStream->GetF4();
if (!axis.x && !axis.y && !axis.z)
axis.y = 1.f;
@@ -842,16 +839,16 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
// ////////////////////////////////////////////////////////////////////
// SCALING KEYFRAME
case Discreet3DS::CHUNK_TRACKSCALE: {
stream->IncPtr(10);
const unsigned int numFrames = stream->GetI2();
stream->IncPtr(2);
mStream->IncPtr(10);
const unsigned int numFrames = mStream->GetI2();
mStream->IncPtr(2);
bool sortKeys = false;
std::vector<aiVectorKey> *l = &mCurrentNode->aScalingKeys;
l->reserve(numFrames);
for (unsigned int i = 0; i < numFrames; ++i) {
const unsigned int fidx = stream->GetI4();
const unsigned int fidx = mStream->GetI4();
SkipTCBInfo();
// Setup a new key
@@ -859,9 +856,9 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
v.mTime = (double)fidx;
// ... and read its value
v.mValue.x = stream->GetF4();
v.mValue.y = stream->GetF4();
v.mValue.z = stream->GetF4();
v.mValue.x = mStream->GetF4();
v.mValue.y = mStream->GetF4();
v.mValue.z = mStream->GetF4();
// check whether we'll need to sort the keys
if (!l->empty() && v.mTime <= l->back().mTime)
@@ -902,23 +899,23 @@ void Discreet3DSImporter::ParseFaceChunk() {
if (num > mMesh.mFaces.size()) {
throw DeadlyImportError("3DS: More smoothing groups than faces");
}
for (std::vector<D3DS::Face>::iterator i = mMesh.mFaces.begin(); m != num; ++i, ++m) {
for (auto i = mMesh.mFaces.begin(); m != num; ++i, ++m) {
// nth bit is set for nth smoothing group
(*i).iSmoothGroup = stream->GetI4();
i->iSmoothGroup = mStream->GetI4();
}
} break;
case Discreet3DS::CHUNK_FACEMAT: {
// at fist an asciiz with the material name
const char *sz = (const char *)stream->GetPtr();
while (stream->GetI1())
const char *sz = (const char *)mStream->GetPtr();
while (mStream->GetI1())
;
// find the index of the material
unsigned int idx = 0xcdcdcdcd, cnt = 0;
for (std::vector<D3DS::Material>::const_iterator i = mScene->mMaterials.begin(); i != mScene->mMaterials.end(); ++i, ++cnt) {
for (auto i = mScene->mMaterials.begin(); i != mScene->mMaterials.end(); ++i, ++cnt) {
// use case independent comparisons. hopefully it will work.
if ((*i).mName.length() && !ASSIMP_stricmp(sz, (*i).mName.c_str())) {
if (i->mName.length() && !ASSIMP_stricmp(sz, i->mName.c_str())) {
idx = cnt;
break;
}
@@ -928,9 +925,9 @@ void Discreet3DSImporter::ParseFaceChunk() {
}
// Now continue and read all material indices
cnt = (uint16_t)stream->GetI2();
cnt = (uint16_t)mStream->GetI2();
for (unsigned int i = 0; i < cnt; ++i) {
unsigned int fidx = (uint16_t)stream->GetI2();
unsigned int fidx = (uint16_t)mStream->GetI2();
// check range
if (fidx >= mMesh.mFaceMaterials.size()) {
@@ -955,59 +952,59 @@ void Discreet3DSImporter::ParseMeshChunk() {
switch (chunk.Flag) {
case Discreet3DS::CHUNK_VERTLIST: {
// This is the list of all vertices in the current mesh
int num = (int)(uint16_t)stream->GetI2();
int num = (int)(uint16_t)mStream->GetI2();
mMesh.mPositions.reserve(num);
while (num-- > 0) {
aiVector3D v;
v.x = stream->GetF4();
v.y = stream->GetF4();
v.z = stream->GetF4();
v.x = mStream->GetF4();
v.y = mStream->GetF4();
v.z = mStream->GetF4();
mMesh.mPositions.push_back(v);
}
} break;
case Discreet3DS::CHUNK_TRMATRIX: {
// This is the RLEATIVE transformation matrix of the current mesh. Vertices are
// pretransformed by this matrix wonder.
mMesh.mMat.a1 = stream->GetF4();
mMesh.mMat.b1 = stream->GetF4();
mMesh.mMat.c1 = stream->GetF4();
mMesh.mMat.a2 = stream->GetF4();
mMesh.mMat.b2 = stream->GetF4();
mMesh.mMat.c2 = stream->GetF4();
mMesh.mMat.a3 = stream->GetF4();
mMesh.mMat.b3 = stream->GetF4();
mMesh.mMat.c3 = stream->GetF4();
mMesh.mMat.a4 = stream->GetF4();
mMesh.mMat.b4 = stream->GetF4();
mMesh.mMat.c4 = stream->GetF4();
mMesh.mMat.a1 = mStream->GetF4();
mMesh.mMat.b1 = mStream->GetF4();
mMesh.mMat.c1 = mStream->GetF4();
mMesh.mMat.a2 = mStream->GetF4();
mMesh.mMat.b2 = mStream->GetF4();
mMesh.mMat.c2 = mStream->GetF4();
mMesh.mMat.a3 = mStream->GetF4();
mMesh.mMat.b3 = mStream->GetF4();
mMesh.mMat.c3 = mStream->GetF4();
mMesh.mMat.a4 = mStream->GetF4();
mMesh.mMat.b4 = mStream->GetF4();
mMesh.mMat.c4 = mStream->GetF4();
} break;
case Discreet3DS::CHUNK_MAPLIST: {
// This is the list of all UV coords in the current mesh
int num = (int)(uint16_t)stream->GetI2();
int num = (int)(uint16_t)mStream->GetI2();
mMesh.mTexCoords.reserve(num);
while (num-- > 0) {
aiVector3D v;
v.x = stream->GetF4();
v.y = stream->GetF4();
v.x = mStream->GetF4();
v.y = mStream->GetF4();
mMesh.mTexCoords.push_back(v);
}
} break;
case Discreet3DS::CHUNK_FACELIST: {
// This is the list of all faces in the current mesh
int num = (int)(uint16_t)stream->GetI2();
int num = (int)(uint16_t)mStream->GetI2();
mMesh.mFaces.reserve(num);
while (num-- > 0) {
// 3DS faces are ALWAYS triangles
mMesh.mFaces.emplace_back();
D3DS::Face &sFace = mMesh.mFaces.back();
Face &sFace = mMesh.mFaces.back();
sFace.mIndices[0] = (uint16_t)stream->GetI2();
sFace.mIndices[1] = (uint16_t)stream->GetI2();
sFace.mIndices[2] = (uint16_t)stream->GetI2();
sFace.mIndices[0] = (uint16_t)mStream->GetI2();
sFace.mIndices[1] = (uint16_t)mStream->GetI2();
sFace.mIndices[2] = (uint16_t)mStream->GetI2();
stream->IncPtr(2); // skip edge visibility flag
mStream->IncPtr(2); // skip edge visibility flag
}
// Resize the material array (0xcdcdcdcd marks the default material; so if a face is
@@ -1015,7 +1012,7 @@ void Discreet3DSImporter::ParseMeshChunk() {
mMesh.mFaceMaterials.resize(mMesh.mFaces.size(), 0xcdcdcdcd);
// Larger 3DS files could have multiple FACE chunks here
chunkSize = (int)stream->GetRemainingSizeToLimit();
chunkSize = (int)mStream->GetRemainingSizeToLimit();
if (chunkSize > (int)sizeof(Discreet3DS::Chunk))
ParseFaceChunk();
} break;
@@ -1032,9 +1029,9 @@ void Discreet3DSImporter::ParseMaterialChunk() {
{
// The material name string is already zero-terminated, but we need to be sure ...
const char *sz = (const char *)stream->GetPtr();
const char *sz = (const char *)mStream->GetPtr();
unsigned int cnt = 0;
while (stream->GetI1())
while (mStream->GetI1())
++cnt;
if (!cnt) {
@@ -1102,7 +1099,7 @@ void Discreet3DSImporter::ParseMaterialChunk() {
case Discreet3DS::CHUNK_MAT_SHADING:
// This is the material shading mode
mScene->mMaterials.back().mShading = (D3DS::Discreet3DS::shadetype3ds)stream->GetI2();
mScene->mMaterials.back().mShading = (Discreet3DS::shadetype3ds)mStream->GetI2();
break;
case Discreet3DS::CHUNK_MAT_TWO_SIDE:
@@ -1178,31 +1175,31 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture *pcOut) {
switch (chunk.Flag) {
case Discreet3DS::CHUNK_MAPFILE: {
// The material name string is already zero-terminated, but we need to be sure ...
const char *sz = (const char *)stream->GetPtr();
const char *sz = (const char *)mStream->GetPtr();
unsigned int cnt = 0;
while (stream->GetI1())
while (mStream->GetI1())
++cnt;
pcOut->mMapName = std::string(sz, cnt);
} break;
case Discreet3DS::CHUNK_PERCENTD:
// Manually parse the blend factor
pcOut->mTextureBlend = ai_real(stream->GetF8());
pcOut->mTextureBlend = ai_real(mStream->GetF8());
break;
case Discreet3DS::CHUNK_PERCENTF:
// Manually parse the blend factor
pcOut->mTextureBlend = stream->GetF4();
pcOut->mTextureBlend = mStream->GetF4();
break;
case Discreet3DS::CHUNK_PERCENTW:
// Manually parse the blend factor
pcOut->mTextureBlend = (ai_real)((uint16_t)stream->GetI2()) / ai_real(100.0);
pcOut->mTextureBlend = (ai_real)((uint16_t) mStream->GetI2()) / ai_real(100.0);
break;
case Discreet3DS::CHUNK_MAT_MAP_USCALE:
// Texture coordinate scaling in the U direction
pcOut->mScaleU = stream->GetF4();
pcOut->mScaleU = mStream->GetF4();
if (0.0f == pcOut->mScaleU) {
ASSIMP_LOG_WARN("Texture coordinate scaling in the x direction is zero. Assuming 1.");
pcOut->mScaleU = 1.0f;
@@ -1210,7 +1207,7 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture *pcOut) {
break;
case Discreet3DS::CHUNK_MAT_MAP_VSCALE:
// Texture coordinate scaling in the V direction
pcOut->mScaleV = stream->GetF4();
pcOut->mScaleV = mStream->GetF4();
if (0.0f == pcOut->mScaleV) {
ASSIMP_LOG_WARN("Texture coordinate scaling in the y direction is zero. Assuming 1.");
pcOut->mScaleV = 1.0f;
@@ -1219,21 +1216,21 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture *pcOut) {
case Discreet3DS::CHUNK_MAT_MAP_UOFFSET:
// Texture coordinate offset in the U direction
pcOut->mOffsetU = -stream->GetF4();
pcOut->mOffsetU = -mStream->GetF4();
break;
case Discreet3DS::CHUNK_MAT_MAP_VOFFSET:
// Texture coordinate offset in the V direction
pcOut->mOffsetV = stream->GetF4();
pcOut->mOffsetV = mStream->GetF4();
break;
case Discreet3DS::CHUNK_MAT_MAP_ANG:
// Texture coordinate rotation, CCW in DEGREES
pcOut->mRotation = -AI_DEG_TO_RAD(stream->GetF4());
pcOut->mRotation = -AI_DEG_TO_RAD(mStream->GetF4());
break;
case Discreet3DS::CHUNK_MAT_MAP_TILING: {
const uint16_t iFlags = stream->GetI2();
const uint16_t iFlags = mStream->GetI2();
// Get the mapping mode (for both axes)
if (iFlags & 0x2u)
@@ -1258,9 +1255,11 @@ ai_real Discreet3DSImporter::ParsePercentageChunk() {
ReadChunk(&chunk);
if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag) {
return stream->GetF4() * ai_real(100) / ai_real(0xFFFF);
} else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) {
return (ai_real)((uint16_t)stream->GetI2()) / (ai_real)0xFFFF;
return mStream->GetF4() * ai_real(100) / ai_real(0xFFFF);
}
if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) {
return (ai_real)((uint16_t)mStream->GetI2()) / (ai_real)0xFFFF;
}
return get_qnan();
@@ -1291,9 +1290,9 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D *out, bool acceptPercent) {
*out = clrError;
return;
}
out->r = stream->GetF4();
out->g = stream->GetF4();
out->b = stream->GetF4();
out->r = mStream->GetF4();
out->g = mStream->GetF4();
out->b = mStream->GetF4();
break;
case Discreet3DS::CHUNK_LINRGBB:
@@ -1305,15 +1304,15 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D *out, bool acceptPercent) {
return;
}
const ai_real invVal = ai_real(1.0) / ai_real(255.0);
out->r = (ai_real)(uint8_t)stream->GetI1() * invVal;
out->g = (ai_real)(uint8_t)stream->GetI1() * invVal;
out->b = (ai_real)(uint8_t)stream->GetI1() * invVal;
out->r = (ai_real)(uint8_t)mStream->GetI1() * invVal;
out->g = (ai_real)(uint8_t)mStream->GetI1() * invVal;
out->b = (ai_real)(uint8_t)mStream->GetI1() * invVal;
} break;
// Percentage chunks are accepted, too.
case Discreet3DS::CHUNK_PERCENTF:
if (acceptPercent && 4 <= diff) {
out->g = out->b = out->r = stream->GetF4();
out->g = out->b = out->r = mStream->GetF4();
break;
}
*out = clrError;
@@ -1321,14 +1320,14 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D *out, bool acceptPercent) {
case Discreet3DS::CHUNK_PERCENTW:
if (acceptPercent && 1 <= diff) {
out->g = out->b = out->r = (ai_real)(uint8_t)stream->GetI1() / ai_real(255.0);
out->g = out->b = out->r = (ai_real)(uint8_t)mStream->GetI1() / ai_real(255.0);
break;
}
*out = clrError;
return;
default:
stream->IncPtr(diff);
mStream->IncPtr(diff);
// Skip unknown chunks, hope this won't cause any problems.
return ParseColorChunk(out, acceptPercent);
};
+27 -41
View File
@@ -1,10 +1,8 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -51,20 +49,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/BaseImporter.h>
#include <assimp/types.h>
#include "3DSHelper.h"
#include <assimp/StreamReader.h>
struct aiNode;
namespace Assimp {
using namespace D3DS;
namespace Assimp {
// ---------------------------------------------------------------------------------
/** Importer class for 3D Studio r3 and r4 3DS files
*/
class Discreet3DSImporter : public BaseImporter {
class Discreet3DSImporter final : public BaseImporter {
public:
Discreet3DSImporter();
~Discreet3DSImporter() override = default;
@@ -101,15 +96,14 @@ protected:
// -------------------------------------------------------------------
/** Converts a temporary material to the outer representation
*/
void ConvertMaterial(D3DS::Material& p_cMat,
aiMaterial& p_pcOut);
void ConvertMaterial(D3DS::Material& p_cMat, aiMaterial& p_pcOut);
// -------------------------------------------------------------------
/** Read a chunk
*
* @param pcOut Receives the current chunk
*/
void ReadChunk(Discreet3DS::Chunk* pcOut);
void ReadChunk(D3DS::Discreet3DS::Chunk* pcOut);
// -------------------------------------------------------------------
/** Parse a percentage chunk. mCurrent will point to the next
@@ -119,13 +113,10 @@ protected:
ai_real ParsePercentageChunk();
// -------------------------------------------------------------------
/** Parse a color chunk. mCurrent will point to the next
* chunk behind afterwards. If no color chunk is found
* QNAN is returned in all members.
*/
void ParseColorChunk(aiColor3D* p_pcOut,
bool p_bAcceptPercent = true);
/** Parse a color chunk. mCurrent will point to the next chunk behind
* afterward. If no color chunk is found QNAN is returned in all members.
*/
void ParseColorChunk(aiColor3D* p_pcOut, bool p_bAcceptPercent = true);
// -------------------------------------------------------------------
/** Skip a chunk in the file
@@ -133,7 +124,7 @@ protected:
void SkipChunk();
// -------------------------------------------------------------------
/** Generate the nodegraph
/** Generate the node-graph
*/
void GenerateNodeGraph(aiScene* pcOut);
@@ -229,19 +220,19 @@ protected:
// -------------------------------------------------------------------
/** Add a node to the node graph
*/
void AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut,D3DS::Node* pcIn,
void AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut, D3DS::Node* pcIn,
aiMatrix4x4& absTrafo);
// -------------------------------------------------------------------
/** Search for a node in the graph.
* Called recursively
*/
void InverseNodeSearch(D3DS::Node* pcNode,D3DS::Node* pcCurrent);
void InverseNodeSearch(D3DS::Node* pcNode, D3DS::Node* pcCurrent);
// -------------------------------------------------------------------
/** Apply the master scaling factor to the mesh
*/
void ApplyMasterScale(aiScene* pScene);
void ApplyMasterScale(const aiScene* pScene);
// -------------------------------------------------------------------
/** Clamp all indices in the file to a valid range
@@ -253,31 +244,26 @@ protected:
*/
void SkipTCBInfo();
protected:
/** Stream to read from */
StreamReaderLE* stream;
/** Last touched node index */
private:
/// Stream to read from
StreamReaderLE* mStream;
/// Last touched node index
short mLastNodeIndex;
/** Current node, root node */
D3DS::Node* mCurrentNode, *mRootNode;
/** Scene under construction */
/// Current node
D3DS::Node* mCurrentNode;
/// Root node
D3DS::Node *mRootNode;
/// Scene under construction
D3DS::Scene* mScene;
/** Ambient base color of the scene */
/// Ambient base color of the scene
aiColor3D mClrAmbient;
/** Master scaling factor of the scene */
/// Master scaling factor of the scene
ai_real mMasterScale;
/** Path to the background image of the scene */
/// Path to the background image of the scene
std::string mBackgroundImage;
/// true for has a background
bool bHasBG;
/** true if PRJ file */
/// true if PRJ file
bool bIsPrj;
};
+17 -27
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -49,8 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
struct aiMaterial;
struct aiMesh;
namespace Assimp {
namespace D3MF {
namespace Assimp:: D3MF {
enum class ResourceType {
RT_Object,
@@ -65,8 +64,7 @@ class Resource {
public:
int mId;
Resource(int id) :
mId(id) {
explicit Resource(int id) : mId(id) {
// empty
}
@@ -77,7 +75,7 @@ public:
}
};
class EmbeddedTexture : public Resource {
class EmbeddedTexture final : public Resource {
public:
std::string mPath;
std::string mContentType;
@@ -85,12 +83,7 @@ public:
std::string mTilestyleV;
std::vector<char> mBuffer;
EmbeddedTexture(int id) :
Resource(id),
mPath(),
mContentType(),
mTilestyleU(),
mTilestyleV() {
explicit EmbeddedTexture(int id) : Resource(id) {
// empty
}
@@ -101,13 +94,12 @@ public:
}
};
class Texture2DGroup : public Resource {
class Texture2DGroup final : public Resource {
public:
std::vector<aiVector2D> mTex2dCoords;
int mTexId;
Texture2DGroup(int id) :
Resource(id),
mTexId(-1) {
explicit Texture2DGroup(int id) : Resource(id), mTexId(-1) {
// empty
}
@@ -118,11 +110,11 @@ public:
}
};
class ColorGroup : public Resource {
class ColorGroup final : public Resource {
public:
std::vector<aiColor4D> mColors;
ColorGroup(int id) :
Resource(id){
explicit ColorGroup(int id) : Resource(id) {
// empty
}
@@ -133,13 +125,11 @@ public:
}
};
class BaseMaterials : public Resource {
class BaseMaterials final : public Resource {
public:
std::vector<unsigned int> mMaterialIndex;
BaseMaterials(int id) :
Resource(id),
mMaterialIndex() {
explicit BaseMaterials(int id) : Resource(id) {
// empty
}
@@ -153,16 +143,17 @@ public:
struct Component {
int mObjectId;
aiMatrix4x4 mTransformation;
std::string mPath; // production extension: external model file, empty = same file
};
class Object : public Resource {
class Object final : public Resource {
public:
std::vector<aiMesh *> mMeshes;
std::vector<unsigned int> mMeshIndex;
std::vector<Component> mComponents;
std::string mName;
Object(int id) :
explicit Object(int id) :
Resource(id),
mName(std::string("Object_") + ai_to_string(id)) {
// empty
@@ -175,5 +166,4 @@ public:
}
};
} // namespace D3MF
} // namespace Assimp
} // namespace Assimp::D3MF
+69 -71
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -40,85 +40,83 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
namespace Assimp {
namespace D3MF {
namespace XmlTag {
namespace Assimp::D3MF::XmlTag {
// Root tag
const char* const RootTag = "3MF";
constexpr char RootTag[] = "3MF";
// Meta-data
const char* const meta = "metadata";
const char* const meta_name = "name";
constexpr char meta[] = "metadata";
constexpr char meta_name[] = "name";
// Model-data specific tags
const char* const model = "model";
const char* const model_unit = "unit";
const char* const metadata = "metadata";
const char* const resources = "resources";
const char* const object = "object";
const char* const mesh = "mesh";
const char* const components = "components";
const char* const component = "component";
const char* const vertices = "vertices";
const char* const vertex = "vertex";
const char* const triangles = "triangles";
const char* const triangle = "triangle";
const char* const x = "x";
const char* const y = "y";
const char* const z = "z";
const char* const v1 = "v1";
const char* const v2 = "v2";
const char* const v3 = "v3";
const char* const id = "id";
const char* const pid = "pid";
const char* const pindex = "pindex";
const char* const p1 = "p1";
const char *const p2 = "p2";
const char *const p3 = "p3";
const char* const name = "name";
const char* const type = "type";
const char* const build = "build";
const char* const item = "item";
const char* const objectid = "objectid";
const char* const transform = "transform";
const char *const path = "path";
constexpr char model[] = "model";
constexpr char model_unit[] = "unit";
constexpr char metadata[] = "metadata";
constexpr char resources[] = "resources";
constexpr char object[] = "object";
constexpr char mesh[] = "mesh";
constexpr char components[] = "components";
constexpr char component[] = "component";
constexpr char vertices[] = "vertices";
constexpr char vertex[] = "vertex";
constexpr char triangles[] = "triangles";
constexpr char triangle[] = "triangle";
constexpr char x[] = "x";
constexpr char y[] = "y";
constexpr char z[] = "z";
constexpr char v1[] = "v1";
constexpr char v2[] = "v2";
constexpr char v3[] = "v3";
constexpr char id[] = "id";
constexpr char pid[] = "pid";
constexpr char pindex[] = "pindex";
constexpr char p1[] = "p1";
constexpr char p2[] = "p2";
constexpr char p3[] = "p3";
constexpr char name[] = "name";
constexpr char type[] = "type";
constexpr char build[] = "build";
constexpr char item[] = "item";
constexpr char objectid[] = "objectid";
constexpr char transform[] = "transform";
constexpr char path[] = "path";
// Production extension (namespace prefix "p" by convention)
constexpr char p_path[] = "p:path";
// Material definitions
const char* const basematerials = "basematerials";
const char* const basematerials_base = "base";
const char* const basematerials_name = "name";
const char* const basematerials_displaycolor = "displaycolor";
const char* const texture_2d = "m:texture2d";
const char *const texture_group = "m:texture2dgroup";
const char *const texture_content_type = "contenttype";
const char *const texture_tilestyleu = "tilestyleu";
const char *const texture_tilestylev = "tilestylev";
const char *const texture_2d_coord = "m:tex2coord";
const char *const texture_cuurd_u = "u";
const char *const texture_cuurd_v = "v";
constexpr char basematerials[] = "basematerials";
constexpr char basematerials_base[] = "base";
constexpr char basematerials_name[] = "name";
constexpr char basematerials_displaycolor[] = "displaycolor";
constexpr char texture_2d[] = "m:texture2d";
constexpr char texture_group[] = "m:texture2dgroup";
constexpr char texture_content_type[] = "contenttype";
constexpr char texture_tilestyleu[] = "tilestyleu";
constexpr char texture_tilestylev[] = "tilestylev";
constexpr char texture_2d_coord[] = "m:tex2coord";
constexpr char texture_cuurd_u[] = "u";
constexpr char texture_cuurd_v[] = "v";
// vertex color definitions
const char *const colorgroup = "m:colorgroup";
const char *const color_item = "m:color";
const char *const color_vaule = "color";
constexpr char colorgroup[] = "m:colorgroup";
constexpr char color_item[] = "m:color";
constexpr char color_value[] = "color";
// Meta info tags
const char* const CONTENT_TYPES_ARCHIVE = "[Content_Types].xml";
const char* const ROOT_RELATIONSHIPS_ARCHIVE = "_rels/.rels";
const char* const SCHEMA_CONTENTTYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
const char* const SCHEMA_RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
const char* const RELS_RELATIONSHIP_CONTAINER = "Relationships";
const char* const RELS_RELATIONSHIP_NODE = "Relationship";
const char* const RELS_ATTRIB_TARGET = "Target";
const char* const RELS_ATTRIB_TYPE = "Type";
const char* const RELS_ATTRIB_ID = "Id";
const char* const PACKAGE_START_PART_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
const char* const PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket";
const char* const PACKAGE_TEXTURE_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";
const char* const PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
const char* const PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
}
constexpr char CONTENT_TYPES_ARCHIVE[] = "[Content_Types].xml";
constexpr char ROOT_RELATIONSHIPS_ARCHIVE[] = "_rels/.rels";
constexpr char SCHEMA_CONTENTTYPES[] = "http://schemas.openxmlformats.org/package/2006/content-types";
constexpr char SCHEMA_RELATIONSHIPS[] = "http://schemas.openxmlformats.org/package/2006/relationships";
constexpr char RELS_RELATIONSHIP_CONTAINER[] = "Relationships";
constexpr char RELS_RELATIONSHIP_NODE[] = "Relationship";
constexpr char RELS_ATTRIB_TARGET[] = "Target";
constexpr char RELS_ATTRIB_TYPE[] = "Type";
constexpr char RELS_ATTRIB_ID[] = "Id";
constexpr char PACKAGE_START_PART_RELATIONSHIP_TYPE[] = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
constexpr char PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE[] = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket";
constexpr char PACKAGE_TEXTURE_RELATIONSHIP_TYPE[] = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";
constexpr char PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE[] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
constexpr char PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE[] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
} // Namespace D3MF
} // Namespace Assimp
} // namespace Assimp::D3MF
+6 -7
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -48,7 +48,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include "3MFXmlTags.h"
@@ -94,7 +93,7 @@ D3MFExporter::~D3MFExporter() {
mRelations.clear();
}
bool D3MFExporter::validate() {
bool D3MFExporter::validate() const {
if (mArchiveName.empty()) {
return false;
}
@@ -249,10 +248,10 @@ void D3MFExporter::writeBaseMaterials() {
if (color.r <= 1 && color.g <= 1 && color.b <= 1 && color.a <= 1) {
hexDiffuseColor = ai_rgba2hex(
(int)((ai_real)color.r) * 255,
(int)((ai_real)color.g) * 255,
(int)((ai_real)color.b) * 255,
(int)((ai_real)color.a) * 255,
(int)(((ai_real)color.r) * 255),
(int)(((ai_real)color.g) * 255),
(int)(((ai_real)color.b) * 255),
(int)(((ai_real)color.a) * 255),
true);
} else {
+2 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -68,7 +68,7 @@ class D3MFExporter {
public:
D3MFExporter( const char* pFile, const aiScene* pScene );
~D3MFExporter();
bool validate();
bool validate() const;
bool exportArchive( const char *file );
bool exportContentTypes();
bool exportRelations();
+3 -3
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -85,7 +85,7 @@ bool D3MFImporter::CanRead(const std::string &filename, IOSystem *pIOHandler, bo
if (!ZipArchiveIOSystem::isZipArchive(pIOHandler, filename)) {
return false;
}
static const char *const ModelRef = "3D/3dmodel.model";
static constexpr char ModelRef[] = "3D/3dmodel.model";
ZipArchiveIOSystem archive(pIOHandler, filename);
if (!archive.Exists(ModelRef)) {
return false;
@@ -107,7 +107,7 @@ void D3MFImporter::InternReadFile(const std::string &filename, aiScene *pScene,
XmlParser xmlParser;
if (xmlParser.parse(opcPackage.RootStream())) {
XmlSerializer xmlSerializer(&xmlParser);
XmlSerializer xmlSerializer(xmlParser, &opcPackage);
xmlSerializer.ImportXml(pScene);
const std::vector<aiTexture*> &tex = opcPackage.GetEmbeddedTextures();
+2 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -53,7 +53,7 @@ namespace Assimp {
///
/// Implements the basic topology import and embedded textures.
// ---------------------------------------------------------------------------
class D3MFImporter : public BaseImporter {
class D3MFImporter final : public BaseImporter {
public:
/// @brief The default class constructor.
D3MFImporter() = default;
+39 -12
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -65,10 +65,9 @@ namespace D3MF {
using OpcPackageRelationshipPtr = std::shared_ptr<OpcPackageRelationship>;
class OpcPackageRelationshipReader {
class OpcPackageRelationshipReader final {
public:
OpcPackageRelationshipReader(XmlParser &parser) :
mRelations() {
explicit OpcPackageRelationshipReader(XmlParser &parser) : mRelations() {
XmlNode root = parser.getRootNode();
ParseRootNode(root);
}
@@ -132,6 +131,7 @@ static bool IsEmbeddedTexture( const std::string &filename ) {
// ------------------------------------------------------------------------------------------------
D3MFOpcPackage::D3MFOpcPackage(IOSystem *pIOHandler, const std::string &rFile) :
mRootStream(nullptr),
mRootPath(),
mZipArchive() {
mZipArchive = new ZipArchiveIOSystem(pIOHandler, rFile);
if (!mZipArchive->isOpen()) {
@@ -153,19 +153,13 @@ D3MFOpcPackage::D3MFOpcPackage(IOSystem *pIOHandler, const std::string &rFile) :
continue;
}
std::string rootFile = ReadPackageRootRelationship(fileStream);
if (!rootFile.empty() && rootFile[0] == '/') {
rootFile = rootFile.substr(1);
if (rootFile[0] == '/') {
// deal with zip-bug
rootFile = rootFile.substr(1);
}
}
std::string rootFile = NormalizePath(ReadPackageRootRelationship(fileStream));
ASSIMP_LOG_VERBOSE_DEBUG(rootFile);
mZipArchive->Close(fileStream);
mRootPath = rootFile;
mRootStream = mZipArchive->Open(rootFile.c_str());
ai_assert(mRootStream != nullptr);
if (nullptr == mRootStream) {
@@ -177,6 +171,12 @@ D3MFOpcPackage::D3MFOpcPackage(IOSystem *pIOHandler, const std::string &rFile) :
IOStream *fileStream = mZipArchive->Open(file.c_str());
LoadEmbeddedTextures(fileStream, file);
mZipArchive->Close(fileStream);
} else if (BaseImporter::GetExtension(file) == "model") {
// Production-extension model parts are opened on demand via OpenPart().
ASSIMP_LOG_VERBOSE_DEBUG("Referenced model part: ", file);
} else if (BaseImporter::GetExtension(file) == "rels") {
// Relationship parts of referenced model files; resolved via path attributes.
ASSIMP_LOG_VERBOSE_DEBUG("Relationship part: ", file);
} else {
ASSIMP_LOG_WARN("Ignored file of unknown type: ", file);
}
@@ -192,6 +192,33 @@ IOStream *D3MFOpcPackage::RootStream() const {
return mRootStream;
}
const std::string &D3MFOpcPackage::RootPath() const {
return mRootPath;
}
std::string D3MFOpcPackage::NormalizePath(const std::string &path) {
size_t pos = 0;
while (pos < path.size() && path[pos] == '/') {
++pos;
}
return path.substr(pos);
}
IOStream *D3MFOpcPackage::OpenPart(const std::string &path) {
const std::string normalized = NormalizePath(path);
if (normalized.empty() || !mZipArchive->Exists(normalized.c_str())) {
return nullptr;
}
return mZipArchive->Open(normalized.c_str());
}
void D3MFOpcPackage::CloseStream(IOStream *stream) {
if (nullptr != stream) {
mZipArchive->Close(stream);
}
}
const std::vector<aiTexture *> &D3MFOpcPackage::GetEmbeddedTextures() const {
return mEmbeddedTextures;
}
+10 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -65,6 +65,14 @@ public:
D3MFOpcPackage( IOSystem* pIOHandler, const std::string& file );
~D3MFOpcPackage();
IOStream* RootStream() const;
/// @brief Absolute path of the root model part inside the container (production extension).
const std::string &RootPath() const;
/// @brief Open an arbitrary model part referenced via a production-extension path attribute.
/// The returned stream must be released with CloseStream(). Returns nullptr if missing.
IOStream *OpenPart(const std::string &path);
void CloseStream(IOStream *stream);
/// @brief Strip leading slashes so an OPC absolute path matches the zip entry name.
static std::string NormalizePath(const std::string &path);
bool validate();
const std::vector<aiTexture*> &GetEmbeddedTextures() const;
@@ -74,6 +82,7 @@ protected:
private:
IOStream* mRootStream;
std::string mRootPath;
ZipArchiveIOSystem *mZipArchive;
std::vector<aiTexture *> mEmbeddedTextures;
};
+190 -79
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -43,7 +43,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "3MFXmlTags.h"
#include "3MFTypes.h"
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <set>
#include <utility>
namespace Assimp {
@@ -57,8 +59,8 @@ static constexpr size_t ColRGBA_Len = 9;
static constexpr size_t ColRGB_Len = 7;
// format of the color string: #RRGGBBAA or #RRGGBB (3MF Core chapter 5.1.1)
bool validateColorString(const char *color) {
const size_t len = strlen(color);
bool validateColorString(const std::string color) {
const size_t len = color.size();
if (ColRGBA_Len != len && ColRGB_Len != len) {
return false;
}
@@ -120,8 +122,7 @@ aiMatrix4x4 parseTransformMatrix(const std::string& matrixStr) {
for (char c : matrixStr) {
if (c == ' ') {
if (!currentNumber.empty()) {
float f = std::stof(currentNumber);
numbers.push_back(f);
numbers.push_back(ai_strtof(currentNumber.c_str(), nullptr));
currentNumber.clear();
}
} else {
@@ -129,8 +130,14 @@ aiMatrix4x4 parseTransformMatrix(const std::string& matrixStr) {
}
}
if (!currentNumber.empty()) {
const float f = std::stof(currentNumber);
numbers.push_back(f);
numbers.push_back(ai_strtof(currentNumber.c_str(), nullptr));
}
// A 3MF transform is a row-major 4x3 affine matrix (3MF Core 3.3); the implicit
// fourth column is (0,0,0,1). Anything shorter is malformed, so fall back to identity.
constexpr size_t AffineMatrixValueCount = 12;
if (numbers.size() < AffineMatrixValueCount) {
return aiMatrix4x4();
}
aiMatrix4x4 transformMatrix;
@@ -157,8 +164,8 @@ aiMatrix4x4 parseTransformMatrix(const std::string& matrixStr) {
return transformMatrix;
}
bool parseColor(const char *color, aiColor4D &diffuse) {
if (nullptr == color) {
bool parseColor(const std::string &color, aiColor4D &diffuse) {
if (color.empty()) {
return false;
}
@@ -178,7 +185,7 @@ bool parseColor(const char *color, aiColor4D &diffuse) {
char b[3] = { color[5], color[6], '\0' };
diffuse.b = static_cast<ai_real>(strtol(b, nullptr, 16)) / ai_real(255.0);
const size_t len = strlen(color);
const size_t len = color.size();
if (ColRGB_Len == len) {
return true;
}
@@ -199,31 +206,27 @@ void assignDiffuseColor(XmlNode &node, aiMaterial *mat) {
} // namespace
XmlSerializer::XmlSerializer(XmlParser *xmlParser) :
mResourcesDictionnary(),
XmlSerializer::XmlSerializer(XmlParser &xmlParser, D3MFOpcPackage *package) :
mResourcesByFile(),
mCurrentResources(nullptr),
mMeshCount(0),
mXmlParser(xmlParser) {
ai_assert(nullptr != xmlParser);
mXmlParser(xmlParser),
mPackage(package) {
// empty
}
XmlSerializer::~XmlSerializer() {
for (auto &it : mResourcesDictionnary) {
delete it.second;
for (auto &file : mResourcesByFile) {
for (auto &it : file.second) {
delete it.second;
}
}
}
void XmlSerializer::ImportXml(aiScene *scene) {
if (nullptr == scene) {
return;
}
void XmlSerializer::ReadModel(XmlNode &modelNode, const std::string &fileKey) {
mCurrentResources = &mResourcesByFile[fileKey];
scene->mRootNode = new aiNode(XmlTag::RootTag);
XmlNode node = mXmlParser->getRootNode().child(XmlTag::model);
if (node.empty()) {
return;
}
XmlNode resNode = node.child(XmlTag::resources);
XmlNode resNode = modelNode.child(XmlTag::resources);
for (auto &currentNode : resNode.children()) {
const std::string currentNodeName = currentNode.name();
if (currentNodeName == XmlTag::texture_2d) {
@@ -240,29 +243,110 @@ void XmlSerializer::ImportXml(aiScene *scene) {
ReadColorGroup(currentNode);
}
}
StoreMaterialsInScene(scene);
XmlNode buildNode = node.child(XmlTag::build);
if (buildNode.empty()) {
}
void XmlSerializer::LoadModelFile(const std::string &path) {
if (path.empty() || nullptr == mPackage) {
return;
}
// Already loaded (e.g. the root file, or referenced from multiple places).
if (mResourcesByFile.find(path) != mResourcesByFile.end()) {
return;
}
for (auto &currentNode : buildNode.children()) {
const std::string currentNodeName = currentNode.name();
if (currentNodeName == XmlTag::item) {
int objectId = IdNotSet;
std::string transformationMatrixStr;
aiMatrix4x4 transformationMatrix;
getNodeAttribute(currentNode, D3MF::XmlTag::objectid, objectId);
bool hasTransform = getNodeAttribute(currentNode, D3MF::XmlTag::transform, transformationMatrixStr);
IOStream *stream = mPackage->OpenPart(path);
if (nullptr == stream) {
ASSIMP_LOG_WARN("3MF: cannot open referenced model part: ", path);
return;
}
auto it = mResourcesDictionnary.find(objectId);
if (it != mResourcesDictionnary.end() && it->second->getType() == ResourceType::RT_Object) {
Object *obj = static_cast<Object *>(it->second);
if (hasTransform) {
transformationMatrix = parseTransformMatrix(transformationMatrixStr);
XmlParser parser;
if (parser.parse(stream)) {
XmlNode modelNode = parser.getRootNode().child(XmlTag::model);
if (!modelNode.empty()) {
// ReadObject copies all data into Object/aiMesh, so the parser may be
// discarded once the resources of this part have been read.
ReadModel(modelNode, path);
}
}
mPackage->CloseStream(stream);
}
void XmlSerializer::ImportXml(aiScene *scene) {
if (nullptr == scene) {
return;
}
scene->mRootNode = new aiNode(XmlTag::RootTag);
XmlNode node = mXmlParser.getRootNode().child(XmlTag::model);
if (node.empty()) {
return;
}
const std::string rootKey = (nullptr != mPackage) ? mPackage->RootPath() : std::string();
ReadModel(node, rootKey);
XmlNode buildNode = node.child(XmlTag::build);
// Production extension: build items and root-object components may reference objects
// in separate model parts via a path attribute. Load every referenced part now, before
// materials are copied into the scene, so material indices defined there stay valid.
std::set<std::string> referencedFiles;
if (!buildNode.empty()) {
for (auto &currentNode : buildNode.children()) {
if (std::string(currentNode.name()) == XmlTag::item) {
std::string path;
if (getNodeAttribute(currentNode, D3MF::XmlTag::p_path, path)) {
referencedFiles.insert(D3MFOpcPackage::NormalizePath(path));
}
}
}
}
auto rootIt = mResourcesByFile.find(rootKey);
if (rootIt != mResourcesByFile.end()) {
for (auto &it : rootIt->second) {
if (it.second->getType() == ResourceType::RT_Object) {
Object *obj = static_cast<Object *>(it.second);
for (const Component &c : obj->mComponents) {
if (!c.mPath.empty()) {
referencedFiles.insert(c.mPath);
}
}
}
}
}
for (const std::string &file : referencedFiles) {
LoadModelFile(file);
}
addObjectToNode(scene->mRootNode, obj, transformationMatrix);
StoreMaterialsInScene(scene);
if (!buildNode.empty()) {
for (auto &currentNode : buildNode.children()) {
const std::string currentNodeName = currentNode.name();
if (currentNodeName == XmlTag::item) {
int objectId = IdNotSet;
std::string transformationMatrixStr;
std::string itemPath;
aiMatrix4x4 transformationMatrix;
getNodeAttribute(currentNode, D3MF::XmlTag::objectid, objectId);
bool hasTransform = getNodeAttribute(currentNode, D3MF::XmlTag::transform, transformationMatrixStr);
bool hasPath = getNodeAttribute(currentNode, D3MF::XmlTag::p_path, itemPath);
const std::string fileKey = hasPath ? D3MFOpcPackage::NormalizePath(itemPath) : rootKey;
auto fileIt = mResourcesByFile.find(fileKey);
if (fileIt == mResourcesByFile.end()) {
continue;
}
auto it = fileIt->second.find(objectId);
if (it != fileIt->second.end() && it->second->getType() == ResourceType::RT_Object) {
Object *obj = static_cast<Object *>(it->second);
if (hasTransform) {
transformationMatrix = parseTransformMatrix(transformationMatrixStr);
}
addObjectToNode(scene->mRootNode, obj, transformationMatrix, fileKey);
}
}
}
}
@@ -277,23 +361,25 @@ void XmlSerializer::ImportXml(aiScene *scene) {
}
}
// import the meshes, materials are already stored
// import the meshes from every model part, materials are already stored
scene->mNumMeshes = static_cast<unsigned int>(mMeshCount);
if (scene->mNumMeshes != 0) {
scene->mMeshes = new aiMesh *[scene->mNumMeshes]();
for (auto &it : mResourcesDictionnary) {
if (it.second->getType() == ResourceType::RT_Object) {
Object *obj = static_cast<Object *>(it.second);
ai_assert(nullptr != obj);
for (unsigned int i = 0; i < obj->mMeshes.size(); ++i) {
scene->mMeshes[obj->mMeshIndex[i]] = obj->mMeshes[i];
for (auto &file : mResourcesByFile) {
for (auto &it : file.second) {
if (it.second->getType() == ResourceType::RT_Object) {
Object *obj = static_cast<Object *>(it.second);
ai_assert(nullptr != obj);
for (unsigned int i = 0; i < obj->mMeshes.size(); ++i) {
scene->mMeshes[obj->mMeshIndex[i]] = obj->mMeshes[i];
}
}
}
}
}
}
void XmlSerializer::addObjectToNode(aiNode *parent, Object *obj, aiMatrix4x4 nodeTransform) {
void XmlSerializer::addObjectToNode(aiNode *parent, Object *obj, const aiMatrix4x4 &nodeTransform, const std::string &fileKey) {
ai_assert(nullptr != obj);
aiNode *sceneNode = new aiNode(obj->mName);
@@ -306,10 +392,17 @@ void XmlSerializer::addObjectToNode(aiNode *parent, Object *obj, aiMatrix4x4 nod
parent->addChildren(1, &sceneNode);
}
for (Assimp::D3MF::Component c : obj->mComponents) {
auto it = mResourcesDictionnary.find(c.mObjectId);
if (it != mResourcesDictionnary.end() && it->second->getType() == ResourceType::RT_Object) {
addObjectToNode(sceneNode, static_cast<Object *>(it->second), c.mTransformation);
for (const Assimp::D3MF::Component &c : obj->mComponents) {
// A component without a path references an object in the same model part;
// with a path (production extension, already normalized) it references another part.
const std::string &childKey = c.mPath.empty() ? fileKey : c.mPath;
auto fileIt = mResourcesByFile.find(childKey);
if (fileIt == mResourcesByFile.end()) {
continue;
}
auto it = fileIt->second.find(c.mObjectId);
if (it != fileIt->second.end() && it->second->getType() == ResourceType::RT_Object) {
addObjectToNode(sceneNode, static_cast<Object *>(it->second), c.mTransformation, childKey);
}
}
}
@@ -332,13 +425,16 @@ void XmlSerializer::ReadObject(XmlNode &node) {
mesh->mName.Set(ai_to_string(id));
if (hasPid) {
auto it = mResourcesDictionnary.find(pid);
if (hasPindex && it != mResourcesDictionnary.end()) {
auto it = mCurrentResources->find(pid);
if (hasPindex && it != mCurrentResources->end()) {
if (it->second->getType() == ResourceType::RT_BaseMaterials) {
BaseMaterials *materials = static_cast<BaseMaterials *>(it->second);
mesh->mMaterialIndex = materials->mMaterialIndex[pindex];
if (pindex >= 0 && static_cast<size_t>(pindex) < materials->mMaterialIndex.size()) {
mesh->mMaterialIndex = materials->mMaterialIndex[pindex];
}
} else if (it->second->getType() == ResourceType::RT_Texture2DGroup) {
Texture2DGroup *group = static_cast<Texture2DGroup *>(it->second);
const bool pindexValid = pindex >= 0 && static_cast<size_t>(pindex) < group->mTex2dCoords.size();
if (mesh->mTextureCoords[0] == nullptr) {
mesh->mNumUVComponents[0] = 2;
for (unsigned int i = 1; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
@@ -353,11 +449,13 @@ void XmlSerializer::ReadObject(XmlNode &node) {
}
mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
for (unsigned int vertex_idx = 0; vertex_idx < mesh->mNumVertices; vertex_idx++) {
mesh->mTextureCoords[0][vertex_idx] =
aiVector3D(group->mTex2dCoords[pindex].x, group->mTex2dCoords[pindex].y, 0.0f);
if (pindexValid) {
for (unsigned int vertex_idx = 0; vertex_idx < mesh->mNumVertices; vertex_idx++) {
mesh->mTextureCoords[0][vertex_idx] =
aiVector3D(group->mTex2dCoords[pindex].x, group->mTex2dCoords[pindex].y, 0.0f);
}
}
} else {
} else if (pindexValid) {
for (unsigned int vertex_idx = 0; vertex_idx < mesh->mNumVertices; vertex_idx++) {
if (mesh->mTextureCoords[0][vertex_idx].z < 0) {
// use default
@@ -371,8 +469,10 @@ void XmlSerializer::ReadObject(XmlNode &node) {
mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
ColorGroup *group = static_cast<ColorGroup *>(it->second);
for (unsigned int vertex_idx = 0; vertex_idx < mesh->mNumVertices; vertex_idx++) {
mesh->mColors[0][vertex_idx] = group->mColors[pindex];
if (pindex >= 0 && static_cast<size_t>(pindex) < group->mColors.size()) {
for (unsigned int vertex_idx = 0; vertex_idx < mesh->mNumVertices; vertex_idx++) {
mesh->mColors[0][vertex_idx] = group->mColors[pindex];
}
}
}
}
@@ -393,15 +493,22 @@ void XmlSerializer::ReadObject(XmlNode &node) {
componentTransform = parseTransformMatrix(componentTransformStr);
}
// Production extension: a component may reference an object in another model
// part. Normalize the path once here so every later lookup can compare directly.
std::string componentPath;
if (getNodeAttribute(currentSubNode, D3MF::XmlTag::p_path, componentPath)) {
componentPath = D3MFOpcPackage::NormalizePath(componentPath);
}
if (getNodeAttribute(currentSubNode, D3MF::XmlTag::objectid, objectId)) {
obj->mComponents.push_back({ objectId, componentTransform });
obj->mComponents.push_back({ objectId, componentTransform, componentPath });
}
}
}
}
}
mResourcesDictionnary.insert(std::make_pair(id, obj));
mCurrentResources->insert(std::make_pair(id, obj));
}
aiMesh *XmlSerializer::ReadMesh(XmlNode &node) {
@@ -463,13 +570,13 @@ void XmlSerializer::ImportTriangles(XmlNode &node, aiMesh *mesh) {
int pindex[3];
aiFace face = ReadTriangle(currentNode, pindex[0], pindex[1], pindex[2]);
if (hasPid && (pindex[0] != IdNotSet || pindex[1] != IdNotSet || pindex[2] != IdNotSet)) {
auto it = mResourcesDictionnary.find(pid);
if (it != mResourcesDictionnary.end()) {
auto it = mCurrentResources->find(pid);
if (it != mCurrentResources->end()) {
if (it->second->getType() == ResourceType::RT_BaseMaterials) {
BaseMaterials *baseMaterials = static_cast<BaseMaterials *>(it->second);
auto update_material = [&](int idx) {
if (pindex[idx] != IdNotSet) {
if (pindex[idx] != IdNotSet && static_cast<size_t>(pindex[idx]) < baseMaterials->mMaterialIndex.size()) {
mesh->mMaterialIndex = baseMaterials->mMaterialIndex[pindex[idx]];
}
};
@@ -500,10 +607,12 @@ void XmlSerializer::ImportTriangles(XmlNode &node, aiMesh *mesh) {
}
auto update_texture = [&](int idx) {
if (pindex[idx] != IdNotSet) {
if (pindex[idx] != IdNotSet && static_cast<size_t>(pindex[idx]) < group->mTex2dCoords.size()) {
size_t vertex_index = face.mIndices[idx];
mesh->mTextureCoords[0][vertex_index] =
aiVector3D(group->mTex2dCoords[pindex[idx]].x, group->mTex2dCoords[pindex[idx]].y, 0.0f);
if (vertex_index < mesh->mNumVertices) {
mesh->mTextureCoords[0][vertex_index] =
aiVector3D(group->mTex2dCoords[pindex[idx]].x, group->mTex2dCoords[pindex[idx]].y, 0.0f);
}
}
};
@@ -519,9 +628,11 @@ void XmlSerializer::ImportTriangles(XmlNode &node, aiMesh *mesh) {
}
auto update_color = [&](int idx) {
if (pindex[idx] != IdNotSet) {
if (pindex[idx] != IdNotSet && static_cast<size_t>(pindex[idx]) < group->mColors.size()) {
size_t vertex_index = face.mIndices[idx];
mesh->mColors[0][vertex_index] = group->mColors[pindex[idx]];
if (vertex_index < mesh->mNumVertices) {
mesh->mColors[0][vertex_index] = group->mColors[pindex[idx]];
}
}
};
@@ -556,7 +667,7 @@ void XmlSerializer::ReadBaseMaterials(XmlNode &node) {
}
}
mResourcesDictionnary.insert(std::make_pair(id, baseMaterials));
mCurrentResources->insert(std::make_pair(id, baseMaterials));
}
}
@@ -643,7 +754,7 @@ void XmlSerializer::ReadTextureGroup(XmlNode &node) {
Texture2DGroup *group = new Texture2DGroup(id);
ReadTextureCoords2D(node, group);
mResourcesDictionnary.insert(std::make_pair(id, group));
mCurrentResources->insert(std::make_pair(id, group));
}
aiMaterial *XmlSerializer::readMaterialDef(XmlNode &node, unsigned int basematerialsId) {
@@ -680,7 +791,7 @@ void XmlSerializer::ReadColor(XmlNode &node, ColorGroup *colorGroup) {
for (XmlNode currentNode : node.children()) {
const std::string currentName = currentNode.name();
if (currentName == XmlTag::color_item) {
const char *color = currentNode.attribute(XmlTag::color_vaule).as_string();
const char *color = currentNode.attribute(XmlTag::color_value).as_string();
aiColor4D color_value;
if (parseColor(color, color_value)) {
colorGroup->mColors.push_back(color_value);
@@ -701,7 +812,7 @@ void XmlSerializer::ReadColorGroup(XmlNode &node) {
ColorGroup *group = new ColorGroup(id);
ReadColor(node, group);
mResourcesDictionnary.insert(std::make_pair(id, group));
mCurrentResources->insert(std::make_pair(id, group));
}
void XmlSerializer::StoreMaterialsInScene(aiScene *scene) {
+15 -6
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -44,6 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/mesh.h>
#include <vector>
#include <map>
#include <string>
struct aiNode;
struct aiMesh;
@@ -59,14 +60,17 @@ class Texture2DGroup;
class EmbeddedTexture;
class ColorGroup;
class XmlSerializer {
/// @brief his class implements ther 3mf serialization.
class XmlSerializer final {
public:
XmlSerializer(XmlParser *xmlParser);
XmlSerializer(XmlParser &xmlParser, D3MFOpcPackage *package);
~XmlSerializer();
void ImportXml(aiScene *scene);
private:
void addObjectToNode(aiNode *parent, Object *obj, aiMatrix4x4 nodeTransform);
void ReadModel(XmlNode &modelNode, const std::string &fileKey);
void LoadModelFile(const std::string &path);
void addObjectToNode(aiNode *parent, Object *obj, const aiMatrix4x4 &nodeTransform, const std::string &fileKey);
void ReadObject(XmlNode &node);
aiMesh *ReadMesh(XmlNode &node);
void ReadMetadata(XmlNode &node);
@@ -90,9 +94,14 @@ private:
std::vector<MetaEntry> mMetaData;
std::vector<EmbeddedTexture *> mEmbeddedTextures;
std::vector<aiMaterial *> mMaterials;
std::map<unsigned int, Resource *> mResourcesDictionnary;
// Resources are scoped per model file: object ids are only unique within a single
// .model part (the production extension splits a model across multiple parts).
using ResourceMap = std::map<unsigned int, Resource *>;
std::map<std::string, ResourceMap> mResourcesByFile;
ResourceMap *mCurrentResources;
unsigned int mMeshCount;
XmlParser *mXmlParser;
XmlParser &mXmlParser;
D3MFOpcPackage *mPackage;
};
} // namespace D3MF
+54 -14
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -75,6 +75,8 @@ static constexpr aiImporterDesc desc = {
"ac acc ac3d"
};
static constexpr auto ACDoubleSidedFlag = 0x20;
// ------------------------------------------------------------------------------------------------
// skip to the next token
inline const char *AcSkipToNextToken(const char *buffer, const char *end) {
@@ -123,12 +125,36 @@ inline const char *TAcCheckedLoadFloatArray(const char *buffer, const char *end,
}
for (unsigned int _i = 0; _i < num; ++_i) {
buffer = AcSkipToNextToken(buffer, end);
buffer = fast_atoreal_move<float>(buffer, ((float *)out)[_i]);
buffer = fast_atoreal_move(buffer, ((float *)out)[_i]);
}
return buffer;
}
// ------------------------------------------------------------------------------------------------
// Reverses vertex indices in a face.
static void flipWindingOrder(aiFace &f) {
std::reverse(f.mIndices, f.mIndices + f.mNumIndices);
}
// ------------------------------------------------------------------------------------------------
// Duplicates a face and inverts it. Also duplicates all vertices (so the new face gets its own
// set of normals and isn’t smoothed against the original).
static void buildBacksideOfFace(const aiFace &origFace, aiFace *&outFaces, aiVector3D *&outVertices, const aiVector3D *allVertices,
aiVector3D *&outUV, const aiVector3D *allUV, unsigned &curIdx) {
auto &newFace = *outFaces++;
newFace = origFace;
flipWindingOrder(newFace);
for (unsigned f = 0; f < newFace.mNumIndices; ++f) {
*outVertices++ = allVertices[newFace.mIndices[f]];
if (outUV) {
*outUV = allUV[newFace.mIndices[f]];
outUV++;
}
newFace.mIndices[f] = curIdx++;
}
}
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
AC3DImporter::AC3DImporter() :
@@ -144,14 +170,10 @@ AC3DImporter::AC3DImporter() :
// nothing to be done here
}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
AC3DImporter::~AC3DImporter() = default;
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool AC3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
static const uint32_t tokens[] = { AI_MAKE_MAGIC("AC3D") };
static constexpr uint32_t tokens[] = { AI_MAKE_MAGIC("AC3D") };
return CheckMagicToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
}
@@ -171,8 +193,9 @@ bool AC3DImporter::GetNextLine() {
// ------------------------------------------------------------------------------------------------
// Parse an object section in an AC file
bool AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
if (!TokenMatch(mBuffer.data, "OBJECT", 6))
if (!TokenMatch(mBuffer.data, "OBJECT", 6)) {
return false;
}
SkipSpaces(&mBuffer.data, mBuffer.end);
@@ -192,7 +215,6 @@ bool AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
light->mAttenuationConstant = 1.f;
// Generate a default name for both the light source and the node
// FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
light->mName.length = ::ai_snprintf(light->mName.data, AI_MAXLEN, "ACLight_%i", static_cast<unsigned int>(mLights->size()) - 1);
obj.name = std::string(light->mName.data);
@@ -202,8 +224,10 @@ bool AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
obj.type = Object::Group;
} else if (!ASSIMP_strincmp(mBuffer.data, "world", 5)) {
obj.type = Object::World;
} else
} else {
obj.type = Object::Poly;
}
while (GetNextLine()) {
if (TokenMatch(mBuffer.data, "kids", 4)) {
SkipSpaces(&mBuffer.data, mBuffer.end);
@@ -344,6 +368,7 @@ bool AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
}
}
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: \'kids\' line was expected");
return false;
}
@@ -452,6 +477,8 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
if ((*it).entries.empty()) {
ASSIMP_LOG_WARN("AC3D: surface has zero vertex references");
}
const bool isDoubleSided = ACDoubleSidedFlag == (it->flags & ACDoubleSidedFlag);
const int doubleSidedFactor = isDoubleSided ? 2 : 1;
// validate all vertex indices to make sure we won't crash here
for (it2 = (*it).entries.begin(),
@@ -481,8 +508,8 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
// triangle strip
case Surface::TriangleStrip:
needMat[idx].first += (unsigned int)(*it).entries.size() - 2;
needMat[idx].second += ((unsigned int)(*it).entries.size() - 2) * 3;
needMat[idx].first += static_cast<unsigned int>(it->entries.size() - 2) * doubleSidedFactor;
needMat[idx].second += static_cast<unsigned int>(it->entries.size() - 2) * 3 * doubleSidedFactor;
break;
default:
@@ -495,8 +522,8 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
case Surface::Polygon:
// the number of faces increments by one, the number
// of vertices by surface.numref.
needMat[idx].first++;
needMat[idx].second += (unsigned int)(*it).entries.size();
needMat[idx].first += doubleSidedFactor;
needMat[idx].second += static_cast<unsigned int>(it->entries.size()) * doubleSidedFactor;
};
}
unsigned int *pip = node->mMeshes = new unsigned int[node->mNumMeshes];
@@ -546,6 +573,7 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
for (it = object.surfaces.begin(); it != end; ++it) {
if (mat == (*it).mat) {
const Surface &src = *it;
const bool isDoubleSided = ACDoubleSidedFlag == (src.flags & ACDoubleSidedFlag);
// closed polygon
uint8_t type = (*it).GetType();
@@ -571,12 +599,18 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
++uv;
}
}
if(isDoubleSided) // Need a backface?
buildBacksideOfFace(faces[-1], faces, vertices, mesh->mVertices, uv, mesh->mTextureCoords[0], cur);
}
} else if (type == Surface::TriangleStrip) {
for (unsigned int i = 0; i < (unsigned int)src.entries.size() - 2; ++i) {
const Surface::SurfaceEntry &entry1 = src.entries[i];
const Surface::SurfaceEntry &entry2 = src.entries[i + 1];
const Surface::SurfaceEntry &entry3 = src.entries[i + 2];
const unsigned int verticesNeeded = isDoubleSided ? 6 : 3;
if (static_cast<unsigned>(vertices - mesh->mVertices) + verticesNeeded > mesh->mNumVertices) {
throw DeadlyImportError("AC3D: Invalid number of vertices");
}
aiFace &face = *faces++;
face.mNumIndices = 3;
@@ -620,6 +654,8 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
uv->y = entry3.second.y;
++uv;
}
if(isDoubleSided) // Need a backface?
buildBacksideOfFace(faces[-1], faces, vertices, mesh->mVertices, uv, mesh->mTextureCoords[0], cur);
}
} else {
@@ -629,6 +665,10 @@ aiNode *AC3DImporter::ConvertObjectSection(Object &object,
unsigned int tmp = (unsigned int)(*it).entries.size();
if (Surface::OpenLine == type) --tmp;
for (unsigned int m = 0; m < tmp; ++m) {
if (static_cast<unsigned>(vertices - mesh->mVertices) + 2 > mesh->mNumVertices) {
throw DeadlyImportError("AC3D: Invalid number of vertices");
}
aiFace &face = *faces++;
face.mNumIndices = 2;
+4 -4
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -60,10 +60,10 @@ namespace Assimp {
// ---------------------------------------------------------------------------
/** AC3D (*.ac) importer class
*/
class AC3DImporter : public BaseImporter {
class AC3DImporter final : public BaseImporter {
public:
AC3DImporter();
~AC3DImporter() override;
~AC3DImporter() override = default;
// Represents an AC3D material
struct Material {
@@ -103,7 +103,7 @@ public:
unsigned int mat, flags;
typedef std::pair<unsigned int, aiVector2D> SurfaceEntry;
using SurfaceEntry = std::pair<unsigned int, aiVector2D>;
std::vector<SurfaceEntry> entries;
// Type is low nibble of flags
+15 -35
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -113,10 +113,10 @@ bool AMFImporter::Find_NodeElement(const std::string &pID, const AMFNodeElementB
bool AMFImporter::Find_ConvertedNode(const std::string &pID, NodeArray &nodeArray, aiNode **pNode) const {
aiString node_name(pID.c_str());
for (aiNode *node : nodeArray) {
for (std::unique_ptr<aiNode> &node : nodeArray) {
if (node->mName == node_name) {
if (pNode != nullptr) {
*pNode = node;
*pNode = node.get();
}
return true;
@@ -178,28 +178,6 @@ bool AMFImporter::XML_SearchNode(const std::string &nodeName) {
return nullptr != mXmlParser->findNode(nodeName);
}
void AMFImporter::ParseHelper_FixTruncatedFloatString(const char *pInStr, std::string &pOutString) {
size_t instr_len;
pOutString.clear();
instr_len = strlen(pInStr);
if (!instr_len) return;
pOutString.reserve(instr_len * 3 / 2);
// check and correct floats in format ".x". Must be "x.y".
if (pInStr[0] == '.') pOutString.push_back('0');
pOutString.push_back(pInStr[0]);
for (size_t ci = 1; ci < instr_len; ci++) {
if ((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t'))) {
pOutString.push_back('0');
pOutString.push_back('.');
} else {
pOutString.push_back(pInStr[ci]);
}
}
}
static bool ParseHelper_Decode_Base64_IsBase64(const char pChar) {
return (isalnum((unsigned char)pChar) || (pChar == '+') || (pChar == '/'));
}
@@ -213,7 +191,10 @@ void AMFImporter::ParseHelper_Decode_Base64(const std::string &pInputBase64, std
uint8_t arr4[4], arr3[3];
// check input data
if (pInputBase64.size() % 4) throw DeadlyImportError("Base64-encoded data must have size multiply of four.");
if (pInputBase64.size() % 4) {
throw DeadlyImportError("Base64-encoded data must have size multiply of four.");
}
// prepare output place
pOutputData.clear();
pOutputData.reserve(pInputBase64.size() / 4 * 3);
@@ -346,8 +327,7 @@ void AMFImporter::ParseNode_Root() {
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Constellation(XmlNode &node) {
std::string id;
id = node.attribute("id").as_string();
std::string id = node.attribute("id").as_string();
// create and if needed - define new grouping object.
AMFNodeElementBase *ne = new AMFConstellation(mNodeElement_Cur);
@@ -403,17 +383,17 @@ void AMFImporter::ParseNode_Instance(XmlNode &node) {
for (auto &currentNode : node.children()) {
const std::string &currentName = currentNode.name();
if (currentName == "deltax") {
XmlParser::getValueAsFloat(currentNode, als.Delta.x);
XmlParser::getValueAsReal(currentNode, als.Delta.x);
} else if (currentName == "deltay") {
XmlParser::getValueAsFloat(currentNode, als.Delta.y);
XmlParser::getValueAsReal(currentNode, als.Delta.y);
} else if (currentName == "deltaz") {
XmlParser::getValueAsFloat(currentNode, als.Delta.z);
XmlParser::getValueAsReal(currentNode, als.Delta.z);
} else if (currentName == "rx") {
XmlParser::getValueAsFloat(currentNode, als.Delta.x);
XmlParser::getValueAsReal(currentNode, als.Delta.x);
} else if (currentName == "ry") {
XmlParser::getValueAsFloat(currentNode, als.Delta.y);
XmlParser::getValueAsReal(currentNode, als.Delta.y);
} else if (currentName == "rz") {
XmlParser::getValueAsFloat(currentNode, als.Delta.z);
XmlParser::getValueAsReal(currentNode, als.Delta.z);
}
}
ParseHelper_Node_Exit();
@@ -493,7 +473,7 @@ void AMFImporter::ParseNode_Metadata(XmlNode &node) {
// read attribute
ne = new AMFMetadata(mNodeElement_Cur);
((AMFMetadata *)ne)->Type = type;
((AMFMetadata *)ne)->MetaType = type;
((AMFMetadata *)ne)->Value = value;
mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element
mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph.
+4 -5
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -97,10 +97,10 @@ namespace Assimp {
/// new - <texmap> and children <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>
/// old - <map> and children <u1>, <u2>, <u3>, <v1>, <v2>, <v3>
///
class AMFImporter : public BaseImporter {
class AMFImporter final : public BaseImporter {
using AMFMetaDataArray = std::vector<AMFMetadata *>;
using MeshArray = std::vector<aiMesh *>;
using NodeArray = std::vector<aiNode *>;
using MeshArray = std::vector<std::unique_ptr<aiMesh> >;
using NodeArray = std::vector<std::unique_ptr<aiNode> >;
public:
struct SPP_Material;
@@ -168,7 +168,6 @@ public:
AI_WONT_RETURN void Throw_ID_NotFound(const std::string &pID) const AI_WONT_RETURN_SUFFIX;
void XML_CheckNode_MustHaveChildren(pugi::xml_node &node);
bool XML_SearchNode(const std::string &nodeName);
void ParseHelper_FixTruncatedFloatString(const char *pInStr, std::string &pOutString);
AMFImporter(const AMFImporter &pScene) = delete;
AMFImporter &operator=(const AMFImporter &pScene) = delete;
+5 -5
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -167,11 +167,11 @@ void AMFImporter::ParseNode_Coordinates(XmlNode &node) {
AMFCoordinates &als = *((AMFCoordinates *)ne); // alias for convenience
const std::string &currentName = ai_tolower(currentNode.name());
if (currentName == "x") {
XmlParser::getValueAsFloat(currentNode, als.Coordinate.x);
XmlParser::getValueAsReal(currentNode, als.Coordinate.x);
} else if (currentName == "y") {
XmlParser::getValueAsFloat(currentNode, als.Coordinate.y);
XmlParser::getValueAsReal(currentNode, als.Coordinate.y);
} else if (currentName == "z") {
XmlParser::getValueAsFloat(currentNode, als.Coordinate.z);
XmlParser::getValueAsReal(currentNode, als.Coordinate.z);
}
}
ParseHelper_Node_Exit();
@@ -202,7 +202,7 @@ void AMFImporter::ParseNode_Volume(XmlNode &node) {
((AMFVolume *)ne)->MaterialID = node.attribute("materialid").as_string();
((AMFVolume *)ne)->Type = type;
((AMFVolume *)ne)->VolumeType = type;
// Check for child nodes
bool col_read = false;
if (!node.empty()) {
+7 -8
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -263,26 +263,25 @@ void AMFImporter::ParseNode_TexMap(XmlNode &node, const bool pUseOldName) {
const std::string &name = currentNode.name();
if (name == "utex1") {
read_flag[0] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[0].x);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[0].x);
} else if (name == "utex2") {
read_flag[1] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[1].x);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[1].x);
} else if (name == "utex3") {
read_flag[2] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[2].x);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[2].x);
} else if (name == "vtex1") {
read_flag[3] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[0].y);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[0].y);
} else if (name == "vtex2") {
read_flag[4] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[1].y);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[1].y);
} else if (name == "vtex3") {
read_flag[5] = true;
XmlParser::getValueAsFloat(node, als.TextureCoordinate[2].y);
XmlParser::getValueAsReal(currentNode, als.TextureCoordinate[2].y);
}
}
ParseHelper_Node_Exit();
} else {
for (pugi::xml_attribute &attr : node.attributes()) {
const std::string name = attr.name();
+57 -54
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -56,7 +56,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
/// \class CAMFImporter_NodeElement
/// Base class for elements of nodes.
class AMFNodeElementBase {
public:
@@ -87,7 +86,8 @@ public:
AMFNodeElementBase *Parent; ///< Parent element. If nullptr then this node is root.
std::list<AMFNodeElementBase *> Child; ///< Child elements.
public: /// Destructor, virtual..
public:
/// Destructor, virtual..
virtual ~AMFNodeElementBase() = default;
/// Disabled copy constructor and co.
@@ -98,27 +98,25 @@ public: /// Destructor, virtual..
protected:
/// In constructor inheritor must set element type.
/// \param [in] pType - element type.
/// \param [in] type - element type.
/// \param [in] pParent - parent element.
AMFNodeElementBase(const EType pType, AMFNodeElementBase *pParent) :
Type(pType), Parent(pParent) {
AMFNodeElementBase(EType type, AMFNodeElementBase *pParent) :
Type(type), Parent(pParent) {
// empty
}
}; // class IAMFImporter_NodeElement
/// \struct CAMFImporter_NodeElement_Constellation
/// A collection of objects or constellations with specific relative locations.
struct AMFConstellation : public AMFNodeElementBase {
struct AMFConstellation final : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFConstellation(AMFNodeElementBase *pParent) :
explicit AMFConstellation(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Constellation, pParent) {}
}; // struct CAMFImporter_NodeElement_Constellation
/// \struct CAMFImporter_NodeElement_Instance
/// Part of constellation.
struct AMFInstance : public AMFNodeElementBase {
struct AMFInstance final : public AMFNodeElementBase {
std::string ObjectID; ///< ID of object for instantiation.
/// \var Delta - The distance of translation in the x, y, or z direction, respectively, in the referenced object's coordinate system, to
@@ -131,24 +129,24 @@ struct AMFInstance : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFInstance(AMFNodeElementBase *pParent) :
explicit AMFInstance(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Instance, pParent) {}
};
/// \struct CAMFImporter_NodeElement_Metadata
/// Structure that define metadata node.
struct AMFMetadata : public AMFNodeElementBase {
std::string Type; ///< Type of "Value".
std::string Value; ///< Value.
std::string MetaType; ///< Type of "Value".
std::string Value; ///< Value.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFMetadata(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Metadata, pParent) {}
explicit AMFMetadata(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Metadata, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Root
/// Structure that define root node.
struct AMFRoot : public AMFNodeElementBase {
@@ -157,11 +155,12 @@ struct AMFRoot : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFRoot(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Root, pParent) {}
explicit AMFRoot(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Root, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Color
/// Structure that define object node.
struct AMFColor : public AMFNodeElementBase {
bool Composed; ///< Type of color stored: if true then look for formula in \ref Color_Composed[4], else - in \ref Color.
@@ -171,92 +170,97 @@ struct AMFColor : public AMFNodeElementBase {
/// @brief Constructor.
/// @param [in] pParent - pointer to parent node.
AMFColor(AMFNodeElementBase *pParent) :
explicit AMFColor(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Color, pParent), Composed(false), Color() {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Material
/// Structure that define material node.
struct AMFMaterial : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFMaterial(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Material, pParent) {}
explicit AMFMaterial(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Material, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Object
/// Structure that define object node.
struct AMFObject : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFObject(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Object, pParent) {}
explicit AMFObject(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Object, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Mesh
/// Structure that define mesh node.
struct AMFMesh : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFMesh(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Mesh, pParent) {}
explicit AMFMesh(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Mesh, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Vertex
/// Structure that define vertex node.
struct AMFVertex : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFVertex(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Vertex, pParent) {}
explicit AMFVertex(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Vertex, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Edge
/// Structure that define edge node.
struct AMFEdge : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFEdge(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Edge, pParent) {}
explicit AMFEdge(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Edge, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Vertices
/// Structure that define vertices node.
struct AMFVertices : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFVertices(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Vertices, pParent) {}
explicit AMFVertices(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Vertices, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Volume
/// Structure that define volume node.
struct AMFVolume : public AMFNodeElementBase {
std::string MaterialID; ///< Which material to use.
std::string Type; ///< What this volume describes can be "region" or "support". If none specified, "object" is assumed.
std::string VolumeType; ///< What this volume describes can be "region" or "support". If none specified, "object" is assumed.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFVolume(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Volume, pParent) {}
explicit AMFVolume(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Volume, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Coordinates
/// Structure that define coordinates node.
struct AMFCoordinates : public AMFNodeElementBase {
aiVector3D Coordinate; ///< Coordinate.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFCoordinates(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Coordinates, pParent) {}
explicit AMFCoordinates(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Coordinates, pParent) {
// empty
}
};
/// \struct CAMFImporter_NodeElement_TexMap
/// Structure that define texture coordinates node.
struct AMFTexMap : public AMFNodeElementBase {
aiVector3D TextureCoordinate[3]; ///< Texture coordinates.
@@ -267,20 +271,19 @@ struct AMFTexMap : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFTexMap(AMFNodeElementBase *pParent) :
explicit AMFTexMap(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_TexMap, pParent), TextureCoordinate{} {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Triangle
/// Structure that define triangle node.
struct AMFTriangle : public AMFNodeElementBase {
size_t V[3]; ///< Triangle vertices.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFTriangle(AMFNodeElementBase *pParent) :
explicit AMFTriangle(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Triangle, pParent) {
// empty
}
@@ -294,7 +297,7 @@ struct AMFTexture : public AMFNodeElementBase {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
AMFTexture(AMFNodeElementBase *pParent) :
explicit AMFTexture(AMFNodeElementBase *pParent) :
AMFNodeElementBase(ENET_Texture, pParent), Width(0), Height(0), Depth(0), Data(), Tiled(false) {
// empty
}
+31 -35
View File
@@ -1,9 +1,9 @@
/*
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -57,8 +57,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Assimp {
aiColor4D AMFImporter::SPP_Material::GetColor(const float /*pX*/, const float /*pY*/, const float /*pZ*/) const {
aiColor4D tcol;
// Check if stored data are supported.
if (!Composition.empty()) {
throw DeadlyImportError("IME. GetColor for composition");
@@ -68,7 +66,7 @@ aiColor4D AMFImporter::SPP_Material::GetColor(const float /*pX*/, const float /*
throw DeadlyImportError("IME. GetColor, composed color");
}
tcol = Color->Color;
aiColor4D tcol = Color->Color;
// Check if default color must be used
if ((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0)) {
@@ -224,7 +222,8 @@ size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string &
}
// Create format hint.
strcpy(converted_texture.FormatHint, "rgba0000"); // copy initial string.
constexpr char templateColor[] = "rgba0000";
memcpy(converted_texture.FormatHint, templateColor, 8);
if (!r.empty()) converted_texture.FormatHint[4] = '8';
if (!g.empty()) converted_texture.FormatHint[5] = '8';
if (!b.empty()) converted_texture.FormatHint[6] = '8';
@@ -332,7 +331,7 @@ void AMFImporter::Postprocess_AddMetadata(const AMFMetaDataArray &metadataList,
size_t meta_idx(0);
for (const AMFMetadata *metadata : metadataList) {
sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata->Type, aiString(metadata->Value));
sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata->MetaType, aiString(metadata->Value));
}
}
@@ -510,7 +509,7 @@ void AMFImporter::Postprocess_BuildMeshSet(const AMFMesh &pNodeElement, const st
} // if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != nullptr)) else
}; // auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
aiMesh *tmesh = new aiMesh;
std::unique_ptr<aiMesh> tmesh(new aiMesh);
tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; // Only triangles is supported by AMF.
//
@@ -531,11 +530,9 @@ void AMFImporter::Postprocess_BuildMeshSet(const AMFMesh &pNodeElement, const st
col_arr.reserve(VertexCount_Max * 2);
{ // fill arrays
size_t vert_idx_from, vert_idx_to;
// first iteration.
vert_idx_to = 0;
vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
size_t vert_idx_to = 0;
size_t vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
if (vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
@@ -638,7 +635,7 @@ void AMFImporter::Postprocess_BuildMeshSet(const AMFMesh &pNodeElement, const st
// store new aiMesh
mesh_idx.push_back(static_cast<unsigned int>(pMeshList.size()));
pMeshList.push_back(tmesh);
pMeshList.emplace_back(std::move(tmesh));
} // for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
} // if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
} // for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
@@ -671,34 +668,31 @@ void AMFImporter::Postprocess_BuildMaterial(const AMFMaterial &pMaterial) {
}
void AMFImporter::Postprocess_BuildConstellation(AMFConstellation &pConstellation, NodeArray &nodeArray) const {
aiNode *con_node;
std::list<aiNode *> ch_node;
std::list<std::unique_ptr<aiNode> > ch_node;
// We will build next hierarchy:
// aiNode as parent (<constellation>) for set of nodes as a children
// |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
// ...
// \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
con_node = new aiNode;
std::unique_ptr<aiNode> con_node(new aiNode);
con_node->mName = pConstellation.ID;
// Walk through children and search for instances of another objects, constellations.
for (const AMFNodeElementBase *ne : pConstellation.Child) {
aiMatrix4x4 tmat;
aiNode *t_node;
aiNode *found_node;
if (ne->Type == AMFNodeElementBase::ENET_Metadata) continue;
if (ne->Type != AMFNodeElementBase::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>.");
// create alias for convenience
AMFInstance &als = *((AMFInstance *)ne);
// find referenced object
aiNode *found_node;
if (!Find_ConvertedNode(als.ObjectID, nodeArray, &found_node)) Throw_ID_NotFound(als.ObjectID);
// create node for applying transformation
t_node = new aiNode;
t_node->mParent = con_node;
std::unique_ptr<aiNode> t_node(new aiNode);
t_node->mParent = con_node.get();
// apply transformation
aiMatrix4x4 tmat;
aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat;
aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat;
aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat;
@@ -707,8 +701,8 @@ void AMFImporter::Postprocess_BuildConstellation(AMFConstellation &pConstellatio
t_node->mNumChildren = 1;
t_node->mChildren = new aiNode *[t_node->mNumChildren];
SceneCombiner::Copy(&t_node->mChildren[0], found_node);
t_node->mChildren[0]->mParent = t_node;
ch_node.push_back(t_node);
t_node->mChildren[0]->mParent = t_node.get();
ch_node.emplace_back(std::move(t_node));
} // for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
// copy found aiNode's as children
@@ -718,11 +712,11 @@ void AMFImporter::Postprocess_BuildConstellation(AMFConstellation &pConstellatio
con_node->mNumChildren = static_cast<unsigned int>(ch_node.size());
con_node->mChildren = new aiNode *[con_node->mNumChildren];
for (aiNode *node : ch_node)
con_node->mChildren[ch_idx++] = node;
for (auto &node : ch_node)
con_node->mChildren[ch_idx++] = node.release();
// and place "root" of <constellation> node to node list
nodeArray.push_back(con_node);
nodeArray.emplace_back(std::move(con_node));
}
void AMFImporter::Postprocess_BuildScene(aiScene *pScene) {
@@ -776,7 +770,7 @@ void AMFImporter::Postprocess_BuildScene(aiScene *pScene) {
// for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance>
Postprocess_BuildNodeAndObject(*((AMFObject *)root_child), mesh_list, &tnode);
if (tnode != nullptr) {
nodeArray.push_back(tnode);
nodeArray.emplace_back(tnode);
}
}
} // for(const CAMFImporter_NodeElement* root_child: root_el->Child)
@@ -815,7 +809,6 @@ nl_clean_loop:
for (; next_it != nodeArray.end(); ++next_it) {
if ((*next_it)->FindNode((*nl_it)->mName) != nullptr) {
// if current top node(nl_it) found in another top node then erase it from node_list and restart search loop.
// FIXME: this leaks memory on test models test8.amf and test9.amf
nodeArray.erase(nl_it);
goto nl_clean_loop;
@@ -830,7 +823,7 @@ nl_clean_loop:
//
// Nodes
if (!nodeArray.empty()) {
NodeArray::const_iterator nl_it = nodeArray.begin();
NodeArray::iterator nl_it = nodeArray.begin();
pScene->mRootNode->mNumChildren = static_cast<unsigned int>(nodeArray.size());
pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
@@ -838,19 +831,22 @@ nl_clean_loop:
// Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have
// mRootNode only as parent.
(*nl_it)->mParent = pScene->mRootNode;
pScene->mRootNode->mChildren[i] = *nl_it++;
pScene->mRootNode->mChildren[i] = nl_it->release();
nl_it++;
}
} // if(node_list.size() > 0)
//
// Meshes
if (!mesh_list.empty()) {
MeshArray::const_iterator ml_it = mesh_list.begin();
MeshArray::iterator ml_it = mesh_list.begin();
pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
for (size_t i = 0; i < pScene->mNumMeshes; i++)
pScene->mMeshes[i] = *ml_it++;
for (size_t i = 0; i < pScene->mNumMeshes; i++) {
pScene->mMeshes[i] = ml_it->release();
ml_it++;
}
} // if(mesh_list.size() > 0)
//
@@ -867,7 +863,7 @@ nl_clean_loop:
pScene->mTextures[idx]->mHeight = static_cast<unsigned int>(tex_convd.Height);
pScene->mTextures[idx]->pcData = (aiTexel *)tex_convd.Data;
// texture format description.
strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint);
strncpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint, HINTMAXTEXTURELEN);
idx++;
} // for(const SPP_Texture& tex_convd: mTexture_Converted)
+35 -21
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -124,7 +124,7 @@ void ASEImporter::InternReadFile(const std::string &pFile,
// Allocate storage and copy the contents of the file to a memory buffer
std::vector<char> mBuffer2;
TextFileToBuffer(file.get(), mBuffer2);
const size_t fileSize = mBuffer2.size();
this->mBuffer = &mBuffer2[0];
this->pcScene = pScene;
@@ -146,7 +146,7 @@ void ASEImporter::InternReadFile(const std::string &pFile,
};
// Construct an ASE parser and parse the file
ASE::Parser parser(mBuffer, defaultFormat);
ASE::Parser parser(mBuffer, fileSize, defaultFormat);
mParser = &parser;
mParser->Parse();
@@ -189,6 +189,8 @@ void ASEImporter::InternReadFile(const std::string &pFile,
aiMesh **pp = pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
for (std::vector<aiMesh *>::const_iterator i = avOutMeshes.begin(); i != avOutMeshes.end(); ++i) {
if (!(*i)->mNumFaces) {
(*i)->mColors[2] = nullptr;
delete *i;
continue;
}
*pp++ = *i;
@@ -446,10 +448,9 @@ void ASEImporter::BuildLights() {
}
// ------------------------------------------------------------------------------------------------
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
aiNode *pcParent, const char *szName) {
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes, aiNode *pcParent, const std::string &name) {
aiMatrix4x4 m;
AddNodes(nodes, pcParent, szName, m);
AddNodes(nodes, pcParent, name, m);
}
// ------------------------------------------------------------------------------------------------
@@ -506,10 +507,9 @@ void ASEImporter::AddMeshes(const ASE::BaseNode *snode, aiNode *node) {
// ------------------------------------------------------------------------------------------------
// Add child nodes to a given parent node
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
aiNode *pcParent, const char *szName,
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes, aiNode *pcParent, const std::string &name,
const aiMatrix4x4 &mat) {
const size_t len = szName ? ::strlen(szName) : 0;
const size_t len = name.size();
ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
// Receives child nodes for the pcParent node
@@ -519,16 +519,18 @@ void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
// which has *us* as parent.
for (std::vector<BaseNode *>::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
const BaseNode *snode = *it;
if (szName) {
if (len != snode->mParent.length() || ::strcmp(szName, snode->mParent.c_str()))
if (!name.empty()) {
if (len != snode->mParent.length() || name != snode->mParent.c_str()) {
continue;
} else if (snode->mParent.length())
}
} else if (snode->mParent.length()) {
continue;
}
(*it)->mProcessed = true;
// Allocate a new node and add it to the output data structure
apcNodes.push_back(new aiNode());
apcNodes.push_back(new aiNode);
aiNode *node = apcNodes.back();
node->mName.Set((snode->mName.length() ? snode->mName.c_str() : "Unnamed_Node"));
@@ -541,7 +543,7 @@ void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
// Add sub nodes - prevent stack overflow due to recursive parenting
if (node->mName != node->mParent->mName && node->mName != node->mParent->mParent->mName) {
AddNodes(nodes, node, node->mName.data, snode->mTransform);
AddNodes(nodes, node, node->mName.C_Str(), snode->mTransform);
}
// Further processing depends on the type of the node
@@ -573,8 +575,8 @@ void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
nd->mParent = node;
// The .Target node is always the first child node
for (unsigned int m = 0; m < node->mNumChildren; ++m)
node->mChildren[m + 1] = node->mChildren[m];
for (unsigned int m = node->mNumChildren; m > 0; --m)
node->mChildren[m] = node->mChildren[m - 1];
node->mChildren[0] = nd;
node->mNumChildren++;
@@ -619,7 +621,8 @@ void ASEImporter::BuildNodes(std::vector<BaseNode *> &nodes) {
}
// add all nodes
AddNodes(nodes, ch, nullptr);
static const std::string none = "";
AddNodes(nodes, ch, none);
// now iterate through al nodes and find those that have not yet
// been added to the nodegraph (= their parent could not be recognized)
@@ -730,16 +733,28 @@ void ASEImporter::BuildUniqueRepresentation(ASE::Mesh &mesh) {
unsigned int iCurrent = 0, fi = 0;
for (std::vector<ASE::Face>::iterator i = mesh.mFaces.begin(); i != mesh.mFaces.end(); ++i, ++fi) {
for (unsigned int n = 0; n < 3; ++n, ++iCurrent) {
const uint32_t curIndex = (*i).mIndices[n];
if (curIndex >= mesh.mPositions.size()) {
throw DeadlyImportError("ASE: Invalid vertex index in face ", fi, ".");
}
mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
// add texture coordinates
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
if (mesh.amTexCoords[c].empty()) break;
amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
const uint32_t uvIndex = (*i).amUVIndices[c][n];
if (uvIndex >= mesh.amTexCoords[c].size()) {
throw DeadlyImportError("ASE: Invalid UV index in face ", fi, ".");
}
amTexCoords[c][iCurrent] = mesh.amTexCoords[c][uvIndex];
}
// add vertex colors
if (!mesh.mVertexColors.empty()) {
mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
const uint32_t colorIndex = (*i).mColorIndices[n];
if (colorIndex >= mesh.mVertexColors.size()) {
throw DeadlyImportError("ASE: Invalid vertex color index in face ", fi, ".");
}
mVertexColors[iCurrent] = mesh.mVertexColors[colorIndex];
}
// add normal vectors
if (!mesh.mNormals.empty()) {
@@ -1265,5 +1280,4 @@ bool ASEImporter::GenerateNormals(ASE::Mesh &mesh) {
}
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
#endif // !! ASSIMP_BUILD_NO_BASE_IMPORTER
#endif // ASSIMP_BUILD_NO_ASE_IMPORTER
+5 -6
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -59,7 +59,7 @@ namespace Assimp {
/** Importer class for the 3DS ASE ASCII format.
*
*/
class ASEImporter : public BaseImporter {
class ASEImporter final : public BaseImporter {
public:
ASEImporter();
~ASEImporter() override = default;
@@ -153,13 +153,13 @@ private:
* \param matrix Current transform
*/
void AddNodes(const std::vector<ASE::BaseNode*>& nodes,
aiNode* pcParent,const char* szName);
aiNode* pcParent, const std::string &name);
void AddNodes(const std::vector<ASE::BaseNode*>& nodes,
aiNode* pcParent,const char* szName,
aiNode* pcParent, const std::string &name,
const aiMatrix4x4& matrix);
void AddMeshes(const ASE::BaseNode* snode,aiNode* node);
void AddMeshes(const ASE::BaseNode* snode, aiNode* node);
// -------------------------------------------------------------------
/** Generate a default material and add it to the parser's list
@@ -188,5 +188,4 @@ protected:
} // end of namespace Assimp
#endif // AI_3DSIMPORTER_H_INC
File diff suppressed because it is too large Load Diff
+17 -19
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -57,14 +57,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ASE is quite similar to 3ds. We can reuse some structures
#include "AssetLib/3DS/3DSLoader.h"
namespace Assimp {
namespace ASE {
namespace Assimp::ASE {
using namespace D3DS;
// ---------------------------------------------------------------------------
/** Helper structure representing an ASE material */
struct Material : public D3DS::Material {
struct Material final : D3DS::Material {
//! Default constructor has been deleted
Material() = delete;
@@ -115,7 +114,7 @@ struct Material : public D3DS::Material {
return *this;
}
~Material() = default;
~Material() override = default;
//! Contains all sub materials of this material
std::vector<Material> avSubMaterials;
@@ -373,8 +372,8 @@ struct Dummy : public BaseNode {
};
// Parameters to Parser::Parse()
#define AI_ASE_NEW_FILE_FORMAT 200
#define AI_ASE_OLD_FILE_FORMAT 110
static constexpr unsigned int AI_ASE_NEW_FILE_FORMAT = 200;
static constexpr unsigned int AI_ASE_OLD_FILE_FORMAT = 110;
// Internally we're a little bit more tolerant
#define AI_ASE_IS_NEW_FILE_FORMAT() (iFileFormat >= 200)
@@ -391,11 +390,11 @@ public:
// -------------------------------------------------------------------
//! Construct a parser from a given input file which is
//! guaranteed to be terminated with zero.
//! @param szFile Input file
//! @param file The name of the input file.
//! @param fileFormatDefault Assumed file format version. If the
//! file format is specified in the file the new value replaces
//! the default value.
Parser(const char *szFile, unsigned int fileFormatDefault);
Parser(const char *file, size_t fileLen, unsigned int fileFormatDefault);
// -------------------------------------------------------------------
//! Parses the file into the parsers internal representation
@@ -553,13 +552,15 @@ private:
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats)
//! \param rIndexOut Output index
void ParseLV4MeshFloatTriple(ai_real *apOut, unsigned int &rIndexOut);
void ParseLV4MeshRealTriple(ai_real *apOut, unsigned int &rIndexOut);
void ParseLV4MeshFloatTriple(float *apOut, unsigned int &rIndexOut);
// -------------------------------------------------------------------
//! Parse a *MESH_VERT block in a file
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats)
void ParseLV4MeshFloatTriple(ai_real *apOut);
void ParseLV4MeshRealTriple(ai_real *apOut);
void ParseLV4MeshFloatTriple(float *apOut);
// -------------------------------------------------------------------
//! Parse a *MESH_TFACE block in a file
@@ -577,7 +578,8 @@ private:
// -------------------------------------------------------------------
//! Parse a single float element
//! \param fOut Output float
void ParseLV4MeshFloat(ai_real &fOut);
void ParseLV4MeshReal(ai_real &fOut);
void ParseLV4MeshFloat(float &fOut);
// -------------------------------------------------------------------
//! Parse a single int element
@@ -617,11 +619,8 @@ private:
bool ParseString(std::string &out, const char *szName);
public:
//! Pointer to current data
const char *filePtr;
/// The end pointer of the file data
const char *mEnd;
const char *mFilePtr; ////< Pointer to current data
const char *mEnd; ///< The end pointer of the file data
//! background color to be passed to the viewer
//! QNAN if none was found
@@ -668,8 +667,7 @@ public:
unsigned int iFileFormat;
};
} // Namespace ASE
} // namespace Assimp
} // Namespace Assimp::ASE
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+24 -24
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -239,29 +239,7 @@ inline size_t WriteArray(IOStream *stream, const T *in, unsigned int size) {
* and the chunk contents to the container stream. This allows relatively easy chunk
* chunk construction, even recursively.
*/
class AssbinChunkWriter : public IOStream {
private:
uint8_t *buffer;
uint32_t magic;
IOStream *container;
size_t cur_size, cursor, initial;
private:
// -------------------------------------------------------------------
void Grow(size_t need = 0) {
size_t new_size = std::max(initial, std::max(need, cur_size + (cur_size >> 1)));
const uint8_t *const old = buffer;
buffer = new uint8_t[new_size];
if (old) {
memcpy(buffer, old, cur_size);
delete[] old;
}
cur_size = new_size;
}
class AssbinChunkWriter final : public IOStream {
public:
AssbinChunkWriter(IOStream *container, uint32_t magic, size_t initial = 4096) :
buffer(nullptr),
@@ -315,6 +293,28 @@ public:
return pCount;
}
private:
// -------------------------------------------------------------------
void Grow(size_t need = 0) {
size_t new_size = std::max(initial, std::max(need, cur_size + (cur_size >> 1)));
const uint8_t *const old = buffer;
buffer = new uint8_t[new_size];
if (old) {
memcpy(buffer, old, cur_size);
delete[] old;
}
cur_size = new_size;
}
private:
uint8_t *buffer;
uint32_t magic;
IOStream *container;
size_t cur_size, cursor, initial;
};
// ----------------------------------------------------------------------------------
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+160 -86
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -48,14 +48,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef ASSIMP_BUILD_NO_ASSBIN_IMPORTER
// internal headers
#include "AssetLib/Assbin/AssbinLoader.h"
#include "AssbinLoader.h"
#include "Common/assbin_chunks.h"
#include <assimp/MemoryIOWrapper.h>
#include <assimp/anim.h>
#include <assimp/importerdesc.h>
#include <assimp/mesh.h>
#include <assimp/scene.h>
#include <climits>
#include <cstdint>
#include <memory>
#include <vector>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB
#include <zlib.h>
@@ -91,10 +95,14 @@ bool AssbinImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, boo
}
char s[32];
in->Read(s, sizeof(char), 32);
const size_t read = in->Read(s, sizeof(char), 32);
pIOHandler->Close(in);
if (read < 19) {
return false;
}
return strncmp(s, "ASSIMP.binary-dump.", 19) == 0;
}
@@ -145,11 +153,18 @@ aiQuaternion Read<aiQuaternion>(IOStream *stream) {
template <>
aiString Read<aiString>(IOStream *stream) {
aiString s;
stream->Read(&s.length, 4, 1);
if (s.length) {
stream->Read(s.data, s.length, 1);
const ai_uint32 len = Read<ai_uint32>(stream);
if (len >= AI_MAXLEN) {
throw DeadlyImportError("ASSBIN: String length too large, potential buffer overflow attempt");
}
s.data[s.length] = 0;
s.length = len;
if (s.length > 0) {
const size_t bytesRead = stream->Read(s.data, sizeof(char), s.length);
if (bytesRead != s.length) {
throw DeadlyImportError("ASSBIN: Unexpected EOF reading string data");
}
}
s.data[s.length] = '\0';
return s;
}
@@ -217,7 +232,7 @@ void AssbinImporter::ReadBinaryNode(IOStream *stream, aiNode **onode, aiNode *pa
throw DeadlyImportError("Magic chunk identifiers are wrong!");
/*uint32_t size =*/Read<uint32_t>(stream);
std::unique_ptr<aiNode> node(new aiNode());
auto node = std::make_unique<aiNode>();
node->mName = Read<aiString>(stream);
node->mTransformation = Read<aiMatrix4x4>(stream);
@@ -225,24 +240,32 @@ void AssbinImporter::ReadBinaryNode(IOStream *stream, aiNode **onode, aiNode *pa
unsigned numMeshes = Read<unsigned int>(stream);
unsigned int nb_metadata = Read<unsigned int>(stream);
if (numMeshes > AI_MAX_ALLOC(unsigned int)) {
throw DeadlyImportError("Assbin: Too many meshes in node, would overflow");
}
if (numChildren > AI_MAX_ALLOC(aiNode *)) {
throw DeadlyImportError("Assbin: Too many children in node, would overflow");
}
if (nb_metadata > AI_MAX_ALLOC(aiMetadataEntry)) {
throw DeadlyImportError("Assbin: Too many metadata properties, would overflow");
}
if (parent) {
node->mParent = parent;
}
if (numMeshes) {
node->mMeshes = new unsigned int[numMeshes];
for (unsigned int i = 0; i < numMeshes; ++i) {
node->mMeshes[i] = Read<unsigned int>(stream);
node->mNumMeshes++;
}
ReadArray(stream, node->mMeshes, numMeshes);
node->mNumMeshes = numMeshes;
}
if (numChildren) {
node->mChildren = new aiNode *[numChildren];
node->mChildren = new aiNode *[numChildren]();
for (unsigned int i = 0; i < numChildren; ++i) {
ReadBinaryNode(stream, &node->mChildren[i], node.get());
node->mNumChildren++;
}
node->mNumChildren = numChildren;
}
if (nb_metadata > 0) {
@@ -253,27 +276,34 @@ void AssbinImporter::ReadBinaryNode(IOStream *stream, aiNode **onode, aiNode *pa
void *data = nullptr;
switch (node->mMetaData->mValues[i].mType) {
case AI_BOOL:
case AI_BOOL: {
data = new bool(Read<bool>(stream));
break;
case AI_INT32:
}
case AI_INT32: {
data = new int32_t(Read<int32_t>(stream));
break;
case AI_UINT64:
}
case AI_UINT64: {
data = new uint64_t(Read<uint64_t>(stream));
break;
case AI_FLOAT:
}
case AI_FLOAT: {
data = new ai_real(Read<ai_real>(stream));
break;
case AI_DOUBLE:
}
case AI_DOUBLE: {
data = new double(Read<double>(stream));
break;
case AI_AISTRING:
}
case AI_AISTRING: {
data = new aiString(Read<aiString>(stream));
break;
case AI_AIVECTOR3D:
}
case AI_AIVECTOR3D: {
data = new aiVector3D(Read<aiVector3D>(stream));
break;
}
#ifndef SWIG
case FORCE_32BIT:
#endif // SWIG
@@ -297,14 +327,17 @@ void AssbinImporter::ReadBinaryBone(IOStream *stream, aiBone *b) {
b->mNumWeights = Read<unsigned int>(stream);
b->mOffsetMatrix = Read<aiMatrix4x4>(stream);
if (b->mNumWeights > AI_MAX_ALLOC(aiVertexWeight) || (size_t)b->mNumWeights > SIZE_MAX / sizeof(aiVertexWeight)) {
throw DeadlyImportError("Assbin: Too many weights, would overflow");
}
// for the moment we write dumb min/max values for the bones, too.
// maybe I'll add a better, hash-like solution later
if (shortened) {
ReadBounds(stream, b->mWeights, b->mNumWeights);
} else {
// else write as usual
b->mWeights = new aiVertexWeight[b->mNumWeights];
ReadArray<aiVertexWeight>(stream, b->mWeights, b->mNumWeights);
ReadArray(stream, b->mWeights, b->mNumWeights);
}
}
@@ -325,6 +358,17 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
mesh->mNumBones = Read<unsigned int>(stream);
mesh->mMaterialIndex = Read<unsigned int>(stream);
if (mesh->mNumVertices > AI_MAX_ALLOC(aiVector3D) || (size_t)mesh->mNumVertices > SIZE_MAX / sizeof(aiVector3D) ||
mesh->mNumVertices > AI_MAX_ALLOC(aiColor4D) || (size_t)mesh->mNumVertices > SIZE_MAX / sizeof(aiColor4D)) {
throw DeadlyImportError("Assbin: Too many vertices, would overflow");
}
if (mesh->mNumFaces > AI_MAX_ALLOC(aiFace) || (size_t)mesh->mNumFaces > SIZE_MAX / sizeof(aiFace)) {
throw DeadlyImportError("Assbin: Too many faces, would overflow");
}
if (mesh->mNumBones > AI_MAX_ALLOC(aiBone *) || (size_t)mesh->mNumBones > SIZE_MAX / sizeof(aiBone *)) {
throw DeadlyImportError("Assbin: Too many bones, would overflow");
}
// first of all, write bits for all existent vertex components
unsigned int c = Read<unsigned int>(stream);
@@ -332,18 +376,16 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
if (shortened) {
ReadBounds(stream, mesh->mVertices, mesh->mNumVertices);
} else {
// else write as usual
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
ReadArray<aiVector3D>(stream, mesh->mVertices, mesh->mNumVertices);
ReadArray(stream, mesh->mVertices, mesh->mNumVertices);
}
}
if (c & ASSBIN_MESH_HAS_NORMALS) {
if (shortened) {
ReadBounds(stream, mesh->mNormals, mesh->mNumVertices);
} else {
// else write as usual
mesh->mNormals = new aiVector3D[mesh->mNumVertices];
ReadArray<aiVector3D>(stream, mesh->mNormals, mesh->mNumVertices);
ReadArray(stream, mesh->mNormals, mesh->mNumVertices);
}
}
if (c & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) {
@@ -351,11 +393,10 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
ReadBounds(stream, mesh->mTangents, mesh->mNumVertices);
ReadBounds(stream, mesh->mBitangents, mesh->mNumVertices);
} else {
// else write as usual
mesh->mTangents = new aiVector3D[mesh->mNumVertices];
ReadArray<aiVector3D>(stream, mesh->mTangents, mesh->mNumVertices);
ReadArray(stream, mesh->mTangents, mesh->mNumVertices);
mesh->mBitangents = new aiVector3D[mesh->mNumVertices];
ReadArray<aiVector3D>(stream, mesh->mBitangents, mesh->mNumVertices);
ReadArray(stream, mesh->mBitangents, mesh->mNumVertices);
}
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
@@ -366,9 +407,8 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
if (shortened) {
ReadBounds(stream, mesh->mColors[n], mesh->mNumVertices);
} else {
// else write as usual
mesh->mColors[n] = new aiColor4D[mesh->mNumVertices];
ReadArray<aiColor4D>(stream, mesh->mColors[n], mesh->mNumVertices);
ReadArray(stream, mesh->mColors[n], mesh->mNumVertices);
}
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
@@ -382,9 +422,8 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
if (shortened) {
ReadBounds(stream, mesh->mTextureCoords[n], mesh->mNumVertices);
} else {
// else write as usual
mesh->mTextureCoords[n] = new aiVector3D[mesh->mNumVertices];
ReadArray<aiVector3D>(stream, mesh->mTextureCoords[n], mesh->mNumVertices);
ReadArray(stream, mesh->mTextureCoords[n], mesh->mNumVertices);
}
}
@@ -403,6 +442,9 @@ void AssbinImporter::ReadBinaryMesh(IOStream *stream, aiMesh *mesh) {
static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
f.mNumIndices = Read<uint16_t>(stream);
if (f.mNumIndices > AI_MAX_FACE_INDICES) {
throw DeadlyImportError("Assbin: Too many face indices, would overflow");
}
f.mIndices = new unsigned int[f.mNumIndices];
for (unsigned int a = 0; a < f.mNumIndices; ++a) {
@@ -438,8 +480,15 @@ void AssbinImporter::ReadBinaryMaterialProperty(IOStream *stream, aiMaterialProp
prop->mDataLength = Read<unsigned int>(stream);
prop->mType = (aiPropertyTypeInfo)Read<unsigned int>(stream);
if (prop->mDataLength > AI_MAX_ALLOC(char)) {
throw DeadlyImportError("Assbin: Material property data too large");
}
prop->mData = new char[prop->mDataLength];
stream->Read(prop->mData, 1, prop->mDataLength);
if (stream->Read(prop->mData, 1, prop->mDataLength) != prop->mDataLength) {
throw DeadlyImportError("ASSBIN: Unexpected EOF reading material property data");
}
}
// -----------------------------------------------------------------------------------
@@ -474,34 +523,38 @@ void AssbinImporter::ReadBinaryNodeAnim(IOStream *stream, aiNodeAnim *nd) {
nd->mPreState = (aiAnimBehaviour)Read<unsigned int>(stream);
nd->mPostState = (aiAnimBehaviour)Read<unsigned int>(stream);
if (nd->mNumPositionKeys > AI_MAX_ALLOC(aiVectorKey) || (size_t)nd->mNumPositionKeys > SIZE_MAX / sizeof(aiVectorKey)) {
throw DeadlyImportError("Assbin: Too many position keys, would overflow");
}
if (nd->mNumRotationKeys > AI_MAX_ALLOC(aiQuatKey) || (size_t)nd->mNumRotationKeys > SIZE_MAX / sizeof(aiQuatKey)) {
throw DeadlyImportError("Assbin: Too many rotation keys, would overflow");
}
if (nd->mNumScalingKeys > AI_MAX_ALLOC(aiVectorKey) || (size_t)nd->mNumScalingKeys > SIZE_MAX / sizeof(aiVectorKey)) {
throw DeadlyImportError("Assbin: Too many scaling keys, would overflow");
}
if (nd->mNumPositionKeys) {
if (shortened) {
ReadBounds(stream, nd->mPositionKeys, nd->mNumPositionKeys);
} // else write as usual
else {
} else {
nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
ReadArray<aiVectorKey>(stream, nd->mPositionKeys, nd->mNumPositionKeys);
ReadArray(stream, nd->mPositionKeys, nd->mNumPositionKeys);
}
}
if (nd->mNumRotationKeys) {
if (shortened) {
ReadBounds(stream, nd->mRotationKeys, nd->mNumRotationKeys);
} else {
// else write as usual
nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
ReadArray<aiQuatKey>(stream, nd->mRotationKeys, nd->mNumRotationKeys);
ReadArray(stream, nd->mRotationKeys, nd->mNumRotationKeys);
}
}
if (nd->mNumScalingKeys) {
if (shortened) {
ReadBounds(stream, nd->mScalingKeys, nd->mNumScalingKeys);
} else {
// else write as usual
nd->mScalingKeys = new aiVectorKey[nd->mNumScalingKeys];
ReadArray<aiVectorKey>(stream, nd->mScalingKeys, nd->mNumScalingKeys);
ReadArray(stream, nd->mScalingKeys, nd->mNumScalingKeys);
}
}
}
@@ -517,6 +570,10 @@ void AssbinImporter::ReadBinaryAnim(IOStream *stream, aiAnimation *anim) {
anim->mTicksPerSecond = Read<double>(stream);
anim->mNumChannels = Read<unsigned int>(stream);
if (anim->mNumChannels > AI_MAX_ALLOC(aiNodeAnim *) || (size_t)anim->mNumChannels > SIZE_MAX / sizeof(aiNodeAnim *)) {
throw DeadlyImportError("Assbin: Too many animation channels, would overflow");
}
if (anim->mNumChannels) {
anim->mChannels = new aiNodeAnim *[anim->mNumChannels];
for (unsigned int a = 0; a < anim->mNumChannels; ++a) {
@@ -528,9 +585,10 @@ void AssbinImporter::ReadBinaryAnim(IOStream *stream, aiAnimation *anim) {
// -----------------------------------------------------------------------------------
void AssbinImporter::ReadBinaryTexture(IOStream *stream, aiTexture *tex) {
if (Read<uint32_t>(stream) != ASSBIN_CHUNK_AITEXTURE)
if (Read<uint32_t>(stream) != ASSBIN_CHUNK_AITEXTURE) {
throw DeadlyImportError("Magic chunk identifiers are wrong!");
/*uint32_t size =*/Read<uint32_t>(stream);
}
Read<uint32_t>(stream); // size
tex->mWidth = Read<unsigned int>(stream);
tex->mHeight = Read<unsigned int>(stream);
@@ -538,11 +596,26 @@ void AssbinImporter::ReadBinaryTexture(IOStream *stream, aiTexture *tex) {
if (!shortened) {
if (!tex->mHeight) {
if (tex->mWidth > AI_MAX_ALLOC(aiTexel)) {
throw DeadlyImportError("Assbin: Texture width too large, would overflow");
}
tex->pcData = new aiTexel[tex->mWidth];
stream->Read(tex->pcData, 1, tex->mWidth);
if (stream->Read(tex->pcData, 1, tex->mWidth) != tex->mWidth) {
throw DeadlyImportError("Assbin: Unexpected EOF reading compressed texture data");
}
} else {
tex->pcData = new aiTexel[tex->mWidth * tex->mHeight];
stream->Read(tex->pcData, 1, tex->mWidth * tex->mHeight * 4);
if (tex->mWidth != 0 &&
static_cast<size_t>(tex->mHeight) >
SIZE_MAX / sizeof(aiTexel) / static_cast<size_t>(tex->mWidth)) {
throw DeadlyImportError("Assbin: Texture dimensions too large");
}
const size_t pixelCount = static_cast<size_t>(tex->mWidth) * tex->mHeight;
const size_t byteCount = pixelCount * sizeof(aiTexel);
tex->pcData = new aiTexel[pixelCount];
if (stream->Read(tex->pcData, 1, byteCount) != byteCount) {
throw DeadlyImportError("Assbin: Unexpected EOF reading texture data");
}
}
}
}
@@ -612,8 +685,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read all meshes
if (scene->mNumMeshes) {
scene->mMeshes = new aiMesh *[scene->mNumMeshes];
memset(scene->mMeshes, 0, scene->mNumMeshes * sizeof(aiMesh *));
scene->mMeshes = new aiMesh *[scene->mNumMeshes]();
for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
scene->mMeshes[i] = new aiMesh();
ReadBinaryMesh(stream, scene->mMeshes[i]);
@@ -622,8 +694,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read materials
if (scene->mNumMaterials) {
scene->mMaterials = new aiMaterial *[scene->mNumMaterials];
memset(scene->mMaterials, 0, scene->mNumMaterials * sizeof(aiMaterial *));
scene->mMaterials = new aiMaterial *[scene->mNumMaterials]();
for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
scene->mMaterials[i] = new aiMaterial();
ReadBinaryMaterial(stream, scene->mMaterials[i]);
@@ -632,8 +703,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read all animations
if (scene->mNumAnimations) {
scene->mAnimations = new aiAnimation *[scene->mNumAnimations];
memset(scene->mAnimations, 0, scene->mNumAnimations * sizeof(aiAnimation *));
scene->mAnimations = new aiAnimation *[scene->mNumAnimations]();
for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
scene->mAnimations[i] = new aiAnimation();
ReadBinaryAnim(stream, scene->mAnimations[i]);
@@ -642,8 +712,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read all textures
if (scene->mNumTextures) {
scene->mTextures = new aiTexture *[scene->mNumTextures];
memset(scene->mTextures, 0, scene->mNumTextures * sizeof(aiTexture *));
scene->mTextures = new aiTexture *[scene->mNumTextures]();
for (unsigned int i = 0; i < scene->mNumTextures; ++i) {
scene->mTextures[i] = new aiTexture();
ReadBinaryTexture(stream, scene->mTextures[i]);
@@ -652,8 +721,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read lights
if (scene->mNumLights) {
scene->mLights = new aiLight *[scene->mNumLights];
memset(scene->mLights, 0, scene->mNumLights * sizeof(aiLight *));
scene->mLights = new aiLight *[scene->mNumLights]();
for (unsigned int i = 0; i < scene->mNumLights; ++i) {
scene->mLights[i] = new aiLight();
ReadBinaryLight(stream, scene->mLights[i]);
@@ -662,8 +730,7 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// Read cameras
if (scene->mNumCameras) {
scene->mCameras = new aiCamera *[scene->mNumCameras];
memset(scene->mCameras, 0, scene->mNumCameras * sizeof(aiCamera *));
scene->mCameras = new aiCamera *[scene->mNumCameras]();
for (unsigned int i = 0; i < scene->mNumCameras; ++i) {
scene->mCameras[i] = new aiCamera();
ReadBinaryCamera(stream, scene->mCameras[i]);
@@ -673,7 +740,19 @@ void AssbinImporter::ReadBinaryScene(IOStream *stream, aiScene *scene) {
// -----------------------------------------------------------------------------------
void AssbinImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
IOStream *stream = pIOHandler->Open(pFile, "rb");
struct IOStreamDeleter {
IOSystem* io;
void operator()(IOStream* s) const {
if (s) {
io->Close(s);
}
}
};
auto stream = std::unique_ptr<IOStream, IOStreamDeleter>(
pIOHandler->Open(pFile, "rb"),
IOStreamDeleter{pIOHandler}
);
if (nullptr == stream) {
throw DeadlyImportError("ASSBIN: Could not open ", pFile);
}
@@ -681,54 +760,49 @@ void AssbinImporter::InternReadFile(const std::string &pFile, aiScene *pScene, I
// signature
stream->Seek(44, aiOrigin_CUR);
unsigned int versionMajor = Read<unsigned int>(stream);
unsigned int versionMinor = Read<unsigned int>(stream);
unsigned int versionMajor = Read<unsigned int>(stream.get());
unsigned int versionMinor = Read<unsigned int>(stream.get());
if (versionMinor != ASSBIN_VERSION_MINOR || versionMajor != ASSBIN_VERSION_MAJOR) {
throw DeadlyImportError("Invalid version, data format not compatible!");
}
/*unsigned int versionRevision =*/Read<unsigned int>(stream);
/*unsigned int compileFlags =*/Read<unsigned int>(stream);
/*unsigned int versionRevision =*/Read<unsigned int>(stream.get());
/*unsigned int compileFlags =*/Read<unsigned int>(stream.get());
shortened = Read<uint16_t>(stream) > 0;
compressed = Read<uint16_t>(stream) > 0;
shortened = Read<uint16_t>(stream.get()) > 0;
compressed = Read<uint16_t>(stream.get()) > 0;
if (shortened)
if (shortened) {
throw DeadlyImportError("Shortened binaries are not supported!");
}
stream->Seek(256, aiOrigin_CUR); // original filename
stream->Seek(128, aiOrigin_CUR); // options
stream->Seek(64, aiOrigin_CUR); // padding
if (compressed) {
uLongf uncompressedSize = Read<uint32_t>(stream);
uLongf uncompressedSize = Read<uint32_t>(stream.get());
uLongf compressedSize = static_cast<uLongf>(stream->FileSize() - stream->Tell());
unsigned char *compressedData = new unsigned char[compressedSize];
size_t len = stream->Read(compressedData, 1, compressedSize);
ai_assert(len == compressedSize);
std::vector<unsigned char> compressedData(compressedSize);
const size_t len = stream->Read(compressedData.data(), 1, compressedSize);
if (len != compressedSize) {
throw DeadlyImportError("ASSBIN: Unexpected EOF while reading compressed data");
}
unsigned char *uncompressedData = new unsigned char[uncompressedSize];
std::vector<unsigned char> uncompressedData(uncompressedSize);
int res = uncompress(uncompressedData, &uncompressedSize, compressedData, (uLong)len);
const int res = uncompress(uncompressedData.data(), &uncompressedSize, compressedData.data(), (uLong)len);
if (res != Z_OK) {
delete[] uncompressedData;
delete[] compressedData;
pIOHandler->Close(stream);
throw DeadlyImportError("Zlib decompression failed.");
}
MemoryIOStream io(uncompressedData, uncompressedSize);
MemoryIOStream io(uncompressedData.data(), uncompressedSize);
ReadBinaryScene(&io, pScene);
delete[] uncompressedData;
delete[] compressedData;
} else {
ReadBinaryScene(stream, pScene);
ReadBinaryScene(stream.get(), pScene);
}
pIOHandler->Close(stream);
}
#endif // !! ASSIMP_BUILD_NO_ASSBIN_IMPORTER
+2 -3
View File
@@ -1,9 +1,8 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -61,7 +60,7 @@ struct aiCamera;
#ifndef ASSIMP_BUILD_NO_ASSBIN_IMPORTER
namespace Assimp {
namespace Assimp {
// ---------------------------------------------------------------------------------
/** Importer class for 3D Studio r3 and r4 3DS files
+2 -3
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -50,7 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/IOSystem.hpp>
#include <assimp/Exporter.hpp>
namespace Assimp {
namespace Assimp {
void ExportSceneAssxml(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/)
{
+1 -2
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+9 -8
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -36,7 +35,6 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
@@ -79,8 +77,7 @@ static int ioprintf(IOStream *io, const char *format, ...) {
}
static const int Size = 4096;
char sz[Size];
::memset(sz, '\0', Size);
char sz[Size] = {};
va_list va;
va_start(va, format);
const unsigned int nSize = vsnprintf(sz, Size - 1, format, va);
@@ -223,7 +220,7 @@ static void WriteDump(const char *pFile, const char *cmd, const aiScene *scene,
const unsigned int majorVersion(aiGetVersionMajor());
const unsigned int minorVersion(aiGetVersionMinor());
const unsigned int rev(aiGetVersionRevision());
const char *curtime(asctime(p));
const char *curtime = asctime(p);
ioprintf(io, header.c_str(), majorVersion, minorVersion, rev, pFile, c.c_str(), curtime, scene->mFlags, 0u);
// write the node graph
@@ -304,7 +301,11 @@ static void WriteDump(const char *pFile, const char *cmd, const aiScene *scene,
bool compressed = (tex->mHeight == 0);
// mesh header
ioprintf(io, "\t<Texture width=\"%u\" height=\"%u\" compressed=\"%s\"> \n",
std::string texName = "unknown";
if (tex->mFilename.length != 0u) {
texName = tex->mFilename.data;
}
ioprintf(io, "\t<Texture name=\"%s\" width=\"%u\" height=\"%u\" compressed=\"%s\"> \n", texName.c_str(),
(compressed ? -1 : tex->mWidth), (compressed ? -1 : tex->mHeight),
(compressed ? "true" : "false"));
@@ -352,7 +353,7 @@ static void WriteDump(const char *pFile, const char *cmd, const aiScene *scene,
for (unsigned int n = 0; n < mat->mNumProperties; ++n) {
const aiMaterialProperty *prop = mat->mProperties[n];
const char *sz = "";
auto sz = "";
if (prop->mType == aiPTI_Float) {
sz = "float";
} else if (prop->mType == aiPTI_Integer) {
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+39 -23
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef ASSIMP_BUILD_NO_B3D_IMPORTER
// internal headers
#include "AssetLib/B3D/B3DImporter.h"
#include "B3DImporter.h"
#include "PostProcessing/ConvertToLHProcess.h"
#include "PostProcessing/TextureTransform.h"
@@ -234,7 +234,18 @@ string B3DImporter::ReadChunk() {
ASSIMP_LOG_DEBUG("ReadChunk: ", tag);
#endif
unsigned sz = (unsigned)ReadInt();
_stack.push_back(_pos + sz);
// Validate the chunk extent before trusting it: a chunk must lie within
// the file and within its enclosing chunk. Without this check a crafted
// size lets ChunkSize() -- and the element counts derived from it in
// ReadVRTS()/ReadTRIS() -- run far past the buffer.
if (sz > _buf.size() - _pos) {
Fail("Bad chunk size");
}
const size_t end = _pos + sz;
if (!_stack.empty() && end > _stack.back()) {
Fail("Bad chunk size");
}
_stack.push_back(end);
return tag;
}
@@ -246,7 +257,9 @@ void B3DImporter::ExitChunk() {
// ------------------------------------------------------------------------------------------------
size_t B3DImporter::ChunkSize() {
return _stack.back() - _pos;
// _stack.back() is the validated end offset of the current chunk; guard
// against unsigned underflow should _pos ever be advanced past it.
return _stack.back() > _pos ? _stack.back() - _pos : 0;
}
// ------------------------------------------------------------------------------------------------
@@ -469,9 +482,11 @@ void B3DImporter::ReadBONE(int id) {
}
// ------------------------------------------------------------------------------------------------
void B3DImporter::ReadKEYS(aiNodeAnim *nodeAnim) {
vector<aiVectorKey> trans, scale;
vector<aiQuatKey> rot;
void B3DImporter::ReadKEYS(AnimKeys& keys) {
vector<aiVectorKey>& trans = keys.positionKeys;
vector<aiVectorKey>& scale = keys.scalingKeys;
vector<aiQuatKey>& rot = keys.rotationKeys;
int flags = ReadInt();
while (ChunkSize()) {
int frame = ReadInt();
@@ -485,21 +500,6 @@ void B3DImporter::ReadKEYS(aiNodeAnim *nodeAnim) {
rot.emplace_back(frame, ReadQuat());
}
}
if (flags & 1) {
nodeAnim->mNumPositionKeys = static_cast<unsigned int>(trans.size());
nodeAnim->mPositionKeys = to_array(trans);
}
if (flags & 2) {
nodeAnim->mNumScalingKeys = static_cast<unsigned int>(scale.size());
nodeAnim->mScalingKeys = to_array(scale);
}
if (flags & 4) {
nodeAnim->mNumRotationKeys = static_cast<unsigned int>(rot.size());
nodeAnim->mRotationKeys = to_array(rot);
}
}
// ------------------------------------------------------------------------------------------------
@@ -542,6 +542,7 @@ aiNode *B3DImporter::ReadNODE(aiNode *parent) {
std::unique_ptr<aiNodeAnim> nodeAnim;
vector<unsigned> meshes;
vector<aiNode *> children;
AnimKeys keys;
while (ChunkSize()) {
const string chunk = ReadChunk();
@@ -560,7 +561,7 @@ aiNode *B3DImporter::ReadNODE(aiNode *parent) {
nodeAnim.reset(new aiNodeAnim);
nodeAnim->mNodeName = node->mName;
}
ReadKEYS(nodeAnim.get());
ReadKEYS(keys);
} else if (chunk == "NODE") {
aiNode *child = ReadNODE(node);
children.push_back(child);
@@ -569,6 +570,21 @@ aiNode *B3DImporter::ReadNODE(aiNode *parent) {
}
if (nodeAnim) {
if (!keys.positionKeys.empty()) {
nodeAnim->mNumPositionKeys = static_cast<unsigned int>(keys.positionKeys.size());
nodeAnim->mPositionKeys = to_array(keys.positionKeys);
}
if (!keys.scalingKeys.empty()) {
nodeAnim->mNumScalingKeys = static_cast<unsigned int>(keys.scalingKeys.size());
nodeAnim->mScalingKeys = to_array(keys.scalingKeys);
}
if (!keys.rotationKeys.empty()) {
nodeAnim->mNumRotationKeys = static_cast<unsigned int>(keys.rotationKeys.size());
nodeAnim->mRotationKeys = to_array(keys.rotationKeys);
}
_nodeAnims.emplace_back(std::move(nodeAnim));
}
+10 -3
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -49,6 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/types.h>
#include <assimp/mesh.h>
#include <assimp/material.h>
#include <assimp/anim.h>
#include <assimp/BaseImporter.h>
#include <memory>
@@ -60,7 +61,7 @@ struct aiAnimation;
namespace Assimp{
class B3DImporter : public BaseImporter{
class B3DImporter final : public BaseImporter{
public:
B3DImporter() = default;
~B3DImporter() override;
@@ -94,6 +95,12 @@ private:
float weights[4];
};
struct AnimKeys {
std::vector<aiVectorKey> positionKeys;
std::vector<aiVectorKey> scalingKeys;
std::vector<aiQuatKey> rotationKeys;
};
AI_WONT_RETURN void Oops() AI_WONT_RETURN_SUFFIX;
AI_WONT_RETURN void Fail(const std::string &str) AI_WONT_RETURN_SUFFIX;
@@ -104,7 +111,7 @@ private:
void ReadTRIS( int v0 );
void ReadMESH();
void ReadBONE( int id );
void ReadKEYS( aiNodeAnim *nodeAnim );
void ReadKEYS( AnimKeys& keys );
void ReadANIM();
aiNode *ReadNODE( aiNode *parent );
+5 -9
View File
@@ -4,9 +4,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -85,11 +83,9 @@ BVHLoader::BVHLoader() :
mLine(),
mAnimTickDuration(),
mAnimNumFrames(),
noSkeletonMesh() {}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
BVHLoader::~BVHLoader() = default;
noSkeletonMesh() {
// empty
}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
@@ -389,7 +385,7 @@ float BVHLoader::GetNextTokenAsFloat() {
// check if the float is valid by testing if the atof() function consumed every char of the token
const char *ctoken = token.c_str();
float result = 0.0f;
ctoken = fast_atoreal_move<float>(ctoken, result);
ctoken = fast_atoreal_move(ctoken, result);
if (ctoken != token.c_str() + token.length())
ThrowException("Expected a floating point number, but found \"", token, "\".");
+9 -15
View File
@@ -4,8 +4,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -62,7 +61,7 @@ namespace Assimp {
* the hierarchy. It contains no actual mesh data, but we generate a dummy mesh
* inside the loader just to be able to see something.
*/
class BVHLoader : public BaseImporter {
class BVHLoader final : public BaseImporter {
/** Possible animation channels for which the motion data holds the values */
enum ChannelType {
@@ -80,32 +79,27 @@ class BVHLoader : public BaseImporter {
std::vector<ChannelType> mChannels;
std::vector<float> mChannelValues; // motion data values for that node. Of size NumChannels * NumFrames
Node() :
mNode(nullptr) {}
explicit Node(const aiNode *pNode) :
mNode(pNode) {}
Node() : mNode(nullptr) {}
explicit Node(const aiNode *pNode) :mNode(pNode) {}
};
public:
BVHLoader();
~BVHLoader();
~BVHLoader() override = default;
public:
/** Returns whether the class can handle the format of the given file.
* See BaseImporter::CanRead() for details. */
bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool cs) const;
bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool cs) const override;
void SetupProperties(const Importer *pImp);
const aiImporterDesc *GetInfo() const;
void SetupProperties(const Importer *pImp) override;
const aiImporterDesc *GetInfo() const override;
protected:
/** Imports the given file into the given scene structure.
* See BaseImporter::InternReadFile() for details
*/
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler);
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) override;
protected:
/** Reads the file */
void ReadStructure(aiScene *pScene);
+4 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
@@ -74,7 +74,9 @@ BlenderBMeshConverter::~BlenderBMeshConverter() {
// ------------------------------------------------------------------------------------------------
bool BlenderBMeshConverter::ContainsBMesh() const {
// TODO - Should probably do some additional verification here
if (BMesh == nullptr) {
return false;
}
return BMesh->totpoly && BMesh->totloop && BMesh->totvert;
}
+5 -7
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
@@ -63,14 +63,12 @@ namespace Assimp
struct MLoop;
}
class BlenderBMeshConverter: public LogFunctions< BlenderBMeshConverter >
class BlenderBMeshConverter final : public LogFunctions< BlenderBMeshConverter >
{
public:
BlenderBMeshConverter( const Blender::Mesh* mesh );
~BlenderBMeshConverter( );
bool ContainsBMesh( ) const;
explicit BlenderBMeshConverter( const Blender::Mesh* mesh );
~BlenderBMeshConverter();
bool ContainsBMesh() const;
const Blender::Mesh* TriangulateBMesh( );
private:
+3 -2
View File
@@ -96,7 +96,7 @@ struct CustomDataTypeDescription {
* other (like CD_ORCO, ...) uses arrays of rawtypes or even arrays of Structures
* use a special readfunction for that cases
*/
static std::array<CustomDataTypeDescription, CD_NUMTYPES> customDataTypeDescriptions = { {
static const std::array<CustomDataTypeDescription, CD_NUMTYPES> customDataTypeDescriptions = { {
DECL_STRUCT_CUSTOMDATATYPEDESCRIPTION(MVert),
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION,
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION,
@@ -142,7 +142,8 @@ static std::array<CustomDataTypeDescription, CD_NUMTYPES> customDataTypeDescript
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION,
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION,
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION } };
DECL_UNSUPPORTED_CUSTOMDATATYPEDESCRIPTION
} };
bool isValidCustomDataType(const int cdtype) {
return cdtype >= 0 && cdtype < CD_NUMTYPES;
+1 -2
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+38 -64
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -56,14 +55,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// enable verbose log output. really verbose, so be careful.
#ifdef ASSIMP_BUILD_DEBUG
#define ASSIMP_BUILD_BLENDER_DEBUG
# define ASSIMP_BUILD_BLENDER_DEBUG
#endif
// set this to non-zero to dump BlenderDNA stuff to dna.txt.
// you could set it on the assimp build command line too without touching it here.
// !!! please make sure this is set to 0 in the repo !!!
#ifndef ASSIMP_BUILD_BLENDER_DEBUG_DNA
#define ASSIMP_BUILD_BLENDER_DEBUG_DNA 0
# define ASSIMP_BUILD_BLENDER_DEBUG_DNA 0
#endif
// #define ASSIMP_BUILD_BLENDER_NO_STATS
@@ -125,22 +124,14 @@ struct ElemBase {
* they used to point to.*/
// -------------------------------------------------------------------------------
struct Pointer {
Pointer() :
val() {
// empty
}
uint64_t val;
uint64_t val{0};
};
// -------------------------------------------------------------------------------
/** Represents a generic offset within a BLEND file */
// -------------------------------------------------------------------------------
struct FileOffset {
FileOffset() :
val() {
// empty
}
uint64_t val;
uint64_t val{0};
};
// -------------------------------------------------------------------------------
@@ -205,7 +196,7 @@ enum ErrorPolicy {
};
#ifdef ASSIMP_BUILD_BLENDER_DEBUG
#define ErrorPolicy_Igno ErrorPolicy_Warn
# define ErrorPolicy_Igno ErrorPolicy_Warn
#endif
// -------------------------------------------------------------------------------
@@ -397,10 +388,9 @@ private:
mutable size_t cache_idx;
};
// --------------------------------------------------------
template <>
// -------------------------------------------------------------------------------------------------------
template<>
struct Structure::_defaultInitializer<ErrorPolicy_Warn> {
template <typename T>
void operator()(T &out, const char *reason = "<add reason>") {
ASSIMP_LOG_WARN(reason);
@@ -410,9 +400,9 @@ struct Structure::_defaultInitializer<ErrorPolicy_Warn> {
}
};
template <>
// -------------------------------------------------------------------------------------------------------
template<>
struct Structure::_defaultInitializer<ErrorPolicy_Fail> {
template <typename T>
void operator()(T & /*out*/, const char *message = "") {
// obviously, it is crucial that _DefaultInitializer is used
@@ -620,31 +610,23 @@ public:
/** Import statistics, i.e. number of file blocks read*/
// -------------------------------------------------------------------------------
class Statistics {
public:
Statistics() :
fields_read(), pointers_resolved(), cache_hits()
// , blocks_read ()
,
cached_objects() {}
Statistics() = default;
~Statistics() = default;
public:
/** total number of fields we read */
unsigned int fields_read;
/// total number of fields we read
unsigned int fields_read = 0;
/** total number of resolved pointers */
unsigned int pointers_resolved;
/// total number of resolved pointers
unsigned int pointers_resolved = 0;
/** number of pointers resolved from the cache */
unsigned int cache_hits;
/// number of pointers resolved from the cache
unsigned int cache_hits = 0;
/** number of blocks (from FileDatabase::entries)
we did actually read from. */
// unsigned int blocks_read;
/** objects in FileData::cache */
unsigned int cached_objects;
/// objects in FileData::cache
unsigned int cached_objects = 0;
};
#endif
// -------------------------------------------------------------------------------
@@ -657,15 +639,13 @@ public:
typedef std::map<Pointer, TOUT<ElemBase>> StructureCache;
public:
ObjectCache(const FileDatabase &db) :
db(db) {
explicit ObjectCache(const FileDatabase &db) : db(db) {
// currently there are only ~400 structure records per blend file.
// we read only a small part of them and don't cache objects
// which we don't need, so this should suffice.
caches.reserve(64);
}
public:
// --------------------------------------------------------
/** Check whether a specific item is in the cache.
* @param s Data type of the item
@@ -673,10 +653,7 @@ public:
* cache doesn't know the item yet.
* @param ptr Item address to look for. */
template <typename T>
void get(
const Structure &s,
TOUT<T> &out,
const Pointer &ptr) const;
void get( const Structure &s,TOUT<T> &out, const Pointer &ptr) const;
// --------------------------------------------------------
/** Add an item to the cache after the item has
@@ -701,7 +678,7 @@ private:
template <>
class ObjectCache<Blender::vector> {
public:
ObjectCache(const FileDatabase &) {}
explicit ObjectCache(const FileDatabase &) {}
template <typename T>
void get(const Structure &, vector<T> &, const Pointer &) {}
@@ -710,7 +687,7 @@ public:
};
#ifdef _MSC_VER
#pragma warning(disable : 4355)
# pragma warning(disable : 4355)
#endif
// -------------------------------------------------------------------------------
@@ -725,16 +702,6 @@ public:
FileDatabase() :
_cacheArrays(*this), _cache(*this), next_cache_idx() {}
public:
// publicly accessible fields
bool i64bit;
bool little;
DNA dna;
std::shared_ptr<StreamReaderAny> reader;
vector<FileBlockHead> entries;
public:
Statistics &stats() const {
return _stats;
}
@@ -753,6 +720,15 @@ public:
return _cacheArrays;
}
public:
// publicly accessible fields
bool i64bit;
bool little;
DNA dna;
std::shared_ptr<StreamReaderAny> reader;
vector<FileBlockHead> entries;
private:
#ifndef ASSIMP_BUILD_BLENDER_NO_STATS
mutable Statistics _stats;
@@ -765,20 +741,19 @@ private:
};
#ifdef _MSC_VER
#pragma warning(default : 4355)
# pragma warning(default : 4355)
#endif
// -------------------------------------------------------------------------------
/** Factory to extract a #DNA from the DNA1 file block in a BLEND file. */
// -------------------------------------------------------------------------------
class DNAParser {
public:
/** Bind the parser to a empty DNA and an input stream */
DNAParser(FileDatabase &db) :
db(db) {}
explicit DNAParser(FileDatabase &db) : db(db) {
// empty
}
public:
// --------------------------------------------------------
/** Locate the DNA in the file and parse it. The input
* stream is expected to point to the beginning of the DN1
@@ -789,7 +764,6 @@ public:
* afterwards.*/
void Parse();
public:
/** Obtain a reference to the extracted DNA information */
const Blender::DNA &GetDNA() const {
return db.dna;
+4 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -841,5 +841,7 @@ template <template <typename> class TOUT> template <typename T> void ObjectCache
#endif
}
}}
}
}
#endif
+3 -4
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -117,7 +116,7 @@ namespace Blender {
mywrap arr;
};
#ifdef _MSC_VER
#if defined(_MSC_VER) && _MSC_VER < 1900
# pragma warning(disable:4351)
#endif
@@ -172,7 +171,7 @@ namespace Blender {
// original file data
const FileDatabase& db;
};
#ifdef _MSC_VER
#if defined(_MSC_VER) && _MSC_VER < 1900
# pragma warning(default:4351)
#endif
+5 -6
View File
@@ -1,10 +1,8 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -110,7 +108,7 @@ BlenderImporter::~BlenderImporter() {
delete modifier_cache;
}
static const char Token[] = "BLENDER";
static constexpr char Token[] = "BLENDER";
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
@@ -495,8 +493,9 @@ void BlenderImporter::BuildDefaultMaterial(Blender::ConversionData &conv_data) {
if (index == static_cast<unsigned int>(-1)) {
// Setup a default material.
std::shared_ptr<Material> p(new Material());
ai_assert(::strlen(AI_DEFAULT_MATERIAL_NAME) < sizeof(p->id.name) - 2);
strcpy(p->id.name + 2, AI_DEFAULT_MATERIAL_NAME);
const size_t len = ::strlen(AI_DEFAULT_MATERIAL_NAME);
ai_assert(len < sizeof(p->id.name) - 2);
memcpy(p->id.name + 2, AI_DEFAULT_MATERIAL_NAME, len);
// Note: MSVC11 does not zero-initialize Material here, although it should.
// Thus all relevant fields should be explicitly initialized. We cannot add
+2 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -105,7 +105,7 @@ class BlenderModifier;
* call it is outsourced to BlenderDNA.cpp/BlenderDNA.h. This class only performs the
* conversion from intermediate format to aiScene. */
// -------------------------------------------------------------------------------------------
class BlenderImporter : public BaseImporter, public LogFunctions<BlenderImporter> {
class BlenderImporter final : public BaseImporter, public LogFunctions<BlenderImporter> {
public:
BlenderImporter();
~BlenderImporter() override;
+1 -2
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+3 -4
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -115,7 +114,7 @@ private:
* Mirror modifier. Status: implemented.
*/
// -------------------------------------------------------------------------------------------
class BlenderModifier_Mirror : public BlenderModifier {
class BlenderModifier_Mirror final : public BlenderModifier {
public:
// --------------------
virtual bool IsActive( const ModifierData& modin);
@@ -132,7 +131,7 @@ public:
// -------------------------------------------------------------------------------------------
/** Subdivision modifier. Status: dummy. */
// -------------------------------------------------------------------------------------------
class BlenderModifier_Subdivision : public BlenderModifier {
class BlenderModifier_Subdivision final : public BlenderModifier {
public:
// --------------------
+46 -50
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -48,8 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h"
namespace Assimp {
namespace Blender {
namespace Assimp::Blender {
// Minor parts of this file are extracts from blender data structures,
// declared in the ./source/blender/makesdna directory.
@@ -116,32 +114,32 @@ struct Collection;
static const size_t MaxNameLen = 1024;
// -------------------------------------------------------------------------------
struct ID : ElemBase {
struct ID final : ElemBase {
char name[MaxNameLen] WARN;
short flag;
};
// -------------------------------------------------------------------------------
struct ListBase : ElemBase {
struct ListBase final : ElemBase {
std::shared_ptr<ElemBase> first;
std::weak_ptr<ElemBase> last;
};
// -------------------------------------------------------------------------------
struct PackedFile : ElemBase {
struct PackedFile final : ElemBase {
int size WARN;
int seek WARN;
std::shared_ptr<FileOffset> data WARN;
};
// -------------------------------------------------------------------------------
struct GroupObject : ElemBase {
struct GroupObject final : ElemBase {
std::shared_ptr<GroupObject> prev, next FAIL;
std::shared_ptr<Object> ob;
};
// -------------------------------------------------------------------------------
struct Group : ElemBase {
struct Group final : ElemBase {
ID id FAIL;
int layer;
@@ -149,32 +147,32 @@ struct Group : ElemBase {
};
// -------------------------------------------------------------------------------
struct CollectionObject : ElemBase {
struct CollectionObject final : ElemBase {
//CollectionObject* prev;
std::shared_ptr<CollectionObject> next;
Object *ob;
};
// -------------------------------------------------------------------------------
struct CollectionChild : ElemBase {
struct CollectionChild final : ElemBase {
std::shared_ptr<CollectionChild> next, prev;
std::shared_ptr<Collection> collection;
};
// -------------------------------------------------------------------------------
struct Collection : ElemBase {
struct Collection final : ElemBase {
ID id FAIL;
ListBase gobject; // CollectionObject
ListBase children; // CollectionChild
};
// -------------------------------------------------------------------------------
struct World : ElemBase {
struct World final : ElemBase {
ID id FAIL;
};
// -------------------------------------------------------------------------------
struct MVert : ElemBase {
struct MVert final : ElemBase {
float co[3] FAIL;
float no[3] FAIL; // read as short and divided through / 32767.f
char flag;
@@ -186,31 +184,31 @@ struct MVert : ElemBase {
};
// -------------------------------------------------------------------------------
struct MEdge : ElemBase {
struct MEdge final : ElemBase {
int v1, v2 FAIL;
char crease, bweight;
short flag;
};
// -------------------------------------------------------------------------------
struct MLoop : ElemBase {
struct MLoop final : ElemBase {
int v, e;
};
// -------------------------------------------------------------------------------
struct MLoopUV : ElemBase {
struct MLoopUV final : ElemBase {
float uv[2];
int flag;
};
// -------------------------------------------------------------------------------
// Note that red and blue are not swapped, as with MCol
struct MLoopCol : ElemBase {
struct MLoopCol final : ElemBase {
unsigned char r, g, b, a;
};
// -------------------------------------------------------------------------------
struct MPoly : ElemBase {
struct MPoly final : ElemBase {
int loopstart;
int totloop;
short mat_nr;
@@ -218,26 +216,26 @@ struct MPoly : ElemBase {
};
// -------------------------------------------------------------------------------
struct MTexPoly : ElemBase {
struct MTexPoly final : ElemBase {
Image *tpage;
char flag, transp;
short mode, tile, pad;
};
// -------------------------------------------------------------------------------
struct MCol : ElemBase {
struct MCol final : ElemBase {
char r, g, b, a FAIL;
};
// -------------------------------------------------------------------------------
struct MFace : ElemBase {
struct MFace final : ElemBase {
int v1, v2, v3, v4 FAIL;
int mat_nr FAIL;
char flag;
};
// -------------------------------------------------------------------------------
struct TFace : ElemBase {
struct TFace final : ElemBase {
float uv[4][2] FAIL;
int col[4] FAIL;
char flag;
@@ -247,7 +245,7 @@ struct TFace : ElemBase {
};
// -------------------------------------------------------------------------------
struct MTFace : ElemBase {
struct MTFace final : ElemBase {
MTFace() :
flag(0),
mode(0),
@@ -265,24 +263,24 @@ struct MTFace : ElemBase {
};
// -------------------------------------------------------------------------------
struct MDeformWeight : ElemBase {
struct MDeformWeight final : ElemBase {
int def_nr FAIL;
float weight FAIL;
};
// -------------------------------------------------------------------------------
struct MDeformVert : ElemBase {
struct MDeformVert final : ElemBase {
vector<MDeformWeight> dw WARN;
int totweight;
};
// -------------------------------------------------------------------------------
#define MA_RAYMIRROR 0x40000
#define MA_TRANSPARENCY 0x10000
#define MA_RAYTRANSP 0x20000
#define MA_ZTRANSP 0x00040
constexpr uint32_t MA_RAYMIRROR = 0x40000;
constexpr uint32_t MA_TRANSPARENCY = 0x10000;
constexpr uint32_t MA_RAYTRANSP = 0x20000;
constexpr uint32_t MA_ZTRANSP = 0x00040;
struct Material : ElemBase {
struct Material final : ElemBase {
ID id FAIL;
float r, g, b WARN;
@@ -404,7 +402,7 @@ CustomDataLayer 104
char name 32 64
void *data 96 8
*/
struct CustomDataLayer : ElemBase {
struct CustomDataLayer final : ElemBase {
int type;
int offset;
int flag;
@@ -442,7 +440,7 @@ CustomData 208
BLI_mempool *pool 192 8
CustomDataExternal *external 200 8
*/
struct CustomData : ElemBase {
struct CustomData final : ElemBase {
vector<std::shared_ptr<struct CustomDataLayer>> layers;
int typemap[42]; // CD_NUMTYPES
int totlayer;
@@ -455,7 +453,7 @@ struct CustomData : ElemBase {
};
// -------------------------------------------------------------------------------
struct Mesh : ElemBase {
struct Mesh final : ElemBase {
ID id FAIL;
int totface FAIL;
@@ -492,7 +490,7 @@ struct Mesh : ElemBase {
};
// -------------------------------------------------------------------------------
struct Library : ElemBase {
struct Library final : ElemBase {
ID id FAIL;
char name[240] WARN;
@@ -516,7 +514,7 @@ struct Camera : ElemBase {
};
// -------------------------------------------------------------------------------
struct Lamp : ElemBase {
struct Lamp final : ElemBase {
enum FalloffType {
FalloffType_Constant = 0x0,
@@ -603,7 +601,7 @@ struct Lamp : ElemBase {
};
// -------------------------------------------------------------------------------
struct ModifierData : ElemBase {
struct ModifierData final : ElemBase {
enum ModifierType {
eModifierType_None = 0,
eModifierType_Subsurf,
@@ -653,9 +651,8 @@ struct SharedModifierData : ElemBase {
ModifierData modifier;
};
// -------------------------------------------------------------------------------
struct SubsurfModifierData : SharedModifierData {
struct SubsurfModifierData final : SharedModifierData {
enum Type {
@@ -675,7 +672,7 @@ struct SubsurfModifierData : SharedModifierData {
};
// -------------------------------------------------------------------------------
struct MirrorModifierData : SharedModifierData {
struct MirrorModifierData final : SharedModifierData {
enum Flags {
Flags_CLIPPING = 1 << 0,
@@ -693,7 +690,7 @@ struct MirrorModifierData : SharedModifierData {
};
// -------------------------------------------------------------------------------
struct Object : ElemBase {
struct Object final : ElemBase {
ID id FAIL;
enum Type {
@@ -734,7 +731,7 @@ struct Object : ElemBase {
};
// -------------------------------------------------------------------------------
struct Base : ElemBase {
struct Base final : ElemBase {
Base *prev WARN;
std::shared_ptr<Base> next WARN;
std::shared_ptr<Object> object WARN;
@@ -746,7 +743,7 @@ struct Base : ElemBase {
};
// -------------------------------------------------------------------------------
struct Scene : ElemBase {
struct Scene final : ElemBase {
ID id FAIL;
std::shared_ptr<Object> camera WARN;
@@ -760,7 +757,7 @@ struct Scene : ElemBase {
};
// -------------------------------------------------------------------------------
struct Image : ElemBase {
struct Image final : ElemBase {
ID id FAIL;
char name[240] WARN;
@@ -790,7 +787,7 @@ struct Image : ElemBase {
};
// -------------------------------------------------------------------------------
struct Tex : ElemBase {
struct Tex final : ElemBase {
// actually, the only texture type we support is Type_IMAGE
enum Type {
@@ -875,14 +872,13 @@ struct Tex : ElemBase {
//char use_nodes;
Tex() :
imaflag(ImageFlags_INTERPOL), type(Type_CLOUDS) {
Tex() : imaflag(ImageFlags_INTERPOL), type(Type_CLOUDS) {
// empty
}
};
// -------------------------------------------------------------------------------
struct MTex : ElemBase {
struct MTex final : ElemBase {
enum Projection {
Proj_N = 0,
@@ -971,6 +967,6 @@ struct MTex : ElemBase {
MTex() = default;
};
} // namespace Blender
} // namespace Assimp
} // namespace Assimp::Blender
#endif
+1 -1
View File
@@ -47,7 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h"
#include "BlenderScene.h"
namespace Assimp {
namespace Assimp {
namespace Blender {
template <> void Structure :: Convert<Object> (
+8 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -381,7 +381,14 @@ inline PointP2T& BlenderTessellatorP2T::GetActualPointStructure( p2t::Point& poi
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Winvalid-offsetof"
#endif // __clang__
#if defined __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif // __GNUC__
unsigned int pointOffset = offsetof( PointP2T, point2D );
#if defined __GNUC__
# pragma GCC diagnostic pop
#endif // __GNUC__
#if defined __clang__
# pragma clang diagnostic pop
#endif
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+3 -11
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2021, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
@@ -64,7 +64,7 @@ namespace {
aiString aiStringFrom(cineware::String const & cinestring) {
aiString result;
cinestring.GetCString(result.data, MAXLEN-1);
cinestring.GetCString(result.data, AI_MAXLEN - 1);
result.length = static_cast<ai_uint32>(cinestring.GetLength());
return result;
}
@@ -86,7 +86,7 @@ namespace Assimp {
}
}
static const aiImporterDesc desc = {
static constexpr aiImporterDesc desc = {
"Cinema4D Importer",
"",
"",
@@ -99,13 +99,6 @@ static const aiImporterDesc desc = {
"c4d"
};
// ------------------------------------------------------------------------------------------------
C4DImporter::C4DImporter() = default;
// ------------------------------------------------------------------------------------------------
C4DImporter::~C4DImporter() = default;
// ------------------------------------------------------------------------------------------------
bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const {
const std::string& extension = GetExtension(pFile);
@@ -196,7 +189,6 @@ void C4DImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS
std::copy(materials.begin(), materials.end(), pScene->mMaterials);
}
// ------------------------------------------------------------------------------------------------
bool C4DImporter::ReadShader(aiMaterial* out, BaseShader* shader) {
// based on Cineware sample code (C4DImportExport.cpp)
+3 -3
View File
@@ -63,7 +63,7 @@ namespace cineware {
class BaseShader;
}
namespace Assimp {
namespace Assimp {
// TinyFormatter.h
namespace Formatter {
template <typename T,typename TR, typename A> class basic_formatter;
@@ -78,8 +78,8 @@ namespace Assimp {
// -------------------------------------------------------------------------------------------
class C4DImporter : public BaseImporter, public LogFunctions<C4DImporter> {
public:
C4DImporter();
~C4DImporter() override;
C4DImporter() = default;
~C4DImporter() override = default;
bool CanRead( const std::string& pFile, IOSystem*, bool checkSig) const override;
protected:
+37 -19
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -45,8 +45,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef ASSIMP_BUILD_NO_COB_IMPORTER
#include "AssetLib/COB/COBLoader.h"
#include "AssetLib/COB/COBScene.h"
#include "COBLoader.h"
#include "COBScene.h"
#include "PostProcessing/ConvertToLHProcess.h"
#include <assimp/LineSplitter.h>
@@ -62,6 +62,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
namespace Assimp {
using namespace Assimp::COB;
using namespace Assimp::Formatter;
@@ -109,10 +110,29 @@ void COBImporter::SetupProperties(const Importer * /*pImp*/) {
}
// ------------------------------------------------------------------------------------------------
/*static*/ AI_WONT_RETURN void COBImporter::ThrowException(const std::string &msg) {
AI_WONT_RETURN void COBImporter::ThrowException(const std::string &msg) {
throw DeadlyImportError("COB: ", msg);
}
// ------------------------------------------------------------------------------------------------
static bool isValidASCIIHeader(const char *head) {
ai_assert(head != nullptr);
if (strncmp(head, "Caligari ", 9) != 0) {
COBImporter::ThrowException("Could not found magic id: `Caligari`");
}
if (strncmp(&head[9], "V00.", 4) != 0) {
COBImporter::ThrowException("Could not found Version tag: `V00.`");
}
ASSIMP_LOG_INFO("File format tag: ", std::string(head + 9, 6));
if (head[16] != 'L') {
COBImporter::ThrowException("File is big-endian, which is not supported");
}
return true;
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void COBImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
@@ -126,19 +146,15 @@ void COBImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSy
std::unique_ptr<StreamReaderLE> stream(new StreamReaderLE(file));
// check header
char head[32];
stream->CopyAndAdvance(head, 32);
if (strncmp(head, "Caligari ", 9) != 0) {
ThrowException("Could not found magic id: `Caligari`");
}
ASSIMP_LOG_INFO("File format tag: ", std::string(head + 9, 6));
if (head[16] != 'L') {
ThrowException("File is big-endian, which is not supported");
}
static constexpr size_t HeaderSize = 32u;
char head[HeaderSize] = {};
stream->CopyAndAdvance(head, HeaderSize);
// load data into intermediate structures
if (head[15] == 'A') {
if (!isValidASCIIHeader(head)) {
ThrowException("Invalid ASCII file header");
}
ReadAsciiFile(scene, stream.get());
} else {
ReadBinaryFile(scene, stream.get());
@@ -228,7 +244,7 @@ aiNode *COBImporter::BuildNodes(const Node &root, const Scene &scin, aiScene *fi
const Mesh &ndmesh = (const Mesh &)(root);
if (ndmesh.vertex_positions.size() && ndmesh.texture_coords.size()) {
typedef std::pair<const unsigned int, Mesh::FaceRefList> Entry;
using Entry = std::pair<const unsigned int, Mesh::FaceRefList>;
for (const Entry &reflist : ndmesh.temp_map) {
{ // create mesh
size_t n = 0;
@@ -372,9 +388,11 @@ aiNode *COBImporter::BuildNodes(const Node &root, const Scene &scin, aiScene *fi
}
// add children recursively
nd->mChildren = new aiNode *[root.temp_children.size()]();
for (const Node *n : root.temp_children) {
(nd->mChildren[nd->mNumChildren++] = BuildNodes(*n, scin, fill))->mParent = nd;
if (!root.temp_children.empty()) {
nd->mChildren = new aiNode *[root.temp_children.size()]();
for (const Node *n : root.temp_children) {
(nd->mChildren[nd->mNumChildren++] = BuildNodes(*n, scin, fill))->mParent = nd;
}
}
return nd;
@@ -1168,6 +1186,6 @@ void COBImporter::ReadUnit_Binary(COB::Scene &out, StreamReaderLE &reader, const
ASSIMP_LOG_WARN("`Unit` chunk ", nfo.id, " is a child of ", nfo.parent_id, " which does not exist");
}
}
} // namespace Assimp
#endif // ASSIMP_BUILD_NO_COB_IMPORTER
+7 -7
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -73,7 +72,7 @@ namespace COB {
*
* Currently relatively limited, loads only ASCII files and needs more test coverage. */
// -------------------------------------------------------------------------------------------
class COBImporter : public BaseImporter {
class COBImporter final : public BaseImporter {
public:
COBImporter() = default;
~COBImporter() override = default;
@@ -82,6 +81,10 @@ public:
bool CanRead(const std::string &pFile, IOSystem *pIOHandler,
bool checkSig) const override;
// -------------------------------------------------------------------
/** Prepend 'COB: ' and throw msg.*/
AI_WONT_RETURN static void ThrowException(const std::string &msg) AI_WONT_RETURN_SUFFIX;
protected:
// --------------------
const aiImporterDesc *GetInfo() const override;
@@ -94,10 +97,6 @@ protected:
IOSystem *pIOHandler) override;
private:
// -------------------------------------------------------------------
/** Prepend 'COB: ' and throw msg.*/
AI_WONT_RETURN static void ThrowException(const std::string &msg) AI_WONT_RETURN_SUFFIX;
// -------------------------------------------------------------------
/** @brief Read from an ascii scene/object file
* @param out Receives output data.
@@ -149,4 +148,5 @@ private:
}; // !class COBImporter
} // end of namespace Assimp
#endif // AI_UNREALIMPORTER_H_INC
+83 -76
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -52,68 +52,66 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <deque>
#include <map>
namespace Assimp {
namespace COB {
namespace Assimp::COB {
// ------------------
/** Represents a single vertex index in a face */
struct VertexIndex
{
struct VertexIndex {
// intentionally uninitialized
unsigned int pos_idx,uv_idx;
};
// ------------------
/** COB Face data structure */
struct Face
{
struct Face {
// intentionally uninitialized
unsigned int material, flags;
unsigned int material;
unsigned int flags;
std::vector<VertexIndex> indices;
};
// ------------------
/** COB chunk header information */
const unsigned int NO_SIZE = UINT_MAX;
constexpr unsigned int NO_SIZE = UINT_MAX;
struct ChunkInfo
{
ChunkInfo ()
: id (0)
, parent_id (0)
, version (0)
, size (NO_SIZE)
{}
struct ChunkInfo {
ChunkInfo() = default;
virtual ~ChunkInfo() = default;
// Id of this chunk, unique within file
unsigned int id;
unsigned int id{ 0 };
// and the corresponding parent
unsigned int parent_id;
unsigned int parent_id{ 0 };
// version. v1.23 becomes 123
unsigned int version;
unsigned int version{ 0 };
// chunk size in bytes, only relevant for binary files
// NO_SIZE is also valid.
unsigned int size;
unsigned int size{NO_SIZE};
};
// ------------------
/** A node in the scenegraph */
struct Node : public ChunkInfo
{
struct Node : ChunkInfo {
enum Type {
TYPE_MESH,TYPE_GROUP,TYPE_LIGHT,TYPE_CAMERA,TYPE_BONE
TYPE_INVALID = -1,
TYPE_MESH = 0,
TYPE_GROUP,
TYPE_LIGHT,
TYPE_CAMERA,
TYPE_BONE,
TYPE_COUNT
};
virtual ~Node() = default;
Node(Type type) : type(type), unit_scale(1.f){}
~Node() override = default;
explicit Node(Type type) : type(type), unit_scale(1.f){}
Type type;
// used during resolving
typedef std::deque<const Node*> ChildList;
using ChildList = std::deque<const Node*> ;
mutable ChildList temp_children;
// unique name
@@ -128,8 +126,7 @@ struct Node : public ChunkInfo
// ------------------
/** COB Mesh data structure */
struct Mesh : public Node
{
struct Mesh final : Node {
using ChunkInfo::operator=;
enum DrawFlags {
SOLID = 0x1,
@@ -162,107 +159,118 @@ struct Mesh : public Node
// ------------------
/** COB Group data structure */
struct Group : public Node
{
struct Group final : Node {
using ChunkInfo::operator=;
Group() : Node(TYPE_GROUP) {}
Group() : Node(TYPE_GROUP) {
// empty
}
};
// ------------------
/** COB Bone data structure */
struct Bone : public Node
{
struct Bone final : Node {
using ChunkInfo::operator=;
Bone() : Node(TYPE_BONE) {}
Bone() : Node(TYPE_BONE) {
// empty
}
};
// ------------------
/** COB Light data structure */
struct Light : public Node
{
struct Light final : Node {
enum LightType {
SPOT,LOCAL,INFINITE
SPOT,
LOCAL,
INFINITE
};
using ChunkInfo::operator=;
Light() : Node(TYPE_LIGHT),angle(),inner_angle(),ltype(SPOT) {}
Light() : Node(TYPE_LIGHT), ltype() {
// empty
}
aiColor3D color;
float angle,inner_angle;
float angle{ 0.0f };
float inner_angle{ 0.0f };
LightType ltype;
LightType ltype{SPOT};
};
// ------------------
/** COB Camera data structure */
struct Camera : public Node
{
struct Camera final : Node {
using ChunkInfo::operator=;
Camera() : Node(TYPE_CAMERA) {}
Camera() : Node(TYPE_CAMERA) {
// empty
}
};
// ------------------
/** COB Texture data structure */
struct Texture
{
struct Texture {
std::string path;
aiUVTransform transform;
};
// ------------------
/** COB Material data structure */
struct Material : ChunkInfo
{
struct Material : ChunkInfo {
using ChunkInfo::operator=;
enum Shader {
FLAT,PHONG,METAL
FLAT,
PHONG,
METAL
};
enum AutoFacet {
FACETED,AUTOFACETED,SMOOTH
FACETED,
AUTOFACETED,
SMOOTH
};
Material() : alpha(),exp(),ior(),ka(),ks(1.f),
matnum(UINT_MAX),
shader(FLAT),autofacet(FACETED),
autofacet_angle()
{}
Material() : shader(FLAT) {
// empty
}
std::string type;
aiColor3D rgb;
float alpha, exp, ior,ka,ks;
unsigned int matnum;
float alpha{ 0.0f };
float exp{ 0.0f };
float ior{ 0.0f };
float ka{ 0.0f };
float ks{ 1.0f };
unsigned int matnum{ UINT_MAX };
Shader shader;
AutoFacet autofacet;
float autofacet_angle;
AutoFacet autofacet{FACETED};
float autofacet_angle{ 0.0f };
std::shared_ptr<Texture> tex_env,tex_bump,tex_color;
};
// ------------------
/** Embedded bitmap, for instance for the thumbnail image */
struct Bitmap : ChunkInfo
{
Bitmap() : orig_size() {}
struct BitmapHeader
{
struct Bitmap : ChunkInfo {
Bitmap() = default;
struct BitmapHeader {
// empty
};
BitmapHeader head;
size_t orig_size;
size_t orig_size{ 0u };
std::vector<char> buff_zipped;
};
typedef std::deque< std::shared_ptr<Node> > NodeList;
typedef std::vector< Material > MaterialList;
using NodeList = std::deque< std::shared_ptr<Node>>;
using MaterialList = std::vector< Material >;
// ------------------
/** Represents a master COB scene, even if we loaded just a single COB file */
struct Scene
{
struct Scene {
NodeList nodes;
MaterialList materials;
@@ -270,7 +278,6 @@ struct Scene
Bitmap thumbnail;
};
} // end COB
} // end Assimp
} // end Assimp::COB
#endif
#endif // INCLUDED_AI_COB_SCENE_H
+40 -31
View File
@@ -3,9 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -73,10 +71,9 @@ static constexpr aiImporterDesc desc = {
"csm"
};
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
CSMImporter::CSMImporter() : noSkeletonMesh(){
CSMImporter::CSMImporter() : noSkeletonMesh() {
// empty
}
@@ -102,8 +99,7 @@ void CSMImporter::SetupProperties(const Importer* pImp) {
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void CSMImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler)
{
aiScene* pScene, IOSystem* pIOHandler) {
std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file
@@ -122,23 +118,24 @@ void CSMImporter::InternReadFile( const std::string& pFile,
// now process the file and look out for '$' sections
while (true) {
SkipSpaces(&buffer, end);
if ('\0' == *buffer)
if ('\0' == *buffer) {
break;
}
if ('$' == *buffer) {
if ('$' == *buffer) {
++buffer;
if (TokenMatchI(buffer,"firstframe",10)) {
if (TokenMatchI(buffer,"firstframe",10)) {
SkipSpaces(&buffer, end);
first = strtol10(buffer,&buffer);
}
else if (TokenMatchI(buffer,"lastframe",9)) {
else if (TokenMatchI(buffer,"lastframe",9)) {
SkipSpaces(&buffer, end);
last = strtol10(buffer,&buffer);
}
else if (TokenMatchI(buffer,"rate",4)) {
SkipSpaces(&buffer, end);
float d = { 0.0f };
buffer = fast_atoreal_move<float>(buffer,d);
buffer = fast_atoreal_move(buffer,d);
anim->mTicksPerSecond = d;
}
else if (TokenMatchI(buffer,"order",5)) {
@@ -153,8 +150,9 @@ void CSMImporter::InternReadFile( const std::string& pFile,
anims_temp.push_back(new aiNodeAnim());
aiNodeAnim* nda = anims_temp.back();
char* ot = nda->mNodeName.data;
while (!IsSpaceOrNewLine(*buffer)) {
char *ot = nda->mNodeName.data;
const char *ot_end = nda->mNodeName.data + AI_MAXLEN;
while (!IsSpaceOrNewLine(*buffer) && buffer != end && ot != ot_end) {
*ot++ = *buffer++;
}
@@ -177,15 +175,26 @@ void CSMImporter::InternReadFile( const std::string& pFile,
// If we know how many frames we'll read, we can preallocate some storage
unsigned int alloc = 100;
if (last != 0x00ffffff) {
if (last != 0x00ffffff && last > first) {
// re-init if the file has last frame data
alloc = last-first;
alloc += alloc>>2u; // + 25%
for (unsigned int i = 0; i < anim->mNumChannels; ++i) {
if (anim->mChannels[i]->mPositionKeys != nullptr) delete[] anim->mChannels[i]->mPositionKeys;
anim->mChannels[i]->mPositionKeys = new aiVectorKey[alloc];
}
} else {
// default init
for (unsigned int i = 0; i < anim->mNumChannels; ++i) {
if (anim->mChannels[i]->mPositionKeys != nullptr) continue;
anim->mChannels[i]->mPositionKeys = new aiVectorKey[alloc];
}
}
unsigned int filled = 0;
// Track every channel's own buffer capacity. A single shared counter
// is not enough: a DROPOUT marker makes a channel skip a frame, so the
// channels' key counts drift apart and each buffer has to grow on its own.
std::vector<unsigned int> capacity(anim->mNumChannels, alloc);
// Now read all point data.
while (true) {
@@ -201,12 +210,13 @@ void CSMImporter::InternReadFile( const std::string& pFile,
for (unsigned int i = 0; i < anim->mNumChannels;++i) {
aiNodeAnim* s = anim->mChannels[i];
if (s->mNumPositionKeys == alloc) {
// need to reallocate?
if (s->mNumPositionKeys == capacity[i]) {
// this channel's buffer is full, grow it
aiVectorKey* old = s->mPositionKeys;
s->mPositionKeys = new aiVectorKey[s->mNumPositionKeys = alloc*2];
::memcpy(s->mPositionKeys,old,sizeof(aiVectorKey)*alloc);
s->mPositionKeys = new aiVectorKey[capacity[i]*2];
::memcpy(s->mPositionKeys,old,sizeof(aiVectorKey)*capacity[i]);
delete[] old;
capacity[i] *= 2;
}
// read x,y,z
@@ -220,28 +230,21 @@ void CSMImporter::InternReadFile( const std::string& pFile,
} else {
aiVectorKey* sub = s->mPositionKeys + s->mNumPositionKeys;
sub->mTime = (double)frame;
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.x);
buffer = fast_atoreal_move(buffer, sub->mValue.x);
if (!SkipSpacesAndLineEnd(&buffer, end)) {
throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample y coord");
}
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.y);
buffer = fast_atoreal_move(buffer, sub->mValue.y);
if (!SkipSpacesAndLineEnd(&buffer, end)) {
throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample z coord");
}
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.z);
buffer = fast_atoreal_move(buffer, sub->mValue.z);
++s->mNumPositionKeys;
}
}
// update allocation granularity
if (filled == alloc) {
alloc *= 2;
}
++filled;
}
// all channels must be complete in order to continue safely.
for (unsigned int i = 0; i < anim->mNumChannels;++i) {
@@ -273,7 +276,13 @@ void CSMImporter::InternReadFile( const std::string& pFile,
nd->mName = anim->mChannels[i]->mNodeName;
nd->mParent = pScene->mRootNode;
aiMatrix4x4::Translation(na->mPositionKeys[0].mValue, nd->mTransformation);
if (na->mPositionKeys != nullptr && na->mNumPositionKeys > 0) {
aiMatrix4x4::Translation(na->mPositionKeys[0].mValue, nd->mTransformation);
} else {
// Use identity matrix if no valid position data is available
nd->mTransformation = aiMatrix4x4();
DefaultLogger::get()->warn("CSM: No position keys available for node - using identity transformation");
}
}
// Store the one and only animation in the scene
+2 -2
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -58,7 +58,7 @@ namespace Assimp {
* Link to file format specification:
* <max_8_dvd>\samples\Motion\Docs\CSM.rtf
*/
class CSMImporter : public BaseImporter {
class CSMImporter final : public BaseImporter {
public:
CSMImporter();
~CSMImporter() override = default;
+326 -273
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -36,7 +35,6 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
@@ -64,6 +62,37 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Assimp {
static const aiNode *findSkeletonRootNode(const aiScene *scene, const aiMesh *mesh) {
std::set<const aiNode *> topParentBoneNodes;
if (mesh && mesh->mNumBones > 0) {
for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
aiBone *bone = mesh->mBones[i];
const aiNode *node = scene->mRootNode->findBoneNode(bone);
if (node) {
while (node->mParent && scene->findBone(node->mParent->mName) != nullptr) {
node = node->mParent;
}
topParentBoneNodes.insert(node);
}
}
}
if (!topParentBoneNodes.empty()) {
const aiNode *parentBoneNode = *topParentBoneNodes.begin();
if (topParentBoneNodes.size() == 1) {
return parentBoneNode;
} else {
for (auto it : topParentBoneNodes) {
if (it->mParent) return it->mParent;
}
return parentBoneNode;
}
}
return nullptr;
}
// ------------------------------------------------------------------------------------------------
// Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
void ExportSceneCollada(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties * /*pProperties*/) {
@@ -152,10 +181,6 @@ ColladaExporter::ColladaExporter(const aiScene *pScene, IOSystem *pIOSystem, con
WriteFile();
}
// ------------------------------------------------------------------------------------------------
// Destructor
ColladaExporter::~ColladaExporter() = default;
// ------------------------------------------------------------------------------------------------
// Starts writing the contents
void ColladaExporter::WriteFile() {
@@ -331,60 +356,68 @@ void ColladaExporter::WriteHeader() {
// ------------------------------------------------------------------------------------------------
// Write the embedded textures
void ColladaExporter::WriteTextures() {
static const unsigned int buffer_size = 1024;
char str[buffer_size];
static constexpr unsigned int buffer_size = 1024;
char str[buffer_size] = {'\0'};
if (mScene->HasTextures()) {
for (unsigned int i = 0; i < mScene->mNumTextures; i++) {
// It would be great to be able to create a directory in portable standard C++, but it's not the case,
// so we just write the textures in the current directory.
if (!mScene->HasTextures()) {
return;
}
aiTexture *texture = mScene->mTextures[i];
if (nullptr == texture) {
continue;
}
for (unsigned int i = 0; i < mScene->mNumTextures; i++) {
// It would be great to be able to create a directory in portable standard C++, but it's not the case,
// so we just write the textures in the current directory.
ASSIMP_itoa10(str, buffer_size, i + 1);
std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char *)texture->achFormatHint);
std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb"));
if (outfile == nullptr) {
throw DeadlyExportError("could not open output texture file: " + mPath + name);
}
if (texture->mHeight == 0) {
outfile->Write((void *)texture->pcData, texture->mWidth, 1);
} else {
Bitmap::Save(texture, outfile.get());
}
outfile->Flush();
textures.insert(std::make_pair(i, name));
aiTexture *texture = mScene->mTextures[i];
if (nullptr == texture) {
continue;
}
ASSIMP_itoa10(str, buffer_size, i + 1);
std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char *)texture->achFormatHint);
std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb"));
if (outfile == nullptr) {
throw DeadlyExportError("could not open output texture file: " + mPath + name);
}
if (texture->mHeight == 0) {
outfile->Write((void *)texture->pcData, texture->mWidth, 1);
} else {
Bitmap::Save(texture, outfile.get());
}
outfile->Flush();
textures.insert(std::make_pair(i, name));
}
}
// ------------------------------------------------------------------------------------------------
// Write the embedded textures
void ColladaExporter::WriteCamerasLibrary() {
if (mScene->HasCameras()) {
mOutput << startstr << "<library_cameras>" << endstr;
PushTag();
for (size_t a = 0; a < mScene->mNumCameras; ++a)
WriteCamera(a);
PopTag();
mOutput << startstr << "</library_cameras>" << endstr;
if (!mScene->HasCameras()) {
return;
}
mOutput << startstr << "<library_cameras>" << endstr;
PushTag();
for (size_t a = 0; a < mScene->mNumCameras; ++a) {
WriteCamera(a);
}
PopTag();
mOutput << startstr << "</library_cameras>" << endstr;
}
void ColladaExporter::WriteCamera(size_t pIndex) {
const aiCamera *cam = mScene->mCameras[pIndex];
if (cam == nullptr) {
return;
}
const std::string cameraId = GetObjectUniqueId(AiObjectType::Camera, pIndex);
const std::string cameraName = GetObjectName(AiObjectType::Camera, pIndex);
@@ -422,22 +455,27 @@ void ColladaExporter::WriteCamera(size_t pIndex) {
// ------------------------------------------------------------------------------------------------
// Write the embedded textures
void ColladaExporter::WriteLightsLibrary() {
if (mScene->HasLights()) {
mOutput << startstr << "<library_lights>" << endstr;
PushTag();
for (size_t a = 0; a < mScene->mNumLights; ++a)
WriteLight(a);
PopTag();
mOutput << startstr << "</library_lights>" << endstr;
if (!mScene->HasLights()) {
return;
}
mOutput << startstr << "<library_lights>" << endstr;
PushTag();
for (size_t a = 0; a < mScene->mNumLights; ++a) {
WriteLight(a);
}
PopTag();
mOutput << startstr << "</library_lights>" << endstr;
}
void ColladaExporter::WriteLight(size_t pIndex) {
const aiLight *light = mScene->mLights[pIndex];
if (light == nullptr) {
return;
}
const std::string lightId = GetObjectUniqueId(AiObjectType::Light, pIndex);
const std::string lightName = GetObjectName(AiObjectType::Light, pIndex);
@@ -462,6 +500,7 @@ void ColladaExporter::WriteLight(size_t pIndex) {
case aiLightSource_AREA:
case aiLightSource_UNDEFINED:
case _aiLightSource_Force32Bit:
default:
break;
}
PopTag();
@@ -521,10 +560,6 @@ void ColladaExporter::WriteSpotLight(const aiLight *const light) {
mOutput << startstr << "<quadratic_attenuation>"
<< light->mAttenuationQuadratic
<< "</quadratic_attenuation>" << endstr;
/*
out->mAngleOuterCone = AI_DEG_TO_RAD (std::acos(std::pow(0.1f,1.f/srcLight->mFalloffExponent))+
srcLight->mFalloffAngle);
*/
const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
mOutput << startstr << "<falloff_angle sid=\"fall_off_angle\">"
@@ -559,41 +594,43 @@ void ColladaExporter::WriteAmbientLight(const aiLight *const light) {
// ------------------------------------------------------------------------------------------------
// Reads a single surface entry from the given material keys
bool ColladaExporter::ReadMaterialSurface(Surface &poSurface, const aiMaterial &pSrcMat, aiTextureType pTexture, const char *pKey, size_t pType, size_t pIndex) {
if (pSrcMat.GetTextureCount(pTexture) > 0) {
aiString texfile;
unsigned int uvChannel = 0;
pSrcMat.GetTexture(pTexture, 0, &texfile, nullptr, &uvChannel);
std::string index_str(texfile.C_Str());
if (index_str.size() != 0 && index_str[0] == '*') {
unsigned int index;
index_str = index_str.substr(1, std::string::npos);
try {
index = (unsigned int)strtoul10_64<DeadlyExportError>(index_str.c_str());
} catch (std::exception &error) {
throw DeadlyExportError(error.what());
}
std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
if (name != textures.end()) {
poSurface.texture = name->second;
} else {
throw DeadlyExportError("could not find embedded texture at index " + index_str);
}
} else {
poSurface.texture = texfile.C_Str();
}
poSurface.channel = uvChannel;
poSurface.exist = true;
} else {
if (pSrcMat.GetTextureCount(pTexture) == 0) {
if (pKey)
poSurface.exist = pSrcMat.Get(pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
return poSurface.exist;
}
aiString texfile;
unsigned int uvChannel = 0;
pSrcMat.GetTexture(pTexture, 0, &texfile, nullptr, &uvChannel);
std::string index_str(texfile.C_Str());
if (index_str.size() != 0 && index_str[0] == '*') {
unsigned int index;
index_str = index_str.substr(1, std::string::npos);
try {
index = (unsigned int)strtoul10_64<DeadlyExportError>(index_str.c_str());
} catch (std::exception &error) {
throw DeadlyExportError(error.what());
}
std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
if (name != textures.end()) {
poSurface.texture = name->second;
} else {
throw DeadlyExportError("could not find embedded texture at index " + index_str);
}
} else {
poSurface.texture = texfile.C_Str();
}
poSurface.channel = uvChannel;
poSurface.exist = true;
return poSurface.exist;
}
@@ -606,79 +643,87 @@ static bool isalnum_C(char c) {
// ------------------------------------------------------------------------------------------------
// Writes an image entry for the given surface
void ColladaExporter::WriteImageEntry(const Surface &pSurface, const std::string &imageId) {
if (!pSurface.texture.empty()) {
mOutput << startstr << "<image id=\"" << imageId << "\">" << endstr;
PushTag();
mOutput << startstr << "<init_from>";
// URL encode image file name first, then XML encode on top
std::stringstream imageUrlEncoded;
for (std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it) {
if (isalnum_C((unsigned char)*it) || *it == ':' || *it == '_' || *it == '-' || *it == '.' || *it == '/' || *it == '\\')
imageUrlEncoded << *it;
else
imageUrlEncoded << '%' << std::hex << size_t((unsigned char)*it) << std::dec;
}
mOutput << XMLEscape(imageUrlEncoded.str());
mOutput << "</init_from>" << endstr;
PopTag();
mOutput << startstr << "</image>" << endstr;
if (pSurface.texture.empty()) {
return;
}
mOutput << startstr << "<image id=\"" << imageId << "\">" << endstr;
PushTag();
mOutput << startstr << "<init_from>";
// URL encode image file name first, then XML encode on top
std::stringstream imageUrlEncoded;
for (std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it) {
if (isalnum_C((unsigned char)*it) || *it == ':' || *it == '_' || *it == '-' || *it == '.' || *it == '/' || *it == '\\')
imageUrlEncoded << *it;
else
imageUrlEncoded << '%' << std::hex << size_t((unsigned char)*it) << std::dec;
}
mOutput << XMLEscape(imageUrlEncoded.str());
mOutput << "</init_from>" << endstr;
PopTag();
mOutput << startstr << "</image>" << endstr;
}
// ------------------------------------------------------------------------------------------------
// Writes a color-or-texture entry into an effect definition
void ColladaExporter::WriteTextureColorEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &imageId) {
if (pSurface.exist) {
mOutput << startstr << "<" << pTypeName << ">" << endstr;
PushTag();
if (pSurface.texture.empty()) {
mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
} else {
mOutput << startstr << "<texture texture=\"" << imageId << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
}
PopTag();
mOutput << startstr << "</" << pTypeName << ">" << endstr;
if (!pSurface.exist) {
return;
}
mOutput << startstr << "<" << pTypeName << ">" << endstr;
PushTag();
if (pSurface.texture.empty()) {
mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
} else {
mOutput << startstr << "<texture texture=\"" << imageId << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
}
PopTag();
mOutput << startstr << "</" << pTypeName << ">" << endstr;
}
// ------------------------------------------------------------------------------------------------
// Writes the two parameters necessary for referencing a texture in an effect entry
void ColladaExporter::WriteTextureParamEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &materialId) {
// if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
if (!pSurface.texture.empty()) {
mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-surface\">" << endstr;
PushTag();
mOutput << startstr << "<surface type=\"2D\">" << endstr;
PushTag();
mOutput << startstr << "<init_from>" << materialId << "-" << pTypeName << "-image</init_from>" << endstr;
PopTag();
mOutput << startstr << "</surface>" << endstr;
PopTag();
mOutput << startstr << "</newparam>" << endstr;
mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-sampler\">" << endstr;
PushTag();
mOutput << startstr << "<sampler2D>" << endstr;
PushTag();
mOutput << startstr << "<source>" << materialId << "-" << pTypeName << "-surface</source>" << endstr;
PopTag();
mOutput << startstr << "</sampler2D>" << endstr;
PopTag();
mOutput << startstr << "</newparam>" << endstr;
if (pSurface.texture.empty()) {
return;
}
mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-surface\">" << endstr;
PushTag();
mOutput << startstr << "<surface type=\"2D\">" << endstr;
PushTag();
mOutput << startstr << "<init_from>" << materialId << "-" << pTypeName << "-image</init_from>" << endstr;
PopTag();
mOutput << startstr << "</surface>" << endstr;
PopTag();
mOutput << startstr << "</newparam>" << endstr;
mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-sampler\">" << endstr;
PushTag();
mOutput << startstr << "<sampler2D>" << endstr;
PushTag();
mOutput << startstr << "<source>" << materialId << "-" << pTypeName << "-surface</source>" << endstr;
PopTag();
mOutput << startstr << "</sampler2D>" << endstr;
PopTag();
mOutput << startstr << "</newparam>" << endstr;
}
// ------------------------------------------------------------------------------------------------
// Writes a scalar property
void ColladaExporter::WriteFloatEntry(const Property &pProperty, const std::string &pTypeName) {
if (pProperty.exist) {
mOutput << startstr << "<" << pTypeName << ">" << endstr;
PushTag();
mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
PopTag();
mOutput << startstr << "</" << pTypeName << ">" << endstr;
if (!pProperty.exist) {
return;
}
mOutput << startstr << "<" << pTypeName << ">" << endstr;
PushTag();
mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
PopTag();
mOutput << startstr << "</" << pTypeName << ">" << endstr;
}
// ------------------------------------------------------------------------------------------------
@@ -832,8 +877,9 @@ void ColladaExporter::WriteControllerLibrary() {
void ColladaExporter::WriteController(size_t pIndex) {
const aiMesh *mesh = mScene->mMeshes[pIndex];
// Is there a skin controller?
if (mesh->mNumBones == 0 || mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
if (mesh->mNumBones == 0 || mesh->mNumFaces == 0 || mesh->mNumVertices == 0) {
return;
}
const std::string idstr = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
const std::string namestr = GetObjectName(AiObjectType::Mesh, pIndex);
@@ -864,8 +910,9 @@ void ColladaExporter::WriteController(size_t pIndex) {
mOutput << startstr << "<Name_array id=\"" << idstr << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
for (size_t i = 0; i < mesh->mNumBones; ++i)
for (size_t i = 0; i < mesh->mNumBones; ++i) {
mOutput << GetBoneUniqueId(mesh->mBones[i]) << ' ';
}
mOutput << "</Name_array>" << endstr;
@@ -888,9 +935,11 @@ void ColladaExporter::WriteController(size_t pIndex) {
std::vector<ai_real> bind_poses;
bind_poses.reserve(mesh->mNumBones * 16);
for (unsigned int i = 0; i < mesh->mNumBones; ++i)
for (unsigned int j = 0; j < 4; ++j)
for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
for (unsigned int j = 0; j < 4; ++j) {
bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
}
}
WriteFloatArray(idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real *)bind_poses.data(), bind_poses.size() / 16);
@@ -898,9 +947,11 @@ void ColladaExporter::WriteController(size_t pIndex) {
std::vector<ai_real> skin_weights;
skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
for (size_t i = 0; i < mesh->mNumBones; ++i)
for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
for (size_t i = 0; i < mesh->mNumBones; ++i) {
for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
}
}
WriteFloatArray(idstr + "-skin-weights", FloatType_Weight, (const ai_real *)skin_weights.data(), skin_weights.size());
@@ -924,12 +975,15 @@ void ColladaExporter::WriteController(size_t pIndex) {
mOutput << startstr << "<vcount>";
std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
for (size_t i = 0; i < mesh->mNumBones; ++i)
for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
for (size_t i = 0; i < mesh->mNumBones; ++i) {
for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
}
}
for (size_t i = 0; i < mesh->mNumVertices; ++i)
for (size_t i = 0; i < mesh->mNumVertices; ++i) {
mOutput << num_influences[i] << " ";
}
mOutput << "</vcount>" << endstr;
@@ -945,7 +999,7 @@ void ColladaExporter::WriteController(size_t pIndex) {
ai_uint weight_index = 0;
std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
for (unsigned int i = 0; i < mesh->mNumBones; ++i)
for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
for (unsigned j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
for (ai_uint k = 0; k < num_influences[vId]; ++k) {
@@ -957,9 +1011,11 @@ void ColladaExporter::WriteController(size_t pIndex) {
}
++weight_index;
}
}
for (size_t i = 0; i < joint_weight_indices.size(); ++i)
for (size_t i = 0; i < joint_weight_indices.size(); ++i) {
mOutput << joint_weight_indices[i] << " ";
}
num_influences.clear();
accum_influences.clear();
@@ -983,8 +1039,9 @@ void ColladaExporter::WriteGeometryLibrary() {
mOutput << startstr << "<library_geometries>" << endstr;
PushTag();
for (size_t a = 0; a < mScene->mNumMeshes; ++a)
for (size_t a = 0; a < mScene->mNumMeshes; ++a) {
WriteGeometry(a);
}
PopTag();
mOutput << startstr << "</library_geometries>" << endstr;
@@ -997,8 +1054,9 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
const std::string geometryId = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
const std::string geometryName = GetObjectName(AiObjectType::Mesh, pIndex);
if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0) {
return;
}
// opening tag
mOutput << startstr << "<geometry id=\"" << geometryId << "\" name=\"" << geometryName << "\" >" << endstr;
@@ -1010,8 +1068,9 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
// Positions
WriteFloatArray(geometryId + "-positions", FloatType_Vector, (ai_real *)mesh->mVertices, mesh->mNumVertices);
// Normals, if any
if (mesh->HasNormals())
if (mesh->HasNormals()) {
WriteFloatArray(geometryId + "-normals", FloatType_Vector, (ai_real *)mesh->mNormals, mesh->mNumVertices);
}
// texture coords
for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
@@ -1040,10 +1099,11 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
int countLines = 0;
int countPoly = 0;
for (size_t a = 0; a < mesh->mNumFaces; ++a) {
if (mesh->mFaces[a].mNumIndices == 2)
if (mesh->mFaces[a].mNumIndices == 2) {
countLines++;
else if (mesh->mFaces[a].mNumIndices >= 3)
} else if (mesh->mFaces[a].mNumIndices >= 3) {
countPoly++;
}
}
// lines
@@ -1051,13 +1111,18 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
PushTag();
mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
if (mesh->HasNormals())
if (mesh->HasNormals()) {
mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
}
for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
if (mesh->HasTextureCoords(static_cast<unsigned int>(a)))
mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" "
if (mesh->HasTextureCoords(static_cast<unsigned int>(a))) {
mOutput << startstr
<< "<input semantic=\"TEXCOORD\" source=\"#"
<< geometryId
<< "-tex" << a << "\" "
<< "set=\"" << a << "\""
<< " />" << endstr;
}
}
for (size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
@@ -1070,8 +1135,9 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
for (size_t a = 0; a < mesh->mNumFaces; ++a) {
const aiFace &face = mesh->mFaces[a];
if (face.mNumIndices != 2) continue;
for (size_t b = 0; b < face.mNumIndices; ++b)
for (size_t b = 0; b < face.mNumIndices; ++b) {
mOutput << face.mIndices[b] << " ";
}
}
mOutput << "</p>" << endstr;
PopTag();
@@ -1085,8 +1151,9 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
PushTag();
mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
if (mesh->HasNormals())
if (mesh->HasNormals()) {
mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
}
for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
if (mesh->HasTextureCoords(static_cast<unsigned int>(a)))
mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" "
@@ -1111,8 +1178,9 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
for (size_t a = 0; a < mesh->mNumFaces; ++a) {
const aiFace &face = mesh->mFaces[a];
if (face.mNumIndices < 3) continue;
for (size_t b = 0; b < face.mNumIndices; ++b)
for (size_t b = 0; b < face.mNumIndices; ++b) {
mOutput << face.mIndices[b] << " ";
}
}
mOutput << "</p>" << endstr;
PopTag();
@@ -1131,13 +1199,27 @@ void ColladaExporter::WriteGeometry(size_t pIndex) {
void ColladaExporter::WriteFloatArray(const std::string &pIdString, FloatDataType pType, const ai_real *pData, size_t pElementCount) {
size_t floatsPerElement = 0;
switch (pType) {
case FloatType_Vector: floatsPerElement = 3; break;
case FloatType_TexCoord2: floatsPerElement = 2; break;
case FloatType_TexCoord3: floatsPerElement = 3; break;
case FloatType_Color: floatsPerElement = 3; break;
case FloatType_Mat4x4: floatsPerElement = 16; break;
case FloatType_Weight: floatsPerElement = 1; break;
case FloatType_Time: floatsPerElement = 1; break;
case FloatType_Vector:
floatsPerElement = 3;
break;
case FloatType_TexCoord2:
floatsPerElement = 2;
break;
case FloatType_TexCoord3:
floatsPerElement = 3;
break;
case FloatType_Color:
floatsPerElement = 3;
break;
case FloatType_Mat4x4:
floatsPerElement = 16;
break;
case FloatType_Weight:
floatsPerElement = 1;
break;
case FloatType_Time:
floatsPerElement = 1;
break;
default:
return;
}
@@ -1163,8 +1245,9 @@ void ColladaExporter::WriteFloatArray(const std::string &pIdString, FloatDataTyp
mOutput << pData[a * 4 + 2] << " ";
}
} else {
for (size_t a = 0; a < pElementCount * floatsPerElement; ++a)
for (size_t a = 0; a < pElementCount * floatsPerElement; ++a) {
mOutput << pData[a] << " ";
}
}
mOutput << "</float_array>" << endstr;
PopTag();
@@ -1256,9 +1339,13 @@ void ColladaExporter::WriteSceneLibrary() {
// ------------------------------------------------------------------------------------------------
void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
const aiAnimation *anim = mScene->mAnimations[pIndex];
if (anim->mNumChannels == 0 && anim->mNumMeshChannels == 0 && anim->mNumMorphMeshChannels == 0)
if (anim == nullptr) {
return;
}
if (anim->mNumChannels == 0 && anim->mNumMeshChannels == 0 && anim->mNumMorphMeshChannels == 0) {
return;
}
const std::string animationNameEscaped = GetObjectName(AiObjectType::Animation, pIndex);
const std::string idstrEscaped = GetObjectUniqueId(AiObjectType::Animation, pIndex);
@@ -1269,8 +1356,11 @@ void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
std::string cur_node_idstr;
for (size_t a = 0; a < anim->mNumChannels; ++a) {
const aiNodeAnim *nodeAnim = anim->mChannels[a];
if (nodeAnim == nullptr) {
continue;
}
// sanity check
// sanity checks
if (nodeAnim->mNumPositionKeys != nodeAnim->mNumScalingKeys || nodeAnim->mNumPositionKeys != nodeAnim->mNumRotationKeys) {
continue;
}
@@ -1369,6 +1459,9 @@ void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
for (size_t a = 0; a < anim->mNumChannels; ++a) {
const aiNodeAnim *nodeAnim = anim->mChannels[a];
if (nodeAnim == nullptr) {
continue;
}
{
// samplers
@@ -1387,97 +1480,42 @@ void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
for (size_t a = 0; a < anim->mNumChannels; ++a) {
const aiNodeAnim *nodeAnim = anim->mChannels[a];
if (nodeAnim == nullptr) {
continue;
}
{
// channels
mOutput << startstr << "<channel source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-sampler")) << "\" target=\"" << XMLIDEncode(nodeAnim->mNodeName.data) << "/matrix\"/>" << endstr;
mOutput << startstr
<< "<channel source=\"#"
<< XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-sampler"))
<< "\" target=\""
<< XMLIDEncode(nodeAnim->mNodeName.data)
<< "/matrix\"/>"
<< endstr;
}
}
PopTag();
mOutput << startstr << "</animation>" << endstr;
}
// ------------------------------------------------------------------------------------------------
void ColladaExporter::WriteAnimationsLibrary() {
if (mScene->mNumAnimations > 0) {
mOutput << startstr << "<library_animations>" << endstr;
PushTag();
// start recursive write at the root node
for (size_t a = 0; a < mScene->mNumAnimations; ++a)
WriteAnimationLibrary(a);
PopTag();
mOutput << startstr << "</library_animations>" << endstr;
}
}
// ------------------------------------------------------------------------------------------------
// Helper to find a bone by name in the scene
aiBone *findBone(const aiScene *scene, const aiString &name) {
for (size_t m = 0; m < scene->mNumMeshes; m++) {
aiMesh *mesh = scene->mMeshes[m];
for (size_t b = 0; b < mesh->mNumBones; b++) {
aiBone *bone = mesh->mBones[b];
if (name == bone->mName) {
return bone;
}
}
}
return nullptr;
}
// ------------------------------------------------------------------------------------------------
// Helper to find the node associated with a bone in the scene
const aiNode *findBoneNode(const aiNode *aNode, const aiBone *bone) {
if (aNode && bone && aNode->mName == bone->mName) {
return aNode;
if (mScene->mNumAnimations == 0) {
return;
}
if (aNode && bone) {
for (unsigned int i = 0; i < aNode->mNumChildren; ++i) {
aiNode *aChild = aNode->mChildren[i];
const aiNode *foundFromChild = nullptr;
if (aChild) {
foundFromChild = findBoneNode(aChild, bone);
if (foundFromChild) {
return foundFromChild;
}
}
}
mOutput << startstr << "<library_animations>" << endstr;
PushTag();
// start recursive write at the root node
for (size_t a = 0; a < mScene->mNumAnimations; ++a) {
WriteAnimationLibrary(a);
}
return nullptr;
}
const aiNode *findSkeletonRootNode(const aiScene *scene, const aiMesh *mesh) {
std::set<const aiNode *> topParentBoneNodes;
if (mesh && mesh->mNumBones > 0) {
for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
aiBone *bone = mesh->mBones[i];
const aiNode *node = findBoneNode(scene->mRootNode, bone);
if (node) {
while (node->mParent && findBone(scene, node->mParent->mName) != nullptr) {
node = node->mParent;
}
topParentBoneNodes.insert(node);
}
}
}
if (!topParentBoneNodes.empty()) {
const aiNode *parentBoneNode = *topParentBoneNodes.begin();
if (topParentBoneNodes.size() == 1) {
return parentBoneNode;
} else {
for (auto it : topParentBoneNodes) {
if (it->mParent) return it->mParent;
}
return parentBoneNode;
}
}
return nullptr;
PopTag();
mOutput << startstr << "</library_animations>" << endstr;
}
// ------------------------------------------------------------------------------------------------
@@ -1488,13 +1526,13 @@ void ColladaExporter::WriteNode(const aiNode *pNode) {
// Assimp-specific: nodes with no name cannot be associated with bones
const char *node_type;
bool is_joint, is_skeleton_root = false;
if (pNode->mName.length == 0 || nullptr == findBone(mScene, pNode->mName)) {
if (pNode->mName.length == 0 || nullptr == mScene->findBone(pNode->mName)) {
node_type = "NODE";
is_joint = false;
} else {
node_type = "JOINT";
is_joint = true;
if (!pNode->mParent || nullptr == findBone(mScene, pNode->mParent->mName)) {
if (!pNode->mParent || nullptr == mScene->findBone(pNode->mParent->mName)) {
is_skeleton_root = true;
}
}
@@ -1532,7 +1570,6 @@ void ColladaExporter::WriteNode(const aiNode *pNode) {
}
// customized, sid should be 'matrix' to match with loader code.
//mOutput << startstr << "<matrix sid=\"transform\">";
mOutput << startstr << "<matrix sid=\"matrix\">";
mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
@@ -1556,7 +1593,6 @@ void ColladaExporter::WriteNode(const aiNode *pNode) {
break;
}
}
} else
// instance every geometry
for (size_t a = 0; a < pNode->mNumMeshes; ++a) {
@@ -1612,8 +1648,9 @@ void ColladaExporter::WriteNode(const aiNode *pNode) {
}
// recurse into subnodes
for (size_t a = 0; a < pNode->mNumChildren; ++a)
for (size_t a = 0; a < pNode->mNumChildren; ++a) {
WriteNode(pNode->mChildren[a]);
}
PopTag();
mOutput << startstr << "</node>" << endstr;
@@ -1628,8 +1665,9 @@ void ColladaExporter::CreateNodeIds(const aiNode *node) {
std::string ColladaExporter::GetNodeUniqueId(const aiNode *node) {
// Use the pointer as the key. This is safe because the scene is immutable.
auto idIt = mNodeIdMap.find(node);
if (idIt != mNodeIdMap.cend())
if (idIt != mNodeIdMap.cend()) {
return idIt->second;
}
// Prefer the requested Collada Id if extant
std::string idStr;
@@ -1640,36 +1678,42 @@ std::string ColladaExporter::GetNodeUniqueId(const aiNode *node) {
idStr = node->mName.C_Str();
}
// Make sure the requested id is valid
if (idStr.empty())
if (idStr.empty()) {
idStr = "node";
else
} else {
idStr = XMLIDEncode(idStr);
}
// Ensure it's unique
idStr = MakeUniqueId(mUniqueIds, idStr, std::string());
mUniqueIds.insert(idStr);
mNodeIdMap.insert(std::make_pair(node, idStr));
return idStr;
}
std::string ColladaExporter::GetNodeName(const aiNode *node) {
if (node == nullptr) {
return std::string();
}
return XMLEscape(node->mName.C_Str());
}
std::string ColladaExporter::GetBoneUniqueId(const aiBone *bone) {
// Find the Node that is this Bone
const aiNode *boneNode = findBoneNode(mScene->mRootNode, bone);
if (boneNode == nullptr)
const aiNode *boneNode = mScene->mRootNode->findBoneNode(bone);
if (boneNode == nullptr) {
return std::string();
}
return GetNodeUniqueId(boneNode);
}
std::string ColladaExporter::GetObjectUniqueId(AiObjectType type, size_t pIndex) {
auto idIt = GetObjectIdMap(type).find(pIndex);
if (idIt != GetObjectIdMap(type).cend())
if (idIt != GetObjectIdMap(type).cend()) {
return idIt->second;
}
// Not seen this object before, create and add
NameIdPair result = AddObjectIndexToMaps(type, pIndex);
@@ -1678,8 +1722,9 @@ std::string ColladaExporter::GetObjectUniqueId(AiObjectType type, size_t pIndex)
std::string ColladaExporter::GetObjectName(AiObjectType type, size_t pIndex) {
auto objectName = GetObjectNameMap(type).find(pIndex);
if (objectName != GetObjectNameMap(type).cend())
if (objectName != GetObjectNameMap(type).cend()) {
return objectName->second;
}
// Not seen this object before, create and add
NameIdPair result = AddObjectIndexToMaps(type, pIndex);
@@ -1699,9 +1744,15 @@ ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType t
// Get the name and id postfix
switch (type) {
case AiObjectType::Mesh: name = mScene->mMeshes[index]->mName.C_Str(); break;
case AiObjectType::Material: name = mScene->mMaterials[index]->GetName().C_Str(); break;
case AiObjectType::Animation: name = mScene->mAnimations[index]->mName.C_Str(); break;
case AiObjectType::Mesh:
name = mScene->mMeshes[index]->mName.C_Str();
break;
case AiObjectType::Material:
name = mScene->mMaterials[index]->GetName().C_Str();
break;
case AiObjectType::Animation:
name = mScene->mAnimations[index]->mName.C_Str();
break;
case AiObjectType::Light:
name = mScene->mLights[index]->mName.C_Str();
idPostfix = "-light";
@@ -1710,7 +1761,8 @@ ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType t
name = mScene->mCameras[index]->mName.C_Str();
idPostfix = "-camera";
break;
case AiObjectType::Count: throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
case AiObjectType::Count:
throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
}
if (name.empty()) {
@@ -1728,8 +1780,9 @@ ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType t
idStr = XMLIDEncode(name);
}
if (!name.empty())
if (!name.empty()) {
name = XMLEscape(name);
}
idStr = MakeUniqueId(mUniqueIds, idStr, idPostfix);
@@ -1743,5 +1796,5 @@ ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType t
} // end of namespace Assimp
#endif
#endif
#endif // ASSIMP_BUILD_NO_COLLADA_EXPORTER
#endif // ASSIMP_BUILD_NO_EXPORT
+3 -4
View File
@@ -2,8 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -66,13 +65,13 @@ class IOSystem;
/// Helper class to export a given scene to a Collada file. Just for my personal
/// comfort when implementing it.
class ColladaExporter {
class ColladaExporter final {
public:
/// Constructor for a specific scene to export
ColladaExporter(const aiScene *pScene, IOSystem *pIOSystem, const std::string &path, const std::string &file);
/// Destructor
virtual ~ColladaExporter();
virtual ~ColladaExporter() = default;
protected:
/// Starts writing the contents
+1 -1
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
+18 -12
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -50,6 +50,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <vector>
@@ -341,7 +342,7 @@ struct SubMesh {
/// Contains data for a single mesh
struct Mesh {
Mesh(const std::string &id) :
explicit Mesh(const std::string &id) :
mId(id) {
for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
mNumUVComponents[i] = 2;
@@ -591,21 +592,26 @@ struct Animation {
std::vector<AnimationChannel> mChannels;
/// the sub-animations, if any
std::vector<Animation *> mSubAnims;
std::vector<std::unique_ptr<Animation>> mSubAnims;
Animation() {}
Animation(const Animation &) = delete;
Animation &operator=(const Animation &) = delete;
Animation(Animation &&) noexcept = default;
Animation &operator=(Animation &&) noexcept = default;
/// Destructor
~Animation() {
for (std::vector<Animation *>::iterator it = mSubAnims.begin(); it != mSubAnims.end(); ++it) {
delete *it;
}
}
/// Collect all channels in the animation hierarchy into a single channel list.
void CollectChannelsRecursively(std::vector<AnimationChannel> &channels) {
channels.insert(channels.end(), mChannels.begin(), mChannels.end());
for (std::vector<Animation *>::iterator it = mSubAnims.begin(); it != mSubAnims.end(); ++it) {
Animation *pAnim = (*it);
for (auto it = mSubAnims.begin(); it != mSubAnims.end(); ++it) {
Animation *pAnim = it->get();
pAnim->CollectChannelsRecursively(channels);
}
}
@@ -619,8 +625,8 @@ struct Animation {
std::set<std::string> childrenTargets;
bool childrenAnimationsHaveDifferentChannels = true;
for (std::vector<Animation *>::iterator it = pParent->mSubAnims.begin(); it != pParent->mSubAnims.end();) {
Animation *anim = *it;
for (auto it = pParent->mSubAnims.begin(); it != pParent->mSubAnims.end();) {
Animation *anim = it->get();
// Assign the first animation name to the parent if empty.
// This prevents the animation name from being lost when animations are combined
if (mName.empty()) {
@@ -640,8 +646,8 @@ struct Animation {
// We only want to combine animations if they have different channels
if (childrenAnimationsHaveDifferentChannels) {
for (std::vector<Animation *>::iterator it = pParent->mSubAnims.begin(); it != pParent->mSubAnims.end();) {
Animation *anim = *it;
for (auto it = pParent->mSubAnims.begin(); it != pParent->mSubAnims.end();) {
Animation *anim = it->release();
pParent->mChannels.push_back(anim->mChannels[0]);
+72 -69
View File
@@ -3,7 +3,7 @@
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -77,18 +77,26 @@ static constexpr aiImporterDesc desc = {
"dae xml zae"
};
static const float kMillisecondsFromSeconds = 1000.f;
static constexpr float kMillisecondsFromSeconds = 1000.f;
// Add an item of metadata to a node
// Assumes the key is not already in the list
template <typename T>
inline void AddNodeMetaData(aiNode *node, const std::string &key, const T &value) {
void AddNodeMetaData(aiNode *node, const std::string &key, const T &value) {
if (nullptr == node->mMetaData) {
node->mMetaData = new aiMetadata();
}
node->mMetaData->Add(key, value);
}
// ------------------------------------------------------------------------------------------------
// Reads a float value from an accessor and its data array.
static ai_real ReadFloat(const Accessor &pAccessor, const Data &pData, size_t pIndex, size_t pOffset) {
const size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
ai_assert(pos < pData.mValues.size());
return pData.mValues[pos];
}
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
ColladaLoader::ColladaLoader() :
@@ -152,7 +160,7 @@ void ColladaLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IO
throw DeadlyImportError("Collada: File came out empty. Something is wrong here.");
}
// reserve some storage to avoid unnecessary reallocs
// reserve some storage to avoid unnecessary reallocates
newMats.reserve(parser.mMaterialLibrary.size() * 2u);
mMeshes.reserve(parser.mMeshLibrary.size() * 2u);
@@ -176,7 +184,7 @@ void ColladaLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IO
0, 0, parser.mUnitSize, 0,
0, 0, 0, 1);
}
if (!ignoreUpDirection) {
// Convert to Y_UP, if different orientation
if (parser.mUpDirection == ColladaParser::UP_X) {
@@ -224,7 +232,7 @@ void ColladaLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IO
// Recursively constructs a scene node for the given parser node and returns it.
aiNode *ColladaLoader::BuildHierarchy(const ColladaParser &pParser, const Collada::Node *pNode) {
// create a node for it
aiNode *node = new aiNode();
auto *node = new aiNode();
// find a name for the new node. It's more complicated than you might think
node->mName.Set(FindNameForNode(pNode));
@@ -272,24 +280,24 @@ aiNode *ColladaLoader::BuildHierarchy(const ColladaParser &pParser, const Collad
// ------------------------------------------------------------------------------------------------
// Resolve node instances
void ColladaLoader::ResolveNodeInstances(const ColladaParser &pParser, const Node *pNode,
std::vector<const Node*> &resolved) {
std::vector<const Node*> &resolved) const {
// reserve enough storage
resolved.reserve(pNode->mNodeInstances.size());
// ... and iterate through all nodes to be instanced as children of pNode
for (const auto &nodeInst : pNode->mNodeInstances) {
for (const auto &[mNode] : pNode->mNodeInstances) {
// find the corresponding node in the library
const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find(nodeInst.mNode);
const auto itt = pParser.mNodeLibrary.find(mNode);
const Node *nd = itt == pParser.mNodeLibrary.end() ? nullptr : (*itt).second;
// FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
// need to check for both name and ID to catch all. To avoid breaking valid files,
// the workaround is only enabled when the first attempt to resolve the node has failed.
if (nullptr == nd) {
nd = FindNode(pParser.mRootNode, nodeInst.mNode);
nd = FindNode(pParser.mRootNode, mNode);
}
if (nullptr == nd) {
ASSIMP_LOG_ERROR("Collada: Unable to resolve reference to instanced node ", nodeInst.mNode);
ASSIMP_LOG_ERROR("Collada: Unable to resolve reference to instanced node ", mNode);
} else {
// attach this node to the list of children
resolved.push_back(nd);
@@ -299,8 +307,8 @@ void ColladaLoader::ResolveNodeInstances(const ColladaParser &pParser, const Nod
// ------------------------------------------------------------------------------------------------
// Resolve UV channels
void ColladaLoader::ApplyVertexToEffectSemanticMapping(Sampler &sampler, const SemanticMappingTable &table) {
SemanticMappingTable::InputSemanticMap::const_iterator it = table.mMap.find(sampler.mUVChannel);
static void ApplyVertexToEffectSemanticMapping(Sampler &sampler, const SemanticMappingTable &table) {
const auto it = table.mMap.find(sampler.mUVChannel);
if (it == table.mMap.end()) {
return;
}
@@ -317,7 +325,7 @@ void ColladaLoader::ApplyVertexToEffectSemanticMapping(Sampler &sampler, const S
void ColladaLoader::BuildLightsForNode(const ColladaParser &pParser, const Node *pNode, aiNode *pTarget) {
for (const LightInstance &lid : pNode->mLights) {
// find the referred light
ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find(lid.mLight);
auto srcLightIt = pParser.mLightLibrary.find(lid.mLight);
if (srcLightIt == pParser.mLightLibrary.end()) {
ASSIMP_LOG_WARN("Collada: Unable to find light for ID \"", lid.mLight, "\". Skipping.");
continue;
@@ -325,7 +333,7 @@ void ColladaLoader::BuildLightsForNode(const ColladaParser &pParser, const Node
const Collada::Light *srcLight = &srcLightIt->second;
// now fill our ai data structure
aiLight *out = new aiLight();
auto out = new aiLight();
out->mName = pTarget->mName;
out->mType = (aiLightSourceType)srcLight->mType;
@@ -382,7 +390,7 @@ void ColladaLoader::BuildLightsForNode(const ColladaParser &pParser, const Node
void ColladaLoader::BuildCamerasForNode(const ColladaParser &pParser, const Node *pNode, aiNode *pTarget) {
for (const CameraInstance &cid : pNode->mCameras) {
// find the referred light
ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find(cid.mCamera);
auto srcCameraIt = pParser.mCameraLibrary.find(cid.mCamera);
if (srcCameraIt == pParser.mCameraLibrary.end()) {
ASSIMP_LOG_WARN("Collada: Unable to find camera for ID \"", cid.mCamera, "\". Skipping.");
continue;
@@ -395,7 +403,7 @@ void ColladaLoader::BuildCamerasForNode(const ColladaParser &pParser, const Node
}
// now fill our ai data structure
aiCamera *out = new aiCamera();
auto *out = new aiCamera();
out->mName = pTarget->mName;
// collada cameras point in -Z by default, rest is specified in node transform
@@ -445,10 +453,10 @@ void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node
const Controller *srcController = nullptr;
// find the referred mesh
ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find(mid.mMeshOrController);
auto srcMeshIt = pParser.mMeshLibrary.find(mid.mMeshOrController);
if (srcMeshIt == pParser.mMeshLibrary.end()) {
// if not found in the mesh-library, it might also be a controller referring to a mesh
ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find(mid.mMeshOrController);
auto srcContrIt = pParser.mControllerLibrary.find(mid.mMeshOrController);
if (srcContrIt != pParser.mControllerLibrary.end()) {
srcController = &srcContrIt->second;
srcMeshIt = pParser.mMeshLibrary.find(srcController->mMeshId);
@@ -462,7 +470,7 @@ void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node
continue;
}
} else {
// ID found in the mesh library -> direct reference to an unskinned mesh
// ID found in the mesh library -> direct reference to a not skinned mesh
srcMesh = srcMeshIt->second;
}
@@ -476,7 +484,7 @@ void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node
// find material assigned to this submesh
std::string meshMaterial;
std::map<std::string, SemanticMappingTable>::const_iterator meshMatIt = mid.mMaterials.find(submesh.mMaterial);
auto meshMatIt = mid.mMaterials.find(submesh.mMaterial);
const Collada::SemanticMappingTable *table = nullptr;
if (meshMatIt != mid.mMaterials.end()) {
@@ -492,30 +500,34 @@ void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node
// OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
// given. The only mapping stuff which we do actually support is the UV channel.
std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find(meshMaterial);
auto matIt = mMaterialIndexByName.find(meshMaterial);
unsigned int matIdx = 0;
if (matIt != mMaterialIndexByName.end()) {
matIdx = static_cast<unsigned int>(matIt->second);
}
if (table && !table->mMap.empty()) {
std::pair<Collada::Effect *, aiMaterial *> &mat = newMats[matIdx];
if (matIdx < newMats.size()) {
std::pair<Collada::Effect *, aiMaterial *> &mat = newMats[matIdx];
// Iterate through all texture channels assigned to the effect and
// check whether we have mapping information for it.
ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
// Iterate through all texture channels assigned to the effect and
// check whether we have mapping information for it.
ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
} else {
ASSIMP_LOG_WARN("Collada: Ignoring material mapping for mesh \"", mid.mMeshOrController, "\". Material index ", matIdx, " is out of bounds (newMats.size()=", newMats.size(), ").");
}
}
// built lookup index of the Mesh-Submesh-Material combination
ColladaMeshIndex index(mid.mMeshOrController, sm, meshMaterial);
// if we already have the mesh at the library, just add its index to the node's array
std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find(index);
auto dstMeshIt = mMeshIndexByID.find(index);
if (dstMeshIt != mMeshIndexByID.end()) {
newMeshRefs.push_back(dstMeshIt->second);
} else {
@@ -530,7 +542,7 @@ void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node
faceStart += submesh.mNumFaces;
// assign the material index
std::map<std::string, size_t>::const_iterator subMatIt = mMaterialIndexByName.find(submesh.mMaterial);
auto subMatIt = mMaterialIndexByName.find(submesh.mMaterial);
if (subMatIt != mMaterialIndexByName.end()) {
dstMesh->mMaterialIndex = static_cast<unsigned int>(subMatIt->second);
} else {
@@ -618,23 +630,21 @@ aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrc
std::copy(pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() + pStartVertex + numVertices, dstMesh->mTangents);
}
// bitangents, if given.
// bi-tangents, if given.
if (pSrcMesh->mBitangents.size() >= pStartVertex + numVertices) {
dstMesh->mBitangents = new aiVector3D[numVertices];
std::copy(pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() + pStartVertex + numVertices, dstMesh->mBitangents);
}
// same for texture coords, as many as we have
// empty slots are not allowed, need to pack and adjust UV indexes accordingly
for (size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
if (pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices) {
dstMesh->mTextureCoords[real] = new aiVector3D[numVertices];
dstMesh->mTextureCoords[a] = new aiVector3D[numVertices];
for (size_t b = 0; b < numVertices; ++b) {
dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex + b];
dstMesh->mTextureCoords[a][b] = pSrcMesh->mTexCoords[a][pStartVertex + b];
}
dstMesh->mNumUVComponents[real] = pSrcMesh->mNumUVComponents[a];
++real;
dstMesh->mNumUVComponents[a] = pSrcMesh->mNumUVComponents[a];
}
}
@@ -666,7 +676,7 @@ aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrc
std::vector<float> targetWeights;
Collada::MorphMethod method = Normalized;
for (std::map<std::string, Controller>::const_iterator it = pParser.mControllerLibrary.begin();
for (auto it = pParser.mControllerLibrary.begin();
it != pParser.mControllerLibrary.end(); ++it) {
const Controller &c = it->second;
const Collada::Mesh *baseMesh = pParser.ResolveLibraryReference(pParser.mMeshLibrary, c.mMeshId);
@@ -756,7 +766,7 @@ aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrc
std::vector<IndexPairVector::const_iterator> weightStartPerVertex;
weightStartPerVertex.resize(pSrcController->mWeightCounts.size(), pSrcController->mWeights.end());
IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
auto pit = pSrcController->mWeights.begin();
for (size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a) {
weightStartPerVertex[a] = pit;
pit += pSrcController->mWeightCounts[a];
@@ -768,7 +778,7 @@ aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrc
// the controller assigns the vertex weights
size_t orgIndex = pSrcMesh->mFacePosIndices[a];
// find the vertex weights for this vertex
IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
auto iit = weightStartPerVertex[orgIndex];
size_t pairCount = pSrcController->mWeightCounts[orgIndex];
for (size_t b = 0; b < pairCount; ++b, ++iit) {
@@ -809,7 +819,7 @@ aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrc
}
// create bone with its weights
aiBone *bone = new aiBone;
auto bone = new aiBone;
bone->mName = ReadString(jointNamesAcc, jointNames, a);
bone->mOffsetMatrix.a1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 0);
bone->mOffsetMatrix.a2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 1);
@@ -975,7 +985,7 @@ void ColladaLoader::StoreAnimations(aiScene *pScene, const ColladaParser &pParse
// if there are other animations which fit the template anim, combine all channels into a single anim
if (!collectedAnimIndices.empty()) {
aiAnimation *combinedAnim = new aiAnimation();
auto *combinedAnim = new aiAnimation();
combinedAnim->mName = aiString(std::string("combinedAnim_") + char('0' + a));
combinedAnim->mDuration = templateAnim->mDuration;
combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
@@ -1022,8 +1032,8 @@ void ColladaLoader::StoreAnimations(aiScene *pScene, const ColladaParser &pParse
std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
// create nested animations, if given
for (auto mSubAnim : pSrcAnim->mSubAnims) {
StoreAnimations(pScene, pParser, mSubAnim, animName);
for (auto &mSubAnim : pSrcAnim->mSubAnims) {
StoreAnimations(pScene, pParser, mSubAnim.get(), animName);
}
// create animation channels, if any
@@ -1042,7 +1052,7 @@ struct MorphTimeValues {
};
void insertMorphTimeValue(std::vector<MorphTimeValues> &values, float time, float weight, unsigned int value) {
MorphTimeValues::key k;
MorphTimeValues::key k{};
k.mValue = value;
k.mWeight = weight;
if (values.empty() || time < values[0].mTime) {
@@ -1079,6 +1089,7 @@ static float getWeightAtKey(const std::vector<MorphTimeValues> &values, int key,
return mKey.mWeight;
}
}
// no value at key found, try to interpolate if present at other keys. if not, return zero
// TODO: interpolation
return 0.0f;
@@ -1107,7 +1118,7 @@ void ColladaLoader::CreateAnimation(aiScene *pScene, const ColladaParser &pParse
// now check all channels if they affect the current node
std::string targetID, subElement;
for (std::vector<AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
for (auto cit = pSrcAnim->mChannels.begin();
cit != pSrcAnim->mChannels.end(); ++cit) {
const AnimationChannel &srcChannel = *cit;
ChannelEntry entry;
@@ -1350,7 +1361,7 @@ void ColladaLoader::CreateAnimation(aiScene *pScene, const ColladaParser &pParse
// build an animation channel for the given node out of these trafo keys
if (!resultTrafos.empty()) {
aiNodeAnim *dstAnim = new aiNodeAnim;
auto *dstAnim = new aiNodeAnim;
dstAnim->mNodeName = nodeName;
dstAnim->mNumPositionKeys = static_cast<unsigned int>(resultTrafos.size());
dstAnim->mNumRotationKeys = static_cast<unsigned int>(resultTrafos.size());
@@ -1392,7 +1403,7 @@ void ColladaLoader::CreateAnimation(aiScene *pScene, const ColladaParser &pParse
// or 2) one channel with morph target count arrays
// assume first
aiMeshMorphAnim *morphAnim = new aiMeshMorphAnim;
auto *morphAnim = new aiMeshMorphAnim;
morphAnim->mName.Set(nodeName);
std::vector<MorphTimeValues> morphTimeValues;
@@ -1435,7 +1446,7 @@ void ColladaLoader::CreateAnimation(aiScene *pScene, const ColladaParser &pParse
}
if (!anims.empty() || !morphAnims.empty()) {
aiAnimation *anim = new aiAnimation;
auto anim = new aiAnimation;
anim->mName.Set(pName);
anim->mNumChannels = static_cast<unsigned int>(anims.size());
if (anim->mNumChannels > 0) {
@@ -1515,7 +1526,7 @@ void ColladaLoader::AddTexture(aiMaterial &mat,
map = sampler.mUVId;
} else {
map = -1;
for (std::string::const_iterator it = sampler.mUVChannel.begin(); it != sampler.mUVChannel.end(); ++it) {
for (auto it = sampler.mUVChannel.begin(); it != sampler.mUVChannel.end(); ++it) {
if (IsNumeric(*it)) {
map = strtoul10(&(*it));
break;
@@ -1533,7 +1544,7 @@ void ColladaLoader::AddTexture(aiMaterial &mat,
// Fills materials from the collada material definitions
void ColladaLoader::FillMaterials(const ColladaParser &pParser, aiScene * /*pScene*/) {
for (auto &elem : newMats) {
aiMaterial &mat = (aiMaterial &)*elem.second;
auto &mat = (aiMaterial &)*elem.second;
Collada::Effect &effect = *elem.first;
// resolve shading mode
@@ -1643,17 +1654,17 @@ void ColladaLoader::FillMaterials(const ColladaParser &pParser, aiScene * /*pSce
void ColladaLoader::BuildMaterials(ColladaParser &pParser, aiScene * /*pScene*/) {
newMats.reserve(pParser.mMaterialLibrary.size());
for (ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin();
for (auto matIt = pParser.mMaterialLibrary.begin();
matIt != pParser.mMaterialLibrary.end(); ++matIt) {
const Material &material = matIt->second;
// a material is only a reference to an effect
ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find(material.mEffect);
auto effIt = pParser.mEffectLibrary.find(material.mEffect);
if (effIt == pParser.mEffectLibrary.end())
continue;
Effect &effect = effIt->second;
// create material
aiMaterial *mat = new aiMaterial;
auto *mat = new aiMaterial;
aiString name(material.mName.empty() ? matIt->first : material.mName);
mat->AddProperty(&name, AI_MATKEY_NAME);
@@ -1676,7 +1687,7 @@ aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser &pParse
std::string name = pName;
while (true) {
// the given string is a param entry. Find it
Effect::ParamLibrary::const_iterator it = pEffect.mParams.find(name);
auto it = pEffect.mParams.find(name);
// if not found, we're at the end of the recursion. The resulting string should be the image ID
if (it == pEffect.mParams.end())
break;
@@ -1686,7 +1697,7 @@ aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser &pParse
}
// find the image referred by this name in the image library of the scene
ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find(name);
auto imIt = pParser.mImageLibrary.find(name);
if (imIt == pParser.mImageLibrary.end()) {
ASSIMP_LOG_WARN("Collada: Unable to resolve effect texture entry \"", pName, "\", ended up at ID \"", name, "\".");
@@ -1698,7 +1709,7 @@ aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser &pParse
// if this is an embedded texture image setup an aiTexture for it
if (!imIt->second.mImageData.empty()) {
aiTexture *tex = new aiTexture();
auto *tex = new aiTexture();
// Store embedded texture name reference
tex->mFilename.Set(imIt->second.mFileName.c_str());
@@ -1730,14 +1741,6 @@ aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser &pParse
return result;
}
// ------------------------------------------------------------------------------------------------
// Reads a float value from an accessor and its data array.
ai_real ColladaLoader::ReadFloat(const Accessor &pAccessor, const Data &pData, size_t pIndex, size_t pOffset) const {
size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
ai_assert(pos < pData.mValues.size());
return pData.mValues[pos];
}
// ------------------------------------------------------------------------------------------------
// Reads a string value from an accessor and its data array.
const std::string &ColladaLoader::ReadString(const Accessor &pAccessor, const Data &pData, size_t pIndex) const {
@@ -1820,4 +1823,4 @@ std::string ColladaLoader::FindNameForNode(const Node *pNode) {
} // Namespace Assimp
#endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER
#endif // !! ASSIMP_BUILD_NO_COLLADA_IMPORTER
+26 -36
View File
@@ -4,8 +4,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -77,10 +76,13 @@ struct ColladaMeshIndex {
}
};
/** Loader class to read Collada scenes. Collada is over-engineered to death, with every new iteration bringing
* more useless stuff, so I limited the data to what I think is useful for games.
/**
* @brief Loader class to read Collada scenes.
*
* Collada is over-engineered to death, with every new iteration bringing more useless stuff,
* so I limited the data to what I think is useful for games.
*/
class ColladaLoader : public BaseImporter {
class ColladaLoader final : public BaseImporter {
public:
/// The class constructor.
ColladaLoader();
@@ -102,50 +104,51 @@ protected:
/// See #BaseImporter::InternReadFile for the details
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) override;
/** Recursively constructs a scene node for the given parser node and returns it. */
/// Recursively constructs a scene node for the given parser node and returns it.
aiNode *BuildHierarchy(const ColladaParser &pParser, const Collada::Node *pNode);
/** Resolve node instances */
/// Resolve node instances
void ResolveNodeInstances(const ColladaParser &pParser, const Collada::Node *pNode,
std::vector<const Collada::Node *> &resolved);
std::vector<const Collada::Node *> &resolved) const;
/** Builds meshes for the given node and references them */
/// Builds meshes for the given node and references them
void BuildMeshesForNode(const ColladaParser &pParser, const Collada::Node *pNode,
aiNode *pTarget);
/// Lookup for meshes by their name
aiMesh *findMesh(const std::string &meshid);
/** Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh */
/// Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
aiMesh *CreateMesh(const ColladaParser &pParser, const Collada::Mesh *pSrcMesh, const Collada::SubMesh &pSubMesh,
const Collada::Controller *pSrcController, size_t pStartVertex, size_t pStartFace);
/** Builds cameras for the given node and references them */
/// Builds cameras for the given node and references them
void BuildCamerasForNode(const ColladaParser &pParser, const Collada::Node *pNode,
aiNode *pTarget);
/** Builds lights for the given node and references them */
/// Builds lights for the given node and references them
void BuildLightsForNode(const ColladaParser &pParser, const Collada::Node *pNode,
aiNode *pTarget);
/** Stores all meshes in the given scene */
/// Stores all meshes in the given scene
void StoreSceneMeshes(aiScene *pScene);
/** Stores all materials in the given scene */
/// Stores all materials in the given scene
void StoreSceneMaterials(aiScene *pScene);
/** Stores all lights in the given scene */
/// Stores all lights in the given scene
void StoreSceneLights(aiScene *pScene);
/** Stores all cameras in the given scene */
/// Stores all cameras in the given scene
void StoreSceneCameras(aiScene *pScene);
/** Stores all textures in the given scene */
/// Stores all textures in the given scene
void StoreSceneTextures(aiScene *pScene);
/** Stores all animations
* @param pScene target scene to store the anims
*/
void StoreAnimations(aiScene *pScene, const ColladaParser &pParser);
/// Stores all animations
/// @param pScene Target scene to store the anims
/// @param parser The collada parser
void StoreAnimations(aiScene *pScene, const ColladaParser &parser);
/** Stores all animations for the given source anim and its nested child animations
* @param pScene target scene to store the anims
@@ -163,10 +166,6 @@ protected:
/** Fill materials from the collada material definitions */
void FillMaterials(const ColladaParser &pParser, aiScene *pScene);
/** Resolve UV channel mappings*/
void ApplyVertexToEffectSemanticMapping(Collada::Sampler &sampler,
const Collada::SemanticMappingTable &table);
/** Add a texture and all of its sampling properties to a material*/
void AddTexture(aiMaterial &mat, const ColladaParser &pParser,
const Collada::Effect &effect,
@@ -177,22 +176,13 @@ protected:
aiString FindFilenameForEffectTexture(const ColladaParser &pParser,
const Collada::Effect &pEffect, const std::string &pName);
/** Reads a float value from an accessor and its data array.
* @param pAccessor The accessor to use for reading
* @param pData The data array to read from
* @param pIndex The index of the element to retrieve
* @param pOffset Offset into the element, for multipart elements such as vectors or matrices
* @return the specified value
*/
ai_real ReadFloat(const Collada::Accessor &pAccessor, const Collada::Data &pData, size_t pIndex, size_t pOffset) const;
/** Reads a string value from an accessor and its data array.
* @param pAccessor The accessor to use for reading
* @param pData The data array to read from
* @param pIndex The index of the element to retrieve
* @return the specified value
*/
const std::string &ReadString(const Collada::Accessor &pAccessor, const Collada::Data &pData, size_t pIndex) const;
[[nodiscard]] const std::string &ReadString(const Collada::Accessor &pAccessor, const Collada::Data &pData, size_t pIndex) const;
/** Recursively collects all nodes into the given array */
void CollectNodes(const aiNode *pNode, std::vector<const aiNode *> &poNodes) const;
@@ -205,7 +195,7 @@ protected:
/** Finds a proper name for a node derived from the collada-node's properties */
std::string FindNameForNode(const Collada::Node *pNode);
protected:
private:
/** Filename, for a verbose error message */
std::string mFileName;
File diff suppressed because it is too large Load Diff
+83 -112
View File
@@ -2,7 +2,7 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2024, assimp team
Copyright (c) 2006-2026, assimp team
All rights reserved.
@@ -48,7 +48,6 @@
#define AI_COLLADAPARSER_H_INC
#include "ColladaHelper.h"
#include <assimp/TinyFormatter.h>
#include <assimp/ai_assert.h>
#include <assimp/XmlParser.h>
@@ -67,268 +66,240 @@ class ZipArchiveIOSystem;
class ColladaParser {
friend class ColladaLoader;
/** Converts a path read from a collada file to the usual representation */
static void UriDecodePath(aiString &ss);
public:
/// Map for generic metadata as aiString.
using StringMetaData = std::map<std::string, aiString>;
protected:
/** Map for generic metadata as aiString */
typedef std::map<std::string, aiString> StringMetaData;
/** Constructor from XML file */
/// Constructor from XML file.
ColladaParser(IOSystem *pIOHandler, const std::string &pFile);
/** Destructor */
/// Destructor
~ColladaParser();
/** Attempts to read the ZAE manifest and returns the DAE to open */
/// Attempts to read the ZAE manifest and returns the DAE to open
static std::string ReadZaeManifest(ZipArchiveIOSystem &zip_archive);
/** Reads the contents of the file */
/// Reads the contents of the file
void ReadContents(XmlNode &node);
/** Reads the structure of the file */
/// Reads the structure of the file
void ReadStructure(XmlNode &node);
/** Reads asset information such as coordinate system information and legal blah */
/// Reads asset information such as coordinate system information and legal blah
void ReadAssetInfo(XmlNode &node);
/** Reads contributor information such as author and legal blah */
/// Reads contributor information such as author and legal blah
void ReadContributorInfo(XmlNode &node);
/** Reads generic metadata into provided map and renames keys for Assimp */
void ReadMetaDataItem(XmlNode &node, StringMetaData &metadata);
/** Reads the animation library */
/// Reads the animation library
void ReadAnimationLibrary(XmlNode &node);
/** Reads the animation clip library */
/// Reads the animation clip library
void ReadAnimationClipLibrary(XmlNode &node);
/** Unwrap controllers dependency hierarchy */
/// Unwrap controllers dependency hierarchy
void PostProcessControllers();
/** Re-build animations from animation clip library, if present, otherwise combine single-channel animations */
/// Re-build animations from animation clip library, if present, otherwise combine single-channel animations
void PostProcessRootAnimations();
/** Reads an animation into the given parent structure */
/// Reads an animation into the given parent structure
void ReadAnimation(XmlNode &node, Collada::Animation *pParent);
/** Reads an animation sampler into the given anim channel */
void ReadAnimationSampler(XmlNode &node, Collada::AnimationChannel &pChannel);
/** Reads the skeleton controller library */
/// Reads the skeleton controller library
void ReadControllerLibrary(XmlNode &node);
/** Reads a controller into the given mesh structure */
/// Reads a controller into the given mesh structure
void ReadController(XmlNode &node, Collada::Controller &pController);
/** Reads the joint definitions for the given controller */
void ReadControllerJoints(XmlNode &node, Collada::Controller &pController);
/// Reads the image library contents
void ReadImageLibrary(const XmlNode &node);
/** Reads the joint weights for the given controller */
void ReadControllerWeights(XmlNode &node, Collada::Controller &pController);
/// Reads an image entry into the given image
void ReadImage(const XmlNode &node, Collada::Image &pImage) const;
/** Reads the image library contents */
void ReadImageLibrary(XmlNode &node);
/** Reads an image entry into the given image */
void ReadImage(XmlNode &node, Collada::Image &pImage);
/** Reads the material library */
/// Reads the material library
void ReadMaterialLibrary(XmlNode &node);
/** Reads a material entry into the given material */
void ReadMaterial(XmlNode &node, Collada::Material &pMaterial);
/** Reads the camera library */
/// Reads the camera library
void ReadCameraLibrary(XmlNode &node);
/** Reads a camera entry into the given camera */
void ReadCamera(XmlNode &node, Collada::Camera &pCamera);
/** Reads the light library */
/// Reads the light library
void ReadLightLibrary(XmlNode &node);
/** Reads a light entry into the given light */
void ReadLight(XmlNode &node, Collada::Light &pLight);
/** Reads the effect library */
/// Reads the effect library
void ReadEffectLibrary(XmlNode &node);
/** Reads an effect entry into the given effect*/
/// Reads an effect entry into the given effect
void ReadEffect(XmlNode &node, Collada::Effect &pEffect);
/** Reads an COMMON effect profile */
/// Reads an COMMON effect profile
void ReadEffectProfileCommon(XmlNode &node, Collada::Effect &pEffect);
/** Read sampler properties */
/// Read sampler properties
void ReadSamplerProperties(XmlNode &node, Collada::Sampler &pSampler);
/** Reads an effect entry containing a color or a texture defining that color */
/// Reads an effect entry containing a color or a texture defining that color
void ReadEffectColor(XmlNode &node, aiColor4D &pColor, Collada::Sampler &pSampler);
/** Reads an effect entry containing a float */
/// Reads an effect entry containing a float
void ReadEffectFloat(XmlNode &node, ai_real &pFloat);
/** Reads an effect parameter specification of any kind */
/// Reads an effect parameter specification of any kind
void ReadEffectParam(XmlNode &node, Collada::EffectParam &pParam);
/** Reads the geometry library contents */
/// Reads the geometry library contents
void ReadGeometryLibrary(XmlNode &node);
/** Reads a geometry from the geometry library. */
/// Reads a geometry from the geometry library.
void ReadGeometry(XmlNode &node, Collada::Mesh &pMesh);
/** Reads a mesh from the geometry library */
/// Reads a mesh from the geometry library
void ReadMesh(XmlNode &node, Collada::Mesh &pMesh);
/** Reads a source element - a combination of raw data and an accessor defining
* things that should not be redefinable. Yes, that's another rant.
*/
/// Reads a source element - a combination of raw data and an accessor defining
///things that should not be definable. Yes, that's another rant.
void ReadSource(XmlNode &node);
/** Reads a data array holding a number of elements, and stores it in the global library.
* Currently supported are array of floats and arrays of strings.
*/
/// Reads a data array holding a number of elements, and stores it in the global library.
/// Currently supported are array of floats and arrays of strings.
void ReadDataArray(XmlNode &node);
/** Reads an accessor and stores it in the global library under the given ID -
* accessors use the ID of the parent <source> element
*/
/// Reads an accessor and stores it in the global library under the given ID -
/// accessors use the ID of the parent <source> element
void ReadAccessor(XmlNode &node, const std::string &pID);
/** Reads input declarations of per-vertex mesh data into the given mesh */
/// Reads input declarations of per-vertex mesh data into the given mesh
void ReadVertexData(XmlNode &node, Collada::Mesh &pMesh);
/** Reads input declarations of per-index mesh data into the given mesh */
/// Reads input declarations of per-index mesh data into the given mesh
void ReadIndexData(XmlNode &node, Collada::Mesh &pMesh);
/** Reads a single input channel element and stores it in the given array, if valid */
/// Reads a single input channel element and stores it in the given array, if valid
void ReadInputChannel(XmlNode &node, std::vector<Collada::InputChannel> &poChannels);
/** Reads a <p> primitive index list and assembles the mesh data into the given mesh */
/// Reads a <p> primitive index list and assembles the mesh data into the given mesh
size_t ReadPrimitives(XmlNode &node, Collada::Mesh &pMesh, std::vector<Collada::InputChannel> &pPerIndexChannels,
size_t pNumPrimitives, const std::vector<size_t> &pVCount, Collada::PrimitiveType pPrimType);
/** Copies the data for a single primitive into the mesh, based on the InputChannels */
/// Copies the data for a single primitive into the mesh, based on the InputChannels
void CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset,
Collada::Mesh &pMesh, std::vector<Collada::InputChannel> &pPerIndexChannels,
size_t currentPrimitive, const std::vector<size_t> &indices);
/** Reads one triangle of a tristrip into the mesh */
/// Reads one triangle of a tristrip into the mesh
void ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Collada::Mesh &pMesh,
std::vector<Collada::InputChannel> &pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t> &indices);
/** Extracts a single object from an input channel and stores it in the appropriate mesh data array */
/// Extracts a single object from an input channel and stores it in the appropriate mesh data array
void ExtractDataObjectFromChannel(const Collada::InputChannel &pInput, size_t pLocalIndex, Collada::Mesh &pMesh);
/** Reads the library of node hierarchies and scene parts */
/// Reads the library of node hierarchies and scene parts
void ReadSceneLibrary(XmlNode &node);
/** Reads a scene node's contents including children and stores it in the given node */
/// Reads a scene node's contents including children and stores it in the given node
void ReadSceneNode(XmlNode &node, Collada::Node *pNode);
/** Reads a node transformation entry of the given type and adds it to the given node's transformation list. */
void ReadNodeTransformation(XmlNode &node, Collada::Node *pNode, Collada::TransformType pType);
/** Reads a mesh reference in a node and adds it to the node's mesh list */
/// Reads a mesh reference in a node and adds it to the node's mesh list
void ReadNodeGeometry(XmlNode &node, Collada::Node *pNode);
/** Reads the collada scene */
/// Reads the collada scene
void ReadScene(XmlNode &node);
// Processes bind_vertex_input and bind elements
/// Processes bind_vertex_input and bind elements
void ReadMaterialVertexInputBinding(XmlNode &node, Collada::SemanticMappingTable &tbl);
/** Reads embedded textures from a ZAE archive*/
/// Reads embedded textures from a ZAE archive
void ReadEmbeddedTextures(ZipArchiveIOSystem &zip_archive);
protected:
/** Calculates the resulting transformation from all the given transform steps */
/// Converts a path read from a collada file to the usual representation
static void UriDecodePath(aiString &ss);
/// Calculates the resulting transformation from all the given transform steps
aiMatrix4x4 CalculateResultTransform(const std::vector<Collada::Transform> &pTransforms) const;
/** Determines the input data type for the given semantic string */
/// Determines the input data type for the given semantic string
Collada::InputType GetTypeForSemantic(const std::string &pSemantic);
/** Finds the item in the given library by its reference, throws if not found */
/// Finds the item in the given library by its reference, throws if not found
template <typename Type>
const Type &ResolveLibraryReference(const std::map<std::string, Type> &pLibrary, const std::string &pURL) const;
protected:
// Filename, for a verbose error message
private:
/// Filename, for a verbose error message
std::string mFileName;
// XML reader, member for everyday use
/// XML reader, member for everyday use
XmlParser mXmlParser;
/** All data arrays found in the file by ID. Might be referred to by actually
everyone. Collada, you are a steaming pile of indirection. */
/// All data arrays found in the file by ID. Might be referred to by actually
/// everyone. Collada, you are a steaming pile of indirection.
using DataLibrary = std::map<std::string, Collada::Data> ;
DataLibrary mDataLibrary;
/** Same for accessors which define how the data in a data array is accessed. */
/// Same for accessors which define how the data in a data array is accessed.
using AccessorLibrary = std::map<std::string, Collada::Accessor> ;
AccessorLibrary mAccessorLibrary;
/** Mesh library: mesh by ID */
/// Mesh library: mesh by ID
using MeshLibrary = std::map<std::string, Collada::Mesh *>;
MeshLibrary mMeshLibrary;
/** node library: root node of the hierarchy part by ID */
/// node library: root node of the hierarchy part by ID
using NodeLibrary = std::map<std::string, Collada::Node *>;
NodeLibrary mNodeLibrary;
/** Image library: stores texture properties by ID */
/// Image library: stores texture properties by ID
using ImageLibrary = std::map<std::string, Collada::Image> ;
ImageLibrary mImageLibrary;
/** Effect library: surface attributes by ID */
/// Effect library: surface attributes by ID
using EffectLibrary = std::map<std::string, Collada::Effect> ;
EffectLibrary mEffectLibrary;
/** Material library: surface material by ID */
/// Material library: surface material by ID
using MaterialLibrary = std::map<std::string, Collada::Material> ;
MaterialLibrary mMaterialLibrary;
/** Light library: surface light by ID */
/// Light library: surface light by ID
using LightLibrary = std::map<std::string, Collada::Light> ;
LightLibrary mLightLibrary;
/** Camera library: surface material by ID */
/// Camera library: surface material by ID
using CameraLibrary = std::map<std::string, Collada::Camera> ;
CameraLibrary mCameraLibrary;
/** Controller library: joint controllers by ID */
/// Controller library: joint controllers by ID
using ControllerLibrary = std::map<std::string, Collada::Controller> ;
ControllerLibrary mControllerLibrary;
/** Animation library: animation references by ID */
/// Animation library: animation references by ID
using AnimationLibrary = std::map<std::string, Collada::Animation *> ;
AnimationLibrary mAnimationLibrary;
/** Animation clip library: clip animation references by ID */
/// Animation clip library: clip animation references by ID
using AnimationClipLibrary = std::vector<std::pair<std::string, std::vector<std::string>>> ;
AnimationClipLibrary mAnimationClipLibrary;
/** Pointer to the root node. Don't delete, it just points to one of
the nodes in the node library. */
/// Pointer to the root node. Don't delete, it just points to one of the nodes in the node library.
Collada::Node *mRootNode;
/** Root animation container */
/// Root animation container
Collada::Animation mAnims;
/** Size unit: how large compared to a meter */
/// Size unit: how large compared to a meter
ai_real mUnitSize;
/** Which is the up vector */
/// Which is the up vector
enum { UP_X,
UP_Y,
UP_Z } mUpDirection;
/** Asset metadata (global for scene) */
/// Asset metadata (global for scene)
StringMetaData mAssetMetaData;
/** Collada file format version */
/// Collada file format version
Collada::FormatVersion mFormat;
};

Some files were not shown because too many files have changed in this diff Show More