0
# GPU Interfaces
1
2
Main WebGPU interfaces including the root GPU object, adapters, and devices that provide the foundation for GPU access and resource management.
3
4
## Capabilities
5
6
### GPU Root Interface
7
8
The main entry point for WebGPU functionality, accessed through `navigator.gpu`.
9
10
```typescript { .api }
11
interface GPU {
12
/**
13
* Requests a GPU adapter with optional configuration
14
* @param options - Optional adapter selection criteria
15
* @returns Promise resolving to adapter or null if unavailable
16
*/
17
requestAdapter(options?: GPURequestAdapterOptions): Promise<GPUAdapter | null>;
18
19
/**
20
* Gets the preferred canvas format for the current platform
21
* @returns The recommended texture format for canvas contexts
22
*/
23
getPreferredCanvasFormat(): GPUTextureFormat;
24
25
/** Set of WGSL language features supported by the implementation */
26
readonly wgslLanguageFeatures: WGSLLanguageFeatures;
27
}
28
29
interface GPURequestAdapterOptions {
30
powerPreference?: GPUPowerPreference;
31
forceFallbackAdapter?: boolean;
32
}
33
```
34
35
### GPU Adapter Interface
36
37
Represents a GPU adapter with information about capabilities and limits.
38
39
```typescript { .api }
40
interface GPUAdapter {
41
/** Set of features supported by this adapter */
42
readonly features: GPUSupportedFeatures;
43
44
/** Limits and capabilities of this adapter */
45
readonly limits: GPUSupportedLimits;
46
47
/** Information about the adapter hardware */
48
readonly info: GPUAdapterInfo;
49
50
/**
51
* Requests a logical device from this adapter
52
* @param descriptor - Optional device configuration
53
* @returns Promise resolving to the device
54
*/
55
requestDevice(descriptor?: GPUDeviceDescriptor): Promise<GPUDevice>;
56
}
57
58
interface GPUDeviceDescriptor extends GPUObjectDescriptorBase {
59
requiredFeatures?: Iterable<GPUFeatureName>;
60
requiredLimits?: Record<string, GPUSize64>;
61
defaultQueue?: GPUQueueDescriptor;
62
}
63
64
interface GPUQueueDescriptor extends GPUObjectDescriptorBase {}
65
```
66
67
### GPU Adapter Information
68
69
Detailed information about the GPU hardware and driver.
70
71
```typescript { .api }
72
interface GPUAdapterInfo {
73
/** The name of the vendor of the adapter, if available. Empty string otherwise. */
74
readonly vendor: string;
75
76
/** The name of the family or class of GPUs the adapter belongs to, if available. Empty string otherwise. */
77
readonly architecture: string;
78
79
/** A vendor-specific identifier for the adapter, if available. Empty string otherwise. */
80
readonly device: string;
81
82
/** A human readable string describing the adapter as reported by the driver, if available. Empty string otherwise. */
83
readonly description: string;
84
85
/** If the "subgroups" feature is supported, the minimum supported subgroup size for the adapter. */
86
readonly subgroupMinSize?: number;
87
88
/** If the "subgroups" feature is supported, the maximum supported subgroup size for the adapter. */
89
readonly subgroupMaxSize?: number;
90
91
/** Whether the adapter is a fallback adapter. */
92
readonly isFallbackAdapter: boolean;
93
}
94
```
95
96
### GPU Device Interface
97
98
The main logical device interface for creating resources and submitting commands.
99
100
```typescript { .api }
101
interface GPUDevice extends EventTarget, GPUObjectBase {
102
/** Set of features available on this device */
103
readonly features: GPUSupportedFeatures;
104
105
/** Limits and capabilities of this device */
106
readonly limits: GPUSupportedLimits;
107
108
/** Information about the physical adapter which created this device */
109
readonly adapterInfo: GPUAdapterInfo;
110
111
/** Default queue for command submission */
112
readonly queue: GPUQueue;
113
114
/** Current device state */
115
readonly lost: Promise<GPUDeviceLostInfo>;
116
117
/** Destroys the device and releases resources */
118
destroy(): void;
119
120
// Resource creation methods
121
createBuffer(descriptor: GPUBufferDescriptor): GPUBuffer;
122
createTexture(descriptor: GPUTextureDescriptor): GPUTexture;
123
createSampler(descriptor?: GPUSamplerDescriptor): GPUSampler;
124
125
/**
126
* Creates a GPUExternalTexture wrapping the provided image source
127
* @param descriptor - Provides the external image source object and any creation options
128
*/
129
importExternalTexture(descriptor: GPUExternalTextureDescriptor): GPUExternalTexture;
130
131
// Binding and layout creation
132
createBindGroupLayout(descriptor: GPUBindGroupLayoutDescriptor): GPUBindGroupLayout;
133
createPipelineLayout(descriptor: GPUPipelineLayoutDescriptor): GPUPipelineLayout;
134
createBindGroup(descriptor: GPUBindGroupDescriptor): GPUBindGroup;
135
136
// Shader and pipeline creation
137
createShaderModule(descriptor: GPUShaderModuleDescriptor): GPUShaderModule;
138
createComputePipeline(descriptor: GPUComputePipelineDescriptor): GPUComputePipeline;
139
createRenderPipeline(descriptor: GPURenderPipelineDescriptor): GPURenderPipeline;
140
createComputePipelineAsync(descriptor: GPUComputePipelineDescriptor): Promise<GPUComputePipeline>;
141
createRenderPipelineAsync(descriptor: GPURenderPipelineDescriptor): Promise<GPURenderPipeline>;
142
143
// Command recording
144
createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): GPUCommandEncoder;
145
createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): GPURenderBundleEncoder;
146
147
// Query creation
148
createQuerySet(descriptor: GPUQuerySetDescriptor): GPUQuerySet;
149
150
// Error handling
151
pushErrorScope(filter: GPUErrorFilter): void;
152
popErrorScope(): Promise<GPUError | null>;
153
154
// Event handling for uncaptured errors
155
addEventListener<K extends keyof __GPUDeviceEventMap>(
156
type: K,
157
listener: (this: GPUDevice, ev: __GPUDeviceEventMap[K]) => any,
158
options?: boolean | AddEventListenerOptions
159
): void;
160
addEventListener(
161
type: string,
162
listener: EventListenerOrEventListenerObject,
163
options?: boolean | AddEventListenerOptions
164
): void;
165
removeEventListener<K extends keyof __GPUDeviceEventMap>(
166
type: K,
167
listener: (this: GPUDevice, ev: __GPUDeviceEventMap[K]) => any,
168
options?: boolean | EventListenerOptions
169
): void;
170
removeEventListener(
171
type: string,
172
listener: EventListenerOrEventListenerObject,
173
options?: boolean | EventListenerOptions
174
): void;
175
}
176
177
interface __GPUDeviceEventMap {
178
uncapturederror: GPUUncapturedErrorEvent;
179
}
180
181
type GPUErrorFilter = "validation" | "out-of-memory" | "internal";
182
```
183
184
### GPU Queue Interface
185
186
Command queue for submitting work to the GPU.
187
188
```typescript { .api }
189
interface GPUQueue {
190
readonly label: string | undefined;
191
192
/**
193
* Submits command buffers for execution
194
* @param commandBuffers - Array of command buffers to execute
195
*/
196
submit(commandBuffers: Iterable<GPUCommandBuffer>): void;
197
198
/**
199
* Handles promise returned by buffer.mapAsync()
200
* @param buffer - Buffer that was mapped
201
*/
202
onSubmittedWorkDone(): Promise<void>;
203
204
/**
205
* Writes data directly to a buffer
206
* @param buffer - Target buffer
207
* @param bufferOffset - Offset in the buffer
208
* @param data - Source data
209
* @param dataOffset - Offset in source data (in elements)
210
* @param size - Number of bytes to write
211
*/
212
writeBuffer(
213
buffer: GPUBuffer,
214
bufferOffset: GPUSize64,
215
data: GPUAllowSharedBufferSource,
216
dataOffset?: GPUSize64,
217
size?: GPUSize64
218
): void;
219
220
/**
221
* Writes data directly to a texture
222
* @param destination - Target texture and layout
223
* @param data - Source data
224
* @param dataLayout - Data layout in the source
225
* @param size - Size of the data to copy
226
*/
227
writeTexture(
228
destination: GPUTexelCopyTextureInfo,
229
data: GPUAllowSharedBufferSource,
230
dataLayout: GPUTexelCopyBufferLayout,
231
size: GPUExtent3D
232
): void;
233
234
/**
235
* Copies an image from an external source to a texture
236
* @param source - External image source
237
* @param destination - Target texture
238
* @param copySize - Size of the region to copy
239
*/
240
copyExternalImageToTexture(
241
source: GPUCopyExternalImageSourceInfo,
242
destination: GPUCopyExternalImageDestInfo,
243
copySize: GPUExtent3D
244
): void;
245
}
246
```
247
248
### GPU Canvas Context
249
250
Context for WebGPU rendering to HTML canvas elements.
251
252
```typescript { .api }
253
interface GPUCanvasContext {
254
readonly canvas: HTMLCanvasElement | OffscreenCanvas;
255
256
/**
257
* Configures the context for rendering
258
* @param configuration - Canvas configuration options
259
*/
260
configure(configuration: GPUCanvasConfiguration): void;
261
262
/** Returns the context configuration */
263
getConfiguration(): GPUCanvasConfigurationOut | null;
264
265
/** Unconfigures the context */
266
unconfigure(): void;
267
268
/**
269
* Gets the current texture for rendering
270
* @returns Texture representing the current frame
271
*/
272
getCurrentTexture(): GPUTexture;
273
}
274
275
interface GPUCanvasConfiguration {
276
device: GPUDevice;
277
format: GPUTextureFormat;
278
usage?: GPUTextureUsageFlags;
279
colorSpace?: GPUCanvasColorSpace;
280
toneMapping?: GPUCanvasToneMapping;
281
alphaMode?: GPUCanvasAlphaMode;
282
}
283
284
type GPUCanvasColorSpace = "srgb" | "display-p3";
285
type GPUCanvasAlphaMode = "opaque" | "premultiplied";
286
287
interface GPUCanvasToneMapping {
288
mode?: GPUCanvasToneMappingMode;
289
}
290
291
type GPUCanvasToneMappingMode = "standard" | "extended";
292
```
293
294
### Supported Features and Limits
295
296
Information about device capabilities.
297
298
```typescript { .api }
299
type GPUSupportedFeatures = ReadonlySet<string>;
300
301
interface GPUSupportedLimits {
302
readonly maxTextureDimension1D: number;
303
readonly maxTextureDimension2D: number;
304
readonly maxTextureDimension3D: number;
305
readonly maxTextureArrayLayers: number;
306
readonly maxBindGroups: number;
307
readonly maxBindGroupsPlusVertexBuffers: number;
308
readonly maxBindingsPerBindGroup: number;
309
readonly maxDynamicUniformBuffersPerPipelineLayout: number;
310
readonly maxDynamicStorageBuffersPerPipelineLayout: number;
311
readonly maxSampledTexturesPerShaderStage: number;
312
readonly maxSamplersPerShaderStage: number;
313
readonly maxStorageBuffersPerShaderStage: number;
314
readonly maxStorageTexturesPerShaderStage: number;
315
readonly maxUniformBuffersPerShaderStage: number;
316
readonly maxUniformBufferBindingSize: number;
317
readonly maxStorageBufferBindingSize: number;
318
readonly minUniformBufferOffsetAlignment: number;
319
readonly minStorageBufferOffsetAlignment: number;
320
readonly maxVertexBuffers: number;
321
readonly maxBufferSize: number;
322
readonly maxVertexAttributes: number;
323
readonly maxVertexBufferArrayStride: number;
324
readonly maxInterStageShaderComponents: number;
325
readonly maxInterStageShaderVariables: number;
326
readonly maxColorAttachments: number;
327
readonly maxColorAttachmentBytesPerSample: number;
328
readonly maxComputeWorkgroupStorageSize: number;
329
readonly maxComputeInvocationsPerWorkgroup: number;
330
readonly maxComputeWorkgroupSizeX: number;
331
readonly maxComputeWorkgroupSizeY: number;
332
readonly maxComputeWorkgroupSizeZ: number;
333
readonly maxComputeWorkgroupsPerDimension: number;
334
}
335
```
336
337
### Device Lost Information
338
339
Information about device loss events.
340
341
```typescript { .api }
342
interface GPUDeviceLostInfo {
343
/** Reason for device loss */
344
readonly reason: GPUDeviceLostReason;
345
346
/** Human-readable message about the loss */
347
readonly message: string;
348
}
349
350
type GPUDeviceLostReason = "unknown" | "destroyed";
351
```
352
353
### Error Types
354
355
Complete error hierarchy for WebGPU error handling.
356
357
```typescript { .api }
358
interface GPUError {
359
/** Human-readable error message for debugging */
360
readonly message: string;
361
}
362
363
interface GPUInternalError extends GPUError {
364
/** @internal */
365
readonly __brand: "GPUInternalError";
366
}
367
368
interface GPUOutOfMemoryError extends GPUError {
369
/** @internal */
370
readonly __brand: "GPUOutOfMemoryError";
371
}
372
373
interface GPUPipelineError extends DOMException {
374
/** @internal */
375
readonly __brand: "GPUPipelineError";
376
377
/** The type of error encountered in pipeline creation */
378
readonly reason: GPUPipelineErrorReason;
379
}
380
381
interface GPUValidationError extends GPUError {
382
/** @internal */
383
readonly __brand: "GPUValidationError";
384
}
385
386
interface GPUUncapturedErrorEvent extends Event {
387
/** @internal */
388
readonly __brand: "GPUUncapturedErrorEvent";
389
390
/** The uncaptured error */
391
readonly error: GPUError;
392
}
393
394
interface GPUUncapturedErrorEventInit extends EventInit {
395
error: GPUError;
396
}
397
398
type GPUPipelineErrorReason = "validation" | "internal";
399
400
interface GPUPipelineErrorInit {
401
reason: GPUPipelineErrorReason;
402
}
403
```
404
405
### Navigator Integration
406
407
Extensions to the Navigator interface for WebGPU access.
408
409
```typescript { .api }
410
interface NavigatorGPU {
411
readonly gpu: GPU;
412
}
413
414
interface Navigator extends NavigatorGPU {}
415
interface WorkerNavigator extends NavigatorGPU {}
416
```
417
418
## Usage Examples
419
420
### Basic GPU Access
421
422
```typescript
423
// Check for WebGPU support
424
if (!navigator.gpu) {
425
throw new Error("WebGPU not supported");
426
}
427
428
// Get the GPU interface
429
const gpu: GPU = navigator.gpu;
430
431
// Request an adapter
432
const adapter: GPUAdapter | null = await gpu.requestAdapter({
433
powerPreference: "high-performance"
434
});
435
436
if (!adapter) {
437
throw new Error("No suitable GPU adapter found");
438
}
439
440
// Check adapter capabilities
441
console.log("Supported features:", Array.from(adapter.features));
442
console.log("Max texture size:", adapter.limits.maxTextureDimension2D);
443
```
444
445
### Device Creation and Configuration
446
447
```typescript
448
// Request a device with specific features
449
const device: GPUDevice = await adapter.requestDevice({
450
requiredFeatures: ["timestamp-query", "depth-clip-control"],
451
requiredLimits: {
452
maxBufferSize: 1024 * 1024 * 1024, // Request 1GB max buffer size
453
maxTextureDimension2D: 8192 // Request support for 8K textures
454
}
455
});
456
457
// Set up error handling
458
device.addEventListener("uncapturederror", (event) => {
459
console.error("Uncaptured WebGPU error:", event.error);
460
});
461
462
// Push error scope for validation errors
463
device.pushErrorScope("validation");
464
465
// ... GPU operations ...
466
467
// Check for validation errors
468
const error = await device.popErrorScope();
469
if (error) {
470
console.error("Validation error:", error.message);
471
}
472
```
473
474
### Canvas Setup
475
476
```typescript
477
// Get canvas and context
478
const canvas = document.querySelector("canvas") as HTMLCanvasElement;
479
const context: GPUCanvasContext = canvas.getContext("webgpu")!;
480
481
// Configure canvas for rendering
482
context.configure({
483
device,
484
format: gpu.getPreferredCanvasFormat(),
485
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
486
alphaMode: "premultiplied"
487
});
488
489
// Get current frame texture
490
const currentTexture: GPUTexture = context.getCurrentTexture();
491
```
492
493
### Queue Operations
494
495
```typescript
496
// Write data directly to buffer
497
const data = new Float32Array([1, 2, 3, 4]);
498
device.queue.writeBuffer(
499
buffer,
500
0, // offset
501
data.buffer,
502
0, // data offset
503
data.byteLength
504
);
505
506
// Submit command buffers
507
const commandBuffer = commandEncoder.finish();
508
device.queue.submit([commandBuffer]);
509
510
// Wait for submitted work to complete
511
await device.queue.onSubmittedWorkDone();
512
```
513
514
### Feature Detection
515
516
```typescript
517
// Check for optional features
518
const requiredFeatures: GPUFeatureName[] = [
519
"depth-clip-control",
520
"timestamp-query",
521
"texture-compression-bc"
522
];
523
524
const hasAllFeatures = requiredFeatures.every(feature =>
525
adapter.features.has(feature)
526
);
527
528
if (hasAllFeatures) {
529
console.log("All required features supported");
530
} else {
531
console.warn("Some features not available");
532
}
533
534
// Check specific limits
535
const limits = adapter.limits;
536
if (limits.maxTextureDimension2D >= 4096) {
537
console.log("4K textures supported");
538
}
539
540
if (limits.maxComputeWorkgroupSizeX >= 1024) {
541
console.log("Large compute workgroups supported");
542
}
543
```