forked from juj/wasm_webgpu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib_webgpu.js
2466 lines (2173 loc) · 123 KB
/
lib_webgpu.js
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
{{{
global.wassert = function(condition) {
if (ASSERTIONS || global.WEBGPU_DEBUG) return `assert(${condition}, "assert(${condition.replace(/"/g, "'")}) failed!");`;
else return '';
};
global.wdebuglog = function(condition) {
return global.WEBGPU_DEBUG ? `console.log(${condition});` : '';
}
global.wdebugwarn = function(condition) {
return global.WEBGPU_DEBUG ? `console.warn(${condition});` : '';
}
global.wdebugerror = function(condition) {
return global.WEBGPU_DEBUG ? `console.error(${condition});` : '';
}
global.wdebugdir = function(condition) {
return global.WEBGPU_DEBUG ? `console.dir(${condition});` : '';
}
global.werror = function(condition) {
return global.WEBGPU_DEBUG ? `console.error(${condition});` : '';
}
// Implement safe heap accesses for 2GB, 4GB and Wasm64 build modes.
// (TODO: lib_webgpu is not yet really Wasm64-capable except for the two functions below)
global.ptrToIdx = function(ptr, accessWidth) {
if (MEMORY64) return `${ptr} >>= ${accessWidth}n`;
if (MAXIMUM_MEMORY > 2*1024*1024*1024) return `${ptr} >>>= ${accessWidth}`;
return `${ptr} >>= ${accessWidth}`;
}
global.shiftPtr = function(ptr, accessWidth) {
if (MEMORY64) return `${ptr} >> ${accessWidth}n`;
if (MAXIMUM_MEMORY > 2*1024*1024*1024) return `${ptr} >>> ${accessWidth}`;
return `${ptr} >> ${accessWidth}`;
}
null;
}}}
mergeInto(LibraryManager.library, {
$debugDir: function(x, desc) {
#if global.WEBGPU_DEBUG
if (desc) console.log(`${desc}:`);
console.dir(x);
#endif
return x;
},
// Stores a ID->WebGPU object mapping registry of global top-level WebGPU objects.
$wgpu: {},
// Free ID counter generation number
// 0: reserved for invalid object, 1: reserved for special GPUTexture that GPUCanvasContext.getCurrentTexture() returns.
$wgpuIdCounter: 1,
// Stores the given WebGPU object under a new free WebGPU object ID.
// Returns the new ID. Can be called with a null/undefined, in which
// case no object/ID is persisted.
$wgpuStore__deps: ['$wgpu', '$wgpuIdCounter'],
$wgpuStore: function(object) {
if (object) {
// WebGPU renderer usage can burn through a lot of object IDs each rendered frame
// (a number of GPUCommandEncoder, GPUTexture, GPUTextureView, GPURenderPassEncoder,
// GPUCommandBuffer objects are created each application frame)
// If we assume an upper bound of 1000 object IDs created per rendered frame, and a
// new mobile device with 120hz display, a signed int32 state space is exhausted in
// 2147483646 / 1000 / 120 / 60 / 60 = 4.97 hours, which is realistic for a page to
// stay open for that long. Therefore handle wraparound of the ID counter generation,
// and find free gaps in the object IDs for new objects.
while(wgpu[++wgpuIdCounter]) if (wgpuIdCounter > 2147483646) wgpuIdCounter = 1;
wgpu[wgpuIdCounter] = object;
// Each persisted objects gets a custom 'wid' field (wasm ID) which stores the ID that
// this object is known by on Wasm side.
object.wid = wgpuIdCounter;
#if global.WEBGPU_DEBUG
debugDir(object, `Stored WebGPU object with ID ${wgpuIdCounter}`);
#endif
return wgpuIdCounter;
}
// Implicit return undefined to marshal ID 0 over to Wasm.
},
// Marks the given 'object' to be a child/derived object of 'parent',
// and stores a reference to the object in the WebGPU table,
// returning the ID.
$wgpuStoreAndSetParent__deps: ['$wgpuStore'],
$wgpuStoreAndSetParent: function(object, parent) {
object = wgpuStore(object);
object && parent.derivedObjects.push(object);
return object;
},
$wgpuReadArrayOfWgpuObjects: function(ptr, numObjects) {
{{{ wassert('numObjects >= 0'); }}}
{{{ wassert('ptr != 0 || numObjects == 0'); }}} // Must be non-null pointer
{{{ wassert('ptr % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('ptr', 2); }}}
let arrayOfObjects = [];
while(numObjects--) {
{{{ wassert('HEAPU32[ptr]'); }}} // Must reference a nonzero WebGPU object handle
{{{ wassert('wgpu[HEAPU32[ptr]]'); }}} // Must reference a valid WebGPU object
arrayOfObjects.push(wgpu[HEAPU32[ptr++]]);
}
return arrayOfObjects;
},
$wgpuReadI53FromU64HeapIdx: function(heap32Idx) {
{{{ wassert('heap32Idx != 0'); }}}
#if WASM_BIGINT
{{{ wassert('heap32Idx % 2 == 0'); }}}
// TODO: return Number(HEAPU64[heap32Idx>>1]);
#else
return HEAPU32[heap32Idx] + HEAPU32[heap32Idx+1] * 4294967296;
#endif
},
$wgpuWriteU64HeapIdx: function(heap32Idx, number) {
{{{ wassert('heap32Idx != 0'); }}}
#if WASM_BIGINT
{{{ wassert('heap32Idx % 2 == 0'); }}}
// TODO: HEAPU64[heap32Idx>>1] = number;
#else
HEAPU32[heap32Idx] = number;
HEAPU32[heap32Idx+1] = number / 4294967296;
#endif
},
wgpu_get_num_live_objects__deps: ['$wgpu'],
wgpu_get_num_live_objects: function() {
return Object.keys(wgpu).length;
},
// Calls .destroy() on the given WebGPU object, and releases the reference to it.
wgpu_object_destroy__deps: ['$wgpu'],
wgpu_object_destroy: function(object) {
let o = wgpu[object];
{{{ wassert(`o || !wgpu.hasOwnProperty(object), 'wgpu dictionary should never be storing key-values with null/undefined value in it'`); }}}
if (o) {
// WebGPU objects of type GPUDevice, GPUBuffer, GPUTexture and GPUQuerySet have an explicit .destroy() function. Call that if applicable.
if (o['destroy']) o['destroy']();
// If the given object has derived objects (GPUTexture -> GPUTextureViews), delete those in a hierarchy as well.
if (o.derivedObjects) o.derivedObjects.forEach(_wgpu_object_destroy);
// Finally erase reference to this object.
delete wgpu[object];
}
{{{ wassert(`!wgpu.hasOwnProperty(object), 'object should have gotten deleted'`); }}}
},
wgpu_destroy_all_objects__deps: ['$wgpu'],
wgpu_destroy_all_objects: function() {
wgpu.forEach((o) => { if (o['destroy']) o['destroy'](); });
wgpu = {};
},
wgpu_is_valid_object: function(o) { return !!wgpu[o]; }, // Tests if this ID references anything (not just a GPUObjectBase)
wgpu_is_adapter: function(o) { return wgpu[o] instanceof GPUAdapter; },
wgpu_is_device: function(o) { return wgpu[o] instanceof GPUDevice; },
wgpu_is_buffer: function(o) { return wgpu[o] instanceof GPUBuffer; },
wgpu_is_texture: function(o) { return wgpu[o] instanceof GPUTexture; },
wgpu_is_texture_view: function(o) { return wgpu[o] instanceof GPUTextureView; },
wgpu_is_external_texture: function(o) { return wgpu[o] instanceof GPUExternalTexture; },
wgpu_is_sampler: function(o) { return wgpu[o] instanceof GPUSampler; },
wgpu_is_bind_group_layout: function(o) { return wgpu[o] instanceof GPUBindGroupLayout; },
wgpu_is_bind_group: function(o) { return wgpu[o] instanceof GPUBindGroup; },
wgpu_is_pipeline_layout: function(o) { return wgpu[o] instanceof GPUPipelineLayout; },
wgpu_is_shader_module: function(o) { return wgpu[o] instanceof GPUShaderModule; },
wgpu_is_compute_pipeline: function(o) { return wgpu[o] instanceof GPUComputePipeline; },
wgpu_is_render_pipeline: function(o) { return wgpu[o] instanceof GPURenderPipeline; },
wgpu_is_command_buffer: function(o) { return wgpu[o] instanceof GPUCommandBuffer; },
wgpu_is_command_encoder: function(o) { return wgpu[o] instanceof GPUCommandEncoder; },
wgpu_is_binding_commands_mixin: function(o) { return wgpu[o] instanceof GPUComputePassEncoder || wgpu[o] instanceof GPURenderPassEncoder || wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_render_commands_mixin: function(o) { return wgpu[o] instanceof GPURenderPassEncoder || wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_render_pass_encoder: function(o) { return wgpu[o] instanceof GPURenderPassEncoder; },
wgpu_is_render_bundle: function(o) { return wgpu[o] instanceof GPURenderBundle; },
wgpu_is_render_bundle_encoder: function(o) { return wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_queue: function(o) { return wgpu[o] instanceof GPUQueue; },
wgpu_is_query_set: function(o) { return wgpu[o] instanceof GPUQuerySet; },
wgpu_is_canvas_context: function(o) { return wgpu[o] instanceof GPUCanvasContext; },
wgpu_is_device_lost_info: function(o) { return wgpu[o] instanceof GPUDeviceLostInfo; },
wgpu_is_error: function(o) { return wgpu[o] instanceof GPUError; },
wgpu_object_set_label: function(o, label) {
{{{ wassert('wgpu[o]'); }}}
wgpu[o]['label'] = UTF8ToString(label);
},
wgpu_object_get_label: function(o, dstLabel, dstLabelSize) {
{{{ wassert('wgpu[o]'); }}}
stringToUTF8(wgpu[o]['label'], dstLabel, dstLabelSize);
},
wgpu_canvas_get_webgpu_context__deps: ['$wgpuStore', '$debugDir'],
wgpu_canvas_get_webgpu_context: function(canvasSelector) {
{{{ wdebuglog('`wgpu_canvas_get_webgpu_context(canvasSelector=${UTF8ToString(canvasSelector)})`'); }}}
return wgpuStore(
debugDir(
debugDir(
document.querySelector(UTF8ToString(canvasSelector)),
'canvas'
)
.getContext('webgpu'),
'canvas.getContext("webgpu")'
)
);
},
////////////////////////////////////////////////////////////
// Automatically generated with scripts/compress_strings.js:
$wgpuDecodeStrings__docs: '/** @param {number=} ch */',
$wgpuDecodeStrings: function(s, c, ch) {
ch = ch || 65;
for(c = c.split('|'); c[0];) s = s['replaceAll'](String.fromCharCode(ch++), c.pop());
return [,].concat(s.split(' '));
},
$GPUTextureAndVertexFormats__deps: ['$wgpuDecodeStrings'],
//$GPUTextureAndVertexFormats: [undefined (0), 'r8unorm' (1), 'r8snorm' (2), 'r8uint' (3), 'r8sint' (4), 'r16uint' (5), 'r16sint' (6), 'r16float' (7), 'rg8unorm' (8), 'rg8snorm' (9), 'rg8uint' (10), 'rg8sint' (11), 'r32uint' (12), 'r32sint' (13), 'r32float' (14), 'rg16uint' (15), 'rg16sint' (16), 'rg16float' (17), 'rgba8unorm' (18), 'rgba8unorm-srgb' (19), 'rgba8snorm' (20), 'rgba8uint' (21), 'rgba8sint' (22), 'bgra8unorm' (23), 'bgra8unorm-srgb' (24), 'rgb9e5ufloat' (25), 'rgb10a2unorm' (26), 'rg11b10ufloat' (27), 'rg32uint' (28), 'rg32sint' (29), 'rg32float' (30), 'rgba16uint' (31), 'rgba16sint' (32), 'rgba16float' (33), 'rgba32uint' (34), 'rgba32sint' (35), 'rgba32float' (36), 'stencil8' (37), 'depth16unorm' (38), 'depth24plus' (39), 'depth24plus-stencil8' (40), 'depth32float' (41), 'depth32float-stencil8' (42), 'bc1-rgba-unorm' (43), 'bc1-rgba-unorm-srgb' (44), 'bc2-rgba-unorm' (45), 'bc2-rgba-unorm-srgb' (46), 'bc3-rgba-unorm' (47), 'bc3-rgba-unorm-srgb' (48), 'bc4-r-unorm' (49), 'bc4-r-snorm' (50), 'bc5-rg-unorm' (51), 'bc5-rg-snorm' (52), 'bc6h-rgb-ufloat' (53), 'bc6h-rgb-float' (54), 'bc7-rgba-unorm' (55), 'bc7-rgba-unorm-srgb' (56), 'etc2-rgb8unorm' (57), 'etc2-rgb8unorm-srgb' (58), 'etc2-rgb8a1unorm' (59), 'etc2-rgb8a1unorm-srgb' (60), 'etc2-rgba8unorm' (61), 'etc2-rgba8unorm-srgb' (62), 'eac-r11unorm' (63), 'eac-r11snorm' (64), 'eac-rg11unorm' (65), 'eac-rg11snorm' (66), 'astc-4x4-unorm' (67), 'astc-4x4-unorm-srgb' (68), 'astc-5x4-unorm' (69), 'astc-5x4-unorm-srgb' (70), 'astc-5x5-unorm' (71), 'astc-5x5-unorm-srgb' (72), 'astc-6x5-unorm' (73), 'astc-6x5-unorm-srgb' (74), 'astc-6x6-unorm' (75), 'astc-6x6-unorm-srgb' (76), 'astc-8x5-unorm' (77), 'astc-8x5-unorm-srgb' (78), 'astc-8x6-unorm' (79), 'astc-8x6-unorm-srgb' (80), 'astc-8x8-unorm' (81), 'astc-8x8-unorm-srgb' (82), 'astc-10x5-unorm' (83), 'astc-10x5-unorm-srgb' (84), 'astc-10x6-unorm' (85), 'astc-10x6-unorm-srgb' (86), 'astc-10x8-unorm' (87), 'astc-10x8-unorm-srgb' (88), 'astc-10x10-unorm' (89), 'astc-10x10-unorm-srgb' (90), 'astc-12x10-unorm' (91), 'astc-12x10-unorm-srgb' (92), 'astc-12x12-unorm' (93), 'astc-12x12-unorm-srgb' (94), 'uint8x2' (95), 'uint8x4' (96), 'sint8x2' (97), 'sint8x4' (98), 'unorm8x2' (99), 'unorm8x4' (100), 'snorm8x2' (101), 'snorm8x4' (102), 'uint16x2' (103), 'uint16x4' (104), 'sint16x2' (105), 'sint16x4' (106), 'unorm16x2' (107), 'unorm16x4' (108), 'snorm16x2' (109), 'snorm16x4' (110), 'float16x2' (111), 'float16x4' (112), 'float32' (113), 'float32x2' (114), 'float32x3' (115), 'float32x4' (116), 'uint32' (117), 'uint32x2' (118), 'uint32x3' (119), 'uint32x4' (120), 'sint32' (121), 'sint32x2' (122), 'sint32x3' (123), 'sint32x4' (124)],
$GPUTextureAndVertexFormats: "wgpuDecodeStrings('r8YA8RmA8UA8TAHUAHTAHVO8YO8RmO8UO8TALUALTALVOHUOHTOHV W8Y W8Z W8Rm W8U W8T bgra8Y bgra8ZOb9e5uVOb10a2YO11b10uVOLUOLTOLV WHU WHT WHV WLU WLT WLV GJHYJ24plusJ24plus-GJLVJLV-GQ1-W-YQ1-W-ZQ2-W-YQ2-W-ZQ3-W-YQ3-W-ZQ4-r-YQ4-r-RmQ5-rg-YQ5-rg-RmQ6h-rgb-uVQ6h-rgb-VQ7-W-YQ7-W-ZSYSZSa1YSa1Z etc2-W8Y etc2-W8ZI11YI11RmIg11YIg11RmX4x4-YX4x4-ZX5x4-YX5x4-ZX5x5-YX5x5-ZX6x5-YX6x5-ZX6x6-YX6x6-ZX8x5-YX8x5-ZX8x6-YX8x6-ZX8x8-YX8x8-ZXE5-YXE5-ZXE6-YXE6-ZXE8-YXE8-ZXE10-YXE10-ZX12x10-YX12x10-ZX12x12-YX12x12-Z U8MU8KT8MT8KY8MY8KRm8MRm8KUHMUHKTHMTHKYHMYHKRmHMRmHKVHMVHKVL VLMVLx3 VLKUL ULMULx3 ULKTL TLMTLx3 TLx4', 'unorm-srgb|unorm| astc-|rgba|float|uint|sint| etc2-rgb8|snor| bc|-BC| rg|-AC|x2 |32|x4 | depth| eac-r|16|stencil8|-D-BJ|10x| D|Im|-D-AJ| r')",
wgpu32BitLimitNames__deps: ['$wgpuDecodeStrings'],
//wgpu32BitLimitNames: ['maxTextureDimension1D' (0), 'maxTextureDimension2D' (1), 'maxTextureDimension3D' (2), 'maxTextureArrayLayers' (3), 'maxBindGroups' (4), 'maxBindingsPerBindGroup' (5), 'maxDynamicUniformBuffersPerPipelineLayout' (6), 'maxDynamicStorageBuffersPerPipelineLayout' (7), 'maxSampledTexturesPerShaderStage' (8), 'maxSamplersPerShaderStage' (9), 'maxStorageBuffersPerShaderStage' (10), 'maxStorageTexturesPerShaderStage' (11), 'maxUniformBuffersPerShaderStage' (12), 'minUniformBufferOffsetAlignment' (13), 'minStorageBufferOffsetAlignment' (14), 'maxVertexBuffers' (15), 'maxVertexAttributes' (16), 'maxVertexBufferArrayStride' (17), 'maxInterStageShaderComponents' (18), 'maxInterStageShaderVariables' (19), 'maxColorAttachments' (20), 'maxColorAttachmentBytesPerSample' (21), 'maxComputeWorkgroupStorageSize' (22), 'maxComputeInvocationsPerWorkgroup' (23), 'maxComputeWorkgroupSizeX' (24), 'maxComputeWorkgroupSizeY' (25), 'maxComputeWorkgroupSizeZ' (26)],
wgpu32BitLimitNames: "wgpuDecodeStrings('>1D >2D >3D max6ArrayLayer<BindGroup<BindingsPerBindGroup maxDynamic5m=DynamicS:e=4d6?ax4r?axS:eB7?axS:e6?ax5mB7?in5m;minS:e;maxVertexB7<VertexAttribute<VertexB7ArrayStride max9Component<9Variable<8<8BytesPer4@:eSize maxComputeInvocationsPerWorkgroup@izeX@izeY@izeZ', ' maxComputeWorkgroupS|sPerShaderStage m|maxTextureDimension|BuffersPerPipelineLayout max|s max|BufferOffsetAlignment |torag|InterStageShader|ColorAttachment|uffer|Texture|Unifor|Sample', 52).slice(1)",
wgpu64BitLimitNames__deps: ['$wgpuDecodeStrings'],
//wgpu64BitLimitNames: ['maxUniformBufferBindingSize' (0), 'maxStorageBufferBindingSize' (1), 'maxBufferSize' (2)],
wgpu64BitLimitNames: "wgpuDecodeStrings('maxUniform4Storage4BufferSize', 'BufferBindingSize max', 52).slice(1)",
wgpuFeatures__deps: ['$wgpuDecodeStrings'],
//wgpuFeatures: ['depth-clip-control' (0), 'depth32float-stencil8' (1), 'texture-compression-bc' (2), 'texture-compression-etc2' (3), 'texture-compression-astc' (4), 'timestamp-query' (5), 'indirect-first-instance' (6), 'shader-f16' (7), 'rg11b10ufloat-renderable' (8)],
wgpuFeatures: "wgpuDecodeStrings('A-clip-control A32BCencil8DbcDetc2DaCc timeCamp-query indirect-firC-inCance shader-f16 rg11b10uBrenderable', ' texture-compression-|st|float-|depth').slice(1)",
$GPUBlendFactors__deps: ['$wgpuDecodeStrings'],
//$GPUBlendFactors: [undefined (0), 'zero' (1), 'one' (2), 'src' (3), 'one-minus-src' (4), 'src-alpha' (5), 'one-minus-src-alpha' (6), 'dst' (7), 'one-minus-dst' (8), 'dst-alpha' (9), 'one-minus-dst-alpha' (10), 'src-alpha-saturated' (11), 'constant' (12), 'one-minus-constant' (13)],
$GPUBlendFactors: "wgpuDecodeStrings('zero one BEB BDEBD AEA ADEAD BD-saturated CEC', ' one-minus-|-alpha|constant|src|dst')",
$GPUStencilOperations__deps: ['$wgpuDecodeStrings'],
//$GPUStencilOperations: [undefined (0), 'keep' (1), 'zero' (2), 'replace' (3), 'invert' (4), 'increment-clamp' (5), 'decrement-clamp' (6), 'increment-wrap' (7), 'decrement-wrap' (8)],
$GPUStencilOperations: "wgpuDecodeStrings('keep zero replace invert inCBdeCBinCA deCA', 'crement-|clamp |wrap')",
$GPUCompareFunctions__deps: ['$wgpuDecodeStrings'],
//$GPUCompareFunctions: [undefined (0), 'never' (1), 'less' (2), 'equal' (3), 'less-equal' (4), 'greater' (5), 'not-equal' (6), 'greater-equal' (7), 'always' (8)],
$GPUCompareFunctions: "wgpuDecodeStrings('neverA equalACB notCBCalways', '-equal |greater| less')",
$GPUBlendOperations__deps: ['$wgpuDecodeStrings'],
//$GPUBlendOperations: [undefined (0), 'add' (1), 'subtract' (2), 'reverse-subtract' (3), 'min' (4), 'max' (5)],
$GPUBlendOperations: "wgpuDecodeStrings('add Areverse-Amin max', 'subtract ')",
$GPUIndexFormats__deps: ['$wgpuDecodeStrings'],
//$GPUIndexFormats: [undefined (0), 'uint16' (1), 'uint32' (2)],
$GPUIndexFormats: "wgpuDecodeStrings('A16 A32', 'uint')",
$GPUBufferMapStates__deps: ['$wgpuDecodeStrings'],
//$GPUBufferMapStates: [undefined (0), 'unmapped' (1), 'pending' (2), 'mapped' (3)],
$GPUBufferMapStates: "wgpuDecodeStrings('unA pending A', 'mapped')",
$GPUTextureDimensions: [, '1d', '2d', '3d'],
$GPUTextureViewDimensions__deps: ['$wgpuDecodeStrings'],
//$GPUTextureViewDimensions: [undefined (0), '1d' (1), '2d' (2), '2d-array' (3), 'cube' (4), 'cube-array' (5), '3d' (6)],
$GPUTextureViewDimensions: "wgpuDecodeStrings('1B 2dCA AC3d', '-array |d 2d|cube')",
$GPUAddressModes__deps: ['$wgpuDecodeStrings'],
//$GPUAddressModes: [undefined (0), 'clamp-to-edge' (1), 'repeat' (2), 'mirror-repeat' (3)],
$GPUAddressModes: "wgpuDecodeStrings('clamp-to-edge A mirror-A', 'repeat')",
$GPUTextureAspects__deps: ['$wgpuDecodeStrings'],
//$GPUTextureAspects: [undefined (0), 'all' (1), 'stencil-only' (2), 'depth-only' (3)],
$GPUTextureAspects: "wgpuDecodeStrings('all stencilA depthA', '-only')",
$GPUPipelineStatisticNames: [, 'timestamp'],
$GPUPrimitiveTopologys__deps: ['$wgpuDecodeStrings'],
//$GPUPrimitiveTopologys: [undefined (0), 'point-list' (1), 'line-list' (2), 'line-strip' (3), 'triangle-list' (4), 'triangle-strip' (5)],
$GPUPrimitiveTopologys: "wgpuDecodeStrings('pointDADAB CDCB', '-list |triangle|-strip|line')",
$GPUBufferBindingTypes__deps: ['$wgpuDecodeStrings'],
//$GPUBufferBindingTypes: [undefined (0), 'uniform' (1), 'storage' (2), 'read-only-storage' (3)],
$GPUBufferBindingTypes: "wgpuDecodeStrings('uniform A read-only-A', 'storage')",
$GPUSamplerBindingTypes__deps: ['$wgpuDecodeStrings'],
//$GPUSamplerBindingTypes: [undefined (0), 'filtering' (1), 'non-filtering' (2), 'comparison' (3)],
$GPUSamplerBindingTypes: "wgpuDecodeStrings('Anon-Acomparison', 'filtering ')",
$GPUTextureSampleTypes__deps: ['$wgpuDecodeStrings'],
//$GPUTextureSampleTypes: [undefined (0), 'float' (1), 'unfilterable-float' (2), 'depth' (3), 'sint' (4), 'uint' (5)],
$GPUTextureSampleTypes: "wgpuDecodeStrings('Aunfilterable-Adepth sint uint', 'float ')",
$GPUQueryTypes: [, 'occlusion', 'timestamp'],
$HTMLPredefinedColorSpaces: [, 'srgb', 'display-p3'],
$GPUFilterModes__deps: ['$wgpuDecodeStrings'],
//$GPUFilterModes: [undefined (0), 'nearest' (1), 'linear' (2)],
$GPUFilterModes: "wgpuDecodeStrings('Aest liA', 'near')",
$GPUMipmapFilterModes__deps: ['$wgpuDecodeStrings'],
//$GPUMipmapFilterModes: [undefined (0), 'nearest' (1), 'linear' (2)],
$GPUMipmapFilterModes: "wgpuDecodeStrings('Aest liA', 'near')",
$GPULoadOps: ['load', 'clear'],
$GPUStoreOps: ['store', 'discard'],
$GPUComputePassTimestampLocations: ['beginning', 'end'],
$GPUAutoLayoutMode: '="auto"',
// End of automatically generated with scripts/compress_strings.js
//////////////////////////////////////////////////////////////////
wgpu_canvas_context_configure__deps: ['$GPUTextureAndVertexFormats', '$HTMLPredefinedColorSpaces', '$wgpuReadArrayOfWgpuObjects'],
wgpu_canvas_context_configure: function(canvasContext, config) {
{{{ wdebuglog('`wgpu_canvas_context_configure(canvasContext=${canvasContext}, config=${config})`'); }}}
{{{ wassert('canvasContext != 0'); }}}
{{{ wassert('wgpu[canvasContext]'); }}}
{{{ wassert('wgpu[canvasContext] instanceof GPUCanvasContext'); }}}
{{{ wassert('config != 0'); }}} // Must be non-null
{{{ wassert('config % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('config', 2); }}}
wgpu[canvasContext]['configure'](
debugDir(
{
'device': wgpu[HEAPU32[config]],
'format': GPUTextureAndVertexFormats[HEAPU32[config+1]],
'usage': HEAPU32[config+2],
'viewFormats': wgpuReadArrayOfWgpuObjects(HEAPU32[config+4], HEAPU32[config+3]),
'colorSpace': HTMLPredefinedColorSpaces[HEAPU32[config+5]],
'alphaMode': [, 'opaque', 'premultiplied'][HEAPU32[config+6]]
},
'canvasContext.configure() with config'
)
);
},
wgpu_canvas_context_get_current_texture__deps: ['wgpu_object_destroy'],
wgpu_canvas_context_get_current_texture: function(canvasContext) {
{{{ wdebuglog('`wgpu_canvas_context_get_current_texture(canvasContext=${canvasContext})`'); }}}
{{{ wassert('canvasContext != 0'); }}}
{{{ wassert('wgpu[canvasContext]'); }}}
{{{ wassert('wgpu[canvasContext] instanceof GPUCanvasContext'); }}}
// The canvas context texture is a special texture that automatically invalidates itself after the current rAF()
// callback if over. Therefore when a new swap chain texture is produced, we need to delete the old one to avoid
// accumulating references to stale textures from each frame.
// Acquire the new canvas context texture..
canvasContext = wgpu[canvasContext]['getCurrentTexture']();
{{{ wassert('canvasContext'); }}}
// The browser implementation for getCurrentTexture() should always return a new texture for each frame, so
// derivedObjects array should not have a chance to pile up (a lot of) derived views. It is observed that
// Chrome at least will temporarily return the same texture when it is not compositing, in which case
// derivedObjects will have ~20-50(?) old derived views simultaneously. These will clear up when Chrome
// actually starts compositing.
{{{ wassert('!canvasContext.derivedObjects || canvasContext.derivedObjects.length < 1000'); }}}
if (canvasContext != wgpu[1]) {
// ... and destroy previous special canvas context texture, if it was an old one.
_wgpu_object_destroy(1);
wgpu[1] = canvasContext;
canvasContext.wid = 1;
canvasContext.derivedObjects = []; // GPUTextureViews are derived off of GPUTextures
}
// The canvas context texture is hardcoded the special ID 1. Return that to caller.
return 1;
},
wgpuReportErrorCodeAndMessage: function(device, callback, errorCode, stringMessage, userData) {
if (stringMessage) {
// n.b. these variables deliberately rely on 'var' scope.
var stackTop = stackSave(),
len = lengthBytesUTF8(stringMessage)+1,
errorMessage = stackAlloc(len);
stringToUTF8(stringMessage, errorMessage, len);
}
{{{ makeDynCall('viiii', 'callback') }}}(device, errorCode, errorMessage, userData);
if (stackTop) stackRestore(stackTop);
},
wgpu_device_set_lost_callback__deps: ['wgpuReportErrorCodeAndMessage'],
wgpu_device_set_lost_callback: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['lost'].then((deviceLostInfo) => {
_wgpuReportErrorCodeAndMessage(device, callback,
deviceLostInfo['reason'] == 'destroyed' ? 1/*WGPU_DEVICE_LOST_REASON_DESTROYED*/ : 0,
deviceLostInfo['message'], userData);
});
},
wgpu_device_push_error_scope: function(device, filter) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['pushErrorScope']([, 'out-of-memory', 'validation', 'internal'][filter]);
},
wgpuDispatchWebGpuErrorEvent__deps: ['wgpuReportErrorCodeAndMessage'],
wgpuDispatchWebGpuErrorEvent: function(device, callback, error, userData) {
// Awkward WebGPU spec: errors do not contain a data-driven error code that
// could be used to identify the error type in a general forward compatible
// fashion, but must do an 'instanceof' check to look at the types of the
// errors. If new error types are introduced in the future, their types won't
// be recognized! (and code size creeps by having to do an 'instanceof' on every
// error type)
_wgpuReportErrorCodeAndMessage(device,
callback,
error
? (error instanceof GPUInternalError ? 3/*WGPU_ERROR_TYPE_INTERNAL*/
: (error instanceof GPUValidationError ? 2/*WGPU_ERROR_TYPE_VALIDATION*/
: (error instanceof GPUOutOfMemoryError ? 1/*WGPU_ERROR_TYPE_OUT_OF_MEMORY*/
: 3/*WGPU_ERROR_TYPE_UNKNOWN_ERROR*/)))
: 0/*WGPU_ERROR_TYPE_NO_ERROR*/,
error && error['message'],
userData);
},
wgpu_device_pop_error_scope_async__deps: ['wgpuDispatchWebGpuErrorEvent'],
wgpu_device_pop_error_scope_async: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
{{{ wassert('callback'); }}}
function dispatchErrorCallback(error) {
_wgpuDispatchWebGpuErrorEvent(device, callback, error, userData);
}
wgpu[device]['popErrorScope']().then(dispatchErrorCallback).catch(dispatchErrorCallback);
},
wgpu_device_set_uncapturederror_callback__deps: ['wgpuDispatchWebGpuErrorEvent'],
wgpu_device_set_uncapturederror_callback: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['onuncapturederror'] = callback ? function(uncapturedError) {
{{{ wdebugdir('uncapturedError'); }}}
_wgpuDispatchWebGpuErrorEvent(device, callback, uncapturedError['error'], userData);
} : null;
},
navigator_gpu_request_adapter_async__deps: ['$wgpuStore', '$debugDir'],
navigator_gpu_request_adapter_async__docs: '/** @suppress{checkTypes} */', // This function intentionally calls cb() without args.
navigator_gpu_request_adapter_async: function(options, adapterCallback, userData) {
{{{ wdebuglog('`navigator_gpu_request_adapter_async: options: ${options}, adapterCallback: ${adapterCallback}, userData: ${userData}`'); }}}
{{{ wassert('adapterCallback, "must pass a callback function to navigator_gpu_request_adapter_async!"'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('options != 0'); }}}
{{{ wassert('options % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('options', 2); }}}
let gpu = navigator['gpu'],
powerPreference = [, 'low-power', 'high-performance'][HEAPU32[options]],
opts = {};
if (gpu) {
if (options) {
opts['forceFallbackAdapter'] = !!HEAPU32[options+1];
if (powerPreference) opts['powerPreference'] = powerPreference;
}
{{{ wdebuglog('`navigator.gpu.requestAdapter(options=${JSON.stringify(opts)})`'); }}}
function cb(adapter) {
{{{ wdebuglog('`navigator.gpu.requestAdapter resolved with following adapter:`'); }}}
{{{ wdebugdir('adapter'); }}}
{{{ makeDynCall('vii', 'adapterCallback') }}}(wgpuStore(adapter), userData);
}
gpu['requestAdapter'](opts).then(cb).catch(
#if ASSERTIONS || WEBGPU_DEBUG
(e)=>{console.error(`navigator.gpu.requestAdapter() Promise failed: ${e}`); cb(/*intentionally omit arg to pass undefined*/)}
#else
()=>{cb(/*intentionally omit arg to pass undefined*/)}
#endif
);
return 1/*EM_TRUE*/;
}
{{{ werror('`WebGPU is not supported by the current browser!`'); }}}
// Implicit return EM_FALSE, WebGPU is not supported.
},
#if ASYNCIFY
$wgpuAsync: function(promise) {
return Asyncify.handleAsync(() => { return promise; });
},
navigator_gpu_request_adapter_sync__deps: ['$wgpuStore', '$debugDir', '$wgpuAsync'],
navigator_gpu_request_adapter_sync: function(options) {
{{{ wdebuglog('`navigator_gpu_request_adapter_sync: options: ${options}`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('options != 0'); }}}
{{{ wassert('options % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('options', 2); }}}
let gpu = navigator['gpu'],
powerPreference = [, 'low-power', 'high-performance'][HEAPU32[options]],
opts = {};
if (gpu) {
if (options) {
opts['forceFallbackAdapter'] = !!HEAPU32[options+1];
if (powerPreference) opts['powerPreference'] = powerPreference;
}
{{{ wdebuglog('`navigator.gpu.requestAdapter(options=${JSON.stringify(opts)})`'); }}}
return wgpuAsync(gpu['requestAdapter'](opts).then(wgpuStore));
}
{{{ werror('`WebGPU is not supported by the current browser!`'); }}}
// Implicit return EM_FALSE, WebGPU is not supported.
},
#endif
// A "_simple" variant of navigator_gpu_request_adapter_async() that does
// not take in any descriptor params, for building tiny code with default
// args and creating readable test cases etc.
navigator_gpu_request_adapter_async_simple__deps: ['$wgpuStore'],
navigator_gpu_request_adapter_async_simple: function(adapterCallback) {
{{{ wdebuglog('`navigator_gpu_request_adapter_async_simple(adapterCallback=${adapterCallback})`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
navigator['gpu']['requestAdapter']().then(adapter => {
// N.b. this function deliberately invokes a callback with signature 'vii',
// the second integer parameter is intentionally passed as undefined and coerced to zero to save code bytes.
{{{ makeDynCall('vii', 'adapterCallback') }}}(wgpuStore(adapter));
});
},
#if ASYNCIFY
navigator_gpu_request_adapter_sync_simple__deps: ['$wgpuStore', '$wgpuAsync'],
navigator_gpu_request_adapter_sync_simple: function() {
{{{ wdebuglog('`navigator_gpu_request_adapter_sync_simple()`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
return wgpuAsync(navigator['gpu']['requestAdapter']().then(wgpuStore));
},
#endif
navigator_gpu_get_preferred_canvas_format__deps: ['$GPUTextureAndVertexFormats'],
navigator_gpu_get_preferred_canvas_format: function() {
{{{ wdebuglog('`navigator_gpu_get_preferred_canvas_format()`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('GPUTextureAndVertexFormats.includes(navigator["gpu"]["getPreferredCanvasFormat"]())'); }}}
return GPUTextureAndVertexFormats.indexOf(navigator['gpu']['getPreferredCanvasFormat']());
},
wgpu_adapter_or_device_get_features__deps: ['wgpuFeatures'],
wgpu_adapter_or_device_get_features: function(adapterOrDevice) {
{{{ wdebuglog('`wgpu_adapter_or_device_get_features(adapterOrDevice: ${adapterOrDevice})`'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
let id = 1,
featuresBitMask = 0;
for(let feature of _wgpuFeatures) {
if (wgpu[adapterOrDevice]['features'].has(feature)) featuresBitMask |= id;
id *= 2;
}
return featuresBitMask;
},
wgpu_adapter_or_device_supports_feature__deps: ['wgpuFeatures'],
wgpu_adapter_or_device_supports_feature: function(adapterOrDevice, feature) {
{{{ wdebuglog('`wgpu_adapter_or_device_supports_feature(adapterOrDevice: ${adapterOrDevice}, feature: ${feature})`'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
return wgpu[adapterOrDevice]['features'].has(_wgpuFeatures[32 - Match.clz32(feature)])
},
wgpu_adapter_or_device_get_limits__deps: ['wgpu32BitLimitNames', 'wgpu64BitLimitNames', '$wgpuWriteU64HeapIdx'],
wgpu_adapter_or_device_get_limits: function(adapterOrDevice, limits) {
{{{ wdebuglog('`wgpu_adapter_or_device_get_limits(adapterOrDevice: ${adapterOrDevice}, limits: ${limits})`'); }}}
{{{ wassert('limits != 0, "passed a null limits struct pointer"'); }}}
{{{ wassert('limits % 4 == 0, "passed an unaligned limits struct pointer"'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
let l = wgpu[adapterOrDevice]['limits'];
{{{ ptrToIdx('limits', 2); }}}
for(let limitName of _wgpu64BitLimitNames) {
wgpuWriteU64HeapIdx(limits, l[limitName]);
limits += 2;
}
for(let limitName of _wgpu32BitLimitNames) {
HEAPU32[limits++] = l[limitName];
}
},
wgpu_adapter_is_fallback_adapter: function(adapter) {
{{{ wdebuglog('`wgpu_adapter_is_fallback_adapter(adapter: ${adapter}`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
return wgpu[adapter]['isFallbackAdapter'];
},
wgpu_adapter_request_device_async__deps: ['$wgpuStore', 'wgpuFeatures', 'wgpu32BitLimitNames', 'wgpu64BitLimitNames', '$wgpuReadI53FromU64HeapIdx'],
wgpu_adapter_request_device_async__docs: '/** @suppress{checkTypes} */', // This function intentionally calls cb() without args.
wgpu_adapter_request_device_async: function(adapter, descriptor, deviceCallback, userData) {
{{{ wdebuglog('`wgpu_adapter_request_device_async(adapter: ${adapter}, deviceCallback: ${deviceCallback}, userData: ${userData})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
{{{ wassert('descriptor != 0'); }}}
{{{ wassert('descriptor % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('descriptor', 2); }}}
let requiredFeatures = [], requiredLimits = {}, v = HEAPU32[descriptor], defaultQueueLabel;
descriptor += 2;
{{{ wassert('_wgpuFeatures.length == 9'); }}}
{{{ wassert('_wgpuFeatures.length <= 30'); }}} // We can only do up to 30 distinct feature bits here with the current code.
for(let i = 0; i < 9/*_wgpuFeatures.length*/; ++i) {
if (v & (1 << i)) requiredFeatures.push(_wgpuFeatures[i]);
}
// Marshal all the complex 64-bit quantities first ..
for(let limitName of _wgpu64BitLimitNames) {
if ((v = wgpuReadI53FromU64HeapIdx(descriptor))) requiredLimits[limitName] = v;
descriptor += 2;
}
// .. followed by the 32-bit quantities.
for(let limitName of _wgpu32BitLimitNames) {
if ((v = HEAPU32[descriptor++])) requiredLimits[limitName] = v;
}
function cb(device) {
// If device is non-null, initialization succeeded.
{{{ wdebuglog('`wgpu[adapter].requestDevice resolved with following device:`'); }}}
{{{ wdebugdir('device'); }}}
if (device) {
device.derivedObjects = []; // A large number of objects are derived from GPUDevice (GPUBuffers, GPUTextures, GPUSamplers, ....)
// Register an ID for the queue of this newly created device
wgpuStore(device['queue']);
}
{{{ makeDynCall('vii', 'deviceCallback') }}}(wgpuStore(device), userData);
}
defaultQueueLabel = HEAPU32[descriptor];
wgpu[adapter]['requestDevice'](
debugDir(
{
'requiredFeatures': requiredFeatures,
'requiredLimits': requiredLimits,
'defaultQueue': defaultQueueLabel ? { 'label': UTF8ToString(defaultQueueLabel) } : void 0
},
'GPUAdapter.requestDevice() with desc'
)
).then(cb).catch(
#if ASSERTIONS || WEBGPU_DEBUG
(e)=>{console.error(`GPUAdapter.requestDevice() Promise failed: ${e}`); cb(/*intentionally omit arg to pass undefined*/)}
#else
()=>{cb(/*intentionally omit arg to pass undefined*/)}
#endif
);
},
#if ASYNCIFY
wgpu_adapter_request_device_sync__deps: ['$wgpuStore', 'wgpuFeatures', 'wgpu32BitLimitNames', 'wgpu64BitLimitNames', '$wgpuReadI53FromU64HeapIdx', '$wgpuAsync'],
wgpu_adapter_request_device_sync: function(adapter, descriptor) {
{{{ wdebuglog('`wgpu_adapter_request_device_sync(adapter: ${adapter})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
{{{ wassert('descriptor != 0'); }}}
{{{ wassert('descriptor % 4 == 0'); }}} // Must be aligned at uint32_t boundary
{{{ ptrToIdx('descriptor', 2); }}}
let requiredFeatures = [], requiredLimits = {}, v = HEAPU32[descriptor], defaultQueueLabel;
descriptor += 2;
{{{ wassert('_wgpuFeatures.length == 9'); }}}
{{{ wassert('_wgpuFeatures.length <= 30'); }}} // We can only do up to 30 distinct feature bits here with the current code.
for(let i = 0; i < 9/*_wgpuFeatures.length*/; ++i) {
if (v & (1 << i)) requiredFeatures.push(_wgpuFeatures[i]);
}
// Marshal all the complex 64-bit quantities first ..
for(let limitName of _wgpu64BitLimitNames) {
if ((v = wgpuReadI53FromU64HeapIdx(descriptor))) requiredLimits[limitName] = v;
descriptor += 2;
}
// .. followed by the 32-bit quantities.
for(let limitName of _wgpu32BitLimitNames) {
if ((v = HEAPU32[descriptor++])) requiredLimits[limitName] = v;
}
function cb(device) {
// If device is non-null, initialization succeeded.
{{{ wdebuglog('`wgpu[adapter].requestDevice resolved with following device:`'); }}}
{{{ wdebugdir('device'); }}}
if (device) {
device.derivedObjects = []; // A large number of objects are derived from GPUDevice (GPUBuffers, GPUTextures, GPUSamplers, ....)
// Register an ID for the queue of this newly created device
wgpuStore(device['queue']);
}
return wgpuStore(device);
}
defaultQueueLabel = HEAPU32[descriptor];
return wgpuAsync(wgpu[adapter]['requestDevice'](
debugDir(
{
'requiredFeatures': requiredFeatures,
'requiredLimits': requiredLimits,
'defaultQueue': defaultQueueLabel ? { 'label': UTF8ToString(defaultQueueLabel) } : void 0
},
'GPUAdapter.requestDevice() with desc'
)
).then(cb));
},
#endif
// A "_simple" variant of wgpu_adapter_request_device_async() that does
// not take in any descriptor params, for building tiny code with default
// args and creating readable test cases etc.
wgpu_adapter_request_device_async_simple__deps: ['$wgpuStore'],
wgpu_adapter_request_device_async_simple: function(adapter, deviceCallback) {
{{{ wdebuglog('`wgpu_adapter_request_device_sync_simple(adapter: ${adapter}, deviceCallback=${deviceCallback})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
wgpu[adapter]['requestDevice']().then(device => {
device.derivedObjects = [];
wgpuStore(device['queue']);
{{{ makeDynCall('vii', 'deviceCallback') }}}(wgpuStore(device));
});
},
#if ASYNCIFY
wgpu_adapter_request_device_sync_simple__deps: ['$wgpuStore', '$wgpuAsync'],
wgpu_adapter_request_device_sync_simple: function(adapter) {
{{{ wdebuglog('`wgpu_adapter_request_device_sync_simple(adapter: ${adapter})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
return wgpuAsync(wgpu[adapter]['requestDevice']().then(device => {
device.derivedObjects = [];
wgpuStore(device['queue']);
return wgpuStore(device);
}));
},
#endif
wgpu_adapter_request_adapter_info_async__docs: '/** @suppress{checkTypes} */', // This function intentionally calls cb() without args.
wgpu_adapter_request_adapter_info_async: function(adapter, unmaskHints, callback, userData) {
{{{ wdebuglog('`wgpu_adapter_request_adapter_info_async(adapter: ${adapter}, unmaskHints: ${unmaskHints}, callback: ${callback}, userData: ${userData})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
{{{ wassert('callback != 0'); }}}
{{{ wassert('unmaskHints != 0'); }}}
function cb(adapterInfo) {
{{{ wdebuglog('`GPUAdapter.requestAdapterInfo() resolved with following adapterInfo:`'); }}}
{{{ wdebugdir('adapterInfo'); }}}
let stackTop = stackSave(),
info = stackAlloc(2048);
stringToUTF8(adapterInfo['vendor'], info, 512);
stringToUTF8(adapterInfo['architecture'], info + 512, 512);
stringToUTF8(adapterInfo['device'], info + 1024, 512);
stringToUTF8(adapterInfo['description'], info + 1536, 512);
{{{ makeDynCall('viii', 'callback') }}}(adapter, info, userData);
stackRestore(stackTop);
}
let hints = [];
{{{ ptrToIdx('unmaskHints', 2); }}}
while(HEAPU32[unmaskHints]) {
hints.push(UTF8ToString(HEAPU32[unmaskHints++]));
}
{{{ wdebuglog('`wgpu_adapter_request_adapter_info_async() requesting adapter info with hints [${hints.join(", ")}]`'); }}}
return wgpu[adapter]['requestAdapterInfo'](hints).then(cb).catch(
#if ASSERTIONS || WEBGPU_DEBUG
(e)=>{console.error(`GPUAdapter.requestAdapterInfo() Promise failed: ${e}`); cb(/*intentionally omit arg to pass undefined*/)}
#else
()=>{cb(/*intentionally omit arg to pass undefined*/)}
#endif
);
},
// TODO: Create asyncified wgpu_adapter_request_adapter_info_sync() function.
wgpu_device_get_queue: function(device) {
{{{ wdebuglog('`wgpu_device_get_queue(device=${device})`'); }}}
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
{{{ wassert('wgpu[device].wid == device', "GPUDevice has lost its wid member field!"); }}}
{{{ wassert('wgpu[device]["queue"].wid', "GPUDevice.queue must have been assigned an ID in function wgpu_adapter_request_device!"); }}}
return wgpu[device]['queue'].wid;
},
$wgpuReadShaderModuleCompilationHints__deps: ['$GPUAutoLayoutMode'],
$wgpuReadShaderModuleCompilationHints: function(index) {
let numHints = HEAP32[index],
hints = {},
hintsIndex = {{{ shiftPtr('HEAPU32[index+1]', 2) }}},
hint;
{{{ wassert('numHints >= 0'); }}}
while(numHints--) {
hint = HEAPU32[hintsIndex+1];
// hint == 0 (WGPU_AUTO_LAYOUT_MODE_NO_HINT) means no compilation hints are passed,
// hint == 1 (WGPU_AUTO_LAYOUT_MODE_AUTO) means { layout: 'auto' } hint will be passed.
// hint > 1: A handle to a given GPUPipelineLayout object is specified as a hint for creating the shader.
// See https://github.com/gpuweb/gpuweb/pull/2876#issuecomment-1218341636
{{{ wassert('hint <= 1 || wgpu[hint]'); }}}
{{{ wassert('hint <= 1 || wgpu[hint] instanceof GPUPipelineLayout'); }}}
hints[UTF8ToString(HEAPU32[hintsIndex])] = hint ? { 'layout': hint > 1 ? wgpu[hint] : GPUAutoLayoutMode } : null;
hintsIndex += 2;
}
return hints;
},
$wgpuReadShaderModuleDescriptor__deps: ['$wgpuReadShaderModuleCompilationHints'],
$wgpuReadShaderModuleDescriptor: function(descriptor) {
{{{ wassert('descriptor != 0'); }}}
{{{ wassert('descriptor % 4 == 0'); }}} // Must be aligned at uint32_t boundary
descriptor = {{{ shiftPtr('descriptor', 2) }}};
return {
'code': UTF8ToString(HEAPU32[descriptor]),
// TODO: add support for 'sourceMap' field
'hints': wgpuReadShaderModuleCompilationHints(descriptor+1)
}
},
wgpu_device_create_shader_module__deps: ['$wgpuStoreAndSetParent', '$wgpuReadShaderModuleDescriptor'],
wgpu_device_create_shader_module: function(device, descriptor) {
{{{ wdebuglog('`wgpu_device_create_shader_module(device=${device}, descriptor=${descriptor})`'); }}}
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
return wgpuStoreAndSetParent(
wgpu[device]['createShaderModule'](
debugDir(wgpuReadShaderModuleDescriptor(descriptor), 'device.createShaderModule() with desc')
),
wgpu[device]
);
},
wgpu_shader_module_get_compilation_info_async: function(shaderModule, callback, userData) {
{{{ wdebuglog('`wgpu_shader_module_get_compilation_info_async(shaderModule=${shaderModule}, callback=${callback}, userData=${userData})`'); }}}
{{{ wassert('shaderModule != 0'); }}}
{{{ wassert('wgpu[shaderModule]'); }}}
{{{ wassert('wgpu[shaderModule] instanceof GPUShaderModule'); }}}
{{{ wassert('callback != 0'); }}}
wgpu[shaderModule]['compilationInfo']().then(info => {
{{{ wdebuglog('`shaderModule.compilationInfo() completed with info:`'); }}}
{{{ wdebugdir('info'); }}}
// To optimize marshalling, call into malloc() just once, and marshal the compilationInfo
// object into one memory block, with the following layout:
// A) 1 * struct WGpuCompilationInfo, followed by
// B) info.messages.length * struct WGpuCompilationMessage, followed by
// C) info.messages.length * null-terminated C strings for the messages.
let msgs = info['messages'],
len = msgs['length'],
structLen = len * 24/*sizeof(WGpuCompilationMessage) */
+ 4/*sizeof(WGpuCompilationInfo)*/,
totalLen = structLen, msg, infoPtr, msgPtr, i;
for(msg of msgs) totalLen += lengthBytesUTF8(msg['message']) + 1;
infoPtr = _malloc(totalLen);
msgPtr = infoPtr + structLen;
i = {{{ shiftPtr('infoPtr', 2) }}};
// Write A) struct WGpuCompilationInfo.
HEAPU32[i++] = len;
for(msg of msgs) {
// Write B) struct WGpuCompilationMessage.
HEAPU32[i++] = msgPtr;
HEAPU32[i++] = ['error', 'warning', 'info'].indexOf(msg['type']);
HEAPU32[i++] = msg['lineNum'];
HEAPU32[i++] = msg['linePos'];
HEAPU32[i++] = msg['offset'];
HEAPU32[i++] = msg['length'];
// Write C) null-terminated C string for the message.
msgPtr += stringToUTF8(msg['message'], msgPtr, 2**32) + 1;
}
{{{ makeDynCall('viii', 'callback') }}}(shaderModule, infoPtr, userData);
});
},
wgpu_device_create_buffer__deps: ['$wgpuReadI53FromU64HeapIdx', '$wgpuStoreAndSetParent'],
wgpu_device_create_buffer: function(device, descriptor) {
{{{ wdebuglog('`wgpu_device_create_buffer(device=${device}, descriptor=${descriptor})`'); }}}
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
{{{ wassert('descriptor != 0'); }}}
{{{ wassert('descriptor % 4 == 0'); }}} // Must be aligned at uint32_t boundary
device = wgpu[device];
{{{ ptrToIdx('descriptor', 2); }}}
let buffer = device['createBuffer'](
debugDir(
{
'size': wgpuReadI53FromU64HeapIdx(descriptor),
'usage': HEAPU32[descriptor+2],
'mappedAtCreation': !!HEAPU32[descriptor+3]
},
'GPUDevice.createBuffer() with desc'
)
);
// Add tracking space for mapped ranges
buffer.mappedRanges = {};
// Mark this object to be of type GPUBuffer for wgpu_device_create_bind_group().
buffer.isBuffer = 1;
return wgpuStoreAndSetParent(buffer, device);
},
wgpu_buffer_get_mapped_range: function(gpuBuffer, offset, size) {
{{{ wdebuglog('`wgpu_buffer_get_mapped_range(gpuBuffer=${gpuBuffer}, offset=${offset}, size=${size})`'); }}}
{{{ wassert('gpuBuffer != 0'); }}}
{{{ wassert('wgpu[gpuBuffer]'); }}}
{{{ wassert('wgpu[gpuBuffer] instanceof GPUBuffer'); }}}
{{{ wassert('Number.isSafeInteger(offset)'); }}}
{{{ wassert('offset >= 0'); }}}
{{{ wassert('Number.isSafeInteger(size)'); }}}
{{{ wassert('size >= -1'); }}}
{{{ wdebuglog("`gpuBuffer.getMappedRange(offset=${offset}, size=${size}):`"); }}}
gpuBuffer = wgpu[gpuBuffer];
try {
// Awkward polymorphism: cannot pass undefined as size to map whole buffer, but must call the shorter function.
gpuBuffer.mappedRanges[offset] = size < 0 ? gpuBuffer['getMappedRange'](offset) : gpuBuffer['getMappedRange'](offset, size);
} catch(e) {
// E.g. if the GPU ran out of memory when creating a new buffer, this can fail.
{{{ wdebuglog('`gpuBuffer.getMappedRange() failed!`'); }}}
{{{ wdebugdir('e'); }}}
return -1;
}
{{{ wdebuglog('`returned:`'); }}}
{{{ wdebugdir('gpuBuffer.mappedRanges[offset]'); }}}
return offset;
},
wgpu_buffer_read_mapped_range: function(gpuBuffer, startOffset, subOffset, dst, size) {
{{{ wdebuglog('`wgpu_buffer_read_mapped_range(gpuBuffer=${gpuBuffer}, startOffset=${startOffset}, subOffset=${subOffset}, dst=${dst}, size=${size})`'); }}}
{{{ wassert('gpuBuffer != 0'); }}}
{{{ wassert('wgpu[gpuBuffer]'); }}}
{{{ wassert('wgpu[gpuBuffer] instanceof GPUBuffer'); }}}
{{{ wassert('wgpu[gpuBuffer].mappedRanges[startOffset]', "wgpu_buffer_read_mapped_range: No such mapped range with specified startOffset!"); }}}
{{{ wassert('Number.isSafeInteger(startOffset)'); }}}
{{{ wassert('startOffset >= 0'); }}}
{{{ wassert('Number.isSafeInteger(subOffset)'); }}}
{{{ wassert('subOffset >= 0'); }}}
{{{ wassert('Number.isSafeInteger(size)'); }}}
{{{ wassert('size >= 0'); }}}
{{{ wassert('dst || size == 0'); }}}
// N.b. this generates garbage because JavaScript does not allow ArrayBufferView.set(ArrayBuffer, offset, size, dst)
// but must create a dummy view.
HEAPU8.set(new Uint8Array(wgpu[gpuBuffer].mappedRanges[startOffset], subOffset, size), dst);
},
wgpu_buffer_write_mapped_range: function(gpuBuffer, startOffset, subOffset, src, size) {
{{{ wdebuglog('`wgpu_buffer_write_mapped_range(gpuBuffer=${gpuBuffer}, startOffset=${startOffset}, subOffset=${subOffset}, src=${src}, size=${size})`'); }}}
{{{ wassert('gpuBuffer != 0'); }}}
{{{ wassert('wgpu[gpuBuffer]'); }}}
{{{ wassert('wgpu[gpuBuffer] instanceof GPUBuffer'); }}}
{{{ wassert('wgpu[gpuBuffer].mappedRanges[startOffset]', "wgpu_buffer_write_mapped_range: No such mapped range with specified startOffset!"); }}}
{{{ wassert('Number.isSafeInteger(startOffset)'); }}}
{{{ wassert('startOffset >= 0'); }}}
{{{ wassert('Number.isSafeInteger(subOffset)'); }}}
{{{ wassert('subOffset >= 0'); }}}
{{{ wassert('Number.isSafeInteger(size)'); }}}
{{{ wassert('size >= 0'); }}}
{{{ wassert('src || size == 0'); }}}
// Here 'buffer' refers to the global Wasm memory buffer.
// N.b. generates garbage.
new Uint8Array(wgpu[gpuBuffer].mappedRanges[startOffset]).set(new Uint8Array(HEAPU8.buffer, src, size), subOffset);
},
wgpu_buffer_unmap: function(gpuBuffer) {
{{{ wdebuglog('`wgpu_buffer_unmap(gpuBuffer=${gpuBuffer})`'); }}}
{{{ wassert('gpuBuffer != 0'); }}}
{{{ wassert('wgpu[gpuBuffer]'); }}}