Coverage Report

Created: 2026-11-12 07:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/SIB/SIBImporter.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  SIBImporter.cpp
43
 *  @brief Implementation of the SIB importer class.
44
 *
45
 *  The Nevercenter Silo SIB format is undocumented.
46
 *  All details here have been reverse engineered from
47
 *  studying the binary files output by Silo.
48
 *
49
 *  Nevertheless, this implementation is reasonably complete.
50
 */
51
52
#ifndef ASSIMP_BUILD_NO_SIB_IMPORTER
53
54
// internal headers
55
#include "SIBImporter.h"
56
#include <assimp/ByteSwapper.h>
57
#include <assimp/StreamReader.h>
58
#include <assimp/TinyFormatter.h>
59
#include "utf8.h"
60
#include <assimp/importerdesc.h>
61
#include <assimp/scene.h>
62
#include <assimp/DefaultLogger.hpp>
63
#include <assimp/IOSystem.hpp>
64
#include <assimp/StringUtils.h>
65
66
#include <map>
67
#include <cmath>
68
69
namespace Assimp {
70
71
static constexpr aiImporterDesc desc = {
72
    "Silo SIB Importer",
73
    "Richard Mitton (http://www.codersnotes.com/about)",
74
    "",
75
    "Does not apply subdivision.",
76
    aiImporterFlags_SupportBinaryFlavour,
77
    0, 0,
78
    0, 0,
79
    "sib"
80
};
81
82
struct SIBChunk {
83
    uint32_t Tag;
84
    uint32_t Size;
85
};
86
87
enum {
88
    POS,
89
    NRM,
90
    UV,
91
    N
92
};
93
94
using SIBPair = std::pair<uint32_t, uint32_t>;
95
96
struct SIBEdge {
97
    uint32_t faceA, faceB;
98
    bool creased;
99
};
100
101
struct SIBMesh {
102
    aiMatrix4x4 axis;
103
    uint32_t numPts;
104
    std::vector<aiVector3D> pos, nrm, uv;
105
    std::vector<uint32_t> idx;
106
    std::vector<uint32_t> faceStart;
107
    std::vector<uint32_t> mtls;
108
    std::vector<SIBEdge> edges;
109
    std::map<SIBPair, uint32_t> edgeMap;
110
};
111
112
struct SIBObject {
113
    aiString name;
114
    aiMatrix4x4 axis;
115
    size_t meshIdx, meshCount;
116
};
117
118
struct SIB {
119
    std::vector<aiMaterial *> mtls;
120
    std::vector<aiMesh *> meshes;
121
    std::vector<aiLight *> lights;
122
    std::vector<SIBObject> objs, insts;
123
124
0
    SIB() = default;
125
126
    // The lists above own their elements until they are handed over to the aiScene,
127
    // so a copy would hand the same pointers to two destructors.
128
    SIB(const SIB &) = delete;
129
    SIB &operator=(const SIB &) = delete;
130
0
    ~SIB() {
131
        // Anything still held here was not handed over to the aiScene, which happens
132
        // when parsing was aborted by an error.
133
0
        for (aiMaterial *mtl : mtls) {
134
0
            delete mtl;
135
0
        }
136
0
        for (aiMesh *mesh : meshes) {
137
0
            delete mesh;
138
0
        }
139
0
        for (aiLight *light : lights) {
140
0
            delete light;
141
0
        }
142
0
    }
143
};
144
145
// ------------------------------------------------------------------------------------------------
146
0
static SIBEdge &GetEdge(SIBMesh *mesh, uint32_t posA, uint32_t posB) {
147
0
    SIBPair pair = (posA < posB) ? SIBPair(posA, posB) : SIBPair(posB, posA);
148
0
    auto it = mesh->edgeMap.find(pair);
149
0
    if (it != mesh->edgeMap.end()) {
150
0
        return mesh->edges[it->second];
151
0
    }
152
153
0
    SIBEdge edge;
154
0
    edge.creased = false;
155
0
    edge.faceA = edge.faceB = 0xffffffff;
156
0
    mesh->edgeMap[pair] = static_cast<uint32_t>(mesh->edges.size());
157
0
    mesh->edges.push_back(edge);
158
0
    return mesh->edges.back();
159
0
}
160
161
// ------------------------------------------------------------------------------------------------
162
// Helpers for reading chunked data.
163
164
0
#define TAG(A, B, C, D) ((A << 24) | (B << 16) | (C << 8) | D)
165
166
0
static SIBChunk ReadChunk(StreamReaderLE *stream) {
167
0
    SIBChunk chunk;
168
0
    chunk.Tag = stream->GetU4();
169
0
    chunk.Size = stream->GetU4();
170
0
    if (chunk.Size > stream->GetRemainingSizeToLimit()) {
171
0
        ASSIMP_LOG_ERROR("SIB: Chunk overflow");
172
0
    }
173
0
    ByteSwap::Swap4(&chunk.Tag);
174
0
    return chunk;
175
0
}
176
177
0
static aiColor3D ReadColor(StreamReaderLE *stream) {
178
0
    float r = stream->GetF4();
179
0
    float g = stream->GetF4();
180
0
    float b = stream->GetF4();
181
0
    stream->GetU4(); // Colors have an unused(?) 4th component.
182
0
    return aiColor3D(r, g, b);
183
0
}
184
185
0
static void UnknownChunk(StreamReaderLE * /*stream*/, const SIBChunk &chunk) {
186
0
    char temp[4] = {
187
0
        static_cast<char>((chunk.Tag >> 24) & 0xff),
188
0
        static_cast<char>((chunk.Tag >> 16) & 0xff),
189
0
        static_cast<char>((chunk.Tag >> 8) & 0xff),
190
0
        static_cast<char>(chunk.Tag & 0xff)
191
0
    };
192
193
0
    ASSIMP_LOG_WARN("SIB: Skipping unknown '", ai_str_toprintable(temp, 4), "' chunk.");
194
0
}
195
196
// Reads a UTF-16LE string and returns it at UTF-8.
197
0
static aiString ReadString(StreamReaderLE *stream, uint32_t numWChars) {
198
0
    if (nullptr == stream || 0 == numWChars) {
199
0
        return aiString();
200
0
    }
201
202
    // Allocate buffers (max expansion is 1 byte -> 4 bytes for UTF-8)
203
0
    std::vector<unsigned char> str;
204
0
    str.reserve(numWChars * 4 + 1);
205
0
    uint16_t *temp = new uint16_t[numWChars];
206
0
    for (uint32_t n = 0; n < numWChars; ++n) {
207
0
        temp[n] = stream->GetU2();
208
0
    }
209
210
    // Convert it and NUL-terminate.
211
0
    const uint16_t *start(temp), *end(temp + numWChars);
212
0
    utf8::utf16to8(start, end, back_inserter(str));
213
0
    str[str.size() - 1] = '\0';
214
215
    // Return the final string.
216
0
    aiString result = aiString((const char *)&str[0]);
217
0
    delete[] temp;
218
219
0
    return result;
220
0
}
221
222
// ------------------------------------------------------------------------------------------------
223
// Returns whether the class can handle the format of the given file.
224
18.8k
bool SIBImporter::CanRead(const std::string &filename, IOSystem * /*pIOHandler*/, bool /*checkSig*/) const {
225
18.8k
    return SimpleExtensionCheck(filename, "sib");
226
18.8k
}
227
228
// ------------------------------------------------------------------------------------------------
229
161k
const aiImporterDesc *SIBImporter::GetInfo() const {
230
161k
    return &desc;
231
161k
}
232
233
// ------------------------------------------------------------------------------------------------
234
0
static void ReadVerts(SIBMesh *mesh, StreamReaderLE *stream, uint32_t count) {
235
0
    if (nullptr == mesh || nullptr == stream) {
236
0
        return;
237
0
    }
238
239
0
    mesh->pos.resize(count);
240
0
    for (uint32_t n = 0; n < count; ++n) {
241
0
        mesh->pos[n].x = stream->GetF4();
242
0
        mesh->pos[n].y = stream->GetF4();
243
0
        mesh->pos[n].z = stream->GetF4();
244
0
    }
245
0
}
246
247
// ------------------------------------------------------------------------------------------------
248
0
static void ReadFaces(SIBMesh *mesh, StreamReaderLE *stream) {
249
0
    uint32_t ptIdx = 0;
250
0
    while (stream->GetRemainingSizeToLimit() > 0) {
251
0
        uint32_t numPoints = stream->GetU4();
252
253
        // Every point of the face is stored as a single 4-byte index, so a face can
254
        // never have more points than the remaining chunk data can hold. Rejecting
255
        // larger counts here also keeps the index array size below the point where
256
        // numPoints * N would wrap around.
257
0
        if (numPoints == 0 || numPoints > stream->GetRemainingSizeToLimit() / 4) {
258
0
            throw DeadlyImportError("SIB: Invalid face point count.");
259
0
        }
260
261
        // Store room for the N index channels, plus the point count.
262
0
        const size_t pos = mesh->idx.size() + 1;
263
0
        mesh->idx.resize(pos + static_cast<size_t>(numPoints) * N);
264
0
        mesh->idx[pos - 1] = numPoints;
265
0
        uint32_t *idx = &mesh->idx[pos];
266
267
0
        mesh->faceStart.push_back(static_cast<uint32_t>(pos - 1));
268
0
        mesh->mtls.push_back(0);
269
270
        // Read all the position data.
271
        // UV/normals will be supplied later.
272
        // Positions are supplied indexed already, so we preserve that
273
        // mapping. UVs are supplied uniquely, so we allocate unique indices.
274
0
        for (uint32_t n = 0; n < numPoints; n++, idx += N, ptIdx++) {
275
0
            const uint32_t p = stream->GetU4();
276
0
            if (p >= mesh->pos.size()) {
277
0
                throw DeadlyImportError("Vertex index is out of range.");
278
0
            }
279
0
            idx[POS] = p;
280
0
            idx[NRM] = ptIdx;
281
0
            idx[UV] = ptIdx;
282
0
        }
283
0
    }
284
285
    // Allocate data channels for normals/UVs.
286
0
    mesh->nrm.resize(ptIdx, aiVector3D(0, 0, 0));
287
0
    mesh->uv.resize(ptIdx, aiVector3D(0, 0, 0));
288
289
0
    mesh->numPts = ptIdx;
290
0
}
291
292
// ------------------------------------------------------------------------------------------------
293
0
static void ReadUVs(SIBMesh *mesh, StreamReaderLE *stream) {
294
0
    while (stream->GetRemainingSizeToLimit() > 0) {
295
0
        const uint32_t faceIdx = stream->GetU4();
296
0
        const uint32_t numPoints = stream->GetU4();
297
298
0
        if (faceIdx >= mesh->faceStart.size()) {
299
0
            throw DeadlyImportError("Invalid face index.");
300
0
        }
301
302
0
        const uint32_t pos = mesh->faceStart[faceIdx];
303
304
        // mesh->idx[pos] holds the number of points the face was built with in ReadFaces(). A UV chunk that claims
305
        // more points than that would walk idx past the end of the face's index data and off the end of 
306
        // mesh->idx entirely, so reject it.
307
0
        if (numPoints > mesh->idx[pos]) {
308
0
            throw DeadlyImportError("SIB: UV point count exceeds face point count.");
309
0
        }
310
311
0
        uint32_t *idx = &mesh->idx[pos + 1];
312
313
0
        for (uint32_t n = 0; n < numPoints; n++, idx += N) {
314
0
            uint32_t id = idx[UV];
315
0
            mesh->uv[id].x = stream->GetF4();
316
0
            mesh->uv[id].y = stream->GetF4();
317
0
        }
318
0
    }
319
0
}
320
321
// ------------------------------------------------------------------------------------------------
322
0
static void ReadMtls(SIBMesh *mesh, StreamReaderLE *stream) {
323
    // Material assignments are stored run-length encoded.
324
    // Also, we add 1 to each material so that we can use mtl #0
325
    // as the default material.
326
0
    uint32_t prevFace = stream->GetU4();
327
0
    uint32_t prevMtl = stream->GetU4() + 1;
328
0
    while (stream->GetRemainingSizeToLimit() > 0) {
329
0
        const uint32_t face = stream->GetU4();
330
0
        const uint32_t mtl = stream->GetU4() + 1;
331
0
        while (prevFace < face) {
332
0
            if (prevFace >= mesh->mtls.size()) {
333
0
                throw DeadlyImportError("Invalid face index.");
334
0
            }
335
0
            mesh->mtls[prevFace++] = prevMtl;
336
0
        }
337
338
0
        prevFace = face;
339
0
        prevMtl = mtl;
340
0
    }
341
342
0
    while (prevFace < mesh->mtls.size()) {
343
0
        mesh->mtls[prevFace++] = prevMtl;
344
0
    }
345
0
}
346
347
// ------------------------------------------------------------------------------------------------
348
0
static void ReadAxis(aiMatrix4x4 &axis, StreamReaderLE *stream) {
349
0
    axis.a4 = stream->GetF4();
350
0
    axis.b4 = stream->GetF4();
351
0
    axis.c4 = stream->GetF4();
352
0
    axis.d4 = 1;
353
0
    axis.a1 = stream->GetF4();
354
0
    axis.b1 = stream->GetF4();
355
0
    axis.c1 = stream->GetF4();
356
0
    axis.d1 = 0;
357
0
    axis.a2 = stream->GetF4();
358
0
    axis.b2 = stream->GetF4();
359
0
    axis.c2 = stream->GetF4();
360
0
    axis.d2 = 0;
361
0
    axis.a3 = stream->GetF4();
362
0
    axis.b3 = stream->GetF4();
363
0
    axis.c3 = stream->GetF4();
364
0
    axis.d3 = 0;
365
0
}
366
367
// ------------------------------------------------------------------------------------------------
368
0
static void ReadEdges(SIBMesh *mesh, StreamReaderLE *stream) {
369
0
    while (stream->GetRemainingSizeToLimit() > 0) {
370
0
        const uint32_t posA = stream->GetU4();
371
0
        const uint32_t posB = stream->GetU4();
372
0
        GetEdge(mesh, posA, posB);
373
0
    }
374
0
}
375
376
// ------------------------------------------------------------------------------------------------
377
0
static void ReadCreases(SIBMesh *mesh, StreamReaderLE *stream) {
378
0
    while (stream->GetRemainingSizeToLimit() > 0) {
379
0
        const uint32_t edge = stream->GetU4();
380
0
        if (edge >= mesh->edges.size()) {
381
0
            throw DeadlyImportError("SIB: Invalid edge index.");
382
0
        }
383
0
        mesh->edges[edge].creased = true;
384
0
    }
385
0
}
386
387
// ------------------------------------------------------------------------------------------------
388
0
static void ConnectFaces(SIBMesh *mesh) {
389
    // Find faces connected to each edge.
390
0
    const size_t numFaces = mesh->faceStart.size();
391
0
    for (size_t faceIdx = 0; faceIdx < numFaces; faceIdx++) {
392
0
        uint32_t *idx = &mesh->idx[mesh->faceStart[faceIdx]];
393
0
        const uint32_t numPoints = *idx++;
394
0
        uint32_t prev = idx[(numPoints - 1) * N + POS];
395
396
0
        for (uint32_t i = 0; i < numPoints; i++, idx += N) {
397
0
            uint32_t next = idx[POS];
398
399
            // Find this edge.
400
0
            SIBEdge &edge = GetEdge(mesh, prev, next);
401
402
            // Link this face onto it.
403
            // This gives potentially undesirable normals when used
404
            // with non-2-manifold surfaces, but then so does Silo to begin with.
405
0
            if (edge.faceA == 0xffffffff) {
406
0
                edge.faceA = static_cast<uint32_t>(faceIdx);
407
0
            } else if (edge.faceB == 0xffffffff) {
408
0
                edge.faceB = static_cast<uint32_t>(faceIdx);
409
0
            }
410
0
            prev = next;
411
0
        }
412
0
    }
413
0
}
414
415
// ------------------------------------------------------------------------------------------------
416
static aiVector3D CalculateVertexNormal(SIBMesh *mesh, uint32_t faceIdx, uint32_t pos,
417
0
        const std::vector<aiVector3D> &faceNormals) {
418
    // Creased edges complicate this. We need to find the start/end range of the
419
    // ring of faces that touch this position.
420
    // We do this in two passes. The first pass is to find the end of the range,
421
    // the second is to work backwards to the start and calculate the final normal.
422
0
    aiVector3D vtxNormal;
423
0
    for (int pass = 0; pass < 2; pass++) {
424
0
        vtxNormal = aiVector3D(0, 0, 0);
425
0
        uint32_t startFaceIdx = faceIdx;
426
0
        uint32_t prevFaceIdx = faceIdx;
427
428
        // Process each connected face.
429
0
        while (true) {
430
            // Accumulate the face normal.
431
0
            vtxNormal += faceNormals[faceIdx];
432
433
0
            uint32_t nextFaceIdx = 0xffffffff;
434
435
            // Move to the next edge sharing this position.
436
0
            uint32_t *idx = &mesh->idx[mesh->faceStart[faceIdx]];
437
0
            uint32_t numPoints = *idx++;
438
0
            uint32_t posA = idx[(numPoints - 1) * N + POS];
439
0
            for (uint32_t n = 0; n < numPoints; n++, idx += N) {
440
0
                uint32_t posB = idx[POS];
441
442
                // Test if this edge shares our target position.
443
0
                if (posA == pos || posB == pos) {
444
0
                    SIBEdge &edge = GetEdge(mesh, posA, posB);
445
446
                    // Non-manifold meshes can produce faces which share
447
                    // positions but have no edge entry, so check it.
448
0
                    if (edge.faceA == faceIdx || edge.faceB == faceIdx) {
449
                        // Move to whichever side we didn't just come from.
450
0
                        if (!edge.creased) {
451
0
                            if (edge.faceA != prevFaceIdx && edge.faceA != faceIdx && edge.faceA != 0xffffffff) {
452
0
                                nextFaceIdx = edge.faceA;
453
0
                            } else if (edge.faceB != prevFaceIdx && edge.faceB != faceIdx && edge.faceB != 0xffffffff) {
454
0
                                nextFaceIdx = edge.faceB;
455
0
                            }
456
0
                        }
457
0
                    }
458
0
                }
459
460
0
                posA = posB;
461
0
            }
462
463
            // Stop once we hit either an creased/unconnected edge, or we
464
            // wrapped around and hit our start point.
465
0
            if (nextFaceIdx == 0xffffffff || nextFaceIdx == startFaceIdx) {
466
0
                break;
467
0
            }
468
469
0
            prevFaceIdx = faceIdx;
470
0
            faceIdx = nextFaceIdx;
471
0
        }
472
0
    }
473
474
    // Normalize it.
475
0
    const float len = vtxNormal.Length();
476
0
    if (std::fpclassify(len) > FP_ZERO) {
477
0
        vtxNormal /= len;
478
0
    }
479
    
480
0
    return vtxNormal;
481
0
}
482
483
// ------------------------------------------------------------------------------------------------
484
0
static void CalculateNormals(SIBMesh *mesh) {
485
0
    const size_t numFaces = mesh->faceStart.size();
486
487
    // Calculate face normals.
488
0
    std::vector<aiVector3D> faceNormals(numFaces);
489
0
    for (size_t faceIdx = 0; faceIdx < numFaces; faceIdx++) {
490
0
        uint32_t *idx = &mesh->idx[mesh->faceStart[faceIdx]];
491
0
        const uint32_t numPoints = *idx++;
492
493
0
        aiVector3D faceNormal(0, 0, 0);
494
495
0
        uint32_t *prev = &idx[(numPoints - 1) * N];
496
497
0
        for (uint32_t i = 0; i < numPoints; i++) {
498
0
            uint32_t *next = &idx[i * N];
499
500
0
            faceNormal += mesh->pos[prev[POS]] ^ mesh->pos[next[POS]];
501
0
            prev = next;
502
0
        }
503
504
0
        faceNormals[faceIdx] = faceNormal;
505
0
    }
506
507
    // Calculate vertex normals.
508
0
    for (size_t faceIdx = 0; faceIdx < numFaces; faceIdx++) {
509
0
        uint32_t *idx = &mesh->idx[mesh->faceStart[faceIdx]];
510
0
        const uint32_t numPoints = *idx++;
511
512
0
        for (uint32_t i = 0; i < numPoints; i++) {
513
0
            uint32_t pos = idx[i * N + POS];
514
0
            uint32_t nrm = idx[i * N + NRM];
515
0
            aiVector3D vtxNorm = CalculateVertexNormal(mesh, static_cast<uint32_t>(faceIdx), pos, faceNormals);
516
0
            mesh->nrm[nrm] = vtxNorm;
517
0
        }
518
0
    }
519
0
}
520
521
// ------------------------------------------------------------------------------------------------
522
struct TempMesh {
523
    std::vector<aiVector3D> vtx;
524
    std::vector<aiVector3D> nrm;
525
    std::vector<aiVector3D> uv;
526
    std::vector<aiFace> faces;
527
};
528
529
0
static void ReadShape(SIB *sib, StreamReaderLE *stream) {
530
0
    SIBMesh smesh;
531
0
    aiString name;
532
533
0
    while (stream->GetRemainingSizeToLimit() >= sizeof(SIBChunk)) {
534
0
        SIBChunk chunk = ReadChunk(stream);
535
0
        unsigned oldLimit = stream->SetReadLimit(stream->GetCurrentPos() + chunk.Size);
536
537
0
        switch (chunk.Tag) {
538
0
            case TAG('M', 'I', 'R', 'P'): break; // mirror plane maybe?
539
0
            case TAG('I', 'M', 'R', 'P'): break; // instance mirror? (not supported here yet)
540
0
            case TAG('D', 'I', 'N', 'F'): break; // display info, not needed
541
0
            case TAG('P', 'I', 'N', 'F'): break; // ?
542
0
            case TAG('V', 'M', 'I', 'R'): break; // ?
543
0
            case TAG('F', 'M', 'I', 'R'): break; // ?
544
0
            case TAG('T', 'X', 'S', 'M'): break; // ?
545
0
            case TAG('F', 'A', 'H', 'S'): break; // ?
546
0
            case TAG('V', 'R', 'T', 'S'): ReadVerts(&smesh, stream, chunk.Size / 12); break;
547
0
            case TAG('F', 'A', 'C', 'S'): ReadFaces(&smesh, stream); break;
548
0
            case TAG('F', 'T', 'V', 'S'): ReadUVs(&smesh, stream); break;
549
0
            case TAG('S', 'N', 'A', 'M'): name = ReadString(stream, chunk.Size / 2); break;
550
0
            case TAG('F', 'A', 'M', 'A'): ReadMtls(&smesh, stream); break;
551
0
            case TAG('A', 'X', 'I', 'S'): ReadAxis(smesh.axis, stream); break;
552
0
            case TAG('E', 'D', 'G', 'S'): ReadEdges(&smesh, stream); break;
553
0
            case TAG('E', 'C', 'R', 'S'): ReadCreases(&smesh, stream); break;
554
0
            default: UnknownChunk(stream, chunk); break;
555
0
        }
556
557
0
        stream->SetCurrentPos(stream->GetReadLimit());
558
0
        stream->SetReadLimit(oldLimit);
559
0
    }
560
561
0
    ai_assert(smesh.faceStart.size() == smesh.mtls.size()); // sanity check
562
563
    // Silo doesn't store any normals in the file - we need to compute
564
    // them ourselves. We can't let AssImp handle it as AssImp doesn't
565
    // know about our creased edges.
566
0
    ConnectFaces(&smesh);
567
0
    CalculateNormals(&smesh);
568
569
    // Construct the transforms.
570
0
    aiMatrix4x4 worldToLocal = smesh.axis;
571
0
    worldToLocal.Inverse();
572
0
    aiMatrix4x4 worldToLocalN = worldToLocal;
573
0
    worldToLocalN.a4 = worldToLocalN.b4 = worldToLocalN.c4 = 0.0f;
574
0
    worldToLocalN.Inverse().Transpose();
575
576
    // Allocate final mesh data.
577
    // We'll allocate one mesh for each material. (we'll strip unused ones after)
578
0
    std::vector<TempMesh> meshes(sib->mtls.size());
579
580
    // Un-index the source data and apply to each vertex.
581
0
    for (unsigned fi = 0; fi < smesh.faceStart.size(); fi++) {
582
0
        uint32_t start = smesh.faceStart[fi];
583
0
        uint32_t mtl = smesh.mtls[fi];
584
0
        uint32_t *idx = &smesh.idx[start];
585
586
0
        if (mtl >= meshes.size()) {
587
0
            ASSIMP_LOG_ERROR("SIB: Face material index is invalid.");
588
0
            mtl = 0;
589
0
        }
590
591
0
        TempMesh &dest = meshes[mtl];
592
593
0
        aiFace face;
594
0
        face.mNumIndices = *idx++;
595
0
        face.mIndices = new unsigned[face.mNumIndices];
596
0
        for (unsigned pt = 0; pt < face.mNumIndices; pt++, idx += N) {
597
0
            size_t vtxIdx = dest.vtx.size();
598
0
            face.mIndices[pt] = static_cast<unsigned int>(vtxIdx);
599
600
            // De-index it. We don't need to validate here as
601
            // we did it when creating the data.
602
0
            aiVector3D pos = smesh.pos[idx[POS]];
603
0
            aiVector3D nrm = smesh.nrm[idx[NRM]];
604
0
            aiVector3D uv = smesh.uv[idx[UV]];
605
606
            // The verts are supplied in world-space, so let's
607
            // transform them back into the local space of this mesh:
608
0
            pos = worldToLocal * pos;
609
0
            nrm = worldToLocalN * nrm;
610
611
0
            dest.vtx.push_back(pos);
612
0
            dest.nrm.push_back(nrm);
613
0
            dest.uv.push_back(uv);
614
0
        }
615
0
        dest.faces.push_back(face);
616
0
    }
617
618
0
    SIBObject obj;
619
0
    obj.name = name;
620
0
    obj.axis = smesh.axis;
621
0
    obj.meshIdx = sib->meshes.size();
622
623
    // Now that we know the size of everything,
624
    // we can build the final one-material-per-mesh data.
625
0
    for (size_t n = 0; n < meshes.size(); n++) {
626
0
        TempMesh &src = meshes[n];
627
0
        if (src.faces.empty()) {
628
0
            continue;
629
0
        }
630
631
0
        aiMesh *mesh = new aiMesh;
632
0
        mesh->mName = name;
633
0
        mesh->mNumFaces = static_cast<unsigned int>(src.faces.size());
634
0
        mesh->mFaces = new aiFace[mesh->mNumFaces];
635
0
        mesh->mNumVertices = static_cast<unsigned int>(src.vtx.size());
636
0
        mesh->mVertices = new aiVector3D[mesh->mNumVertices];
637
0
        mesh->mNormals = new aiVector3D[mesh->mNumVertices];
638
0
        mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
639
0
        mesh->mNumUVComponents[0] = 2;
640
0
        mesh->mMaterialIndex = static_cast<unsigned int>(n);
641
642
0
        for (unsigned i = 0; i < mesh->mNumVertices; i++) {
643
0
            mesh->mVertices[i] = src.vtx[i];
644
0
            mesh->mNormals[i] = src.nrm[i];
645
0
            mesh->mTextureCoords[0][i] = src.uv[i];
646
0
        }
647
0
        for (unsigned i = 0; i < mesh->mNumFaces; i++) {
648
0
            mesh->mFaces[i] = src.faces[i];
649
0
        }
650
651
0
        sib->meshes.push_back(mesh);
652
0
    }
653
654
0
    obj.meshCount = sib->meshes.size() - obj.meshIdx;
655
0
    sib->objs.push_back(obj);
656
0
}
657
658
// ------------------------------------------------------------------------------------------------
659
0
static void ReadMaterial(SIB *sib, StreamReaderLE *stream) {
660
0
    aiColor3D diff = ReadColor(stream);
661
0
    aiColor3D ambi = ReadColor(stream);
662
0
    aiColor3D spec = ReadColor(stream);
663
0
    aiColor3D emis = ReadColor(stream);
664
0
    float shiny = static_cast<float>(stream->GetU4());
665
666
0
    uint32_t nameLen = stream->GetU4();
667
0
    aiString name = ReadString(stream, nameLen / 2);
668
0
    uint32_t texLen = stream->GetU4();
669
0
    aiString tex = ReadString(stream, texLen / 2);
670
671
0
    aiMaterial *mtl = new aiMaterial();
672
0
    mtl->AddProperty(&diff, 1, AI_MATKEY_COLOR_DIFFUSE);
673
0
    mtl->AddProperty(&ambi, 1, AI_MATKEY_COLOR_AMBIENT);
674
0
    mtl->AddProperty(&spec, 1, AI_MATKEY_COLOR_SPECULAR);
675
0
    mtl->AddProperty(&emis, 1, AI_MATKEY_COLOR_EMISSIVE);
676
0
    mtl->AddProperty(&shiny, 1, AI_MATKEY_SHININESS);
677
0
    mtl->AddProperty(&name, AI_MATKEY_NAME);
678
0
    if (tex.length > 0) {
679
0
        mtl->AddProperty(&tex, AI_MATKEY_TEXTURE_DIFFUSE(0));
680
0
        mtl->AddProperty(&tex, AI_MATKEY_TEXTURE_AMBIENT(0));
681
0
    }
682
683
0
    sib->mtls.push_back(mtl);
684
0
}
685
686
// ------------------------------------------------------------------------------------------------
687
0
static void ReadLightInfo(aiLight *light, StreamReaderLE *stream) {
688
0
    uint32_t type = stream->GetU4();
689
0
    switch (type) {
690
0
        case 0: light->mType = aiLightSource_POINT; break;
691
0
        case 1: light->mType = aiLightSource_SPOT; break;
692
0
        case 2: light->mType = aiLightSource_DIRECTIONAL; break;
693
0
        default: light->mType = aiLightSource_UNDEFINED; break;
694
0
    }
695
696
0
    light->mPosition.x = stream->GetF4();
697
0
    light->mPosition.y = stream->GetF4();
698
0
    light->mPosition.z = stream->GetF4();
699
0
    light->mDirection.x = stream->GetF4();
700
0
    light->mDirection.y = stream->GetF4();
701
0
    light->mDirection.z = stream->GetF4();
702
0
    light->mColorDiffuse = ReadColor(stream);
703
0
    light->mColorAmbient = ReadColor(stream);
704
0
    light->mColorSpecular = ReadColor(stream);
705
0
    ai_real spotExponent = stream->GetF4();
706
0
    ai_real spotCutoff = stream->GetF4();
707
0
    light->mAttenuationConstant = stream->GetF4();
708
0
    light->mAttenuationLinear = stream->GetF4();
709
0
    light->mAttenuationQuadratic = stream->GetF4();
710
711
    // Silo uses the OpenGL default lighting model for it's
712
    // spot cutoff/exponent. AssImp unfortunately, does not.
713
    // Let's try and approximate it by solving for the
714
    // 99% and 1% percentiles.
715
    //    OpenGL: I = cos(angle)^E
716
    //   Solving: angle = acos(I^(1/E))
717
0
    ai_real E = ai_real(1.0) / std::max(spotExponent, (ai_real)0.00001);
718
0
    ai_real inner = std::acos(std::pow((ai_real)0.99, E));
719
0
    ai_real outer = std::acos(std::pow((ai_real)0.01, E));
720
721
    // Apply the cutoff.
722
0
    outer = std::min(outer, AI_DEG_TO_RAD(spotCutoff));
723
724
0
    light->mAngleInnerCone = std::min(inner, outer);
725
0
    light->mAngleOuterCone = outer;
726
0
}
727
728
0
static void ReadLight(SIB *sib, StreamReaderLE *stream) {
729
0
    aiLight *light = new aiLight();
730
731
0
    while (stream->GetRemainingSizeToLimit() >= sizeof(SIBChunk)) {
732
0
        SIBChunk chunk = ReadChunk(stream);
733
0
        unsigned oldLimit = stream->SetReadLimit(stream->GetCurrentPos() + chunk.Size);
734
735
0
        switch (chunk.Tag) {
736
0
            case TAG('L', 'N', 'F', 'O'): ReadLightInfo(light, stream); break;
737
0
            case TAG('S', 'N', 'A', 'M'): light->mName = ReadString(stream, chunk.Size / 2); break;
738
0
            default: UnknownChunk(stream, chunk); break;
739
0
        }
740
741
0
        stream->SetCurrentPos(stream->GetReadLimit());
742
0
        stream->SetReadLimit(oldLimit);
743
0
    }
744
745
0
    sib->lights.push_back(light);
746
0
}
747
748
// ------------------------------------------------------------------------------------------------
749
0
static void ReadScale(aiMatrix4x4 &axis, StreamReaderLE *stream) {
750
0
    aiMatrix4x4 scale;
751
0
    scale.a1 = stream->GetF4();
752
0
    scale.b1 = stream->GetF4();
753
0
    scale.c1 = stream->GetF4();
754
0
    scale.d1 = stream->GetF4();
755
0
    scale.a2 = stream->GetF4();
756
0
    scale.b2 = stream->GetF4();
757
0
    scale.c2 = stream->GetF4();
758
0
    scale.d2 = stream->GetF4();
759
0
    scale.a3 = stream->GetF4();
760
0
    scale.b3 = stream->GetF4();
761
0
    scale.c3 = stream->GetF4();
762
0
    scale.d3 = stream->GetF4();
763
0
    scale.a4 = stream->GetF4();
764
0
    scale.b4 = stream->GetF4();
765
0
    scale.c4 = stream->GetF4();
766
0
    scale.d4 = stream->GetF4();
767
768
0
    axis = axis * scale;
769
0
}
770
771
0
static void ReadInstance(SIB *sib, StreamReaderLE *stream) {
772
0
    SIBObject inst;
773
0
    uint32_t shapeIndex = 0;
774
775
0
    while (stream->GetRemainingSizeToLimit() >= sizeof(SIBChunk)) {
776
0
        SIBChunk chunk = ReadChunk(stream);
777
0
        unsigned oldLimit = stream->SetReadLimit(stream->GetCurrentPos() + chunk.Size);
778
779
0
        switch (chunk.Tag) {
780
0
            case TAG('D', 'I', 'N', 'F'): break; // display info, not needed
781
0
            case TAG('P', 'I', 'N', 'F'): break; // ?
782
0
            case TAG('A', 'X', 'I', 'S'): ReadAxis(inst.axis, stream); break;
783
0
            case TAG('I', 'N', 'S', 'I'): shapeIndex = stream->GetU4(); break;
784
0
            case TAG('S', 'M', 'T', 'X'): ReadScale(inst.axis, stream); break;
785
0
            case TAG('S', 'N', 'A', 'M'): inst.name = ReadString(stream, chunk.Size / 2); break;
786
0
            default: UnknownChunk(stream, chunk); break;
787
0
        }
788
789
0
        stream->SetCurrentPos(stream->GetReadLimit());
790
0
        stream->SetReadLimit(oldLimit);
791
0
    }
792
793
0
    if (shapeIndex >= sib->objs.size()) {
794
0
        throw DeadlyImportError("SIB: Invalid shape index.");
795
0
    }
796
797
0
    const SIBObject &src = sib->objs[shapeIndex];
798
0
    inst.meshIdx = src.meshIdx;
799
0
    inst.meshCount = src.meshCount;
800
0
    sib->insts.push_back(inst);
801
0
}
802
803
// ------------------------------------------------------------------------------------------------
804
0
static void CheckVersion(StreamReaderLE *stream) {
805
0
    uint32_t version = stream->GetU4();
806
0
    if (version < 1 || version > 2) {
807
0
        throw DeadlyImportError("SIB: Unsupported file version.");
808
0
    }
809
0
}
810
811
0
static void ReadScene(SIB *sib, StreamReaderLE *stream) {
812
    // Parse each chunk in turn.
813
0
    while (stream->GetRemainingSizeToLimit() >= sizeof(SIBChunk)) {
814
0
        SIBChunk chunk = ReadChunk(stream);
815
0
        unsigned oldLimit = stream->SetReadLimit(stream->GetCurrentPos() + chunk.Size);
816
817
0
        switch (chunk.Tag) {
818
0
            case TAG('H', 'E', 'A', 'D'): CheckVersion(stream); break;
819
0
            case TAG('S', 'H', 'A', 'P'): ReadShape(sib, stream); break;
820
0
            case TAG('G', 'R', 'P', 'S'): break; // group assignment, we don't import this
821
0
            case TAG('T', 'E', 'X', 'P'): break; // ?
822
0
            case TAG('I', 'N', 'S', 'T'): ReadInstance(sib, stream); break;
823
0
            case TAG('M', 'A', 'T', 'R'): ReadMaterial(sib, stream); break;
824
0
            case TAG('L', 'G', 'H', 'T'): ReadLight(sib, stream); break;
825
0
            default: UnknownChunk(stream, chunk); break;
826
0
        }
827
828
0
        stream->SetCurrentPos(stream->GetReadLimit());
829
0
        stream->SetReadLimit(oldLimit);
830
0
    }
831
0
}
832
833
// ------------------------------------------------------------------------------------------------
834
// Imports the given file into the given scene structure.
835
0
void SIBImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
836
0
    auto file = pIOHandler->Open(pFile, "rb");
837
0
    if (!file) {
838
0
        throw DeadlyImportError("SIB: Could not open ", pFile);
839
0
    }
840
841
0
    StreamReaderLE stream(file);
842
843
    // We should have at least one chunk
844
0
    if (stream.GetRemainingSize() < 16) {
845
0
        throw DeadlyImportError("SIB file is either empty or corrupt: ", pFile);
846
0
    }
847
848
0
    SIB sib;
849
850
    // Default material.
851
0
    aiMaterial *defmtl = new aiMaterial;
852
0
    aiString defname = aiString(AI_DEFAULT_MATERIAL_NAME);
853
0
    defmtl->AddProperty(&defname, AI_MATKEY_NAME);
854
0
    sib.mtls.push_back(defmtl);
855
856
    // Read it all.
857
0
    ReadScene(&sib, &stream);
858
859
    // Join the instances and objects together.
860
0
    size_t firstInst = sib.objs.size();
861
0
    sib.objs.insert(sib.objs.end(), sib.insts.begin(), sib.insts.end());
862
0
    sib.insts.clear();
863
864
    // Transfer to the aiScene.
865
0
    pScene->mNumMaterials = static_cast<unsigned int>(sib.mtls.size());
866
0
    pScene->mNumMeshes = static_cast<unsigned int>(sib.meshes.size());
867
0
    pScene->mNumLights = static_cast<unsigned int>(sib.lights.size());
868
0
    pScene->mMaterials = pScene->mNumMaterials ? new aiMaterial *[pScene->mNumMaterials] : nullptr;
869
0
    pScene->mMeshes = pScene->mNumMeshes ? new aiMesh *[pScene->mNumMeshes] : nullptr;
870
0
    pScene->mLights = pScene->mNumLights ? new aiLight *[pScene->mNumLights] : nullptr;
871
0
    if (pScene->mNumMaterials) {
872
0
        memcpy(pScene->mMaterials, &sib.mtls[0], sizeof(aiMaterial *) * pScene->mNumMaterials);
873
0
    }
874
0
    if (pScene->mNumMeshes) {
875
0
        memcpy(pScene->mMeshes, &sib.meshes[0], sizeof(aiMesh *) * pScene->mNumMeshes);
876
0
    }
877
0
    if (pScene->mNumLights) {
878
0
        memcpy(pScene->mLights, &sib.lights[0], sizeof(aiLight *) * pScene->mNumLights);
879
0
    }
880
881
    // The scene owns them now, so make sure they are not deleted twice. The light list
882
    // is still needed below and is released after the nodes have been built.
883
0
    sib.mtls.clear();
884
0
    sib.meshes.clear();
885
886
    // The scene owns them now, so make sure they are not deleted twice. The light list
887
    // is still needed below and is released after the nodes have been built.
888
0
    sib.mtls.clear();
889
0
    sib.meshes.clear();
890
891
    // Construct the root node.
892
0
    size_t childIdx = 0;
893
0
    aiNode *root = new aiNode();
894
0
    root->mName.Set("<SIBRoot>");
895
0
    root->mNumChildren = static_cast<unsigned int>(sib.objs.size() + sib.lights.size());
896
0
    root->mChildren = root->mNumChildren ? new aiNode *[root->mNumChildren] : nullptr;
897
0
    pScene->mRootNode = root;
898
899
    // Add nodes for each object.
900
0
    for (size_t n = 0; n < sib.objs.size(); n++) {
901
0
        ai_assert(root->mChildren);
902
0
        SIBObject &obj = sib.objs[n];
903
0
        aiNode *node = new aiNode;
904
0
        root->mChildren[childIdx++] = node;
905
0
        node->mName = obj.name;
906
0
        node->mParent = root;
907
0
        node->mTransformation = obj.axis;
908
909
0
        node->mNumMeshes = static_cast<unsigned int>(obj.meshCount);
910
0
        node->mMeshes = node->mNumMeshes ? new unsigned[node->mNumMeshes] : nullptr;
911
0
        for (unsigned i = 0; i < node->mNumMeshes; i++) {
912
0
            node->mMeshes[i] = static_cast<unsigned int>(obj.meshIdx + i);
913
0
        }
914
915
        // Mark instanced objects as being so.
916
0
        if (n >= firstInst) {
917
0
            node->mMetaData = aiMetadata::Alloc(1);
918
0
            node->mMetaData->Set(0, "IsInstance", true);
919
0
        }
920
0
    }
921
922
    // Add nodes for each light.
923
    // (no transformation as the light is already in world space)
924
0
    for (size_t n = 0; n < sib.lights.size(); n++) {
925
0
        ai_assert(root->mChildren);
926
0
        aiLight *light = sib.lights[n];
927
0
        if (nullptr != light) {
928
0
            aiNode *node = new aiNode;
929
0
            root->mChildren[childIdx++] = node;
930
0
            node->mName = light->mName;
931
0
            node->mParent = root;
932
0
        }
933
0
    }
934
935
0
    sib.lights.clear();
936
0
}
937
938
} // namespace Assimp
939
940
#endif // !! ASSIMP_BUILD_NO_SIB_IMPORTER