@drawcall/webgpu 0.2.1 → 0.3.0

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.
package/package.json CHANGED
@@ -1,13 +1,19 @@
1
1
  {
2
2
  "name": "@drawcall/webgpu",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "WebGPU rendering and compute in browsers and Node.js, with or without a GPU",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {
8
8
  ".": {
9
- "node": "./src/index.js",
10
- "default": "./src/browser.js"
9
+ "node": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/index.js"
12
+ },
13
+ "default": {
14
+ "types": "./src/browser.d.ts",
15
+ "default": "./src/browser.js"
16
+ }
11
17
  }
12
18
  },
13
19
  "files": [
@@ -33,20 +39,22 @@
33
39
  "release:trust": "node deps/release.js trust"
34
40
  },
35
41
  "dependencies": {
42
+ "@webgpu/types": "^0.1.74",
36
43
  "detect-libc": "2.1.2",
37
44
  "sharp": "0.35.5"
38
45
  },
39
46
  "optionalDependencies": {
40
- "@drawcall/webgpu-linux-x64": "0.2.1",
41
- "@drawcall/webgpu-linux-arm64": "0.2.1",
42
- "@drawcall/webgpu-darwin-x64": "0.2.1",
43
- "@drawcall/webgpu-darwin-arm64": "0.2.1",
44
- "@drawcall/webgpu-win32-x64": "0.2.1",
45
- "@drawcall/webgpu-linuxmusl-x64": "0.2.1",
46
- "@drawcall/webgpu-linuxmusl-arm64": "0.2.1",
47
- "@drawcall/webgpu-win32-arm64": "0.2.1"
47
+ "@drawcall/webgpu-linux-x64": "0.3.0",
48
+ "@drawcall/webgpu-linux-arm64": "0.3.0",
49
+ "@drawcall/webgpu-darwin-x64": "0.3.0",
50
+ "@drawcall/webgpu-darwin-arm64": "0.3.0",
51
+ "@drawcall/webgpu-win32-x64": "0.3.0",
52
+ "@drawcall/webgpu-linuxmusl-x64": "0.3.0",
53
+ "@drawcall/webgpu-linuxmusl-arm64": "0.3.0",
54
+ "@drawcall/webgpu-win32-arm64": "0.3.0"
48
55
  },
49
56
  "devDependencies": {
50
- "three": "0.186.1"
57
+ "three": "0.186.1",
58
+ "typescript": "5.9.3"
51
59
  }
52
60
  }
@@ -5,11 +5,11 @@ description: Use @drawcall/webgpu for portable Three.js rendering and WebGPU com
5
5
 
6
6
  # Render a scene
7
7
 
8
- Use the same Three.js scene and renderer code in both environments. Browser canvases are real DOM elements; append them to the application container and use normal CSS and resize handling. In workers, request an offscreen canvas and send dimensions from the main thread. Node has no layout engine: supply output dimensions, and do not infer them from CSS.
8
+ Use the same Three.js scene and renderer code in both environments. Browser canvases are real DOM elements; append them to the application container and use normal CSS and resize handling. In browser workers, request an offscreen canvas and send dimensions from the main thread. Node has no layout engine: supply output dimensions, and do not infer them from CSS.
9
9
 
10
- In Node, create the canvas before loading assets and keep it alive until loaders and rendering finish. Import scene classes from `three/webgpu` and loaders from `three/addons`. Keep original assets intact; compressed glTF can use the standard `DRACOLoader` with its decoder directory served over HTTP.
10
+ In Node, importing the package installs `navigator.gpu` and the page APIs Three's loaders use, such as `createImageBitmap` and `Worker`, for the rest of the process; loaders need no canvas. Import scene classes from `three/webgpu` and loaders from `three/addons`. Keep original assets intact; compressed glTF can use the standard `DRACOLoader` with its decoder directory served over HTTP.
11
11
 
12
- Install `three` and `sharp` as application dependencies for this Node export pattern:
12
+ Install `three`, and `sharp` for the example's PNG encoding; any encoder of raw RGBA works:
13
13
 
14
14
  ```js
15
15
  import { createCanvas } from '@drawcall/webgpu';
@@ -40,12 +40,16 @@ Use HTTP(S) URLs for standard loaders, including assets on a local file server;
40
40
 
41
41
  The example above exports a frame in Node. In browsers, use the canvas normally; do not call its Node-only export and cleanup methods. For portable Three readback, use a render target and Three’s readback API.
42
42
 
43
- Render the final frame to the canvas. If custom passes use render targets, call `renderer.setRenderTarget(null)` before the final canvas render and readback. Dispose the renderer and loaders before the canvas. A canvas does not own an application-supplied device: destroy that device after all rendering and compute users finish.
43
+ Render the final frame to the canvas. If custom passes use render targets, call `renderer.setRenderTarget(null)` before the final canvas render and readback. Dispose the renderer before the canvas, and dispose loaders when done: their workers keep Node running. A canvas does not own an application-supplied device: destroy that device after all rendering and compute users finish.
44
44
 
45
- For cold server-side rendering, launch a fresh process per task, render, encode, and await disposal. Node does not supply a browser DOM, video decoding, 2D canvas, or the complete browser Worker API. Code that needs a 2D canvas can use a canvas library: `copyExternalImageToTexture`, and so Three's `CanvasTexture`, accepts that library's canvases and `ImageData`, and `readImageBitmap` turns a decoded `ImageBitmap` into pixels it can draw. Blob image decoding and classic workers support the tested glTF and Draco paths; other loaders may need browser APIs outside this scope. Treat unsupported API errors as compatibility gaps rather than replacing assets or patching Three.js.
45
+ For cold server-side rendering, launch a fresh process per task, render, encode, and await disposal. Node does not supply a browser DOM, video decoding, 2D canvas, or the complete browser Worker API. Code that needs a 2D canvas can use a canvas library: `copyExternalImageToTexture`, and so Three's `CanvasTexture`, accepts that library's canvases and `ImageData`, and `readImageBitmap` turns a decoded `ImageBitmap` into pixels it can draw. Blob image decoding and classic workers support the tested glTF and Draco paths; other loaders may need browser APIs outside this scope. An uncaught error in a worker fires `error` on its `Worker`, and the worker keeps running; an error no listener cancels is logged, and a load waiting on the failed task does not settle. Treat unsupported API errors as compatibility gaps rather than replacing assets or patching Three.js.
46
+
47
+ # TypeScript
48
+
49
+ The package ships its types, built on `@webgpu/types`. They and the page APIs Node gains, such as `ImageBitmap`, are declared in TypeScript's `dom` lib, so include it. Node code compiled with `bundler` module resolution gets the browser entry's types unless it sets `"customConditions": ["node"]`. `@types/three` types `WebGPURenderer`'s `canvas` as a DOM canvas, which the Node canvas is not; it implements what the renderer uses, so cast it there.
46
50
 
47
51
  # Compute without a canvas
48
52
 
49
- Import `requestAdapter` from the package, check its result, then call the adapter’s standard `requestDevice` with the features and limits the workload requires. Use ordinary WGSL, buffers, compute passes, and queue submission. No canvas or loader host is needed. Destroy application-owned devices when finished; do not rely on garbage collection to release GPU resources. Node prefers a native GPU adapter and falls back to the bundled CPU renderer; request `{ forceFallbackAdapter: true }` to select the CPU renderer explicitly. GPU, browser, and CPU adapters can expose different capabilities. To render Three on a specific adapter, pass a device created from it to `WebGPURenderer`.
53
+ Import `requestAdapter` from the package, check its result, then call the adapter’s standard `requestDevice` with the features and limits the workload requires. Use ordinary WGSL, buffers, compute passes, and queue submission. No canvas is needed. Destroy application-owned devices when finished; do not rely on garbage collection to release GPU resources. Node prefers a native GPU adapter and falls back to the bundled CPU renderer; request `{ forceFallbackAdapter: true }` to select the CPU renderer explicitly. GPU, browser, and CPU adapters can expose different capabilities. To render Three on a specific adapter, pass a device created from it to `WebGPURenderer`.
50
54
 
51
55
  For combined raw compute and Three rendering, pass the same application-created device to `WebGPURenderer`. For Three TSL compute nodes, use the renderer’s compute API directly. Neither path requires changing Three.js.
@@ -0,0 +1,13 @@
1
+ /// <reference types="@webgpu/types" />
2
+
3
+ /** A detached canvas element, or an OffscreenCanvas with offscreen, such as in a worker. */
4
+ export function createCanvas(width: number, height: number, options?: { offscreen?: false }): Promise<HTMLCanvasElement>;
5
+ export function createCanvas(width: number, height: number, options: { offscreen: true }): Promise<OffscreenCanvas>;
6
+ export function createCanvas(width: number, height: number, options: { offscreen: boolean }): Promise<HTMLCanvasElement | OffscreenCanvas>;
7
+
8
+ /** The browser's adapter selection, null when it has none. */
9
+ export function requestAdapter(options?: GPURequestAdapterOptions): Promise<GPUAdapter | null>;
10
+
11
+ export function getPreferredCanvasFormat(): GPUTextureFormat;
12
+
13
+ export function readImageBitmap(bitmap: ImageBitmap): ImageData;
package/src/browser.js CHANGED
@@ -1,4 +1,3 @@
1
- /** Return a real browser canvas; CSS, events and layout remain browser-owned. */
2
1
  export async function createCanvas(width, height, { offscreen = false } = {}) {
3
2
  if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
4
3
  throw new RangeError('Canvas dimensions must be positive integers');
@@ -16,7 +15,6 @@ function gpu() {
16
15
  return navigator.gpu;
17
16
  }
18
17
 
19
- /** Forward standard adapter selection to the browser, including its null result. */
20
18
  export async function requestAdapter(options) {
21
19
  return gpu().requestAdapter(options);
22
20
  }
@@ -25,7 +23,6 @@ export function getPreferredCanvasFormat() {
25
23
  return gpu().getPreferredCanvasFormat();
26
24
  }
27
25
 
28
- /** The straight-alpha sRGB RGBA pixels of an ImageBitmap, as ImageData. */
29
26
  export function readImageBitmap(bitmap) {
30
27
  const context = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d');
31
28
  context.drawImage(bitmap, 0, 0);
package/src/canvas.js CHANGED
@@ -4,7 +4,7 @@ function dimension(value) {
4
4
  }
5
5
 
6
6
  // A native canvas keeps its last frame available until resize or reconfiguration.
7
- export function canvas(width, height, check) {
7
+ export function canvas(width, height) {
8
8
  width = dimension(width);
9
9
  height = dimension(height);
10
10
  let configuration, texture, device, lost;
@@ -14,7 +14,6 @@ export function canvas(width, height, check) {
14
14
  const onError = event => errors.push(event.error);
15
15
 
16
16
  function ready() {
17
- check();
18
17
  if (closed) throw new Error('Canvas is disposed');
19
18
  if (lost) throw new Error(`Device lost: ${lost.reason}: ${lost.message}`);
20
19
  if (errors.length) throw new AggregateError(errors, 'WebGPU rendering failed');
@@ -35,7 +34,15 @@ export function canvas(width, height, check) {
35
34
  removeEventListener: events.removeEventListener.bind(events),
36
35
  dispatchEvent: events.dispatchEvent.bind(events),
37
36
  getContext(type) { ready(); return type === 'webgpu' ? context : null; },
38
- /** Returns the current frame as packed, top-row-first straight-alpha RGBA8 bytes. */
37
+ async dispose() {
38
+ if (closed) return;
39
+ closed = true;
40
+ reset();
41
+ configuration = undefined;
42
+ device?.removeEventListener('uncapturederror', onError);
43
+ if (lost && lost.reason !== 'destroyed') errors.push(new Error(`Device lost: ${lost.reason}: ${lost.message}`));
44
+ if (errors.length) throw new AggregateError(errors, 'WebGPU rendering failed');
45
+ },
39
46
  async readPixels() {
40
47
  ready();
41
48
  if (!texture) throw new Error('Render a frame before reading canvas pixels');
@@ -84,23 +91,32 @@ export function canvas(width, height, check) {
84
91
  canvas: output,
85
92
  configure(value) {
86
93
  ready();
87
- if (device && value.device !== device) throw new TypeError('A canvas cannot switch WebGPU devices');
88
- if (!value.device || typeof value.device.createTexture !== 'function') throw new TypeError('A WebGPU device is required');
89
- if ((value.colorSpace ?? 'srgb') !== 'srgb') throw new TypeError('Only sRGB canvas color space is supported');
90
- if (!['opaque', 'premultiplied'].includes(value.alphaMode ?? 'opaque')) throw new TypeError('Unsupported canvas alpha mode');
91
- if ((value.toneMapping?.mode ?? 'standard') !== 'standard') throw new TypeError('Extended canvas tone mapping is not supported');
92
- if (!['rgba8unorm', 'bgra8unorm'].includes(value.format)) throw new TypeError('Unsupported canvas format');
94
+ // The configuration as getConfiguration reports it, with the defaults filled in.
95
+ const next = {
96
+ ...value,
97
+ usage: value.usage ?? GPUTextureUsage.RENDER_ATTACHMENT,
98
+ colorSpace: value.colorSpace ?? 'srgb',
99
+ alphaMode: value.alphaMode ?? 'opaque',
100
+ toneMapping: { mode: value.toneMapping?.mode ?? 'standard' },
101
+ viewFormats: [...(value.viewFormats ?? [])],
102
+ };
103
+ if (device && next.device !== device) throw new TypeError('A canvas cannot switch WebGPU devices');
104
+ if (!next.device || typeof next.device.createTexture !== 'function') throw new TypeError('A WebGPU device is required');
105
+ if (next.colorSpace !== 'srgb') throw new TypeError('Only sRGB canvas color space is supported');
106
+ if (!['opaque', 'premultiplied'].includes(next.alphaMode)) throw new TypeError('Unsupported canvas alpha mode');
107
+ if (next.toneMapping.mode !== 'standard') throw new TypeError('Extended canvas tone mapping is not supported');
108
+ if (!['rgba8unorm', 'bgra8unorm'].includes(next.format)) throw new TypeError('Unsupported canvas format');
93
109
  if (!device) {
94
- device = value.device;
110
+ device = next.device;
95
111
  device.addEventListener('uncapturederror', onError);
96
112
  device.lost.then(info => { if (!closed) lost = info; });
97
113
  }
98
114
  reset();
99
- configuration = { ...value, viewFormats: [...(value.viewFormats ?? [])] };
115
+ configuration = next;
100
116
  },
101
117
  getConfiguration() {
102
118
  ready();
103
- return configuration ? { ...configuration, viewFormats: [...configuration.viewFormats] } : null;
119
+ return configuration ? { ...configuration, toneMapping: { ...configuration.toneMapping }, viewFormats: [...configuration.viewFormats] } : null;
104
120
  },
105
121
  getCurrentTexture() {
106
122
  ready();
@@ -109,7 +125,7 @@ export function canvas(width, height, check) {
109
125
  texture ??= device.createTexture({
110
126
  size: [width, height],
111
127
  format: configuration.format,
112
- usage: (configuration.usage ?? GPUTextureUsage.RENDER_ATTACHMENT) | GPUTextureUsage.COPY_SRC,
128
+ usage: configuration.usage | GPUTextureUsage.COPY_SRC,
113
129
  viewFormats: configuration.viewFormats,
114
130
  });
115
131
  return texture;
@@ -117,17 +133,5 @@ export function canvas(width, height, check) {
117
133
  unconfigure() { ready(); reset(); configuration = undefined; },
118
134
  };
119
135
 
120
- return {
121
- output,
122
- close() {
123
- closed = true;
124
- reset();
125
- configuration = undefined;
126
- if (device) {
127
- device.removeEventListener('uncapturederror', onError);
128
- }
129
- if (lost && lost.reason !== 'destroyed') errors.push(new Error(`Device lost: ${lost.reason}: ${lost.message}`));
130
- if (errors.length) throw new AggregateError(errors, 'WebGPU rendering failed');
131
- },
132
- };
136
+ return output;
133
137
  }
package/src/image.js CHANGED
@@ -1,7 +1,7 @@
1
- // Node image decoding for the platform boundary. Three's loaders remain untouched.
2
- import { globals } from './globals.js';
1
+ // Node image sources: Blob decoding, ImageData and 2D canvas uploads, and ImageBitmap readback.
2
+ import { createRequire } from 'node:module';
3
3
 
4
- let sharpPromise;
4
+ const require = createRequire(import.meta.url);
5
5
 
6
6
  /**
7
7
  * Let copyExternalImageToTexture take ImageData and 2D canvases, which Node has only through canvas libraries: their
@@ -45,14 +45,9 @@ export function readImageBitmap(native, bitmap) {
45
45
  return { width: bitmap.width, height: bitmap.height, data: new Uint8ClampedArray(data.buffer), colorSpace: 'srgb' };
46
46
  }
47
47
 
48
- export function installImages(native) {
49
- if (typeof native.createImageBitmapFromRGBA !== 'function') throw new Error('Native ImageBitmap bridge is unavailable');
50
- const installed = globals();
51
- let decoder, previousCache, closed = false;
52
- const ImageBitmap = native.ImageBitmap ?? native.globals?.ImageBitmap;
53
- if (!ImageBitmap) throw new Error('Native ImageBitmap constructor is unavailable');
54
- async function createImageBitmap(source, options = {}) {
55
- if (closed) throw new Error('Image decoder is disposed');
48
+ /** createImageBitmap for Blobs, decoded by sharp into native ImageBitmaps. */
49
+ export function imageBitmapFactory(native) {
50
+ return async function createImageBitmap(source, options = {}) {
56
51
  if (!(source instanceof Blob)) throw new TypeError('This Node image platform currently supports Blob input only');
57
52
  if (arguments.length > 2) throw new TypeError('ImageBitmap cropping is not implemented');
58
53
  const supported = new Set(['imageOrientation', 'premultiplyAlpha', 'colorSpaceConversion']);
@@ -63,21 +58,13 @@ export function installImages(native) {
63
58
  if (!['from-image', 'flipY', 'none'].includes(orientation)) throw new TypeError('Invalid imageOrientation');
64
59
  if (!['none', 'premultiply', 'default'].includes(premultiply)) throw new TypeError('Invalid premultiplyAlpha');
65
60
  if (!['none', 'default'].includes(conversion)) throw new TypeError('Invalid colorSpaceConversion');
66
- sharpPromise ??= import('sharp').then(module => module.default);
67
- const sharp = await sharpPromise;
68
- if (closed) throw new Error('Image decoder is disposed');
69
- if (!decoder) {
70
- decoder = sharp;
71
- const cache = sharp.cache();
72
- previousCache = { memory: cache.memory.max, files: cache.files.max, items: cache.items.max };
73
- sharp.cache(false);
74
- }
61
+ // require, unlike import(), retries a failed load and reports its own error each time.
62
+ const sharp = require('sharp');
75
63
  let image = sharp(Buffer.from(await source.arrayBuffer()), { ignoreIcc: conversion === 'none' });
76
64
  if (orientation !== 'none') image = image.autoOrient();
77
65
  if (orientation === 'flipY') image = image.flip();
78
66
  if (conversion === 'default') image = image.toColourspace('srgb');
79
67
  const { data, info } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
80
- if (closed) throw new Error('Image decoder is disposed');
81
68
  const premultipliedAlpha = premultiply === 'premultiply';
82
69
  if (premultipliedAlpha) for (let i = 0; i < data.length; i += 4) {
83
70
  data[i] = Math.round(data[i] * data[i + 3] / 255);
@@ -86,17 +73,5 @@ export function installImages(native) {
86
73
  }
87
74
  // The native object owns a copy; its lifetime is independent of Sharp/JS buffers.
88
75
  return native.createImageBitmapFromRGBA(info.width, info.height, data, { premultipliedAlpha, colorSpace: 'srgb' });
89
- }
90
- try {
91
- installed.set('createImageBitmap', createImageBitmap);
92
- installed.set('ImageBitmap', ImageBitmap);
93
- } catch (error) {
94
- installed.restore();
95
- throw error;
96
- }
97
- return () => {
98
- closed = true;
99
- installed.restore();
100
- if (decoder) decoder.cache(previousCache);
101
76
  };
102
77
  }
package/src/index.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ /// <reference types="@webgpu/types" />
2
+
3
+ /**
4
+ * A headless canvas with a WebGPU context. It has no layout: width and height set the output resolution, and style
5
+ * assignments are inert.
6
+ */
7
+ export interface Canvas extends EventTarget {
8
+ width: number;
9
+ height: number;
10
+ readonly style: Record<string, string>;
11
+ getContext(type: 'webgpu'): CanvasContext;
12
+ getContext(type: string): null;
13
+ /** The current frame as packed, top-row-first straight-alpha RGBA8 bytes. */
14
+ readPixels(): Promise<Uint8Array>;
15
+ /** Releases the canvas texture and rejects with the rendering errors and device loss it saw. */
16
+ dispose(): Promise<void>;
17
+ }
18
+
19
+ export interface CanvasContext extends Omit<GPUCanvasContext, 'canvas'> {
20
+ readonly canvas: Canvas;
21
+ }
22
+
23
+ export function createCanvas(width: number, height: number): Promise<Canvas>;
24
+
25
+ /** The native GPU when there is one; the bundled CPU renderer with forceFallbackAdapter or without a GPU. */
26
+ export function requestAdapter(options?: GPURequestAdapterOptions): Promise<GPUAdapter | null>;
27
+
28
+ export function getPreferredCanvasFormat(): GPUTextureFormat;
29
+
30
+ /** The straight-alpha sRGB pixels of an ImageBitmap from createImageBitmap. */
31
+ export function readImageBitmap(bitmap: ImageBitmap): Pick<ImageData, 'width' | 'height' | 'data'> & { colorSpace: 'srgb' };
package/src/index.js CHANGED
@@ -1,39 +1,20 @@
1
1
  import { canvas } from './canvas.js';
2
- import { getRuntime } from './gpu.js';
3
2
  import { readImageBitmap as readNative } from './image.js';
3
+ import { gpu, native } from './runtime.js';
4
4
 
5
- export { requestAdapter, getPreferredCanvasFormat } from './gpu.js';
5
+ export async function createCanvas(width, height) {
6
+ if (arguments.length > 2) throw new TypeError('Node canvases take no options; every Node canvas is headless');
7
+ return canvas(width, height);
8
+ }
9
+
10
+ export async function requestAdapter(options) {
11
+ return gpu.requestAdapter(options);
12
+ }
6
13
 
7
- /**
8
- * Create a headless WebGPU canvas. CSS style assignments are inert in Node;
9
- * width/height control output resolution. The offscreen option is browser-only
10
- * selection: every Node canvas is already headless.
11
- * readPixels() returns straight-alpha RGBA8. Dispose renderer/loaders before the
12
- * canvas. Canvas disposal never destroys an application-owned GPUDevice.
13
- */
14
- export async function createCanvas(width, height, { offscreen = false } = {}) {
15
- if (typeof offscreen !== 'boolean') throw new TypeError('offscreen must be a boolean');
16
- let disposal;
17
- const target = canvas(width, height, () => {
18
- if (disposal) throw new Error('Canvas is disposed');
19
- });
20
- const { native } = getRuntime();
21
- const { acquireHost } = await import('./host.js');
22
- const release = await acquireHost(native);
23
- target.output.dispose = () => disposal ??= (async () => {
24
- const failures = [];
25
- for (const action of [() => target.close(), release]) {
26
- try { await action(); } catch (error) { failures.push(error); }
27
- }
28
- if (failures.length) throw new AggregateError(failures, 'Canvas cleanup failed');
29
- })();
30
- return target.output;
14
+ export function getPreferredCanvasFormat() {
15
+ return gpu.getPreferredCanvasFormat();
31
16
  }
32
17
 
33
- /**
34
- * The straight-alpha sRGB RGBA pixels of an ImageBitmap from createImageBitmap, as ImageData's fields: what a 2D canvas
35
- * library needs to draw it, since Node has no 2D canvas of its own.
36
- */
37
18
  export function readImageBitmap(bitmap) {
38
- return readNative(getRuntime().native, bitmap);
19
+ return readNative(native, bitmap);
39
20
  }
package/src/native.js CHANGED
@@ -21,28 +21,18 @@ function directory() {
21
21
 
22
22
  export function loadNative() {
23
23
  const dir = directory();
24
- const settings = {
25
- LP_NUM_THREADS: '2',
26
- // Cold processes cannot benefit from cross-render shader reuse. Disabling the
27
- // disk cache also avoids the cached vertex-object corruption seen in Mesa 26.
28
- MESA_SHADER_CACHE_DISABLE: 'true',
29
- };
30
- const previous = new Map(Object.keys(settings).map(key => [key, process.env[key]]));
31
- const restore = () => {
32
- for (const [key, value] of previous) {
33
- if (value === undefined) delete process.env[key];
34
- else process.env[key] = value;
35
- }
36
- };
37
- Object.assign(process.env, settings);
24
+ // Mesa defaults that the user's environment overrides. The bundled CPU renderer (llvmpipe) renders with two threads.
25
+ process.env.LP_NUM_THREADS ??= '2';
26
+ // Cold processes cannot benefit from cross-render shader reuse. Disabling any Mesa driver's disk
27
+ // cache also avoids the cached vertex-object corruption seen in Mesa 26.
28
+ process.env.MESA_SHADER_CACHE_DISABLE ??= 'true';
38
29
  try {
39
30
  const native = require(join(dir, 'dawn.node'));
40
31
  if (typeof native.createImageBitmapFromRGBA !== 'function') {
41
32
  throw new Error('The native binding lacks ImageBitmap support; use the @drawcall/webgpu native build');
42
33
  }
43
- return { native, restore };
34
+ return native;
44
35
  } catch (error) {
45
- restore();
46
36
  if (error.code === 'ERR_DLOPEN_FAILED') {
47
37
  throw Object.assign(new Error(`Cannot load @drawcall/webgpu for ${process.platform}-${process.arch} on Node.js ${process.version}: ${error.message}`, { cause: error }), { code: error.code });
48
38
  }
package/src/runtime.js ADDED
@@ -0,0 +1,21 @@
1
+ import { imageBitmapFactory, installCopySources } from './image.js';
2
+ import { loadNative } from './native.js';
3
+ import { Worker } from './worker.js';
4
+
5
+ // Importing loads Dawn and installs, for the rest of the process, WebGPU as browsers expose it and the page APIs
6
+ // Three's loaders use. WebGPU, ImageBitmap and createImageBitmap replace existing definitions, since uploads need the
7
+ // native ImageBitmap; the other page APIs are added only where missing. The instance does not keep Node's event loop
8
+ // alive when no GPU operations are pending.
9
+ export const native = loadNative();
10
+ export const gpu = native.create([]);
11
+ Object.assign(globalThis, native.globals, { createImageBitmap: imageBitmapFactory(native) });
12
+ installCopySources(native);
13
+ globalThis.navigator ??= {};
14
+ Object.defineProperty(globalThis.navigator, 'gpu', { value: gpu, configurable: true });
15
+ globalThis.self ??= globalThis;
16
+ globalThis.Worker ??= Worker;
17
+ globalThis.ProgressEvent ??= class ProgressEvent extends Event {
18
+ constructor(type, values = {}) { super(type); Object.assign(this, values); }
19
+ };
20
+ globalThis.requestAnimationFrame ??= callback => setTimeout(() => callback(performance.now()));
21
+ globalThis.cancelAnimationFrame ??= clearTimeout;
package/src/worker.js CHANGED
@@ -1,14 +1,11 @@
1
- import { Worker as Thread, isMainThread, parentPort, workerData } from 'node:worker_threads';
1
+ import { MessageChannel, Worker as Thread, isMainThread, parentPort, workerData } from 'node:worker_threads';
2
2
  import { resolveObjectURL } from 'node:buffer';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { runInNewContext } from 'node:vm';
5
5
 
6
- const workers = new Set();
7
- const stopping = new Set();
8
-
9
6
  function errorEvent(error) {
10
7
  const event = new Event('error', { cancelable: true });
11
- Object.assign(event, { error, message: error.message, filename: '', lineno: 0, colno: 0 });
8
+ Object.assign(event, { error, message: String(error?.message ?? error), filename: '', lineno: 0, colno: 0 });
12
9
  return event;
13
10
  }
14
11
 
@@ -27,9 +24,12 @@ export class Worker extends EventTarget {
27
24
  const blob = location.protocol === 'blob:' ? resolveObjectURL(location.href) : undefined;
28
25
  if (location.protocol === 'blob:' && !blob) throw new DOMException('Unknown Blob URL', 'NetworkError');
29
26
  if (!['blob:', 'data:', 'file:', 'http:', 'https:'].includes(location.protocol)) throw new TypeError('Unsupported Worker URL protocol');
27
+ // The thread reports its uncaught errors on their own channel, apart from the script's messages.
28
+ const { port1: errors, port2 } = new MessageChannel();
30
29
  // Classic workers do not inherit Node CLI flags such as --input-type.
31
- this.#thread = new Thread(new URL(import.meta.url), { execArgv: [], workerData: { workerHost: true, blob, url: location.href, name } });
32
- workers.add(this);
30
+ this.#thread = new Thread(new URL(import.meta.url), {
31
+ execArgv: [], workerData: { workerHost: true, blob, url: location.href, name, errors: port2 }, transferList: [port2],
32
+ });
33
33
  for (const type of ['message', 'messageerror', 'error']) {
34
34
  this.addEventListener(type, event => {
35
35
  if (this['on' + type]?.call(this, event) === true && type === 'error') event.preventDefault();
@@ -37,11 +37,13 @@ export class Worker extends EventTarget {
37
37
  }
38
38
  this.#thread.on('message', data => this.dispatchEvent(new MessageEvent('message', { data })));
39
39
  this.#thread.on('messageerror', error => this.dispatchEvent(new MessageEvent('messageerror', { data: error })));
40
- this.#thread.on('error', error => {
41
- // An unhandled decoder failure must stop a pending loader, not hang it.
42
- if (this.dispatchEvent(errorEvent(error))) throw error;
43
- });
44
- this.#thread.on('exit', () => workers.delete(this));
40
+ // As in browsers, an error no listener cancels is logged, not thrown into the caller's process.
41
+ const report = error => {
42
+ if (this.dispatchEvent(errorEvent(error))) console.error('Uncaught error in Worker', error);
43
+ };
44
+ errors.on('message', report);
45
+ errors.unref();
46
+ this.#thread.on('error', report);
45
47
  }
46
48
  postMessage(message, options = []) {
47
49
  if (this.#stopped) return;
@@ -50,31 +52,33 @@ export class Worker extends EventTarget {
50
52
  terminate() {
51
53
  if (this.#stopped) return;
52
54
  this.#stopped = true;
53
- const pending = this.#thread.terminate();
54
- stopping.add(pending);
55
- pending.then(() => stopping.delete(pending), error => { stopping.delete(pending); throw error; });
55
+ this.#thread.terminate();
56
56
  }
57
57
  }
58
58
 
59
- export function installWorkers() {
60
- const previous = Object.getOwnPropertyDescriptor(globalThis, 'Worker');
61
- Object.defineProperty(globalThis, 'Worker', { value: Worker, configurable: true, writable: true });
62
- return async () => {
59
+ if (!isMainThread && workerData?.workerHost) {
60
+ const { blob, url, name, errors } = workerData;
61
+ // As in browsers, an uncaught error reaches the Worker's error listeners and the worker keeps running.
62
+ // Errors are cloned to the host; a value that cannot be is reported as its string.
63
+ const report = error => {
63
64
  try {
64
- for (const worker of workers) worker.terminate();
65
- await Promise.all(stopping);
66
- } finally {
67
- if (previous) Object.defineProperty(globalThis, 'Worker', previous);
68
- else delete globalThis.Worker;
65
+ errors.postMessage(error);
66
+ } catch {
67
+ errors.postMessage(String(error));
69
68
  }
70
69
  };
71
- }
72
-
73
- if (!isMainThread && workerData?.workerHost) {
74
- const { blob, url, name } = workerData;
70
+ // Node 22 emits uncaughtException twice in a row for each error in a worker thread, before any microtask runs.
71
+ const none = Symbol('none');
72
+ let current = none;
73
+ process.on('uncaughtException', error => {
74
+ if (error === current) return;
75
+ current = error;
76
+ queueMicrotask(() => { current = none; });
77
+ report(error);
78
+ });
75
79
  const events = new EventTarget();
76
80
  const scope = {
77
- name, location: new URL(url), onmessage: null, onmessageerror: null, onerror: null,
81
+ name, location: new URL(url), onmessage: null, onmessageerror: null,
78
82
  console, performance, crypto, fetch, URL, URLSearchParams, Blob, TextEncoder, TextDecoder,
79
83
  Event, EventTarget, MessageEvent, DOMException, WebAssembly, atob, btoa,
80
84
  setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask,
@@ -90,7 +94,11 @@ if (!isMainThread && workerData?.workerHost) {
90
94
  if (!response.ok) throw new Error('Worker script HTTP ' + response.status);
91
95
  return response.text();
92
96
  });
93
- runInNewContext(source, scope, { filename: url });
97
+ try {
98
+ runInNewContext(source, scope, { filename: url });
99
+ } catch (error) {
100
+ report(error);
101
+ }
94
102
  parentPort.on('message', data => {
95
103
  const event = new MessageEvent('message', { data });
96
104
  scope.onmessage?.call(scope, event);
package/src/globals.js DELETED
@@ -1,15 +0,0 @@
1
- export function globals() {
2
- const previous = new Map();
3
- return {
4
- set(name, value) {
5
- if (!previous.has(name)) previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
6
- Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
7
- },
8
- restore() {
9
- for (const [name, descriptor] of previous) {
10
- if (descriptor) Object.defineProperty(globalThis, name, descriptor);
11
- else delete globalThis[name];
12
- }
13
- },
14
- };
15
- }
package/src/gpu.js DELETED
@@ -1,42 +0,0 @@
1
- import { globals } from './globals.js';
2
- import { installCopySources } from './image.js';
3
- import { loadNative } from './native.js';
4
-
5
- let runtime;
6
-
7
- // Keep Dawn's instance alive independently of canvases and devices. It does not
8
- // keep Node's event loop alive when no GPU operations are pending.
9
- export function getRuntime() {
10
- if (runtime) return runtime;
11
- const installed = globals();
12
- const loaded = loadNative();
13
- try {
14
- const gpu = loaded.native.create([]);
15
- for (const [name, value] of Object.entries(loaded.native.globals)) {
16
- if (name !== 'ImageBitmap') installed.set(name, value);
17
- }
18
- installCopySources(loaded.native);
19
- const navigator = globalThis.navigator ?? {};
20
- Object.defineProperty(navigator, 'gpu', { value: gpu, configurable: true });
21
- if (!globalThis.navigator) installed.set('navigator', navigator);
22
- runtime = { gpu, native: loaded.native };
23
- return runtime;
24
- } catch (error) {
25
- installed.restore();
26
- loaded.restore();
27
- throw error;
28
- }
29
- }
30
-
31
- /**
32
- * Select an adapter using standard GPURequestAdapterOptions. Native GPUs rank first;
33
- * the bundled CPU renderer is the fallback adapter (forceFallbackAdapter: true).
34
- */
35
- export async function requestAdapter(options) {
36
- return getRuntime().gpu.requestAdapter(options);
37
- }
38
-
39
- /** Preferred canvas format of the active WebGPU implementation. */
40
- export function getPreferredCanvasFormat() {
41
- return getRuntime().gpu.getPreferredCanvasFormat();
42
- }
package/src/host.js DELETED
@@ -1,62 +0,0 @@
1
- import { globals } from './globals.js';
2
- import { installImages } from './image.js';
3
- import { installWorkers } from './worker.js';
4
-
5
- let host;
6
- let closing;
7
-
8
- // Only canvases need loader and animation support; compute leaves it untouched.
9
- export async function acquireHost(native) {
10
- while (closing) await closing;
11
- host ??= install(native);
12
- const current = host;
13
- current.users++;
14
- let released = false;
15
- return async () => {
16
- if (released) return;
17
- released = true;
18
- if (--current.users) return;
19
- host = undefined;
20
- closing = current.close().finally(() => { closing = undefined; });
21
- await closing;
22
- };
23
- }
24
-
25
- function install(native) {
26
- const installed = globals();
27
- const frames = new Set();
28
- let restoreImages, restoreWorkers;
29
- async function close() {
30
- const failures = [];
31
- for (const action of [
32
- () => { for (const frame of frames) clearTimeout(frame); frames.clear(); },
33
- () => restoreWorkers?.(),
34
- () => restoreImages?.(),
35
- () => installed.restore(),
36
- ]) {
37
- try { await action(); } catch (error) { failures.push(error); }
38
- }
39
- if (failures.length) throw new AggregateError(failures, 'Canvas platform cleanup failed');
40
- }
41
- try {
42
- installed.set('self', globalThis);
43
- installed.set('ProgressEvent', class extends Event {
44
- constructor(type, values = {}) { super(type); Object.assign(this, values); }
45
- });
46
- installed.set('requestAnimationFrame', callback => {
47
- const frame = setTimeout(() => { frames.delete(frame); callback(performance.now()); });
48
- frames.add(frame);
49
- return frame;
50
- });
51
- installed.set('cancelAnimationFrame', frame => { clearTimeout(frame); frames.delete(frame); });
52
- restoreImages = installImages(native);
53
- restoreWorkers = installWorkers();
54
- return { users: 0, close };
55
- } catch (error) {
56
- // Installation is synchronous; these restorations do not need worker teardown
57
- // unless installWorkers completed, after which installation cannot fail.
58
- restoreImages?.();
59
- installed.restore();
60
- throw error;
61
- }
62
- }