• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

visgl / luma.gl / 29586628011

17 Jul 2026 02:06PM UTC coverage: 72.414%. First build
29586628011

Pull #2742

github

web-flow
Merge 7723ea416 into 01dd287e7
Pull Request #2742: fix(core): manage device canvas context lifecycle

11344 of 17638 branches covered (64.32%)

Branch coverage included in aggregate %.

116 of 129 new or added lines in 13 files covered. (89.92%)

21991 of 28396 relevant lines covered (77.44%)

5583.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.56
/modules/webgpu/src/adapter/webgpu-device.ts
1
// luma.gl
2
// SPDX-License-Identifier: MIT
3
// Copyright (c) vis.gl contributors
4

5
// biome-ignore format: preserve layout
6
// / <reference types="@webgpu/types" />
7

8
import type {
9
  Bindings,
10
  ComputePipeline,
11
  ComputeShaderLayout,
12
  DeviceInfo,
13
  DeviceLimits,
14
  DeviceFeature,
15
  DeviceTextureFormatCapabilities,
16
  VertexFormat,
17
  CanvasContextProps,
18
  PresentationContextProps,
19
  PresentationContext,
20
  BufferProps,
21
  SamplerProps,
22
  ShaderProps,
23
  TextureProps,
24
  Texture,
25
  ExternalTextureProps,
26
  FramebufferProps,
27
  RenderPipelineProps,
28
  ComputePipelineProps,
29
  VertexArrayProps,
30
  TransformFeedback,
31
  TransformFeedbackProps,
32
  QuerySet,
33
  QuerySetProps,
34
  DeviceProps,
35
  CommandEncoderProps,
36
  CommandEncoder,
37
  PipelineLayoutProps,
38
  RenderPipeline,
39
  RenderBundleEncoderProps,
40
  ShaderLayout
41
} from '@luma.gl/core';
42
import {Buffer, Device, DeviceFeatures, isHTMLInCanvasSupported} from '@luma.gl/core';
43
import {WebGPUBuffer} from './resources/webgpu-buffer';
44
import {WebGPUTexture} from './resources/webgpu-texture';
45
import {WebGPUExternalTexture} from './resources/webgpu-external-texture';
46
import {WebGPUSampler, type WebGPUSamplerProps} from './resources/webgpu-sampler';
47
import {WebGPUShader} from './resources/webgpu-shader';
48
import {WebGPURenderPipeline} from './resources/webgpu-render-pipeline';
49
import {WebGPURenderBundleEncoder} from './resources/webgpu-render-bundle';
50
import {WebGPUFramebuffer} from './resources/webgpu-framebuffer';
51
import {WebGPUComputePipeline} from './resources/webgpu-compute-pipeline';
52
import {WebGPUVertexArray} from './resources/webgpu-vertex-array';
53

54
import {WebGPUCanvasContext} from './webgpu-canvas-context';
55
import {WebGPUPresentationContext} from './webgpu-presentation-context';
56
import {WebGPUCommandEncoder} from './resources/webgpu-command-encoder';
57
import {WebGPUCommandBuffer} from './resources/webgpu-command-buffer';
58
import {WebGPUQuerySet} from './resources/webgpu-query-set';
59
import {WebGPUPipelineLayout} from './resources/webgpu-pipeline-layout';
60
import {WebGPUFence} from './resources/webgpu-fence';
61

62
import {getShaderLayoutFromWGSL} from '../wgsl/get-shader-layout-wgsl';
63
import {generateMipmapsWebGPU} from './helpers/generate-mipmaps-webgpu';
64
import {getBindGroup} from './helpers/get-bind-group';
65
import {
66
  getCpuHotspotProfiler as getWebGPUCpuHotspotProfiler,
67
  getCpuHotspotSubmitReason as getWebGPUCpuHotspotSubmitReason,
68
  getTimestamp
69
} from './helpers/cpu-hotspot-profiler';
70

71
/** WebGPU Device implementation */
72
export class WebGPUDevice extends Device {
73
  /** The underlying WebGPU device */
74
  readonly handle: GPUDevice;
75
  /* The underlying WebGPU adapter */
76
  readonly adapter: GPUAdapter;
77
  /* The underlying WebGPU adapter's info */
78
  readonly adapterInfo: GPUAdapterInfo;
79

80
  /** type of this device */
81
  readonly type = 'webgpu';
72✔
82

83
  readonly preferredColorFormat = navigator.gpu.getPreferredCanvasFormat() as
72✔
84
    | 'rgba8unorm'
85
    | 'bgra8unorm';
86
  readonly preferredDepthFormat = 'depth24plus';
72✔
87

88
  readonly features: DeviceFeatures;
89
  readonly info: DeviceInfo;
90
  readonly limits: DeviceLimits;
91

92
  readonly lost: Promise<{reason: 'destroyed'; message: string}>;
93

94
  override canvasContext: WebGPUCanvasContext | null = null;
72✔
95

96
  private readonly _lostState = {isLost: false};
72✔
97
  private _defaultSampler: WebGPUSampler | null = null;
72✔
98
  private readonly _onUncapturedError = (event: Event) => {
72✔
NEW
99
    event.preventDefault();
×
100
    // TODO is this the right way to make sure the error is an Error instance?
101
    const errorMessage =
NEW
102
      event instanceof GPUUncapturedErrorEvent ? event.error.message : 'Unknown WebGPU error';
×
NEW
103
    this.reportError(new Error(errorMessage), this)();
×
NEW
104
    this.debug();
×
105
  };
106
  commandEncoder: WebGPUCommandEncoder;
107

108
  override get [Symbol.toStringTag](): string {
109
    return 'WebGPUDevice';
×
110
  }
111

112
  override toString(): string {
113
    return `WebGPUDevice(${this.id})`;
2✔
114
  }
115

116
  constructor(
117
    props: DeviceProps,
118
    device: GPUDevice,
119
    adapter: GPUAdapter,
120
    adapterInfo: GPUAdapterInfo
121
  ) {
122
    super({...props, id: props.id || 'webgpu-device'});
72✔
123
    this.handle = device;
72✔
124
    this.adapter = adapter;
72✔
125
    this.adapterInfo = adapterInfo;
72✔
126

127
    this.info = this._getInfo();
72✔
128
    this.features = this._getFeatures();
72✔
129
    this.limits = getWebGPUDeviceLimits(this.handle.limits);
72✔
130

131
    // Listen for uncaptured WebGPU errors
132
    device.addEventListener('uncapturederror', this._onUncapturedError);
72✔
133

134
    // "Context" loss handling
135
    const lostState = this._lostState;
72✔
136
    this.lost = this.handle.lost.then(lostInfo => {
72✔
137
      lostState.isLost = true;
7✔
138
      return {reason: 'destroyed', message: lostInfo.message};
7✔
139
    });
140

141
    // Note: WebGPU devices can be created without a canvas, for compute shader purposes
142
    const canvasContextProps = Device._getCanvasContextProps(props);
72✔
143
    if (canvasContextProps) {
72!
144
      this.canvasContext = this._registerCanvasSurface(
72✔
145
        new WebGPUCanvasContext(this, this.adapter, canvasContextProps)
146
      );
147
    }
148

149
    this.commandEncoder = this.createCommandEncoder({});
72✔
150
  }
151

152
  // TODO
153
  // Load the glslang module now so that it is available synchronously when compiling shaders
154
  // const {glsl = true} = props;
155
  // this.glslang = glsl && await loadGlslangModule();
156

157
  destroy(): void {
158
    if (!this._releaseDeviceReference()) {
1!
NEW
159
      return;
×
160
    }
161

162
    this._finalizeDevice({destroyHandle: this._ownsHandle});
1✔
163
  }
164

165
  override detach(): GPUDevice {
NEW
166
    this._detachDeviceReference();
×
NEW
167
    this._finalizeDevice({destroyHandle: false});
×
NEW
168
    return this.handle;
×
169
  }
170

171
  private _finalizeDevice(options: {destroyHandle: boolean}): void {
172
    this.handle.removeEventListener('uncapturederror', this._onUncapturedError);
1✔
173
    this._destroyCanvasSurfaces();
1✔
174
    this.commandEncoder?.destroy();
1✔
175
    this._defaultSampler?.destroy();
1✔
176
    this._defaultSampler = null;
1✔
177
    if (options.destroyHandle) {
1!
178
      this.handle.destroy();
1✔
179
    }
180
  }
181

182
  get isLost(): boolean {
183
    return this._lostState.isLost;
288✔
184
  }
185

186
  getShaderLayout(source: string) {
187
    return getShaderLayoutFromWGSL(source);
688✔
188
  }
189

190
  override isVertexFormatSupported(format: VertexFormat): boolean {
191
    const info = this.getVertexFormatInfo(format);
×
192
    return !info.webglOnly;
×
193
  }
194

195
  createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): WebGPUBuffer {
196
    const newProps = this._normalizeBufferProps(props);
1,241✔
197
    return new WebGPUBuffer(this, newProps);
1,241✔
198
  }
199

200
  createTexture(props: TextureProps): WebGPUTexture {
201
    return new WebGPUTexture(this, props);
296✔
202
  }
203

204
  createExternalTexture(props: ExternalTextureProps): WebGPUExternalTexture {
205
    return new WebGPUExternalTexture(this, props);
1✔
206
  }
207

208
  createShader(props: ShaderProps): WebGPUShader {
209
    return new WebGPUShader(this, props);
397✔
210
  }
211

212
  createSampler(props: SamplerProps): WebGPUSampler {
213
    return new WebGPUSampler(this, props as WebGPUSamplerProps);
13✔
214
  }
215

216
  getDefaultSampler(): WebGPUSampler {
217
    this._defaultSampler ||= new WebGPUSampler(this, {
223✔
218
      id: `${this.id}-default-sampler`
219
    });
220
    return this._defaultSampler;
223✔
221
  }
222

223
  createRenderPipeline(props: RenderPipelineProps): WebGPURenderPipeline {
224
    return new WebGPURenderPipeline(this, props);
84✔
225
  }
226

227
  createFramebuffer(props: FramebufferProps): WebGPUFramebuffer {
228
    return new WebGPUFramebuffer(this, props);
137✔
229
  }
230

231
  createComputePipeline(props: ComputePipelineProps): WebGPUComputePipeline {
232
    return new WebGPUComputePipeline(this, props);
284✔
233
  }
234

235
  /** Creates an encoder for reusable WebGPU draw commands. */
236
  createRenderBundleEncoder(props: RenderBundleEncoderProps = {}): WebGPURenderBundleEncoder {
×
237
    return new WebGPURenderBundleEncoder(this, props);
5✔
238
  }
239

240
  createVertexArray(props: VertexArrayProps): WebGPUVertexArray {
241
    return new WebGPUVertexArray(this, props);
88✔
242
  }
243

244
  override createCommandEncoder(props?: CommandEncoderProps): WebGPUCommandEncoder {
245
    return new WebGPUCommandEncoder(this, props);
370✔
246
  }
247

248
  override writeBufferViaCommandEncoder(
249
    commandEncoder: CommandEncoder,
250
    destinationBuffer: Buffer,
251
    data: ArrayBufferLike | ArrayBufferView | SharedArrayBuffer,
252
    byteOffset: number = 0
52✔
253
  ): void {
254
    const webgpuCommandEncoder = commandEncoder as WebGPUCommandEncoder;
52✔
255
    const uploadData = ArrayBuffer.isView(data)
52!
256
      ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
257
      : new Uint8Array(data);
258
    // WebGPU cannot encode CPU writes directly on a command encoder. Record the
259
    // upload as a staging-buffer copy so it stays ordered with the draw/dispatch
260
    // commands that will consume the destination buffer.
261
    const uploadBuffer = this.createBuffer({
52✔
262
      usage: Buffer.COPY_SRC,
263
      data: uploadData
264
    });
265

266
    webgpuCommandEncoder.trackTransientUploadBuffer(uploadBuffer);
52✔
267
    webgpuCommandEncoder.copyBufferToBuffer({
52✔
268
      sourceBuffer: uploadBuffer,
269
      destinationBuffer,
270
      destinationOffset: byteOffset,
271
      size: uploadData.byteLength
272
    });
273
  }
274

275
  // WebGPU specifics
276

277
  createTransformFeedback(props: TransformFeedbackProps): TransformFeedback {
278
    throw new Error('Transform feedback not supported in WebGPU');
×
279
  }
280

281
  override createQuerySet(props: QuerySetProps): QuerySet {
282
    return new WebGPUQuerySet(this, props);
6✔
283
  }
284

285
  override createFence(): WebGPUFence {
286
    return new WebGPUFence(this);
1✔
287
  }
288

289
  createCanvasContext(props: CanvasContextProps): WebGPUCanvasContext {
290
    return this._registerCanvasSurface(new WebGPUCanvasContext(this, this.adapter, props));
1✔
291
  }
292

293
  createPresentationContext(props?: PresentationContextProps): PresentationContext {
294
    return this._registerCanvasSurface(new WebGPUPresentationContext(this, props));
3✔
295
  }
296

297
  createPipelineLayout(props: PipelineLayoutProps): WebGPUPipelineLayout {
298
    return new WebGPUPipelineLayout(this, props);
84✔
299
  }
300

301
  override generateMipmapsWebGPU(texture: Texture): void {
302
    generateMipmapsWebGPU(this, texture);
12✔
303
  }
304

305
  override _createBindGroupLayoutWebGPU(
306
    pipeline: RenderPipeline | ComputePipeline,
307
    group: number
308
  ): GPUBindGroupLayout {
309
    return (pipeline as WebGPURenderPipeline | WebGPUComputePipeline).handle.getBindGroupLayout(
337✔
310
      group
311
    );
312
  }
313

314
  override _createBindGroupWebGPU(
315
    bindGroupLayout: unknown,
316
    shaderLayout: ShaderLayout | ComputeShaderLayout,
317
    bindings: Bindings,
318
    group: number,
319
    label?: string
320
  ): GPUBindGroup | null {
321
    if (Object.keys(bindings).length === 0) {
712✔
322
      return this.handle.createBindGroup({
18✔
323
        label,
324
        layout: bindGroupLayout as GPUBindGroupLayout,
325
        entries: []
326
      });
327
    }
328

329
    return getBindGroup(
694✔
330
      this,
331
      bindGroupLayout as GPUBindGroupLayout,
332
      shaderLayout,
333
      bindings,
334
      group,
335
      label
336
    );
337
  }
338

339
  submit(commandBuffer?: WebGPUCommandBuffer): void {
340
    let submittedCommandEncoder: WebGPUCommandEncoder | null = null;
284✔
341
    if (!commandBuffer) {
284✔
342
      ({submittedCommandEncoder, commandBuffer} = this._finalizeDefaultCommandEncoderForSubmit());
213✔
343
    }
344

345
    const profiler = getWebGPUCpuHotspotProfiler(this);
284✔
346
    const startTime = profiler ? getTimestamp() : 0;
284✔
347
    const submitReason = getWebGPUCpuHotspotSubmitReason(this);
284✔
348
    const transientUploadBuffers = commandBuffer.transientUploadBuffers;
284✔
349
    let didSubmit = false;
284✔
350
    try {
284✔
351
      this.pushErrorScope('validation');
284✔
352
      const queueSubmitStartTime = profiler ? getTimestamp() : 0;
284✔
353
      this.handle.queue.submit([commandBuffer.handle]);
284✔
354
      didSubmit = true;
284✔
355
      if (profiler) {
284✔
356
        profiler.queueSubmitCount = (profiler.queueSubmitCount || 0) + 1;
42✔
357
        profiler.queueSubmitTimeMs =
42✔
358
          (profiler.queueSubmitTimeMs || 0) + (getTimestamp() - queueSubmitStartTime);
46✔
359
      }
360
      this.popErrorScope((error: GPUError) => {
284✔
361
        this.reportError(new Error(`${this} command submission: ${error.message}`), this)();
1✔
362
        this.debug();
1✔
363
      });
364

365
      if (submittedCommandEncoder) {
284✔
366
        const submitResolveKickoffStartTime = profiler ? getTimestamp() : 0;
213✔
367
        scheduleMicrotask(() => {
213✔
368
          submittedCommandEncoder
213✔
369
            .resolveTimeProfilingQuerySet()
370
            .then(() => {
371
              this.commandEncoder._gpuTimeMs = submittedCommandEncoder._gpuTimeMs;
213✔
372
            })
373
            .catch(() => {});
374
        });
375
        if (profiler) {
213✔
376
          profiler.submitResolveKickoffCount = (profiler.submitResolveKickoffCount || 0) + 1;
42✔
377
          profiler.submitResolveKickoffTimeMs =
42✔
378
            (profiler.submitResolveKickoffTimeMs || 0) +
67✔
379
            (getTimestamp() - submitResolveKickoffStartTime);
380
        }
381
      }
382
    } finally {
383
      if (transientUploadBuffers.length) {
284✔
384
        if (didSubmit) {
5!
385
          // The GPU may still be reading from the staging buffers after
386
          // queue.submit() returns, so defer destruction until the submitted
387
          // work has fully completed.
388
          this.handle.queue
5✔
389
            .onSubmittedWorkDone()
390
            .then(() => {
391
              for (const uploadBuffer of transientUploadBuffers) {
4✔
392
                uploadBuffer.destroy();
10✔
393
              }
394
            })
395
            .catch(() => {
396
              for (const uploadBuffer of transientUploadBuffers) {
×
397
                uploadBuffer.destroy();
×
398
              }
399
            });
400
        } else {
401
          for (const uploadBuffer of transientUploadBuffers) {
×
402
            uploadBuffer.destroy();
×
403
          }
404
        }
405
      }
406
      if (profiler) {
284✔
407
        profiler.submitCount = (profiler.submitCount || 0) + 1;
42✔
408
        profiler.submitTimeMs = (profiler.submitTimeMs || 0) + (getTimestamp() - startTime);
42✔
409
        const reasonCountKey =
410
          submitReason === 'query-readback' ? 'queryReadbackSubmitCount' : 'defaultSubmitCount';
42!
411
        const reasonTimeKey =
412
          submitReason === 'query-readback' ? 'queryReadbackSubmitTimeMs' : 'defaultSubmitTimeMs';
42!
413
        profiler[reasonCountKey] = (profiler[reasonCountKey] || 0) + 1;
42✔
414
        profiler[reasonTimeKey] = (profiler[reasonTimeKey] || 0) + (getTimestamp() - startTime);
42✔
415
      }
416
      const commandBufferDestroyStartTime = profiler ? getTimestamp() : 0;
284✔
417
      commandBuffer.destroy();
284✔
418
      if (profiler) {
284✔
419
        profiler.commandBufferDestroyCount = (profiler.commandBufferDestroyCount || 0) + 1;
42✔
420
        profiler.commandBufferDestroyTimeMs =
42✔
421
          (profiler.commandBufferDestroyTimeMs || 0) +
49✔
422
          (getTimestamp() - commandBufferDestroyStartTime);
423
      }
424
    }
425
  }
426

427
  private _finalizeDefaultCommandEncoderForSubmit(): {
428
    submittedCommandEncoder: WebGPUCommandEncoder;
429
    commandBuffer: WebGPUCommandBuffer;
430
  } {
431
    const submittedCommandEncoder = this.commandEncoder;
213✔
432
    if (
213!
433
      submittedCommandEncoder.getTimeProfilingSlotCount() > 0 &&
213!
434
      submittedCommandEncoder.getTimeProfilingQuerySet() instanceof WebGPUQuerySet
435
    ) {
436
      const querySet = submittedCommandEncoder.getTimeProfilingQuerySet() as WebGPUQuerySet;
×
437
      querySet._encodeResolveToReadBuffer(submittedCommandEncoder, {
×
438
        firstQuery: 0,
439
        queryCount: submittedCommandEncoder.getTimeProfilingSlotCount()
440
      });
441
    }
442

443
    const commandBuffer = submittedCommandEncoder.finish();
213✔
444
    this.commandEncoder.destroy();
213✔
445
    this.commandEncoder = this.createCommandEncoder({
213✔
446
      id: submittedCommandEncoder.props.id,
447
      timeProfilingQuerySet: submittedCommandEncoder.getTimeProfilingQuerySet()
448
    });
449

450
    return {submittedCommandEncoder, commandBuffer};
213✔
451
  }
452

453
  // WebGPU specific
454

455
  pushErrorScope(scope: 'validation' | 'out-of-memory'): void {
456
    if (!this.props.debug) {
8,136✔
457
      return;
18✔
458
    }
459
    const profiler = getWebGPUCpuHotspotProfiler(this);
8,118✔
460
    const startTime = profiler ? getTimestamp() : 0;
8,118✔
461
    this.handle.pushErrorScope(scope);
8,118✔
462
    if (profiler) {
8,118✔
463
      profiler.errorScopePushCount = (profiler.errorScopePushCount || 0) + 1;
149✔
464
      profiler.errorScopeTimeMs = (profiler.errorScopeTimeMs || 0) + (getTimestamp() - startTime);
149✔
465
    }
466
  }
467

468
  popErrorScope(handler: (error: GPUError) => void): Promise<void> {
469
    if (!this.props.debug) {
8,136✔
470
      return Promise.resolve();
18✔
471
    }
472
    const profiler = getWebGPUCpuHotspotProfiler(this);
8,118✔
473
    const startTime = profiler ? getTimestamp() : 0;
8,118✔
474
    const errorScopePromise = this.handle
8,118✔
475
      .popErrorScope()
476
      .then((error: GPUError | null) => {
477
        if (error) {
7,093✔
478
          handler(error);
11✔
479
        }
480
      })
481
      .catch((error: unknown) => {
482
        if (this.shouldIgnoreDroppedInstanceError(error, 'popErrorScope')) {
209!
483
          return;
209✔
484
        }
485

486
        const errorMessage = error instanceof Error ? error.message : String(error);
×
487
        this.reportError(new Error(`${this} popErrorScope failed: ${errorMessage}`), this)();
×
488
        this.debug();
×
489
      });
490
    if (profiler) {
8,118✔
491
      profiler.errorScopePopCount = (profiler.errorScopePopCount || 0) + 1;
149✔
492
      profiler.errorScopeTimeMs = (profiler.errorScopeTimeMs || 0) + (getTimestamp() - startTime);
149✔
493
    }
494
    return errorScopePromise;
8,118✔
495
  }
496

497
  // PRIVATE METHODS
498

499
  protected _getInfo(): DeviceInfo {
500
    const [driver, driverVersion] = ((this.adapterInfo as any).driver || '').split(' Version ');
72✔
501

502
    // See https://developer.chrome.com/blog/new-in-webgpu-120#adapter_information_updates
503
    const vendor = this.adapterInfo.vendor || this.adapter.__brand || 'unknown';
72!
504
    const renderer = driver || '';
72✔
505
    const version = driverVersion || '';
72✔
506
    const fallback = Boolean(
72✔
507
      (this.adapterInfo as any).isFallbackAdapter ??
72!
508
        (this.adapter as any).isFallbackAdapter ??
509
        false
510
    );
511
    const softwareRenderer = /SwiftShader/i.test(
72✔
512
      `${vendor} ${renderer} ${this.adapterInfo.architecture || ''}`
72!
513
    );
514

515
    const gpuArchitecture = this.adapterInfo.architecture || 'unknown';
72!
516
    const gpu =
517
      identifyGPUVendor(vendor, renderer) ??
72✔
518
      (softwareRenderer || fallback ? 'software' : 'unknown');
144!
519
    const gpuBackend = (this.adapterInfo as any).backend || 'unknown';
72✔
520
    const gpuType =
72✔
521
      ((this.adapterInfo as any).type || '').split(' ')[0].toLowerCase() ||
144✔
522
      (softwareRenderer || fallback ? 'cpu' : 'unknown');
144!
523

524
    return {
72✔
525
      type: 'webgpu',
526
      vendor,
527
      renderer,
528
      version,
529
      gpu,
530
      gpuType,
531
      gpuBackend,
532
      gpuArchitecture,
533
      fallback,
534
      featureLevel: getWebGPUDeviceFeatureLevel(this.props.featureLevel),
535
      shadingLanguage: 'wgsl',
536
      shadingLanguageVersion: 100
537
    };
538
  }
539

540
  shouldIgnoreDroppedInstanceError(error: unknown, operation?: string): boolean {
541
    const errorMessage = error instanceof Error ? error.message : String(error);
213!
542
    return (
213✔
543
      errorMessage.includes('Instance dropped') &&
852!
544
      (!operation || errorMessage.includes(operation)) &&
545
      (this._lostState.isLost ||
546
        this.info.gpu === 'software' ||
547
        this.info.gpuType === 'cpu' ||
548
        Boolean(this.info.fallback))
549
    );
550
  }
551

552
  protected _getFeatures(): DeviceFeatures {
553
    // Initialize with actual WebGPU Features (note that unknown features may not be in DeviceFeature type)
554
    const features = new Set<DeviceFeature>(this.handle.features as Set<DeviceFeature>);
72✔
555
    // Fixups for pre-standard names: https://github.com/webgpu-native/webgpu-headers/issues/133
556
    // @ts-expect-error Chrome Canary v99
557
    if (features.has('depth-clamping')) {
72!
558
      // @ts-expect-error Chrome Canary v99
559
      features.delete('depth-clamping');
×
560
      features.add('depth-clip-control');
×
561
    }
562

563
    // Some subsets of WebGPU extensions correspond to WebGL extensions
564
    if (features.has('texture-compression-bc')) {
72✔
565
      features.add('texture-compression-bc5-webgl');
69✔
566
    }
567

568
    if (this.handle.features.has('chromium-experimental-norm16-texture-formats')) {
72!
569
      features.add('norm16-renderable-webgl');
×
570
    }
571

572
    if (this.handle.features.has('chromium-experimental-snorm16-texture-formats')) {
72!
573
      features.add('snorm16-renderable-webgl');
×
574
    }
575

576
    const WEBGPU_ALWAYS_FEATURES: DeviceFeature[] = [
72✔
577
      'compilation-status-async-webgl',
578
      'float32-renderable-webgl',
579
      'float16-renderable-webgl',
580
      'norm16-renderable-webgl',
581
      'texture-filterable-anisotropic-webgl',
582
      'shader-noperspective-interpolation-webgl'
583
    ];
584

585
    for (const feature of WEBGPU_ALWAYS_FEATURES) {
72✔
586
      features.add(feature);
432✔
587
    }
588

589
    if (
72!
590
      isHTMLInCanvasSupported() &&
72!
591
      typeof (
592
        this.handle.queue as GPUQueue & {
593
          copyElementImageToTexture?: unknown;
594
        }
595
      ).copyElementImageToTexture === 'function'
596
    ) {
597
      features.add('html-in-canvas');
×
598
    }
599

600
    return new DeviceFeatures(Array.from(features), this.props._disabledFeatures);
72✔
601
  }
602

603
  override _getDeviceSpecificTextureFormatCapabilities(
604
    capabilities: DeviceTextureFormatCapabilities
605
  ): DeviceTextureFormatCapabilities {
606
    const {format} = capabilities;
76✔
607
    if (format.includes('webgl')) {
76✔
608
      return {format, create: false, render: false, filter: false, blend: false, store: false};
11✔
609
    }
610
    return capabilities;
65✔
611
  }
612
}
613

614
function getWebGPUDeviceLimits(limits: GPUSupportedLimits): DeviceLimits {
615
  const stageSpecificLimits: Partial<Record<keyof DeviceLimits, number>> = {
72✔
616
    maxStorageBuffersInVertexStage:
617
      limits.maxStorageBuffersInVertexStage ?? limits.maxStorageBuffersPerShaderStage,
72!
618
    maxStorageBuffersInFragmentStage:
619
      limits.maxStorageBuffersInFragmentStage ?? limits.maxStorageBuffersPerShaderStage,
72!
620
    maxStorageTexturesInVertexStage:
621
      limits.maxStorageTexturesInVertexStage ?? limits.maxStorageTexturesPerShaderStage,
72!
622
    maxStorageTexturesInFragmentStage:
623
      limits.maxStorageTexturesInFragmentStage ?? limits.maxStorageTexturesPerShaderStage
72!
624
  };
625

626
  return new Proxy(limits, {
72✔
627
    get(target, property) {
628
      return typeof property === 'string' && property in stageSpecificLimits
1,205✔
629
        ? stageSpecificLimits[property as keyof DeviceLimits]
630
        : Reflect.get(target, property, target);
631
    }
632
  }) as DeviceLimits;
633
}
634

635
function getWebGPUDeviceFeatureLevel(
636
  featureLevel: DeviceProps['featureLevel']
637
): NonNullable<DeviceInfo['featureLevel']> {
638
  return featureLevel === 'best-available' ? 'core' : featureLevel || 'core';
72!
639
}
640

641
function identifyGPUVendor(
642
  vendor: string,
643
  renderer: string
644
): 'nvidia' | 'intel' | 'apple' | 'amd' | null {
645
  if (/NVIDIA/i.exec(vendor) || /NVIDIA/i.exec(renderer)) {
72!
646
    return 'nvidia';
×
647
  }
648
  if (/INTEL/i.exec(vendor) || /INTEL/i.exec(renderer)) {
72!
649
    return 'intel';
×
650
  }
651
  if (/Apple/i.exec(vendor) || /Apple/i.exec(renderer)) {
72!
652
    return 'apple';
×
653
  }
654
  if (
72!
655
    /AMD/i.exec(vendor) ||
288✔
656
    /AMD/i.exec(renderer) ||
657
    /ATI/i.exec(vendor) ||
658
    /ATI/i.exec(renderer)
659
  ) {
660
    return 'amd';
×
661
  }
662
  return null;
72✔
663
}
664

665
function scheduleMicrotask(callback: () => void): void {
666
  if (globalThis.queueMicrotask) {
213!
667
    globalThis.queueMicrotask(callback);
213✔
668
    return;
213✔
669
  }
670
  Promise.resolve()
×
671
    .then(callback)
672
    .catch(() => {});
673
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc