-
Notifications
You must be signed in to change notification settings - Fork 24
/
cornell_box.c
2253 lines (2027 loc) · 76.8 KB
/
cornell_box.c
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
#include "example_base.h"
#include <string.h>
#include "../webgpu/imgui_overlay.h"
/* -------------------------------------------------------------------------- *
* WebGPU Example - Cornell Box
*
* A classic Cornell box, using a lightmap generated using software ray-tracing.
*
* Ref:
* https://github.com/webgpu/webgpu-samples/tree/main/src/sample/cornell
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* Shader store
* -------------------------------------------------------------------------- */
#define PRESENTATION_FORMAT "bgra8unorm"
typedef struct {
const char* filename;
file_read_result_t read_result;
} shader_store_entry;
static struct {
shader_store_entry common;
shader_store_entry radiosity;
shader_store_entry rasterizer;
shader_store_entry raytracer;
shader_store_entry tonemapper;
} shader_store = {
.common.filename = "shaders/cornell_box/common.wgsl",
.radiosity.filename = "shaders/cornell_box/radiosity.wgsl",
.rasterizer.filename = "shaders/cornell_box/rasterizer.wgsl",
.raytracer.filename = "shaders/cornell_box/raytracer.wgsl",
.tonemapper.filename = "shaders/cornell_box/tonemapper.wgsl",
};
static void initialize_shader_store_entry(shader_store_entry* entry)
{
read_file(entry->filename, &entry->read_result, true);
log_debug("Read file: %s, size: %d bytes\n", entry->filename,
entry->read_result.size);
ASSERT(entry->read_result.size > 0);
}
static void create_shader_store(void)
{
initialize_shader_store_entry(&shader_store.common);
initialize_shader_store_entry(&shader_store.radiosity);
initialize_shader_store_entry(&shader_store.rasterizer);
initialize_shader_store_entry(&shader_store.raytracer);
initialize_shader_store_entry(&shader_store.tonemapper);
}
static void destroy_shader_store_entry(shader_store_entry* entry)
{
if (entry->read_result.size > 0) {
free(entry->read_result.data);
entry->read_result.size = 0;
}
}
static void destroy_shader_store(void)
{
destroy_shader_store_entry(&shader_store.common);
destroy_shader_store_entry(&shader_store.radiosity);
destroy_shader_store_entry(&shader_store.rasterizer);
destroy_shader_store_entry(&shader_store.raytracer);
destroy_shader_store_entry(&shader_store.tonemapper);
}
static void concat_shader_store_entries(shader_store_entry* e1,
shader_store_entry* e2, char** dst)
{
uint32_t total_size = e1->read_result.size + 1 + e2->read_result.size + 1;
*dst = malloc(total_size);
sprintf(*dst, "%s\n%s%c", e1->read_result.data, e2->read_result.data, '\0');
}
/* -------------------------------------------------------------------------- *
* Common holds the shared WGSL between the shaders, including the common
* uniform buffer.
* -------------------------------------------------------------------------- */
typedef struct {
/* The common uniform buffer bind group and layout */
struct {
WGPUBindGroupLayout bind_group_layout;
WGPUBindGroup bind_group;
} uniforms;
wgpu_context_t* wgpu_context;
wgpu_buffer_t uniform_buffer;
struct {
mat4 view_matrix;
mat4 mvp;
mat4 inv_mvp;
mat4 projection_matrix;
} ubo_vs;
uint64_t frame;
} common_t;
static void common_init_defaults(common_t* this)
{
memset(this, 0, sizeof(*this));
}
static void common_create(common_t* this, wgpu_context_t* wgpu_context,
wgpu_buffer_t* quads)
{
common_init_defaults(this);
this->wgpu_context = wgpu_context;
/* Uniform buffer */
this->uniform_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Common uniform buffer",
.size = 0 + //
4 * 16 + // mvp
4 * 16 + // inv_mvp
4 * 4, // seed
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
});
/* Uniforms bind group layout */
{
WGPUBindGroupLayoutEntry bgl_entries[2] = {
[0] = (WGPUBindGroupLayoutEntry) {
// common_uniforms
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Compute,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = this->uniform_buffer.size,
},
.sampler = {0},
},
[1] = (WGPUBindGroupLayoutEntry) {
// quads
.binding = 1,
.visibility = WGPUShaderStage_Compute,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_ReadOnlyStorage,
.minBindingSize = quads->size,
},
.sampler = {0},
},
};
this->uniforms.bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = "Common bind group layout",
.entryCount = (uint32_t)ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
ASSERT(this->uniforms.bind_group_layout != NULL)
}
/* Uniforms bind group */
{
WGPUBindGroupEntry bg_entries[2] = {
[0] = (WGPUBindGroupEntry) {
// common_uniforms
.binding = 0,
.buffer = this->uniform_buffer.buffer,
.offset = 0,
.size = this->uniform_buffer.size,
},
[1] = (WGPUBindGroupEntry) {
// quads
.binding = 1,
.buffer = quads->buffer,
.offset = 0,
.size = quads->size,
},
};
WGPUBindGroupDescriptor bg_desc = {
.label = "Common bind group",
.layout = this->uniforms.bind_group_layout,
.entryCount = (uint32_t)ARRAY_SIZE(bg_entries),
.entries = bg_entries,
};
this->uniforms.bind_group
= wgpuDeviceCreateBindGroup(wgpu_context->device, &bg_desc);
ASSERT(this->uniforms.bind_group != NULL)
}
}
static void common_destroy(common_t* this)
{
wgpu_destroy_buffer(&this->uniform_buffer);
WGPU_RELEASE_RESOURCE(BindGroupLayout, this->uniforms.bind_group_layout)
WGPU_RELEASE_RESOURCE(BindGroup, this->uniforms.bind_group)
}
typedef struct {
bool rotate_camera;
float aspect;
} common_update_params_t;
/* Updates the uniform buffer data */
static void common_update(common_t* this, common_update_params_t* params)
{
glm_mat4_identity(this->ubo_vs.view_matrix);
glm_mat4_identity(this->ubo_vs.mvp);
glm_mat4_identity(this->ubo_vs.inv_mvp);
glm_mat4_identity(this->ubo_vs.projection_matrix);
glm_perspective(PI2 / 8.0f, params->aspect, 0.5f, 100.0f,
this->ubo_vs.projection_matrix);
float view_rotation = params->rotate_camera ? this->frame / 1000.0f : 0.0f;
glm_lookat(
(vec3){sin(view_rotation) * 15.0f, 5.0f, cos(view_rotation) * 15.0f},
(vec3){0.0f, 5.0f, 0.0f}, (vec3){0.0f, 1.0f, 0.0f},
this->ubo_vs.view_matrix);
glm_mat4_mul(this->ubo_vs.projection_matrix, this->ubo_vs.view_matrix,
this->ubo_vs.mvp);
glm_mat4_inv(this->ubo_vs.mvp, this->ubo_vs.inv_mvp);
float uniform_data_f32[36] = {0};
uint8_t i = 0;
for (uint8_t r = 0; r < 4; ++r) {
for (uint8_t c = 0; c < 4; ++c) {
uniform_data_f32[i++] = this->ubo_vs.mvp[r][c];
}
}
for (uint8_t r = 0; r < 4; ++r) {
for (uint8_t c = 0; c < 4; ++c) {
uniform_data_f32[i++] = this->ubo_vs.inv_mvp[r][c];
}
}
const float mult = (float)0xffffffff;
uniform_data_f32[32] = (uint32_t)(mult * random_float());
uniform_data_f32[33] = (uint32_t)(mult * random_float());
uniform_data_f32[34] = (uint32_t)(mult * random_float());
wgpu_queue_write_buffer(this->wgpu_context, this->uniform_buffer.buffer, 0,
uniform_data_f32, sizeof(uniform_data_f32));
this->frame++;
}
/* -------------------------------------------------------------------------- *
* Scene holds the cornell-box scene information.
* -------------------------------------------------------------------------- */
#define SCENE_QUADS_LENGTH 19u
#define SCENE_QUAD_STRIDE (16 * 4)
#define SCENE_QUAD_VERTEX_STRIDE (4 * 10)
typedef struct {
vec3 center;
vec3 right;
vec3 up;
vec3 color;
float emissive;
} quad_t;
typedef enum {
QuadType_Convex,
QuadType_Concave,
} quad_type_t;
/**
* @brief Calculates the length of a vec3
*
* @param {ReadonlyVec3} a vector to calculate length of
* @returns {Number} length of a
*/
static float vec3_len(vec3 v)
{
const float x = v[0];
const float y = v[1];
const float z = v[2];
return sqrt(x * x + y * y + z * z);
}
/**
* @brief Calculates the squared length of a vec3
*
* @param {ReadonlyVec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
static float vec3_sqr_len(vec3 v)
{
const float x = v[0];
const float y = v[1];
const float z = v[2];
return x * x + y * y + z * z;
}
static void vec3_sign(vec3 v, quad_type_t type, vec3* dst)
{
glm_vec3_copy(v, *dst);
if (type == QuadType_Convex) {
glm_vec3_negate(*dst);
}
}
static void reciprocal(vec3 v, vec3* dst)
{
const float s = 1.0f / vec3_sqr_len(v);
glm_vec3_mul((vec3){s, s, s}, v, *dst);
}
// ─────────┐
// ╱ +Y ╱│
// ┌────────┐ │
// │ │+X
// │ +Z │ │
// │ │╱
// └────────┘
typedef enum {
CubeFace_Positive_X,
CubeFace_Positive_Y,
CubeFace_Positive_Z,
CubeFace_Negative_X,
CubeFace_Negative_Y,
CubeFace_Negative_Z,
} cube_face_t;
typedef struct {
vec3 center;
float width;
float height;
float depth;
float rotation;
vec3* color;
uint8_t color_count;
quad_type_t type;
} box_params_t;
static void create_box(box_params_t* params, quad_t* quads)
{
// ─────────┐
// ╱ +Y ╱│
// ┌────────┐ │ y
// │ │+X ^
// │ +Z │ │ │ -z
// │ │╱ │╱
// └────────┘ └─────> x
vec3 x = {
cos(params->rotation) * (params->width / 2.0f), /* x */
0.0f, /* y */
sin(params->rotation) * (params->depth / 2.0f) /* z */
};
vec3 y = {0.0f, params->height / 2.0f, 0.0f};
vec3 z = {
sin(params->rotation) * (params->width / 2.0f), /* x */
0.0f, /* y */
-cos(params->rotation) * (params->depth / 2.0f) /* z */
};
vec3 colors[6] = {0};
for (uint8_t i = 0; i < 6; ++i) {
glm_vec3_copy(params->color[MIN(i, params->color_count - 1)], colors[i]);
}
/* Box faces */
{
/* PositiveX */
quad_t* quad = &quads[0];
glm_vec3_add(params->center, x, quad->center);
vec3 vec3_tmp = GLM_VEC3_ZERO_INIT;
glm_vec3_negate_to(z, vec3_tmp);
vec3_sign(vec3_tmp, params->type, &quad->right);
glm_vec3_copy(y, quad->up);
glm_vec3_copy(colors[CubeFace_Positive_X], quad->color);
/* PositiveY */
quad = &quads[1];
glm_vec3_add(params->center, y, quad->center);
vec3_sign(x, params->type, &quad->right);
glm_vec3_negate_to(z, quad->up);
glm_vec3_copy(colors[CubeFace_Positive_Y], quad->color);
/* PositiveZ */
quad = &quads[2];
glm_vec3_add(params->center, z, quad->center);
vec3_sign(x, params->type, &quad->right);
glm_vec3_copy(y, quad->up);
glm_vec3_copy(colors[CubeFace_Positive_Z], quad->color);
/* NegativeX */
quad = &quads[3];
glm_vec3_sub(params->center, x, quad->center);
vec3_sign(z, params->type, &quad->right);
glm_vec3_copy(y, quad->up);
glm_vec3_copy(colors[CubeFace_Negative_X], quad->color);
/* NegativeY */
quad = &quads[4];
glm_vec3_sub(params->center, y, quad->center);
vec3_sign(x, params->type, &quad->right);
glm_vec3_copy(z, quad->up);
glm_vec3_copy(colors[CubeFace_Negative_Y], quad->color);
/* NegativeZ */
quad = &quads[5];
glm_vec3_sub(params->center, z, quad->center);
glm_vec3_negate_to(x, vec3_tmp);
vec3_sign(vec3_tmp, params->type, &quad->right);
glm_vec3_copy(y, quad->up);
glm_vec3_copy(colors[CubeFace_Negative_Z], quad->color);
}
}
static quad_t light = {
.center = {0.0f, 9.95f, 0.0f},
.right = {1.0f, 0.0f, 0.0f},
.up = {0.0f, 0.0f, 1.0f},
.color = {5.0f, 5.0f, 5.0f},
.emissive = 1.0f,
};
typedef struct {
uint32_t vertex_count;
uint32_t index_count;
wgpu_buffer_t vertices;
wgpu_buffer_t indices;
WGPUVertexBufferLayout vertex_buffer_layout;
WGPUVertexAttribute vertex_buffer_layout_attributes[3];
wgpu_buffer_t quad_buffer;
quad_t quads[SCENE_QUADS_LENGTH];
uint32_t quads_length;
vec3 light_center;
float light_width;
float light_height;
} scene_t;
static void scene_init_defaults(scene_t* this)
{
memset(this, 0, sizeof(*this));
this->quads_length = SCENE_QUADS_LENGTH;
glm_vec3_copy(light.center, this->light_center);
this->light_width = vec3_len(light.right) * 2.0f;
this->light_height = vec3_len(light.up) * 2.0f;
}
static void scene_create(scene_t* this, wgpu_context_t* wgpu_context)
{
scene_init_defaults(this);
/* Quads */
{
/* Box 1 - quads */
{
vec3 color_array[6] = {
{0.0f, 0.5f, 0.0f}, /* PositiveX */
{0.5f, 0.5f, 0.5f}, /* PositiveY */
{0.5f, 0.5f, 0.5f}, /* PositiveZ */
{0.5f, 0.0f, 0.0f}, /* NegativeX */
{0.5f, 0.5f, 0.5f}, /* NegativeY */
{0.5f, 0.5f, 0.5f}, /* NegativeZ */
};
create_box(
&(box_params_t){
.center = {0.0f, 5.0f, 0.0f},
.width = 10.0f,
.height = 10.0f,
.depth = 10.0f,
.rotation = 0.0f,
.color = color_array,
.color_count = (uint32_t)ARRAY_SIZE(color_array),
.type = QuadType_Concave,
},
&this->quads[0]);
}
/* Box 2 - quads */
{
vec3 color_array[1] = {{0.8f, 0.8f, 0.8f}};
create_box(
&(box_params_t){
.center = {1.5f, 1.5f, 1.0f},
.width = 3.0f,
.height = 3.0f,
.depth = 3.0f,
.rotation = 0.3f,
.color = color_array,
.color_count = (uint32_t)ARRAY_SIZE(color_array),
.type = QuadType_Convex,
},
&this->quads[6]);
}
/* Box 3 - quads */
{
vec3 color_array[1] = {{0.8f, 0.8f, 0.8f}};
create_box(
&(box_params_t){
.center = {-2.0f, 3.0f, -2.0f},
.width = 3.0f,
.height = 6.0f,
.depth = 3.0f,
.rotation = -0.4f,
.color = color_array,
.color_count = (uint32_t)ARRAY_SIZE(color_array),
.type = QuadType_Convex,
},
&this->quads[12]);
}
/* Light quad */
memcpy(&this->quads[18], &light, sizeof(light));
}
/* Quad buffer */
{
float quad_data[SCENE_QUAD_STRIDE * SCENE_QUADS_LENGTH] = {0};
float vertex_data[SCENE_QUADS_LENGTH * SCENE_QUAD_VERTEX_STRIDE] = {0};
uint16_t index_data[SCENE_QUADS_LENGTH * 9] = {0}; /* TODO: 6? */
uint32_t quad_data_offset = 0;
uint32_t vertex_data_offset = 0;
uint32_t index_data_offset = 0;
for (uint32_t quad_idx = 0; quad_idx < SCENE_QUADS_LENGTH; ++quad_idx) {
quad_t* quad = &this->quads[quad_idx];
vec3 normal = GLM_VEC3_ZERO_INIT;
glm_vec3_cross(quad->right, quad->up, normal);
glm_vec3_normalize(normal);
quad_data[quad_data_offset++] = normal[0];
quad_data[quad_data_offset++] = normal[1];
quad_data[quad_data_offset++] = normal[2];
quad_data[quad_data_offset++] = -glm_vec3_dot(normal, quad->center);
vec3 inv_right = GLM_VEC3_ZERO_INIT;
reciprocal(quad->right, &inv_right);
quad_data[quad_data_offset++] = inv_right[0];
quad_data[quad_data_offset++] = inv_right[1];
quad_data[quad_data_offset++] = inv_right[2];
quad_data[quad_data_offset++] = -glm_vec3_dot(inv_right, quad->center);
vec3 inv_up = GLM_VEC3_ZERO_INIT;
reciprocal(quad->up, &inv_up);
quad_data[quad_data_offset++] = inv_up[0];
quad_data[quad_data_offset++] = inv_up[1];
quad_data[quad_data_offset++] = inv_up[2];
quad_data[quad_data_offset++] = -glm_vec3_dot(inv_up, quad->center);
quad_data[quad_data_offset++] = quad->color[0];
quad_data[quad_data_offset++] = quad->color[1];
quad_data[quad_data_offset++] = quad->color[2];
quad_data[quad_data_offset++] = quad->emissive;
// a ----- b
// | |
// | m |
// | |
// c ----- d
vec3 a = GLM_VEC3_ZERO_INIT;
glm_vec3_sub(quad->center, quad->right, a);
glm_vec3_add(a, quad->up, a);
vec3 b = GLM_VEC3_ZERO_INIT;
glm_vec3_add(quad->center, quad->right, b);
glm_vec3_add(b, quad->up, b);
vec3 c = GLM_VEC3_ZERO_INIT;
glm_vec3_sub(quad->center, quad->right, c);
glm_vec3_sub(c, quad->up, c);
vec3 d = GLM_VEC3_ZERO_INIT;
glm_vec3_add(quad->center, quad->right, d);
glm_vec3_sub(d, quad->up, d);
vertex_data[vertex_data_offset++] = a[0];
vertex_data[vertex_data_offset++] = a[1];
vertex_data[vertex_data_offset++] = a[2];
vertex_data[vertex_data_offset++] = 1;
vertex_data[vertex_data_offset++] = 0; /* uv.x */
vertex_data[vertex_data_offset++] = 1; /* uv.y */
vertex_data[vertex_data_offset++] = quad_idx;
vertex_data[vertex_data_offset++] = quad->color[0] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[1] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[2] * quad->emissive;
vertex_data[vertex_data_offset++] = b[0];
vertex_data[vertex_data_offset++] = b[1];
vertex_data[vertex_data_offset++] = b[2];
vertex_data[vertex_data_offset++] = 1;
vertex_data[vertex_data_offset++] = 1; /* uv.x */
vertex_data[vertex_data_offset++] = 1; /* uv.y */
vertex_data[vertex_data_offset++] = quad_idx;
vertex_data[vertex_data_offset++] = quad->color[0] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[1] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[2] * quad->emissive;
vertex_data[vertex_data_offset++] = c[0];
vertex_data[vertex_data_offset++] = c[1];
vertex_data[vertex_data_offset++] = c[2];
vertex_data[vertex_data_offset++] = 1;
vertex_data[vertex_data_offset++] = 0; /* uv.x */
vertex_data[vertex_data_offset++] = 0; /* uv.y */
vertex_data[vertex_data_offset++] = quad_idx;
vertex_data[vertex_data_offset++] = quad->color[0] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[1] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[2] * quad->emissive;
vertex_data[vertex_data_offset++] = d[0];
vertex_data[vertex_data_offset++] = d[1];
vertex_data[vertex_data_offset++] = d[2];
vertex_data[vertex_data_offset++] = 1;
vertex_data[vertex_data_offset++] = 1; /* uv.x */
vertex_data[vertex_data_offset++] = 0; /* uv.y */
vertex_data[vertex_data_offset++] = quad_idx;
vertex_data[vertex_data_offset++] = quad->color[0] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[1] * quad->emissive;
vertex_data[vertex_data_offset++] = quad->color[2] * quad->emissive;
index_data[index_data_offset++] = this->vertex_count + 0; /* a */
index_data[index_data_offset++] = this->vertex_count + 2; /* c */
index_data[index_data_offset++] = this->vertex_count + 1; /* b */
index_data[index_data_offset++] = this->vertex_count + 1; /* b */
index_data[index_data_offset++] = this->vertex_count + 2; /* c */
index_data[index_data_offset++] = this->vertex_count + 3; /* d */
this->index_count += 6;
this->vertex_count += 4;
}
/* Quads storage buffer */
this->quad_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Scene quad buffer",
.size = SCENE_QUAD_STRIDE * SCENE_QUADS_LENGTH,
.usage = WGPUBufferUsage_Storage,
.initial.data = quad_data,
});
/* Quads vertices buffer */
this->vertices
= wgpu_create_buffer(wgpu_context, &(wgpu_buffer_desc_t){
.label = "Scene vertices buffer",
.size = sizeof(vertex_data),
.usage = WGPUBufferUsage_Vertex,
.initial.data = vertex_data,
});
/* Quads indices buffer */
this->indices
= wgpu_create_buffer(wgpu_context, &(wgpu_buffer_desc_t){
.label = "Scene indices buffer",
.size = sizeof(index_data),
.usage = WGPUBufferUsage_Index,
.initial.data = index_data,
});
}
/* Vertex buffer layout */
{
WGPUVertexAttribute attributes[3] = {
[0] = (WGPUVertexAttribute) {
// position
.shaderLocation = 0,
.offset = 0 * 4,
.format = WGPUVertexFormat_Float32x4,
},
[1] = (WGPUVertexAttribute) {
// uv
.shaderLocation = 1,
.offset = 4 * 4,
.format = WGPUVertexFormat_Float32x3,
},
[2] = (WGPUVertexAttribute) {
// color
.shaderLocation = 2,
.offset = 7 * 4,
.format = WGPUVertexFormat_Float32x3,
},
};
memcpy(&this->vertex_buffer_layout_attributes[0], attributes,
sizeof(attributes));
this->vertex_buffer_layout = (WGPUVertexBufferLayout){
.arrayStride = SCENE_QUAD_VERTEX_STRIDE,
.attributeCount = (uint32_t)ARRAY_SIZE(attributes),
.attributes = this->vertex_buffer_layout_attributes,
};
}
}
static void scene_destroy(scene_t* this)
{
wgpu_destroy_buffer(&this->vertices);
wgpu_destroy_buffer(&this->indices);
wgpu_destroy_buffer(&this->quad_buffer);
}
/* --------------------------------------------------------------------------
* Radiosity computes lightmaps, calculated by software raytracing of light in
* the scene.
* -------------------------------------------------------------------------- */
typedef struct {
// The output lightmap format and dimensions
WGPUTextureFormat lightmap_format;
uint32_t lightmap_width;
uint32_t lightmap_height;
// The output lightmap.
texture_t lightmap;
uint32_t lightmap_depth_or_array_layers;
// Number of photons emitted per workgroup.
// This is equal to the workgroup size (one photon per invocation)
uint32_t photons_per_workgroup;
// Number of radiosity workgroups dispatched per frame.
uint32_t workgroups_per_frame;
uint32_t photons_per_frame;
// Maximum value that can be added to the 'accumulation' buffer, per
// photon, across all texels.
uint32_t photon_energy;
// The total number of lightmap texels for all quads.
uint32_t total_lightmap_texels;
uint32_t accumulation_to_lightmap_workgroup_size_x;
uint32_t accumulation_to_lightmap_workgroup_size_y;
wgpu_context_t* wgpu_context;
common_t* common;
scene_t* scene;
WGPUPipelineLayout pipeline_layout;
WGPUComputePipeline radiosity_pipeline;
WGPUComputePipeline accumulation_to_lightmap_pipeline;
WGPUBindGroupLayout bind_group_layout;
WGPUBindGroup bind_group;
wgpu_buffer_t accumulation_buffer;
wgpu_buffer_t uniform_buffer;
// The 'accumulation' buffer average value
float accumulation_mean;
// The maximum value of 'accumulationAverage' before all values in
// 'accumulation' are reduced to avoid integer overflows.
uint32_t accumulation_mean_max;
} radiosity_t;
static void radiosity_init_defaults(radiosity_t* this)
{
memset(this, 0, sizeof(*this));
this->lightmap_format = WGPUTextureFormat_RGBA16Float;
this->lightmap_width = 256;
this->lightmap_height = 256;
this->photons_per_workgroup = 256;
this->workgroups_per_frame = 1024;
this->photons_per_frame
= this->photons_per_workgroup * this->workgroups_per_frame;
this->photon_energy = 100000;
this->accumulation_to_lightmap_workgroup_size_x = 16;
this->accumulation_to_lightmap_workgroup_size_y = 16;
this->accumulation_mean = 0.0f;
this->accumulation_mean_max = 0x10000000;
}
static void radiosity_create(radiosity_t* this, wgpu_context_t* wgpu_context,
common_t* common, scene_t* scene)
{
radiosity_init_defaults(this);
this->wgpu_context = wgpu_context;
this->common = common;
this->scene = scene;
/* Lightmap */
{
// Texture
WGPUTextureDescriptor texture_desc = {
.label = "Radiosity lightmap texture",
.size = (WGPUExtent3D) {
.width = this->lightmap_width,
.height = this->lightmap_height,
.depthOrArrayLayers = this->scene->quads_length,
},
.mipLevelCount = 1,
.sampleCount = 1,
.dimension = WGPUTextureDimension_2D,
.format = this->lightmap_format,
.usage
= WGPUTextureUsage_TextureBinding | WGPUTextureUsage_StorageBinding,
};
this->lightmap.texture
= wgpuDeviceCreateTexture(this->wgpu_context->device, &texture_desc);
ASSERT(this->lightmap.texture != NULL);
this->lightmap_depth_or_array_layers = this->scene->quads_length;
// Texture view
WGPUTextureViewDescriptor texture_view_dec = {
.label = "Radiosity lightmap texture view",
.dimension = WGPUTextureViewDimension_2DArray,
.format = texture_desc.format,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = this->lightmap_depth_or_array_layers,
.aspect = WGPUTextureAspect_All,
};
this->lightmap.view
= wgpuTextureCreateView(this->lightmap.texture, &texture_view_dec);
ASSERT(this->lightmap.view != NULL);
// Texture sampler
WGPUSamplerDescriptor sampler_desc = {
.label = "Radiosity lightmap texture sampler",
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.minFilter = WGPUFilterMode_Linear,
.magFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Nearest,
.lodMinClamp = 0.0f,
.lodMaxClamp = 1.0f,
.maxAnisotropy = 1,
};
this->lightmap.sampler
= wgpuDeviceCreateSampler(wgpu_context->device, &sampler_desc);
ASSERT(this->lightmap.sampler != NULL);
}
/* Accumulation buffer */
{
this->accumulation_buffer = wgpu_create_buffer(
this->wgpu_context, &(wgpu_buffer_desc_t){
.label = "Radiosity accumulation buffer",
.size = this->lightmap_width * this->lightmap_height
* this->scene->quads_length * 16,
.usage = WGPUBufferUsage_Storage,
});
this->total_lightmap_texels = this->lightmap_width * this->lightmap_height
* this->scene->quads_length;
}
/* Uniform buffer */
{
this->uniform_buffer = wgpu_create_buffer(
this->wgpu_context,
&(wgpu_buffer_desc_t){
.label = "Radiosity uniform buffer",
.size = 8 * 4, /* 8 x f32 */
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
});
}
/* Bind group layout */
{
WGPUBindGroupLayoutEntry bgl_entries[3] = {
[0] = (WGPUBindGroupLayoutEntry) {
// Binding 0: accumulation buffer
.binding = 0,
.visibility = WGPUShaderStage_Compute,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_Storage,
.minBindingSize = this->accumulation_buffer.size,
},
.sampler = {0},
},
[1] = (WGPUBindGroupLayoutEntry) {
// Binding 1: lightmap
.binding = 1,
.visibility = WGPUShaderStage_Compute,
.storageTexture = {
.access = WGPUStorageTextureAccess_WriteOnly,
.format = this->lightmap_format,
.viewDimension = WGPUTextureViewDimension_2DArray,
},
},
[2] = (WGPUBindGroupLayoutEntry) {
// Binding 2: radiosity_uniforms
.binding = 2,
.visibility = WGPUShaderStage_Compute,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = this->uniform_buffer.size,
},
.sampler = {0},
}
};
this->bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = "Radiosity bind group layout",
.entryCount = (uint32_t)ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
ASSERT(this->bind_group_layout != NULL);
}
/* Bind group */
{
WGPUBindGroupEntry bg_entries[3] = {
[0] = (WGPUBindGroupEntry) {
// Binding 0: accumulation buffer
.binding = 0,
.buffer = this->accumulation_buffer.buffer,
.offset = 0,
.size = this->accumulation_buffer.size,
},
[1] = (WGPUBindGroupEntry) {
// Binding 1: lightmap
.binding = 1,
.textureView = this->lightmap.view,
},
[2] = (WGPUBindGroupEntry) {
// Binding 2: radiosity_uniforms
.binding = 2,
.buffer = this->uniform_buffer.buffer,
.offset = 0,
.size = this->uniform_buffer.size,
},
};
this->bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = "Radiosity bind group",
.layout = this->bind_group_layout,
.entryCount = (uint32_t)ARRAY_SIZE(bg_entries),
.entries = bg_entries,
});
ASSERT(this->bind_group != NULL);
}
/* Compute pipeline layout */
{
WGPUBindGroupLayout bind_group_layouts[2] = {
this->common->uniforms.bind_group_layout, /* Group 0 */
this->bind_group_layout, /* Group 1 */
};
WGPUPipelineLayoutDescriptor compute_pipeline_layout_desc = {
.label = "Radiosity accumulate pipeline layout",
.bindGroupLayoutCount = (uint32_t)ARRAY_SIZE(bind_group_layouts),
.bindGroupLayouts = bind_group_layouts,
};
this->pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &compute_pipeline_layout_desc);
ASSERT(this->pipeline_layout != NULL);
}
/* Compute shader */
char* wgsl_code = {0};
concat_shader_store_entries(&shader_store.common, &shader_store.radiosity,
&wgsl_code);
/* Radiosity compute pipeline */
{
/* Constants */
WGPUConstantEntry constant_entries[2] = {
[0] = (WGPUConstantEntry) {
.key = "PhotonsPerWorkgroup",
.value = this->photons_per_workgroup,
},
[1] = (WGPUConstantEntry) {
.key = "PhotonEnergy",
.value = this->photon_energy,
},
};
/* Compute shader */
wgpu_shader_t radiosity_comp_shader = wgpu_shader_create(
wgpu_context, &(wgpu_shader_desc_t){
// Compute shader WGSL
.label = "Radiosity comp shader",
.wgsl_code = {wgsl_code},
.entry = "radiosity",
.constants.count = (uint32_t)ARRAY_SIZE(constant_entries),
.constants.entries = constant_entries,
});
/* Compute pipeline*/
this->radiosity_pipeline = wgpuDeviceCreateComputePipeline(
wgpu_context->device,
&(WGPUComputePipelineDescriptor){
.label = "Radiosity radiosity pipeline",
.layout = this->pipeline_layout,
.compute = radiosity_comp_shader.programmable_stage_descriptor,
});
/* Cleanup */
wgpu_shader_release(&radiosity_comp_shader);
}
/* Accumulation to lightmap compute pipeline */
{
/* Constants */
WGPUConstantEntry constant_entries[2] = {
[0] = (WGPUConstantEntry) {
.key = "AccumulationToLightmapWorkgroupSizeX",
.value = this->accumulation_to_lightmap_workgroup_size_x,
},
[1] = (WGPUConstantEntry) {
.key = "AccumulationToLightmapWorkgroupSizeY",
.value = this->accumulation_to_lightmap_workgroup_size_y,
},
};
/* Compute shader */
wgpu_shader_t accumulation_to_lightmap_comp_shader = wgpu_shader_create(
wgpu_context, &(wgpu_shader_desc_t){
// Compute shader WGSL
.label = "Accumulation to lightmap comp shader",
.wgsl_code = {wgsl_code},
.entry = "accumulation_to_lightmap",
.constants.count = (uint32_t)ARRAY_SIZE(constant_entries),