-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebgpu_recorder.js
1544 lines (1387 loc) · 62.7 KB
/
webgpu_recorder.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
const _postMessage = self.postMessage;
const _dispatchEvent = self.dispatchEvent;
const _document = self.document;
export function webgpu_recorder_download_data(data, filename) {
try {
const link = document.createElement("a");
link.href = URL.createObjectURL(new Blob([data], { type: "text/html" }));
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (e) {
}
}
export class WebGPURecorder {
// public:
constructor(options) {
options = options || {};
this.config = {
maxFrameCount: Math.max((options.frames ?? 100) - 1, 1),
exportName: options.export || "WebGPURecord",
canvasWidth: options.width || 800,
canvasHeight: options.height || 600,
removeUnusedResources: !!options.removeUnusedResources,
messageRecording: !!options.messageRecording,
download: options.download ?? true
};
this._objectIndex = 1;
this._initalized = false;
this._initializeCommandObjects = [];
this._frameCommandObjects = [];
this._currentFrameCommandObjects = null;
this._initializeCommands = [];
this._frameCommands = [];
this._frameObjects = [];
this._initializeObjects = [];
this._currentFrameCommands = null;
this._currentFrameObjects = null;
this.__frameObjects = [];
this.__initializeObjects = [];
this.__currentFrameObjects = null;
this._frameIndex = -1;
this._isRecording = false;
this._frameVariables = {};
this._arrayCache = [];
this._totalData = 0;
this._isRecording = true;
this._initalized = true;
this._frameVariables[-1] = new Set();
this._adapter = null;
this._unusedTextures = new Set();
this._unusedTextureViews = new Map();
this._unusedBuffers = new Set();
this._dataCacheObjects = [];
this._externalImageBufferPromises = [];
// Check if the browser supports WebGPU
if (!navigator.gpu) {
return;
}
this._gpuWrapper = new GPUObjectWrapper(this);
this._gpuWrapper.onPromiseResolve = this._onAsyncResolve.bind(this);
this._gpuWrapper.onPreCall = this._preMethodCall.bind(this);
this._gpuWrapper.onPostCall = this._onMethodCall.bind(this);
this._registerObject(navigator.gpu);
this._recordLine(`${this._getObjectVariable(navigator.gpu)} = navigator.gpu;`, null);
this._wrapCanvases();
const self = this;
// Capture any dynamically created canvases
if (_document) {
const __createElement = document.createElement;
_document.createElement = function (type) {
const element = __createElement.call(_document, type);
if (type === "canvas") {
self._wrapCanvas(element);
}
return element;
};
}
// Wrap requestAnimationFrame so it can keep track of per-frame recording and know when
// the maximum number of frames has been reached.
//
// It would be nice to be able to arbitrarily start/stop recording. To do this,
// we would need to keep track of things like shader creation/deletion that can happen
// at arbitrary frames prior to the start, for any objects used within that recorded
// duration.
const __requestAnimationFrame = requestAnimationFrame;
requestAnimationFrame = function (cb) {
function callback(timestamp) {
self._frameStart(timestamp);
const result = cb(timestamp);
if (result instanceof Promise) {
Promise.all([result]).then(() => {
self._frameEnd(timestamp);
});
} else {
self._frameEnd(timestamp);
}
}
return __requestAnimationFrame(callback);
};
}
getNextId() {
return this._objectIndex++;
}
// private:
_frameStart() {
this._frameIndex++;
this._frameVariables[this._frameIndex] = new Set();
this._currentFrameCommands = [];
this._frameCommands.push(this._currentFrameCommands);
this._currentFrameObjects = [];
this._frameObjects.push(this._currentFrameObjects);
this.__currentFrameObjects = [];
this.__frameObjects.push(this.__currentFrameObjects);
this._currentFrameCommandObjects = [];
this._frameCommandObjects.push(this._currentFrameCommandObjects);
}
_frameEnd() {
if (this._frameIndex === this.config.maxFrameCount) {
this.generateOutput();
}
}
_removeUnusedCommands(objects, commands, unusedObjects, removeValue) {
const l = objects.length;
for (let i = l - 1; i >= 0; --i) {
const object = objects[i];
if (!object) {
continue;
}
if (unusedObjects.has(object.__id)) {
commands[i] = removeValue;
}
}
}
generateOutput() {
const unusedObjects = new Set();
this._isRecording = false;
if (this.config.removeUnusedResources) {
for (const object of this._unusedTextures) {
unusedObjects.add(object);
}
for (const [key, value] of this._unusedTextureViews) {
unusedObjects.add(key);
}
for (const object of this._unusedBuffers) {
unusedObjects.add(object);
}
this._removeUnusedCommands(this._initializeObjects, this._initializeCommands, unusedObjects, "");
this._removeUnusedCommands(this.__initializeObjects, this._initializeCommandObjects, unusedObjects, null);
}
this._initializeCommands = this._initializeCommands.filter((cmd) => !!cmd);
if (this.config.removeUnusedResources) {
for (const obj of unusedObjects) {
for (let di = 0, dl = this._dataCacheObjects.length; di < dl; ++di) {
let dataObj = this._dataCacheObjects[di];
if (dataObj) {
for (let li = dataObj.length - 1; li >= 0; --li) {
if (dataObj[li].__id === obj) {
dataObj.splice(li, 1);
}
}
if (dataObj.length === 0) {
this._arrayCache[di].length = 0;
this._arrayCache[di].type = "Uint8Array";
this._arrayCache[di].array = new Uint8Array(0);
}
}
}
}
}
let s =`
<!DOCTYPE html>
<html>
<body style="text-align: center;">
<canvas id="#webgpu" width=${this.config.canvasWidth} height=${this.config.canvasHeight}></canvas>
<script>
let D = new Array(${this._arrayCache.length});
async function main() {
await loadData();
let canvas = document.getElementById("#webgpu");
let context = canvas.getContext("webgpu");
let frameLabel = document.createElement("div");
frameLabel.style = "position: absolute; top: 10px; left: 10px; font-size: 24pt; color: #f00;";
document.body.append(frameLabel);
${this._getVariableDeclarations(-1)}
${this._initializeCommands.join("\n ")}\n`;
for (let fi = 0, fl = this._frameCommands.length; fi < fl; ++fi) {
if (this.config.removeUnusedResources) {
this._removeUnusedCommands(this._frameObjects[fi], this._frameCommands[fi], unusedObjects, "");
this._removeUnusedCommands(this.__frameObjects[fi], this._frameCommandObjects[fi], unusedObjects, null);
this._frameCommands[fi] = this._frameCommands[fi].filter((cmd) => !!cmd);
}
s += `
async function f${fi}() {
${this._getVariableDeclarations(fi)}
${this._frameCommands[fi].join("\n ")}
}\n`;
}
s += " let frames=[";
for (let fi = 0, fl = this._frameCommands.length; fi < fl; ++fi) {
s += `f${fi},`;
}
s += "];";
s += `
let frame = 0;
let lastFrame = -1;
let t0 = performance.now();
async function renderFrame() {
if (frame > ${this._frameCommands.length - 1}) return;
requestAnimationFrame(renderFrame);
if (frame == lastFrame) return;
lastFrame = frame;
let t1 = performance.now();
frameLabel.innerText = "F: " + (frame + 1) + " T:" + (t1 - t0).toFixed(2);
t0 = t1;
try {
await frames[frame]();
} catch (err) {
console.log("Error Frame:", frame);
console.error(err.message);
}
frame++;
}
requestAnimationFrame(renderFrame);
}
function setCanvasSize(canvas, width, height) {
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
}
async function B64ToA(s, type, length) {
if (Uint8Array.fromBase64) {
const s2 = s.substr(s.indexOf(",") + 1);
const b = Uint8Array.fromBase64(s2);
if (type == "Uint32Array") {
return new Uint32Array(b.buffer);
}
return b;
}
const res = await fetch(s);
const x = new Uint8Array(await res.arrayBuffer());
if (type == "Uint32Array") {
return new Uint32Array(x.buffer, 0, x.length/4);
}
return new Uint8Array(x.buffer, 0, x.length);
}
async function loadData() {\n`;
this._encodedData = [];
const self = this;
Promise.all(this._externalImageBufferPromises).then(() => {
self._externalImageBufferPromises.length = 0;
const promises = [];
for (let ai = 0; ai < self._arrayCache.length; ++ai) {
const a = self._arrayCache[ai];
promises.push(new Promise((resolve) => {
self._encodeDataUrl(a.array).then((b64) => {
self._encodedData[ai] = b64;
s += `D[${ai}] = await B64ToA("${b64}", "${a.type}", ${a.length});\n`;
resolve();
});
}));
}
Promise.all(promises).then(() => {
s += `
}
main();
</script>
</body>
</html>\n`;
self._downloadFile(s, (self.config.exportName || "WebGpuRecord") + ".html");
});
});
}
async _encodeDataUrl(a, type = "application/octet-stream") {
const bytes = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
return await new Promise((resolve, reject) => {
const reader = Object.assign(new FileReader(), {
onload: () => resolve(reader.result),
onerror: () => reject(reader.error),
});
reader.readAsDataURL(new File([bytes], "", { type }));
});
}
_dispatchEvent(message) {
message.__webgpuRecorder = true;
message.__webgpuRecorderPage = true;
message.__webgpuRecorderWorker = !_document;
if (_document) {
_dispatchEvent(new CustomEvent("__WebGPURecorder", { detail: message }));
} else {
_postMessage(message);
}
}
_downloadFile(data, filename) {
if (this.config.download) {
if (_document) {
webgpu_recorder_download_data(data, filename);
} else {
_postMessage({ type: "webgpu_record_download", data, filename });
}
}
if (this.config.messageRecording) {
this._initializeCommandObjects = this._initializeCommandObjects.filter((value) => !!value);
let count = this._initializeCommandObjects.length;
for (let i = 0; i < this._frameCommandObjects.length; ++i) {
this._frameCommandObjects[i] = this._frameCommandObjects[i].filter((value) => !!value);
count += this._frameCommandObjects[i].length;
}
this._dispatchEvent({ action: "webgpu_record_data_count", count: this._arrayCache.length });
let index = 0;
let frame = -1;
const action = "webgpu_record_command";
for (let i = 0; i < this._initializeCommandObjects.length; ++i) {
const command = this._initializeCommandObjects[i];
this._dispatchEvent({ action, command, commandIndex: i, frame, index, count });
index++;
}
for (frame = 0; frame < this._frameCommandObjects.length; ++frame) {
const commands = this._frameCommandObjects[frame];
for (let j = 0; j < commands.length; ++j) {
const command = commands[j];
this._dispatchEvent({ action, command, commandIndex: j, frame, index, count });
index++;
}
}
{
const count = this._arrayCache.length;
const action = "webgpu_record_data";
for (let index = 0; index < count; ++index) {
const a = this._arrayCache[index];
const size = a.length;
const type = a.type;
const data = this._encodedData[index];
this._dispatchEvent({ action, data, type, size, index, count });
}
}
}
this._encodedData.length = 0;
}
_wrapCanvas(c) {
if (c.__id) {
return;
}
this._registerObject(c);
let self = this;
let __getContext = c.getContext;
c.getContext = function (a1, a2) {
let ret = __getContext.call(c, a1, a2);
if (a1 === "webgpu") {
if (ret) {
self._wrapContext(ret);
}
}
return ret;
};
}
_wrapCanvases() {
if (_document) {
const canvases = _document.getElementsByTagName("canvas");
for (let i = 0; i < canvases.length; ++i) {
const c = canvases[i];
this._wrapCanvas(c);
}
}
}
_registerObject(object) {
const id = this.getNextId(object);
object.__id = id;
object.__frame = this._frameIndex;
}
_isFrameVariable(frame, name) {
return this._frameVariables[frame] && this._frameVariables[frame].has(name);
}
_removeVariable(name) {
for (const f in this._frameVariables) {
const fs = this._frameVariables[f];
fs.delete(name);
}
}
_addVariable(frame, name) {
this._frameVariables[frame].add(name);
}
_getVariableDeclarations(frame) {
const s = this._frameVariables[frame];
if (!s.size) {
return "";
}
return `let ${[...s].join(",")};`;
}
_getObjectVariable(object) {
if (!object) {
return undefined;
}
if (object instanceof GPUCanvasContext) {
return "context";
}
if (object.__id === undefined) {
this._registerObject(object);
}
const name = `x${object.constructor.name.replace(/^GPU/, "")}${(object.__id || 0)}`;
if (this._frameIndex != object.__frame) {
if (!this._isFrameVariable(-1, name)) {
this._removeVariable(name);
this._addVariable(-1, name);
}
} else {
this._addVariable(this._frameIndex, name);
}
return name;
}
_wrapContext(ctx) {
this._recordLine(`${this._getObjectVariable(ctx)} = canvas.getContext("webgpu");`, null);
}
_onAsyncResolve(object, method, args, id, result) {
if (method === "requestDevice") {
const adapter = object;
if (adapter.__id === undefined) {
this._recordCommand(true, navigator.gpu, "requestAdapter", adapter, []);
}
result.queue.__device = result; // Add a reference to the device on the queue object.
}
this._recordCommand(true, object, method, result, args);
}
_preMethodCall(object, method, args) {
if (!this._isRecording) {
return;
}
// We can"t track every change made to a mappedRange buffer since that all happens
// outside the scope of what WebGPU is in control of. So we keep track of all the
// mapped buffer ranges, and when unmap is called, we record the content of their data
// so that they have their correct data for the unmap.
if (method === "unmap") {
if (object.__mappedRanges) {
for (const buffer of object.__mappedRanges) {
// Make a copy of the mappedRange buffer data as it is when unmap
// is called.
const cacheIndex = this._getDataCache(buffer, 0, buffer.byteLength, buffer);
// Set the mappedRange buffer data in the recording to what is in the buffer
// at the time unmap is called.
this._recordLine(`new Uint8Array(${this._getObjectVariable(buffer)}).set(D[${cacheIndex}]);`, object);
this._recordCommand("", buffer, "__writeData", null, [cacheIndex], true);
}
delete object.__mappedRanges;
}
} else if (method === "getCurrentTexture") {
this._recordLine(`setCanvasSize(${this._getObjectVariable(object)}.canvas, ${object.canvas.width}, ${object.canvas.height})`, null);
this._recordCommand("", object, "__setCanvasSize", null, [object.canvas.width, object.canvas.height], true);
} else if (method === "createTexture") {
args[0].usage |= GPUTextureUsage.COPY_SRC;
}
}
_onMethodCall(object, method, args, result) {
if (!this._isRecording) {
return;
}
if (method === "copyExternalImageToTexture") {
const queue = object;
// copyExternalImageToTexture uses ImageBitmap (or canvas or offscreenCanvas) as
// its source, which we can"t record. Convert copyExternalImageToTexture to
// writeTexture, and record the bytes from the ImageBitmap. To do that, we need
// to inject a `createBuffer`, `copyTextureToBuffer`, `mapAsync` to record the bytes from the texture.
// This means the data in the data cache will be pending the async map resolve. Make a slot for the data
// in the data cache, and fill it in when the map resolves. Keep track of all pending promises
// and resolve them before generating the recording data.
// The reason we can't just draw the ImageBitmap to a canvas and then copy that to a texture is because
// that would only work for RGBA8 textures, and ImageBitmap can be 16-bit or other formats.
const texture = args[1]["texture"];
const format = texture.format;
const formatInfo = WebGPURecorder._formatInfo[format];
const bytesPerPixel = formatInfo ? formatInfo.bytesPerBlock : 4;
const width = args[0].source.width;
const bytesPerRow = (width * bytesPerPixel + 255) & ~0xff;
const rowsPerImage = args[0].source.height;
const size = bytesPerRow * rowsPerImage;
const copySize = args[2];
this._gpuWrapper.skipRecord++;
const device = queue.__device;
const buffer = device.createBuffer({ size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
const commandEncoder = device.createCommandEncoder();
commandEncoder.copyTextureToBuffer({ texture: args[1].texture }, { buffer, bytesPerRow, rowsPerImage }, copySize);
queue.submit([commandEncoder.finish()]);
this._gpuWrapper.skipRecord--;
let cacheIndex = -1;
try {
const bytes = new Uint8Array(size);
cacheIndex = this._getDataCache(bytes, 0, size, texture, false);
this._recordLine(`${this._getObjectVariable(queue)}.writeTexture(${this._stringifyObject(method, args[1])}, D[${cacheIndex}], {bytesPerRow:${bytesPerRow}}, ${this._stringifyObject(method, copySize)});`, object);
this._recordCommand(false, queue, "__writeTexture", null, [args[1], { __data: cacheIndex }, { bytesPerRow }, copySize], true);
} catch (e) {
console.error(e.message);
}
const self = this;
const promise = new Promise((resolve) => {
self._gpuWrapper.skipRecord++;
buffer.mapAsync(GPUMapMode.READ).then(() => {
const range = buffer.getMappedRange();
const bufferData = new Uint8Array(range);
self._replaceDataCache(cacheIndex, bufferData, 0, bufferData.length);
resolve();
});
this._gpuWrapper.skipRecord--;
});
this._externalImageBufferPromises.push(promise);
} else {
this._recordCommand(false, object, method, result, args);
}
if (method === "getMappedRange") {
// Keep track of the mapped ranges for the buffer object. The recording will set their
// data when unmap is called.
if (!object.__mappedRanges) {
object.__mappedRanges = [];
}
object.__mappedRanges.push(result);
} else if (method === "submit") {
// just to give the file some structure
this._recordLine("", null);
}
}
_stringifyObject(method, object, toJson) {
let s = "";
let first = true;
for (const key in object) {
let value = object[key];
if (key.startsWith("_")) {
continue;
}
if (value instanceof Function) {
continue;
}
if (value === undefined) {
continue;
}
if (!first) {
s += ",";
}
first = false;
s += `"${key}":`;
if (method === "requestDevice") {
if (key === "requiredFeatures") {
s += "requiredFeatures";
continue;
} else if (key === "requiredLimits") {
s += "requiredLimits";
continue;
}
}
if (method === "createBindGroup") {
if (key === "resource") {
if (this._unusedTextureViews.has(value.__id)) {
const texture = this._unusedTextureViews.get(value.__id);
this._unusedTextures.delete(texture);
}
}
} else if (method === "beginRenderPass") {
if (key === "colorAttachments") {
for (const desc of value) {
if (desc["view"]) {
const view = desc["view"];
if (this._unusedTextureViews.has(view.__id)) {
const texture = this._unusedTextureViews.get(view.__id);
this._unusedTextures.delete(texture);
this._unusedTextureViews.delete(view.__id);
}
}
}
}
}
if (value === null) {
s += "null";
} else if (typeof (value) === "string") {
if (!toJson && method === "createShaderModule") {
s += `\`${value}\``;
} else {
s += JSON.stringify(value);
}
} else if (value.__id !== undefined) {
if (toJson) {
s += `{ "__id":"${this._getObjectVariable(value)}" }`;
} else {
s += this._getObjectVariable(value);
}
} else if (value.__data !== undefined) {
if (toJson) {
s += `{ "__data": ${value.__data} }`;
} else {
s += `D[${value.__data}]`;
}
} else if (value.constructor === Array) {
s += this._stringifyArray(value, toJson);
} else if (typeof (value) === "object") {
s += this._stringifyObject(method, value, toJson);
} else {
s += `${value}`;
}
}
s = `{${s}}`;
return s;
}
_stringifyArray(a, toJson) {
let s = "[";
s += this._stringifyArgs("", a, toJson);
s += "]";
return s;
}
_heapAccessShiftForWebGPUHeap(heap) {
if (!heap.BYTES_PER_ELEMENT) {
return 0;
}
return 31 - Math.clz32(heap.BYTES_PER_ELEMENT);
}
_replaceDataCache(index, heap, offset, length) {
const byteOffset = (heap.byteOffset ?? 0) + ((offset ?? 0) << this._heapAccessShiftForWebGPUHeap(heap));
const byteLength = length === undefined ? heap.byteLength : (length << this._heapAccessShiftForWebGPUHeap(heap));
this._totalData += byteLength;
const view = new Uint8Array(heap.buffer ?? heap, byteOffset, byteLength);
const arrayCopy = Uint8Array.from(view);
this._arrayCache[index] = {
length: byteLength,
type: heap.constructor === "ArrayBuffer" ? Uint8Array : heap.constructor.name,
array: arrayCopy
};
}
_compareCacheData(a, b) {
if (a.length != b.length) {
return false;
}
for (let i = 0, l = a.length; i < l; ++i) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
_getDataCache(heap, offset, length, object, skipCompare) {
let self = this;
let cacheIndex = -1;
if (!skipCompare) {
const byteOffset = (heap.byteOffset ?? 0) + ((offset ?? 0) << this._heapAccessShiftForWebGPUHeap(heap));
const byteLength = length === undefined ? heap.byteLength : (length << this._heapAccessShiftForWebGPUHeap(heap));
this._totalData += byteLength;
const view = new Uint8Array(heap.buffer ?? heap, byteOffset, byteLength);
for (let ai = 0; ai < self._arrayCache.length; ++ai) {
const c = self._arrayCache[ai];
if (c.length === length) {
if (this._compareCacheData(this._arrayCache[ai].array, view)) {
cacheIndex = ai;
break;
}
}
}
if (cacheIndex === -1) {
cacheIndex = self._arrayCache.length;
const arrayCopy = Uint8Array.from(view);
self._arrayCache.push({
length: byteLength,
type: heap.constructor === "ArrayBuffer" ? Uint8Array : heap.constructor.name,
array: arrayCopy
});
}
} else {
cacheIndex = self._arrayCache.length;
const array = heap;
self._arrayCache.push({
length,
type: heap.constructor === "ArrayBuffer" ? Uint8Array : heap.constructor.name,
array
});
}
if (object) {
if (!this._dataCacheObjects[cacheIndex]) {
this._dataCacheObjects[cacheIndex] = [];
}
this._dataCacheObjects[cacheIndex].push(object);
}
return cacheIndex;
}
_processArgs(method, args) {
args = [...args];
// In order to capture buffer data, we need to know the offset and size of the data,
// which are arguments of specific methods. So we need to special case those methods to
// properly capture the buffer data passed to them.
if (method === "writeBuffer") {
const buffer = args[2];
const offset = args[3];
const size = args[4];
const cacheIndex = this._getDataCache(buffer, offset, size, buffer);
args[2] = { __data: cacheIndex };
args[3] = 0;
} else if (method === "writeTexture") {
const texture = args[0].texture;
const buffer = args[1];
const bytesPerRow = args[2].bytesPerRow;
const width = args[3].width || args[3][0];
const { blockWidth, blockHeight, bytesPerBlock } = WebGPURecorder._formatInfo[texture.format];
const widthInBlocks = width / blockWidth;
const rows = args[2].rowsPerImage || (args[3].height || args[3][1] || 1) / blockHeight;
const layers = args[3].depthOrArrayLayers || args[3][2] || 1;
const totalRows = rows * layers;
const size = totalRows > 0
? bytesPerRow * (totalRows - 1) + widthInBlocks * bytesPerBlock
: 0;
const offset = args[2].offset;
// offset is in bytes but source can be any TypedArray
// getDataCache assumes offset is in TypedArray.BYTES_PER_ELEMENT size
// so view the data as bytes.
const cacheIndex = this._getDataCache(new Uint8Array(buffer.buffer || buffer, buffer.byteOffset, buffer.byteLength), offset, size, texture);
args[1] = { __data: cacheIndex };
args[2] = { offset: 0, bytesPerRow: args[2].bytesPerRow, rowsPerImage: args[2].rowsPerImage };
} else if (method === "setBindGroup") {
if (args.length === 5) {
const buffer = args[2];
const offset = args[3];
const size = args[4];
const offsets = this._getDataCache(buffer, offset, size, buffer);
args[2] = { __data: offsets };
args.length = 3;
} else if (args.length === 3 && args[2]?.length) {
const buffer = args[2];
const offsets = this._getDataCache(buffer, 0, buffer.length, buffer);
args[2] = { __data: offsets };
args.length = 3;
}
} else if (method === "createBindGroup") {
if (args[0]["entries"]) {
const entries = args[0]["entries"];
for (const entry of entries) {
const value = entry["resource"];
if (value && value.__id) {
if (this._unusedTextureViews.has(value.__id)) {
const texture = this._unusedTextureViews.get(value.__id);
this._unusedTextures.delete(texture);
}
} else if (value && value["buffer"]) {
const buffer = value["buffer"];
if (this._unusedBuffers.has(buffer.__id)) {
this._unusedBuffers.delete(buffer.__id);
}
}
}
}
} else if (method === "copyBufferToTexture") {
const buffer = args[0].buffer;
this._unusedBuffers.delete(buffer.__id);
const texture = args[1].texture;
this._unusedTextures.delete(texture.__id);
} else if (method === "copyTextureToBuffer") {
const texture = args[0].texture;
this._unusedTextures.delete(texture.__id);
const buffer = args[1].buffer;
this._unusedBuffers.delete(buffer.__id);
} else if (method === "copyBufferToBuffer") {
this._unusedBuffers.delete(args[0].__id);
this._unusedBuffers.delete(args[2].__id);
} else if (method === "setVertexBuffer") {
const buffer = args[1];
this._unusedBuffers.delete(buffer.__id);
} else if (method === "setIndexBuffer") {
const buffer = args[0];
this._unusedBuffers.delete(buffer.__id);
} else if (method === "beginRenderPass") {
if (args[0]["colorAttachments"]) {
const value = args[0]["colorAttachments"];
for (const desc of value) {
if (desc["view"]) {
const view = desc["view"];
if (this._unusedTextureViews.has(view.__id)) {
const texture = this._unusedTextureViews.get(view.__id);
this._unusedTextures.delete(texture);
this._unusedTextureViews.delete(view.__id);
}
}
}
}
if (args[0]["depthStencilAttachment"]) {
const value = args[0]["depthStencilAttachment"];
if (value["view"]) {
const view = value["view"];
if (this._unusedTextureViews.has(view.__id)) {
const texture = this._unusedTextureViews.get(view.__id);
this._unusedTextures.delete(texture);
this._unusedTextureViews.delete(view.__id);
}
}
}
}
return args;
}
_stringifyArgs(method, args, toJson) {
if (args.length === 0 || (args.length === 1 && args[0] === undefined)) {
return "";
}
args = this._processArgs(method, args);
const argStrings = [];
for (const a of args) {
if (a === undefined) {
if (!toJson) {
argStrings.push("undefined");
}
} else if (a === null) {
argStrings.push("null");
} else if (a.__data !== undefined) {
if (toJson) {
argStrings.push(`{ "__data": ${a.__data} }`); // This is a captured data buffer.
} else {
argStrings.push(`D[${a.__data}]`);
}
} else if (a.__id) {
if (toJson) {
argStrings.push(`{ "__id": "${this._getObjectVariable(a)}" }`);
} else {
argStrings.push(this._getObjectVariable(a));
}
} else if (a.constructor === Array) {
argStrings.push(this._stringifyArray(a, toJson));
} else if (typeof (a) === "object") {
argStrings.push(this._stringifyObject(method, a, toJson));
} else if (typeof (a) === "string") {
if (!toJson && method === "createShaderModule") {
argStrings.push(`\`${a}\``);
} else {
argStrings.push(JSON.stringify(a));
}
} else {
argStrings.push(a);
}
}
return argStrings.join();
}
_recordLine(line, object) {
if (this._isRecording) {
if (this._frameIndex === -1) {
this._initializeCommands.push(line);
this._initializeObjects.push(object);
} else {
this._currentFrameCommands.push(line);
this._currentFrameObjects.push(object);
}
}
}
_recordCommand(async, object, method, result, args, skipLine) {
if (!this._isRecording) {
return;
}
if (result) {
if (typeof (result) === "string") {
return;
}
if (result.__id === undefined) {
this._registerObject(result);
}
}
async = async ? "await " : "";
let obj = object;
const hasAdapter = !!this._adapter;
if (!hasAdapter && method === "requestAdapter") {
this._adapter = result;
} else if (method === "createTexture") {
this._unusedTextures.add(result.__id);
obj = result;
} else if (method === "createView") {
this._unusedTextureViews.set(result.__id, object.__id);
} else if (method === "writeTexture") {
obj = args[0].texture;
} else if (method === "createBuffer") {
this._unusedBuffers.add(result.__id);
obj = result;
} else if (method === "writeBuffer") {
obj = args[0];
}
const newArgs = `[${this._stringifyArgs(method, args, true)}]`;
const commandObj = { "object": this._getObjectVariable(object), method, "result": this._getObjectVariable(result), args: newArgs, async };
if (this._frameIndex === -1) {
this._initializeCommandObjects.push(commandObj);
this.__initializeObjects.push(obj);
} else {
this._currentFrameCommandObjects.push(commandObj);
this.__currentFrameObjects.push(obj);
}
if (skipLine) {
return;
}
// Add a blank line before render and compute passes to make them easier to
// identify in the recording file.
if (method === "beginRenderPass" || method === "beginComputePass") {
this._recordLine("\n", null);
}
if (result) {
this._recordLine(`${this._getObjectVariable(result)} = ${async}${this._getObjectVariable(object)}.${method}(${this._stringifyArgs(method, args)});`, obj);
} else {
this._recordLine(`${async}${this._getObjectVariable(object)}.${method}(${this._stringifyArgs(method, args)});`, obj);
}
// Add a blank line after ending render and compute passes to make them easier
// to identify in the recording file.
if (method === "end") {
this._recordLine("\n", null);
}
if (!hasAdapter && method === "requestAdapter") {