Coverage Report

Created: 2026-11-12 07:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/Ply/PlyLoader.cpp
Line
Count
Source
1
/*
2
---------------------------------------------------------------------------
3
Open Asset Import Library (assimp)
4
---------------------------------------------------------------------------
5
6
Copyright (c) 2006-2026, 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  PlyLoader.cpp
43
 *  @brief Implementation of the PLY importer class
44
 */
45
46
#ifndef ASSIMP_BUILD_NO_PLY_IMPORTER
47
48
// internal headers
49
#include "PlyLoader.h"
50
51
// standard headers
52
#include <assimp/IOStreamBuffer.h>
53
#include <assimp/importerdesc.h>
54
#include <assimp/scene.h>
55
#include <assimp/IOSystem.hpp>
56
57
// other headers
58
#include <memory>
59
60
namespace Assimp {
61
62
    // ------------------------------------------------------------------------------------------------
63
    static constexpr ai_uint NotSet = 0xFFFFFFFF;
64
65
    static constexpr aiImporterDesc desc = {
66
        "Stanford Polygon Library (PLY) Importer",
67
        "",
68
        "",
69
        "",
70
        aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportTextFlavour,
71
        0,
72
        0,
73
        0,
74
        0,
75
        "ply"
76
    };
77
78
    namespace { // Internal stuff
79
        // ------------------------------------------------------------------------------------------------
80
        // Checks that property index is within range
81
        template <class T>
82
3.97M
        const T &GetProperty(const std::vector<T> &props, int idx) {
83
3.97M
            if (static_cast<size_t>(idx) >= props.size()) {
84
0
                throw DeadlyImportError("Invalid .ply file: Property index is out of range.");
85
0
            }
86
87
3.97M
            return props[idx];
88
3.97M
        }
89
90
        // ------------------------------------------------------------------------------------------------
91
196
        bool isBigEndian(const char *szMe) {
92
196
            ai_assert(nullptr != szMe);
93
94
            // binary_little_endian
95
            // binary_big_endian
96
196
            bool isBigEndian{ false };
97
    #if (defined AI_BUILD_BIG_ENDIAN)
98
            if ('l' == *szMe || 'L' == *szMe) {
99
                isBigEndian = true;
100
            }
101
    #else
102
196
            if ('b' == *szMe || 'B' == *szMe) {
103
12
                isBigEndian = true;
104
12
            }
105
196
    #endif // ! AI_BUILD_BIG_ENDIAN
106
107
196
            return isBigEndian;
108
196
        }
109
110
        // ------------------------------------------------------------------------------------------------
111
        // Convert a color component to [0...1]
112
568k
        ai_real NormalizeColorValue(PropertyInstance::ValueUnion val, EDataType eType) {
113
568k
            switch (eType) {
114
559k
                case EDT_Float:
115
559k
                    return val.fFloat;
116
935
                case EDT_Double:
117
935
                    return static_cast<ai_real>(val.fDouble);
118
8.24k
                case EDT_UChar:
119
8.24k
                    return static_cast<ai_real>(val.iUInt) / static_cast<ai_real>(0xFF);
120
0
                case EDT_Char:
121
0
                    return static_cast<ai_real>(val.iInt + (0xFF / 2)) / static_cast<ai_real>(0xFF);
122
0
                case EDT_UShort:
123
0
                    return static_cast<ai_real>(val.iUInt) / static_cast<ai_real>(0xFFFF);
124
0
                case EDT_Short:
125
0
                    return static_cast<ai_real>(val.iInt + (0xFFFF / 2)) / static_cast<ai_real>(0xFFFF);
126
0
                case EDT_UInt:
127
0
                    return static_cast<ai_real>(val.iUInt) / static_cast<ai_real>(0xFFFFFFFFu);
128
0
                case EDT_Int:
129
0
                    return (static_cast<ai_real>(val.iInt) / static_cast<ai_real>(0xFF)) + 0.5f;
130
0
                default:
131
0
                    break;
132
568k
            }
133
134
0
            return 0.0f;
135
568k
        }
136
137
        // ------------------------------------------------------------------------------------------------
138
        // Get a RGBA color in [0...1] range
139
        void GetMaterialColor(const std::vector<PLY::PropertyInstance> &avList, unsigned int positions[4], EDataType types[4],
140
0
                aiColor4D *clrOut) {
141
0
            ai_assert(nullptr != clrOut);
142
143
0
            if (NotSet == positions[0]) {
144
0
                clrOut->r = 0.0f;
145
0
            } else {
146
0
                clrOut->r = NormalizeColorValue(GetProperty(avList, positions[0]).avList.front(), types[0]);
147
0
            }
148
149
0
            if (NotSet == positions[1]) {
150
0
                clrOut->g = 0.0f;
151
0
            } else {
152
0
                clrOut->g = NormalizeColorValue(GetProperty(avList, positions[1]).avList.front(), types[1]);
153
0
            }
154
155
0
            if (NotSet == positions[2]) {
156
0
                clrOut->b = 0.0f;
157
0
            } else {
158
0
                clrOut->b = NormalizeColorValue(GetProperty(avList, positions[2]).avList.front(), types[2]);
159
0
            }
160
161
            // assume 1.0 for the alpha channel ifit is not set
162
0
            if (NotSet == positions[3]) {
163
0
                clrOut->a = 1.0f;
164
0
            } else {
165
0
                clrOut->a = NormalizeColorValue(GetProperty(avList, positions[3]).avList.front(), types[3]);
166
0
            }
167
0
        }
168
169
    } // namespace
170
171
    // ------------------------------------------------------------------------------------------------
172
165k
    PLYImporter::~PLYImporter() {
173
165k
        delete mGeneratedMesh;
174
165k
    }
175
176
    // ------------------------------------------------------------------------------------------------
177
    // Returns whether the class can handle the format of the given file.
178
39.9k
    bool PLYImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool) const {
179
39.9k
        static const char *tokens[] = { "ply" };
180
39.9k
        return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
181
39.9k
    }
182
183
    // ------------------------------------------------------------------------------------------------
184
163k
    const aiImporterDesc *PLYImporter::GetInfo() const {
185
163k
        return &desc;
186
163k
    }
187
188
    // ------------------------------------------------------------------------------------------------
189
    // Imports the given file into the given scene structure.
190
1.62k
    void PLYImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
191
1.62k
        const std::string mode = "rb";
192
1.62k
        std::unique_ptr<IOStream> fileStream(pIOHandler->Open(pFile, mode));
193
1.62k
        if (!fileStream) {
194
0
            throw DeadlyImportError("Failed to open file ", pFile, ".");
195
0
        }
196
197
        // Get the file-size
198
1.62k
        const size_t fileSize = fileStream->FileSize();
199
1.62k
        if (0 == fileSize) {
200
0
            throw DeadlyImportError("File ", pFile, " is empty.");
201
0
        }
202
203
1.62k
        IOStreamBuffer<char> streamedBuffer(1024 * 1024);
204
1.62k
        streamedBuffer.open(fileStream.get());
205
206
        // the beginning of the file must be PLY - magic, magic
207
1.62k
        std::vector<char> headerCheck;
208
1.62k
        streamedBuffer.getNextLine(headerCheck);
209
210
1.62k
        if ((headerCheck.size() < 3) ||
211
1.62k
                (headerCheck[0] != 'P' && headerCheck[0] != 'p') ||
212
1.59k
                (headerCheck[1] != 'L' && headerCheck[1] != 'l') ||
213
1.58k
                (headerCheck[2] != 'Y' && headerCheck[2] != 'y')) {
214
40
            streamedBuffer.close();
215
40
            throw DeadlyImportError("Invalid .ply file: Incorrect magic number (expected 'ply' or 'PLY').");
216
40
        }
217
218
1.58k
        std::vector<char> mBuffer2;
219
1.58k
        streamedBuffer.getNextLine(mBuffer2);
220
1.58k
        mBuffer = (unsigned char *)&mBuffer2[0];
221
222
1.58k
        auto szMe = (char *)&this->mBuffer[0];
223
1.58k
        const char *end = &mBuffer2[0] + mBuffer2.size();
224
1.58k
        SkipSpacesAndLineEnd(szMe, (const char **)&szMe, end);
225
226
        // determine the format of the file data and construct the aiMesh
227
1.58k
        DOM sPlyDom;
228
1.58k
        this->pcDOM = &sPlyDom;
229
230
1.58k
        if (TokenMatch(szMe, "format", 6)) {
231
1.49k
            if (TokenMatch(szMe, "ascii", 5)) {
232
1.26k
                SkipLine(szMe, (const char **)&szMe, end);
233
1.26k
                if (!DOM::ParseInstance(streamedBuffer, &sPlyDom, this)) {
234
525
                    if (mGeneratedMesh != nullptr) {
235
0
                        delete (mGeneratedMesh);
236
0
                        mGeneratedMesh = nullptr;
237
0
                    }
238
239
525
                    streamedBuffer.close();
240
525
                    throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#1)");
241
525
                }
242
1.26k
            } else if (!strncmp(szMe, "binary_", 7)) {
243
196
                szMe += 7;
244
245
                // skip the line, parse the rest of the header and build the DOM
246
196
                if (const bool bIsBE = isBigEndian(szMe); !PLY::DOM::ParseInstanceBinary(streamedBuffer, &sPlyDom, this, bIsBE)) {
247
72
                    if (mGeneratedMesh != nullptr) {
248
0
                        delete (mGeneratedMesh);
249
0
                        mGeneratedMesh = nullptr;
250
0
                    }
251
252
72
                    streamedBuffer.close();
253
72
                    throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#2)");
254
72
                }
255
196
            } else {
256
31
                if (mGeneratedMesh != nullptr) {
257
0
                    delete mGeneratedMesh;
258
0
                    mGeneratedMesh = nullptr;
259
0
                }
260
261
31
                streamedBuffer.close();
262
31
                throw DeadlyImportError("Invalid .ply file: Unknown file format");
263
31
            }
264
1.49k
        } else {
265
93
            AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
266
93
            if (mGeneratedMesh != nullptr) {
267
0
                delete (mGeneratedMesh);
268
0
                mGeneratedMesh = nullptr;
269
0
            }
270
271
93
            streamedBuffer.close();
272
93
            throw DeadlyImportError("Invalid .ply file: Missing format specification");
273
93
        }
274
275
        // free the file buffer
276
865
        streamedBuffer.close();
277
278
865
        if (mGeneratedMesh == nullptr) {
279
190
            throw DeadlyImportError("Invalid .ply file: Unable to extract mesh data ");
280
190
        }
281
282
        // if no face list is existing we assume that the vertex
283
        // list is containing a list of points
284
675
        bool pointsOnly = mGeneratedMesh->mFaces == nullptr ? true : false;
285
675
        if (pointsOnly) {
286
225
            mGeneratedMesh->mPrimitiveTypes = aiPrimitiveType::aiPrimitiveType_POINT;
287
225
        }
288
289
        // now load a list of all materials
290
675
        std::vector<aiMaterial *> avMaterials;
291
675
        std::string defaultTexture;
292
675
        LoadMaterial(&avMaterials, defaultTexture, pointsOnly);
293
294
        // now generate the output scene object. Fill the material list
295
675
        pScene->mNumMaterials = static_cast<unsigned int>(avMaterials.size());
296
675
        pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
297
1.03k
        for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
298
356
            pScene->mMaterials[i] = avMaterials[i];
299
356
        }
300
301
        // fill the mesh list
302
675
        pScene->mNumMeshes = 1;
303
675
        pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
304
675
        pScene->mMeshes[0] = mGeneratedMesh;
305
306
        // Move the mesh ownership into the scene instance
307
675
        mGeneratedMesh = nullptr;
308
309
        // generate a simple node structure
310
675
        pScene->mRootNode = new aiNode();
311
675
        pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
312
675
        pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
313
314
1.03k
        for (unsigned int i = 0; i < pScene->mRootNode->mNumMeshes; ++i) {
315
356
            pScene->mRootNode->mMeshes[i] = i;
316
356
        }
317
675
    }
318
319
6.14M
    void PLYImporter::LoadVertex(const Element *pcElement, const ElementInstance *instElement, unsigned int pos) {
320
6.14M
        ai_assert(nullptr != pcElement);
321
6.14M
        ai_assert(nullptr != instElement);
322
323
6.14M
        ai_uint aiPositions[3] = { NotSet, NotSet, NotSet };
324
6.14M
        EDataType aiTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
325
326
6.14M
        ai_uint aiNormal[3] = { NotSet, NotSet, NotSet };
327
6.14M
        EDataType aiNormalTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
328
329
6.14M
        unsigned int aiColors[4] = { NotSet, NotSet, NotSet, NotSet };
330
6.14M
        EDataType aiColorsTypes[4] = { EDT_Char, EDT_Char, EDT_Char, EDT_Char };
331
332
6.14M
        unsigned int aiTexcoord[2] = { NotSet, NotSet };
333
6.14M
        EDataType aiTexcoordTypes[2] = { EDT_Char, EDT_Char };
334
335
        // now check whether which normal components are available
336
6.14M
        unsigned int _a(0), cnt(0);
337
15.2M
        for (auto a = pcElement->alProperties.begin(); a != pcElement->alProperties.end(); ++a, ++_a) {
338
9.12M
            if (a->bIsList) {
339
33.1k
                continue;
340
33.1k
            }
341
342
            // Positions
343
9.08M
            if (EST_XCoord == a->Semantic) {
344
402k
                ++cnt;
345
402k
                aiPositions[0] = _a;
346
402k
                aiTypes[0] = a->eType;
347
8.68M
            } else if (EST_YCoord == a->Semantic) {
348
579k
                ++cnt;
349
579k
                aiPositions[1] = _a;
350
579k
                aiTypes[1] = a->eType;
351
8.10M
            } else if (EST_ZCoord == a->Semantic) {
352
704k
                ++cnt;
353
704k
                aiPositions[2] = _a;
354
704k
                aiTypes[2] = a->eType;
355
7.40M
            } else if (EST_XNormal == a->Semantic) {
356
                // Normals
357
257k
                ++cnt;
358
257k
                aiNormal[0] = _a;
359
257k
                aiNormalTypes[0] = a->eType;
360
7.14M
            } else if (EST_YNormal == a->Semantic) {
361
465k
                ++cnt;
362
465k
                aiNormal[1] = _a;
363
465k
                aiNormalTypes[1] = a->eType;
364
6.67M
            } else if (EST_ZNormal == a->Semantic) {
365
325k
                ++cnt;
366
325k
                aiNormal[2] = _a;
367
325k
                aiNormalTypes[2] = a->eType;
368
6.35M
            } else if (EST_Red == a->Semantic) {
369
                // Colors
370
304k
                ++cnt;
371
304k
                aiColors[0] = _a;
372
304k
                aiColorsTypes[0] = a->eType;
373
6.04M
            } else if (EST_Green == a->Semantic) {
374
99.2k
                ++cnt;
375
99.2k
                aiColors[1] = _a;
376
99.2k
                aiColorsTypes[1] = a->eType;
377
5.94M
            } else if (EST_Blue == a->Semantic) {
378
65.9k
                ++cnt;
379
65.9k
                aiColors[2] = _a;
380
65.9k
                aiColorsTypes[2] = a->eType;
381
5.88M
            } else if (EST_Alpha == a->Semantic) {
382
131k
                ++cnt;
383
131k
                aiColors[3] = _a;
384
131k
                aiColorsTypes[3] = a->eType;
385
5.75M
            } else if (EST_UTextureCoord == a->Semantic) {
386
                // Texture coordinates
387
455k
                ++cnt;
388
455k
                aiTexcoord[0] = _a;
389
455k
                aiTexcoordTypes[0] = a->eType;
390
5.29M
            } else if (EST_VTextureCoord == a->Semantic) {
391
316k
                ++cnt;
392
316k
                aiTexcoord[1] = _a;
393
316k
                aiTexcoordTypes[1] = a->eType;
394
316k
            }
395
9.08M
        }
396
397
        // check whether we have a valid source for the vertex data
398
6.14M
        if (0 != cnt) {
399
            // Position
400
1.23M
            aiVector3D vOut;
401
1.23M
            if (NotSet != aiPositions[0]) {
402
401k
                vOut.x = PropertyInstance::ConvertTo<ai_real>(
403
401k
                        GetProperty(instElement->alProperties, aiPositions[0]).avList.front(), aiTypes[0]);
404
401k
            }
405
406
1.23M
            if (NotSet != aiPositions[1]) {
407
530k
                vOut.y = PropertyInstance::ConvertTo<ai_real>(
408
530k
                        GetProperty(instElement->alProperties, aiPositions[1]).avList.front(), aiTypes[1]);
409
530k
            }
410
411
1.23M
            if (NotSet != aiPositions[2]) {
412
595k
                vOut.z = PropertyInstance::ConvertTo<ai_real>(
413
595k
                        GetProperty(instElement->alProperties, aiPositions[2]).avList.front(), aiTypes[2]);
414
595k
            }
415
416
            // Normals
417
1.23M
            aiVector3D nOut;
418
1.23M
            bool haveNormal = false;
419
1.23M
            if (NotSet != aiNormal[0]) {
420
257k
                nOut.x = PropertyInstance::ConvertTo<ai_real>(
421
257k
                        GetProperty(instElement->alProperties, aiNormal[0]).avList.front(), aiNormalTypes[0]);
422
257k
                haveNormal = true;
423
257k
            }
424
425
1.23M
            if (NotSet != aiNormal[1]) {
426
452k
                nOut.y = PropertyInstance::ConvertTo<ai_real>(
427
452k
                        GetProperty(instElement->alProperties, aiNormal[1]).avList.front(), aiNormalTypes[1]);
428
452k
                haveNormal = true;
429
452k
            }
430
431
1.23M
            if (NotSet != aiNormal[2]) {
432
322k
                nOut.z = PropertyInstance::ConvertTo<ai_real>(
433
322k
                        GetProperty(instElement->alProperties, aiNormal[2]).avList.front(), aiNormalTypes[2]);
434
322k
                haveNormal = true;
435
322k
            }
436
437
            // Colors
438
1.23M
            aiColor4D cOut;
439
1.23M
            bool haveColor = false;
440
1.23M
            if (NotSet != aiColors[0]) {
441
271k
                cOut.r = NormalizeColorValue(GetProperty(instElement->alProperties,
442
271k
                                                    aiColors[0])
443
271k
                                                    .avList.front(),
444
271k
                        aiColorsTypes[0]);
445
271k
                haveColor = true;
446
271k
            }
447
448
1.23M
            if (NotSet != aiColors[1]) {
449
99.0k
                cOut.g = NormalizeColorValue(GetProperty(instElement->alProperties,
450
99.0k
                                                    aiColors[1])
451
99.0k
                                                    .avList.front(),
452
99.0k
                        aiColorsTypes[1]);
453
99.0k
                haveColor = true;
454
99.0k
            }
455
456
1.23M
            if (NotSet != aiColors[2]) {
457
65.8k
                cOut.b = NormalizeColorValue(GetProperty(instElement->alProperties,
458
65.8k
                                                    aiColors[2])
459
65.8k
                                                    .avList.front(),
460
65.8k
                        aiColorsTypes[2]);
461
65.8k
                haveColor = true;
462
65.8k
            }
463
464
            // assume 1.0 for the alpha channel if it is not set
465
1.23M
            if (NotSet == aiColors[3]) {
466
1.10M
                cOut.a = 1.0;
467
1.10M
            } else {
468
131k
                cOut.a = NormalizeColorValue(GetProperty(instElement->alProperties,
469
131k
                                                    aiColors[3])
470
131k
                                                    .avList.front(),
471
131k
                        aiColorsTypes[3]);
472
473
131k
                haveColor = true;
474
131k
            }
475
476
            // Texture coordinates
477
1.23M
            aiVector3D tOut;
478
1.23M
            tOut.z = 0;
479
1.23M
            bool haveTextureCoords = false;
480
1.23M
            if (NotSet != aiTexcoord[0]) {
481
355k
                tOut.x = PropertyInstance::ConvertTo<ai_real>(
482
355k
                        GetProperty(instElement->alProperties, aiTexcoord[0]).avList.front(), aiTexcoordTypes[0]);
483
355k
                haveTextureCoords = true;
484
355k
            }
485
486
1.23M
            if (NotSet != aiTexcoord[1]) {
487
251k
                tOut.y = PropertyInstance::ConvertTo<ai_real>(
488
251k
                        GetProperty(instElement->alProperties, aiTexcoord[1]).avList.front(), aiTexcoordTypes[1]);
489
251k
                haveTextureCoords = true;
490
251k
            }
491
492
            // create aiMesh if needed
493
1.23M
            if (nullptr == mGeneratedMesh) {
494
472
                mGeneratedMesh = new aiMesh();
495
472
                mGeneratedMesh->mMaterialIndex = 0;
496
472
            }
497
498
1.23M
            if (nullptr == mGeneratedMesh->mVertices) {
499
472
                mGeneratedMesh->mNumVertices = pcElement->NumOccur;
500
472
                mGeneratedMesh->mVertices = new aiVector3D[mGeneratedMesh->mNumVertices];
501
472
            }
502
1.23M
            if (pos >= mGeneratedMesh->mNumVertices) {
503
0
                throw DeadlyImportError("Invalid .ply file: Too many vertices");
504
0
            }
505
506
1.23M
            mGeneratedMesh->mVertices[pos] = vOut;
507
508
1.23M
            if (haveNormal) {
509
454k
                if (nullptr == mGeneratedMesh->mNormals)
510
112
                    mGeneratedMesh->mNormals = new aiVector3D[mGeneratedMesh->mNumVertices];
511
454k
                mGeneratedMesh->mNormals[pos] = nOut;
512
454k
            }
513
514
1.23M
            if (haveColor) {
515
502k
                if (nullptr == mGeneratedMesh->mColors[0])
516
158
                    mGeneratedMesh->mColors[0] = new aiColor4D[mGeneratedMesh->mNumVertices];
517
502k
                mGeneratedMesh->mColors[0][pos] = cOut;
518
502k
            }
519
520
1.23M
            if (haveTextureCoords) {
521
355k
                if (nullptr == mGeneratedMesh->mTextureCoords[0]) {
522
101
                    mGeneratedMesh->mNumUVComponents[0] = 2;
523
101
                    mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
524
101
                }
525
355k
                mGeneratedMesh->mTextureCoords[0][pos] = tOut;
526
355k
            }
527
1.23M
        }
528
6.14M
    }
529
530
    // ------------------------------------------------------------------------------------------------
531
    // Try to extract proper faces from the PLY DOM
532
    void PLYImporter::LoadFace(const Element *pcElement, const ElementInstance *instElement,
533
1.49M
            unsigned int pos) {
534
1.49M
        ai_assert(nullptr != pcElement);
535
1.49M
        ai_assert(nullptr != instElement);
536
537
1.49M
        if (mGeneratedMesh == nullptr) {
538
39
            throw DeadlyImportError("Invalid .ply file: Vertices should be declared before faces");
539
39
        }
540
541
1.49M
        bool bOne = false;
542
543
        // index of the vertex index list
544
1.49M
        unsigned int iProperty = NotSet;
545
1.49M
        EDataType eType = EDT_Char;
546
1.49M
        bool bIsTriStrip = false;
547
548
        // texture coordinates
549
1.49M
        unsigned int iTextureCoord = NotSet;
550
1.49M
        EDataType eType3 = EDT_Char;
551
552
        // face = unique number of vertex indices
553
1.49M
        if (EEST_Face == pcElement->eSemantic) {
554
1.49M
            unsigned int _a = 0;
555
1.49M
            for (std::vector<Property>::const_iterator a = pcElement->alProperties.begin();
556
2.72M
                    a != pcElement->alProperties.end(); ++a, ++_a) {
557
1.22M
                if (EST_VertexIndex == a->Semantic) {
558
                    // must be a dynamic list!
559
152k
                    if (!a->bIsList) {
560
33.0k
                        continue;
561
33.0k
                    }
562
563
119k
                    iProperty = _a;
564
119k
                    bOne = true;
565
119k
                    eType = a->eType;
566
1.07M
                } else if (EST_TextureCoordinates == a->Semantic) {
567
                    // must be a dynamic list!
568
0
                    if (!a->bIsList) {
569
0
                        continue;
570
0
                    }
571
0
                    iTextureCoord = _a;
572
0
                    bOne = true;
573
0
                    eType3 = a->eType;
574
0
                }
575
1.22M
            }
576
1.49M
        }
577
        // triangle strip
578
        // TODO: material index support???
579
0
        else if (EEST_TriStrip == pcElement->eSemantic) {
580
0
            unsigned int _a = 0;
581
0
            for (auto a = pcElement->alProperties.begin(); a != pcElement->alProperties.end(); ++a, ++_a) {
582
                // must be a dynamic list!
583
0
                if (!a->bIsList) {
584
0
                    continue;
585
0
                }
586
0
                iProperty = _a;
587
0
                bOne = true;
588
0
                bIsTriStrip = true;
589
0
                eType = a->eType;
590
0
                break;
591
0
            }
592
0
        }
593
594
        // check whether we have at least one per-face information set
595
1.49M
        if (bOne) {
596
119k
            if (mGeneratedMesh->mFaces == nullptr) {
597
135
                mGeneratedMesh->mNumFaces = pcElement->NumOccur;
598
135
                mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
599
119k
            } else {
600
119k
                if (mGeneratedMesh->mNumFaces < pcElement->NumOccur) {
601
0
                    throw DeadlyImportError("Invalid .ply file: Too many faces");
602
0
                }
603
119k
            }
604
605
119k
            if (!bIsTriStrip) {
606
                // parse the list of vertex indices
607
119k
                if (NotSet != iProperty) {
608
119k
                    const unsigned int iNum = static_cast<unsigned int>(GetProperty(instElement->alProperties, iProperty).avList.size());
609
119k
                    mGeneratedMesh->mFaces[pos].mNumIndices = iNum;
610
119k
                    mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[iNum];
611
612
119k
                    std::vector<PropertyInstance::ValueUnion>::const_iterator p =
613
119k
                            GetProperty(instElement->alProperties, iProperty).avList.begin();
614
615
19.6M
                    for (unsigned int a = 0; a < iNum; ++a, ++p) {
616
19.5M
                        mGeneratedMesh->mFaces[pos].mIndices[a] = PropertyInstance::ConvertTo<unsigned int>(*p, eType);
617
19.5M
                    }
618
119k
                }
619
620
119k
                if (NotSet != iTextureCoord) {
621
0
                    const auto iNum = static_cast<unsigned int>(GetProperty(instElement->alProperties, iTextureCoord).avList.size());
622
623
                    // should be 6 coords
624
0
                    auto p = GetProperty(instElement->alProperties, iTextureCoord).avList.begin();
625
0
                    if ((iNum / 3) == 2) { // X Y coord
626
0
                        if (iNum > mGeneratedMesh->mFaces[pos].mNumIndices * 2) {
627
0
                            throw DeadlyImportError("Invalid .ply file: Too many texture coordinates for face");
628
0
                        }
629
0
                        for (unsigned int a = 0; a < iNum; ++a, ++p) {
630
                            // The texture-coordinate list length is independent of the
631
                            // vertex-index list length, so a / 2 may run past the face's
632
                            // index array (which may even be absent). Bound it before use.
633
0
                            const unsigned int faceIndexPos = a / 2;
634
0
                            if (mGeneratedMesh->mFaces[pos].mIndices == nullptr ||
635
0
                                    faceIndexPos >= mGeneratedMesh->mFaces[pos].mNumIndices) {
636
0
                                continue;
637
0
                            }
638
0
                            unsigned int vindex = mGeneratedMesh->mFaces[pos].mIndices[faceIndexPos];
639
0
                            if (vindex < mGeneratedMesh->mNumVertices) {
640
0
                                if (mGeneratedMesh->mTextureCoords[0] == nullptr) {
641
0
                                    mGeneratedMesh->mNumUVComponents[0] = 2;
642
0
                                    mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
643
0
                                }
644
645
0
                                if (a % 2 == 0) {
646
0
                                    mGeneratedMesh->mTextureCoords[0][vindex].x = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
647
0
                                } else {
648
0
                                    mGeneratedMesh->mTextureCoords[0][vindex].y = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
649
0
                                }
650
651
0
                                mGeneratedMesh->mTextureCoords[0][vindex].z = 0;
652
0
                            }
653
0
                        }
654
0
                    }
655
0
                }
656
119k
            } else { // triangle strips
657
                // normally we have only one triangle strip instance where
658
                // a value of -1 indicates a restart of the strip
659
0
                createFromeTriStrip(instElement, iProperty, eType);
660
0
            }
661
119k
        }
662
1.49M
    }
663
664
    // ------------------------------------------------------------------------------------------------
665
0
    void PLYImporter::createFromeTriStrip(const ElementInstance *instElement, unsigned int iProperty, EDataType eType) {
666
0
        bool flip = false;
667
0
        const auto &quak = GetProperty(instElement->alProperties, iProperty).avList;
668
669
0
        std::vector<aiFace> cache;
670
0
        int aiTable[2] = { -1, -1 };
671
0
        for (auto a = quak.begin(); a != quak.end(); ++a) {
672
0
            const int p = PropertyInstance::ConvertTo<int>(*a, eType);
673
674
0
            if (-1 == p) {
675
                // restart the strip ...
676
0
                aiTable[0] = aiTable[1] = -1;
677
0
                flip = false;
678
0
                continue;
679
0
            }
680
            
681
0
            if (-1 == aiTable[0]) {
682
0
                aiTable[0] = p;
683
0
                continue;
684
0
            }
685
            
686
0
            if (-1 == aiTable[1]) {
687
0
                aiTable[1] = p;
688
0
                continue;
689
0
            }
690
0
            aiFace face;
691
0
            face.mNumIndices = 3;
692
0
            face.mIndices = new unsigned int[3];
693
0
            face.mIndices[0] = aiTable[0];
694
0
            face.mIndices[1] = aiTable[1];
695
0
            face.mIndices[2] = p;
696
0
            if (flip) {
697
0
                std::swap(face.mIndices[0], face.mIndices[1]);
698
0
            }
699
0
            cache.push_back(face);
700
            // every second pass swap the indices.
701
0
            flip = !flip;
702
703
0
            aiTable[0] = aiTable[1];
704
0
            aiTable[1] = p;
705
0
        }
706
0
        if (mGeneratedMesh->mFaces != nullptr) {
707
0
            delete[] mGeneratedMesh->mFaces;
708
0
        }
709
0
        mGeneratedMesh->mNumFaces = static_cast<unsigned int>(cache.size());
710
0
        mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
711
0
        std::copy(cache.begin(), cache.end(), mGeneratedMesh->mFaces);
712
0
    }
713
714
    // ------------------------------------------------------------------------------------------------
715
    // Extract a material from the PLY DOM
716
356
    void PLYImporter::LoadMaterial(std::vector<aiMaterial *> *pvOut, std::string &defaultTexture, const bool pointsOnly) {
717
356
        ai_assert(nullptr != pvOut);
718
719
        // diffuse[4], specular[4], ambient[4]
720
        // rgba order
721
356
        unsigned int aaiPositions[3][4] = {
722
356
            { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
723
356
            { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
724
356
            { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
725
356
        };
726
727
356
        EDataType aaiTypes[3][4] = {
728
356
            { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
729
356
            { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
730
356
            { EDT_Char, EDT_Char, EDT_Char, EDT_Char }
731
356
        };
732
356
        ElementInstanceList *pcList = nullptr;
733
734
356
        unsigned int iPhong = 0xFFFFFFFF;
735
356
        EDataType ePhong = EDT_Char;
736
737
356
        unsigned int iOpacity = 0xFFFFFFFF;
738
356
        EDataType eOpacity = EDT_Char;
739
740
        // search in the DOM for a vertex entry
741
356
        unsigned int _i = 0;
742
356
        for (std::vector<Element>::const_iterator i = this->pcDOM->alElements.begin();
743
1.10k
                i != this->pcDOM->alElements.end(); ++i, ++_i) {
744
753
            if (EEST_Material == i->eSemantic) {
745
0
                pcList = &this->pcDOM->alElementData[_i];
746
747
                // now check whether which coordinate sets are available
748
0
                unsigned int _a = 0;
749
0
                for (std::vector<Property>::const_iterator a = i->alProperties.begin(); a != i->alProperties.end(); ++a, ++_a) {
750
0
                    if (a->bIsList) {
751
0
                        continue;
752
0
                    }
753
754
                    // pohng specularity      -----------------------------------
755
0
                    if (EST_PhongPower == (*a).Semantic) {
756
0
                        iPhong = _a;
757
0
                        ePhong = (*a).eType;
758
0
                    }
759
760
                    // general opacity        -----------------------------------
761
0
                    if (EST_Opacity == (*a).Semantic) {
762
0
                        iOpacity = _a;
763
0
                        eOpacity = (*a).eType;
764
0
                    }
765
766
                    // diffuse color channels -----------------------------------
767
0
                    if (EST_DiffuseRed == (*a).Semantic) {
768
0
                        aaiPositions[0][0] = _a;
769
0
                        aaiTypes[0][0] = (*a).eType;
770
0
                    } else if (EST_DiffuseGreen == (*a).Semantic) {
771
0
                        aaiPositions[0][1] = _a;
772
0
                        aaiTypes[0][1] = (*a).eType;
773
0
                    } else if (EST_DiffuseBlue == (*a).Semantic) {
774
0
                        aaiPositions[0][2] = _a;
775
0
                        aaiTypes[0][2] = (*a).eType;
776
0
                    } else if (EST_DiffuseAlpha == (*a).Semantic) {
777
0
                        aaiPositions[0][3] = _a;
778
0
                        aaiTypes[0][3] = (*a).eType;
779
0
                    }
780
                    // specular color channels -----------------------------------
781
0
                    else if (EST_SpecularRed == (*a).Semantic) {
782
0
                        aaiPositions[1][0] = _a;
783
0
                        aaiTypes[1][0] = (*a).eType;
784
0
                    } else if (EST_SpecularGreen == (*a).Semantic) {
785
0
                        aaiPositions[1][1] = _a;
786
0
                        aaiTypes[1][1] = (*a).eType;
787
0
                    } else if (EST_SpecularBlue == (*a).Semantic) {
788
0
                        aaiPositions[1][2] = _a;
789
0
                        aaiTypes[1][2] = (*a).eType;
790
0
                    } else if (EST_SpecularAlpha == (*a).Semantic) {
791
0
                        aaiPositions[1][3] = _a;
792
0
                        aaiTypes[1][3] = (*a).eType;
793
0
                    }
794
                    // ambient color channels -----------------------------------
795
0
                    else if (EST_AmbientRed == (*a).Semantic) {
796
0
                        aaiPositions[2][0] = _a;
797
0
                        aaiTypes[2][0] = (*a).eType;
798
0
                    } else if (EST_AmbientGreen == (*a).Semantic) {
799
0
                        aaiPositions[2][1] = _a;
800
0
                        aaiTypes[2][1] = (*a).eType;
801
0
                    } else if (EST_AmbientBlue == (*a).Semantic) {
802
0
                        aaiPositions[2][2] = _a;
803
0
                        aaiTypes[2][2] = (*a).eType;
804
0
                    } else if (EST_AmbientAlpha == (*a).Semantic) {
805
0
                        aaiPositions[2][3] = _a;
806
0
                        aaiTypes[2][3] = (*a).eType;
807
0
                    }
808
0
                }
809
0
                break;
810
753
            } else if (EEST_TextureFile == i->eSemantic) {
811
0
                defaultTexture = i->szName;
812
0
            }
813
753
        }
814
        // check whether we have a valid source for the material data
815
356
        if (nullptr != pcList) {
816
0
            for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin(); i != pcList->alInstances.end(); ++i) {
817
0
                aiColor4D clrOut;
818
0
                aiMaterial *pcHelper = new aiMaterial();
819
820
                // build the diffuse material color
821
0
                GetMaterialColor((*i).alProperties, aaiPositions[0], aaiTypes[0], &clrOut);
822
0
                pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_DIFFUSE);
823
824
                // build the specular material color
825
0
                GetMaterialColor((*i).alProperties, aaiPositions[1], aaiTypes[1], &clrOut);
826
0
                pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_SPECULAR);
827
828
                // build the ambient material color
829
0
                GetMaterialColor((*i).alProperties, aaiPositions[2], aaiTypes[2], &clrOut);
830
0
                pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_AMBIENT);
831
832
                // handle phong power and shading mode
833
0
                int iMode = aiShadingMode_Gouraud;
834
0
                if (0xFFFFFFFF != iPhong) {
835
0
                    ai_real fSpec = PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), ePhong);
836
837
                    // if shininess is 0 (and the pow() calculation would therefore always
838
                    // become 1, not depending on the angle), use gouraud lighting
839
0
                    if (fSpec) {
840
                        // scale this with 15 ... hopefully this is correct
841
0
                        fSpec *= 15;
842
0
                        pcHelper->AddProperty<ai_real>(&fSpec, 1, AI_MATKEY_SHININESS);
843
844
0
                        iMode = static_cast<int>(aiShadingMode_Phong);
845
0
                    }
846
0
                }
847
0
                pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
848
849
                // handle opacity
850
0
                if (0xFFFFFFFF != iOpacity) {
851
0
                    ai_real fOpacity = PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), eOpacity);
852
0
                    pcHelper->AddProperty<ai_real>(&fOpacity, 1, AI_MATKEY_OPACITY);
853
0
                }
854
855
                // The face order is absolutely undefined for PLY, so we have to
856
                // use two-sided rendering to be sure it's ok.
857
0
                const int two_sided = 1;
858
0
                pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
859
860
                // default texture
861
0
                if (!defaultTexture.empty()) {
862
0
                    const aiString name(defaultTexture.c_str());
863
0
                    pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
864
0
                }
865
866
0
                if (!pointsOnly) {
867
0
                    pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
868
0
                }
869
870
                // set to wireframe, so when using this material info we can switch to points rendering
871
0
                if (pointsOnly) {
872
0
                    constexpr int wireframe = 1;
873
0
                    pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
874
0
                }
875
876
                // add the newly created material instance to the list
877
0
                pvOut->push_back(pcHelper);
878
0
            }
879
356
        } else {
880
            // generate a default material
881
356
            aiMaterial *pcHelper = new aiMaterial();
882
883
            // fill in a default material
884
356
            int iMode = aiShadingMode_Gouraud;
885
356
            pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
886
887
            // generate white material most 3D engine just multiply ambient / diffuse color with actual ambient / light color
888
356
            aiColor3D clr;
889
356
            clr.b = clr.g = clr.r = 1.0f;
890
356
            pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
891
356
            pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
892
893
356
            clr.b = clr.g = clr.r = 1.0f;
894
356
            pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
895
896
            // The face order is absolutely undefined for PLY, so we have to
897
            // use two-sided rendering to be sure it's ok.
898
356
            if (!pointsOnly) {
899
131
                const int two_sided = 1;
900
131
                pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
901
131
            }
902
903
            // default texture
904
356
            if (!defaultTexture.empty()) {
905
0
                const aiString name(defaultTexture.c_str());
906
0
                pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
907
356
            } else {
908
356
                const aiString name(AI_DEFAULT_MATERIAL_NAME);
909
356
                pcHelper->AddProperty(&name, AI_MATKEY_NAME);
910
356
            }
911
912
            // set to wireframe, so when using this material info we can switch to points rendering
913
356
            if (pointsOnly) {
914
225
                constexpr int wireframe = 1;
915
225
                pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
916
225
            }
917
918
356
            pvOut->push_back(pcHelper);
919
356
        }
920
356
    }
921
922
} // namespace Assimp
923
924
#endif // !! ASSIMP_BUILD_NO_PLY_IMPORTER