-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtexture.ts
More file actions
395 lines (353 loc) · 12.7 KB
/
Copy pathtexture.ts
File metadata and controls
395 lines (353 loc) · 12.7 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
// import {Glslang} from '@webgpu/glslang/dist/web-devel-onefile/glslang';
import {Glslang} from '@webgpu/glslang/dist/web-devel/glslang.onefile';
import * as utils from './fixture';
import * as tex_util from './tex_util';
export class TextureOp {
device: GPUDevice;
queue: GPUQueue;
glslang: Glslang;
commandQueue: GPUCommandEncoder[];
times: [];
resultMatrixTexture: GPUTexture;
resultMatrixTextureSize: number;
shape: Uint32Array;
computePipeline: any;
bindGroup: any;
format: GPUTextureFormat;
kBytesPerTexel: number;
bufferID: number;
freeBuffers: Map<number, GPUBuffer[]> = new Map();
constructor(device: GPUDevice, glslang: Glslang, format: GPUTextureFormat) {
this.device = device;
this.queue = device.defaultQueue;
this.glslang = glslang;
this.commandQueue = [];
this.format = format;
this.kBytesPerTexel = tex_util.getBytesPerTexel(format);
this.bufferID = 0;
}
// From: Dawn:ComputeTextureCopyBufferSize
// TODO: Make this works with different input size
getBufferSize() {
const blockHeight = 1;
const blockWidth = 1;
const [widthTex, heightTex] =
tex_util.getPackedMatrixTextureShapeWidthHeight(
this.shape[0], this.shape[1], this.format);
const bytesPerRow = tex_util.getBytesPerRow(widthTex, this.kBytesPerTexel);
const sliceSize = bytesPerRow * (heightTex / blockHeight - 1) +
(widthTex / blockWidth) * this.kBytesPerTexel;
return sliceSize;
}
/*
private writeTexture(
data: Float32Array|Uint32Array, width: number, height: number) {
const [widthTex, heightTex] =
tex_util.getPackedMatrixTextureShapeWidthHeight(
width, height, this.format);
const texture = this.device.createTexture({
size: {width: widthTex, height: heightTex, depth: 1},
format: this.format,
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC |
GPUTextureUsage.STORAGE
});
const bytesPerRow = tex_util.getBytesPerRow(widthTex, this.kBytesPerTexel);
console.log(heightTex);
this.queue.writeTexture(
{texture: texture}, data as ArrayBuffer,
{bytesPerRow: bytesPerRow}, // heightTex
{width: widthTex, height: heightTex, depth: 1});
return texture;
}
*/
private writeTextureWithCopy(
matrixData: Float32Array|Uint32Array, width: number, height: number) {
const src = this.device.createBuffer({
mappedAtCreation: true,
size: this.getBufferSize(),
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC |
GPUBufferUsage.COPY_DST
});
// TODO: turn this into type of secondMatrix.
new Float32Array(src.getMappedRange()).set(matrixData);
src.unmap();
const [widthTex, heightTex] =
tex_util.getPackedMatrixTextureShapeWidthHeight(
width, height, this.format);
const texture = this.device.createTexture({
size: {width: widthTex, height: heightTex, depth: 1},
format: this.format,
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC |
GPUTextureUsage.STORAGE
});
const encoder = this.device.createCommandEncoder();
// TODO: fix the width height.
// copyBufferToTexture(source, destination, copySize).
const bytesPerRow = tex_util.getBytesPerRow(widthTex, this.kBytesPerTexel);
// console.log('bytesPerRow=' + bytesPerRow);
encoder.copyBufferToTexture(
{buffer: src, bytesPerRow: bytesPerRow},
{texture: texture, mipLevel: 0, origin: {x: 0, y: 0, z: 0}},
{width: widthTex, height: heightTex, depth: 1});
this.device.defaultQueue.submit([encoder.finish()]);
return texture;
}
compile(
firstMatrix: Float32Array|Uint32Array,
secondMatrix: Float32Array|Uint32Array, shape: Uint32Array,
computeShaderCode: any) {
this.shape = shape;
const gpuTextureFirstMatrix =
this.writeTextureWithCopy(firstMatrix, this.shape[0], this.shape[1]);
/*
const gpuTextureFirstMatrix =
this.writeTexture(firstMatrix, this.shape[2], this.shape[3]);
*/
const gpuTextureSecondMatrix =
this.writeTextureWithCopy(secondMatrix, this.shape[2], this.shape[3]);
/*
const gpuTextureSecondMatrix =
this.writeTexture(secondMatrix, this.shape[2], this.shape[3]);
*/
// Result Matrix.
this.resultMatrixTextureSize =
Float32Array.BYTES_PER_ELEMENT * (shape[4] * shape[5]);
const [widthTex, heightTex] =
tex_util.getPackedMatrixTextureShapeWidthHeight(
this.shape[4], this.shape[5], this.format);
this.resultMatrixTexture = this.device.createTexture({
size: {width: widthTex, height: heightTex, depth: 1},
format: this.format,
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.STORAGE
});
// This works.
/*
const [shapeBuffer, shapeMapping] = this.device.createBufferMapped({
size: shape.byteLength,
usage: GPUBufferUsage.UNIFORM,
});
new Uint32Array(shapeMapping).set(shape);
shapeBuffer.unmap();
*/
// TODO: make this buffer.destroy automatically!
const shapeBuffer = this.device.createBuffer({
mappedAtCreation: true,
size: shape.byteLength,
usage: GPUBufferUsage.UNIFORM
});
// TODO: turn this into type of shape.
new Uint32Array(shapeBuffer.getMappedRange()).set(shape);
shapeBuffer.unmap();
// This works too.
/*
const shapeBuffer = this.uploadToGPUBuffer(
shape, shape.byteLength,
GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_SRC |
GPUBufferUsage.COPY_DST);
*/
return this.createLayout(
gpuTextureFirstMatrix, gpuTextureSecondMatrix, shapeBuffer,
computeShaderCode);
}
private createLayout(
gpuTextureFirstMatrix: GPUTexture, gpuTextureSecondMatrix: GPUTexture,
shapeBuffer: GPUBuffer, computeShaderCode: any) {
// Bind group layout and bind group
// TODO: currently this doesn't support read write storage.
// https://gpuweb.github.io/gpuweb/#enumdef-gpubindingtype
// Use old layout:
// Bind group layout and bind group
// Old layout.
const bindGroupLayout = this.device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
type: 'uniform-buffer'
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
type: 'writeonly-storage-texture',
storageTextureFormat: this.format
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
type: 'readonly-storage-texture',
storageTextureFormat: this.format
},
{
binding: 3,
visibility: GPUShaderStage.COMPUTE,
type: 'readonly-storage-texture',
storageTextureFormat: this.format
}
]
});
this.bindGroup = this.device.createBindGroup({
layout: bindGroupLayout,
entries: [
{binding: 0, resource: {buffer: shapeBuffer}},
{binding: 1, resource: this.resultMatrixTexture.createView()},
{binding: 2, resource: gpuTextureFirstMatrix.createView()},
{binding: 3, resource: gpuTextureSecondMatrix.createView()},
]
});
// Old layout end.
// Pipeline setup
const result =
this.glslang.compileGLSLZeroCopy(computeShaderCode, 'compute', false);
if (result.data.length === 0) {
throw new Error('Shader compilation failed');
}
this.computePipeline = this.device.createComputePipeline({
// For new layout, remove this line.
layout: this.device.createPipelineLayout(
{bindGroupLayouts: [bindGroupLayout]}),
computeStage: {
module: this.device.createShaderModule({code: result.data}),
entryPoint: 'main'
}
});
/* New layout
const bindGroup = this.device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{binding: 0, resource: {buffer: shapeBuffer}},
{binding: 1, resource: this.resultMatrixTexture.createView()},
{binding: 2, resource: gpuTextureFirstMatrix.createView()},
{binding: 3, resource: gpuTextureSecondMatrix.createView()},
]
});
*/
return;
}
compileAndRunSync(
workGroupSize: [number, number, number], workPerThread = 1) {
// TODO: figure out how to return non const two values.
this.dispatchAndSubmit(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize, workPerThread);
return true;
}
private dispatchAndSubmit(
computePipeline: any, bindGroup: any, dispatchX: number,
dispatchY: number, workGroupSize: [number, number, number],
workPerThread = 1) {
// Commands submission.
const commandEncoder = this.device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatch(
dispatchX / workGroupSize[0] / workPerThread,
dispatchY / workGroupSize[1] / workPerThread);
passEncoder.endPass();
// Submit GPU commands.
const gpuCommands = commandEncoder.finish();
this.device.defaultQueue.submit([gpuCommands]);
}
async data() {
const arrayBuffer = await this.getBufferData();
return new Float32Array(arrayBuffer);
}
async getBufferData() {
// Get a GPU buffer for reading in an unmapped state.
const gpuReadBuffer = this.device.createBuffer({
size: this.getBufferSize(), // Float32Array.BYTES_PER_ELEMENT *
// (this.shape[0] * this.shape[1]),
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
});
// console.log('T2B this.getBufferSize()=' + this.getBufferSize());
// Commands submission.
const commandEncoder = this.device.createCommandEncoder();
const [widthTex, heightTex] =
tex_util.getPackedMatrixTextureShapeWidthHeight(
this.shape[0], this.shape[1], this.format);
// console.log('widthTex = ' + widthTex + '; heightTex = ' + heightTex);
const bytesPerRow = tex_util.getBytesPerRow(widthTex, this.kBytesPerTexel);
// Encode commands for copying texture to buffer.
commandEncoder.copyTextureToBuffer(
{
texture: this.resultMatrixTexture,
mipLevel: 0,
origin: {x: 0, y: 0, z: 0}
},
{buffer: gpuReadBuffer, bytesPerRow: bytesPerRow},
{width: widthTex, height: heightTex, depth: 1});
// Submit GPU commands.
this.device.defaultQueue.submit([commandEncoder.finish()]);
// t.expectContents(dst, data);
/*
const fence = this.queue.createFence();
this.queue.signal(fence, 2);
await fence.onCompletion(2);
*/
// Read buffer.
// const mapped = await gpuReadBuffer.mapReadAsync();
/*
const mapped: ArrayBuffer = await staging.mapReadAsync();
const values = mapped.slice(0);
await staging.mapAsync(GPUMapMode.READ);
const values = staging.getMappedRange().slice(0);
*/
await gpuReadBuffer.mapAsync(GPUMapMode.READ);
const arrayBuffer = gpuReadBuffer.getMappedRange().slice(0);
// this.releaseBuffer(gpuReadBuffer);
gpuReadBuffer.unmap();
gpuReadBuffer.destroy();
return arrayBuffer;
}
// ---------Below code is not used!-------------------
// TODO: Float32Array is bad. And buffer is bad.
async compileAndRun(workGroupSize: [number, number, number]) {
// TODO: figure out how to return non const two values.
await this.dispatchAndSubmitWithFence(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize);
return true;
}
private async dispatchAndSubmitWithFence(
computePipeline: any, bindGroup: any, dispatchX: number,
dispatchY: number, workGroupSize: [number, number, number]) {
const start = utils.now();
// Commands submission.
this.dispatchAndSubmit(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize);
const fence = this.queue.createFence();
this.queue.signal(fence, 1);
await fence.onCompletion(1);
console.log((utils.now() - start).toFixed(2));
}
getBufferKey() {
return this.bufferID++;
}
releaseBuffer(buffer: GPUBuffer) {
if (this.freeBuffers == null) {
return;
}
const key = this.getBufferKey();
if (!this.freeBuffers.has(key)) {
this.freeBuffers.set(key, []);
}
this.freeBuffers.get(key).push(buffer);
}
// Call this after execute.
disposeReadBackBuffer() {
if (this.freeBuffers == null) {
return;
}
this.freeBuffers.forEach((buffers, key) => {
buffers.forEach(buff => {
// console.log(' freeBuffers destroy key = ' + key);
buff.unmap();
buff.destroy();
});
});
}
dispose() {
this.disposeReadBackBuffer();
}
}