-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathtext_rendering_msdf.c
More file actions
1546 lines (1327 loc) · 50.9 KB
/
Copy pathtext_rendering_msdf.c
File metadata and controls
1546 lines (1327 loc) · 50.9 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 "common_shaders.h"
#include "meshes.h"
#include "webgpu/wgpu_common.h"
#include <cJSON.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
#include "core/image_loader.h"
/* -------------------------------------------------------------------------- *
* WebGPU Example - Text Rendering MSDF
*
* This example demonstrates text rendering using Multichannel Signed Distance
* Fields (MSDF). MSDF allows for high-quality, resolution-independent text
* rendering with smooth edges at any scale.
*
* The example renders:
* - A rotating cube with face labels ("Front", "Back", "Left", "Right",
* "Top", "Bottom")
* - A scrolling text crawl displaying information about WebGPU
*
* Ref:
* https://github.com/webgpu/webgpu-samples/tree/main/sample/textRenderingMsdf
* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- *
* WGSL Shaders
* -------------------------------------------------------------------------- */
static const char* msdf_text_shader_wgsl;
/* -------------------------------------------------------------------------- *
* Constants
* -------------------------------------------------------------------------- */
#define MAX_TEXT_CHARS 2048
#define MAX_FORMATTED_TEXTS 16
#define MAX_KERNINGS 512
#define MAX_FONT_CHARS 128
#define FONT_JSON_BUFFER_SIZE (32 * 1024)
#define FONT_TEXTURE_SIZE (512 * 512 * 4)
/* -------------------------------------------------------------------------- *
* MSDF Font Character structure
* -------------------------------------------------------------------------- */
typedef struct msdf_char_t {
int32_t id;
int32_t index;
float width;
float height;
float xoffset;
float yoffset;
float xadvance;
float x;
float y;
int32_t page;
int32_t char_index;
} msdf_char_t;
/* -------------------------------------------------------------------------- *
* MSDF Font Kerning structure
* -------------------------------------------------------------------------- */
typedef struct msdf_kerning_t {
int32_t first;
int32_t second;
int32_t amount;
} msdf_kerning_t;
/* -------------------------------------------------------------------------- *
* MSDF Font structure
* -------------------------------------------------------------------------- */
typedef struct msdf_font_t {
WGPURenderPipeline pipeline;
WGPUBindGroup bind_group;
float line_height;
msdf_char_t chars[MAX_FONT_CHARS];
int32_t char_count;
msdf_kerning_t kernings[MAX_KERNINGS];
int32_t kerning_count;
msdf_char_t default_char;
float scale_w;
float scale_h;
} msdf_font_t;
/* -------------------------------------------------------------------------- *
* MSDF Text Measurements structure
* -------------------------------------------------------------------------- */
typedef struct msdf_text_measurements_t {
float width;
float height;
float line_widths[64];
int32_t line_count;
int32_t printed_char_count;
} msdf_text_measurements_t;
/* -------------------------------------------------------------------------- *
* MSDF Formatted Text structure
* -------------------------------------------------------------------------- */
typedef struct msdf_text_t {
WGPURenderBundle render_bundle;
msdf_text_measurements_t measurements;
WGPUBuffer text_buffer;
float buffer_array[24]; /* 16 for transform + 4 for color + 1 for scale + 3
padding */
bool buffer_dirty;
} msdf_text_t;
/* -------------------------------------------------------------------------- *
* Text formatting options
* -------------------------------------------------------------------------- */
typedef struct msdf_text_format_options_t {
bool centered;
float pixel_scale;
float color[4];
bool has_color;
} msdf_text_format_options_t;
/* -------------------------------------------------------------------------- *
* State struct
* -------------------------------------------------------------------------- */
static struct {
/* WebGPU context pointer for callbacks */
wgpu_context_t* wgpu_context;
/* Cube geometry */
cube_mesh_t cube_mesh;
wgpu_buffer_t cube_vertices;
/* Cube rendering */
WGPURenderPipeline cube_pipeline;
WGPUBuffer cube_uniform_buffer;
WGPUBindGroup cube_bind_group;
/* MSDF text renderer */
struct {
WGPUBindGroupLayout font_bind_group_layout;
WGPUBindGroupLayout text_bind_group_layout;
WGPURenderPipeline pipeline;
WGPUSampler sampler;
WGPUBuffer camera_uniform_buffer;
float camera_array[32]; /* projection + view matrices */
WGPURenderBundleEncoderDescriptor render_bundle_desc;
WGPUTextureFormat color_formats[1];
} text_renderer;
/* Font data */
struct {
msdf_font_t font;
wgpu_texture_t texture;
WGPUBuffer chars_buffer;
bool loaded;
} font;
/* Formatted texts */
msdf_text_t texts[MAX_FORMATTED_TEXTS];
int32_t text_count;
/* Text transforms for cube faces */
mat4 text_transforms[6];
/* Indices into texts array */
int32_t title_text_idx;
int32_t large_text_idx;
/* View matrices */
struct {
mat4 projection;
mat4 view;
mat4 model;
mat4 model_view_projection;
mat4 text_matrix;
} view_matrices;
/* Async loading buffers (native only; WAjic uses dynamic allocation) */
#ifndef __WAJIC__
uint8_t font_json_buffer[FONT_JSON_BUFFER_SIZE];
uint8_t font_texture_buffer[FONT_TEXTURE_SIZE];
#endif
/* Render pass */
WGPURenderPassColorAttachment color_attachment;
WGPURenderPassDepthStencilAttachment depth_stencil_attachment;
WGPURenderPassDescriptor render_pass_descriptor;
/* Timing */
uint64_t start_time;
WGPUBool initialized;
} state = {
.color_attachment = {
.loadOp = WGPULoadOp_Clear,
.storeOp = WGPUStoreOp_Store,
.clearValue = {0.0, 0.0, 0.0, 1.0},
.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED,
},
.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,
},
.title_text_idx = -1,
.large_text_idx = -1,
};
/* -------------------------------------------------------------------------- *
* MSDF Font helper functions
* -------------------------------------------------------------------------- */
static msdf_char_t* font_get_char(msdf_font_t* font, int32_t char_code)
{
for (int32_t i = 0; i < font->char_count; ++i) {
if (font->chars[i].id == char_code) {
return &font->chars[i];
}
}
return &font->default_char;
}
static float font_get_x_advance(msdf_font_t* font, int32_t char_code,
int32_t next_char_code)
{
msdf_char_t* c = font_get_char(font, char_code);
float advance = c->xadvance;
if (next_char_code >= 0) {
for (int32_t i = 0; i < font->kerning_count; ++i) {
if (font->kernings[i].first == char_code
&& font->kernings[i].second == next_char_code) {
advance += (float)font->kernings[i].amount;
break;
}
}
}
return advance;
}
/* -------------------------------------------------------------------------- *
* MSDF Text helper functions
* -------------------------------------------------------------------------- */
static void msdf_text_set_transform(msdf_text_t* text, mat4 matrix)
{
memcpy(text->buffer_array, matrix, sizeof(mat4));
text->buffer_dirty = true;
}
static void msdf_text_set_color(msdf_text_t* text, float r, float g, float b,
float a)
{
text->buffer_array[16] = r;
text->buffer_array[17] = g;
text->buffer_array[18] = b;
text->buffer_array[19] = a;
text->buffer_dirty = true;
}
static void msdf_text_set_pixel_scale(msdf_text_t* text, float pixel_scale)
{
text->buffer_array[20] = pixel_scale;
text->buffer_dirty = true;
}
static WGPURenderBundle
msdf_text_get_render_bundle(wgpu_context_t* wgpu_context, msdf_text_t* text)
{
if (text->buffer_dirty) {
text->buffer_dirty = false;
wgpuQueueWriteBuffer(wgpu_context->queue, text->text_buffer, 0,
text->buffer_array, sizeof(text->buffer_array));
}
return text->render_bundle;
}
/* -------------------------------------------------------------------------- *
* Measure text function
* -------------------------------------------------------------------------- */
typedef void (*char_callback_fn)(float x, float y, int32_t line, msdf_char_t* c,
void* user_data);
static msdf_text_measurements_t measure_text(msdf_font_t* font,
const char* text,
char_callback_fn callback,
void* user_data)
{
msdf_text_measurements_t measurements = {0};
float max_width = 0.0f;
float text_offset_x = 0.0f;
float text_offset_y = 0.0f;
int32_t line = 0;
int32_t printed_char_count = 0;
size_t len = strlen(text);
int32_t next_char_code = (len > 0) ? (int32_t)(unsigned char)text[0] : -1;
for (size_t i = 0; i < len; ++i) {
int32_t char_code = next_char_code;
next_char_code = (i < len - 1) ? (int32_t)(unsigned char)text[i + 1] : -1;
switch (char_code) {
case 10: /* Newline */
if (measurements.line_count < 64) {
measurements.line_widths[measurements.line_count++] = text_offset_x;
}
line++;
if (text_offset_x > max_width) {
max_width = text_offset_x;
}
text_offset_x = 0.0f;
text_offset_y -= font->line_height;
break;
case 13: /* CR */
break;
case 32: /* Space */
text_offset_x += font_get_x_advance(font, char_code, -1);
break;
default: {
msdf_char_t* c = font_get_char(font, char_code);
if (callback) {
callback(text_offset_x, text_offset_y, line, c, user_data);
}
text_offset_x += font_get_x_advance(font, char_code, next_char_code);
printed_char_count++;
break;
}
}
}
if (measurements.line_count < 64) {
measurements.line_widths[measurements.line_count++] = text_offset_x;
}
if (text_offset_x > max_width) {
max_width = text_offset_x;
}
measurements.width = max_width;
measurements.height = (float)measurements.line_count * font->line_height;
measurements.printed_char_count = printed_char_count;
return measurements;
}
/* -------------------------------------------------------------------------- *
* Format text callback data
* -------------------------------------------------------------------------- */
typedef struct format_text_callback_data_t {
float* text_array;
int32_t offset;
msdf_text_measurements_t* measurements;
bool centered;
} format_text_callback_data_t;
static void format_text_callback(float x, float y, int32_t line, msdf_char_t* c,
void* user_data)
{
format_text_callback_data_t* data = (format_text_callback_data_t*)user_data;
float actual_x = x;
float actual_y = y;
if (data->centered && data->measurements) {
float line_offset
= data->measurements->width * -0.5f
- (data->measurements->width - data->measurements->line_widths[line])
* -0.5f;
actual_x = x + line_offset;
actual_y = y + data->measurements->height * 0.5f;
}
data->text_array[data->offset] = actual_x;
data->text_array[data->offset + 1] = actual_y;
data->text_array[data->offset + 2] = (float)c->char_index;
data->text_array[data->offset + 3] = 0.0f; /* padding */
data->offset += 4;
}
/* -------------------------------------------------------------------------- *
* Format text function
* -------------------------------------------------------------------------- */
static int32_t format_text(wgpu_context_t* wgpu_context, msdf_font_t* font,
const char* text,
msdf_text_format_options_t* options)
{
if (state.text_count >= MAX_FORMATTED_TEXTS) {
return -1;
}
size_t text_len = strlen(text);
size_t buffer_size = (text_len + 6) * sizeof(float) * 4;
float* text_array = malloc(buffer_size);
if (!text_array) {
return -1;
}
memset(text_array, 0, buffer_size);
/* Initialize text uniform data (first 24 floats) */
/* Identity transform matrix (16 floats) */
glm_mat4_identity((vec4*)text_array);
/* Color (4 floats) */
if (options && options->has_color) {
text_array[16] = options->color[0];
text_array[17] = options->color[1];
text_array[18] = options->color[2];
text_array[19] = options->color[3];
}
else {
text_array[16] = 1.0f;
text_array[17] = 1.0f;
text_array[18] = 1.0f;
text_array[19] = 1.0f;
}
/* Pixel scale */
float pixel_scale = (options && options->pixel_scale > 0.0f) ?
options->pixel_scale :
(1.0f / 512.0f);
text_array[20] = pixel_scale;
text_array[21] = 0.0f; /* padding */
text_array[22] = 0.0f; /* padding */
text_array[23] = 0.0f; /* padding */
/* Measure and format text */
msdf_text_measurements_t measurements;
format_text_callback_data_t cb_data = {
.text_array = text_array,
.offset = 24,
.measurements = NULL,
.centered = options && options->centered,
};
if (options && options->centered) {
/* First pass: measure */
measurements = measure_text(font, text, NULL, NULL);
cb_data.measurements = &measurements;
/* Second pass: format with centering */
measure_text(font, text, format_text_callback, &cb_data);
}
else {
measurements = measure_text(font, text, format_text_callback, &cb_data);
}
/* Create text buffer */
WGPUBuffer text_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("MSDF text - Storage buffer"),
.usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst,
.size = buffer_size,
.mappedAtCreation = false,
});
/* Write initial data */
wgpuQueueWriteBuffer(wgpu_context->queue, text_buffer, 0, text_array,
buffer_size);
/* Create bind group */
WGPUBindGroup text_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor){
.label = STRVIEW("MSDF text - Bind group"),
.layout = state.text_renderer.text_bind_group_layout,
.entryCount = 2,
.entries = (WGPUBindGroupEntry[]){
{
.binding = 0,
.buffer = state.text_renderer.camera_uniform_buffer,
.offset = 0,
.size = sizeof(state.text_renderer.camera_array),
},
{
.binding = 1,
.buffer = text_buffer,
.offset = 0,
.size = buffer_size,
},
},
});
/* Create render bundle */
WGPURenderBundleEncoder encoder = wgpuDeviceCreateRenderBundleEncoder(
wgpu_context->device,
&(WGPURenderBundleEncoderDescriptor){
.label = STRVIEW("MSDF text - Render bundle encoder"),
.colorFormatCount = 1,
.colorFormats = state.text_renderer.color_formats,
.depthStencilFormat = wgpu_context->depth_stencil_format,
.sampleCount = 1,
});
wgpuRenderBundleEncoderSetPipeline(encoder, state.text_renderer.pipeline);
wgpuRenderBundleEncoderSetBindGroup(encoder, 0, state.font.font.bind_group, 0,
NULL);
wgpuRenderBundleEncoderSetBindGroup(encoder, 1, text_bind_group, 0, NULL);
wgpuRenderBundleEncoderDraw(encoder, 4, measurements.printed_char_count, 0,
0);
WGPURenderBundle render_bundle = wgpuRenderBundleEncoderFinish(encoder, NULL);
wgpuRenderBundleEncoderRelease(encoder);
wgpuBindGroupRelease(text_bind_group);
/* Store in state */
int32_t idx = state.text_count++;
msdf_text_t* msdf_text = &state.texts[idx];
msdf_text->render_bundle = render_bundle;
msdf_text->measurements = measurements;
msdf_text->text_buffer = text_buffer;
msdf_text->buffer_dirty = false;
/* Copy initial values to buffer_array */
memcpy(msdf_text->buffer_array, text_array, sizeof(msdf_text->buffer_array));
free(text_array);
return idx;
}
/* -------------------------------------------------------------------------- *
* Initialize cube mesh
* -------------------------------------------------------------------------- */
static void init_cube_mesh(void)
{
cube_mesh_init(&state.cube_mesh);
}
/* -------------------------------------------------------------------------- *
* Initialize cube vertex buffer
* -------------------------------------------------------------------------- */
static void init_cube_vertex_buffer(wgpu_context_t* wgpu_context)
{
state.cube_vertices = wgpu_create_buffer(
wgpu_context, &(wgpu_buffer_desc_t){
.label = "Cube - Vertices buffer",
.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
.size = sizeof(state.cube_mesh.vertex_array),
.initial.data = state.cube_mesh.vertex_array,
});
}
/* -------------------------------------------------------------------------- *
* Initialize cube pipeline
* -------------------------------------------------------------------------- */
static void init_cube_pipeline(wgpu_context_t* wgpu_context)
{
WGPUShaderModule vert_shader_module
= wgpu_create_shader_module(wgpu_context->device, basic_vertex_shader_wgsl);
WGPUShaderModule frag_shader_module = wgpu_create_shader_module(
wgpu_context->device, vertex_position_color_fragment_shader_wgsl);
/* Depth stencil state */
WGPUDepthStencilState depth_stencil_state
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = wgpu_context->depth_stencil_format,
.depth_write_enabled = true,
});
/* Vertex buffer layout */
WGPU_VERTEX_BUFFER_LAYOUT(cube, state.cube_mesh.vertex_size,
/* Attribute location 0: Position */
WGPU_VERTATTR_DESC(0, WGPUVertexFormat_Float32x4,
state.cube_mesh.position_offset),
/* Attribute location 1: UV */
WGPU_VERTATTR_DESC(1, WGPUVertexFormat_Float32x2,
state.cube_mesh.uv_offset))
state.cube_pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("Cube - Render pipeline"),
.layout = NULL, /* auto layout */
.vertex = {
.module = vert_shader_module,
.entryPoint = STRVIEW("main"),
.bufferCount = 1,
.buffers = &cube_vertex_buffer_layout,
},
.fragment = &(WGPUFragmentState){
.module = frag_shader_module,
.entryPoint = STRVIEW("main"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleList,
.cullMode = WGPUCullMode_Back,
.frontFace = WGPUFrontFace_CCW,
},
.depthStencil = &depth_stencil_state,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
});
wgpuShaderModuleRelease(vert_shader_module);
wgpuShaderModuleRelease(frag_shader_module);
}
/* -------------------------------------------------------------------------- *
* Initialize cube uniform buffer
* -------------------------------------------------------------------------- */
static void init_cube_uniform_buffer(wgpu_context_t* wgpu_context)
{
state.cube_uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("Cube - Uniform buffer"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(mat4),
});
state.cube_bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor){
.label = STRVIEW("Cube - Bind group"),
.layout = wgpuRenderPipelineGetBindGroupLayout(state.cube_pipeline, 0),
.entryCount = 1,
.entries = &(WGPUBindGroupEntry){
.binding = 0,
.buffer = state.cube_uniform_buffer,
.offset = 0,
.size = sizeof(mat4),
},
});
}
/* -------------------------------------------------------------------------- *
* Initialize text renderer
* -------------------------------------------------------------------------- */
static void init_text_renderer(wgpu_context_t* wgpu_context)
{
/* Store color format for render bundles */
state.text_renderer.color_formats[0] = wgpu_context->render_format;
/* Create sampler */
state.text_renderer.sampler = wgpuDeviceCreateSampler(
wgpu_context->device, &(WGPUSamplerDescriptor){
.label = STRVIEW("MSDF text - Sampler"),
.addressModeU = WGPUAddressMode_ClampToEdge,
.addressModeV = WGPUAddressMode_ClampToEdge,
.addressModeW = WGPUAddressMode_ClampToEdge,
.minFilter = WGPUFilterMode_Linear,
.magFilter = WGPUFilterMode_Linear,
.mipmapFilter = WGPUMipmapFilterMode_Linear,
.maxAnisotropy = 16,
});
/* Create camera uniform buffer */
state.text_renderer.camera_uniform_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("MSDF camera - Uniform buffer"),
.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst,
.size = sizeof(state.text_renderer.camera_array),
});
/* Create font bind group layout */
state.text_renderer.font_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("MSDF Font - Bind group layout"),
.entryCount = 3,
.entries = (WGPUBindGroupLayoutEntry[]){
{
.binding = 0,
.visibility = WGPUShaderStage_Fragment,
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
{
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.sampler = {
.type = WGPUSamplerBindingType_Filtering,
},
},
{
.binding = 2,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_ReadOnlyStorage,
.minBindingSize = 0,
},
},
},
});
/* Create text bind group layout */
state.text_renderer.text_bind_group_layout = wgpuDeviceCreateBindGroupLayout(
wgpu_context->device,
&(WGPUBindGroupLayoutDescriptor){
.label = STRVIEW("MSDF text - Bind group layout"),
.entryCount = 2,
.entries = (WGPUBindGroupLayoutEntry[]){
{
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.minBindingSize = sizeof(state.text_renderer.camera_array),
},
},
{
.binding = 1,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_ReadOnlyStorage,
.minBindingSize = 0,
},
},
},
});
/* Create pipeline layout */
WGPUBindGroupLayout bind_group_layouts[2] = {
state.text_renderer.font_bind_group_layout,
state.text_renderer.text_bind_group_layout,
};
WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(
wgpu_context->device, &(WGPUPipelineLayoutDescriptor){
.label = STRVIEW("MSDF text + Pipeline layout"),
.bindGroupLayoutCount = 2,
.bindGroupLayouts = bind_group_layouts,
});
/* Create shader module */
WGPUShaderModule shader_module
= wgpu_create_shader_module(wgpu_context->device, msdf_text_shader_wgsl);
/* Create render pipeline */
WGPUDepthStencilState depth_stencil_state
= wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){
.format = wgpu_context->depth_stencil_format,
.depth_write_enabled = false,
});
state.text_renderer.pipeline = wgpuDeviceCreateRenderPipeline(
wgpu_context->device,
&(WGPURenderPipelineDescriptor){
.label = STRVIEW("MSDF text - Rznder pipeline"),
.layout = pipeline_layout,
.vertex = {
.module = shader_module,
.entryPoint = STRVIEW("vertexMain"),
},
.fragment = &(WGPUFragmentState){
.module = shader_module,
.entryPoint = STRVIEW("fragmentMain"),
.targetCount = 1,
.targets = &(WGPUColorTargetState){
.format = wgpu_context->render_format,
.blend = &(WGPUBlendState){
.color = {
.srcFactor = WGPUBlendFactor_SrcAlpha,
.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha,
.operation = WGPUBlendOperation_Add,
},
.alpha = {
.srcFactor = WGPUBlendFactor_One,
.dstFactor = WGPUBlendFactor_One,
.operation = WGPUBlendOperation_Add,
},
},
.writeMask = WGPUColorWriteMask_All,
},
},
.primitive = {
.topology = WGPUPrimitiveTopology_TriangleStrip,
.stripIndexFormat = WGPUIndexFormat_Uint32,
},
.depthStencil = &depth_stencil_state,
.multisample = {
.count = 1,
.mask = 0xFFFFFFFF,
},
});
wgpuShaderModuleRelease(shader_module);
wgpuPipelineLayoutRelease(pipeline_layout);
}
/* -------------------------------------------------------------------------- *
* Font texture fetch callback
* -------------------------------------------------------------------------- */
static void font_texture_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("Font texture fetch failed, error: %d\n", response->error_code);
return;
}
int img_width, img_height, num_channels;
const int desired_channels = 4;
uint8_t* pixels = image_pixels_from_memory(
response->data.ptr, (int)response->data.size, &img_width, &img_height,
&num_channels, desired_channels);
if (pixels) {
wgpu_texture_t* texture = &state.font.texture;
texture->desc = (wgpu_texture_desc_t){
.extent = (WGPUExtent3D){
.width = img_width,
.height = img_height,
.depthOrArrayLayers = 1,
},
.format = WGPUTextureFormat_RGBA8Unorm,
.pixels = {
.ptr = pixels,
.size = img_width * img_height * 4,
},
};
texture->desc.is_dirty = true;
}
}
/* -------------------------------------------------------------------------- *
* Initialize font bind group (called after texture loads)
* -------------------------------------------------------------------------- */
static void init_font_bind_group(wgpu_context_t* wgpu_context)
{
/* Release old bind group if exists */
WGPU_RELEASE_RESOURCE(BindGroup, state.font.font.bind_group)
state.font.font.bind_group = wgpuDeviceCreateBindGroup(
wgpu_context->device,
&(WGPUBindGroupDescriptor){
.label = STRVIEW("MSDF font - Bind group"),
.layout = state.text_renderer.font_bind_group_layout,
.entryCount = 3,
.entries = (WGPUBindGroupEntry[]){
{
.binding = 0,
.textureView = state.font.texture.view,
},
{
.binding = 1,
.sampler = state.text_renderer.sampler,
},
{
.binding = 2,
.buffer = state.font.chars_buffer,
.offset = 0,
.size = state.font.font.char_count * 8 * sizeof(float),
},
},
});
}
/* -------------------------------------------------------------------------- *
* Font JSON fetch callback
* -------------------------------------------------------------------------- */
static void font_json_fetch_callback(const sfetch_response_t* response)
{
if (!response->fetched) {
printf("Font JSON fetch failed, error: %d\n", response->error_code);
return;
}
wgpu_context_t* wgpu_context = state.wgpu_context;
/* Parse JSON */
cJSON* json = cJSON_ParseWithLength((const char*)response->data.ptr,
response->data.size);
if (!json) {
printf("Failed to parse font JSON\n");
return;
}
/* Parse common info */
cJSON* common = cJSON_GetObjectItem(json, "common");
if (common) {
state.font.font.line_height
= (float)cJSON_GetObjectItem(common, "lineHeight")->valuedouble;
state.font.font.scale_w
= (float)cJSON_GetObjectItem(common, "scaleW")->valuedouble;
state.font.font.scale_h
= (float)cJSON_GetObjectItem(common, "scaleH")->valuedouble;
}
float u = 1.0f / state.font.font.scale_w;
float v = 1.0f / state.font.font.scale_h;
/* Parse characters */
cJSON* chars = cJSON_GetObjectItem(json, "chars");
if (chars) {
int char_count = cJSON_GetArraySize(chars);
state.font.font.char_count
= (char_count > MAX_FONT_CHARS) ? MAX_FONT_CHARS : char_count;
/* Create chars buffer for GPU */
float* chars_array = malloc(state.font.font.char_count * 8 * sizeof(float));
int array_offset = 0;
for (int i = 0; i < state.font.font.char_count; ++i) {
cJSON* c = cJSON_GetArrayItem(chars, i);
msdf_char_t* fc = &state.font.font.chars[i];
fc->id = cJSON_GetObjectItem(c, "id")->valueint;
fc->index = cJSON_GetObjectItem(c, "index")->valueint;
fc->width = (float)cJSON_GetObjectItem(c, "width")->valuedouble;
fc->height = (float)cJSON_GetObjectItem(c, "height")->valuedouble;
fc->xoffset = (float)cJSON_GetObjectItem(c, "xoffset")->valuedouble;
fc->yoffset = (float)cJSON_GetObjectItem(c, "yoffset")->valuedouble;
fc->xadvance = (float)cJSON_GetObjectItem(c, "xadvance")->valuedouble;
fc->x = (float)cJSON_GetObjectItem(c, "x")->valuedouble;
fc->y = (float)cJSON_GetObjectItem(c, "y")->valuedouble;
fc->page = cJSON_GetObjectItem(c, "page")->valueint;
fc->char_index = i;
/* Store char data for GPU */
chars_array[array_offset] = fc->x * u; /* texOffset.x */
chars_array[array_offset + 1] = fc->y * v; /* texOffset.y */
chars_array[array_offset + 2] = fc->width * u; /* texExtent.x */
chars_array[array_offset + 3] = fc->height * v; /* texExtent.y */
chars_array[array_offset + 4] = fc->width; /* size.x */
chars_array[array_offset + 5] = fc->height; /* size.y */
chars_array[array_offset + 6] = fc->xoffset; /* offset.x */
chars_array[array_offset + 7] = -fc->yoffset; /* offset.y */
array_offset += 8;
}
/* Set default char */
if (state.font.font.char_count > 0) {
state.font.font.default_char = state.font.font.chars[0];
}
/* Create GPU buffer for char data */
state.font.chars_buffer = wgpuDeviceCreateBuffer(
wgpu_context->device,
&(WGPUBufferDescriptor){
.label = STRVIEW("MSDF character layout buffer"),
.usage = WGPUBufferUsage_Storage | WGPUBufferUsage_CopyDst,
.size = state.font.font.char_count * 8 * sizeof(float),
.mappedAtCreation = false,
});
wgpuQueueWriteBuffer(wgpu_context->queue, state.font.chars_buffer, 0,
chars_array,
state.font.font.char_count * 8 * sizeof(float));
free(chars_array);
}
/* Parse kernings */
cJSON* kernings = cJSON_GetObjectItem(json, "kernings");