Repository navigation
Expand file tree
/
Copy pathscene.cpp
More file actions
829 lines (709 loc) · 25.5 KB
/
Copy pathscene.cpp
File metadata and controls
829 lines (709 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/*
* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2021-2025 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <filesystem>
#include <functional>
#include <assert.h>
#include <glm/gtc/type_ptr.hpp>
#include <cgltf.h>
#include <nvutils/file_mapping.hpp>
#include "scene.hpp"
#define USE_CACHECOMBINE 1
namespace {
struct FileMappingList
{
struct Entry
{
nvutils::FileReadMapping mapping;
int64_t refCount = 1;
};
std::unordered_map<std::string, Entry> m_nameToMapping;
std::unordered_map<const void*, std::string> m_dataToName;
#ifndef NDEBUG
int64_t m_openBias = 0;
#endif
bool open(const char* path, size_t* size, void** data)
{
#ifndef NDEBUG
m_openBias++;
#endif
std::string pathStr(path);
auto it = m_nameToMapping.find(pathStr);
if(it != m_nameToMapping.end())
{
*data = const_cast<void*>(it->second.mapping.data());
*size = it->second.mapping.size();
it->second.refCount++;
return true;
}
Entry entry;
if(entry.mapping.open(path))
{
const void* mappingData = entry.mapping.data();
*data = const_cast<void*>(mappingData);
*size = entry.mapping.size();
m_dataToName.insert({mappingData, pathStr});
m_nameToMapping.insert({pathStr, std::move(entry)});
return true;
}
return false;
}
void close(void* data)
{
#ifndef NDEBUG
m_openBias--;
#endif
auto itName = m_dataToName.find(data);
if(itName != m_dataToName.end())
{
auto itMapping = m_nameToMapping.find(itName->second);
if(itMapping != m_nameToMapping.end())
{
itMapping->second.refCount--;
if(!itMapping->second.refCount)
{
m_nameToMapping.erase(itMapping);
m_dataToName.erase(itName);
}
}
}
}
~FileMappingList()
{
#ifndef NDEBUG
assert(m_openBias == 0 && "open/close bias wrong");
#endif
assert(m_nameToMapping.empty() && m_dataToName.empty() && "not all opened files were closed");
}
};
cgltf_result map_cgltf(const struct cgltf_memory_options* memory_options,
const struct cgltf_file_options* file_options,
const char* path,
cgltf_size* size,
void** data)
{
FileMappingList* mappings = (FileMappingList*)file_options->user_data;
if(mappings->open(path, size, data))
{
return cgltf_result_success;
}
return cgltf_result_io_error;
}
void unmap_cgltf(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data)
{
FileMappingList* mappings = (FileMappingList*)file_options->user_data;
mappings->close(data);
}
// Defines a unique_ptr that can be used for cgltf_data objects.
// Freeing a unique_cgltf_ptr calls cgltf_free, instead of delete.
// This can be constructed using unique_cgltf_ptr foo(..., &cgltf_free).
using unique_cgltf_ptr = std::unique_ptr<cgltf_data, decltype(&cgltf_free)>;
} // anonymous namespace
glm::vec4 randomVector(float from, float to)
{
glm::vec4 vec;
float width = to - from;
for(int i = 0; i < 4; i++)
{
vec[i] = from + (float(rand()) / float(RAND_MAX)) * width;
}
return vec;
}
// all oct functions derived from "A Survey of Efficient Representations for Independent Unit Vectors"
// http://jcgt.org/published/0003/02/01/paper.pdf
// Returns +/- 1
inline glm::vec3 oct_signNotZero(glm::vec3 v)
{
// leaves z as is
return glm::vec3((v.x >= 0.0f) ? +1.0f : -1.0f, (v.y >= 0.0f) ? +1.0f : -1.0f, 1.0f);
}
// Assume normalized input. Output is on [-1, 1] for each component.
inline glm::vec3 float32x3_to_oct(glm::vec3 v)
{
// Project the sphere onto the octahedron, and then onto the xy plane
glm::vec3 p = glm::vec3(v.x, v.y, 0) * (1.0f / (fabsf(v.x) + fabsf(v.y) + fabsf(v.z)));
// Reflect the folds of the lower hemisphere over the diagonals
return (v.z <= 0.0f) ? glm::vec3(1.0f - fabsf(p.y), 1.0f - fabsf(p.x), 0.0f) * oct_signNotZero(p) : p;
}
inline glm::vec3 oct_to_float32x3(glm::vec3 e)
{
glm::vec3 v = glm::vec3(e.x, e.y, 1.0f - fabsf(e.x) - fabsf(e.y));
if(v.z < 0.0f)
{
v = glm::vec3(1.0f - fabs(v.y), 1.0f - fabs(v.x), v.z) * oct_signNotZero(v);
}
return glm::normalize(v);
}
inline glm::vec3 float32x3_to_octn_precise(glm::vec3 v, const int n)
{
glm::vec3 s = float32x3_to_oct(v); // Remap to the square
// Each snorm's max value interpreted as an integer,
// e.g., 127.0 for snorm8
float M = float(1 << ((n / 2) - 1)) - 1.0f;
// Remap components to snorm(n/2) precision...with floor instead
// of round (see equation 1)
s = glm::floor(glm::clamp(s, -1.0f, +1.0f) * M) * (1.0f / M);
glm::vec3 bestRepresentation = s;
float highestCosine = glm::dot(oct_to_float32x3(s), v);
// Test all combinations of floor and ceil and keep the best.
// Note that at +/- 1, this will exit the square... but that
// will be a worse encoding and never win.
for(int i = 0; i <= 1; ++i)
{
for(int j = 0; j <= 1; ++j)
{
// This branch will be evaluated at compile time
if((i != 0) || (j != 0))
{
// Offset the bit pattern (which is stored in floating
// point!) to effectively change the rounding mode
// (when i or j is 0: floor, when it is one: ceiling)
glm::vec3 candidate = glm::vec3(i, j, 0) * (1 / M) + s;
float cosine = glm::dot(oct_to_float32x3(candidate), v);
if(cosine > highestCosine)
{
bestRepresentation = candidate;
highestCosine = cosine;
}
}
}
}
return bestRepresentation;
}
bool Scene::loadGLTF(const char* filename, int clones, int cloneaxis)
{
FileMappingList mappings;
// Parse the glTF file using cgltf
cgltf_options options = {};
options.file.read = map_cgltf;
options.file.release = unmap_cgltf;
options.file.user_data = &mappings;
cgltf_result cgltfResult;
unique_cgltf_ptr data = unique_cgltf_ptr(nullptr, &cgltf_free);
{
// We have this local pointer followed by an ownership transfer here
// because cgltf_parse_file takes a pointer to a pointer to cgltf_data.
cgltf_data* rawData = nullptr;
cgltfResult = cgltf_parse_file(&options, filename, &rawData);
data = unique_cgltf_ptr(rawData, &cgltf_free);
}
if(cgltfResult != cgltf_result_success || !data)
{
return false;
}
// Validate the glTF file
cgltfResult = cgltf_validate(data.get());
if(cgltfResult != cgltf_result_success)
{
return false;
}
// Load buffers
cgltfResult = cgltf_load_buffers(&options, data.get(), filename);
if(cgltfResult != cgltf_result_success)
{
return false;
}
int copies = clones + 1;
srand(234525);
// Create default materials if none exist
if(data->materials_count == 0)
{
m_materials.resize(1);
Material& material = m_materials[0];
for(int i = 0; i < 2; i++)
{
material.sides[i].ambient = randomVector(0.0f, 0.1f);
material.sides[i].diffuse = glm::vec4(0.7f, 0.7f, 0.7f, 1.0f) + randomVector(0.0f, 0.07f);
material.sides[i].diffuse.w = 1.0f;
material.sides[i].specular = randomVector(0.25f, 0.55f);
material.sides[i].emissive = randomVector(0.0f, 0.05f);
}
}
else
{
// Convert glTF materials
m_materials.resize(data->materials_count);
for(size_t n = 0; n < data->materials_count; n++)
{
const cgltf_material* gltfMaterial = &data->materials[n];
Material& material = m_materials[n];
for(int i = 0; i < 2; i++)
{
material.sides[i].ambient = randomVector(0.0f, 0.1f);
// Use base color from glTF material
if(gltfMaterial->has_pbr_metallic_roughness)
{
const float* baseColor = gltfMaterial->pbr_metallic_roughness.base_color_factor;
material.sides[i].diffuse =
glm::vec4(baseColor[0], baseColor[1], baseColor[2], baseColor[3]) + randomVector(0.0f, 0.07f);
}
else
{
material.sides[i].diffuse = glm::vec4(0.7f, 0.7f, 0.7f, 1.0f) + randomVector(0.0f, 0.07f);
material.sides[i].diffuse.w = 1.0f;
}
material.sides[i].specular = randomVector(0.25f, 0.55f);
material.sides[i].emissive = randomVector(0.0f, 0.05f);
}
}
}
// Count geometry elements. glTF has no concept of "parts", so we map
// primitives to parts. Unfortunately primitives may each have separate
// geometry. Meshes for this demo are created specially so each primitive
// references the same range of geometry data, but with offset triangle
// indices. To use this safely we first search the file and find these
// duplicate references. To support other glTF files, we fall back to a
// per-primitive mesh which has a single part.
int numGeoms = 0;
std::vector<std::vector<int>> meshPrimitiveToGeom(data->meshes_count);
std::vector<std::vector<int>> meshUniquePrimitives(data->meshes_count);
for(size_t meshIndex = 0; meshIndex < data->meshes_count; meshIndex++)
{
std::unordered_map<const cgltf_accessor*, int> vertexBufferToGeom;
const cgltf_mesh* gltfMesh = &data->meshes[meshIndex];
for(uint32_t primIdx = 0; primIdx < static_cast<uint32_t>(gltfMesh->primitives_count); primIdx++)
{
const cgltf_primitive* gltfPrim = &gltfMesh->primitives[primIdx];
if(gltfPrim->type != cgltf_primitive_type_triangles)
continue;
// Find position attribute
for(size_t attribIdx = 0; attribIdx < gltfPrim->attributes_count; attribIdx++)
{
const cgltf_attribute* gltfAttrib = &gltfPrim->attributes[attribIdx];
if(strcmp(gltfAttrib->name, "POSITION") == 0)
{
auto [it, inserted] = vertexBufferToGeom.insert({gltfAttrib->data, numGeoms});
if(inserted)
{
meshPrimitiveToGeom[meshIndex].push_back(numGeoms++);
meshUniquePrimitives[meshIndex].push_back(primIdx);
}
else
{
meshPrimitiveToGeom[meshIndex].push_back(it->second);
}
break;
}
}
}
}
// Process geometries (meshes)
m_geometry.resize(numGeoms * copies);
m_geometryBboxes.resize(numGeoms * copies);
m_trianglePartIdsSize = 0;
m_partTriCountsSize = 0;
// Count vertices and triangles across all primitives
for(size_t meshIndex = 0; meshIndex < data->meshes_count; meshIndex++)
{
const cgltf_mesh* gltfMesh = &data->meshes[meshIndex];
// Count vertices, ignoring primitives that reference the same vertex buffer
for(size_t primIdx : meshUniquePrimitives[meshIndex])
{
const cgltf_primitive* gltfPrim = &gltfMesh->primitives[primIdx];
int geomIndex = meshPrimitiveToGeom[meshIndex][primIdx];
Geometry& geom = m_geometry[geomIndex];
// Find position attribute
for(size_t attribIdx = 0; attribIdx < gltfPrim->attributes_count; attribIdx++)
{
const cgltf_attribute* gltfAttrib = &gltfPrim->attributes[attribIdx];
if(strcmp(gltfAttrib->name, "POSITION") == 0)
{
geom.numVertices += (uint32_t)gltfAttrib->data->count;
break;
}
}
}
// Count triangles and parts
for(size_t primIdx = 0; primIdx < gltfMesh->primitives_count; primIdx++)
{
const cgltf_primitive* gltfPrim = &gltfMesh->primitives[primIdx];
if(gltfPrim->type != cgltf_primitive_type_triangles)
continue;
int geomIndex = meshPrimitiveToGeom[meshIndex][primIdx];
Geometry& geom = m_geometry[geomIndex];
geom.numIndexSolid += (uint32_t)gltfPrim->indices->count;
geom.numParts++;
}
}
// Allocate vertex and index data
for(int geomIndex = 0; geomIndex < numGeoms; geomIndex++)
{
Geometry& geom = m_geometry[geomIndex];
// Allocate vertex and index data
geom.vboData = new Vertex[geom.numVertices];
geom.vboSize = sizeof(Vertex) * geom.numVertices;
geom.iboData = new uint32_t[geom.numIndexSolid];
geom.iboSize = sizeof(uint32_t) * geom.numIndexSolid;
geom.trianglePartIdsData = new uint32_t[geom.numIndexSolid / 3];
geom.trianglePartIdsSize = sizeof(uint32_t) * (geom.numIndexSolid / 3);
geom.partTriCountsData = new uint32_t[geom.numParts];
geom.partTriCountsSize = sizeof(uint32_t) * geom.numParts;
geom.partTriOffsetsData = new uint32_t[geom.numParts];
geom.partTriOffsetsSize = sizeof(uint32_t) * geom.numParts;
m_trianglePartIdsSize += geom.trianglePartIdsSize;
m_partTriCountsSize += geom.partTriCountsSize;
geom.parts.resize(geom.numParts);
}
// Fill vertex and index data
for(size_t meshIndex = 0; meshIndex < data->meshes_count; meshIndex++)
{
const cgltf_mesh* gltfMesh = &data->meshes[meshIndex];
// Process unique vertex buffers
for(size_t primIdx : meshUniquePrimitives[meshIndex])
{
const cgltf_primitive* gltfPrim = &gltfMesh->primitives[primIdx];
int geomIndex = meshPrimitiveToGeom[meshIndex][primIdx];
Geometry& geom = m_geometry[geomIndex];
assert(geom.build.vertexOffset == 0);
uint32_t primVertices = 0;
bool hasNormals = false;
for(size_t attribIdx = 0; attribIdx < gltfPrim->attributes_count; attribIdx++)
{
const cgltf_attribute* gltfAttrib = &gltfPrim->attributes[attribIdx];
const cgltf_accessor* accessor = gltfAttrib->data;
if(strcmp(gltfAttrib->name, "POSITION") == 0)
{
primVertices = (uint32_t)accessor->count;
// Read positions
for(size_t i = 0; i < accessor->count; i++)
{
glm::vec3 pos;
cgltf_accessor_read_float(accessor, i, &pos.x, 3);
assert(geom.build.vertexOffset + i < geom.numVertices);
geom.vboData[geom.build.vertexOffset + i].position = pos;
m_geometryBboxes[geomIndex].merge(glm::vec4(pos, 1.0f));
}
}
else if(strcmp(gltfAttrib->name, "NORMAL") == 0)
{
// Read normals and encode them
for(size_t i = 0; i < accessor->count; i++)
{
glm::vec3 normal;
cgltf_accessor_read_float(accessor, i, &normal.x, 3);
normal = glm::normalize(normal);
glm::vec3 packed = float32x3_to_octn_precise(normal, 16);
geom.vboData[geom.build.vertexOffset + i].normalOctX =
std::min(32767, std::max(-32767, int32_t(packed.x * 32767.0f)));
geom.vboData[geom.build.vertexOffset + i].normalOctY =
std::min(32767, std::max(-32767, int32_t(packed.y * 32767.0f)));
}
hasNormals = true;
}
}
// Fill normals for vertices that don't have them
if(!hasNormals)
{
for(uint32_t i = 0; i < primVertices; i++)
{
if(geom.vboData[geom.build.vertexOffset + i].normalOctX == 0 && geom.vboData[geom.build.vertexOffset + i].normalOctY == 0)
{
glm::vec3 normal = glm::normalize(geom.vboData[geom.build.vertexOffset + i].position);
glm::vec3 packed = float32x3_to_octn_precise(normal, 16);
geom.vboData[geom.build.vertexOffset + i].normalOctX =
std::min(32767, std::max(-32767, int32_t(packed.x * 32767.0f)));
geom.vboData[geom.build.vertexOffset + i].normalOctY =
std::min(32767, std::max(-32767, int32_t(packed.y * 32767.0f)));
}
}
}
geom.build.vertexOffset += (uint32_t)primVertices;
}
// Process indices for all primitives
for(size_t primIdx = 0; primIdx < gltfMesh->primitives_count; primIdx++)
{
const cgltf_primitive* gltfPrim = &gltfMesh->primitives[primIdx];
if(gltfPrim->type != cgltf_primitive_type_triangles)
continue;
int geomIndex = meshPrimitiveToGeom[meshIndex][primIdx];
Geometry& geom = m_geometry[geomIndex];
uint32_t primTriangles = (uint32_t)gltfPrim->indices->count / 3;
// Process indices
const cgltf_accessor* indexAccessor = gltfPrim->indices;
for(size_t i = 0; i < indexAccessor->count; i++)
{
geom.iboData[geom.build.indexOffset + i] = (uint32_t)cgltf_accessor_read_index(indexAccessor, i);
}
// Set up part info
geom.parts[geom.build.partIdx].indexSolid.offset = geom.build.indexOffset * sizeof(uint32_t);
geom.parts[geom.build.partIdx].indexSolid.count = (uint32_t)indexAccessor->count;
geom.partTriCountsData[geom.build.partIdx] = primTriangles;
geom.partTriOffsetsData[geom.build.partIdx] =
geom.build.partIdx > 0 ?
geom.partTriOffsetsData[geom.build.partIdx - 1] + geom.partTriCountsData[geom.build.partIdx - 1] :
0;
// Fill triangle part IDs
for(uint32_t i = 0; i < primTriangles; i++)
{
geom.trianglePartIdsData[geom.build.triangleOffset + i] = geom.build.partIdx;
}
geom.build.indexOffset += (uint32_t)indexAccessor->count;
geom.build.triangleOffset += primTriangles;
geom.build.partIdx++;
}
}
#if !defined(NDEBUG)
// Validate geometry
for(int geomIndex = 0; geomIndex < numGeoms; geomIndex++)
{
const Geometry& geom = m_geometry[geomIndex];
assert(geom.numVertices == geom.build.vertexOffset);
assert(geom.numIndexSolid == geom.build.indexOffset);
assert(geom.numIndexSolid == geom.build.triangleOffset * 3);
assert(geom.numParts == geom.build.partIdx);
assert(geom.numParts == geom.parts.size());
}
#endif
// Clone geometries
for(int c = 1; c <= clones; c++)
{
for(int n = 0; n < numGeoms; n++)
{
m_geometryBboxes[n + numGeoms * c] = m_geometryBboxes[n];
const Geometry& geomorig = m_geometry[n];
Geometry& geom = m_geometry[n + numGeoms * c];
geom = geomorig;
geom.cloneIdx = n;
}
}
// Process nodes and create matrices
m_matrices.resize(data->nodes_count * copies);
// First pass: compute all world transforms by traversing hierarchy
std::vector<bool> processed(data->nodes_count, false);
// Helper function to recursively compute world transforms
std::function<void(const cgltf_node*, const glm::mat4&)> processNodeHierarchy = [&](const cgltf_node* node,
const glm::mat4& parentTransform) {
if(!node)
return;
size_t nodeIndex = node - data->nodes;
if(processed[nodeIndex])
return;
// Compute local transform
glm::mat4 localTransform(1.0f);
cgltf_node_transform_local(node, glm::value_ptr(localTransform));
// Compute world transform
glm::mat4 worldTransform = parentTransform * localTransform;
m_matrices[nodeIndex].worldMatrix = worldTransform;
m_matrices[nodeIndex].worldMatrixIT = glm::transpose(glm::inverse(worldTransform));
processed[nodeIndex] = true;
// Process children
for(size_t childIdx = 0; childIdx < node->children_count; childIdx++)
{
processNodeHierarchy(node->children[childIdx], worldTransform);
}
};
// Process all root nodes (nodes without parents)
for(size_t n = 0; n < data->nodes_count; n++)
{
const cgltf_node* node = &data->nodes[n];
if(node->parent == nullptr && !processed[n])
{
processNodeHierarchy(node, glm::mat4(1.0f));
}
}
// Handle any remaining unprocessed nodes (shouldn't happen in valid glTF)
for(size_t n = 0; n < data->nodes_count; n++)
{
if(!processed[n])
{
const cgltf_node* node = &data->nodes[n];
glm::mat4 localTransform(1.0f);
cgltf_node_transform_local(node, glm::value_ptr(localTransform));
m_matrices[n].worldMatrix = localTransform;
m_matrices[n].worldMatrixIT = glm::transpose(glm::inverse(localTransform));
}
}
// Create objects from mesh nodes
std::vector<Object> tempObjects;
m_numObjectParts = 0;
for(size_t n = 0; n < data->nodes_count; n++)
{
const cgltf_node* gltfNode = &data->nodes[n];
if(!gltfNode->mesh)
continue;
ptrdiff_t meshIndex = gltfNode->mesh - data->meshes;
// Iterate over the unique vertex buffers and create objects for each
for(size_t primIdx : meshUniquePrimitives[meshIndex])
{
int geomIndex = meshPrimitiveToGeom[meshIndex][primIdx];
Object object;
object.matrixIndex = (int)n;
object.geometryIndex = geomIndex;
object.uniquePartOffset = m_numObjectParts;
const Geometry& geom = m_geometry[geomIndex];
// Iterate over all primitives that share the same geometry buffers -
// these are the "parts"
object.parts.resize(geom.numParts);
size_t partIdx = 0;
for(size_t partPrimIdx = 0; partPrimIdx < gltfNode->mesh->primitives_count; partPrimIdx++)
{
const cgltf_primitive* gltfPartPrim = &gltfNode->mesh->primitives[partPrimIdx];
if(gltfPartPrim->type != cgltf_primitive_type_triangles)
continue;
if(meshPrimitiveToGeom[meshIndex][primIdx] != geomIndex)
continue;
object.parts[partIdx].active = 1;
object.parts[partIdx].matrixIndex = object.matrixIndex;
// Use material from primitive if available
if(gltfPartPrim->material)
{
object.parts[partIdx].materialIndex = (int)(gltfPartPrim->material - data->materials);
}
else
{
object.parts[partIdx].materialIndex = 0; // Default material
}
partIdx++;
}
assert(partIdx == geom.numParts);
m_numObjectParts += geom.numParts;
// Update bounding box
BBox bbox = m_geometryBboxes[object.geometryIndex].transformed(m_matrices[n].worldMatrix);
m_bbox.merge(bbox);
tempObjects.push_back(object);
}
}
// Resize objects array and copy
m_objects.resize(tempObjects.size() * copies);
for(size_t i = 0; i < tempObjects.size(); i++)
{
m_objects[i] = tempObjects[i];
}
// Handle cloning similar to original implementation
if(clones > 0)
{
glm::vec4 dim = m_bbox.max - m_bbox.min;
int sq = 1;
int numAxis = 0;
for(int i = 0; i < 3; i++)
{
numAxis += (cloneaxis & (1 << i)) ? 1 : 0;
}
assert(numAxis);
switch(numAxis)
{
case 1:
sq = copies;
break;
case 2:
while(sq * sq < copies)
sq++;
break;
case 3:
while(sq * sq * sq < copies)
sq++;
break;
}
for(int c = 1; c <= clones; c++)
{
int numNodes = (int)data->nodes_count;
glm::vec4 shift = dim * 1.05f;
float u = 0, v = 0, w = 0;
switch(numAxis)
{
case 1:
u = float(c);
break;
case 2:
u = float(c % sq);
v = float(c / sq);
break;
case 3:
u = float(c % sq);
v = float((c / sq) % sq);
w = float(c / (sq * sq));
break;
}
float use = u;
if(cloneaxis & (1 << 0))
{
shift.x *= -use;
if(numAxis > 1)
use = v;
}
else
shift.x = 0;
if(cloneaxis & (1 << 1))
{
shift.y *= use;
if(numAxis > 2)
use = w;
else if(numAxis > 1)
use = v;
}
else
shift.y = 0;
if(cloneaxis & (1 << 2))
{
shift.z *= -use;
}
else
shift.z = 0;
shift.w = 0;
// Clone matrices
for(int n = 0; n < numNodes; n++)
{
MatrixNode& node = m_matrices[n + numNodes * c];
MatrixNode& nodeOrig = m_matrices[n];
node = nodeOrig;
node.worldMatrix[3] = node.worldMatrix[3] + shift;
node.worldMatrixIT = glm::transpose(glm::inverse(node.worldMatrix));
}
// Clone objects
for(size_t n = 0; n < tempObjects.size(); n++)
{
const Object& objectorig = m_objects[n];
Object& object = m_objects[n + tempObjects.size() * c];
object = objectorig;
object.geometryIndex += c * numGeoms;
object.matrixIndex += c * numNodes;
for(size_t i = 0; i < object.parts.size(); i++)
{
object.parts[i].matrixIndex += c * numNodes;
}
object.uniquePartOffset += c * m_numObjectParts;
}
}
}
return true;
}
void Scene::unload()
{
if(m_geometry.empty())
return;
for(size_t i = 0; i < m_geometry.size(); i++)
{
if(m_geometry[i].cloneIdx >= 0)
continue;
delete[] m_geometry[i].vboData;
delete[] m_geometry[i].iboData;
delete[] m_geometry[i].trianglePartIdsData;
delete[] m_geometry[i].partTriCountsData;
delete[] m_geometry[i].partTriOffsetsData;
}
m_matrices.clear();
m_geometryBboxes.clear();
m_geometry.clear();
m_objects.clear();
m_geometryBboxes.clear();
}