-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathviewer.cxx
1563 lines (1218 loc) · 42 KB
/
viewer.cxx
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
#define CGLTF_IMPLEMENTATION
#include "../thirdparty/cgltf/cgltf.h"
#define STB_IMAGE_IMPLEMENTATION
#include "texture.hxx"
#include "appglfw.hxx"
#include <vector>
#include <iostream>
#include <type_traits>
#include <cassert>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include "brdf.hxx"
#include "tonemapping.hxx"
// PBR metallic roughness
struct pbrMetallicRoughness_t {
// baseColorTexture
// metallicRoughnessTexture
vec4 baseColorFactor;
float metallicFactor;
float roughnessFactor;
float padding0, padding1;
};
// KHR_materials_pbrSpecularGlossiness
struct KHR_materials_pbrSpecularGlossiness_t {
// diffuseTexture
// specularGlossinessTexture
vec4 diffuseFactor;
vec3 specularFactor;
float glossinessFactor;
};
// KHR_materials_clearcoat
struct KHR_materials_clearcoat_t {
// clearcoatTexture
// clearcoatRoughnessTexture
// clearcoatNormalTexture
float clearcoatFactor;
float clearcoatRoughnessFactor;
float padding0, padding1;
};
// KHR_materials_transmission
struct KHR_materials_transmission_t {
// transmissionTexture
float transmissionFactor;
float ior;
float padding0, padding1;
};
struct material_uniform_t {
// Textures:
// normalTexture
// occlusionTexture
// emissiveTexture
vec3 emissiveFactor;
float alphaCutoff;
// Material models
pbrMetallicRoughness_t pbrMetallicRoughness;
KHR_materials_pbrSpecularGlossiness_t pbrSpecularGlossiness;
KHR_materials_clearcoat_t clearcoat;
KHR_materials_transmission_t transmission;
};
enum light_type_t {
light_type_directional,
light_type_point,
light_type_spot,
};
struct light_t {
vec3 direction;
float range;
vec3 color;
float intensity;
vec3 position;
float innerConeCos;
float outerConeCos;
light_type_t type;
vec2 padding;
};
struct uniform_t {
// Transform model space into world space.
mat4 model_to_world;
// Transform world space into clip space.
mat4 view_projection;
// The sky projection*view. This removes any translation.
mat4 sky_view_projection;
// The normal matrix is just a rotation (and possibly a scale). It
// ignores translation, so encode it as a mat3.
mat3x4 normal;
vec3 camera; // Position of camera.
float normal_scale;
material_uniform_t material;
float exposure;
int light_count;
/*
light_t lights[16];
mat4 joint_matrices[75];
// TODO: Make these mat4x3. We only use 3D matrix operations.
mat4 joint_normal_matrices[75];
*/
};
////////////////////////////////////////////////////////////////////////////////
// Vertex attribute and sampler binding locations.
enum typename vattrib_index_t {
// Shader locations for vertex attributes.
vattrib_position = vec3,
vattrib_normal = vec3,
vattrib_tangent = vec3,
vattrib_binormal = vec3,
// Repeat these vertex attributes in cycles of three. We don't have to
// bind all of them.
vattrib_texcoord0 = vec2,
vattrib_joints0 = ivec4,
vattrib_weights0 = vec4,
vattrib_texcoord1 = vec2,
vattrib_joints1 = ivec4,
vattrib_weights1 = vec4,
};
enum typename sampler_index_t {
// Core
sampler_normal = sampler2D,
sampler_occlusion = sampler2D,
sampler_emissive = sampler2D,
// pbrMetallicRoughness
sampler_baseColor = sampler2D,
sampler_metallicRoughness = sampler2D,
// pbrSpecularGlossiness
sampler_diffuse = sampler2D,
sampler_specularGlossiness = sampler2D,
// KHR_materials_clearcoat
sampler_clearcoat = sampler2D,
sampler_clearcoatRoughness = sampler2D,
sampler_clearcoatNormal = sampler2D,
// KHR_materials_transmission
sampler_transmission = sampler2D,
// Image-based lighting textures and LUTs.
// The Env samplers are cube maps.
sampler_GGXLut = sampler2D,
sampler_GGXEnv = samplerCube,
sampler_LambertianEnv = samplerCube,
sampler_CharlieLut = sampler2D,
sampler_CharlieEnv = samplerCube,
};
////////////////////////////////////////////////////////////////////////////////
// Vertex and fragment shader feature sets. The spaceship generates
// relational operators so we can use these as keys in maps.
// Shader specialization constants
struct vert_features_t {
// Each flag indicates the availability of a vertex attribute.
// vattrib_position is always available.
bool normal; // vattrib_normal
bool tangent; // vattrib_tangent + vattrib_binormal
bool texcoord0; // vattrib_texcoord0
bool texcoord1; // vattrib_texcoord1
bool joints0; // vattrib_joints0 + vattrib_weights0
bool joints1; // vattrib_joints1 + vattrib_weights1
};
[[spirv::constant(0)]]
vert_features_t vert_features;
struct frag_features_t {
// Incoming vertex properties.
bool normal;
bool tangents;
// Available texture maps.
bool normal_map;
bool emissive_map;
bool occlusion_map;
// Material properties.
bool metallicRoughness;
bool anisotropy;
bool ibl;
bool point_lights;
};
[[spirv::constant(0)]]
frag_features_t frag_features;
[[spirv::uniform(0)]]
uniform_t uniforms;
inline mat4 skinning_matrix(ivec4 joints, vec4 weights, const mat4* matrices) {
mat4 skin =
weights.x * matrices[joints.x] +
weights.y * matrices[joints.y] +
weights.z * matrices[joints.z] +
weights.w * matrices[joints.w];
return skin;
}
[[spirv::vert]]
void vert_main() {
// Always load the position attribute.
vec4 pos = vec4(shader_in<vattrib_position>, 1);
// TODO: Apply skeletal animation.
/*
if(vert_features.joints0) {
// Compute the first 4 components of the skin matrix.
mat4 skin = skinning_matrix(
shader_in<vattrib_joints0, ivec4>,
shader_in<vattrib_weights0>,
uniforms.joint_matrices
);
if(vert_features.joints1) {
// Compute the next 4 components of the skin matrix.
skin += skinning_matrix(
shader_in<vattrib_joints1, ivec4>,
shader_in<vattrib_weights1>,
uniforms.joint_matrices
);
}
// Advance the position by the skin matrix.
pos = skin * pos;
}
*/
// Transform the model vertex into world space.
pos = uniforms.model_to_world * pos;
// Pass the vertex position to the fragment shader.
shader_out<vattrib_position> = pos.xyz / pos.w;
// Pass the vertex normal to the fragment shader.
if(vert_features.normal) {
// Load the vertex normal attribute.
vec3 n = shader_in<vattrib_normal>;
// TODO: Apply morphing.
// TODO: Apply skinning.
// Rotate into normal space and send to the fragment shader.
shader_out<vattrib_normal> = normalize(mat3(uniforms.normal) * n);
}
// Pass through texcoords.
if(vert_features.texcoord0)
shader_out<vattrib_texcoord0> = shader_in<vattrib_texcoord0>;
if(vert_features.texcoord1)
shader_out<vattrib_texcoord1> = shader_in<vattrib_texcoord1>;
// Set the vertex positions.
glvert_Output.Position = uniforms.view_projection * pos;
}
////////////////////////////////////////////////////////////////////////////////
struct normal_info_t {
vec3 ng;
vec3 n;
vec3 t;
vec3 b;
};
inline normal_info_t get_normal_info(vec3 pos, vec3 v, vec2 uv) {
// Get derivatives of texcoord wrt fragment coordinates.
vec3 uv_dx = vec3(glfrag_dFdx(uv), 0);
vec3 uv_dy = vec3(glfrag_dFdy(uv), 0);
vec3 t_ = (uv_dy.t * glfrag_dFdx(pos) - uv_dx.t * glfrag_dFdy(pos)) /
(uv_dx.s * uv_dy.t - uv_dy.s * uv_dx.t);
vec3 ng, t, b;
if(frag_features.tangents) {
ng = shader_in<vattrib_normal>;
t = shader_in<vattrib_tangent>;
b = shader_in<vattrib_binormal>;
} else {
if(frag_features.normal) {
ng = shader_in<vattrib_normal>;
} else {
ng = normalize(cross(glfrag_dFdx(pos), glfrag_dFdy(pos)));
}
// Compute tangent and binormal.
t = normalize(t_ - ng * dot(ng, t_));
b = cross(ng, t);
}
// For back-facing surface, the tangential basis vectors are negated.
float facing = 2 * step(0.f, dot(v, ng)) - 1;
t *= facing;
b *= facing;
ng *= facing;
vec3 direction;
if(frag_features.anisotropy) {
} else {
direction = vec3(1, 0, 0);
}
t = mat3(t, b, ng) * direction;
b = normalize(cross(ng, t));
vec3 n;
if(frag_features.normal_map) {
n = 2 * texture(shader_sampler<sampler_normal>, uv).rgb - 1;
n *= vec3(uniforms.normal_scale, uniforms.normal_scale, 1);
n = mat3(t, b, ng) * normalize(n);
} else {
n = ng;
}
normal_info_t info;
info.ng = ng;
info.t = t;
info.b = b;
info.n = n;
return info;
}
struct material_info_t {
vec3 f0;
float roughness;
vec3 albedo;
float alpha_roughness;
vec3 f90;
float metallic;
vec3 n;
vec3 base_color;
};
inline void get_metallic_roughness(material_info_t& info, float f0, vec2 uv) {
info.metallic = 1; uniforms.material.pbrMetallicRoughness.metallicFactor;
info.roughness = 1; uniforms.material.pbrMetallicRoughness.roughnessFactor;
// Sample the metallic-roughness texture. This has g and b channels.
vec4 mr = texture(shader_sampler<sampler_metallicRoughness>, uv);
info.roughness *= mr.g;
info.metallic *= mr.b;
// TODO: Provide for specular override of f0.
info.albedo = mix(info.base_color * (1 - f0), 0, info.metallic);
info.f0 = mix(f0, info.base_color, info.metallic);
}
// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#appendix-b-brdf-implementation
inline float get_range_attenuation(float range, float distance) {
// NOTE: Multiple returns cause validation error.
if(range <= 0)
return 1;
else
return clamp(1.f - pow(distance / range, 4.f), 1.f, 0.f) /
(distance * distance);
}
inline float get_spot_attenuation(vec3 point_to_light, vec3 direction,
float outer_cos, float inner_cos) {
float cos = dot(normalize(direction), -normalize(point_to_light));
return
cos <= outer_cos ? 0 :
cos >= inner_cos ? 1 :
smoothstep(outer_cos, inner_cos, cos);
}
// Image-based lighting.
inline vec3 getIBLRadianceGGX(vec3 n, vec3 v, float roughness, vec3 color) {
int levels = textureQueryLevels(shader_sampler<sampler_GGXEnv>);
float NdotV = clamp(dot(n, v), 0.f, 1.f);
float lod = levels * clamp(roughness, 0.f, 1.f);
vec3 reflection = normalize(reflect(-v, n));
vec2 brdfSamplePoint = clamp(vec2(NdotV, roughness), 0, 1);
vec2 brdf = texture(
shader_sampler<sampler_GGXLut>,
brdfSamplePoint
).rg;
vec3 specular = textureLod(
shader_sampler<sampler_GGXEnv>,
reflection,
lod
).rgb;
return specular * (color * brdf.x + brdf.y);
}
inline vec3 getIBLRadianceLambertian(vec3 n, vec3 color) {
vec3 diffuseLight = texture(
shader_sampler<sampler_LambertianEnv>,
n
).rgb;
return diffuseLight * color;
}
[[spirv::frag]]
void frag_main() {
vec3 pos = shader_in<vattrib_position>;
vec2 uv = shader_in<vattrib_texcoord0>;
vec4 base_color = texture(shader_sampler<sampler_baseColor>, uv);
base_color = sRGBToLinear(base_color);
vec3 v = normalize(uniforms.camera - pos);
// Get the position of the fragment.
normal_info_t normal = get_normal_info(pos, v, uv);
vec3 n = normal.n;
vec3 t = normal.t;
vec3 b = normal.b;
float NdotV = clamp(dot(n, v), 0.f, 1.f);
float TdotV = clamp(dot(t, v), 0.f, 1.f);
float BdotV = clamp(dot(b, v), 0.f, 1.f);
// The default index of refraction of 1.5 yields a dielectric normal incidence reflectance of 0.04.
float ior = 1.5;
float f0_ior = 0.04;
material_info_t material { };
material.base_color = base_color.rgb;
if(frag_features.metallicRoughness) {
// Load metallic-roughness properties once. We'll need these for each light
// in the scene.
get_metallic_roughness(material, f0_ior, uv);
}
// Clamp the metallic-roughness parameters.
material.roughness = clamp(material.roughness, 0.f, 1.f);
material.metallic = clamp(material.metallic, 0.f, 1.f);
material.alpha_roughness = material.roughness * material.roughness;
// Compute reflectance.
float reflectance = max(max(material.f0.r, material.f0.g), material.f0.b);
material.f90 = vec3(clamp(50 * reflectance, 0.f, 1.f));
material.n = n;
vec3 f_diffuse(0);
vec3 f_specular(0);
if(frag_features.ibl) {
// Use image-based lighting.
f_specular += getIBLRadianceGGX(n, v, material.roughness, material.f0);
f_diffuse += getIBLRadianceLambertian(n, material.albedo);
}
/*
// Specialization constant over point lighting.
if(frag_features.point_lights) {
// Dynamic uniform control flow over all lights.
for(int i = 0; i < uniforms.light_count; ++i) {
light_t light = uniforms.lights[i];
vec3 point_to_light = -light.direction;
float attenuation = 1;
if(light_type_directional == light.type) {
point_to_light = -light.direction;
} else if(light_type_point == light.type) {
point_to_light = light.position - pos;
attenuation = get_range_attenuation(light.range, length(point_to_light));
} else {
// light_type_spot
point_to_light = light.position - pos;
attenuation = get_range_attenuation(light.range, length(point_to_light));
attenuation *= get_spot_attenuation(point_to_light, light.direction,
light.outerConeCos, light.innerConeCos);
}
vec3 intensity = attenuation * light.intensity * light.color;
vec3 l = normalize(point_to_light);
vec3 h = normalize(l + v); // Half-angle vector.
float NdotL = clamp(dot(n, l), 0.f, 1.f);
float NdotH = clamp(dot(n, h), 0.f, 1.f);
float LdotH = clamp(dot(l, h), 0.f, 1.f);
float VdotH = clamp(dot(v, h), 0.f, 1.f);
if(NdotL > 0 || NdotV > 0) {
// Calculation of analytical light
//https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#acknowledgments AppendixB
f_diffuse += intensity * NdotL * BRDF_lambertian(material.f0,
material.f90, material.albedo, VdotH);
f_specular += intensity * NdotL * BRDF_specularGGX(material.f0,
material.f90, material.alpha_roughness, VdotH, NdotL, NdotV,
NdotH);
}
}
}
*/
vec3 f_emissive(0);
if(frag_features.emissive_map) {
vec3 sample = texture(shader_sampler<sampler_emissive>, uv).rgb;
f_emissive = sRGBToLinear(sample);
}
vec3 color = f_diffuse + f_specular + f_emissive;
if(frag_features.occlusion_map) {
float ao = texture(shader_sampler<sampler_occlusion>, uv).r;
color = mix(color, color * ao, 1.f);
}
shader_out<0, vec4> = vec4(toneMap(color, uniforms.exposure), base_color.a);
}
////////////////////////////////////////////////////////////////////////////////
// Skybox shaders
[[spirv::vert]]
void vert_sky() {
vec3 vertex = shader_in<vattrib_position>;
vec4 pos = uniforms.sky_view_projection * vec4(vertex, 1);
// Return .z with the .w value to get maximum depth for the skybox.
glvert_Output.Position = pos.xyww;
// Use the cube vertex position as the sampler.
shader_out<vattrib_position> = vertex;
}
[[spirv::frag]]
void frag_sky() {
vec3 texcoord = shader_in<vattrib_position>;
vec3 color = texture(
shader_sampler<sampler_GGXEnv>,
texcoord,
-.5f
).rgb;
shader_out<0, vec4> = vec4(toneMap(color, uniforms.exposure), 1);
}
////////////////////////////////////////////////////////////////////////////////
struct env_map_t {
// GL textures.
GLuint GGXLut; // specular/specular.ktx2
GLuint GGXEnv; // images/lut_ggx.png
GLuint LambertianEnv; // lambertian/diffuse.ktx2
GLuint CharlieLut; // images/lut_charlie.png
GLuint CharlieEnv; // charlie/sheen.ktx2
};
struct env_paths_t {
const char* GGXLut;
const char* GGXEnv;
const char* LambertianEnv;
const char* CharlieLut;
const char* CharlieEnv;
};
GLuint create_hdr_cubemap(const char* path) {
const uint8_t ktx2_version[12] {
0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
};
struct ktx2_header_t {
char identifier[12];
uint32_t vkFormat;
uint32_t typeSize;
uint32_t width;
uint32_t height;
uint32_t pixelDepth;
uint32_t layerCount;
uint32_t faceCount;
uint32_t levelCount;
uint32_t supercompressionScheme;
// Index
uint32_t dfdByteOffset;
uint32_t dfdByteLength;
uint32_t kvdByteOffset;
uint32_t kvdByteLength;
uint64_t sgdByteOffset;
uint64_t sgdByteLength;
struct indexing_t {
uint64_t byteOffset;
uint64_t byteLength;
uint64_t uncompressedByteLength;
};
indexing_t levels[1]; // levelCount elements.
};
int fd = open(path, O_RDONLY);
if(-1 == fd) {
printf("cannot open file %s\n", path);
exit(1);
}
struct stat statbuf;
if(-1 == fstat(fd, &statbuf)) {
printf("cannot stat file %s\n", path);
exit(1);
}
if(statbuf.st_size < sizeof(ktx2_header_t)) {
printf("file %s is too small to be a ktx2 file", path);
exit(1);
}
const char* data = (const char*)mmap(nullptr, statbuf.st_size, PROT_READ,
MAP_PRIVATE, fd, 0);
const ktx2_header_t& header = *(const ktx2_header_t*)data;
if(memcmp(header.identifier, ktx2_version, 12)) {
printf("file %s has the wrong KTX2 identifier", path);
exit(1);
}
if(6 != header.faceCount) {
printf("file %s does not hold a cube map", path);
exit(1);
}
GLenum format, iformat;
switch(header.vkFormat) {
case 97:
format = GL_HALF_FLOAT;
iformat = GL_RGBA16F;
break;
case 109:
format = GL_FLOAT;
iformat = GL_RGBA32F;
break;
default:
printf("cube map in %s is not encoded in a supported format", path);
exit(1);
}
// Construct the cube map and all of its face-layers.
GLuint cubemap;
glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &cubemap);
glTextureStorage2D(cubemap, header.levelCount, iformat, header.width,
header.height);
// The file is encoded by levels.
for(int level = 0; level < header.levelCount; ++level) {
ktx2_header_t::indexing_t indexing = header.levels[level];
// Find the mip map level dimensions.
uint32_t width = header.width >> level;
uint32_t height = header.height >> level;
// Upload all six levels at once.
const char* level_data = data + indexing.byteOffset;
glTextureSubImage3D(cubemap, level, 0, 0, 0, width, height, 6, GL_RGBA,
GL_HALF_FLOAT, level_data);
}
munmap((void*)data, statbuf.st_size);
close(fd);
glTextureParameteri(cubemap, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(cubemap, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(cubemap, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(cubemap, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return cubemap;
}
env_map_t load_env_map(env_paths_t paths) {
env_map_t map { };
map.GGXLut = load_texture(paths.GGXLut);
map.GGXEnv = create_hdr_cubemap(paths.GGXEnv);
map.LambertianEnv = create_hdr_cubemap(paths.LambertianEnv);
map.CharlieLut = load_texture(paths.CharlieLut);
map.CharlieEnv = create_hdr_cubemap(paths.CharlieEnv);
return map;
}
////////////////////////////////////////////////////////////////////////////////
int find_node_index(const cgltf_data* data, const cgltf_node* node) {
return node - data->nodes;
}
int find_image_index(const cgltf_data* data, cgltf_image* image) {
return image - data->images;
}
int find_sampler_index(const cgltf_data* data, cgltf_sampler* sampler) {
return sampler - data->samplers;
}
int find_texture_index(const cgltf_data* data, cgltf_texture* texture) {
return texture - data->textures;
}
int find_material_index(const cgltf_data* data, cgltf_material* material) {
return material - data->materials;
}
int find_view_index(const cgltf_data* data, const cgltf_buffer_view* view) {
return view - data->buffer_views;
}
int find_buffer_index(const cgltf_data* data, const cgltf_buffer* buffer) {
return buffer - data->buffers;
}
struct texture_view_t {
// Index of the texture in the gltf stream.
int index = -1;
// Index of the TEXCOORD_n in the vertex attribute stream.
int texcoord = 0;
// The scalar multiplied applied to each normal vector of the normal
// texture.
// Also strength for occlusionTextureInfo.
float scale = 1.f;
explicit operator bool() const noexcept { return -1 != index; }
};
struct material_textures_t {
// Core:
texture_view_t normal;
texture_view_t occlusion;
texture_view_t emissive;
// pbrMetallicRoughness
texture_view_t baseColor;
texture_view_t metallicRoughness;
// KHR_materials_pbrSpecularGlossiness
texture_view_t diffuse;
texture_view_t specularGlossiness;
// KHR_materials_clearcoat
texture_view_t clearcoat;
texture_view_t clearcoatRoughness;
texture_view_t clearcoatNormal;
// KHR_materials_transmission
texture_view_t transmission;
};
struct material_t {
bool has_pbr_metallic_roughness;
bool has_pbr_specular_glossiness;
bool has_clearcoat;
bool has_transmission;
material_uniform_t uniform;
material_textures_t textures;
};
// Binary search in the array of animation keyframe times.
// This searches the input accessor of the animation sampler.
std::pair<int, float> find_animation_interpolate(
const cgltf_animation_sampler* sampler, float t) {
// Check sampler->input->min and max.
cgltf_accessor* input = sampler->input;
assert(cgltf_component_type_r_32f == input->component_type);
assert(cgltf_type_scalar == input->type);
const cgltf_buffer_view* view = input->buffer_view;
const char* data = (const char*)view->buffer->data + view->offset;
const float* times = (const float*)data;
const float* lb = std::lower_bound(times, times + input->count, t);
int index = lb - times;
float weight = 0;
if(index < input->count) {
float t0 = times[index];
float t1 = times[index + 1];
weight = (t - t0) / (t1 - t0);
} else {
index = input->count - 1;
weight = 1;
}
return { index, weight };
}
vec3 interpolate_lerp(const cgltf_animation_sampler* sampler,
std::pair<int, float> interpolant) {
cgltf_accessor* output = sampler->output;
assert(cgltf_component_type_r_32f == output->component_type);
assert(cgltf_type_vec3 == output->type);
const cgltf_buffer_view* view = output->buffer_view;
const char* data = (const char*)view->buffer->data + view->offset;
const vec3* vectors = (const vec3*)data;
vec3 a = vectors[interpolant.first];
vec3 b = vectors[interpolant.first + 1];
return a * (1 - interpolant.second) + b * interpolant.second;
}
vec4 interpolate_slerp(const cgltf_animation_sampler* sampler,
std::pair<int, float> interpolant) {
cgltf_accessor* output = sampler->output;
assert(cgltf_component_type_r_32f == output->component_type);
assert(cgltf_type_vec4 == output->type);
const cgltf_buffer_view* view = output->buffer_view;
const char* data = (const char*)view->buffer->data + view->offset;
const vec4* quats = (const vec4*)data;
vec4 a = quats[interpolant.first];
vec4 b = quats[interpolant.first + 1];
return slerp(a, b, interpolant.second);
}
struct animation_t {
enum path_t {
path_translation,
path_rotation,
path_scale,
path_weights,
};
struct channel_t {
int sampler;
int node;
};
std::vector<channel_t> channels;
struct sampler_t {
};
};
struct sampler_t {
GLenum mag_filter, min_filter;
GLenum wrap_s, wrap_t;
};
struct texture_t {
int image;
int sampler;
};
struct prim_t {
int offset; // byte offset into the buffer.
int count;
vec3 min, max;
int material;
// The VAO for rendering the primitive.
GLuint vao = 0;
GLenum elements_type = GL_NONE;
};
struct mesh_t {
std::vector<prim_t> primitives;
};
// Create array buffers for storing vertex data.
struct model_t {
model_t(const char* path);
~model_t();
GLuint load_buffer(const cgltf_buffer* buffer);
GLuint load_image(const cgltf_image* image, const char* data_path);
sampler_t load_sampler(const cgltf_sampler* sampler);
texture_t load_texture(const cgltf_texture* texture);
material_t load_material(const cgltf_material* material);
texture_view_t load_texture_view(const cgltf_texture_view& view);
prim_t load_prim(const cgltf_primitive* prim);
mesh_t load_mesh(const cgltf_mesh* mesh);
void bind_texture(sampler_index_t sampler_index, texture_view_t view);
void bind_material(material_t& material);
void render_primitive(mesh_t& mesh, prim_t& prim);
std::vector<mesh_t> meshes;
std::vector<GLuint> buffers;
std::vector<GLuint> images;
std::vector<sampler_t> samplers;
std::vector<texture_t> textures;
std::vector<material_t> materials;
std::vector<light_t> lights;
cgltf_data* data = nullptr;
};
model_t::model_t(const char* path) {
cgltf_options options { };
printf("Parsing %s...\n", path);
cgltf_result result = cgltf_parse_file(&options, path, &data);
if(cgltf_result_success != result) {
std::cerr<< enum_to_string(result)<< "\n";
exit(1);
}
result = cgltf_load_buffers(&options, data, path);
if(cgltf_result_success != result) {
std::cerr<< enum_to_string(result)<< "\n";
exit(1);
}
// Load the buffers.
buffers.resize(data->buffers_count);
for(int i = 0; i < data->buffers_count; ++i) {
buffers[i] = load_buffer(data->buffers + i);
}
// Load the images.
images.resize(data->images_count);
for(int i = 0; i < data->images_count; ++i) {
images[i] = load_image(data->images + i, path);
}
// Load the textures.
textures.resize(data->textures_count);
for(int i = 0; i < data->textures_count; ++i) {
textures[i] = load_texture(data->textures + i);
}
// Load the samplers. These apply glTextureParameters to the textures.
samplers.resize(data->samplers_count);
for(int i = 0; i < data->samplers_count; ++i) {
samplers[i] = load_sampler(data->samplers + i);
}