-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathinstancing.c
More file actions
1752 lines (1529 loc) · 58.2 KB
/
Copy pathinstancing.c
File metadata and controls
1752 lines (1529 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
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 "webgpu/imgui_overlay.h"
#include "webgpu/wgpu_common.h"
#include "core/camera.h"
#include "core/gltf_model.h"
#include "core/image_loader.h"
#include <cglm/cglm.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef __WAJIC__
#define WAJIC_SFETCH_IMPL
#include <wajic_sfetch.h>
#define WAJIC_TIME_IMPL
#include <wajic_time.h>
#else
#define SOKOL_FETCH_IMPL
#include <sokol_fetch.h>
#define SOKOL_LOG_IMPL
#include <sokol_log.h>
#define SOKOL_TIME_IMPL
#include <sokol_time.h>
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#define CIMGUI_DEFINE_ENUMS_AND_STRUCTS
#endif
#include <cimgui.h>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
/* In WAjic, WGPU handles are uint32_t; redefine NULL to 0 so that handle
* assignments like `state.bg_rocks = NULL` compile without warnings. */
#ifdef __WAJIC__
#ifdef NULL
#undef NULL
#define NULL 0
#endif
#endif
/* -------------------------------------------------------------------------- *
* WebGPU Example - Instanced Mesh Rendering
*
* Renders thousands of asteroid rocks orbiting a lava planet using GPU
* instancing. Each rock instance uses a separate per-instance vertex buffer
* containing position, rotation, scale, and texture array layer index.
* Three render pipelines handle the star field backdrop (procedural vertex
* shader), the planet (single 2D texture), and the instanced rocks (2D
* texture array).
*
* Ported from Sascha Willems' Vulkan example "instancing"
* https://github.com/SaschaWillems/Vulkan/tree/master/examples/instancing
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders (declared here, defined at bottom of file)
* -------------------------------------------------------------------------- */
static const char* instancing_rocks_shader_wgsl;
static const char* instancing_planet_shader_wgsl;
static const char* instancing_starfield_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define INSTANCE_COUNT (8192u)
/* Rock texture atlas: 5 layers of 512×512 RGBA stacked vertically */
#define ROCKS_LAYER_SIZE (512u)
#define ROCKS_LAYER_COUNT (5u)
/* Planet texture: single 512×512 RGBA */
#define PLANET_TEXTURE_SIZE (512u)
/* File buffer sizes (for PNG-compressed data) */
#define PLANET_FILE_BUFFER_SIZE (640u * 1024u) /* ~640 KB */
#define ROCKS_FILE_BUFFER_SIZE (3u * 1024u * 1024u) /* ~3 MB */
// clang-format off
static const char* rock_model_path = "assets/models/rock01.gltf";
static const char* planet_model_path = "assets/models/lavaplanet.gltf";
static const char* rocks_tex_path = "assets/textures/texturearray_rocks_rgba.png";
static const char* planet_tex_path = "assets/textures/lavaplanet_rgba.png";
// clang-format on
/* -------------------------------------------------------------------------- *
* Data layouts
* -------------------------------------------------------------------------- */
/* Per-instance data placed in its own vertex buffer (binding 1) */
typedef struct {
vec3 pos; /* World-space position for this instance */
vec3 rot; /* Rotation seed angles (x, y, z) */
float scale; /* Uniform scale */
uint32_t tex_index; /* Index into the rocks texture array (0 .. 4) */
} instance_data_t; /* 32 bytes total */
/* Uniform buffer – must match WGSL struct layout exactly.
* Offsets (WGSL std140 / WebGPU alignment):
* projection @ 0 (64 bytes)
* view @ 64 (64 bytes)
* lightPos @ 128 (16 bytes)
* locSpeed @ 144 (4 bytes)
* globSpeed @ 148 (4 bytes)
* _pad @ 152 (8 bytes) → struct size = 160 bytes
*/
typedef struct {
mat4 projection;
mat4 view;
vec4 light_pos;
float loc_speed;
float glob_speed;
float _pad[2];
} uniform_data_t; /* 160 bytes */
/* -------------------------------------------------------------------------- *
* Global state
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* ---- Models ---------------------------------------------------------- */
struct {
gltf_model_t rock;
gltf_model_t planet;
bool rock_loaded;
bool planet_loaded;
#ifdef __WAJIC__
bool model_buffers_created;
#endif
} models;
/* GPU geometry buffers (one vertex + one index buffer per model) */
struct {
struct {
WGPUBuffer vertex;
WGPUBuffer index;
} rock;
struct {
WGPUBuffer vertex;
WGPUBuffer index;
} planet;
} model_buffers;
/* ---- Instance data ---------------------------------------------------- */
WGPUBuffer instance_buffer;
/* ---- Textures --------------------------------------------------------- */
wgpu_texture_t rocks_texture; /* texture_2d_array, 5 layers */
wgpu_texture_t planet_texture; /* texture_2d, single layer */
/* Async-load staging data */
uint8_t* rocks_file_buffer;
uint8_t* planet_file_buffer;
bool rocks_texture_loaded;
bool planet_texture_loaded;
/* ---- Uniform buffer --------------------------------------------------- */
WGPUBuffer uniform_buffer;
uniform_data_t ubo;
/* ---- Bind group layouts ----------------------------------------------- */
WGPUBindGroupLayout bgl_ubo_only; /* starfield: binding 0 = UBO only */
WGPUBindGroupLayout bgl_static; /* planet: binding 0=UBO, 1=sampler, */
/* binding 2=texture_2d */
WGPUBindGroupLayout bgl_rocks; /* rocks: binding 0=UBO, 1=sampler, */
/* binding 2=texture_2d_array */
/* ---- Bind groups ------------------------------------------------------ */
WGPUBindGroup bg_starfield; /* UBO only */
WGPUBindGroup bg_planet; /* UBO + sampler + planet texture */
WGPUBindGroup bg_rocks; /* UBO + sampler + rocks texture array */
/* ---- Pipeline layouts ------------------------------------------------- */
WGPUPipelineLayout pl_starfield;
WGPUPipelineLayout pl_static;
WGPUPipelineLayout pl_rocks;
/* ---- Pipelines -------------------------------------------------------- */
WGPURenderPipeline pipeline_starfield;
WGPURenderPipeline pipeline_planet;
WGPURenderPipeline pipeline_rocks;
/* ---- Render pass ------------------------------------------------------ */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* ---- Timing ----------------------------------------------------------- */
uint64_t last_frame_time;
bool paused;
WGPUBool initialized;
} state = {
.ubo = {
.light_pos = {0.0f, 5.0f, 0.0f, 1.0f}, /* WebGPU Y-up: light above */
.loc_speed = 0.0f,
.glob_speed = 0.0f,
},
.color_attachment = {
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.2f, 1.0f},
},
.depth_stencil_attachment = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Clear,
.stencilStoreOp = WGPUStoreOp_Store,
.stencilClearValue = 0,
},
.render_pass_descriptor = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
};
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
#ifdef __WAJIC__
static void rock_model_fetch_cb(const sfetch_response_t* resp)
{
if (!resp->fetched) {
printf("[instancing] Rock model fetch failed, error: %d\n",
resp->error_code);
return;
}
state.models.rock_loaded = gltf_model_load_from_memory(
&state.models.rock, resp->data.ptr, resp->data.size, rock_model_path, 1.0f);
if (state.models.rock_loaded) {
gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
gltf_model_bake_node_transforms(&state.models.rock,
state.models.rock.vertices, &desc);
}
else {
printf("[instancing] Failed to parse rock model\n");
}
}
static void planet_model_fetch_cb(const sfetch_response_t* resp)
{
if (!resp->fetched) {
printf("[instancing] Planet model fetch failed, error: %d\n",
resp->error_code);
return;
}
state.models.planet_loaded
= gltf_model_load_from_memory(&state.models.planet, resp->data.ptr,
resp->data.size, planet_model_path, 1.0f);
if (state.models.planet_loaded) {
gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
gltf_model_bake_node_transforms(&state.models.planet,
state.models.planet.vertices, &desc);
}
else {
printf("[instancing] Failed to parse planet model\n");
}
}
#endif /* __WAJIC__ */
static void load_models(void)
{
#ifdef __WAJIC__
sfetch_send(&(sfetch_request_t){
.path = rock_model_path,
.callback = rock_model_fetch_cb,
});
sfetch_send(&(sfetch_request_t){
.path = planet_model_path,
.callback = planet_model_fetch_cb,
});
#else
gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices
| GltfLoadingFlag_PreMultiplyVertexColors,
};
state.models.rock_loaded = gltf_model_load_from_file_ext(
&state.models.rock, rock_model_path, 1.0f, &desc);
if (!state.models.rock_loaded) {
printf("[instancing] Failed to load rock model: %s\n", rock_model_path);
}
state.models.planet_loaded = gltf_model_load_from_file_ext(
&state.models.planet, planet_model_path, 1.0f, &desc);
if (!state.models.planet_loaded) {
printf("[instancing] Failed to load planet model: %s\n", planet_model_path);
}
#endif
}
static void create_model_buffers(wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ---- Rock model buffers ---------------------------------------------- */
if (state.models.rock_loaded) {
uint32_t vb_size
= state.models.rock.vertex_count * (uint32_t)sizeof(gltf_vertex_t);
state.model_buffers.rock.vertex = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Rock - Vertex buffer"),
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = vb_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.model_buffers.rock.vertex,
0, state.models.rock.vertices, vb_size);
uint32_t ib_size
= state.models.rock.index_count * (uint32_t)sizeof(uint32_t);
state.model_buffers.rock.index = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Rock index buffer"),
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst,
.size = ib_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.model_buffers.rock.index, 0,
state.models.rock.indices, ib_size);
}
/* ---- Planet model buffers -------------------------------------------- */
if (state.models.planet_loaded) {
uint32_t vb_size
= state.models.planet.vertex_count * (uint32_t)sizeof(gltf_vertex_t);
state.model_buffers.planet.vertex = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Planet vertex buffer"),
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = vb_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.model_buffers.planet.vertex,
0, state.models.planet.vertices, vb_size);
uint32_t ib_size
= state.models.planet.index_count * (uint32_t)sizeof(uint32_t);
state.model_buffers.planet.index = wgpuDeviceCreateBuffer(
device, &(WGPUBufferDescriptor){
.label = STRVIEW("Planet index buffer"),
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst,
.size = ib_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.model_buffers.planet.index,
0, state.models.planet.indices, ib_size);
}
}
/* -------------------------------------------------------------------------- *
* Instance data
* -------------------------------------------------------------------------- */
static float uniform_rand(void)
{
return (float)rand() / ((float)RAND_MAX + 1.0f);
}
static void prepare_instance_data(wgpu_context_t* wgpu_context)
{
srand((unsigned int)time(NULL));
instance_data_t* instances
= (instance_data_t*)malloc(INSTANCE_COUNT * sizeof(instance_data_t));
if (!instances) {
printf("[instancing] Failed to allocate instance data\n");
return;
}
const float pi = 3.14159265358979323846f;
/* Distribute rocks on two concentric rings in the XZ plane */
const float ring0_min = 7.0f, ring0_max = 11.0f;
const float ring1_min = 14.0f, ring1_max = 18.0f;
for (uint32_t i = 0; i < INSTANCE_COUNT / 2; ++i) {
float rho, theta;
/* Inner ring */
rho = sqrtf((ring0_max * ring0_max - ring0_min * ring0_min) * uniform_rand()
+ ring0_min * ring0_min);
theta = 2.0f * pi * uniform_rand();
instances[i].pos[0] = rho * cosf(theta);
instances[i].pos[1] = uniform_rand() * 0.5f - 0.25f;
instances[i].pos[2] = rho * sinf(theta);
instances[i].rot[0] = pi * uniform_rand();
instances[i].rot[1] = pi * uniform_rand();
instances[i].rot[2] = pi * uniform_rand();
instances[i].scale = (1.5f + uniform_rand() - uniform_rand()) * 0.75f;
instances[i].tex_index = (uint32_t)(uniform_rand() * ROCKS_LAYER_COUNT);
if (instances[i].tex_index >= ROCKS_LAYER_COUNT) {
instances[i].tex_index = ROCKS_LAYER_COUNT - 1;
}
/* Outer ring */
rho = sqrtf((ring1_max * ring1_max - ring1_min * ring1_min) * uniform_rand()
+ ring1_min * ring1_min);
theta = 2.0f * pi * uniform_rand();
uint32_t j = i + INSTANCE_COUNT / 2;
instances[j].pos[0] = rho * cosf(theta);
instances[j].pos[1] = uniform_rand() * 0.5f - 0.25f;
instances[j].pos[2] = rho * sinf(theta);
instances[j].rot[0] = pi * uniform_rand();
instances[j].rot[1] = pi * uniform_rand();
instances[j].rot[2] = pi * uniform_rand();
instances[j].scale = (1.5f + uniform_rand() - uniform_rand()) * 0.75f;
instances[j].tex_index = (uint32_t)(uniform_rand() * ROCKS_LAYER_COUNT);
if (instances[j].tex_index >= ROCKS_LAYER_COUNT) {
instances[j].tex_index = ROCKS_LAYER_COUNT - 1;
}
}
/* Upload to GPU */
uint64_t buf_size = INSTANCE_COUNT * sizeof(instance_data_t);
state.instance_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Instance data buffer"),
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = buf_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.instance_buffer, 0, instances,
buf_size);
free(instances);
}
/* -------------------------------------------------------------------------- *
* Texture loading (async via sokol_fetch)
* -------------------------------------------------------------------------- */
/* Forward declarations */
static void init_bind_groups(wgpu_context_t* wgpu_context);
static void update_bind_groups(wgpu_context_t* wgpu_context);
static void fetch_rocks_texture_cb(const sfetch_response_t* resp)
{
if (!resp->fetched) {
printf("[instancing] Rocks texture fetch failed, error: %d\n",
resp->error_code);
return;
}
int w, h, ch;
uint8_t* pixels = image_pixels_from_memory(
resp->data.ptr, (int)resp->data.size, &w, &h, &ch, 4);
if (!pixels) {
printf("[instancing] Failed to decode rocks texture\n");
return;
}
const int exp_w = (int)ROCKS_LAYER_SIZE;
const int exp_h = (int)(ROCKS_LAYER_SIZE * ROCKS_LAYER_COUNT);
if (w != exp_w || h != exp_h) {
printf("[instancing] Rocks texture size mismatch: %dx%d (expected %dx%d)\n",
w, h, exp_w, exp_h);
image_free(pixels);
return;
}
state.rocks_texture.desc = (wgpu_texture_desc_t){
.extent = (WGPUExtent3D){
.width = (uint32_t)ROCKS_LAYER_SIZE,
.height = (uint32_t)ROCKS_LAYER_SIZE,
.depthOrArrayLayers = (uint32_t)ROCKS_LAYER_COUNT,
},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {
.ptr = pixels,
.size = (size_t)ROCKS_LAYER_SIZE * ROCKS_LAYER_SIZE * ROCKS_LAYER_COUNT * 4,
},
.generate_mipmaps = 1,
.mipmap_view_dimension = WGPU_MIPMAP_VIEW_2D_ARRAY,
};
state.rocks_texture.desc.is_dirty = true;
}
static void fetch_planet_texture_cb(const sfetch_response_t* resp)
{
if (!resp->fetched) {
printf("[instancing] Planet texture fetch failed, error: %d\n",
resp->error_code);
return;
}
int w, h, ch;
uint8_t* pixels = image_pixels_from_memory(
resp->data.ptr, (int)resp->data.size, &w, &h, &ch, 4);
if (!pixels) {
printf("[instancing] Failed to decode planet texture\n");
return;
}
if (w != (int)PLANET_TEXTURE_SIZE || h != (int)PLANET_TEXTURE_SIZE) {
printf("[instancing] Planet texture size mismatch: %dx%d\n", w, h);
image_free(pixels);
return;
}
state.planet_texture.desc = (wgpu_texture_desc_t){
.extent = (WGPUExtent3D){
.width = (uint32_t)PLANET_TEXTURE_SIZE,
.height = (uint32_t)PLANET_TEXTURE_SIZE,
.depthOrArrayLayers = 1,
},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {
.ptr = pixels,
.size = (size_t)PLANET_TEXTURE_SIZE * PLANET_TEXTURE_SIZE * 4,
},
.generate_mipmaps = 1,
.mipmap_view_dimension = WGPU_MIPMAP_VIEW_2D,
};
state.planet_texture.desc.is_dirty = true;
}
static void init_textures(wgpu_context_t* wgpu_context)
{
/* ---- Rocks texture array placeholder (1×1 per layer) ----------------- */
{
uint8_t placeholder[4 * ROCKS_LAYER_COUNT];
memset(placeholder, 64, sizeof(placeholder));
state.rocks_texture = wgpu_create_texture(
wgpu_context,
&(wgpu_texture_desc_t){
.extent = {1, 1, ROCKS_LAYER_COUNT},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {.ptr = placeholder, .size = sizeof(placeholder)},
.mipmap_view_dimension = WGPU_MIPMAP_VIEW_2D_ARRAY,
});
sfetch_send(&(sfetch_request_t){
.path = rocks_tex_path,
.callback = fetch_rocks_texture_cb,
#ifndef __WAJIC__
.buffer
= {.ptr = state.rocks_file_buffer, .size = ROCKS_FILE_BUFFER_SIZE},
#endif
});
}
/* ---- Planet texture placeholder (1×1) -------------------------------- */
{
uint8_t placeholder[4] = {64, 64, 64, 255};
state.planet_texture = wgpu_create_texture(
wgpu_context,
&(wgpu_texture_desc_t){
.extent = {1, 1, 1},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {.ptr = placeholder, .size = sizeof(placeholder)},
.mipmap_view_dimension = WGPU_MIPMAP_VIEW_2D,
});
sfetch_send(&(sfetch_request_t){
.path = planet_tex_path,
.callback = fetch_planet_texture_cb,
#ifndef __WAJIC__
.buffer
= {.ptr = state.planet_file_buffer, .size = PLANET_FILE_BUFFER_SIZE},
#endif
});
}
}
static void update_textures(wgpu_context_t* wgpu_context)
{
/* ---- Update rocks texture if new data arrived ------------------------ */
if (state.rocks_texture.desc.is_dirty) {
wgpu_recreate_texture(wgpu_context, &state.rocks_texture);
if (state.rocks_texture.desc.pixels.ptr) {
image_free((void*)state.rocks_texture.desc.pixels.ptr);
state.rocks_texture.desc.pixels.ptr = NULL;
state.rocks_texture.desc.pixels.size = 0;
}
/* Rebind */
if (state.bg_rocks) {
wgpuBindGroupRelease(state.bg_rocks);
state.bg_rocks = NULL;
}
state.rocks_texture_loaded = true;
update_bind_groups(wgpu_context);
}
/* ---- Update planet texture if new data arrived ----------------------- */
if (state.planet_texture.desc.is_dirty) {
wgpu_recreate_texture(wgpu_context, &state.planet_texture);
if (state.planet_texture.desc.pixels.ptr) {
image_free((void*)state.planet_texture.desc.pixels.ptr);
state.planet_texture.desc.pixels.ptr = NULL;
state.planet_texture.desc.pixels.size = 0;
}
/* Rebind */
if (state.bg_planet) {
wgpuBindGroupRelease(state.bg_planet);
state.bg_planet = NULL;
}
state.planet_texture_loaded = true;
update_bind_groups(wgpu_context);
}
}
/* -------------------------------------------------------------------------- *
* Uniform buffer
* -------------------------------------------------------------------------- */
static void init_uniform_buffer(wgpu_context_t* wgpu_context)
{
state.uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Instancing uniform buffer"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(uniform_data_t),
.mappedAtCreation = false,
});
}
static void update_uniform_buffer(wgpu_context_t* wgpu_context, float dt)
{
camera_update(&state.camera, dt);
glm_mat4_copy(state.camera.matrices.perspective, state.ubo.projection);
glm_mat4_copy(state.camera.matrices.view, state.ubo.view);
if (!state.paused) {
state.ubo.loc_speed += dt * 0.35f;
state.ubo.glob_speed += dt * 0.01f;
}
wgpuQueueWriteBuffer(wgpu_context->queue, state.uniform_buffer, 0, &state.ubo,
sizeof(uniform_data_t));
}
/* -------------------------------------------------------------------------- *
* Bind group layouts
* -------------------------------------------------------------------------- */
static void init_bind_group_layouts(wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ---- Starfield: UBO only (binding 0) --------------------------------- */
{
WGPUBindGroupLayoutEntry entries[1] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_data_t),
},
},
};
state.bgl_ubo_only = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("BGL - UBO only"),
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
/* ---- Planet/static: UBO + sampler + texture_2d ----------------------- */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_data_t),
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = (WGPUSamplerBindingLayout){
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = (WGPUTextureBindingLayout){
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
};
state.bgl_static = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("BGL - static (planet)"),
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
/* ---- Rocks: UBO + sampler + texture_2d_array ------------------------- */
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = (WGPUBufferBindingLayout){
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(uniform_data_t),
},
},
[1] = {
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = (WGPUSamplerBindingLayout){
.type = WGPUSamplerBindingType_Filtering,
},
},
[2] = {
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = (WGPUTextureBindingLayout){
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2DArray,
.multisampled = false,
},
},
};
state.bgl_rocks = wgpuDeviceCreateBindGroupLayout(
device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("BGL - rocks (texture array)"),
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Bind groups
* -------------------------------------------------------------------------- */
static void init_bind_groups(wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* ---- Starfield bind group: UBO only ---------------------------------- */
{
WGPUBindGroupEntry entries[1] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
};
state.bg_starfield = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("BG - starfield"),
.layout = state.bgl_ubo_only,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
/* ---- Planet bind group: UBO + sampler + planet texture --------------- */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
[1] = {
.binding = 1,
.sampler = state.planet_texture.sampler,
},
[2] = {
.binding = 2,
.textureView = state.planet_texture.view,
},
};
state.bg_planet = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("BG - planet"),
.layout = state.bgl_static,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
/* ---- Rocks bind group: UBO + sampler + rocks texture array ----------- */
{
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
[1] = {
.binding = 1,
.sampler = state.rocks_texture.sampler,
},
[2] = {
.binding = 2,
.textureView = state.rocks_texture.view,
},
};
state.bg_rocks = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("BG - rocks"),
.layout = state.bgl_rocks,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* Called when a texture is (re)loaded to recreate the affected bind group */
static void update_bind_groups(wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Recreate planet bind group when planet texture changes */
if (!state.bg_planet && state.planet_texture.view) {
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
[1] = {
.binding = 1,
.sampler = state.planet_texture.sampler,
},
[2] = {
.binding = 2,
.textureView = state.planet_texture.view,
},
};
state.bg_planet = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("BG - planet"),
.layout = state.bgl_static,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
/* Recreate rocks bind group when rocks texture changes */
if (!state.bg_rocks && state.rocks_texture.view) {
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
[1] = {
.binding = 1,
.sampler = state.rocks_texture.sampler,
},
[2] = {
.binding = 2,
.textureView = state.rocks_texture.view,
},
};
state.bg_rocks = wgpuDeviceCreateBindGroup(
device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("BG - rocks"),
.layout = state.bgl_rocks,
.entryCount = (uint32_t)ARRAY_SIZE(entries),
.entries = entries,
});
}
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(wgpu_context_t* wgpu_context)
{
WGPUDevice device = wgpu_context->device;
/* Use the framework-managed depth format so it always matches the
* swapchain depth view (wgpu_context->depth_stencil_view). */
const WGPUTextureFormat depth_fmt = wgpu_context->depth_stencil_format;
/* Shared depth-stencil for opaque (planet + rocks) */
WGPUDepthStencilState depth_opaque = {
.format = depth_fmt,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
/* Depth-stencil for starfield (background – no depth write) */
WGPUDepthStencilState depth_starfield = {
.format = depth_fmt,
.depthWriteEnabled = WGPUOptionalBool_False,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
WGPUBlendState blend = wgpu_create_blend_state(false);
WGPUColorTargetState target = {
.format = wgpu_context->render_format,
.blend = &blend,
.writeMask = WGPUColorWriteMask_All,
};
/* ================================================================
* 1. Starfield pipeline (no vertex buffers, no bind groups)
* ================================================================ */
{
state.pl_starfield = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Starfield pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.bgl_ubo_only,
});
WGPUShaderModule sf_shader
= wgpu_create_shader_module(device, instancing_starfield_shader_wgsl);
state.pipeline_starfield = wgpuDeviceCreateRenderPipeline(
device, &(WGPURenderPipelineDescriptor){
.label = STRVIEW("Starfield pipeline"),
.layout = state.pl_starfield,
.vertex = (WGPUVertexState){
.module = sf_shader,
.entryPoint = STRVIEW("vs_starfield"),
.bufferCount = 0,
.buffers = NULL,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
},
.depthStencil = &depth_starfield,
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
.fragment = &(WGPUFragmentState){
.module = sf_shader,
.entryPoint = STRVIEW("fs_starfield"),
.targetCount = 1,
.targets = &target,
},
});
WGPU_RELEASE_RESOURCE(ShaderModule, sf_shader);
}
/* ================================================================
* 2. Planet pipeline (non-instanced, single 2D texture)
* ================================================================ */
{
state.pl_static = wgpuDeviceCreatePipelineLayout(
device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Planet pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.bgl_static,
});