-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebgpufundamentals-timing-original.js
115 lines (102 loc) · 2.79 KB
/
webgpufundamentals-timing-original.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
function assert(cond, msg = "") {
if (!cond) {
throw new Error(msg);
}
}
class TimingHelper {
#canTimestamp;
#device;
#querySet;
#resolveBuffer;
#resultBuffer;
#resultBuffers = [];
// state can be 'free', 'need resolve', 'wait for result'
#state = "free";
constructor(device) {
this.#device = device;
this.#canTimestamp = device.features.has("timestamp-query");
if (this.#canTimestamp) {
this.#querySet = device.createQuerySet({
type: "timestamp",
count: 2,
});
this.#resolveBuffer = device.createBuffer({
size: this.#querySet.count * 8,
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
});
}
}
#beginTimestampPass(encoder, fnName, descriptor) {
if (this.#canTimestamp) {
assert(this.#state === "free", "state not free");
this.#state = "need resolve";
const pass = encoder[fnName]({
...descriptor,
...{
timestampWrites: {
querySet: this.#querySet,
beginningOfPassWriteIndex: 0,
endOfPassWriteIndex: 1,
},
},
});
const resolve = () => this.#resolveTiming(encoder);
pass.end = (function (origFn) {
return function () {
origFn.call(this);
resolve();
};
})(pass.end);
return pass;
} else {
return encoder[fnName](descriptor);
}
}
beginRenderPass(encoder, descriptor = {}) {
return this.#beginTimestampPass(encoder, "beginRenderPass", descriptor);
}
beginComputePass(encoder, descriptor = {}) {
return this.#beginTimestampPass(encoder, "beginComputePass", descriptor);
}
#resolveTiming(encoder) {
if (!this.#canTimestamp) {
return;
}
assert(this.#state === "need resolve", "must call addTimestampToPass");
this.#state = "wait for result";
this.#resultBuffer =
this.#resultBuffers.pop() ||
this.#device.createBuffer({
size: this.#resolveBuffer.size,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
encoder.resolveQuerySet(
this.#querySet,
0,
this.#querySet.count,
this.#resolveBuffer,
0
);
encoder.copyBufferToBuffer(
this.#resolveBuffer,
0,
this.#resultBuffer,
0,
this.#resultBuffer.size
);
}
async getResult() {
if (!this.#canTimestamp) {
return 0;
}
assert(this.#state === "wait for result", "must call resolveTiming");
this.#state = "free";
const resultBuffer = this.#resultBuffer;
await resultBuffer.mapAsync(GPUMapMode.READ);
const times = new BigInt64Array(resultBuffer.getMappedRange());
const duration = Number(times[1] - times[0]);
resultBuffer.unmap();
this.#resultBuffers.push(resultBuffer);
return duration;
}
}