-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathtexture_cubemap_array.c
More file actions
1473 lines (1294 loc) · 51.4 KB
/
Copy pathtexture_cubemap_array.c
File metadata and controls
1473 lines (1294 loc) · 51.4 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>
#ifdef __WAJIC__
#define WAJIC_SFETCH_IMPL
#include <wajic_sfetch.h>
#define WAJIC_TIME_IMPL
#include <wajic_time.h>
/* WAjic WebGPU handles are uint32_t, not pointers; redefine NULL to plain 0
* so WGPU handle assignments compile without pointer-to-integer errors. */
#ifdef NULL
#undef NULL
#define NULL 0
#endif
#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
/* -------------------------------------------------------------------------- *
* WebGPU Example - Texture Cubemap Array
*
* Loads a cubemap array (3 cubemaps) from three Horizontal Cross PNG images
* and displays the selected cubemap as a skybox (background) and as a
* reflection on a selectable 3D object. The active cubemap is selected via
* a GUI slider.
*
* Face extraction from each cross image is done entirely on the GPU via a
* fragment-shader render pass (one per face × layer), writing into the
* correct array layer of a cube-array texture.
* Mipmaps are generated GPU-side using the built-in mipmap generator.
*
* Horizontal Cross layout (4W × 3H, face size = cross_w/4 × cross_h/3):
* col: 0 1 2 3
* row 0: . +Y . .
* row 1: -X +Z +X -Z
* row 2: . -Y . .
*
* Face order in WebGPU cubemap: 0=+X, 1=-X, 2=+Y, 3=-Y, 4=+Z, 5=-Z
* Array layer for face F of cubemap L: L * 6 + F
*
* Ported from Sascha Willems' Vulkan example "texturecubemaparray"
* https://github.com/SaschaWillems/Vulkan/tree/master/examples/texturecubemaparray
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders (declared here, defined at bottom of file)
* -------------------------------------------------------------------------- */
/* Main cubemap array rendering shader (skybox + reflection) */
static const char* texture_cubemap_array_shader_wgsl;
/* GPU face extraction: reads from a 2D cross image, writes to one cube face */
static const char* face_extract_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define NUM_CUBEMAP_FACES (6)
#define NUM_ARRAY_LAYERS (3)
#define NUM_TOTAL_LAYERS (NUM_CUBEMAP_FACES * NUM_ARRAY_LAYERS) /* 18 */
/* Horizontal cross source images: each 1024×768, face size = 1024/4 = 256 */
#define CUBEMAP_FACE_SIZE (256)
/* Buffer large enough for each compressed PNG cross file (~650 KB) */
#define CROSS_FILE_BUF_SIZE (2u * 1024u * 1024u)
#define NUM_OBJECTS (4)
/* -------------------------------------------------------------------------- *
* Uniform data (must match WGSL layout, 16-byte aligned)
* -------------------------------------------------------------------------- */
typedef struct {
mat4 projection; /* 64 bytes, offset 0 */
mat4 model_view; /* 64 bytes, offset 64 */
mat4 inverse_model_view; /* 64 bytes, offset 128 */
float lod_bias; /* 4 bytes, offset 192 */
int32_t cube_map_index; /* 4 bytes, offset 196 */
float _pad[2]; /* 8 bytes, offset 200 */
} uniform_data_t; /* 208 bytes total */
/* -------------------------------------------------------------------------- *
* Global state
* -------------------------------------------------------------------------- */
static struct {
/* Camera */
camera_t camera;
/* Skybox model */
gltf_model_t skybox_model;
bool skybox_model_loaded;
struct {
WGPUBuffer vertex;
WGPUBuffer index;
} skybox_buffers;
/* Selectable 3D object models */
gltf_model_t objects[NUM_OBJECTS];
bool objects_loaded[NUM_OBJECTS];
struct {
WGPUBuffer vertex;
WGPUBuffer index;
} object_buffers[NUM_OBJECTS];
/* Cubemap array texture */
struct {
WGPUTexture handle;
WGPUTextureView view;
WGPUSampler sampler;
bool is_ready;
} cubemap;
/* Per-layer raw PNG file buffers for sokol_fetch */
uint8_t* cross_file_buf[NUM_ARRAY_LAYERS];
/* Decoded cross image pixels per layer (freed after GPU upload) */
uint8_t* cross_pixels[NUM_ARRAY_LAYERS];
int cross_width[NUM_ARRAY_LAYERS];
int cross_height[NUM_ARRAY_LAYERS];
int cross_loaded_count; /* incremented atomically by sfetch callbacks */
/* Uniform buffer */
WGPUBuffer uniform_buffer;
uniform_data_t ubo;
/* Depth texture (recreated on resize) */
struct {
WGPUTexture texture;
WGPUTextureView view;
} depth;
/* Bind group / layout */
WGPUBindGroupLayout bind_group_layout;
WGPUBindGroup bind_group;
bool bind_group_dirty; /* rebuild when cubemap is ready */
/* Render pipelines */
WGPUPipelineLayout pipeline_layout;
WGPURenderPipeline skybox_pipeline;
WGPURenderPipeline reflect_pipeline;
/* Render pass descriptors */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* GUI / settings */
struct {
bool display_skybox;
float lod_bias;
int32_t object_index;
int32_t cube_map_index;
} settings;
const char* object_names[NUM_OBJECTS];
uint64_t last_frame_time;
bool initialized;
#ifdef __WAJIC__
/* WAjic async model tracking: GPU buffers are created in frame() */
int wajic_models_loaded;
bool wajic_model_buffers_created;
#endif
} state = {
/* clang-format off */
.settings = {
.display_skybox = true,
.lod_bias = 0.0f,
.object_index = 0,
.cube_map_index = 1,
},
.object_names = {
"Sphere",
"Teapot",
"Torusknot",
"Venus",
},
.color_attachment = {
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0f, 0.0f, 0.0f, 1.0f},
},
.depth_stencil_attachment = {
.depthLoadOp = WGPULoadOp_Clear,
.depthStoreOp = WGPUStoreOp_Store,
.depthClearValue = 1.0f,
.stencilLoadOp = WGPULoadOp_Undefined,
.stencilStoreOp = WGPUStoreOp_Undefined,
},
.render_pass_descriptor = {
.colorAttachmentCount = 1,
.colorAttachments = &state.color_attachment,
.depthStencilAttachment = &state.depth_stencil_attachment,
},
/* clang-format on */
};
/* -------------------------------------------------------------------------- *
* Depth texture (recreated on resize)
* -------------------------------------------------------------------------- */
static void init_depth_texture(wgpu_context_t* wgpu_context)
{
if (state.depth.view) {
wgpuTextureViewRelease(state.depth.view);
state.depth.view = NULL;
}
if (state.depth.texture) {
wgpuTextureDestroy(state.depth.texture);
wgpuTextureRelease(state.depth.texture);
state.depth.texture = NULL;
}
state.depth.texture = wgpuDeviceCreateTexture(
wgpu_context->device, &(WGPUTextureDescriptor){
.label = STRVIEW("Depth - Texture"),
.usage = WGPUTextureUsage_RenderAttachment,
.dimension = WGPUTextureDimension_2D,
.size = {(uint32_t)wgpu_context->width,
(uint32_t)wgpu_context->height, 1},
.format = WGPUTextureFormat_Depth24Plus,
.mipLevelCount = 1,
.sampleCount = 1,
});
ASSERT(state.depth.texture);
state.depth.view = wgpuTextureCreateView(state.depth.texture, NULL);
ASSERT(state.depth.view);
state.depth_stencil_attachment.view = state.depth.view;
}
/* -------------------------------------------------------------------------- *
* Cubemap array texture
* -------------------------------------------------------------------------- */
/**
* Extract all 18 cubemap faces (6 faces × 3 array layers) from the three
* horizontal cross images that were decoded into state.cross_pixels[].
*
* Algorithm per layer:
* 1. Upload the layer's cross image as a temporary 2D source texture.
* 2. Run one render pass per face, writing to array layer = layer*6 + face.
* 3. Free the CPU pixel buffer for that layer.
* After all layers are done:
* 4. Generate the full mip chain with wgpu_generate_mipmaps (CubeArray).
* 5. Create the permanent cube-array view and sampler.
* 6. Release all temporary resources.
*/
static void extract_cubemap_faces_from_crosses(wgpu_context_t* wgpu_context)
{
/* Use the dimensions from layer 0; all three cross images are the same size
*/
const uint32_t cross_w = (uint32_t)state.cross_width[0];
const uint32_t face_size = cross_w / 4u; /* = cross_h / 3 */
/* ---------------------------------------------------------------------- *
* 2. Create the destination cubemap array texture
* ---------------------------------------------------------------------- */
const uint32_t mip_count = wgpu_texture_mip_level_count(face_size, face_size);
state.cubemap.handle = wgpuDeviceCreateTexture(
wgpu_context->device,
&(WGPUTextureDescriptor){
.label = STRVIEW("Cubemap array - Texture"),
.usage = WGPUTextureUsage_TextureBinding
| WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_CopyDst,
.dimension = WGPUTextureDimension_2D,
.size = {face_size, face_size, NUM_TOTAL_LAYERS},
.format = WGPUTextureFormat_RGBA8Unorm,
.mipLevelCount = mip_count,
.sampleCount = 1,
});
ASSERT(state.cubemap.handle);
/* ---------------------------------------------------------------------- *
* 3. Build the face extraction render pipeline (shared for all layers)
* ---------------------------------------------------------------------- */
WGPUShaderModule extract_shader
= wgpu_create_shader_module(wgpu_context->device, face_extract_shader_wgsl);
WGPUBindGroupLayout extract_bgl = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Extract - Bind group layout"),
.entryCount = 2,
.entries = (WGPUBindGroupLayoutEntry[]){
{
.binding = 0,
.visibility = WGPUShaderStage_Fragment,
.sampler = {.type = WGPUSamplerBindingType_Filtering},
},
{
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
},
});
ASSERT(extract_bgl);
WGPUPipelineLayout extract_pl = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Extract - Pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &extract_bgl,
});
ASSERT(extract_pl);
WGPURenderPipeline extract_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Face extract - Render pipeline"),
.layout = extract_pl,
.vertex = (WGPUVertexState){
.module = extract_shader,
.entryPoint = STRVIEW("vs_extract"),
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
},
.fragment = &(WGPUFragmentState){
.module = extract_shader,
.entryPoint = STRVIEW("fs_extract"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = WGPUTextureFormat_RGBA8Unorm,
.writeMask = WGPUColorWriteMask_All,
},
},
.multisample = (WGPUMultisampleState){.count = 1, .mask = 0xFFFFFFFF},
});
ASSERT(extract_pipeline);
/* A simple linear sampler for the extraction blit */
WGPUSampler extract_sampler = wgpuDeviceCreateSampler(
wgpu_context->device, &(WGPUSamplerDescriptor){
.label = STRVIEW("Cross extract - Sampler"),
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.magFilter = WGPUFilterMode_Linear,
.minFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Nearest,
.maxAnisotropy = 1,
});
ASSERT(extract_sampler);
/* ---------------------------------------------------------------------- *
* 4. For each layer: upload cross → extract 6 faces
* ---------------------------------------------------------------------- */
/* Keep src textures alive until after the submit (destroyed below) */
WGPUTexture src_textures[NUM_ARRAY_LAYERS] = {NULL};
WGPUCommandEncoder enc
= wgpuDeviceCreateCommandEncoder(wgpu_context->device, NULL);
for (uint32_t layer = 0; layer < NUM_ARRAY_LAYERS; ++layer) {
const uint32_t lw = (uint32_t)state.cross_width[layer];
const uint32_t lh = (uint32_t)state.cross_height[layer];
/* Upload this layer's cross pixels to a temporary 2D source texture */
WGPUTexture src_tex = wgpuDeviceCreateTexture(
wgpu_context->device,
&(WGPUTextureDescriptor){
.label = STRVIEW("Cross source texture"),
.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst,
.dimension = WGPUTextureDimension_2D,
.size = {lw, lh, 1},
.format = WGPUTextureFormat_RGBA8Unorm,
.mipLevelCount = 1,
.sampleCount = 1,
});
ASSERT(src_tex);
src_textures[layer] = src_tex;
wgpuQueueWriteTexture(
wgpu_context->queue,
&(WGPUTexelCopyTextureInfo){
.texture = src_tex,
.mipLevel = 0,
.origin = {0, 0, 0},
.aspect = WGPUTextureAspect_All,
},
state.cross_pixels[layer], (size_t)(lw * lh * 4u),
&(WGPUTexelCopyBufferLayout){
.offset = 0,
.bytesPerRow = lw * 4u,
.rowsPerImage = lh,
},
&(WGPUExtent3D){.width = lw, .height = lh, .depthOrArrayLayers = 1});
/* Free CPU pixels now that they are on the GPU */
image_free(state.cross_pixels[layer]);
state.cross_pixels[layer] = NULL;
WGPUTextureView src_view = wgpuTextureCreateView(src_tex, NULL);
ASSERT(src_view);
/* Build bind group for this source texture */
WGPUBindGroup extract_bg = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor){
.label = STRVIEW("Extract BG"),
.layout = extract_bgl,
.entryCount = 2,
.entries = (WGPUBindGroupEntry[]){
{.binding = 0, .sampler = extract_sampler},
{.binding = 1, .textureView = src_view},
},
});
ASSERT(extract_bg);
/* Extract 6 faces for this layer */
for (uint32_t face = 0; face < NUM_CUBEMAP_FACES; ++face) {
const uint32_t array_layer = layer * NUM_CUBEMAP_FACES + face;
/* 2D view targeting this face/layer at mip 0 */
WGPUTextureView face_view = wgpuTextureCreateView(
state.cubemap.handle, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Face dst view"),
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = array_layer,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_All,
});
ASSERT(face_view);
WGPURenderPassColorAttachment color_att = {
.view = face_view,
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0, 0, 0, 1},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
};
WGPURenderPassDescriptor rp_desc = {
.label = STRVIEW("Face extract pass"),
.colorAttachmentCount = 1,
.colorAttachments = &color_att,
};
WGPURenderPassEncoder pass
= wgpuCommandEncoderBeginRenderPass(enc, &rp_desc);
wgpuRenderPassEncoderSetPipeline(pass, extract_pipeline);
wgpuRenderPassEncoderSetBindGroup(pass, 0, extract_bg, 0, NULL);
/* instance_index = face (passed via firstInstance) */
wgpuRenderPassEncoderDraw(pass, 3, 1, 0, face);
wgpuRenderPassEncoderEnd(pass);
WGPU_RELEASE_RESOURCE(RenderPassEncoder, pass)
WGPU_RELEASE_RESOURCE(TextureView, face_view)
}
WGPU_RELEASE_RESOURCE(BindGroup, extract_bg)
WGPU_RELEASE_RESOURCE(TextureView, src_view)
/* Do NOT destroy src_tex here — it is still referenced by the recorded
* commands. It will be destroyed after the submit below. */
}
WGPUCommandBuffer cmd = wgpuCommandEncoderFinish(enc, NULL);
WGPU_RELEASE_RESOURCE(CommandEncoder, enc)
wgpuQueueSubmit(wgpu_context->queue, 1, &cmd);
WGPU_RELEASE_RESOURCE(CommandBuffer, cmd)
/* Safe to destroy source textures now that the GPU work is submitted */
for (uint32_t layer = 0; layer < NUM_ARRAY_LAYERS; ++layer) {
if (src_textures[layer]) {
wgpuTextureDestroy(src_textures[layer]);
WGPU_RELEASE_RESOURCE(Texture, src_textures[layer])
}
}
/* ---------------------------------------------------------------------- *
* 5. Generate full mip chain GPU-side
* ---------------------------------------------------------------------- */
wgpu_generate_mipmaps(wgpu_context, state.cubemap.handle,
WGPU_MIPMAP_VIEW_CUBE_ARRAY);
/* ---------------------------------------------------------------------- *
* 6. Create the permanent cube-array texture view and sampler
* ---------------------------------------------------------------------- */
state.cubemap.view = wgpuTextureCreateView(
state.cubemap.handle, &(WGPUTextureViewDescriptor){
.label = STRVIEW("Cubemap array view"),
.format = WGPUTextureFormat_RGBA8Unorm,
.dimension = WGPUTextureViewDimension_CubeArray,
.baseMipLevel = 0,
.mipLevelCount = mip_count,
.baseArrayLayer = 0,
.arrayLayerCount = NUM_TOTAL_LAYERS,
.aspect = WGPUTextureAspect_All,
});
ASSERT(state.cubemap.view);
state.cubemap.sampler = wgpuDeviceCreateSampler(
wgpu_context->device, &(WGPUSamplerDescriptor){
.label = STRVIEW("Cubemap array sampler"),
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.magFilter = WGPUFilterMode_Linear,
.minFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Linear,
.lodMinClamp = 0.0f,
.lodMaxClamp = (float)mip_count,
.compare = WGPUCompareFunction_Undefined,
.maxAnisotropy = 1,
});
ASSERT(state.cubemap.sampler);
/* ---------------------------------------------------------------------- *
* 7. Release shared extraction resources
* ---------------------------------------------------------------------- */
WGPU_RELEASE_RESOURCE(RenderPipeline, extract_pipeline)
WGPU_RELEASE_RESOURCE(PipelineLayout, extract_pl)
WGPU_RELEASE_RESOURCE(BindGroupLayout, extract_bgl)
WGPU_RELEASE_RESOURCE(ShaderModule, extract_shader)
WGPU_RELEASE_RESOURCE(Sampler, extract_sampler)
}
/* -------------------------------------------------------------------------- *
* Asynchronous horizontal-cross cubemap array loading (3 PNG fetches)
* -------------------------------------------------------------------------- */
static void cross_fetch_callback(const sfetch_response_t* response)
{
/* response->user_data holds the layer index (0, 1, or 2) */
const uint32_t layer = *(const uint32_t*)response->user_data;
if (!response->fetched || !response->data.ptr || !response->data.size) {
printf(
"[texture_cubemap_array] Failed to fetch cross image %u, error: %d\n",
layer, response->error_code);
#ifndef __WAJIC__
free((void*)response->buffer.ptr);
#endif
return;
}
int width = 0, height = 0, channels = 0;
state.cross_pixels[layer]
= image_pixels_from_memory(response->data.ptr, (int)response->data.size,
&width, &height, &channels, 4);
#ifndef __WAJIC__
free((void*)response->buffer.ptr);
#endif
if (!state.cross_pixels[layer]) {
printf("[texture_cubemap_array] Failed to decode cross PNG for layer %u\n",
layer);
return;
}
state.cross_width[layer] = width;
state.cross_height[layer] = height;
state.cross_loaded_count++;
printf(
"[texture_cubemap_array] Layer %u cross image decoded: %dx%d (%d ch)\n",
layer, width, height, channels);
}
static void fetch_cubemap_crosses(void)
{
static const char* cross_paths[NUM_ARRAY_LAYERS] = {
"assets/textures/cubemaps/cubemap_array_layer_0.png",
"assets/textures/cubemaps/cubemap_array_layer_1.png",
"assets/textures/cubemaps/cubemap_array_layer_2.png",
};
/* Store layer index in user_data so the callback knows which slot to fill */
static const uint32_t layer_indices[NUM_ARRAY_LAYERS] = {0, 1, 2};
for (uint32_t i = 0; i < NUM_ARRAY_LAYERS; ++i) {
#ifndef __WAJIC__
state.cross_file_buf[i] = (uint8_t*)malloc(CROSS_FILE_BUF_SIZE);
#endif
sfetch_send(&(sfetch_request_t){
.path = cross_paths[i],
.callback = cross_fetch_callback,
#ifndef __WAJIC__
.buffer = {.ptr = state.cross_file_buf[i], .size = CROSS_FILE_BUF_SIZE},
#endif
.user_data = SFETCH_RANGE(layer_indices[i]),
});
}
}
/* -------------------------------------------------------------------------- *
* Model loading
* -------------------------------------------------------------------------- */
static void create_model_gpu_buffers(wgpu_context_t* wgpu_context,
gltf_model_t* mdl, WGPUBuffer* vb_out,
WGPUBuffer* ib_out, const char* label_vb,
const char* label_ib)
{
uint32_t vb_size = mdl->vertex_count * (uint32_t)sizeof(gltf_vertex_t);
uint32_t ib_size = mdl->index_count * (uint32_t)sizeof(uint32_t);
*vb_out = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = {.data = label_vb, .length = strlen(label_vb)},
.usage = WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst,
.size = vb_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, *vb_out, 0, mdl->vertices, vb_size);
*ib_out = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = {.data = label_ib, .length = strlen(label_ib)},
.usage = WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst,
.size = ib_size,
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, *ib_out, 0, mdl->indices, ib_size);
}
/* WAjic-only: async gltf model fetch callback.
* user_data == -1 → skybox (cube.gltf), 0..NUM_OBJECTS-1 → selectable object */
#ifdef __WAJIC__
static void wajic_model_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("[texture_cubemap_array] model fetch failed, error: %d\n",
response->error_code);
return;
}
const int idx = *(const int*)response->user_data;
gltf_model_desc_t desc
= {.loading_flags = GltfLoadingFlag_PreTransformVertices};
if (idx < 0) {
state.skybox_model_loaded = gltf_model_load_from_memory(
&state.skybox_model, response->data.ptr, response->data.size, NULL, 1.0f);
if (state.skybox_model_loaded) {
gltf_model_bake_node_transforms(&state.skybox_model,
state.skybox_model.vertices, &desc);
}
}
else {
state.objects_loaded[idx] = gltf_model_load_from_memory(
&state.objects[idx], response->data.ptr, response->data.size, NULL, 1.0f);
if (state.objects_loaded[idx]) {
gltf_model_bake_node_transforms(&state.objects[idx],
state.objects[idx].vertices, &desc);
}
}
state.wajic_models_loaded++;
}
#endif /* __WAJIC__ */
static void load_models(wgpu_context_t* wgpu_context)
{
gltf_model_desc_t desc = {
.loading_flags = GltfLoadingFlag_PreTransformVertices,
};
#ifdef __WAJIC__
UNUSED_VAR(wgpu_context);
UNUSED_VAR(desc);
static const char* object_paths[NUM_OBJECTS] = {
"assets/models/sphere.gltf",
"assets/models/teapot.gltf",
"assets/models/torusknot.gltf",
"assets/models/venus.gltf",
};
static const int model_indices[1 + NUM_OBJECTS] = {-1, 0, 1, 2, 3};
sfetch_send(&(sfetch_request_t){
.path = "assets/models/cube.gltf",
.callback = wajic_model_fetch_callback,
.channel = 0,
.user_data = SFETCH_RANGE(model_indices[0]),
});
for (int i = 0; i < NUM_OBJECTS; ++i) {
sfetch_send(&(sfetch_request_t){
.path = object_paths[i],
.callback = wajic_model_fetch_callback,
.channel = 0,
.user_data = SFETCH_RANGE(model_indices[1 + i]),
});
}
#else
/* Skybox cube */
state.skybox_model_loaded = gltf_model_load_from_file_ext(
&state.skybox_model, "assets/models/cube.gltf", 1.0f, &desc);
if (state.skybox_model_loaded) {
create_model_gpu_buffers(
wgpu_context, &state.skybox_model, &state.skybox_buffers.vertex,
&state.skybox_buffers.index, "Skybox VB", "Skybox IB");
}
/* Objects */
static const char* object_paths[NUM_OBJECTS] = {
"assets/models/sphere.gltf",
"assets/models/teapot.gltf",
"assets/models/torusknot.gltf",
"assets/models/venus.gltf",
};
for (int i = 0; i < NUM_OBJECTS; ++i) {
state.objects_loaded[i] = gltf_model_load_from_file_ext(
&state.objects[i], object_paths[i], 1.0f, &desc);
if (state.objects_loaded[i]) {
char lbl_vb[64], lbl_ib[64];
snprintf(lbl_vb, sizeof(lbl_vb), "Object[%d] VB", i);
snprintf(lbl_ib, sizeof(lbl_ib), "Object[%d] IB", i);
create_model_gpu_buffers(wgpu_context, &state.objects[i],
&state.object_buffers[i].vertex,
&state.object_buffers[i].index, lbl_vb, lbl_ib);
}
}
#endif /* !__WAJIC__ */
}
/* -------------------------------------------------------------------------- *
* Uniform buffer
* -------------------------------------------------------------------------- */
static void init_uniform_buffer(wgpu_context_t* wgpu_context)
{
state.uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Uniform buffer"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(uniform_data_t),
.mappedAtCreation = false,
});
ASSERT(state.uniform_buffer);
}
static void update_uniform_buffer(wgpu_context_t* wgpu_context)
{
float aspect = (float)wgpu_context->width / (float)wgpu_context->height;
glm_perspective(glm_rad(60.0f), aspect, 0.1f, 256.0f, state.ubo.projection);
glm_mat4_copy(state.camera.matrices.view, state.ubo.model_view);
glm_mat4_inv(state.ubo.model_view, state.ubo.inverse_model_view);
state.ubo.lod_bias = state.settings.lod_bias;
state.ubo.cube_map_index = state.settings.cube_map_index;
wgpuQueueWriteBuffer(wgpu_context->queue, state.uniform_buffer, 0, &state.ubo,
sizeof(state.ubo));
}
/* -------------------------------------------------------------------------- *
* Bind group layout and bind group
* -------------------------------------------------------------------------- */
static void init_bind_group_layout(wgpu_context_t* wgpu_context)
{
WGPUBindGroupLayoutEntry entries[3] = {
[0] = {
/* Binding 0: UBO (visible to both vertex and fragment) */
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
.minBindingSize = sizeof(uniform_data_t),
},
},
[1] = {
/* Binding 1: Sampler */
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = {.type = WGPUSamplerBindingType_Filtering},
},
[2] = {
/* Binding 2: Cubemap array texture */
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_CubeArray,
.multisampled = false,
},
},
};
state.bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("Cubemap array BGL"),
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.bind_group_layout);
}
static void create_bind_group(wgpu_context_t* wgpu_context)
{
if (state.bind_group) {
WGPU_RELEASE_RESOURCE(BindGroup, state.bind_group)
state.bind_group = NULL;
}
WGPUBindGroupEntry entries[3] = {
[0] = {
.binding = 0,
.buffer = state.uniform_buffer,
.offset = 0,
.size = sizeof(uniform_data_t),
},
[1] = {
.binding = 1,
.sampler = state.cubemap.sampler,
},
[2] = {
.binding = 2,
.textureView = state.cubemap.view,
},
};
state.bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device, &(WGPUBindGroupDescriptor){
.label = STRVIEW("Cubemap array BG"),
.layout = state.bind_group_layout,
.entryCount = ARRAY_SIZE(entries),
.entries = entries,
});
ASSERT(state.bind_group);
state.bind_group_dirty = false;
}
/* -------------------------------------------------------------------------- *
* Render pipelines
* -------------------------------------------------------------------------- */
static void init_pipelines(wgpu_context_t* wgpu_context)
{
state.pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("Cubemap array pipeline layout"),
.bindGroupLayoutCount = 1,
.bindGroupLayouts = &state.bind_group_layout,
});
ASSERT(state.pipeline_layout);
WGPUShaderModule shader = wgpu_create_shader_module(
wgpu_context->device, texture_cubemap_array_shader_wgsl);
/* Vertex attributes: position (skybox + reflect) and normal (reflect only).
*/
WGPUVertexAttribute attrs[2] = {
[0] = {
.shaderLocation = 0,
.format = WGPUVertexFormat_Float32x3,
.offset = offsetof(gltf_vertex_t, position),
},
[1] = {
.shaderLocation = 1,
.format = WGPUVertexFormat_Float32x3,
.offset = offsetof(gltf_vertex_t, normal),
},
};
WGPUVertexBufferLayout vb_layout = {
.arrayStride = sizeof(gltf_vertex_t),
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = ARRAY_SIZE(attrs),
.attributes = attrs,
};
WGPUColorTargetState color_target = {
.format = wgpu_context->render_format,
.blend = NULL,
.writeMask = WGPUColorWriteMask_All,
};
WGPUDepthStencilState depth_no_write = {
.format = WGPUTextureFormat_Depth24Plus,
.depthWriteEnabled = WGPUOptionalBool_False,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
WGPUDepthStencilState depth_write = {
.format = WGPUTextureFormat_Depth24Plus,
.depthWriteEnabled = WGPUOptionalBool_True,
.depthCompare = WGPUCompareFunction_LessEqual,
.stencilFront = {.compare = WGPUCompareFunction_Always},
.stencilBack = {.compare = WGPUCompareFunction_Always},
};
/* Skybox pipeline: cull front faces, no depth write */
state.skybox_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Skybox pipeline"),
.layout = state.pipeline_layout,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_skybox"),
.bufferCount = 1,
.buffers = &vb_layout,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_Front,
},
.depthStencil = &depth_no_write,
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_skybox"),
.targetCount = 1,
.targets = &color_target,
},
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
});
ASSERT(state.skybox_pipeline);
/* Reflect pipeline: cull back faces, depth write enabled */
state.reflect_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Reflect pipeline"),
.layout = state.pipeline_layout,
.vertex = (WGPUVertexState){
.module = shader,
.entryPoint = STRVIEW("vs_reflect"),
.bufferCount = 1,
.buffers = &vb_layout,
},
.primitive = (WGPUPrimitiveState){
.topology = WGPUPrimitiveTopology_TriangleList,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_Back,
},
.depthStencil = &depth_write,
.fragment = &(WGPUFragmentState){
.module = shader,
.entryPoint = STRVIEW("fs_reflect"),
.targetCount = 1,
.targets = &color_target,
},
.multisample = (WGPUMultisampleState){
.count = 1,
.mask = 0xFFFFFFFF,
},
});
ASSERT(state.reflect_pipeline);
WGPU_RELEASE_RESOURCE(ShaderModule, shader)
}
/* -------------------------------------------------------------------------- *
* Draw model helper
* -------------------------------------------------------------------------- */
static void draw_model(WGPURenderPassEncoder pass, gltf_model_t* mdl,
WGPUBuffer vb, WGPUBuffer ib)
{
wgpuRenderPassEncoderSetVertexBuffer(pass, 0, vb, 0, WGPU_WHOLE_SIZE);
wgpuRenderPassEncoderSetIndexBuffer(pass, ib, WGPUIndexFormat_Uint32, 0,
WGPU_WHOLE_SIZE);
for (uint32_t n = 0; n < mdl->linear_node_count; ++n) {
gltf_node_t* node = mdl->linear_nodes[n];
if (!node->mesh) {
continue;
}
for (uint32_t p = 0; p < node->mesh->primitive_count; ++p) {
gltf_primitive_t* prim = &node->mesh->primitives[p];
if (prim->has_indices && prim->index_count > 0) {
wgpuRenderPassEncoderDrawIndexed(pass, prim->index_count, 1,
prim->first_index, 0, 0);