Coverage Report

Created: 2025-11-11 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/ASE/ASELoader.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  ASELoader.cpp
43
 *  @brief Implementation of the ASE importer class
44
 */
45
46
#ifndef ASSIMP_BUILD_NO_ASE_IMPORTER
47
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
48
49
// internal headers
50
#include "ASELoader.h"
51
#include "Common/TargetAnimation.h"
52
#include <assimp/SkeletonMeshBuilder.h>
53
#include <assimp/StringComparison.h>
54
55
#include <assimp/importerdesc.h>
56
#include <assimp/scene.h>
57
#include <assimp/DefaultLogger.hpp>
58
#include <assimp/IOSystem.hpp>
59
#include <assimp/Importer.hpp>
60
61
#include <memory>
62
63
// utilities
64
#include <assimp/fast_atof.h>
65
66
namespace Assimp {
67
using namespace Assimp::ASE;
68
69
static constexpr aiImporterDesc desc = {
70
    "ASE Importer",
71
    "",
72
    "",
73
    "Similar to 3DS but text-encoded",
74
    aiImporterFlags_SupportTextFlavour,
75
    0,
76
    0,
77
    0,
78
    0,
79
    "ase ask"
80
};
81
82
// ------------------------------------------------------------------------------------------------
83
// Constructor to be privately used by Importer
84
ASEImporter::ASEImporter() :
85
891
        mParser(), mBuffer(), pcScene(), configRecomputeNormals(), noSkeletonMesh() {
86
    // empty
87
891
}
88
89
// ------------------------------------------------------------------------------------------------
90
// Returns whether the class can handle the format of the given file.
91
593
bool ASEImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
92
593
    static const char *tokens[] = { "*3dsmax_asciiexport" };
93
593
    return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
94
593
}
95
96
// ------------------------------------------------------------------------------------------------
97
// Loader meta information
98
926
const aiImporterDesc *ASEImporter::GetInfo() const {
99
926
    return &desc;
100
926
}
101
102
// ------------------------------------------------------------------------------------------------
103
// Setup configuration options
104
49
void ASEImporter::SetupProperties(const Importer *pImp) {
105
49
    configRecomputeNormals = (pImp->GetPropertyInteger(
106
49
                                      AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS, 1) ?
107
49
                                      true :
108
49
                                      false);
109
110
49
    noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
111
49
}
112
113
// ------------------------------------------------------------------------------------------------
114
// Imports the given file into the given scene structure.
115
void ASEImporter::InternReadFile(const std::string &pFile,
116
49
        aiScene *pScene, IOSystem *pIOHandler) {
117
49
    std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
118
119
    // Check whether we can read from the file
120
49
    if (file == nullptr) {
121
0
        throw DeadlyImportError("Failed to open ASE file ", pFile, ".");
122
0
    }
123
124
    // Allocate storage and copy the contents of the file to a memory buffer
125
49
    std::vector<char> mBuffer2;
126
49
    TextFileToBuffer(file.get(), mBuffer2);
127
49
    const size_t fileSize = mBuffer2.size();
128
49
    this->mBuffer = &mBuffer2[0];
129
49
    this->pcScene = pScene;
130
131
    // ------------------------------------------------------------------
132
    // Guess the file format by looking at the extension
133
    // ASC is considered to be the older format 110,
134
    // ASE is the actual version 200 (that is currently written by max)
135
    // ------------------------------------------------------------------
136
49
    unsigned int defaultFormat;
137
49
    std::string::size_type s = pFile.length() - 1;
138
49
    switch (pFile.c_str()[s]) {
139
140
0
    case 'C':
141
0
    case 'c':
142
0
        defaultFormat = AI_ASE_OLD_FILE_FORMAT;
143
0
        break;
144
49
    default:
145
49
        defaultFormat = AI_ASE_NEW_FILE_FORMAT;
146
49
    };
147
148
    // Construct an ASE parser and parse the file
149
49
    ASE::Parser parser(mBuffer, fileSize, defaultFormat);
150
49
    mParser = &parser;
151
49
    mParser->Parse();
152
153
    //------------------------------------------------------------------
154
    // Check whether we god at least one mesh. If we did - generate
155
    // materials and copy meshes.
156
    // ------------------------------------------------------------------
157
49
    if (!mParser->m_vMeshes.empty()) {
158
159
        // If absolutely no material has been loaded from the file
160
        // we need to generate a default material
161
6
        GenerateDefaultMaterial();
162
163
        // process all meshes
164
6
        bool tookNormals = false;
165
6
        std::vector<aiMesh *> avOutMeshes;
166
6
        avOutMeshes.reserve(mParser->m_vMeshes.size() * 2);
167
12
        for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
168
6
            if ((*i).bSkip) {
169
0
                continue;
170
0
            }
171
6
            BuildUniqueRepresentation(*i);
172
173
            // Need to generate proper vertex normals if necessary
174
6
            if (GenerateNormals(*i)) {
175
0
                tookNormals = true;
176
0
            }
177
178
            // Convert all meshes to aiMesh objects
179
6
            ConvertMeshes(*i, avOutMeshes);
180
6
        }
181
6
        if (tookNormals) {
182
0
            ASSIMP_LOG_DEBUG("ASE: Taking normals from the file. Use "
183
0
                             "the AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS setting if you "
184
0
                             "experience problems");
185
0
        }
186
187
        // Now build the output mesh list. Remove dummies
188
6
        pScene->mNumMeshes = (unsigned int)avOutMeshes.size();
189
6
        aiMesh **pp = pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
190
12
        for (std::vector<aiMesh *>::const_iterator i = avOutMeshes.begin(); i != avOutMeshes.end(); ++i) {
191
6
            if (!(*i)->mNumFaces) {
192
6
                continue;
193
6
            }
194
0
            *pp++ = *i;
195
0
        }
196
6
        pScene->mNumMeshes = (unsigned int)(pp - pScene->mMeshes);
197
198
        // Build final material indices (remove submaterials and setup
199
        // the final list)
200
6
        BuildMaterialIndices();
201
6
    }
202
203
    // ------------------------------------------------------------------
204
    // Copy all scene graph nodes - lights, cameras, dummies and meshes
205
    // into one huge list.
206
    //------------------------------------------------------------------
207
49
    std::vector<BaseNode *> nodes;
208
49
    nodes.reserve(mParser->m_vMeshes.size() + mParser->m_vLights.size() + mParser->m_vCameras.size() + mParser->m_vDummies.size());
209
210
    // Lights
211
49
    for (auto &light : mParser->m_vLights)
212
0
        nodes.push_back(&light);
213
    // Cameras
214
49
    for (auto &camera : mParser->m_vCameras)
215
44
        nodes.push_back(&camera);
216
    // Meshes
217
49
    for (auto &mesh : mParser->m_vMeshes)
218
6
        nodes.push_back(&mesh);
219
    // Dummies
220
49
    for (auto &dummy : mParser->m_vDummies)
221
0
        nodes.push_back(&dummy);
222
223
    // build the final node graph
224
49
    BuildNodes(nodes);
225
226
    // build output animations
227
49
    BuildAnimations(nodes);
228
229
    // build output cameras
230
49
    BuildCameras();
231
232
    // build output lights
233
49
    BuildLights();
234
235
    // ------------------------------------------------------------------
236
    // If we have no meshes use the SkeletonMeshBuilder helper class
237
    // to build a mesh for the animation skeleton
238
    // FIXME: very strange results
239
    // ------------------------------------------------------------------
240
49
    if (!pScene->mNumMeshes) {
241
8
        pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
242
8
        if (!noSkeletonMesh) {
243
8
            SkeletonMeshBuilder skeleton(pScene);
244
8
        }
245
8
    }
246
49
}
247
// ------------------------------------------------------------------------------------------------
248
6
void ASEImporter::GenerateDefaultMaterial() {
249
6
    ai_assert(nullptr != mParser);
250
251
6
    bool bHas = false;
252
12
    for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
253
6
        if ((*i).bSkip) continue;
254
6
        if (ASE::Face::DEFAULT_MATINDEX == (*i).iMaterialIndex) {
255
6
            (*i).iMaterialIndex = (unsigned int)mParser->m_vMaterials.size();
256
6
            bHas = true;
257
6
        }
258
6
    }
259
6
    if (bHas || mParser->m_vMaterials.empty()) {
260
        // add a simple material without submaterials to the parser's list
261
6
        mParser->m_vMaterials.emplace_back(AI_DEFAULT_MATERIAL_NAME);
262
6
        ASE::Material &mat = mParser->m_vMaterials.back();
263
264
6
        mat.mDiffuse = aiColor3D(0.6f, 0.6f, 0.6f);
265
6
        mat.mSpecular = aiColor3D(1.0f, 1.0f, 1.0f);
266
6
        mat.mAmbient = aiColor3D(0.05f, 0.05f, 0.05f);
267
6
        mat.mShading = Discreet3DS::Gouraud;
268
6
    }
269
6
}
270
271
// ------------------------------------------------------------------------------------------------
272
8
void ASEImporter::BuildAnimations(const std::vector<BaseNode *> &nodes) {
273
    // check whether we have at least one mesh which has animations
274
8
    std::vector<ASE::BaseNode *>::const_iterator i = nodes.begin();
275
8
    unsigned int iNum = 0;
276
58
    for (; i != nodes.end(); ++i) {
277
278
        // TODO: Implement Bezier & TCB support
279
50
        if ((*i)->mAnim.mPositionType != ASE::Animation::TRACK) {
280
0
            ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
281
0
                            "This is not supported.");
282
0
        }
283
50
        if ((*i)->mAnim.mRotationType != ASE::Animation::TRACK) {
284
0
            ASSIMP_LOG_WARN("ASE: Rotation controller uses Bezier/TCB keys. "
285
0
                            "This is not supported.");
286
0
        }
287
50
        if ((*i)->mAnim.mScalingType != ASE::Animation::TRACK) {
288
0
            ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
289
0
                            "This is not supported.");
290
0
        }
291
292
        // We compare against 1 here - firstly one key is not
293
        // really an animation and secondly MAX writes dummies
294
        // that represent the node transformation.
295
50
        if ((*i)->mAnim.akeyPositions.size() > 1 || (*i)->mAnim.akeyRotations.size() > 1 || (*i)->mAnim.akeyScaling.size() > 1) {
296
0
            ++iNum;
297
0
        }
298
50
        if ((*i)->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan((*i)->mTargetPosition.x)) {
299
0
            ++iNum;
300
0
        }
301
50
    }
302
8
    if (iNum) {
303
        // Generate a new animation channel and setup everything for it
304
0
        pcScene->mNumAnimations = 1;
305
0
        pcScene->mAnimations = new aiAnimation *[1];
306
0
        aiAnimation *pcAnim = pcScene->mAnimations[0] = new aiAnimation();
307
0
        pcAnim->mNumChannels = iNum;
308
0
        pcAnim->mChannels = new aiNodeAnim *[iNum];
309
0
        pcAnim->mTicksPerSecond = mParser->iFrameSpeed * mParser->iTicksPerFrame;
310
311
0
        iNum = 0;
312
313
        // Now iterate through all meshes and collect all data we can find
314
0
        for (i = nodes.begin(); i != nodes.end(); ++i) {
315
316
0
            ASE::BaseNode *me = *i;
317
0
            if (me->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan(me->mTargetPosition.x)) {
318
                // Generate an extra channel for the camera/light target.
319
                // BuildNodes() does also generate an extra node, named
320
                // <baseName>.Target.
321
0
                aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
322
0
                nd->mNodeName.Set(me->mName + ".Target");
323
324
                // Allocate the key array and fill it
325
0
                nd->mNumPositionKeys = (unsigned int)me->mTargetAnim.akeyPositions.size();
326
0
                nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
327
328
0
                ::memcpy(nd->mPositionKeys, &me->mTargetAnim.akeyPositions[0],
329
0
                        nd->mNumPositionKeys * sizeof(aiVectorKey));
330
0
            }
331
332
0
            if (me->mAnim.akeyPositions.size() > 1 || me->mAnim.akeyRotations.size() > 1 || me->mAnim.akeyScaling.size() > 1) {
333
                // Begin a new node animation channel for this node
334
0
                aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
335
0
                nd->mNodeName.Set(me->mName);
336
337
                // copy position keys
338
0
                if (me->mAnim.akeyPositions.size() > 1) {
339
                    // Allocate the key array and fill it
340
0
                    nd->mNumPositionKeys = (unsigned int)me->mAnim.akeyPositions.size();
341
0
                    nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
342
343
0
                    ::memcpy(nd->mPositionKeys, &me->mAnim.akeyPositions[0],
344
0
                            nd->mNumPositionKeys * sizeof(aiVectorKey));
345
0
                }
346
                // copy rotation keys
347
0
                if (me->mAnim.akeyRotations.size() > 1) {
348
                    // Allocate the key array and fill it
349
0
                    nd->mNumRotationKeys = (unsigned int)me->mAnim.akeyRotations.size();
350
0
                    nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
351
352
                    // --------------------------------------------------------------------
353
                    // Rotation keys are offsets to the previous keys.
354
                    // We have the quaternion representations of all
355
                    // of them, so we just need to concatenate all
356
                    // (unit-length) quaternions to get the absolute
357
                    // rotations.
358
                    // Rotation keys are ABSOLUTE for older files
359
                    // --------------------------------------------------------------------
360
361
0
                    aiQuaternion cur;
362
0
                    for (unsigned int a = 0; a < nd->mNumRotationKeys; ++a) {
363
0
                        aiQuatKey q = me->mAnim.akeyRotations[a];
364
365
0
                        if (mParser->iFileFormat > 110) {
366
0
                            cur = (a ? cur * q.mValue : q.mValue);
367
0
                            q.mValue = cur.Normalize();
368
0
                        }
369
0
                        nd->mRotationKeys[a] = q;
370
371
                        // need this to get to Assimp quaternion conventions
372
0
                        nd->mRotationKeys[a].mValue.w *= -1.f;
373
0
                    }
374
0
                }
375
                // copy scaling keys
376
0
                if (me->mAnim.akeyScaling.size() > 1) {
377
                    // Allocate the key array and fill it
378
0
                    nd->mNumScalingKeys = (unsigned int)me->mAnim.akeyScaling.size();
379
0
                    nd->mScalingKeys = new aiVectorKey[nd->mNumScalingKeys];
380
381
0
                    ::memcpy(nd->mScalingKeys, &me->mAnim.akeyScaling[0],
382
0
                            nd->mNumScalingKeys * sizeof(aiVectorKey));
383
0
                }
384
0
            }
385
0
        }
386
0
    }
387
8
}
388
389
// ------------------------------------------------------------------------------------------------
390
// Build output cameras
391
8
void ASEImporter::BuildCameras() {
392
8
    if (!mParser->m_vCameras.empty()) {
393
2
        pcScene->mNumCameras = (unsigned int)mParser->m_vCameras.size();
394
2
        pcScene->mCameras = new aiCamera *[pcScene->mNumCameras];
395
396
46
        for (unsigned int i = 0; i < pcScene->mNumCameras; ++i) {
397
44
            aiCamera *out = pcScene->mCameras[i] = new aiCamera();
398
44
            ASE::Camera &in = mParser->m_vCameras[i];
399
400
            // copy members
401
44
            out->mClipPlaneFar = in.mFar;
402
44
            out->mClipPlaneNear = (in.mNear ? in.mNear : 0.1f);
403
44
            out->mHorizontalFOV = in.mFOV;
404
405
44
            out->mName.Set(in.mName);
406
44
        }
407
2
    }
408
8
}
409
410
// ------------------------------------------------------------------------------------------------
411
// Build output lights
412
8
void ASEImporter::BuildLights() {
413
8
    if (!mParser->m_vLights.empty()) {
414
0
        pcScene->mNumLights = (unsigned int)mParser->m_vLights.size();
415
0
        pcScene->mLights = new aiLight *[pcScene->mNumLights];
416
417
0
        for (unsigned int i = 0; i < pcScene->mNumLights; ++i) {
418
0
            aiLight *out = pcScene->mLights[i] = new aiLight();
419
0
            ASE::Light &in = mParser->m_vLights[i];
420
421
            // The direction is encoded in the transformation matrix of the node.
422
            // In 3DS MAX the light source points into negative Z direction if
423
            // the node transformation is the identity.
424
0
            out->mDirection = aiVector3D(0.f, 0.f, -1.f);
425
426
0
            out->mName.Set(in.mName);
427
0
            switch (in.mLightType) {
428
0
            case ASE::Light::TARGET:
429
0
                out->mType = aiLightSource_SPOT;
430
0
                out->mAngleInnerCone = AI_DEG_TO_RAD(in.mAngle);
431
0
                out->mAngleOuterCone = (in.mFalloff ? AI_DEG_TO_RAD(in.mFalloff) : out->mAngleInnerCone);
432
0
                break;
433
434
0
            case ASE::Light::DIRECTIONAL:
435
0
                out->mType = aiLightSource_DIRECTIONAL;
436
0
                break;
437
438
0
            default:
439
                //case ASE::Light::OMNI:
440
0
                out->mType = aiLightSource_POINT;
441
0
                break;
442
0
            };
443
0
            out->mColorDiffuse = out->mColorSpecular = in.mColor * in.mIntensity;
444
0
        }
445
0
    }
446
8
}
447
448
// ------------------------------------------------------------------------------------------------
449
51
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes, aiNode *pcParent, const std::string &name) {
450
51
    aiMatrix4x4 m;
451
51
    AddNodes(nodes, pcParent, name, m);
452
51
}
453
454
// ------------------------------------------------------------------------------------------------
455
// Add meshes to a given node
456
49
void ASEImporter::AddMeshes(const ASE::BaseNode *snode, aiNode *node) {
457
49
    for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i) {
458
        // Get the name of the mesh (the mesh instance has been temporarily stored in the third vertex color)
459
0
        const aiMesh *pcMesh = pcScene->mMeshes[i];
460
0
        const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
461
462
0
        if (mesh == snode) {
463
0
            ++node->mNumMeshes;
464
0
        }
465
0
    }
466
467
49
    if (node->mNumMeshes) {
468
0
        node->mMeshes = new unsigned int[node->mNumMeshes];
469
0
        for (unsigned int i = 0, p = 0; i < pcScene->mNumMeshes; ++i) {
470
471
0
            const aiMesh *pcMesh = pcScene->mMeshes[i];
472
0
            const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
473
0
            if (mesh == snode) {
474
0
                node->mMeshes[p++] = i;
475
476
                // Transform all vertices of the mesh back into their local space ->
477
                // at the moment they are pretransformed
478
0
                aiMatrix4x4 m = mesh->mTransform;
479
0
                m.Inverse();
480
481
0
                aiVector3D *pvCurPtr = pcMesh->mVertices;
482
0
                const aiVector3D *pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
483
0
                while (pvCurPtr != pvEndPtr) {
484
0
                    *pvCurPtr = m * (*pvCurPtr);
485
0
                    pvCurPtr++;
486
0
                }
487
488
                // Do the same for the normal vectors, if we have them.
489
                // As always, inverse transpose.
490
0
                if (pcMesh->mNormals) {
491
0
                    aiMatrix3x3 m3 = aiMatrix3x3(mesh->mTransform);
492
0
                    m3.Transpose();
493
494
0
                    pvCurPtr = pcMesh->mNormals;
495
0
                    pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
496
0
                    while (pvCurPtr != pvEndPtr) {
497
0
                        *pvCurPtr = m3 * (*pvCurPtr);
498
0
                        pvCurPtr++;
499
0
                    }
500
0
                }
501
0
            }
502
0
        }
503
0
    }
504
49
}
505
506
// ------------------------------------------------------------------------------------------------
507
// Add child nodes to a given parent node
508
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes, aiNode *pcParent, const std::string &name,
509
58
        const aiMatrix4x4 &mat) {
510
58
    const size_t len = name.size();
511
58
    ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
512
513
    // Receives child nodes for the pcParent node
514
58
    std::vector<aiNode *> apcNodes;
515
516
    // Now iterate through all nodes in the scene and search for one
517
    // which has *us* as parent.
518
1.96k
    for (std::vector<BaseNode *>::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
519
1.90k
        const BaseNode *snode = *it;
520
1.90k
        if (!name.empty()) {
521
1.85k
            if (len != snode->mParent.length() || name != snode->mParent.c_str()) {
522
1.85k
                continue;
523
1.85k
            }
524
1.85k
        } else if (snode->mParent.length()) {
525
43
            continue;
526
43
        }
527
528
7
        (*it)->mProcessed = true;
529
530
        // Allocate a new node and add it to the output data structure
531
7
        apcNodes.push_back(new aiNode);
532
7
        aiNode *node = apcNodes.back();
533
534
7
        node->mName.Set((snode->mName.length() ? snode->mName.c_str() : "Unnamed_Node"));
535
7
        node->mParent = pcParent;
536
537
        // Setup the transformation matrix of the node
538
7
        aiMatrix4x4 mParentAdjust = mat;
539
7
        mParentAdjust.Inverse();
540
7
        node->mTransformation = mParentAdjust * snode->mTransform;
541
542
        // Add sub nodes - prevent stack overflow due to recursive parenting
543
7
        if (node->mName != node->mParent->mName && node->mName != node->mParent->mParent->mName) {
544
7
            AddNodes(nodes, node, node->mName.C_Str(), snode->mTransform);
545
7
        }
546
547
        // Further processing depends on the type of the node
548
7
        if (snode->mType == ASE::BaseNode::Mesh) {
549
            // If the type of this node is "Mesh" we need to search
550
            // the list of output meshes in the data structure for
551
            // all those that belonged to this node once. This is
552
            // slightly inconvinient here and a better solution should
553
            // be used when this code is refactored next.
554
6
            AddMeshes(snode, node);
555
6
        } else if (is_not_qnan(snode->mTargetPosition.x)) {
556
            // If this is a target camera or light we generate a small
557
            // child node which marks the position of the camera
558
            // target (the direction information is contained in *this*
559
            // node's animation track but the exact target position
560
            // would be lost otherwise)
561
0
            if (!node->mNumChildren) {
562
0
                node->mChildren = new aiNode *[1];
563
0
            }
564
565
0
            aiNode *nd = new aiNode();
566
567
0
            nd->mName.Set(snode->mName + ".Target");
568
569
0
            nd->mTransformation.a4 = snode->mTargetPosition.x - snode->mTransform.a4;
570
0
            nd->mTransformation.b4 = snode->mTargetPosition.y - snode->mTransform.b4;
571
0
            nd->mTransformation.c4 = snode->mTargetPosition.z - snode->mTransform.c4;
572
573
0
            nd->mParent = node;
574
575
            // The .Target node is always the first child node
576
0
            for (unsigned int m = 0; m < node->mNumChildren; ++m)
577
0
                node->mChildren[m + 1] = node->mChildren[m];
578
579
0
            node->mChildren[0] = nd;
580
0
            node->mNumChildren++;
581
582
            // What we did is so great, it is at least worth a debug message
583
0
            ASSIMP_LOG_VERBOSE_DEBUG("ASE: Generating separate target node (", snode->mName, ")");
584
0
        }
585
7
    }
586
587
    // Allocate enough space for the child nodes
588
    // We allocate one slot more  in case this is a target camera/light
589
58
    pcParent->mNumChildren = (unsigned int)apcNodes.size();
590
58
    if (pcParent->mNumChildren) {
591
7
        pcParent->mChildren = new aiNode *[apcNodes.size() + 1 /* PLUS ONE !!! */];
592
593
        // now build all nodes for our nice new children
594
14
        for (unsigned int p = 0; p < apcNodes.size(); ++p)
595
7
            pcParent->mChildren[p] = apcNodes[p];
596
7
    }
597
58
    return;
598
58
}
599
600
// ------------------------------------------------------------------------------------------------
601
// Build the output node graph
602
8
void ASEImporter::BuildNodes(std::vector<BaseNode *> &nodes) {
603
8
    ai_assert(nullptr != pcScene);
604
605
    // allocate the one and only root node
606
8
    aiNode *root = pcScene->mRootNode = new aiNode();
607
8
    root->mName.Set("<ASERoot>");
608
609
    // Setup the coordinate system transformation
610
8
    pcScene->mRootNode->mNumChildren = 1;
611
8
    pcScene->mRootNode->mChildren = new aiNode *[1];
612
8
    aiNode *ch = pcScene->mRootNode->mChildren[0] = new aiNode();
613
8
    ch->mParent = root;
614
615
    // Change the transformation matrix of all nodes
616
50
    for (BaseNode *node : nodes) {
617
50
        aiMatrix4x4 &m = node->mTransform;
618
50
        m.Transpose(); // row-order vs column-order
619
50
    }
620
621
    // add all nodes
622
8
    static const std::string none = "";
623
8
    AddNodes(nodes, ch, none);
624
625
    // now iterate through al nodes and find those that have not yet
626
    // been added to the nodegraph (= their parent could not be recognized)
627
8
    std::vector<const BaseNode *> aiList;
628
58
    for (std::vector<BaseNode *>::iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
629
50
        if ((*it)->mProcessed) {
630
7
            continue;
631
7
        }
632
633
        // check whether our parent is known
634
43
        bool bKnowParent = false;
635
636
        // search the list another time, starting *here* and try to find out whether
637
        // there is a node that references *us* as a parent
638
1.89k
        for (std::vector<BaseNode *>::const_iterator it2 = nodes.begin(); it2 != end; ++it2) {
639
1.84k
            if (it2 == it) {
640
43
                continue;
641
43
            }
642
643
1.80k
            if ((*it2)->mName == (*it)->mParent) {
644
0
                bKnowParent = true;
645
0
                break;
646
0
            }
647
1.80k
        }
648
43
        if (!bKnowParent) {
649
43
            aiList.push_back(*it);
650
43
        }
651
43
    }
652
653
    // Are there any orphaned nodes?
654
8
    if (!aiList.empty()) {
655
1
        std::vector<aiNode *> apcNodes;
656
1
        apcNodes.reserve(aiList.size() + pcScene->mRootNode->mNumChildren);
657
658
2
        for (unsigned int i = 0; i < pcScene->mRootNode->mNumChildren; ++i)
659
1
            apcNodes.push_back(pcScene->mRootNode->mChildren[i]);
660
661
1
        delete[] pcScene->mRootNode->mChildren;
662
44
        for (std::vector<const BaseNode *>::/*const_*/ iterator i = aiList.begin(); i != aiList.end(); ++i) {
663
43
            const ASE::BaseNode *src = *i;
664
665
            // The parent is not known, so we can assume that we must add
666
            // this node to the root node of the whole scene
667
43
            aiNode *pcNode = new aiNode();
668
43
            pcNode->mParent = pcScene->mRootNode;
669
43
            pcNode->mName.Set(src->mName);
670
43
            AddMeshes(src, pcNode);
671
43
            AddNodes(nodes, pcNode, pcNode->mName.data);
672
43
            apcNodes.push_back(pcNode);
673
43
        }
674
675
        // Regenerate our output array
676
1
        pcScene->mRootNode->mChildren = new aiNode *[apcNodes.size()];
677
45
        for (unsigned int i = 0; i < apcNodes.size(); ++i)
678
44
            pcScene->mRootNode->mChildren[i] = apcNodes[i];
679
680
1
        pcScene->mRootNode->mNumChildren = (unsigned int)apcNodes.size();
681
1
    }
682
683
    // Reset the third color set to nullptr - we used this field to store a temporary pointer
684
8
    for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i)
685
0
        pcScene->mMeshes[i]->mColors[2] = nullptr;
686
687
    // The root node should not have at least one child or the file is valid
688
8
    if (!pcScene->mRootNode->mNumChildren) {
689
0
        throw DeadlyImportError("ASE: No nodes loaded. The file is either empty or corrupt");
690
0
    }
691
692
    // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
693
8
    pcScene->mRootNode->mTransformation = aiMatrix4x4(1.f, 0.f, 0.f, 0.f,
694
8
            0.f, 0.f, 1.f, 0.f, 0.f, -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
695
8
}
696
697
// ------------------------------------------------------------------------------------------------
698
// Convert the imported data to the internal verbose representation
699
6
void ASEImporter::BuildUniqueRepresentation(ASE::Mesh &mesh) {
700
    // allocate output storage
701
6
    std::vector<aiVector3D> mPositions;
702
6
    std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
703
6
    std::vector<aiColor4D> mVertexColors;
704
6
    std::vector<aiVector3D> mNormals;
705
6
    std::vector<BoneVertex> mBoneVertices;
706
707
6
    unsigned int iSize = (unsigned int)mesh.mFaces.size() * 3;
708
6
    mPositions.resize(iSize);
709
710
    // optional texture coordinates
711
54
    for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
712
48
        if (!mesh.amTexCoords[i].empty()) {
713
0
            amTexCoords[i].resize(iSize);
714
0
        }
715
48
    }
716
    // optional vertex colors
717
6
    if (!mesh.mVertexColors.empty()) {
718
0
        mVertexColors.resize(iSize);
719
0
    }
720
721
    // optional vertex normals (vertex normals can simply be copied)
722
6
    if (!mesh.mNormals.empty()) {
723
0
        mNormals.resize(iSize);
724
0
    }
725
    // bone vertices. There is no need to change the bone list
726
6
    if (!mesh.mBoneVertices.empty()) {
727
2
        mBoneVertices.resize(iSize);
728
2
    }
729
730
    // iterate through all faces in the mesh
731
6
    unsigned int iCurrent = 0, fi = 0;
732
6
    for (std::vector<ASE::Face>::iterator i = mesh.mFaces.begin(); i != mesh.mFaces.end(); ++i, ++fi) {
733
0
        for (unsigned int n = 0; n < 3; ++n, ++iCurrent) {
734
0
            const uint32_t curIndex = (*i).mIndices[n];
735
0
            if (curIndex >= mesh.mPositions.size()) {
736
0
                throw DeadlyImportError("ASE: Invalid vertex index in face ", fi, ".");
737
0
            }
738
0
            mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
739
740
            // add texture coordinates
741
0
            for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
742
0
                if (mesh.amTexCoords[c].empty()) break;
743
0
                amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
744
0
            }
745
            // add vertex colors
746
0
            if (!mesh.mVertexColors.empty()) {
747
0
                mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
748
0
            }
749
            // add normal vectors
750
0
            if (!mesh.mNormals.empty()) {
751
0
                mNormals[iCurrent] = mesh.mNormals[fi * 3 + n];
752
0
                mNormals[iCurrent].Normalize();
753
0
            }
754
755
            // handle bone vertices
756
0
            if ((*i).mIndices[n] < mesh.mBoneVertices.size()) {
757
                // (sometimes this will cause bone verts to be duplicated
758
                //  however, I' quite sure Schrompf' JoinVerticesStep
759
                //  will fix that again ...)
760
0
                mBoneVertices[iCurrent] = mesh.mBoneVertices[(*i).mIndices[n]];
761
0
            }
762
0
            (*i).mIndices[n] = iCurrent;
763
0
        }
764
0
    }
765
766
    // replace the old arrays
767
6
    mesh.mNormals = mNormals;
768
6
    mesh.mPositions = mPositions;
769
6
    mesh.mVertexColors = mVertexColors;
770
771
54
    for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c)
772
48
        mesh.amTexCoords[c] = amTexCoords[c];
773
6
}
774
775
// ------------------------------------------------------------------------------------------------
776
// Copy a texture from the ASE structs to the output material
777
0
void CopyASETexture(aiMaterial &mat, ASE::Texture &texture, aiTextureType type) {
778
    // Setup the texture name
779
0
    aiString tex;
780
0
    tex.Set(texture.mMapName);
781
0
    mat.AddProperty(&tex, AI_MATKEY_TEXTURE(type, 0));
782
783
    // Setup the texture blend factor
784
0
    if (is_not_qnan(texture.mTextureBlend))
785
0
        mat.AddProperty<ai_real>(&texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type, 0));
786
787
    // Setup texture UV transformations
788
0
    mat.AddProperty<ai_real>(&texture.mOffsetU, 5, AI_MATKEY_UVTRANSFORM(type, 0));
789
0
}
790
791
// ------------------------------------------------------------------------------------------------
792
// Convert from ASE material to output material
793
6
void ASEImporter::ConvertMaterial(ASE::Material &mat) {
794
    // LARGE TODO: Much code her is copied from 3DS ... join them maybe?
795
796
    // Allocate the output material
797
6
    mat.pcInstance = new aiMaterial();
798
799
    // At first add the base ambient color of the
800
    // scene to the material
801
6
    mat.mAmbient.r += mParser->m_clrAmbient.r;
802
6
    mat.mAmbient.g += mParser->m_clrAmbient.g;
803
6
    mat.mAmbient.b += mParser->m_clrAmbient.b;
804
805
6
    aiString name;
806
6
    name.Set(mat.mName);
807
6
    mat.pcInstance->AddProperty(&name, AI_MATKEY_NAME);
808
809
    // material colors
810
6
    mat.pcInstance->AddProperty(&mat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
811
6
    mat.pcInstance->AddProperty(&mat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
812
6
    mat.pcInstance->AddProperty(&mat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
813
6
    mat.pcInstance->AddProperty(&mat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
814
815
    // shininess
816
6
    if (0.0f != mat.mSpecularExponent && 0.0f != mat.mShininessStrength) {
817
0
        mat.pcInstance->AddProperty(&mat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
818
0
        mat.pcInstance->AddProperty(&mat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
819
0
    }
820
    // If there is no shininess, we can disable phong lighting
821
6
    else if (D3DS::Discreet3DS::Metal == mat.mShading ||
822
6
             D3DS::Discreet3DS::Phong == mat.mShading ||
823
6
             D3DS::Discreet3DS::Blinn == mat.mShading) {
824
0
        mat.mShading = D3DS::Discreet3DS::Gouraud;
825
0
    }
826
827
    // opacity
828
6
    mat.pcInstance->AddProperty<ai_real>(&mat.mTransparency, 1, AI_MATKEY_OPACITY);
829
830
    // Two sided rendering?
831
6
    if (mat.mTwoSided) {
832
0
        int i = 1;
833
0
        mat.pcInstance->AddProperty<int>(&i, 1, AI_MATKEY_TWOSIDED);
834
0
    }
835
836
    // shading mode
837
6
    aiShadingMode eShading = aiShadingMode_NoShading;
838
6
    switch (mat.mShading) {
839
0
    case D3DS::Discreet3DS::Flat:
840
0
        eShading = aiShadingMode_Flat;
841
0
        break;
842
0
    case D3DS::Discreet3DS::Phong:
843
0
        eShading = aiShadingMode_Phong;
844
0
        break;
845
0
    case D3DS::Discreet3DS::Blinn:
846
0
        eShading = aiShadingMode_Blinn;
847
0
        break;
848
849
        // I don't know what "Wire" shading should be,
850
        // assume it is simple lambertian diffuse (L dot N) shading
851
0
    case D3DS::Discreet3DS::Wire: {
852
        // set the wireframe flag
853
0
        unsigned int iWire = 1;
854
0
        mat.pcInstance->AddProperty<int>((int *)&iWire, 1, AI_MATKEY_ENABLE_WIREFRAME);
855
0
    }
856
    // fallthrough
857
6
    case D3DS::Discreet3DS::Gouraud:
858
6
        eShading = aiShadingMode_Gouraud;
859
6
        break;
860
0
    case D3DS::Discreet3DS::Metal:
861
0
        eShading = aiShadingMode_CookTorrance;
862
0
        break;
863
6
    }
864
6
    mat.pcInstance->AddProperty<int>((int *)&eShading, 1, AI_MATKEY_SHADING_MODEL);
865
866
    // DIFFUSE texture
867
6
    if (mat.sTexDiffuse.mMapName.length() > 0)
868
0
        CopyASETexture(*mat.pcInstance, mat.sTexDiffuse, aiTextureType_DIFFUSE);
869
870
    // SPECULAR texture
871
6
    if (mat.sTexSpecular.mMapName.length() > 0)
872
0
        CopyASETexture(*mat.pcInstance, mat.sTexSpecular, aiTextureType_SPECULAR);
873
874
    // AMBIENT texture
875
6
    if (mat.sTexAmbient.mMapName.length() > 0)
876
0
        CopyASETexture(*mat.pcInstance, mat.sTexAmbient, aiTextureType_AMBIENT);
877
878
    // OPACITY texture
879
6
    if (mat.sTexOpacity.mMapName.length() > 0)
880
0
        CopyASETexture(*mat.pcInstance, mat.sTexOpacity, aiTextureType_OPACITY);
881
882
    // EMISSIVE texture
883
6
    if (mat.sTexEmissive.mMapName.length() > 0)
884
0
        CopyASETexture(*mat.pcInstance, mat.sTexEmissive, aiTextureType_EMISSIVE);
885
886
    // BUMP texture
887
6
    if (mat.sTexBump.mMapName.length() > 0)
888
0
        CopyASETexture(*mat.pcInstance, mat.sTexBump, aiTextureType_HEIGHT);
889
890
    // SHININESS texture
891
6
    if (mat.sTexShininess.mMapName.length() > 0)
892
0
        CopyASETexture(*mat.pcInstance, mat.sTexShininess, aiTextureType_SHININESS);
893
894
    // store the name of the material itself, too
895
6
    if (mat.mName.length() > 0) {
896
6
        aiString tex;
897
6
        tex.Set(mat.mName);
898
6
        mat.pcInstance->AddProperty(&tex, AI_MATKEY_NAME);
899
6
    }
900
6
    return;
901
6
}
902
903
// ------------------------------------------------------------------------------------------------
904
// Build output meshes
905
6
void ASEImporter::ConvertMeshes(ASE::Mesh &mesh, std::vector<aiMesh *> &avOutMeshes) {
906
    // validate the material index of the mesh
907
6
    if (mesh.iMaterialIndex >= mParser->m_vMaterials.size()) {
908
0
        mesh.iMaterialIndex = (unsigned int)mParser->m_vMaterials.size() - 1;
909
0
        ASSIMP_LOG_WARN("Material index is out of range");
910
0
    }
911
912
    // If the material the mesh is assigned to consists of submeshes, split it
913
6
    if (!mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials.empty()) {
914
0
        std::vector<ASE::Material> vSubMaterials = mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials;
915
916
0
        std::vector<unsigned int> *aiSplit = new std::vector<unsigned int>[vSubMaterials.size()];
917
918
        // build a list of all faces per sub-material
919
0
        for (unsigned int i = 0; i < mesh.mFaces.size(); ++i) {
920
            // check range
921
0
            if (mesh.mFaces[i].iMaterial >= vSubMaterials.size()) {
922
0
                ASSIMP_LOG_WARN("Submaterial index is out of range");
923
924
                // use the last material instead
925
0
                aiSplit[vSubMaterials.size() - 1].push_back(i);
926
0
            } else
927
0
                aiSplit[mesh.mFaces[i].iMaterial].push_back(i);
928
0
        }
929
930
        // now generate submeshes
931
0
        for (unsigned int p = 0; p < vSubMaterials.size(); ++p) {
932
0
            if (!aiSplit[p].empty()) {
933
934
0
                aiMesh *p_pcOut = new aiMesh();
935
0
                p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
936
937
                // let the sub material index
938
0
                p_pcOut->mMaterialIndex = p;
939
940
                // we will need this material
941
0
                mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials[p].bNeed = true;
942
943
                // store the real index here ... color channel 3
944
0
                p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
945
946
                // store a pointer to the mesh in color channel 2
947
0
                p_pcOut->mColors[2] = (aiColor4D *)&mesh;
948
0
                avOutMeshes.push_back(p_pcOut);
949
950
                // convert vertices
951
0
                p_pcOut->mNumVertices = (unsigned int)aiSplit[p].size() * 3;
952
0
                p_pcOut->mNumFaces = (unsigned int)aiSplit[p].size();
953
954
                // receive output vertex weights
955
0
                std::vector<std::pair<unsigned int, float>> *avOutputBones = nullptr;
956
0
                if (!mesh.mBones.empty()) {
957
0
                    avOutputBones = new std::vector<std::pair<unsigned int, float>>[mesh.mBones.size()];
958
0
                }
959
960
                // allocate enough storage for faces
961
0
                p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
962
963
0
                unsigned int iBase = 0, iIndex;
964
0
                if (p_pcOut->mNumVertices) {
965
0
                    p_pcOut->mVertices = new aiVector3D[p_pcOut->mNumVertices];
966
0
                    p_pcOut->mNormals = new aiVector3D[p_pcOut->mNumVertices];
967
0
                    for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
968
969
0
                        iIndex = aiSplit[p][q];
970
971
0
                        p_pcOut->mFaces[q].mIndices = new unsigned int[3];
972
0
                        p_pcOut->mFaces[q].mNumIndices = 3;
973
974
0
                        for (unsigned int t = 0; t < 3; ++t, ++iBase) {
975
0
                            const uint32_t iIndex2 = mesh.mFaces[iIndex].mIndices[t];
976
977
0
                            p_pcOut->mVertices[iBase] = mesh.mPositions[iIndex2];
978
0
                            p_pcOut->mNormals[iBase] = mesh.mNormals[iIndex2];
979
980
                            // convert bones, if existing
981
0
                            if (!mesh.mBones.empty()) {
982
0
                                ai_assert(avOutputBones);
983
                                // check whether there is a vertex weight for this vertex index
984
0
                                if (iIndex2 < mesh.mBoneVertices.size()) {
985
986
0
                                    for (std::vector<std::pair<int, float>>::const_iterator
987
0
                                                    blubb = mesh.mBoneVertices[iIndex2].mBoneWeights.begin();
988
0
                                            blubb != mesh.mBoneVertices[iIndex2].mBoneWeights.end(); ++blubb) {
989
990
                                        // NOTE: illegal cases have already been filtered out
991
0
                                        avOutputBones[(*blubb).first].emplace_back(
992
0
                                                iBase, (*blubb).second);
993
0
                                    }
994
0
                                }
995
0
                            }
996
0
                            p_pcOut->mFaces[q].mIndices[t] = iBase;
997
0
                        }
998
0
                    }
999
0
                }
1000
                // convert texture coordinates (up to AI_MAX_NUMBER_OF_TEXTURECOORDS sets supported)
1001
0
                for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
1002
0
                    if (!mesh.amTexCoords[c].empty()) {
1003
0
                        p_pcOut->mTextureCoords[c] = new aiVector3D[p_pcOut->mNumVertices];
1004
0
                        iBase = 0;
1005
0
                        for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
1006
0
                            iIndex = aiSplit[p][q];
1007
0
                            for (unsigned int t = 0; t < 3; ++t) {
1008
0
                                p_pcOut->mTextureCoords[c][iBase++] = mesh.amTexCoords[c][mesh.mFaces[iIndex].mIndices[t]];
1009
0
                            }
1010
0
                        }
1011
                        // Setup the number of valid vertex components
1012
0
                        p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
1013
0
                    }
1014
0
                }
1015
1016
                // Convert vertex colors (only one set supported)
1017
0
                if (!mesh.mVertexColors.empty()) {
1018
0
                    p_pcOut->mColors[0] = new aiColor4D[p_pcOut->mNumVertices];
1019
0
                    iBase = 0;
1020
0
                    for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
1021
0
                        iIndex = aiSplit[p][q];
1022
0
                        for (unsigned int t = 0; t < 3; ++t) {
1023
0
                            p_pcOut->mColors[0][iBase++] = mesh.mVertexColors[mesh.mFaces[iIndex].mIndices[t]];
1024
0
                        }
1025
0
                    }
1026
0
                }
1027
                // Copy bones
1028
0
                if (!mesh.mBones.empty()) {
1029
0
                    p_pcOut->mNumBones = 0;
1030
0
                    for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock)
1031
0
                        if (!avOutputBones[mrspock].empty()) p_pcOut->mNumBones++;
1032
1033
0
                    p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
1034
0
                    aiBone **pcBone = p_pcOut->mBones;
1035
0
                    for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock) {
1036
0
                        if (!avOutputBones[mrspock].empty()) {
1037
                            // we will need this bone. add it to the output mesh and
1038
                            // add all per-vertex weights
1039
0
                            aiBone *pc = *pcBone = new aiBone();
1040
0
                            pc->mName.Set(mesh.mBones[mrspock].mName);
1041
1042
0
                            pc->mNumWeights = (unsigned int)avOutputBones[mrspock].size();
1043
0
                            pc->mWeights = new aiVertexWeight[pc->mNumWeights];
1044
1045
0
                            for (unsigned int captainkirk = 0; captainkirk < pc->mNumWeights; ++captainkirk) {
1046
0
                                const std::pair<unsigned int, float> &ref = avOutputBones[mrspock][captainkirk];
1047
0
                                pc->mWeights[captainkirk].mVertexId = ref.first;
1048
0
                                pc->mWeights[captainkirk].mWeight = ref.second;
1049
0
                            }
1050
0
                            ++pcBone;
1051
0
                        }
1052
0
                    }
1053
                    // delete allocated storage
1054
0
                    delete[] avOutputBones;
1055
0
                }
1056
0
            }
1057
0
        }
1058
        // delete storage
1059
0
        delete[] aiSplit;
1060
6
    } else {
1061
        // Otherwise we can simply copy the data to one output mesh
1062
        // This codepath needs less memory and uses fast memcpy()s
1063
        // to do the actual copying. So I think it is worth the
1064
        // effort here.
1065
1066
6
        aiMesh *p_pcOut = new aiMesh();
1067
6
        p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
1068
1069
        // set an empty sub material index
1070
6
        p_pcOut->mMaterialIndex = ASE::Face::DEFAULT_MATINDEX;
1071
6
        mParser->m_vMaterials[mesh.iMaterialIndex].bNeed = true;
1072
1073
        // store the real index here ... in color channel 3
1074
6
        p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
1075
1076
        // store a pointer to the mesh in color channel 2
1077
6
        p_pcOut->mColors[2] = (aiColor4D *)&mesh;
1078
6
        avOutMeshes.push_back(p_pcOut);
1079
1080
        // If the mesh hasn't faces or vertices, there are two cases
1081
        // possible: 1. the model is invalid. 2. This is a dummy
1082
        // helper object which we are going to remove later ...
1083
6
        if (mesh.mFaces.empty() || mesh.mPositions.empty()) {
1084
6
            return;
1085
6
        }
1086
1087
        // convert vertices
1088
0
        p_pcOut->mNumVertices = (unsigned int)mesh.mPositions.size();
1089
0
        p_pcOut->mNumFaces = (unsigned int)mesh.mFaces.size();
1090
1091
        // allocate enough storage for faces
1092
0
        p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
1093
1094
        // copy vertices
1095
0
        p_pcOut->mVertices = new aiVector3D[mesh.mPositions.size()];
1096
0
        memcpy(p_pcOut->mVertices, &mesh.mPositions[0],
1097
0
                mesh.mPositions.size() * sizeof(aiVector3D));
1098
1099
        // copy normals
1100
0
        p_pcOut->mNormals = new aiVector3D[mesh.mNormals.size()];
1101
0
        memcpy(p_pcOut->mNormals, &mesh.mNormals[0],
1102
0
                mesh.mNormals.size() * sizeof(aiVector3D));
1103
1104
        // copy texture coordinates
1105
0
        for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
1106
0
            if (!mesh.amTexCoords[c].empty()) {
1107
0
                p_pcOut->mTextureCoords[c] = new aiVector3D[mesh.amTexCoords[c].size()];
1108
0
                memcpy(p_pcOut->mTextureCoords[c], &mesh.amTexCoords[c][0],
1109
0
                        mesh.amTexCoords[c].size() * sizeof(aiVector3D));
1110
1111
                // setup the number of valid vertex components
1112
0
                p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
1113
0
            }
1114
0
        }
1115
1116
        // copy vertex colors
1117
0
        if (!mesh.mVertexColors.empty()) {
1118
0
            p_pcOut->mColors[0] = new aiColor4D[mesh.mVertexColors.size()];
1119
0
            memcpy(p_pcOut->mColors[0], &mesh.mVertexColors[0],
1120
0
                    mesh.mVertexColors.size() * sizeof(aiColor4D));
1121
0
        }
1122
1123
        // copy faces
1124
0
        for (unsigned int iFace = 0; iFace < p_pcOut->mNumFaces; ++iFace) {
1125
0
            p_pcOut->mFaces[iFace].mNumIndices = 3;
1126
0
            p_pcOut->mFaces[iFace].mIndices = new unsigned int[3];
1127
1128
            // copy indices
1129
0
            p_pcOut->mFaces[iFace].mIndices[0] = mesh.mFaces[iFace].mIndices[0];
1130
0
            p_pcOut->mFaces[iFace].mIndices[1] = mesh.mFaces[iFace].mIndices[1];
1131
0
            p_pcOut->mFaces[iFace].mIndices[2] = mesh.mFaces[iFace].mIndices[2];
1132
0
        }
1133
1134
        // copy vertex bones
1135
0
        if (!mesh.mBones.empty() && !mesh.mBoneVertices.empty()) {
1136
0
            std::vector<std::vector<aiVertexWeight>> avBonesOut(mesh.mBones.size());
1137
1138
            // find all vertex weights for this bone
1139
0
            unsigned int quak = 0;
1140
0
            for (std::vector<BoneVertex>::const_iterator harrypotter = mesh.mBoneVertices.begin();
1141
0
                    harrypotter != mesh.mBoneVertices.end(); ++harrypotter, ++quak) {
1142
1143
0
                for (std::vector<std::pair<int, float>>::const_iterator
1144
0
                                ronaldweasley = (*harrypotter).mBoneWeights.begin();
1145
0
                        ronaldweasley != (*harrypotter).mBoneWeights.end(); ++ronaldweasley) {
1146
0
                    aiVertexWeight weight;
1147
0
                    weight.mVertexId = quak;
1148
0
                    weight.mWeight = (*ronaldweasley).second;
1149
0
                    avBonesOut[(*ronaldweasley).first].push_back(weight);
1150
0
                }
1151
0
            }
1152
1153
            // now build a final bone list
1154
0
            p_pcOut->mNumBones = 0;
1155
0
            for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy)
1156
0
                if (!avBonesOut[jfkennedy].empty()) p_pcOut->mNumBones++;
1157
1158
0
            p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
1159
0
            aiBone **pcBone = p_pcOut->mBones;
1160
0
            for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy) {
1161
0
                if (!avBonesOut[jfkennedy].empty()) {
1162
0
                    aiBone *pc = *pcBone = new aiBone();
1163
0
                    pc->mName.Set(mesh.mBones[jfkennedy].mName);
1164
0
                    pc->mNumWeights = (unsigned int)avBonesOut[jfkennedy].size();
1165
0
                    pc->mWeights = new aiVertexWeight[pc->mNumWeights];
1166
0
                    ::memcpy(pc->mWeights, &avBonesOut[jfkennedy][0],
1167
0
                            sizeof(aiVertexWeight) * pc->mNumWeights);
1168
0
                    ++pcBone;
1169
0
                }
1170
0
            }
1171
0
        }
1172
0
    }
1173
6
}
1174
1175
// ------------------------------------------------------------------------------------------------
1176
// Setup proper material indices and build output materials
1177
6
void ASEImporter::BuildMaterialIndices() {
1178
6
    ai_assert(nullptr != pcScene);
1179
1180
    // iterate through all materials and check whether we need them
1181
12
    for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
1182
6
        ASE::Material &mat = mParser->m_vMaterials[iMat];
1183
6
        if (mat.bNeed) {
1184
            // Convert it to the aiMaterial layout
1185
6
            ConvertMaterial(mat);
1186
6
            ++pcScene->mNumMaterials;
1187
6
        }
1188
6
        for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
1189
0
            ASE::Material &submat = mat.avSubMaterials[iSubMat];
1190
0
            if (submat.bNeed) {
1191
                // Convert it to the aiMaterial layout
1192
0
                ConvertMaterial(submat);
1193
0
                ++pcScene->mNumMaterials;
1194
0
            }
1195
0
        }
1196
6
    }
1197
1198
    // allocate the output material array
1199
6
    pcScene->mMaterials = new aiMaterial *[pcScene->mNumMaterials];
1200
6
    D3DS::Material **pcIntMaterials = new D3DS::Material *[pcScene->mNumMaterials];
1201
1202
6
    unsigned int iNum = 0;
1203
12
    for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
1204
6
        ASE::Material &mat = mParser->m_vMaterials[iMat];
1205
6
        if (mat.bNeed) {
1206
6
            ai_assert(nullptr != mat.pcInstance);
1207
6
            pcScene->mMaterials[iNum] = mat.pcInstance;
1208
1209
            // Store the internal material, too
1210
6
            pcIntMaterials[iNum] = &mat;
1211
1212
            // Iterate through all meshes and search for one which is using
1213
            // this top-level material index
1214
6
            for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
1215
0
                aiMesh *mesh = pcScene->mMeshes[iMesh];
1216
0
                if (ASE::Face::DEFAULT_MATINDEX == mesh->mMaterialIndex &&
1217
0
                        iMat == (uintptr_t)mesh->mColors[3]) {
1218
0
                    mesh->mMaterialIndex = iNum;
1219
0
                    mesh->mColors[3] = nullptr;
1220
0
                }
1221
0
            }
1222
6
            iNum++;
1223
6
        }
1224
6
        for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
1225
0
            ASE::Material &submat = mat.avSubMaterials[iSubMat];
1226
0
            if (submat.bNeed) {
1227
0
                ai_assert(nullptr != submat.pcInstance);
1228
0
                pcScene->mMaterials[iNum] = submat.pcInstance;
1229
1230
                // Store the internal material, too
1231
0
                pcIntMaterials[iNum] = &submat;
1232
1233
                // Iterate through all meshes and search for one which is using
1234
                // this sub-level material index
1235
0
                for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
1236
0
                    aiMesh *mesh = pcScene->mMeshes[iMesh];
1237
1238
0
                    if (iSubMat == mesh->mMaterialIndex && iMat == (uintptr_t)mesh->mColors[3]) {
1239
0
                        mesh->mMaterialIndex = iNum;
1240
0
                        mesh->mColors[3] = nullptr;
1241
0
                    }
1242
0
                }
1243
0
                iNum++;
1244
0
            }
1245
0
        }
1246
6
    }
1247
1248
    // Delete our temporary array
1249
6
    delete[] pcIntMaterials;
1250
6
}
1251
1252
// ------------------------------------------------------------------------------------------------
1253
// Generate normal vectors basing on smoothing groups
1254
6
bool ASEImporter::GenerateNormals(ASE::Mesh &mesh) {
1255
1256
6
    if (!mesh.mNormals.empty() && !configRecomputeNormals) {
1257
        // Check whether there are only uninitialized normals. If there are
1258
        // some, skip all normals from the file and compute them on our own
1259
0
        for (std::vector<aiVector3D>::const_iterator qq = mesh.mNormals.begin(); qq != mesh.mNormals.end(); ++qq) {
1260
0
            if ((*qq).x || (*qq).y || (*qq).z) {
1261
0
                return true;
1262
0
            }
1263
0
        }
1264
0
    }
1265
    // The array is reused.
1266
6
    ComputeNormalsWithSmoothingsGroups<ASE::Face>(mesh);
1267
6
    return false;
1268
6
}
1269
1270
}
1271
1272
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
1273
#endif // ASSIMP_BUILD_NO_ASE_IMPORTER