-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathpristine_grid.c
1158 lines (1031 loc) · 37 KB
/
pristine_grid.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 - Pristine Grid
*
* A simple WebGPU implementation of the "Pristine Grid" technique described in
* this wonderful little blog post:
* https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
*
* Ref:
* https://github.com/toji/pristine-grid-webgpu
* https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
// A WebGPU implementation of the "Pristine Grid" shader described at
// https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
static const char* grid_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Math functions
* @ref https://github.com/toji/gl-matrix
* -------------------------------------------------------------------------- */
/**
* @brief Generates a perspective projection matrix with the given bounds.
* The near/far clip planes correspond to a normalized device coordinate Z range
* of [-1, 1], which matches WebGL/OpenGL's clip volume. Passing
* null/undefined/no value for far will generate infinite projection matrix.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum, can be null or Infinity
* @returns {mat4} out
*/
mat4* glm_mat4_perspective_zo(mat4* out, float fovy, float aspect, float near,
const float* far)
{
const float f = 1.0f / tan(fovy / 2.0f);
(*out)[0][0] = f / aspect;
(*out)[0][1] = 0.0f;
(*out)[0][2] = 0.0f;
(*out)[0][3] = 0.0f;
(*out)[1][0] = 0.0f;
(*out)[1][1] = f;
(*out)[1][2] = 0.0f;
(*out)[1][3] = 0.0f;
(*out)[2][0] = 0.0f;
(*out)[2][1] = 0.0f;
(*out)[2][3] = -1.0f;
(*out)[3][0] = 0.0f;
(*out)[3][1] = 0.0f;
(*out)[3][3] = 0.0f;
if (far != NULL && *far != INFINITY) {
const float nf = 1.0f / (near - *far);
(*out)[2][2] = *far * nf;
(*out)[3][2] = *far * near * nf;
}
else {
(*out)[2][2] = -1.0f;
(*out)[3][2] = -near;
}
return out;
}
/**
* @brief Rotates the given 4-by-4 matrix around the x-axis by the given angle.
* @param m - The matrix.
* @param angleInRadians - The angle by which to rotate (in radians).
* @returns The rotated matrix m.
*/
static mat4* glm_mat4_rotate_x(mat4* m, float angle_in_radians)
{
const float s = sin(angle_in_radians);
const float c = cos(angle_in_radians);
const float m10 = (*m)[1][0];
const float m11 = (*m)[1][1];
const float m12 = (*m)[1][2];
const float m13 = (*m)[1][3];
const float m20 = (*m)[2][0];
const float m21 = (*m)[2][1];
const float m22 = (*m)[2][2];
const float m23 = (*m)[2][3];
/* Perform axis-specific matrix multiplication */
(*m)[1][0] = m10 * c + m20 * s;
(*m)[1][1] = m11 * c + m21 * s;
(*m)[1][2] = m12 * c + m22 * s;
(*m)[1][3] = m13 * c + m23 * s;
(*m)[2][0] = m20 * c - m10 * s;
(*m)[2][1] = m21 * c - m11 * s;
(*m)[2][2] = m22 * c - m12 * s;
(*m)[2][3] = m23 * c - m13 * s;
return m;
}
/**
* @brief Rotates the given 4-by-4 matrix around the y-axis by the given angle.
* @param m - The matrix.
* @param angleInRadians - The angle by which to rotate (in radians).
* @returns The rotated matrix m.
*/
static mat4* glm_mat4_rotate_y(mat4* m, float angle_in_radians)
{
const float s = sin(angle_in_radians);
const float c = cos(angle_in_radians);
const float m00 = (*m)[0][0];
const float m01 = (*m)[0][1];
const float m02 = (*m)[0][2];
const float m03 = (*m)[0][3];
const float m20 = (*m)[2][0];
const float m21 = (*m)[2][1];
const float m22 = (*m)[2][2];
const float m23 = (*m)[2][3];
/* Perform axis-specific matrix multiplication */
(*m)[0][0] = m00 * c - m20 * s;
(*m)[0][1] = m01 * c - m21 * s;
(*m)[0][2] = m02 * c - m22 * s;
(*m)[0][3] = m03 * c - m23 * s;
(*m)[2][0] = m00 * s + m20 * c;
(*m)[2][1] = m01 * s + m21 * c;
(*m)[2][2] = m02 * s + m22 * c;
(*m)[2][3] = m03 * s + m23 * c;
return m;
}
/**
* @brief Transform vec3 by 4x4 matrix.
* @param v - the vector
* @param m - The matrix.
* @param dst - vec3 to store result.
* @returns the transformed vector dst
*/
static vec3* glm_vec3_transform_mat4(vec3 v, mat4 m, vec3* dst)
{
const float x = v[0];
const float y = v[1];
const float z = v[2];
const float w = m[0][3] * x + m[1][3] * y + m[2][3] * z + m[3][3];
(*dst)[0] = (m[0][0] * x + m[1][0] * y + m[2][0] * z + m[3][0]) / w;
(*dst)[1] = (m[0][1] * x + m[1][1] * y + m[2][1] * z + m[3][1]) / w;
(*dst)[2] = (m[0][2] * x + m[1][2] * y + m[2][2] * z + m[3][2]) / w;
return dst;
}
/* -------------------------------------------------------------------------- *
* Orbit camera
* -------------------------------------------------------------------------- */
typedef struct orbit_camera_t {
vec2 orbit;
vec2 min_orbit;
vec2 max_orbit;
bool constrain_orbit[2];
float max_distance;
float min_distance;
float distance_step;
bool constrain_distance;
vec3 distance;
vec3 target;
mat4 view_mat;
mat4 camera_mat;
vec3 position;
bool dirty;
struct {
bool moving;
vec2 move_delta;
vec2 prev_position;
} mouse;
} orbit_camera_t;
static void orbit_camera_init_defaults(orbit_camera_t* this)
{
memset(this, 0, sizeof(*this));
glm_vec2_zero(this->orbit);
glm_vec2_copy((vec2){-PI_2, -PI}, this->min_orbit);
glm_vec2_copy((vec2){PI_2, PI}, this->max_orbit);
this->constrain_orbit[0] = true;
this->constrain_orbit[1] = false;
this->max_distance = 10.0f;
this->min_distance = 1.0f;
this->distance_step = 0.005f;
this->constrain_distance = true;
glm_vec3_copy((vec3){0.0f, 0.0f, 1.0f}, this->distance);
glm_vec3_zero(this->target);
glm_mat4_identity(this->view_mat);
glm_mat4_identity(this->camera_mat);
glm_vec3_zero(this->position);
this->dirty = false;
}
/* Construtor */
static void orbit_camera_init(orbit_camera_t* this)
{
orbit_camera_init_defaults(this);
}
static void orbit_camera_orbit(orbit_camera_t* this, float x_delta,
float y_delta)
{
if (x_delta || y_delta) {
this->orbit[1] += x_delta;
if (this->constrain_orbit[1]) {
this->orbit[1]
= MIN(MAX(this->orbit[1], this->min_orbit[1]), this->max_orbit[1]);
}
else {
while (this->orbit[1] < -PI) {
this->orbit[1] += PI2;
}
while (this->orbit[1] >= PI) {
this->orbit[1] -= PI2;
}
}
this->orbit[0] += y_delta;
if (this->constrain_orbit[0]) {
this->orbit[0]
= MIN(MAX(this->orbit[0], this->min_orbit[0]), this->max_orbit[0]);
}
else {
while (this->orbit[0] < -PI) {
this->orbit[0] += PI2;
}
while (this->orbit[0] >= PI) {
this->orbit[0] -= PI2;
}
}
this->dirty = true;
}
}
static vec3* orbit_camera_get_target(orbit_camera_t* this)
{
return &this->target;
}
static void orbit_camera_set_target(orbit_camera_t* this, vec3 value)
{
glm_vec3_copy(value, this->target);
this->dirty = true;
}
static float orbit_camera_get_distance(orbit_camera_t* this)
{
return this->distance[2];
}
static void orbit_camera_set_distance(orbit_camera_t* this, float value)
{
this->distance[2] = value;
if (this->constrain_distance) {
this->distance[2]
= MIN(MAX(this->distance[2], this->min_distance), this->max_distance);
}
this->dirty = true;
}
static void orbit_camera_update_matrices(orbit_camera_t* this)
{
if (this->dirty) {
glm_mat4_identity(this->camera_mat);
glm_translate(this->camera_mat, this->target);
glm_mat4_rotate_y(&this->camera_mat, -this->orbit[1]);
glm_mat4_rotate_x(&this->camera_mat, -this->orbit[0]);
glm_translate(this->camera_mat, this->distance);
glm_mat4_inv(this->camera_mat, this->view_mat);
this->dirty = false;
}
}
static vec3* orbit_camera_get_position(orbit_camera_t* this)
{
orbit_camera_update_matrices(this);
glm_vec3_zero(this->position);
glm_vec3_transform_mat4(this->position, this->camera_mat, &this->position);
return &this->position;
}
static mat4* orbit_camera_get_view_matrix(orbit_camera_t* this)
{
orbit_camera_update_matrices(this);
return &this->view_mat;
}
/* -------------------------------------------------------------------------- *
* Pristine Grid example
* -------------------------------------------------------------------------- */
static const bool use_msaa = false;
static const uint32_t msaa_sample_count = use_msaa ? 4u : 1u;
static WGPUTextureFormat depth_format = WGPUTextureFormat_Depth24PlusStencil8;
/* Vertex layout used in this example */
typedef struct {
vec3 position;
vec2 uv;
} vertex_t;
static struct {
mat4 projection_matrix;
mat4 view_matrix;
vec3 camera_position;
float time;
} camera_uniforms = {0};
static struct {
vec4 line_color;
vec4 base_color;
vec2 line_width;
vec4 padding;
} uniform_array = {0};
static struct {
vec4 clear_color;
vec4 line_color;
vec4 base_color;
float line_width_x;
float line_width_y;
} grid_options = {
.clear_color = {
/* .r = */ 0.0f,
/* .g = */ 0.0f,
/* .b = */ 0.2f,
/* .a = */ 1.0f,
},
.line_color = {
/* .r = */ 1.0f,
/* .g = */ 1.0f,
/* .b = */ 1.0f,
/* .a = */ 1.0f,
},
.base_color = {
/* .r = */ 0.0f,
/* .g = */ 0.0f,
/* .b = */ 0.0f,
/* .a = */ 1.0f,
},
.line_width_x = 0.05f,
.line_width_y = 0.05f,
};
static wgpu_buffer_t vertex_buffer = {0};
static wgpu_buffer_t index_buffer = {0};
static wgpu_buffer_t frame_uniform_buffer = {0};
static wgpu_buffer_t uniform_buffer = {0};
static WGPUBindGroupLayout frame_bind_group_layout = NULL;
static WGPUBindGroupLayout bind_group_layout = NULL;
static WGPUBindGroup frame_bind_group = NULL;
static WGPUBindGroup bind_group = NULL;
static WGPUPipelineLayout pipeline_layout = NULL;
static WGPURenderPipeline pipeline = NULL;
static struct {
struct {
WGPUTexture texture;
WGPUTextureView view;
} msaa_color, depth;
} textures = {0};
/* Render pass descriptor for frame buffer writes */
static struct {
WGPURenderPassColorAttachment color_attachments[1];
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor descriptor;
} render_pass = {0};
/* The orbit camera */
static struct {
float fov;
float z_near;
float z_far;
} camera_parms = {
.fov = PI_2,
.z_near = 0.01f,
.z_far = 128.0f,
};
static orbit_camera_t camera;
/* Other variables */
static const char* example_title = "Pristine Grid";
static bool prepared = false;
static void prepare_vertex_and_index_buffers(wgpu_context_t* wgpu_context)
{
/* Setup vertices (x, y, z, u,v) */
{
static const vertex_t vertex_array[4] = {
{
.position = {-20.0f, -0.5f, -20.0f},
.uv = {0.0f, 0.0f},
},
{
.position = {20.0f, -0.5f, -20.0f},
.uv = {200.0f, 0.0f},
},
{
.position = {-20.0f, -0.5f, 20.0f},
.uv = {0.0f, 200.0f},
},
{
.position = {20.0f, -0.5f, 20.0f},
.uv = {200.0f, 200.0f},
},
};
vertex_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Vertex buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(vertex_array),
.count = (uint32_t)ARRAY_SIZE(vertex_array),
.initial.data = vertex_array,
});
}
/* Setup indices */
{
static const uint16_t index_array[6] = {
0, 1, 2, /* */
1, 2, 3 /* */
};
index_buffer = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Index buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
.size = sizeof(index_array),
.count = (uint32_t)ARRAY_SIZE(index_array),
.initial.data = index_array,
});
}
}
static void update_uniforms(wgpu_context_t* wgpu_context)
{
/* Update color attachment clear color */
render_pass.color_attachments[0].clearValue = (WGPUColor){
.r = grid_options.clear_color[0], /* Red */
.g = grid_options.clear_color[1], /* Green */
.b = grid_options.clear_color[2], /* Blue */
.a = grid_options.clear_color[3], /* Alpha */
};
/* Update uniforms data */
memcpy(&uniform_array.line_color, &grid_options.line_color,
sizeof(WGPUColor));
memcpy(&uniform_array.base_color, &grid_options.base_color,
sizeof(WGPUColor));
glm_vec2_copy((vec2){grid_options.line_width_x, grid_options.line_width_y},
uniform_array.line_width);
/* Update uniform buffer */
wgpu_queue_write_buffer(wgpu_context, uniform_buffer.buffer, 0,
&uniform_array, sizeof(uniform_array));
}
static void update_projection(wgpu_context_t* wgpu_context)
{
const float aspect_ratio
= (float)wgpu_context->surface.width / (float)wgpu_context->surface.height;
// Using mat4.perspectiveZO instead of mat4.perpective because WebGPU's
// normalized device coordinates Z range is [0, 1], instead of WebGL's [-1, 1]
glm_mat4_perspective_zo(&camera_uniforms.projection_matrix, camera_parms.fov,
aspect_ratio, camera_parms.z_near,
&camera_parms.z_far);
}
static void update_mouse_state(wgpu_example_context_t* context)
{
if (!camera.mouse.moving && context->mouse_buttons.left) {
/* pointerdown -> downCallback */
glm_vec2_copy(context->mouse_position, camera.mouse.prev_position);
camera.mouse.moving = true;
}
else if (camera.mouse.moving && context->mouse_buttons.left) {
/* pointermove -> moveCallback */
glm_vec2_sub(context->mouse_position, camera.mouse.prev_position,
camera.mouse.move_delta);
glm_vec2_copy(context->mouse_position, camera.mouse.prev_position);
camera.dirty = camera.dirty
|| ((fabs(camera.mouse.move_delta[0]) > 1.0f)
|| (fabs(camera.mouse.move_delta[1]) > 1.0f));
}
else if (camera.mouse.moving && !context->mouse_buttons.left) {
/* pointerup -> upCallback */
camera.mouse.moving = false;
}
}
static void update_frame_uniforms(wgpu_example_context_t* context)
{
/* Update mouse state */
update_mouse_state(context);
/* Handle mouse movement */
if (camera.dirty) {
orbit_camera_orbit(&camera, camera.mouse.move_delta[0] * 0.025f,
camera.mouse.move_delta[1] * 0.025f);
}
/* Update frame uniforms data */
glm_mat4_copy(*orbit_camera_get_view_matrix(&camera),
camera_uniforms.view_matrix);
glm_vec3_copy(*orbit_camera_get_position(&camera),
camera_uniforms.camera_position);
camera_uniforms.time = context->frame.timestamp_millis;
/* Update uniform buffer */
wgpu_queue_write_buffer(context->wgpu_context, frame_uniform_buffer.buffer, 0,
&camera_uniforms, sizeof(camera_uniforms));
}
static void prepare_uniform_buffers(wgpu_example_context_t* context)
{
wgpu_context_t* wgpu_context = context->wgpu_context;
/* Frame uniform buffer */
{
frame_uniform_buffer
= wgpu_create_buffer(wgpu_context, &(wgpu_buffer_desc_t){
.label = "Frame - Uniform buffer",
.usage = WGPUBufferUsage_CopyDst
| WGPUBufferUsage_Uniform,
.size = sizeof(camera_uniforms),
});
ASSERT(frame_uniform_buffer.buffer != NULL);
}
/* Update uniform buffer */
update_projection(wgpu_context);
update_frame_uniforms(context);
/* Uniform buffer */
{
uniform_buffer
= wgpu_create_buffer(wgpu_context, &(wgpu_buffer_desc_t){
.label = "Uniform buffer",
.usage = WGPUBufferUsage_CopyDst
| WGPUBufferUsage_Uniform,
.size = sizeof(uniform_array),
});
ASSERT(uniform_buffer.buffer != NULL);
}
/* Update uniform buffer */
update_uniforms(wgpu_context);
}
static void setup_bind_group_layouts(wgpu_context_t* wgpu_context)
{
/* Frame bind group layout */
{
WGPUBindGroupLayoutEntry bgl_entries[1] = {
[0] = (WGPUBindGroupLayoutEntry) {
/* Binding 0 : Camera/Frame uniforms */
.binding = 0, /* Camera/Frame uniforms */
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(camera_uniforms),
},
.sampler = {0},
},
};
frame_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = "Frame - Bind group layout",
.entryCount = (uint32_t)ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
ASSERT(frame_bind_group_layout != NULL);
}
/* Pristine Grid bind group layout */
{
WGPUBindGroupLayoutEntry bgl_entries[1] = {
[0] = (WGPUBindGroupLayoutEntry) {
/* Binding 0 : uniform array */
.binding = 0,
.visibility = WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout) {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_array),
},
.sampler = {0},
},
};
bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = "Pristine Grid - Bind group layout",
.entryCount = (uint32_t)ARRAY_SIZE(bgl_entries),
.entries = bgl_entries,
});
ASSERT(bind_group_layout != NULL);
}
}
static void setup_pipeline_layout(wgpu_context_t* wgpu_context)
{
WGPUBindGroupLayout bind_group_layouts[2] = {
frame_bind_group_layout, /* Group 0 */
bind_group_layout, /* Group 1 */
};
pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device,
&(WGPUPipelineLayoutDescriptor){
.label = "Pristine Grid - Pipeline layout",
.bindGroupLayoutCount = (uint32_t)ARRAY_SIZE(bind_group_layouts),
.bindGroupLayouts = bind_group_layouts,
});
ASSERT(pipeline_layout != NULL);
}
static void setup_bind_groups(wgpu_context_t* wgpu_context)
{
/* Frame bind group */
{
frame_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor) {
.label = "Frame - Bind group",
.layout = frame_bind_group_layout,
.entryCount = 1,
.entries = &(WGPUBindGroupEntry) {
/* Binding 0 : Camera uniforms */
.binding = 0, // Camera uniforms
.buffer = frame_uniform_buffer.buffer,
.offset = 0,
.size = frame_uniform_buffer.size,
},
}
);
ASSERT(frame_bind_group != NULL);
}
/* Pristine Grid bind group */
{
bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor) {
.label = "Pristine Grid - Bind group",
.layout = bind_group_layout,
.entryCount = 1,
.entries = &(WGPUBindGroupEntry) {
/* Binding 0 : Uniform buffer */
.binding = 0,
.buffer = uniform_buffer.buffer,
.offset = 0,
.size = uniform_buffer.size,
},
}
);
ASSERT(bind_group != NULL);
}
}
static void allocate_render_targets(wgpu_context_t* wgpu_context,
WGPUExtent2D size)
{
WGPU_RELEASE_RESOURCE(TextureView, textures.msaa_color.view)
WGPU_RELEASE_RESOURCE(Texture, textures.msaa_color.texture)
/* Multi-sampled color render target */
if (msaa_sample_count > 1) {
/* Create the multi-sampled texture */
WGPUTextureDescriptor multisampled_frame_desc = {
.label = "Multi-sampled texture",
.size = (WGPUExtent3D){
.width = size.width,
.height = size.height,
.depthOrArrayLayers = 1,
},
.mipLevelCount = 1,
.sampleCount = msaa_sample_count,
.dimension = WGPUTextureDimension_2D,
.format = wgpu_context->swap_chain.format,
.usage = WGPUTextureUsage_RenderAttachment,
};
textures.msaa_color.texture
= wgpuDeviceCreateTexture(wgpu_context->device, &multisampled_frame_desc);
ASSERT(textures.msaa_color.texture != NULL);
/* Create the multi-sampled texture view */
textures.msaa_color.view = wgpuTextureCreateView(
textures.msaa_color.texture, &(WGPUTextureViewDescriptor){
.label = "Multi-sampled texture view",
.format = wgpu_context->swap_chain.format,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
});
ASSERT(textures.msaa_color.view != NULL);
}
WGPU_RELEASE_RESOURCE(TextureView, textures.depth.view)
WGPU_RELEASE_RESOURCE(Texture, textures.depth.texture)
/* Multi-sampled color render target */
{
/* Create the multi-sampled texture */
WGPUTextureDescriptor multisampled_frame_desc = {
.label = "Depth texture",
.size = (WGPUExtent3D){
.width = size.width,
.height = size.height,
.depthOrArrayLayers = 1,
},
.mipLevelCount = 1,
.sampleCount = msaa_sample_count,
.dimension = WGPUTextureDimension_2D,
.format = depth_format,
.usage = WGPUTextureUsage_RenderAttachment,
};
textures.depth.texture
= wgpuDeviceCreateTexture(wgpu_context->device, &multisampled_frame_desc);
ASSERT(textures.depth.texture != NULL);
/* Create the multi-sampled texture view */
textures.depth.view = wgpuTextureCreateView(
textures.depth.texture, &(WGPUTextureViewDescriptor){
.label = "Multi-sampled texture view",
.format = depth_format,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
});
ASSERT(textures.depth.view != NULL);
}
}
static void setup_render_pass(void)
{
/* Color attachment */
render_pass.color_attachments[0] = (WGPURenderPassColorAttachment){
/* Appropriate target will be populated in onFrame */
.view = msaa_sample_count > 1 ? textures.msaa_color.view : NULL,
.depthSlice = ~0,
.resolveTarget = NULL,
.clearValue = {
.r = grid_options.clear_color[0],
.g = grid_options.clear_color[1],
.b = grid_options.clear_color[2],
.a = grid_options.clear_color[3],
},
.loadOp = WGPULoadOp_Clear,
.storeOp = msaa_sample_count > 1 ? WGPUStoreOp_Discard : WGPUStoreOp_Store,
};
/* Depth-stencil attachment */
render_pass.depth_stencil_attachment = (WGPURenderPassDepthStencilAttachment){
.view = textures.depth.view,
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Discard,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
};
/* Render pass descriptor */
render_pass.descriptor = (WGPURenderPassDescriptor){
.label = "Render pass descriptor",
.colorAttachmentCount = 1,
.colorAttachments = render_pass.color_attachments,
.depthStencilAttachment = &render_pass.depth_stencil_attachment,
};
}
static void prepare_render_pipeline(wgpu_context_t* wgpu_context)
{
/* Primitive state */
WGPUPrimitiveState primitive_state = {
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
};
/* Color target state */
WGPUBlendState blend_state = wgpu_create_blend_state(false);
WGPUColorTargetState color_target_state = (WGPUColorTargetState){
.format = wgpu_context->swap_chain.format,
.blend = &blend_state,
.writeMask = WGPUColorWriteMask_All,
};
/* Depth stencil state */
WGPUDepthStencilState depth_stencil_state
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = depth_format,
.depth_write_enabled = true,
});
depth_stencil_state.depthCompare = WGPUCompareFunction_LessEqual;
/* Vertex buffer layout */
WGPU_VERTEX_BUFFER_LAYOUT(
triangle, 20,
/* Attribute location 0: Position */
WGPU_VERTATTR_DESC(0, WGPUVertexFormat_Float32x3, 0),
/* Attribute location 1: UV */
WGPU_VERTATTR_DESC(1, WGPUVertexFormat_Float32x2, sizeof(float) * 3))
/* Vertex state */
WGPUVertexState vertex_state = wgpu_create_vertex_state(
wgpu_context, &(wgpu_vertex_state_t){
.shader_desc = (wgpu_shader_desc_t){
/* Vertex shader WGSL */
.label = "Grid - Vertex shader WGSL",
.wgsl_code.source = grid_shader_wgsl,
.entry = "vertexMain",
},
.buffer_count = 1,
.buffers = &triangle_vertex_buffer_layout,
});
/* Fragment state */
WGPUFragmentState fragment_state = wgpu_create_fragment_state(
wgpu_context, &(wgpu_fragment_state_t){
.shader_desc = (wgpu_shader_desc_t){
/* Fragment shader WGSL */
.label = "Grid - Fragment shader WGSL",
.wgsl_code.source = grid_shader_wgsl,
.entry = "fragmentMain",
},
.target_count = 1,
.targets = &color_target_state,
});
/* Multisample state */
WGPUMultisampleState multisample_state
= wgpu_create_multisample_state_descriptor(
&(create_multisample_state_desc_t){
.sample_count = msaa_sample_count,
});
/* Create rendering pipeline using the specified states */
pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device, &(WGPURenderPipelineDescriptor){
.label = "Pristine Grid - Render pipeline",
.layout = pipeline_layout,
.primitive = primitive_state,
.vertex = vertex_state,
.fragment = &fragment_state,
.depthStencil = &depth_stencil_state,
.multisample = multisample_state,
});
/* Partial cleanup */
WGPU_RELEASE_RESOURCE(ShaderModule, vertex_state.module);
WGPU_RELEASE_RESOURCE(ShaderModule, fragment_state.module);
}
static void example_on_resize(wgpu_example_context_t* context)
{
wgpu_context_t* wgpu_context = context->wgpu_context;
if (wgpu_context->surface.width == 0 || wgpu_context->surface.height == 0) {
return;
}
update_projection(context->wgpu_context);
if (wgpu_context->device) {
allocate_render_targets(wgpu_context,
(WGPUExtent2D){
.width = wgpu_context->surface.width,
.height = wgpu_context->surface.height,
});
}
}
static int example_initialize(wgpu_example_context_t* context)
{
UNUSED_FUNCTION(orbit_camera_get_target);
UNUSED_FUNCTION(orbit_camera_set_target);
UNUSED_FUNCTION(orbit_camera_get_distance);
UNUSED_FUNCTION(orbit_camera_set_distance);
UNUSED_FUNCTION(example_on_resize);
if (context) {
wgpu_context_t* wgpu_context = context->wgpu_context;
orbit_camera_init(&camera);
prepare_vertex_and_index_buffers(wgpu_context);
prepare_uniform_buffers(context);
setup_bind_group_layouts(wgpu_context);
setup_pipeline_layout(wgpu_context);
prepare_render_pipeline(wgpu_context);
setup_bind_groups(wgpu_context);
allocate_render_targets(wgpu_context,
(WGPUExtent2D){
.width = wgpu_context->surface.width,
.height = wgpu_context->surface.height,
});
setup_render_pass();
prepared = true;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
static WGPURenderPassDescriptor const*
get_default_render_pass_descriptor(wgpu_context_t* wgpu_context)
{
const WGPUTextureView color_texture = wgpu_context->swap_chain.frame_buffer;
if (msaa_sample_count > 1) {
render_pass.color_attachments[0].resolveTarget = color_texture;
}
else {
render_pass.color_attachments[0].view = color_texture;
}
return &render_pass.descriptor;
}
static void example_on_update_ui_overlay(wgpu_example_context_t* context)
{
if (imgui_overlay_header("Settings")) {
if (imgui_overlay_color_edit4(context->imgui_overlay, "clearColor",
grid_options.clear_color)) {
update_uniforms(context->wgpu_context);
}
if (imgui_overlay_color_edit4(context->imgui_overlay, "lineColor",
grid_options.line_color)) {
update_uniforms(context->wgpu_context);
}
if (imgui_overlay_color_edit4(context->imgui_overlay, "baseColor",
grid_options.base_color)) {
update_uniforms(context->wgpu_context);
}
if (imgui_overlay_slider_float(context->imgui_overlay, "lineWidthX",
&grid_options.line_width_x, 0.0f, 1.0f,
"%.001f")) {
update_uniforms(context->wgpu_context);
}
if (imgui_overlay_slider_float(context->imgui_overlay, "lineWidthY",
&grid_options.line_width_y, 0.0f, 1.0f,
"%.001f")) {
update_uniforms(context->wgpu_context);
}
}
}
static WGPUCommandBuffer build_command_buffer(wgpu_context_t* wgpu_context)
{
/* Create command encoder */
wgpu_context->cmd_enc
= wgpuDeviceCreateCommandEncoder(wgpu_context->device, NULL);
/* Create render pass encoder for encoding drawing commands */
wgpu_context->rpass_enc = wgpuCommandEncoderBeginRenderPass(
wgpu_context->cmd_enc, get_default_render_pass_descriptor(wgpu_context));
if (pipeline) {
/* Bind the rendering pipeline */
wgpuRenderPassEncoderSetPipeline(wgpu_context->rpass_enc, pipeline);
/* Set viewport */
wgpuRenderPassEncoderSetViewport(
wgpu_context->rpass_enc, 0.0f, 0.0f, (float)wgpu_context->surface.width,
(float)wgpu_context->surface.height, 0.0f, 1.0f);
/* Set scissor rectangle */
wgpuRenderPassEncoderSetScissorRect(wgpu_context->rpass_enc, 0u, 0u,
wgpu_context->surface.width,
wgpu_context->surface.height);
/* Set the bind groups */
wgpuRenderPassEncoderSetBindGroup(wgpu_context->rpass_enc, 0,
frame_bind_group, 0, 0);
wgpuRenderPassEncoderSetBindGroup(
wgpu_context->rpass_enc, 1, bind_group, 0,
0); /* Assumes the camera bind group is already set. */
/* Bind vertex buffer (contains positions & uvs) */
wgpuRenderPassEncoderSetVertexBuffer(
wgpu_context->rpass_enc, 0, vertex_buffer.buffer, 0, WGPU_WHOLE_SIZE);
/* Bind index buffer */