Experience
Code Location
You may test by yourself.
@yhyddr/images-by-gpu
@yhyddr/images
Performance
It is foreseeable that the larger the image, the higher the GPU advantage.
Key Code
First get GPU
adapter = navigator.gpu.requestAdapter()
device = adapter.requestDevice()
Compute shader code
A syntax based on the C programming language. The following code is used in GPU to compute matrix.
const computeShaderCode = `#version 450
layout(std430, set = 0, binding = 0) readonly buffer FirstMatrix {
vec2 size;
float numbers[];
} firstMatrix;
layout(std430, set = 0, binding = 1) readonly buffer SecondMatrix {
vec2 size;
float numbers[];
} secondMatrix;
layout(std430, set = 0, binding = 2) buffer ResultMatrix {
vec2 size;
float numbers[];
} resultMatrix;
void main() {
resultMatrix.size = vec2(firstMatrix.size.x, secondMatrix.size.y);
ivec2 resultCell = ivec2(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y);
float result = 0.0;
for (int i = 0; i < firstMatrix.size.y; i++) {
int a = i + resultCell.x * int(firstMatrix.size.y);
int b = resultCell.y + i * int(secondMatrix.size.y);
result += firstMatrix.numbers[a] * secondMatrix.numbers[b];
}
int index = resultCell.y + resultCell.x * int(secondMatrix.size.y);
resultMatrix.numbers[index] = result;
}
`;
Compiler
This is a GLSL-to-SPIR-V compiler for the Web and Node.js. It is a WebAssembly build of glslang.
const glslangModule = await import('https://unpkg.com/@webgpu/glslang@0.0.13/dist/web-devel/glslang.js')
const glslang = await glslangModule.default();