-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSceneGPU.h
2568 lines (2122 loc) · 108 KB
/
SceneGPU.h
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <cfloat>
#include <climits>
#include "../Log.h"
#include "BVHSplit.h"
#include "SceneCommon.h"
#include "SparseStorageCPU.h"
#include "TextureUtils.h"
#include "Time_.h"
#include "shaders/shade_sky_interface.h"
namespace Ray {
extern const int MOON_TEX_W;
extern const int MOON_TEX_H;
extern const uint8_t __moon_tex[];
extern const int WEATHER_TEX_RES;
extern const uint8_t __weather_tex[];
extern const int NOISE_3D_RES;
extern const uint8_t __3d_noise_tex[];
extern const int CIRRUS_TEX_RES;
extern const uint8_t __cirrus_tex[];
extern const int CURL_TEX_RES;
extern const uint8_t __curl_tex[];
Ref::fvec4 rgb_to_rgbe(const Ref::fvec4 &rgb);
namespace NS {
class Context;
class Renderer;
template <class T> force_inline T clamp(const T &val, const T &min_val, const T &max_val) {
return std::min(std::max(val, min_val), max_val);
}
inline Ref::fvec4 cross(const Ref::fvec4 &v1, const Ref::fvec4 &v2) {
return Ref::fvec4{v1.get<1>() * v2.get<2>() - v1.get<2>() * v2.get<1>(),
v1.get<2>() * v2.get<0>() - v1.get<0>() * v2.get<2>(),
v1.get<0>() * v2.get<1>() - v1.get<1>() * v2.get<0>(), 0.0f};
}
const eTexFormat g_to_internal_format[] = {
eTexFormat::Undefined, // Undefined
eTexFormat::RGBA8, // RGBA8888
eTexFormat::RGB8, // RGB888
eTexFormat::RG8, // RG88
eTexFormat::R8, // R8
eTexFormat::BC1, // BC1
eTexFormat::BC3, // BC3
eTexFormat::BC4, // BC4
eTexFormat::BC5 // BC5
};
class Scene : public SceneCommon {
protected:
friend class NS::Renderer;
Context *ctx_;
bool use_hwrt_ = false, use_bindless_ = false, use_tex_compression_ = false;
SparseStorage<bvh2_node_t, false /* Replicate */> nodes_;
SparseStorage<tri_accel_t, false /* Replicate */> tris_;
SparseStorage<uint32_t, false /* Replicate */> tri_indices_;
SparseStorage<tri_mat_data_t> tri_materials_;
Cpu::SparseStorage<mesh_t> meshes_;
SparseStorage<mesh_instance_t> mesh_instances_;
SparseStorage<vertex_t> vertices_;
SparseStorage<uint32_t> vtx_indices_;
SparseStorage<material_t> materials_;
SparseStorage<atlas_texture_t> atlas_textures_;
Cpu::SparseStorage<Texture> bindless_textures_;
BindlessTexData bindless_tex_data_;
TextureAtlas tex_atlases_[8];
SparseStorage<light_t> lights_;
Vector<uint32_t> li_indices_;
uint32_t visible_lights_count_ = 0, blocker_lights_count_ = 0;
Vector<light_cwbvh_node_t> light_cwnodes_;
std::vector<uint32_t> dir_lights_; // compacted list of all directional lights
Texture sky_transmittance_lut_tex_, sky_multiscatter_lut_tex_;
Texture sky_moon_tex_, sky_weather_tex_, sky_cirrus_tex_, sky_curl_tex_;
Texture sky_noise3d_tex_;
LightHandle env_map_light_ = InvalidLightHandle;
TextureHandle physical_sky_texture_ = InvalidTextureHandle;
struct {
int res = -1;
float medium_lum = 0.0f;
SmallVector<aligned_vector<fvec4>, 16> mips;
Texture tex;
} env_map_qtree_;
mutable Vector<uint64_t> spatial_cache_entries_;
mutable Vector<packed_cache_voxel_t> spatial_cache_voxels_curr_, spatial_cache_voxels_prev_;
mutable float spatial_cache_cam_pos_prev_[3] = {};
uint32_t tlas_root_ = 0xffffffff, tlas_block_ = 0xffffffff;
bvh_node_t tlas_root_node_ = {};
Buffer rt_geo_data_buf_, rt_instance_buf_, rt_tlas_buf_;
struct MeshBlas {
AccStructure acc;
uint32_t geo_index, geo_count;
FreelistAlloc::Allocation mem_alloc;
};
Cpu::SparseStorage<MeshBlas> rt_mesh_blases_;
const uint32_t RtBLASChunkSize = 16 * 1024 * 1024;
FreelistAlloc rt_blas_mem_alloc_;
std::vector<Buffer> rt_blas_buffers_;
AccStructure rt_tlas_;
Buffer atmosphere_params_buf_;
Shader sh_bake_sky_;
Program prog_bake_sky_;
Pipeline pi_bake_sky_;
bool InitPipelines();
MaterialHandle AddMaterial_nolock(const shading_node_desc_t &m);
void SetMeshInstanceTransform_nolock(MeshInstanceHandle mi_handle, const float *xform);
void RemoveMesh_nolock(MeshHandle m);
void RemoveMeshInstance_nolock(MeshInstanceHandle i);
void Rebuild_SWRT_TLAS_nolock();
void RebuildLightTree_nolock();
std::vector<Ray::color_rgba8_t> CalcSkyEnvTexture(const atmosphere_params_t ¶ms, const int res[2],
const light_t lights[], Span<const uint32_t> dir_lights);
void PrepareSkyEnvMap_nolock(const std::function<void(int, int, ParallelForFunction &&)> ¶llel_for);
void PrepareEnvMapQTree_nolock();
void GenerateTextureMips_nolock();
void PrepareBindlessTextures_nolock();
std::pair<uint32_t, uint32_t> Build_HWRT_BLAS_nolock(uint32_t vert_index, uint32_t vert_count);
void Rebuild_HWRT_TLAS_nolock();
TextureHandle AddAtlasTexture_nolock(const tex_desc_t &t);
TextureHandle AddBindlessTexture_nolock(const tex_desc_t &t);
// Workaround for Intel Arc issues
void _insert_mem_barrier(void *cmdbuf);
template <typename T, int N>
static void WriteTextureMips(const color_t<T, N> data[], const int _res[2], int mip_count, bool compress,
uint8_t out_data[], uint32_t out_size[16]);
public:
Scene(Context *ctx, bool use_hwrt, bool use_bindless, bool use_tex_compression, bool use_spatial_cache);
~Scene() override;
void SetEnvironment(const environment_desc_t &env) override;
TextureHandle AddTexture(const tex_desc_t &t) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
if (use_bindless_) {
return AddBindlessTexture_nolock(t);
} else {
return AddAtlasTexture_nolock(t);
}
}
void RemoveTexture(const TextureHandle t) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
if (use_bindless_) {
bindless_textures_.Erase(t._block);
} else {
atlas_textures_.Erase(t._block);
}
}
MaterialHandle AddMaterial(const shading_node_desc_t &m) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
return AddMaterial_nolock(m);
}
MaterialHandle AddMaterial(const principled_mat_desc_t &m) override;
void RemoveMaterial(const MaterialHandle m) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
materials_.Erase(m._block);
}
MeshHandle AddMesh(const mesh_desc_t &m) override;
void RemoveMesh(MeshHandle m) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
RemoveMesh_nolock(m);
}
LightHandle AddLight(const directional_light_desc_t &l) override;
LightHandle AddLight(const sphere_light_desc_t &l) override;
LightHandle AddLight(const spot_light_desc_t &l) override;
LightHandle AddLight(const rect_light_desc_t &l, const float *xform) override;
LightHandle AddLight(const disk_light_desc_t &l, const float *xform) override;
LightHandle AddLight(const line_light_desc_t &l, const float *xform) override;
void RemoveLight(const LightHandle i) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
lights_.Erase(i._block);
}
MeshInstanceHandle AddMeshInstance(const mesh_instance_desc_t &mi) override;
void SetMeshInstanceTransform(MeshInstanceHandle mi_handle, const float *xform) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
SetMeshInstanceTransform_nolock(mi_handle, xform);
}
void RemoveMeshInstance(MeshInstanceHandle mi) override {
std::unique_lock<std::shared_timed_mutex> lock(mtx_);
RemoveMeshInstance_nolock(mi);
}
void Finalize(const std::function<void(int, int, ParallelForFunction &&)> ¶llel_for) override;
uint32_t triangle_count() const override {
std::shared_lock<std::shared_timed_mutex> lock(mtx_);
return uint32_t(vtx_indices_.size() / 3);
}
uint32_t node_count() const override {
std::shared_lock<std::shared_timed_mutex> lock(mtx_);
return uint32_t(nodes_.size());
}
};
} // namespace NS
} // namespace Ray
namespace Ray {
int round_up(int v, int align);
}
inline Ray::NS::Scene::Scene(Context *ctx, const bool use_hwrt, const bool use_bindless, const bool use_tex_compression,
const bool use_spatial_cache)
: ctx_(ctx), use_hwrt_(use_hwrt), use_bindless_(use_bindless), use_tex_compression_(use_tex_compression),
nodes_(ctx, "Nodes"), tris_(ctx, "Tris"), tri_indices_(ctx, "Tri Indices"), tri_materials_(ctx, "Tri Materials"),
mesh_instances_(ctx, "Mesh Instances"), vertices_(ctx, "Vertices"), vtx_indices_(ctx, "Vtx Indices"),
materials_(ctx, "Materials"), atlas_textures_(ctx, "Atlas Textures"), bindless_tex_data_{ctx},
tex_atlases_{{ctx, "Atlas RGBA", eTexFormat::RGBA8, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas RGB", eTexFormat::RGB8, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas RG", eTexFormat::RG8, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas R", eTexFormat::R8, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas BC1", eTexFormat::BC1, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas BC3", eTexFormat::BC3, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas BC4", eTexFormat::BC4, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE},
{ctx, "Atlas BC5", eTexFormat::BC5, eTexFilter::Nearest, TEXTURE_ATLAS_SIZE, TEXTURE_ATLAS_SIZE}},
lights_(ctx, "Lights"), li_indices_(ctx, "LI Indices"), light_cwnodes_(ctx, "Light CWNodes"),
spatial_cache_entries_(ctx, "Spatial Cache Entries"),
spatial_cache_voxels_curr_(ctx, "Spatial Cache Voxels (1/2)"),
spatial_cache_voxels_prev_(ctx, "Spatial Cache Voxels (2/2)") {
SceneBase::log_ = ctx->log();
InitPipelines();
SetEnvironment({});
if (use_spatial_cache) {
spatial_cache_entries_.Resize(HASH_GRID_CACHE_ENTRIES_COUNT);
spatial_cache_entries_.Fill(0, 0, HASH_GRID_CACHE_ENTRIES_COUNT);
spatial_cache_voxels_curr_.Resize(HASH_GRID_CACHE_ENTRIES_COUNT);
spatial_cache_voxels_curr_.Fill({}, 0, HASH_GRID_CACHE_ENTRIES_COUNT);
spatial_cache_voxels_prev_.Resize(HASH_GRID_CACHE_ENTRIES_COUNT);
spatial_cache_voxels_prev_.Fill({}, 0, HASH_GRID_CACHE_ENTRIES_COUNT);
}
}
inline Ray::TextureHandle Ray::NS::Scene::AddAtlasTexture_nolock(const tex_desc_t &_t) {
atlas_texture_t t;
t.width = uint16_t(_t.w);
t.height = uint16_t(_t.h);
if (_t.is_srgb) {
t.width |= ATLAS_TEX_SRGB_BIT;
}
if (_t.is_YCoCg) {
t.height |= ATLAS_TEX_YCOCG_BIT;
}
if (((_t.generate_mipmaps && !IsCompressedFormat(_t.format)) || _t.mips_count > 1) &&
_t.w > MIN_ATLAS_TEXTURE_SIZE && _t.h > MIN_ATLAS_TEXTURE_SIZE) {
t.height |= ATLAS_TEX_MIPS_BIT;
}
int res[2] = {_t.w, _t.h};
const bool use_compression = use_tex_compression_ && !_t.force_no_compression;
std::unique_ptr<color_rg8_t[]> repacked_normalmap;
bool reconstruct_z = _t.reconstruct_z;
const void *tex_data = _t.data.data();
if (_t.format == eTextureFormat::RGBA8888) {
if (!_t.is_normalmap) {
t.atlas = 0;
} else {
// TODO: get rid of this allocation
repacked_normalmap = std::make_unique<color_rg8_t[]>(res[0] * res[1]);
const bool invert_y = (_t.convention == eTextureConvention::DX);
const auto *rgba_data = reinterpret_cast<const color_rgba8_t *>(_t.data.data());
for (int i = 0; i < res[0] * res[1]; ++i) {
repacked_normalmap[i].v[0] = rgba_data[i].v[0];
repacked_normalmap[i].v[1] = invert_y ? (255 - rgba_data[i].v[1]) : rgba_data[i].v[1];
reconstruct_z |= (rgba_data[i].v[2] < 250);
}
tex_data = repacked_normalmap.get();
t.atlas = use_compression ? 7 : 2;
}
} else if (_t.format == eTextureFormat::RGB888) {
if (!_t.is_normalmap) {
t.atlas = use_compression ? 5 : 1;
t.height |= ATLAS_TEX_YCOCG_BIT;
} else {
// TODO: get rid of this allocation
repacked_normalmap = std::make_unique<color_rg8_t[]>(res[0] * res[1]);
const bool invert_y = (_t.convention == eTextureConvention::DX);
const auto *rgb_data = reinterpret_cast<const color_rgb8_t *>(_t.data.data());
for (int i = 0; i < res[0] * res[1]; ++i) {
repacked_normalmap[i].v[0] = rgb_data[i].v[0];
repacked_normalmap[i].v[1] = invert_y ? (255 - rgb_data[i].v[1]) : rgb_data[i].v[1];
reconstruct_z |= (rgb_data[i].v[2] < 250);
}
tex_data = repacked_normalmap.get();
t.atlas = use_compression ? 7 : 2;
}
} else if (_t.format == eTextureFormat::RG88) {
t.atlas = use_compression ? 7 : 2;
reconstruct_z = _t.is_normalmap;
const bool invert_y = _t.is_normalmap && (_t.convention == eTextureConvention::DX);
if (invert_y) {
// TODO: get rid of this allocation
repacked_normalmap = std::make_unique<color_rg8_t[]>(res[0] * res[1]);
const auto *rg_data = reinterpret_cast<const color_rg8_t *>(_t.data.data());
for (int i = 0; i < res[0] * res[1]; ++i) {
repacked_normalmap[i].v[0] = rg_data[i].v[0];
repacked_normalmap[i].v[1] = 255 - rg_data[i].v[1];
}
tex_data = repacked_normalmap.get();
}
} else if (_t.format == eTextureFormat::R8) {
t.atlas = use_compression ? 6 : 3;
} else {
const bool flip_vertical = (_t.convention == eTextureConvention::DX);
const bool invert_green = (_t.convention == eTextureConvention::DX) && _t.is_normalmap;
reconstruct_z = _t.is_normalmap && (_t.format == eTextureFormat::BC5);
int read_offset = 0;
int _res[2] = {_t.w, _t.h};
// TODO: Get rid of allocation
std::vector<uint8_t> temp_data;
for (int i = 0; i < std::min(_t.mips_count, NUM_MIP_LEVELS) && _res[0] >= 4 && _res[1] >= 4; ++i) {
if (_t.format == eTextureFormat::BC1) {
t.atlas = 4;
temp_data.resize(GetRequiredMemory_BCn<3>(_res[0], _res[1], 1));
Preprocess_BCn<3>(&_t.data[read_offset], (_res[0] + 3) / 4, (_res[1] + 3) / 4, flip_vertical,
invert_green, temp_data.data());
} else if (_t.format == eTextureFormat::BC3) {
t.atlas = 5;
temp_data.resize(GetRequiredMemory_BCn<4>(_res[0], _res[1], 1));
Preprocess_BCn<4>(&_t.data[read_offset], (_res[0] + 3) / 4, (_res[1] + 3) / 4, flip_vertical,
invert_green, temp_data.data());
} else if (_t.format == eTextureFormat::BC4) {
t.atlas = 6;
temp_data.resize(GetRequiredMemory_BCn<1>(_res[0], _res[1], 1));
Preprocess_BCn<1>(&_t.data[read_offset], (_res[0] + 3) / 4, (_res[1] + 3) / 4, flip_vertical,
invert_green, temp_data.data());
} else if (_t.format == eTextureFormat::BC5) {
t.atlas = 7;
temp_data.resize(GetRequiredMemory_BCn<2>(_res[0], _res[1], 1));
Preprocess_BCn<2>(&_t.data[read_offset], (_res[0] + 3) / 4, (_res[1] + 3) / 4, flip_vertical,
invert_green, temp_data.data());
}
int pos[2] = {};
const int page = tex_atlases_[t.atlas].AllocateRaw(temp_data.data(), _res, pos);
t.page[i] = uint8_t(page);
t.pos[i][0] = uint16_t(pos[0]);
t.pos[i][1] = uint16_t(pos[1]);
read_offset += int(temp_data.size());
_res[0] /= 2;
_res[1] /= 2;
}
// Fill remaining mip levels
for (int i = _t.mips_count; i < NUM_MIP_LEVELS; i++) {
t.page[i] = t.page[_t.mips_count - 1];
t.pos[i][0] = t.pos[_t.mips_count - 1][0];
t.pos[i][1] = t.pos[_t.mips_count - 1][1];
}
}
if (reconstruct_z) {
t.width |= uint32_t(ATLAS_TEX_RECONSTRUCT_Z_BIT);
}
if (!IsCompressedFormat(_t.format)) { // Allocate initial mip level
int page = -1, pos[2] = {};
if (t.atlas == 0) {
page = tex_atlases_[0].Allocate<uint8_t, 4>(reinterpret_cast<const color_rgba8_t *>(tex_data), res, pos);
} else if (t.atlas == 1 || t.atlas == 5) {
page =
tex_atlases_[t.atlas].Allocate<uint8_t, 3>(reinterpret_cast<const color_rgb8_t *>(tex_data), res, pos);
} else if (t.atlas == 2 || t.atlas == 7) {
page =
tex_atlases_[t.atlas].Allocate<uint8_t, 2>(reinterpret_cast<const color_rg8_t *>(tex_data), res, pos);
} else if (t.atlas == 3 || t.atlas == 6) {
page = tex_atlases_[t.atlas].Allocate<uint8_t, 1>(reinterpret_cast<const color_r8_t *>(tex_data), res, pos);
}
if (page == -1) {
return InvalidTextureHandle;
}
t.page[0] = uint8_t(page);
t.pos[0][0] = uint16_t(pos[0]);
t.pos[0][1] = uint16_t(pos[1]);
}
// Temporarily fill remaining mip levels with the last one (mips will be added later)
for (int i = 1; i < NUM_MIP_LEVELS && !IsCompressedFormat(_t.format); i++) {
t.page[i] = t.page[0];
t.pos[i][0] = t.pos[0][0];
t.pos[i][1] = t.pos[0][1];
}
if (_t.generate_mipmaps && (use_compression || !ctx_->image_blit_supported()) && !IsCompressedFormat(_t.format)) {
// We have to generate mips here as uncompressed data will be lost
int pages[16], positions[16][2];
if (_t.format == eTextureFormat::RGBA8888) {
tex_atlases_[t.atlas].AllocateMips<uint8_t, 4>(reinterpret_cast<const color_rgba8_t *>(_t.data.data()), res,
NUM_MIP_LEVELS - 1, pages, positions);
} else if (_t.format == eTextureFormat::RGB888) {
tex_atlases_[t.atlas].AllocateMips<uint8_t, 3>(reinterpret_cast<const color_rgb8_t *>(_t.data.data()), res,
NUM_MIP_LEVELS - 1, pages, positions);
} else if (_t.format == eTextureFormat::RG88) {
tex_atlases_[t.atlas].AllocateMips<uint8_t, 2>(reinterpret_cast<const color_rg8_t *>(_t.data.data()), res,
NUM_MIP_LEVELS - 1, pages, positions);
} else if (_t.format == eTextureFormat::R8) {
tex_atlases_[t.atlas].AllocateMips<uint8_t, 1>(reinterpret_cast<const color_r8_t *>(_t.data.data()), res,
NUM_MIP_LEVELS - 1, pages, positions);
} else {
return InvalidTextureHandle;
}
for (int i = 1; i < NUM_MIP_LEVELS; i++) {
t.page[i] = uint8_t(pages[i - 1]);
t.pos[i][0] = uint16_t(positions[i - 1][0]);
t.pos[i][1] = uint16_t(positions[i - 1][1]);
}
}
log_->Info("Ray: Texture '%s' loaded (atlas = %i, %ix%i)", _t.name, int(t.atlas), _t.w, _t.h);
log_->Info("Ray: Atlasses are (RGBA[%i], RGB[%i], RG[%i], R[%i], BC1[%i], BC3[%i], BC4[%i], BC5[%i])",
tex_atlases_[0].page_count(), tex_atlases_[1].page_count(), tex_atlases_[2].page_count(),
tex_atlases_[3].page_count(), tex_atlases_[4].page_count(), tex_atlases_[5].page_count(),
tex_atlases_[6].page_count(), tex_atlases_[7].page_count());
const std::pair<uint32_t, uint32_t> at = atlas_textures_.push(t);
return TextureHandle{at.first, at.second};
}
inline Ray::TextureHandle Ray::NS::Scene::AddBindlessTexture_nolock(const tex_desc_t &_t) {
eTexFormat src_fmt = eTexFormat::Undefined, fmt = eTexFormat::Undefined;
const int expected_mip_count = CalcMipCount(_t.w, _t.h, 4);
const int mip_count = (_t.generate_mipmaps && !Ray::IsCompressedFormat(_t.format))
? expected_mip_count
: std::min(_t.mips_count, expected_mip_count);
Buffer temp_stage_buf("Temp stage buf", ctx_, eBufType::Upload,
3 * _t.w * _t.h * 4 + 4096 * mip_count); // allocate for worst case
uint8_t *stage_data = temp_stage_buf.Map();
bool use_compression = use_tex_compression_ && !_t.force_no_compression;
use_compression &= CanBeBlockCompressed(_t.w, _t.h, mip_count);
uint32_t data_size[16] = {};
std::unique_ptr<uint8_t[]> repacked_data;
bool reconstruct_z = _t.reconstruct_z, is_YCoCg = _t.is_YCoCg;
if (_t.format == eTextureFormat::RGBA8888) {
if (!_t.is_normalmap) {
src_fmt = fmt = eTexFormat::RGBA8;
data_size[0] = round_up(_t.w * 4, TextureDataPitchAlignment) * _t.h;
const auto *rgba_data = reinterpret_cast<const color_rgba8_t *>(_t.data.data());
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &rgba_data[y * _t.w], _t.w * 4);
j += round_up(_t.w * 4, TextureDataPitchAlignment);
}
} else {
// TODO: get rid of this allocation
repacked_data = std::make_unique<uint8_t[]>(2 * _t.w * _t.h);
const bool invert_y = (_t.convention == Ray::eTextureConvention::DX);
const auto *rgba_data = reinterpret_cast<const color_rgba8_t *>(_t.data.data());
for (int i = 0; i < _t.w * _t.h; ++i) {
repacked_data[i * 2 + 0] = rgba_data[i].v[0];
repacked_data[i * 2 + 1] = invert_y ? (255 - rgba_data[i].v[1]) : rgba_data[i].v[1];
reconstruct_z |= (rgba_data[i].v[2] < 250);
}
if (use_compression) {
src_fmt = eTexFormat::RG8;
fmt = eTexFormat::BC5;
data_size[0] = GetRequiredMemory_BC5(_t.w, _t.h, TextureDataPitchAlignment);
CompressImage_BC5<2>(&repacked_data[0], _t.w, _t.h, stage_data,
GetRequiredMemory_BC5(_t.w, 1, TextureDataPitchAlignment));
} else {
src_fmt = fmt = eTexFormat::RG8;
data_size[0] = round_up(_t.w * 2, TextureDataPitchAlignment) * _t.h;
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &repacked_data[y * _t.w * 2], _t.w * 2);
j += round_up(_t.w * 2, TextureDataPitchAlignment);
}
}
}
} else if (_t.format == eTextureFormat::RGB888) {
if (!_t.is_normalmap) {
if (use_compression) {
auto temp_YCoCg = ConvertRGB_to_CoCgxY(_t.data.data(), _t.w, _t.h);
is_YCoCg = true;
src_fmt = eTexFormat::RGB8;
fmt = eTexFormat::BC3;
data_size[0] = GetRequiredMemory_BC3(_t.w, _t.h, TextureDataPitchAlignment);
CompressImage_BC3<true /* Is_YCoCg */>(temp_YCoCg.get(), _t.w, _t.h, stage_data,
GetRequiredMemory_BC3(_t.w, 1, TextureDataPitchAlignment));
} else if (ctx_->rgb8_unorm_is_supported()) {
src_fmt = fmt = eTexFormat::RGB8;
data_size[0] = round_up(_t.w * 3, TextureDataPitchAlignment) * _t.h;
const auto *rgb_data = reinterpret_cast<const color_rgb8_t *>(_t.data.data());
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &rgb_data[y * _t.w], _t.w * 3);
j += round_up(_t.w * 3, TextureDataPitchAlignment);
}
} else {
// Fallback to 4-component texture
src_fmt = fmt = eTexFormat::RGBA8;
data_size[0] = round_up(_t.w * 4, TextureDataPitchAlignment) * _t.h;
// TODO: get rid of this allocation
repacked_data = std::make_unique<uint8_t[]>(4 * _t.w * _t.h);
const auto *rgb_data = _t.data.data();
for (int i = 0; i < _t.w * _t.h; ++i) {
repacked_data[i * 4 + 0] = rgb_data[i * 3 + 0];
repacked_data[i * 4 + 1] = rgb_data[i * 3 + 1];
repacked_data[i * 4 + 2] = rgb_data[i * 3 + 2];
repacked_data[i * 4 + 3] = 255;
}
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &repacked_data[y * _t.w * 4], _t.w * 4);
j += round_up(_t.w * 4, TextureDataPitchAlignment);
}
}
} else {
// TODO: get rid of this allocation
repacked_data = std::make_unique<uint8_t[]>(2 * _t.w * _t.h);
const bool invert_y = (_t.convention == Ray::eTextureConvention::DX);
const auto *rgb_data = reinterpret_cast<const color_rgb8_t *>(_t.data.data());
for (int i = 0; i < _t.w * _t.h; ++i) {
repacked_data[i * 2 + 0] = rgb_data[i].v[0];
repacked_data[i * 2 + 1] = invert_y ? (255 - rgb_data[i].v[1]) : rgb_data[i].v[1];
reconstruct_z |= (rgb_data[i].v[2] < 250);
}
if (use_compression) {
src_fmt = eTexFormat::RG8;
fmt = eTexFormat::BC5;
data_size[0] = GetRequiredMemory_BC5(_t.w, _t.h, TextureDataPitchAlignment);
CompressImage_BC5<2>(&repacked_data[0], _t.w, _t.h, stage_data,
GetRequiredMemory_BC5(_t.w, 1, TextureDataPitchAlignment));
} else {
src_fmt = fmt = eTexFormat::RG8;
data_size[0] = round_up(_t.w * 2, TextureDataPitchAlignment) * _t.h;
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &repacked_data[y * _t.w * 2], _t.w * 2);
j += round_up(_t.w * 2, TextureDataPitchAlignment);
}
}
}
} else if (_t.format == eTextureFormat::RG88) {
src_fmt = fmt = eTexFormat::RG8;
data_size[0] = round_up(_t.w * 2, TextureDataPitchAlignment) * _t.h;
const bool invert_y = _t.is_normalmap && (_t.convention == Ray::eTextureConvention::DX);
const auto *rg_data = reinterpret_cast<const color_rg8_t *>(_t.data.data());
int j = 0;
for (int y = 0; y < _t.h; ++y) {
auto *dst = reinterpret_cast<color_rg8_t *>(&stage_data[j]);
for (int x = 0; x < _t.w; ++x) {
dst[x].v[0] = rg_data[y * _t.w + x].v[0];
dst[x].v[1] = invert_y ? (255 - rg_data[y * _t.w + x].v[1]) : rg_data[y * _t.w + x].v[1];
}
j += round_up(_t.w * 2, TextureDataPitchAlignment);
}
reconstruct_z = _t.is_normalmap;
} else if (_t.format == eTextureFormat::R8) {
if (use_compression) {
src_fmt = eTexFormat::R8;
fmt = eTexFormat::BC4;
data_size[0] = GetRequiredMemory_BC4(_t.w, _t.h, TextureDataPitchAlignment);
CompressImage_BC4<1>(_t.data.data(), _t.w, _t.h, stage_data,
GetRequiredMemory_BC4(_t.w, 1, TextureDataPitchAlignment));
} else {
src_fmt = fmt = eTexFormat::R8;
data_size[0] = round_up(_t.w, TextureDataPitchAlignment) * _t.h;
const auto *r_data = reinterpret_cast<const color_r8_t *>(_t.data.data());
int j = 0;
for (int y = 0; y < _t.h; ++y) {
memcpy(&stage_data[j], &r_data[y * _t.w], _t.w);
j += round_up(_t.w, TextureDataPitchAlignment);
}
}
} else {
//
// Compressed formats
//
src_fmt = fmt = g_to_internal_format[int(_t.format)];
const bool flip_vertical = (_t.convention == eTextureConvention::DX);
const bool invert_green = (_t.convention == eTextureConvention::DX) && _t.is_normalmap;
reconstruct_z = _t.is_normalmap && (_t.format == eTextureFormat::BC5);
int read_offset = 0, write_offset = 0;
int w = _t.w, h = _t.h;
for (int i = 0; i < mip_count; ++i) {
if (_t.format == eTextureFormat::BC1) {
data_size[i] = Preprocess_BCn<3>(&_t.data[read_offset], (w + 3) / 4, (h + 3) / 4, flip_vertical,
invert_green, &stage_data[write_offset],
GetRequiredMemory_BC1(w, 1, TextureDataPitchAlignment));
} else if (_t.format == eTextureFormat::BC3) {
data_size[i] = Preprocess_BCn<4>(&_t.data[read_offset], (w + 3) / 4, (h + 3) / 4, flip_vertical,
invert_green, &stage_data[write_offset],
GetRequiredMemory_BC3(w, 1, TextureDataPitchAlignment));
} else if (_t.format == eTextureFormat::BC4) {
data_size[i] = Preprocess_BCn<1>(&_t.data[read_offset], (w + 3) / 4, (h + 3) / 4, flip_vertical,
invert_green, &stage_data[write_offset],
GetRequiredMemory_BC4(w, 1, TextureDataPitchAlignment));
} else if (_t.format == eTextureFormat::BC5) {
data_size[i] = Preprocess_BCn<2>(&_t.data[read_offset], (w + 3) / 4, (h + 3) / 4, flip_vertical,
invert_green, &stage_data[write_offset],
GetRequiredMemory_BC5(w, 1, TextureDataPitchAlignment));
}
read_offset += data_size[i];
write_offset += round_up(data_size[i], 4096);
w /= 2;
h /= 2;
}
}
if (_t.generate_mipmaps && !IsCompressedFormat(src_fmt)) {
const int res[2] = {_t.w, _t.h};
if (src_fmt == eTexFormat::RGBA8) {
const auto *rgba_data =
reinterpret_cast<const color_rgba8_t *>(repacked_data ? repacked_data.get() : _t.data.data());
WriteTextureMips(rgba_data, res, mip_count, use_compression, stage_data, data_size);
} else if (src_fmt == eTexFormat::RGB8) {
const auto *rgb_data =
reinterpret_cast<const color_rgb8_t *>(repacked_data ? repacked_data.get() : _t.data.data());
WriteTextureMips(rgb_data, res, mip_count, use_compression, stage_data, data_size);
} else if (src_fmt == eTexFormat::RG8) {
const auto *rg_data =
reinterpret_cast<const color_rg8_t *>(repacked_data ? repacked_data.get() : _t.data.data());
WriteTextureMips(rg_data, res, mip_count, use_compression, stage_data, data_size);
} else if (src_fmt == eTexFormat::R8) {
const auto *r_data =
reinterpret_cast<const color_r8_t *>(repacked_data ? repacked_data.get() : _t.data.data());
WriteTextureMips(r_data, res, mip_count, use_compression, stage_data, data_size);
}
}
temp_stage_buf.Unmap();
TexParams p = {};
p.w = _t.w;
p.h = _t.h;
p.format = fmt;
if (_t.is_srgb && !is_YCoCg && !RequiresManualSRGBConversion(fmt)) {
p.format = ToSRGBFormat(p.format);
}
p.mip_count = mip_count;
p.usage = Bitmask<eTexUsage>(eTexUsage::Transfer) | eTexUsage::Sampled;
p.sampling.filter = eTexFilter::Nearest;
std::pair<uint32_t, uint32_t> ret =
bindless_textures_.emplace(_t.name ? _t.name : "Bindless Tex", ctx_, p, ctx_->default_mem_allocs(), log_);
{ // Submit GPU commands
CommandBuffer cmd_buf = BegSingleTimeCommands(ctx_->api(), ctx_->device(), ctx_->temp_command_pool());
int res[2] = {_t.w, _t.h};
uint32_t data_offset = 0;
for (int i = 0; i < p.mip_count; ++i) {
bindless_textures_[ret.first].SetSubImage(i, 0, 0, 0, res[0], res[1], 1, p.format, temp_stage_buf, cmd_buf,
data_offset, data_size[i]);
res[0] = std::max(res[0] / 2, 1);
res[1] = std::max(res[1] / 2, 1);
data_offset += round_up(data_size[i], 4096);
}
EndSingleTimeCommands(ctx_->api(), ctx_->device(), ctx_->graphics_queue(), cmd_buf, ctx_->temp_command_pool());
}
temp_stage_buf.FreeImmediate();
log_->Info("Ray: Texture '%s' loaded (%ix%i)", _t.name, _t.w, _t.h);
assert(ret.first <= 0x00ffffff);
if (_t.is_srgb && (is_YCoCg || RequiresManualSRGBConversion(fmt))) {
ret.first |= TEX_SRGB_BIT;
}
if (reconstruct_z) {
ret.first |= TEX_RECONSTRUCT_Z_BIT;
}
if (is_YCoCg) {
ret.first |= TEX_YCOCG_BIT;
}
return TextureHandle{ret.first, ret.second};
}
template <typename T, int N>
void Ray::NS::Scene::WriteTextureMips(const color_t<T, N> data[], const int _res[2], const int mip_count,
const bool compress, uint8_t out_data[], uint32_t out_size[16]) {
int src_res[2] = {_res[0], _res[1]};
// TODO: try to get rid of these allocations
std::vector<color_t<T, N>> _src_data, dst_data;
for (int i = 1; i < mip_count; ++i) {
const int dst_res[2] = {std::max(src_res[0] / 2, 1), std::max(src_res[1] / 2, 1)};
dst_data.clear();
dst_data.reserve(dst_res[0] * dst_res[1]);
const color_t<T, N> *src_data = (i == 1) ? data : _src_data.data();
for (int y = 0; y < dst_res[1]; ++y) {
for (int x = 0; x < dst_res[0]; ++x) {
const color_t<T, N> c00 = src_data[(2 * y + 0) * src_res[0] + (2 * x + 0)];
const color_t<T, N> c10 = src_data[(2 * y + 0) * src_res[0] + std::min(2 * x + 1, src_res[0] - 1)];
const color_t<T, N> c11 =
src_data[std::min(2 * y + 1, src_res[1] - 1) * src_res[0] + std::min(2 * x + 1, src_res[0] - 1)];
const color_t<T, N> c01 = src_data[std::min(2 * y + 1, src_res[1] - 1) * src_res[0] + (2 * x + 0)];
color_t<T, N> res;
for (int j = 0; j < N; ++j) {
res.v[j] = (c00.v[j] + c10.v[j] + c11.v[j] + c01.v[j]) / 4;
}
dst_data.push_back(res);
}
}
assert(dst_data.size() == (dst_res[0] * dst_res[1]));
out_data += round_up(out_size[i - 1], 4096);
if (compress && N <= 3) {
if (N == 3) {
auto temp_YCoCg = ConvertRGB_to_CoCgxY(&dst_data[0].v[0], dst_res[0], dst_res[1]);
out_size[i] = GetRequiredMemory_BC3(dst_res[0], dst_res[1], TextureDataPitchAlignment);
CompressImage_BC3<true /* Is_YCoCg */>(temp_YCoCg.get(), dst_res[0], dst_res[1], out_data,
GetRequiredMemory_BC3(dst_res[0], 1, TextureDataPitchAlignment));
} else if (N == 1) {
out_size[i] = GetRequiredMemory_BC4(dst_res[0], dst_res[1], TextureDataPitchAlignment);
CompressImage_BC4<N>(&dst_data[0].v[0], dst_res[0], dst_res[1], out_data,
GetRequiredMemory_BC4(dst_res[0], 1, TextureDataPitchAlignment));
} else if (N == 2) {
out_size[i] = GetRequiredMemory_BC5(dst_res[0], dst_res[1], TextureDataPitchAlignment);
CompressImage_BC5<2>(&dst_data[0].v[0], dst_res[0], dst_res[1], out_data,
GetRequiredMemory_BC5(dst_res[0], 1, TextureDataPitchAlignment));
}
} else {
out_size[i] = int(dst_res[1] * round_up(dst_res[0] * sizeof(color_t<T, N>), TextureDataPitchAlignment));
int j = 0;
for (int y = 0; y < dst_res[1]; ++y) {
memcpy(&out_data[j], &dst_data[y * dst_res[0]], dst_res[0] * sizeof(color_t<T, N>));
j += round_up(dst_res[0] * sizeof(color_t<T, N>), TextureDataPitchAlignment);
}
}
src_res[0] = dst_res[0];
src_res[1] = dst_res[1];
std::swap(_src_data, dst_data);
}
}
inline Ray::MaterialHandle Ray::NS::Scene::AddMaterial_nolock(const shading_node_desc_t &m) {
material_t mat = {};
mat.type = m.type;
mat.textures[BASE_TEXTURE] = m.base_texture._index;
mat.roughness_unorm = pack_unorm_16(m.roughness);
mat.textures[ROUGH_TEXTURE] = m.roughness_texture._index;
memcpy(&mat.base_color[0], &m.base_color[0], 3 * sizeof(float));
mat.ior = m.ior;
mat.tangent_rotation = 0.0f;
mat.flags = 0;
if (m.type == eShadingNode::Diffuse) {
mat.sheen_unorm = pack_unorm_16(clamp(0.5f * m.sheen, 0.0f, 1.0f));
mat.sheen_tint_unorm = pack_unorm_16(clamp(m.tint, 0.0f, 1.0f));
mat.textures[METALLIC_TEXTURE] = m.metallic_texture._index;
} else if (m.type == eShadingNode::Glossy) {
mat.tangent_rotation = 2.0f * PI * m.anisotropic_rotation;
mat.textures[METALLIC_TEXTURE] = m.metallic_texture._index;
mat.tint_unorm = pack_unorm_16(clamp(m.tint, 0.0f, 1.0f));
} else if (m.type == eShadingNode::Refractive) {
} else if (m.type == eShadingNode::Emissive) {
mat.strength = m.strength;
if (m.importance_sample) {
mat.flags |= MAT_FLAG_IMP_SAMPLE;
}
} else if (m.type == eShadingNode::Mix) {
mat.strength = m.strength;
mat.textures[MIX_MAT1] = m.mix_materials[0]._index;
mat.textures[MIX_MAT2] = m.mix_materials[1]._index;
if (m.mix_add) {
mat.flags |= MAT_FLAG_MIX_ADD;
}
} else if (m.type == eShadingNode::Transparent) {
}
mat.textures[NORMALS_TEXTURE] = m.normal_map._index;
mat.normal_map_strength_unorm = pack_unorm_16(clamp(m.normal_map_intensity, 0.0f, 1.0f));
const std::pair<uint32_t, uint32_t> mi = materials_.push(mat);
return MaterialHandle{mi.first, mi.second};
}
inline Ray::MaterialHandle Ray::NS::Scene::AddMaterial(const principled_mat_desc_t &m) {
material_t main_mat = {};
main_mat.type = eShadingNode::Principled;
main_mat.textures[BASE_TEXTURE] = m.base_texture._index;
memcpy(&main_mat.base_color[0], &m.base_color[0], 3 * sizeof(float));
main_mat.sheen_unorm = pack_unorm_16(clamp(0.5f * m.sheen, 0.0f, 1.0f));
main_mat.sheen_tint_unorm = pack_unorm_16(clamp(m.sheen_tint, 0.0f, 1.0f));
main_mat.roughness_unorm = pack_unorm_16(clamp(m.roughness, 0.0f, 1.0f));
main_mat.tangent_rotation = 2.0f * PI * clamp(m.anisotropic_rotation, 0.0f, 1.0f);
main_mat.textures[ROUGH_TEXTURE] = m.roughness_texture._index;
main_mat.metallic_unorm = pack_unorm_16(clamp(m.metallic, 0.0f, 1.0f));
main_mat.textures[METALLIC_TEXTURE] = m.metallic_texture._index;
main_mat.ior = m.ior;
main_mat.flags = 0;
main_mat.transmission_unorm = pack_unorm_16(clamp(m.transmission, 0.0f, 1.0f));
main_mat.transmission_roughness_unorm = pack_unorm_16(clamp(m.transmission_roughness, 0.0f, 1.0f));
main_mat.textures[NORMALS_TEXTURE] = m.normal_map._index;
main_mat.normal_map_strength_unorm = pack_unorm_16(clamp(m.normal_map_intensity, 0.0f, 1.0f));
main_mat.anisotropic_unorm = pack_unorm_16(clamp(m.anisotropic, 0.0f, 1.0f));
main_mat.specular_unorm = pack_unorm_16(clamp(m.specular, 0.0f, 1.0f));
main_mat.textures[SPECULAR_TEXTURE] = m.specular_texture._index;
main_mat.specular_tint_unorm = pack_unorm_16(clamp(m.specular_tint, 0.0f, 1.0f));
main_mat.clearcoat_unorm = pack_unorm_16(clamp(m.clearcoat, 0.0f, 1.0f));
main_mat.clearcoat_roughness_unorm = pack_unorm_16(clamp(m.clearcoat_roughness, 0.0f, 1.0f));
const std::pair<uint32_t, uint32_t> mi = materials_.push(main_mat);
auto root_node = MaterialHandle{mi.first, mi.second};
MaterialHandle emissive_node = InvalidMaterialHandle, transparent_node = InvalidMaterialHandle;
if (m.emission_strength > 0.0f &&
(m.emission_color[0] > 0.0f || m.emission_color[1] > 0.0f || m.emission_color[2] > 0.0f)) {
shading_node_desc_t emissive_desc;
emissive_desc.type = eShadingNode::Emissive;
memcpy(emissive_desc.base_color, m.emission_color, 3 * sizeof(float));
emissive_desc.base_texture = m.emission_texture;
emissive_desc.strength = m.emission_strength;
emissive_desc.importance_sample = m.importance_sample;
emissive_node = AddMaterial(emissive_desc);
}
if (m.alpha != 1.0f || m.alpha_texture != InvalidTextureHandle) {
shading_node_desc_t transparent_desc;
transparent_desc.type = eShadingNode::Transparent;
transparent_node = AddMaterial(transparent_desc);
}
if (emissive_node != InvalidMaterialHandle) {
if (root_node == InvalidMaterialHandle) {
root_node = emissive_node;
} else {
shading_node_desc_t mix_node;
mix_node.type = eShadingNode::Mix;
mix_node.base_texture = InvalidTextureHandle;
mix_node.strength = 0.5f;
mix_node.ior = 0.0f;
mix_node.mix_add = true;
mix_node.mix_materials[0] = root_node;
mix_node.mix_materials[1] = emissive_node;
root_node = AddMaterial(mix_node);
}
}
if (transparent_node != InvalidMaterialHandle) {
if (root_node == InvalidMaterialHandle || m.alpha == 0.0f) {
root_node = transparent_node;
} else {
shading_node_desc_t mix_node;
mix_node.type = eShadingNode::Mix;
mix_node.base_texture = m.alpha_texture;
mix_node.strength = m.alpha;
mix_node.ior = 0.0f;
mix_node.mix_materials[0] = transparent_node;
mix_node.mix_materials[1] = root_node;
root_node = AddMaterial(mix_node);
}
}
return root_node;
}
inline Ray::MeshHandle Ray::NS::Scene::AddMesh(const mesh_desc_t &_m) {
std::vector<bvh_node_t> new_nodes;
aligned_vector<tri_accel_t> new_tris;
std::vector<uint32_t> new_tri_indices;
std::vector<uint32_t> new_vtx_indices;
bvh_settings_t s;
s.oversplit_threshold = -1.0f;
s.allow_spatial_splits = _m.allow_spatial_splits;
s.use_fast_bvh_build = _m.use_fast_bvh_build;
s.min_primitives_in_leaf = 8;
s.primitive_alignment = 2;
fvec4 bbox_min{FLT_MAX}, bbox_max{-FLT_MAX};
if (use_hwrt_) {
for (int j = 0; j < int(_m.vtx_indices.size()); j += 3) {
fvec4 p[3];
const uint32_t i0 = _m.vtx_indices[j + 0], i1 = _m.vtx_indices[j + 1], i2 = _m.vtx_indices[j + 2];
memcpy(value_ptr(p[0]), &_m.vtx_positions.data[_m.vtx_positions.offset + i0 * _m.vtx_positions.stride],
3 * sizeof(float));
memcpy(value_ptr(p[1]), &_m.vtx_positions.data[_m.vtx_positions.offset + i1 * _m.vtx_positions.stride],
3 * sizeof(float));
memcpy(value_ptr(p[2]), &_m.vtx_positions.data[_m.vtx_positions.offset + i2 * _m.vtx_positions.stride],
3 * sizeof(float));
bbox_min = min(bbox_min, min(p[0], min(p[1], p[2])));
bbox_max = max(bbox_max, max(p[0], max(p[1], p[2])));
}
} else {
aligned_vector<mtri_accel_t> _unused;
PreprocessMesh(_m.vtx_positions, _m.vtx_indices, _m.base_vertex, s, new_nodes, new_tris, new_tri_indices,
_unused);
memcpy(value_ptr(bbox_min), new_nodes[0].bbox_min, 3 * sizeof(float));
memcpy(value_ptr(bbox_max), new_nodes[0].bbox_max, 3 * sizeof(float));
}
std::vector<tri_mat_data_t> new_tri_materials(_m.vtx_indices.size() / 3, {0xffff, 0xffff});
// init triangle materials
for (const mat_group_desc_t &grp : _m.groups) {
bool is_front_solid = true, is_back_solid = true;
uint32_t material_stack[32];
material_stack[0] = grp.front_mat._index;
uint32_t material_count = 1;
while (material_count && is_front_solid) {
const material_t &mat = materials_[material_stack[--material_count]];
if (mat.type == eShadingNode::Mix) {