Coverage Report

Created: 2025-12-05 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/Irr/IRRMeshLoader.cpp
Line
Count
Source
1
/*
2
---------------------------------------------------------------------------
3
Open Asset Import Library (assimp)
4
---------------------------------------------------------------------------
5
6
Copyright (c) 2006-2025, assimp team
7
8
All rights reserved.
9
10
Redistribution and use of this software in source and binary forms,
11
with or without modification, are permitted provided that the following
12
conditions are met:
13
14
* Redistributions of source code must retain the above
15
  copyright notice, this list of conditions and the
16
  following disclaimer.
17
18
* Redistributions in binary form must reproduce the above
19
  copyright notice, this list of conditions and the
20
  following disclaimer in the documentation and/or other
21
  materials provided with the distribution.
22
23
* Neither the name of the assimp team, nor the names of its
24
  contributors may be used to endorse or promote products
25
  derived from this software without specific prior
26
  written permission of the assimp team.
27
28
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
---------------------------------------------------------------------------
40
*/
41
42
/** @file Implementation of the IrrMesh importer class */
43
44
#ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER
45
46
#include "IRRMeshLoader.h"
47
#include <assimp/ParsingUtils.h>
48
#include <assimp/fast_atof.h>
49
#include <assimp/importerdesc.h>
50
#include <assimp/material.h>
51
#include <assimp/mesh.h>
52
#include <assimp/scene.h>
53
#include <assimp/DefaultLogger.hpp>
54
#include <assimp/IOSystem.hpp>
55
#include <memory>
56
57
using namespace Assimp;
58
59
static constexpr aiImporterDesc desc = {
60
    "Irrlicht Mesh Reader",
61
    "",
62
    "",
63
    "http://irrlicht.sourceforge.net/",
64
    aiImporterFlags_SupportTextFlavour,
65
    0,
66
    0,
67
    0,
68
    0,
69
    "xml irrmesh"
70
};
71
72
// ------------------------------------------------------------------------------------------------
73
// Returns whether the class can handle the format of the given file.
74
487
bool IRRMeshImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
75
    /* NOTE: A simple check for the file extension is not enough
76
     * here. Irrmesh and irr are easy, but xml is too generic
77
     * and could be collada, too. So we need to open the file and
78
     * search for typical tokens.
79
     */
80
487
    static const char *tokens[] = { "irrmesh" };
81
487
    return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
82
487
}
83
84
// ------------------------------------------------------------------------------------------------
85
// Get a list of all file extensions which are handled by this class
86
1.19k
const aiImporterDesc *IRRMeshImporter::GetInfo() const {
87
1.19k
    return &desc;
88
1.19k
}
89
90
0
static void releaseMaterial(aiMaterial **mat) {
91
0
    if (*mat != nullptr) {
92
0
        delete *mat;
93
0
        *mat = nullptr;
94
0
    }
95
0
}
96
97
0
static void releaseMesh(aiMesh **mesh) {
98
0
    if (*mesh != nullptr) {
99
0
        delete *mesh;
100
0
        *mesh = nullptr;
101
0
    }
102
0
}
103
104
// ------------------------------------------------------------------------------------------------
105
// Imports the given file into the given scene structure.
106
void IRRMeshImporter::InternReadFile(const std::string &pFile,
107
0
        aiScene *pScene, IOSystem *pIOHandler) {
108
0
    std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
109
110
    // Check whether we can read from the file
111
0
    if (file == nullptr) {
112
0
        throw DeadlyImportError("Failed to open IRRMESH file ", pFile);
113
0
    }
114
115
    // Construct the irrXML parser
116
0
    XmlParser parser;
117
0
    if (!parser.parse(file.get())) {
118
0
        throw DeadlyImportError("XML parse error while loading IRRMESH file ", pFile);
119
0
    }
120
0
    XmlNode root = parser.getRootNode();
121
122
    // final data
123
0
    std::vector<aiMaterial *> materials;
124
0
    std::vector<aiMesh *> meshes;
125
0
    materials.reserve(5);
126
0
    meshes.reserve(5);
127
128
    // temporary data - current mesh buffer
129
    // TODO move all these to inside loop
130
0
    aiMaterial *curMat = nullptr;
131
0
    aiMesh *curMesh = nullptr;
132
0
    unsigned int curMatFlags = 0;
133
134
0
    std::vector<aiVector3D> curVertices, curNormals, curTangents, curBitangents;
135
0
    std::vector<aiColor4D> curColors;
136
0
    std::vector<aiVector3D> curUVs, curUV2s;
137
138
    // some temporary variables
139
    // textMeaning is a 15 year old variable, that could've been an enum
140
    // int textMeaning = 0; // 0=none? 1=vertices 2=indices
141
    // int vertexFormat = 0; // 0 = normal; 1 = 2 tcoords, 2 = tangents
142
0
    bool useColors = false;
143
144
    // irrmesh files have a top level <mesh> owning multiple <buffer> nodes.
145
    // Each <buffer> contains <material>, <vertices>, and <indices>
146
    // <material> tags here directly owns the material data specs
147
    // <vertices> are a vertex per line, contains position, UV1 coords, maybe UV2, normal, tangent, bitangent
148
    // <boundingbox> is ignored, I think assimp recalculates those?
149
150
    // Parse the XML file
151
0
    pugi::xml_node const &meshNode = root.child("mesh");
152
0
    for (pugi::xml_node bufferNode : meshNode.children()) {
153
0
        if (ASSIMP_stricmp(bufferNode.name(), "buffer")) {
154
            // Might be a useless warning
155
0
            ASSIMP_LOG_WARN("IRRMESH: Ignoring non buffer node <", bufferNode.name(), "> in mesh declaration");
156
0
            continue;
157
0
        }
158
159
0
        curMat = nullptr;
160
0
        curMesh = nullptr;
161
162
0
        curVertices.clear();
163
0
        curColors.clear();
164
0
        curNormals.clear();
165
0
        curUV2s.clear();
166
0
        curUVs.clear();
167
0
        curTangents.clear();
168
0
        curBitangents.clear();
169
170
        // TODO ensure all three nodes are present and populated
171
        // before allocating everything
172
173
        // Get first material node
174
0
        pugi::xml_node materialNode = bufferNode.child("material");
175
0
        if (materialNode) {
176
0
            curMat = ParseMaterial(materialNode, curMatFlags);
177
            // Warn if there's more materials
178
0
            if (materialNode.next_sibling("material")) {
179
0
                ASSIMP_LOG_WARN("IRRMESH: Only one material description per buffer, please");
180
0
            }
181
0
        } else {
182
0
            ASSIMP_LOG_ERROR("IRRMESH: Buffer must contain one material");
183
0
            continue;
184
0
        }
185
186
        // Get first vertices node
187
0
        pugi::xml_node verticesNode = bufferNode.child("vertices");
188
0
        if (verticesNode) {
189
0
            pugi::xml_attribute vertexCountAttrib = verticesNode.attribute("vertexCount");
190
0
            int vertexCount = vertexCountAttrib.as_int();
191
0
            if (vertexCount == 0) {
192
                // This is possible ... remove the mesh from the list and skip further reading
193
0
                ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero vertices");
194
0
                releaseMaterial(&curMat);
195
0
                continue; // Bail out early
196
0
            };
197
198
0
            curVertices.reserve(vertexCount);
199
0
            curNormals.reserve(vertexCount);
200
0
            curColors.reserve(vertexCount);
201
0
            curUVs.reserve(vertexCount);
202
203
0
            VertexFormat vertexFormat;
204
            // Determine the file format
205
0
            pugi::xml_attribute typeAttrib = verticesNode.attribute("type");
206
0
            if (!ASSIMP_stricmp("2tcoords", typeAttrib.value())) {
207
0
                curUV2s.reserve(vertexCount);
208
0
                vertexFormat = VertexFormat::t2coord;
209
0
                if (curMatFlags & AI_IRRMESH_EXTRA_2ND_TEXTURE) {
210
                    // *********************************************************
211
                    // We have a second texture! So use this UV channel
212
                    // for it. The 2nd texture can be either a normal
213
                    // texture (solid_2layer or lightmap_xxx) or a normal
214
                    // map (normal_..., parallax_...)
215
                    // *********************************************************
216
0
                    int idx = 1;
217
0
                    aiMaterial *mat = (aiMaterial *)curMat;
218
219
0
                    if (curMatFlags & AI_IRRMESH_MAT_lightmap) {
220
0
                        mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_LIGHTMAP(0));
221
0
                    } else if (curMatFlags & AI_IRRMESH_MAT_normalmap_solid) {
222
0
                        mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_NORMALS(0));
223
0
                    } else if (curMatFlags & AI_IRRMESH_MAT_solid_2layer) {
224
0
                        mat->AddProperty(&idx, 1, AI_MATKEY_UVWSRC_DIFFUSE(1));
225
0
                    }
226
0
                }
227
0
            } else if (!ASSIMP_stricmp("tangents", typeAttrib.value())) {
228
0
                curTangents.reserve(vertexCount);
229
0
                curBitangents.reserve(vertexCount);
230
0
                vertexFormat = VertexFormat::tangent;
231
0
            } else if (!ASSIMP_stricmp("standard", typeAttrib.value())) {
232
0
                vertexFormat = VertexFormat::standard;
233
0
            } else {
234
                // Unsupported format, discard whole buffer/mesh
235
                // Assuming we have a correct material, then release it
236
                // We don't have a correct mesh for sure here
237
0
                releaseMaterial(&curMat);
238
0
                ASSIMP_LOG_ERROR("IRRMESH: Unknown vertex format");
239
0
                continue; // Skip rest of buffer
240
0
            };
241
242
            // We know what format buffer is, collect numbers
243
0
            std::string v = verticesNode.text().get();
244
0
            const char *end = v.c_str() + v.size();
245
0
            ParseBufferVertices(v.c_str(), end, vertexFormat,
246
0
                    curVertices, curNormals,
247
0
                    curTangents, curBitangents,
248
0
                    curUVs, curUV2s, curColors, useColors);
249
0
        }
250
251
        // Get indices
252
        // At this point we have some vertices and a valid material
253
        // Collect indices and create aiMesh at the same time
254
0
        pugi::xml_node indicesNode = bufferNode.child("indices");
255
0
        if (indicesNode) {
256
            // start a new mesh
257
0
            curMesh = new aiMesh();
258
259
            // allocate storage for all faces
260
0
            pugi::xml_attribute attr = indicesNode.attribute("indexCount");
261
0
            curMesh->mNumVertices = attr.as_int();
262
0
            if (!curMesh->mNumVertices) {
263
                // This is possible ... remove the mesh from the list and skip further reading
264
0
                ASSIMP_LOG_WARN("IRRMESH: Found mesh with zero indices");
265
266
                // mesh - away
267
0
                releaseMesh(&curMesh);
268
269
                // material - away
270
0
                releaseMaterial(&curMat);
271
0
                continue; // Go to next buffer
272
0
            }
273
274
0
            if (curMesh->mNumVertices % 3) {
275
0
                ASSIMP_LOG_WARN("IRRMESH: Number if indices isn't divisible by 3");
276
0
            }
277
278
0
            curMesh->mNumFaces = curMesh->mNumVertices / 3;
279
0
            curMesh->mFaces = new aiFace[curMesh->mNumFaces];
280
281
            // setup some members
282
0
            curMesh->mMaterialIndex = (unsigned int)materials.size();
283
0
            curMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
284
285
            // allocate storage for all vertices
286
0
            curMesh->mVertices = new aiVector3D[curMesh->mNumVertices];
287
288
0
            if (curNormals.size() == curVertices.size()) {
289
0
                curMesh->mNormals = new aiVector3D[curMesh->mNumVertices];
290
0
            }
291
0
            if (curTangents.size() == curVertices.size()) {
292
0
                curMesh->mTangents = new aiVector3D[curMesh->mNumVertices];
293
0
            }
294
0
            if (curBitangents.size() == curVertices.size()) {
295
0
                curMesh->mBitangents = new aiVector3D[curMesh->mNumVertices];
296
0
            }
297
0
            if (curColors.size() == curVertices.size() && useColors) {
298
0
                curMesh->mColors[0] = new aiColor4D[curMesh->mNumVertices];
299
0
            }
300
0
            if (curUVs.size() == curVertices.size()) {
301
0
                curMesh->mTextureCoords[0] = new aiVector3D[curMesh->mNumVertices];
302
0
            }
303
0
            if (curUV2s.size() == curVertices.size()) {
304
0
                curMesh->mTextureCoords[1] = new aiVector3D[curMesh->mNumVertices];
305
0
            }
306
307
            // read indices
308
0
            aiFace *curFace = curMesh->mFaces;
309
0
            aiFace *const faceEnd = curMesh->mFaces + curMesh->mNumFaces;
310
311
0
            aiVector3D *pcV = curMesh->mVertices;
312
0
            aiVector3D *pcN = curMesh->mNormals;
313
0
            aiVector3D *pcT = curMesh->mTangents;
314
0
            aiVector3D *pcB = curMesh->mBitangents;
315
0
            aiColor4D *pcC0 = curMesh->mColors[0];
316
0
            aiVector3D *pcT0 = curMesh->mTextureCoords[0];
317
0
            aiVector3D *pcT1 = curMesh->mTextureCoords[1];
318
319
0
            unsigned int curIdx = 0;
320
0
            unsigned int total = 0;
321
322
            // NOTE this might explode for UTF-16 and wchars
323
0
            const char *sz = indicesNode.text().get();
324
0
            const char *end = sz + std::strlen(sz);
325
326
            // For each index loop over aiMesh faces
327
0
            while (SkipSpacesAndLineEnd(&sz, end)) {
328
0
                if (curFace >= faceEnd) {
329
0
                    ASSIMP_LOG_ERROR("IRRMESH: Too many indices");
330
0
                    break;
331
0
                }
332
                // if new face
333
0
                if (!curIdx) {
334
0
                    curFace->mNumIndices = 3;
335
0
                    curFace->mIndices = new unsigned int[3];
336
0
                }
337
338
                // Read index base 10
339
                // function advances the pointer
340
0
                unsigned int idx = strtoul10(sz, &sz);
341
0
                if (idx >= curVertices.size()) {
342
0
                    ASSIMP_LOG_ERROR("IRRMESH: Index out of range");
343
0
                    idx = 0;
344
0
                }
345
346
                // make up our own indices?
347
0
                curFace->mIndices[curIdx] = total++;
348
349
                // Copy over data to aiMesh
350
0
                *pcV++ = curVertices[idx];
351
0
                if (pcN)
352
0
                    *pcN++ = curNormals[idx];
353
0
                if (pcT)
354
0
                    *pcT++ = curTangents[idx];
355
0
                if (pcB)
356
0
                    *pcB++ = curBitangents[idx];
357
0
                if (pcC0)
358
0
                    *pcC0++ = curColors[idx];
359
0
                if (pcT0)
360
0
                    *pcT0++ = curUVs[idx];
361
0
                if (pcT1)
362
0
                    *pcT1++ = curUV2s[idx];
363
364
                // start new face
365
0
                if (++curIdx == 3) {
366
0
                    ++curFace;
367
0
                    curIdx = 0;
368
0
                }
369
0
            }
370
            // We should be at the end of mFaces
371
0
            if (curFace != faceEnd) {
372
0
                ASSIMP_LOG_ERROR("IRRMESH: Not enough indices");
373
0
            }
374
0
        }
375
376
        // Finish processing the mesh - do some small material workarounds
377
0
        if (curMatFlags & AI_IRRMESH_MAT_trans_vertex_alpha && !useColors) {
378
            // Take the opacity value of the current material
379
            // from the common vertex color alpha
380
0
            aiMaterial *mat = (aiMaterial *)curMat;
381
0
            mat->AddProperty(&curColors[0].a, 1, AI_MATKEY_OPACITY);
382
0
        }
383
384
        // end of previous buffer. A material and a mesh should be there
385
0
        if (!curMat || !curMesh) {
386
0
            ASSIMP_LOG_ERROR("IRRMESH: A buffer must contain a mesh and a material");
387
0
            releaseMaterial(&curMat);
388
0
            releaseMesh(&curMesh);
389
0
        } else {
390
0
            materials.push_back(curMat);
391
0
            meshes.push_back(curMesh);
392
0
        }
393
0
    }
394
395
    // If one is empty then so is the other
396
0
    if (materials.empty() || meshes.empty()) {
397
0
        throw DeadlyImportError("IRRMESH: Unable to read a mesh from this file");
398
0
    }
399
400
    // now generate the output scene
401
0
    pScene->mNumMeshes = (unsigned int)meshes.size();
402
0
    pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
403
0
    for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
404
0
        pScene->mMeshes[i] = meshes[i];
405
406
        // clean this value ...
407
0
        pScene->mMeshes[i]->mNumUVComponents[3] = 0;
408
0
    }
409
410
0
    pScene->mNumMaterials = (unsigned int)materials.size();
411
0
    pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
412
0
    ::memcpy(pScene->mMaterials, &materials[0], sizeof(void *) * pScene->mNumMaterials);
413
414
0
    pScene->mRootNode = new aiNode();
415
0
    pScene->mRootNode->mName.Set("<IRRMesh>");
416
0
    pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
417
0
    pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
418
419
0
    for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
420
0
        pScene->mRootNode->mMeshes[i] = i;
421
0
    };
422
0
}
423
424
void IRRMeshImporter::ParseBufferVertices(const char *sz, const char *end, VertexFormat vertexFormat,
425
        std::vector<aiVector3D> &vertices, std::vector<aiVector3D> &normals,
426
        std::vector<aiVector3D> &tangents, std::vector<aiVector3D> &bitangents,
427
        std::vector<aiVector3D> &UVs, std::vector<aiVector3D> &UV2s,
428
0
        std::vector<aiColor4D> &colors, bool &useColors) {
429
    // read vertices
430
0
    do {
431
0
        SkipSpacesAndLineEnd(&sz, end);
432
0
        aiVector3D temp;
433
0
        aiColor4D c;
434
435
        // Read the vertex position
436
0
        sz = fast_atoreal_move(sz, temp.x);
437
0
        SkipSpaces(&sz, end);
438
439
0
        sz = fast_atoreal_move(sz, temp.y);
440
0
        SkipSpaces(&sz, end);
441
442
0
        sz = fast_atoreal_move(sz, temp.z);
443
0
        SkipSpaces(&sz, end);
444
0
        vertices.push_back(temp);
445
446
        // Read the vertex normals
447
0
        sz = fast_atoreal_move(sz, temp.x);
448
0
        SkipSpaces(&sz, end);
449
450
0
        sz = fast_atoreal_move(sz, temp.y);
451
0
        SkipSpaces(&sz, end);
452
453
0
        sz = fast_atoreal_move(sz, temp.z);
454
0
        SkipSpaces(&sz, end);
455
0
        normals.push_back(temp);
456
457
        // read the vertex colors
458
0
        uint32_t clr = strtoul16(sz, &sz);
459
0
        ColorFromARGBPacked(clr, c);
460
461
        // If we're pushing more than one distinct color
462
0
        if (!colors.empty() && c != *(colors.end() - 1))
463
0
            useColors = true;
464
465
0
        colors.push_back(c);
466
0
        SkipSpaces(&sz, end);
467
468
        // read the first UV coordinate set
469
0
        sz = fast_atoreal_move(sz, temp.x);
470
0
        SkipSpaces(&sz, end);
471
472
0
        sz = fast_atoreal_move(sz, temp.y);
473
0
        SkipSpaces(&sz, end);
474
0
        temp.z = 0.f;
475
0
        temp.y = 1.f - temp.y; // DX to OGL
476
0
        UVs.push_back(temp);
477
478
        // NOTE these correspond to specific S3DVertex* structs in irr sourcecode
479
        // So by definition, all buffers have either UV2 or tangents or neither
480
        // read the (optional) second UV coordinate set
481
0
        if (vertexFormat == VertexFormat::t2coord) {
482
0
            sz = fast_atoreal_move(sz, temp.x);
483
0
            SkipSpaces(&sz, end);
484
485
0
            sz = fast_atoreal_move(sz, temp.y);
486
0
            temp.y = 1.f - temp.y; // DX to OGL
487
0
            UV2s.push_back(temp);
488
0
        }
489
        // read optional tangent and bitangent vectors
490
0
        else if (vertexFormat == VertexFormat::tangent) {
491
            // tangents
492
0
            sz = fast_atoreal_move(sz, temp.x);
493
0
            SkipSpaces(&sz, end);
494
495
0
            sz = fast_atoreal_move(sz, temp.z);
496
0
            SkipSpaces(&sz, end);
497
498
0
            sz = fast_atoreal_move(sz, temp.y);
499
0
            SkipSpaces(&sz, end);
500
0
            temp.y *= -1.0f;
501
0
            tangents.push_back(temp);
502
503
            // bitangents
504
0
            sz = fast_atoreal_move(sz, temp.x);
505
0
            SkipSpaces(&sz, end);
506
507
0
            sz = fast_atoreal_move(sz, temp.z);
508
0
            SkipSpaces(&sz, end);
509
510
0
            sz = fast_atoreal_move(sz, temp.y);
511
0
            SkipSpaces(&sz, end);
512
0
            temp.y *= -1.0f;
513
0
            bitangents.push_back(temp);
514
0
        }
515
0
    } while (SkipLine(&sz, end));
516
    // IMPORTANT: We assume that each vertex is specified in one
517
    // line. So we can skip the rest of the line - unknown vertex
518
    // elements are ignored.
519
0
}
520
521
#endif // !! ASSIMP_BUILD_NO_IRRMESH_IMPORTER