webgpu-computed 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ type WGSl_TYPE = "f32" | "vec2" | "vec3" | "vec4" | "mat3x3" | "mat4x4";
2
+ type GpuComputedOption = {
3
+ workgroupSize?: [number, number, number];
4
+ globalInvocationIdName?: string;
5
+ workgroupIndexName?: string;
6
+ beforeCodes?: string[];
7
+ code?: string;
8
+ };
9
+ type BufferGroup = {
10
+ buffers: {
11
+ name: string;
12
+ buffer: GPUBuffer;
13
+ }[];
14
+ group: GPUBindGroup;
15
+ };
16
+ interface IStructBaseType {
17
+ name: string;
18
+ type: WGSl_TYPE;
19
+ offset?: number;
20
+ size?: number;
21
+ }
22
+ type IStruct = IStructBaseType[];
23
+ interface IStructArray {
24
+ buffer?: number[];
25
+ stride?: number;
26
+ layout: IStruct;
27
+ }
28
+ type BufferDataType = Record<string, (number[]) | IStruct | IStructArray>;
29
+ export declare class GpuComputed {
30
+ template?: BufferDataType;
31
+ option?: GpuComputedOption;
32
+ pipeline?: GPUComputePipeline;
33
+ device?: GPUDevice;
34
+ groupLayout?: any;
35
+ code?: string;
36
+ constructor(template: BufferDataType, option?: GpuComputedOption);
37
+ /** 完善模版数据
38
+ * @param template
39
+ */
40
+ private improveTemplateOption;
41
+ /** 获取Gpu设备
42
+ * @returns
43
+ */
44
+ getDevice(): Promise<{
45
+ adapter: GPUAdapter;
46
+ device: GPUDevice;
47
+ }>;
48
+ /**
49
+ * 初始化计算管线
50
+ */
51
+ initPipeline(): Promise<void>;
52
+ /** 根据数据创建buffer组
53
+ * @param data
54
+ */
55
+ createBindGroup(data: Record<string, any>): {
56
+ group: GPUBindGroup;
57
+ buffers: {
58
+ name: string;
59
+ buffer: GPUBuffer;
60
+ }[];
61
+ };
62
+ /** 数据映射回模版数据
63
+ * @param array
64
+ * @param key
65
+ */
66
+ dataMap(array: number[], key: string): number[] | Record<string, number | number[]> | Record<string, number | number[]>[];
67
+ /** 开始计算
68
+ * @param group 数据组
69
+ * @param workgroupCount 工作组大小
70
+ * @param synchronize 需要同步的数据字段
71
+ * @returns
72
+ */
73
+ computed(group: BufferGroup, workgroupCount: [number, number?, number?], synchronize?: string[]): Promise<number[][]>;
74
+ /** 初始化gpu设备
75
+ * @returns
76
+ */
77
+ static init(): Promise<void>;
78
+ /** 注销gpu设备
79
+ */
80
+ static destroy(): void;
81
+ /**
82
+ * @param data
83
+ */
84
+ static buildBufferTypeByData(data: Record<string, any>): Record<string, IStructArray | number[] | IStruct>;
85
+ /** 通过数据创建
86
+ * @param opt
87
+ * @returns
88
+ */
89
+ static fromByData(opt: {
90
+ data: Record<string, any>;
91
+ } & GpuComputedOption): Promise<GpuComputed>;
92
+ /** 快捷计算方法
93
+ * @param opt
94
+ * @returns
95
+ */
96
+ static computed(opt: {
97
+ data: Record<string, any>;
98
+ workgroupCount: [number, number?, number?];
99
+ synchronize?: string[];
100
+ map?: boolean;
101
+ onSuccess?: (opt: {
102
+ gpuComputed: GpuComputed;
103
+ group: BufferGroup;
104
+ results: number[][];
105
+ }) => void;
106
+ } & GpuComputedOption): Promise<(number[] | Record<string, number | number[]> | Record<string, number | number[]>[])[]>;
107
+ }
108
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare const quat_rotate = "\n fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {\n // q.xyz = vector part, q.w = scalar part\n let t = 2.0 * cross(q.xyz, v);\n return v + q.w * t + cross(q.xyz, t);\n }\n";
2
+ export declare const point_in_obb = "\n fn point_in_obb(\n point: vec3<f32>,\n center: vec3<f32>,\n halfSize: vec3<f32>,\n quat: vec4<f32>\n ) -> bool {\n // \u4E16\u754C\u7A7A\u95F4 \u2192 OBB \u5C40\u90E8\u7A7A\u95F4\n let local = point - center;\n\n // \u9006\u65CB\u8F6C\uFF08\u5171\u8F6D\u56DB\u5143\u6570\uFF09\n let invQuat = vec4<f32>(-quat.xyz, quat.w);\n let pLocal = quat_rotate(invQuat, local);\n\n // AABB \u5224\u65AD\n return all(abs(pLocal) <= halfSize);\n }\n";
@@ -0,0 +1 @@
1
+ export declare function include(path: string, exportDefault?: boolean): Promise<any>;
package/README.md DELETED
@@ -1,388 +0,0 @@
1
- 🌐 Read this in other languages:
2
- - [简体中文](/webgpu-computed/README.md)
3
-
4
- # webgpu-computed
5
-
6
- A simplified WebGPU computing library that encapsulates tedious initialization and buffer management, allowing developers to focus on WGSL shader logic.
7
-
8
- ## Features
9
-
10
- - 🚀 Simplified WebGPU initialization
11
- - 📦 Automatic buffer management and layout calculation
12
- - 🔧 Support for complex data structures (vectors, matrices)
13
- - ⚡ High-performance GPU computing
14
- - 📚 Built-in common WGSL functions
15
- - ✅ Support node
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install webgpu-computed
21
- ```
22
-
23
- ## Quick Start
24
-
25
- ### 1. Initialize WebGPU
26
-
27
- Before using any computing features, you need to initialize the WebGPU environment:
28
-
29
- ```javascript
30
- import { GpuComputed } from 'webgpu-computed';
31
-
32
- // Initialize WebGPU
33
- await GpuComputed.init();
34
- //After using the node environment, please call:
35
- //GpuComputed.destroy()
36
- ```
37
-
38
- ### 2. Perform Simple Computation
39
-
40
- Here is a simple vector addition example:
41
-
42
- ```javascript
43
- import { GpuComputed } from 'webgpu-computed';
44
-
45
- // Prepare data
46
- const data = {
47
- inputA: [1.0, 2.0, 3.0, 4.0],
48
- inputB: [0.5, 1.5, 2.5, 3.5],
49
- output: new Array(4).fill(0) // Output buffer
50
- };
51
-
52
- // WGSL computation code
53
- const code = `
54
- output[index] = inputA[index] + inputB[index];
55
- `;
56
-
57
- // Execute computation
58
- const results = await GpuComputed.computed({
59
- code,
60
- data,
61
- workgroupCount: [1] // Number of workgroups
62
- });
63
-
64
- console.log(results); // [[1.5, 3.5, 5.5, 7.5]]
65
- ```
66
-
67
- ### 3. Using Complex Data Structures
68
-
69
- The library supports vector and matrix types:
70
-
71
- ```javascript
72
- const data = {
73
- positions: [
74
- { pos: [1.0, 2.0, 3.0], vel: [0.1, 0.2, 0.3] },
75
- { pos: [4.0, 5.0, 6.0], vel: [0.4, 0.5, 0.6] }
76
- ],
77
- output: new Array(2).fill({ pos: [0,0,0], vel: [0,0,0] })
78
- };
79
-
80
- const code = `
81
- output[index].pos = positions[index].pos + positions[index].vel;
82
- output[index].vel = positions[index].vel * 2.0;
83
- `;
84
-
85
- const results = await GpuComputed.computed({
86
- code,
87
- data,
88
- workgroupCount: [1]
89
- });
90
- ```
91
-
92
- ## API Reference
93
-
94
- ### GpuComputed Class
95
-
96
- #### Static Methods
97
-
98
- ##### `GpuComputed.init()`
99
-
100
- Initializes the WebGPU environment. Must be called before using other features.
101
-
102
- **Returns**: `Promise<void>`
103
-
104
- **Throws**: If the browser does not support WebGPU or fails to obtain adapter/device
105
-
106
- ##### `GpuComputed.computed(options)`
107
-
108
- Executes a GPU computation task.
109
-
110
- **Parameters**:
111
-
112
- - `code` (string): WGSL computation code
113
- - `data` (object): Input/output data object
114
- - `workgroupCount` (array): Number of workgroups [x, y?, z?]
115
- - `workgroupSize` (array, optional): Workgroup size, default [32, 1, 1]
116
- - `globalInvocationIdName` (string, optional): Global invocation ID variable name, default "grid"
117
- - `workgroupIndexName` (string, optional): Workgroup index variable name, default "index"
118
- - `synchronize` (array, optional): Array of buffer names to synchronize back to CPU
119
- - `beforeCodes` (array, optional): WGSL code snippets before the computation function
120
- - `onSuccess` (function, optional): Success callback function
121
-
122
- **Returns**: `Promise<Array<Float32Array>>` - Data from synchronized buffers
123
-
124
- ### Data Types
125
-
126
- Supports the following WGSL types:
127
-
128
- - `f32`: Single-precision float
129
- - `vec2`: 2D vector
130
- - `vec3`: 3D vector
131
- - `vec4`: 4D vector
132
- - `mat3x3`: 3x3 matrix
133
- - `mat4x4`: 4x4 matrix
134
-
135
- ### Built-in WGSL Functions
136
-
137
- The library provides some commonly used WGSL helper functions:
138
-
139
- #### Quaternion Rotation
140
-
141
- ```wgsl
142
- fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32>
143
- ```
144
-
145
- Usage example:
146
-
147
- ```javascript
148
- import { WGSL_Fun } from 'webgpu-computed';
149
-
150
- await GpuComputed.computed({
151
- code: "",
152
- data: {....},
153
- beforeCodes:[WGSL_Fun.quat_rotate]
154
- })
155
- ```
156
-
157
- #### Point in OBB Detection
158
-
159
- ```wgsl
160
- fn point_in_obb(point: vec3<f32>, center: vec3<f32>, halfSize: vec3<f32>, quat: vec4<f32>) -> bool
161
- ```
162
-
163
- ## Advanced Usage
164
-
165
- ### Custom Workgroup Configuration
166
-
167
- ```javascript
168
- await GpuComputed.computed({
169
- code: '...',
170
- data: {...},
171
- workgroupCount: [4, 4], // 16 workgroups
172
- workgroupSize: [16, 16], // 256 threads per workgroup
173
- });
174
- ```
175
-
176
- ### Synchronizing Data Back to CPU
177
-
178
- ```javascript
179
- const results = await GpuComputed.computed({
180
- code: '...',
181
- data: {...},
182
- synchronize: ['output'], // Specify buffers to synchronize
183
- workgroupCount: [1]
184
- });
185
-
186
- // results contains synchronized data
187
- ```
188
-
189
- ### Callback Function
190
-
191
- ```javascript
192
- await GpuComputed.computed({
193
- code: '...',
194
- data: {...},
195
- workgroupCount: [1],
196
- onSuccess: ({ code, bufferInfoList, results }) => {
197
- console.log('Computation completed', results);
198
- }
199
- });
200
- ```
201
-
202
- ## Browser Support
203
-
204
- - Chrome 113+
205
- - Edge 113+
206
- - Firefox (partial support)
207
- - Safari (partial support)
208
-
209
- Ensure the browser supports the WebGPU API.
210
-
211
- ## Example Project
212
-
213
- ```js
214
- import { GpuComputed } from "webgpu-computed"
215
-
216
- // 1. Initialize WebGPU
217
- console.log('Initializing WebGPU...');
218
- await GpuComputed.init();
219
- console.log('WebGPU initialized successfully');
220
-
221
- // 2. Simple array computation example
222
- console.log('\n=== Simple Array Computation ===');
223
- const simpleData = {
224
- inputA: [1.0, 2.0, 3.0, 4.0],
225
- inputB: [0.5, 1.5, 2.5, 3.5],
226
- output: new Array(4).fill(0)
227
- };
228
-
229
- const simpleCode = `
230
- output[index] = inputA[index] + inputB[index];
231
- `;
232
-
233
- const simpleResults = await GpuComputed.computed({
234
- code: simpleCode,
235
- data: simpleData,
236
- workgroupCount: [1],
237
- synchronize: ['output']
238
- });
239
-
240
- console.log('Simple computation result:', simpleResults[0]); // [1.5, 3.5, 5.5, 7.5]
241
-
242
- // 3. Complex data structure example (struct)
243
- console.log('\n=== Complex Data Structure Computation ===');
244
- const complexData = {
245
- particles: [
246
- { position: [1.0, 2.0, 3.0], velocity: [0.1, 0.2, 0.3], mass: 1.0 },
247
- { position: [4.0, 5.0, 6.0], velocity: [0.4, 0.5, 0.6], mass: 2.0 }
248
- ],
249
- output: [
250
- { position: [0, 0, 0], velocity: [0, 0, 0], mass: 0 },
251
- { position: [0, 0, 0], velocity: [0, 0, 0], mass: 0 }
252
- ]
253
- };
254
-
255
- const complexCode = `
256
- output[index].position = particles[index].position + particles[index].velocity;
257
- output[index].velocity = particles[index].velocity * 2.0;
258
- output[index].mass = particles[index].mass * 1.5;
259
- `;
260
-
261
- const complexResults = await GpuComputed.computed({
262
- code: complexCode,
263
- data: complexData,
264
- workgroupCount: [1],
265
- synchronize: ['output']
266
- });
267
-
268
- console.log('Complex computation result:', complexResults[0]);
269
-
270
- // 4. Using built-in WGSL functions example
271
- console.log('\n=== Using Built-in WGSL Functions ===');
272
- const wgslFunData = {
273
- points: [
274
- {
275
- x: 1.0, y: 0.0, z: 0.0
276
- },
277
- {
278
- x: 0.0, y: 1.0, z: 0.0
279
- },
280
- {
281
- x: -1.0, y: 0.0, z: 0.0
282
- }
283
- ],
284
- obbCenter: [0.0, 0.0, 0.0],
285
- obbHalfSize: [2.0, 2.0, 2.0],
286
- obbRotation: [0.0, 0.0, 0.0, 1.0], // Unit quaternion, no rotation
287
- results: new Array(3).fill(0)
288
- };
289
-
290
- const wgslFunCode = `
291
- let point = vec3(points[index].x, points[index].y, points[index].z);
292
- let center = vec3<f32>(obbCenter[0], obbCenter[1], obbCenter[2]);
293
- let halfSize = vec3<f32>(obbHalfSize[0], obbHalfSize[1], obbHalfSize[2]);
294
- let quat = vec4<f32>(obbRotation[0], obbRotation[1], obbRotation[2], obbRotation[3]);
295
-
296
- if (point_in_obb(point, center, halfSize, quat)) {
297
- results[index] = 1.0;
298
- } else {
299
- results[index] = 0.0;
300
- }
301
- `;
302
-
303
- const wgslFunResults = await GpuComputed.computed({
304
- code: wgslFunCode,
305
- data: wgslFunData,
306
- workgroupCount: [1],
307
- beforeCodes: [WGSL_Fun.quat_rotate, WGSL_Fun.point_in_obb, /** Add your own function code */],
308
- synchronize: ['results']
309
- });
310
-
311
- console.log('OBB detection result:', wgslFunResults[0]); // [1, 1, 1] All points are inside the OBB
312
-
313
- // 5. Custom workgroup configuration example
314
- console.log('\n=== Custom Workgroup Configuration ===');
315
- const largeData = {
316
- largeArray: new Array(1024).fill(0).map((_, i) => i * 1.0),
317
- output: new Array(1024).fill(0)
318
- };
319
-
320
- const largeCode = `
321
- output[index] = largeArray[index] * 2.0;
322
- `;
323
-
324
- const largeResults = await GpuComputed.computed({
325
- code: largeCode,
326
- data: largeData,
327
- workgroupCount: [32], // 32 workgroups
328
- workgroupSize: [32, 1, 1], // 32 threads per workgroup, total 1024 threads
329
- synchronize: ['output']
330
- });
331
-
332
- console.log('Large array computation result (first 10):', largeResults[0].slice(0, 10));
333
-
334
- // 6. Using callback function example
335
- console.log('\n=== Using Callback Function ===');
336
- const callbackData = {
337
- values: [10.0, 20.0, 30.0],
338
- squares: new Array(3).fill(0)
339
- };
340
-
341
- const callbackCode = `
342
- squares[index] = values[index] * values[index];
343
- `;
344
-
345
- await GpuComputed.computed({
346
- code: callbackCode,
347
- data: callbackData,
348
- workgroupCount: [1],
349
- synchronize: ['squares'],
350
- onSuccess: ({ code, bufferInfoList, results }) => {
351
- console.log('Callback triggered, square computation result:', results[0]); // [100, 400, 900]
352
- }
353
- });
354
-
355
- // 7. Multi-dimensional workgroup example
356
- console.log('\n=== Multi-dimensional Workgroup ===');
357
- const matrixData = {
358
- matrixA: new Array(16).fill(0).map((_, i) => i * 1.0),
359
- matrixB: new Array(16).fill(0).map((_, i) => (i + 1) * 1.0),
360
- result: new Array(16).fill(0)
361
- };
362
-
363
- const matrixCode = `
364
- let x = index % 4u;
365
- let y = index / 4u;
366
- let idx = y * 4u + x;
367
- result[idx] = matrixA[idx] + matrixB[idx];
368
- `;
369
-
370
- const matrixResults = await GpuComputed.computed({
371
- code: matrixCode,
372
- data: matrixData,
373
- workgroupCount: [4, 4], // 4x4 workgroup grid
374
- workgroupSize: [1, 1, 1], // 1 thread per workgroup
375
- synchronize: ['result']
376
- });
377
-
378
- console.log('Matrix computation result:', matrixResults[0]);
379
-
380
- console.log('\nAll feature examples completed!');
381
- ```
382
-
383
- ## License
384
-
385
- ISC License
386
-
387
- ---
388
-