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

visgl / luma.gl / 13709656825

06 Mar 2025 10:42PM UTC coverage: 75.243% (-0.01%) from 75.257%
13709656825

push

github

web-flow
chore(webgpu): Improve error handling (#2329)

2021 of 2649 branches covered (76.29%)

Branch coverage included in aggregate %.

9 of 50 new or added lines in 5 files covered. (18.0%)

1 existing line in 1 file now uncovered.

26333 of 35034 relevant lines covered (75.16%)

50.21 hits per line

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

80.16
/modules/engine/src/animation-loop/animation-loop.ts
1
// luma.gl
1✔
2
// SPDX-License-Identifier: MIT
1✔
3
// Copyright (c) vis.gl contributors
1✔
4

1✔
5
import {luma, Device} from '@luma.gl/core';
1✔
6
import {
1✔
7
  requestAnimationFramePolyfill,
1✔
8
  cancelAnimationFramePolyfill
1✔
9
} from './request-animation-frame';
1✔
10
import {Timeline} from '../animation/timeline';
1✔
11
import {AnimationProps} from './animation-props';
1✔
12
import {Stats, Stat} from '@probe.gl/stats';
1✔
13

1✔
14
let statIdCounter = 0;
1✔
15

1✔
16
/** AnimationLoop properties */
1✔
17
export type AnimationLoopProps = {
1✔
18
  device: Device | Promise<Device>;
1✔
19

1✔
20
  onAddHTML?: (div: HTMLDivElement) => string; // innerHTML
1✔
21
  onInitialize?: (animationProps: AnimationProps) => Promise<unknown>;
1✔
22
  onRender?: (animationProps: AnimationProps) => unknown;
1✔
23
  onFinalize?: (animationProps: AnimationProps) => void;
1✔
24
  onError?: (reason: Error) => void;
1✔
25

1✔
26
  stats?: Stats;
1✔
27

1✔
28
  // view parameters - TODO move to CanvasContext?
1✔
29
  autoResizeViewport?: boolean;
1✔
30
};
1✔
31

1✔
32
export type MutableAnimationLoopProps = {
1✔
33
  // view parameters
1✔
34
  autoResizeViewport?: boolean;
1✔
35
};
1✔
36

1✔
37
/** Convenient animation loop */
1✔
38
export class AnimationLoop {
1✔
39
  static defaultAnimationLoopProps = {
1✔
40
    device: null!,
1✔
41

1✔
42
    onAddHTML: () => '',
1✔
43
    onInitialize: async () => null,
1✔
44
    onRender: () => {},
1✔
45
    onFinalize: () => {},
1✔
46
    onError: error => console.error(error), // eslint-disable-line no-console
1✔
47

1✔
48
    stats: luma.stats.get(`animation-loop-${statIdCounter++}`),
1✔
49

1✔
50
    // view parameters
1✔
51
    autoResizeViewport: false
1✔
52
  } as const satisfies Readonly<Required<AnimationLoopProps>>;
1✔
53

1✔
54
  device: Device | null = null;
1✔
55
  canvas: HTMLCanvasElement | OffscreenCanvas | null = null;
1✔
56

1✔
57
  props: Required<AnimationLoopProps>;
1✔
58
  animationProps: AnimationProps | null = null;
1✔
59
  timeline: Timeline | null = null;
1✔
60
  stats: Stats;
1✔
61
  cpuTime: Stat;
1✔
62
  gpuTime: Stat;
1✔
63
  frameRate: Stat;
1✔
64

1✔
65
  display: any;
1✔
66

1✔
67
  needsRedraw: string | false = 'initialized';
1✔
68

1✔
69
  _initialized: boolean = false;
1✔
70
  _running: boolean = false;
1✔
71
  _animationFrameId: any = null;
1✔
72
  _nextFramePromise: Promise<AnimationLoop> | null = null;
1✔
73
  _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;
1✔
74
  _cpuStartTime: number = 0;
1✔
75
  _error: Error | null = null;
1✔
76

1✔
77
  // _gpuTimeQuery: Query | null = null;
1✔
78

1✔
79
  /*
1✔
80
   * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context
1✔
81
   */
1✔
82
  constructor(props: AnimationLoopProps) {
1✔
83
    this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};
6✔
84
    props = this.props;
6✔
85

6✔
86
    if (!props.device) {
6!
87
      throw new Error('No device provided');
×
88
    }
×
89

6✔
90
    // state
6✔
91
    this.stats = props.stats || new Stats({id: 'animation-loop-stats'});
6!
92
    this.cpuTime = this.stats.get('CPU Time');
6✔
93
    this.gpuTime = this.stats.get('GPU Time');
6✔
94
    this.frameRate = this.stats.get('Frame Rate');
6✔
95

6✔
96
    this.setProps({autoResizeViewport: props.autoResizeViewport});
6✔
97

6✔
98
    // Bind methods
6✔
99
    this.start = this.start.bind(this);
6✔
100
    this.stop = this.stop.bind(this);
6✔
101

6✔
102
    this._onMousemove = this._onMousemove.bind(this);
6✔
103
    this._onMouseleave = this._onMouseleave.bind(this);
6✔
104
  }
6✔
105

1✔
106
  destroy(): void {
1✔
107
    this.stop();
×
108
    this._setDisplay(null);
×
109
  }
×
110

1✔
111
  /** @deprecated Use .destroy() */
1✔
112
  delete(): void {
1✔
113
    this.destroy();
×
114
  }
×
115

1✔
116
  reportError(error: Error): void {
1✔
117
    this.props.onError(error);
×
NEW
118
    this._error = error;
×
119
  }
×
120

1✔
121
  /** Flags this animation loop as needing redraw */
1✔
122
  setNeedsRedraw(reason: string): this {
1✔
123
    this.needsRedraw = this.needsRedraw || reason;
4✔
124
    return this;
4✔
125
  }
4✔
126

1✔
127
  setProps(props: MutableAnimationLoopProps): this {
1✔
128
    if ('autoResizeViewport' in props) {
6✔
129
      this.props.autoResizeViewport = props.autoResizeViewport || false;
6✔
130
    }
6✔
131
    return this;
6✔
132
  }
6✔
133

1✔
134
  /** Starts a render loop if not already running */
1✔
135
  async start() {
1✔
136
    if (this._running) {
8✔
137
      return this;
2✔
138
    }
2✔
139
    this._running = true;
6✔
140

6✔
141
    try {
6✔
142
      let appContext;
6✔
143
      if (!this._initialized) {
8✔
144
        this._initialized = true;
5✔
145
        // Create the WebGL context
5✔
146
        await this._initDevice();
5✔
147
        this._initialize();
5✔
148

5✔
149
        // Note: onIntialize can return a promise (e.g. in case app needs to load resources)
5✔
150
        await this.props.onInitialize(this._getAnimationProps());
5✔
151
      }
5✔
152

6✔
153
      // check that we haven't been stopped
6✔
154
      if (!this._running) {
8✔
155
        return null;
1✔
156
      }
1✔
157

5✔
158
      // Start the loop
5✔
159
      if (appContext !== false) {
5✔
160
        // cancel any pending renders to ensure only one loop can ever run
5✔
161
        this._cancelAnimationFrame();
5✔
162
        this._requestAnimationFrame();
5✔
163
      }
5✔
164

5✔
165
      return this;
5✔
166
    } catch (err: unknown) {
8!
167
      const error = err instanceof Error ? err : new Error('Unknown error');
×
168
      this.props.onError(error);
×
169
      // this._running = false; // TODO
×
170
      throw error;
×
171
    }
×
172
  }
8✔
173

1✔
174
  /** Stops a render loop if already running, finalizing */
1✔
175
  stop() {
1✔
176
    // console.debug(`Stopping ${this.constructor.name}`);
6✔
177
    if (this._running) {
6✔
178
      // call callback
6✔
179
      // If stop is called immediately, we can end up in a state where props haven't been initialized...
6✔
180
      if (this.animationProps && !this._error) {
6✔
181
        this.props.onFinalize(this.animationProps);
6✔
182
      }
6✔
183

6✔
184
      this._cancelAnimationFrame();
6✔
185
      this._nextFramePromise = null;
6✔
186
      this._resolveNextFrame = null;
6✔
187
      this._running = false;
6✔
188
    }
6✔
189
    return this;
6✔
190
  }
6✔
191

1✔
192
  /** Explicitly draw a frame */
1✔
193
  redraw(): this {
1✔
194
    if (this.device?.isLost || this._error) {
11!
195
      return this;
×
196
    }
×
197

11✔
198
    this._beginFrameTimers();
11✔
199

11✔
200
    this._setupFrame();
11✔
201
    this._updateAnimationProps();
11✔
202

11✔
203
    this._renderFrame(this._getAnimationProps());
11✔
204

11✔
205
    // clear needsRedraw flag
11✔
206
    this._clearNeedsRedraw();
11✔
207

11✔
208
    if (this._resolveNextFrame) {
11✔
209
      this._resolveNextFrame(this);
4✔
210
      this._nextFramePromise = null;
4✔
211
      this._resolveNextFrame = null;
4✔
212
    }
4✔
213

11✔
214
    this._endFrameTimers();
11✔
215

11✔
216
    return this;
11✔
217
  }
11✔
218

1✔
219
  /** Add a timeline, it will be automatically updated by the animation loop. */
1✔
220
  attachTimeline(timeline: Timeline): Timeline {
1✔
221
    this.timeline = timeline;
×
222
    return this.timeline;
×
223
  }
×
224

1✔
225
  /** Remove a timeline */
1✔
226
  detachTimeline(): void {
1✔
227
    this.timeline = null;
×
228
  }
×
229

1✔
230
  /** Wait until a render completes */
1✔
231
  waitForRender(): Promise<AnimationLoop> {
1✔
232
    this.setNeedsRedraw('waitForRender');
4✔
233

4✔
234
    if (!this._nextFramePromise) {
4✔
235
      this._nextFramePromise = new Promise(resolve => {
4✔
236
        this._resolveNextFrame = resolve;
4✔
237
      });
4✔
238
    }
4✔
239
    return this._nextFramePromise;
4✔
240
  }
4✔
241

1✔
242
  /** TODO - should use device.deviceContext */
1✔
243
  async toDataURL(): Promise<string> {
1✔
244
    this.setNeedsRedraw('toDataURL');
×
245
    await this.waitForRender();
×
246
    if (this.canvas instanceof HTMLCanvasElement) {
×
247
      return this.canvas.toDataURL();
×
248
    }
×
249
    throw new Error('OffscreenCanvas');
×
250
  }
×
251

1✔
252
  // PRIVATE METHODS
1✔
253

1✔
254
  _initialize(): void {
1✔
255
    this._startEventHandling();
5✔
256

5✔
257
    // Initialize the callback data
5✔
258
    this._initializeAnimationProps();
5✔
259
    this._updateAnimationProps();
5✔
260

5✔
261
    // Default viewport setup, in case onInitialize wants to render
5✔
262
    this._resizeViewport();
5✔
263

5✔
264
    // this._gpuTimeQuery = Query.isSupported(this.gl, ['timers']) ? new Query(this.gl) : null;
5✔
265
  }
5✔
266

1✔
267
  _setDisplay(display: any): void {
1✔
268
    if (this.display) {
×
269
      this.display.destroy();
×
270
      this.display.animationLoop = null;
×
271
    }
×
272

×
273
    // store animation loop on the display
×
274
    if (display) {
×
275
      display.animationLoop = this;
×
276
    }
×
277

×
278
    this.display = display;
×
279
  }
×
280

1✔
281
  _requestAnimationFrame(): void {
1✔
282
    if (!this._running) {
15✔
283
      return;
1✔
284
    }
1✔
285

14✔
286
    // VR display has a separate animation frame to sync with headset
14✔
287
    // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/
14✔
288
    // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame
14✔
289
    // if (this.display && this.display.requestAnimationFrame) {
14✔
290
    //   this._animationFrameId = this.display.requestAnimationFrame(this._animationFrame.bind(this));
14✔
291
    // }
14✔
292
    this._animationFrameId = requestAnimationFramePolyfill(this._animationFrame.bind(this));
14✔
293
  }
15✔
294

1✔
295
  _cancelAnimationFrame(): void {
1✔
296
    if (this._animationFrameId === null) {
11✔
297
      return;
6✔
298
    }
6✔
299

5✔
300
    // VR display has a separate animation frame to sync with headset
5✔
301
    // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/
5✔
302
    // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame
5✔
303
    // if (this.display && this.display.cancelAnimationFramePolyfill) {
5✔
304
    //   this.display.cancelAnimationFrame(this._animationFrameId);
5✔
305
    // }
5✔
306
    cancelAnimationFramePolyfill(this._animationFrameId);
5✔
307
    this._animationFrameId = null;
5✔
308
  }
11✔
309

1✔
310
  _animationFrame(): void {
1✔
311
    if (!this._running) {
10!
312
      return;
×
313
    }
×
314
    this.redraw();
10✔
315
    this._requestAnimationFrame();
10✔
316
  }
10✔
317

1✔
318
  // Called on each frame, can be overridden to call onRender multiple times
1✔
319
  // to support e.g. stereoscopic rendering
1✔
320
  _renderFrame(animationProps: AnimationProps): void {
1✔
321
    // Allow e.g. VR display to render multiple frames.
11✔
322
    if (this.display) {
11!
323
      this.display._renderFrame(animationProps);
×
324
      return;
×
325
    }
×
326

11✔
327
    // call callback
11✔
328
    this.props.onRender(this._getAnimationProps());
11✔
329
    // end callback
11✔
330

11✔
331
    // Submit commands (necessary on WebGPU)
11✔
332
    this.device?.submit();
11✔
333
  }
11✔
334

1✔
335
  _clearNeedsRedraw(): void {
1✔
336
    this.needsRedraw = false;
11✔
337
  }
11✔
338

1✔
339
  _setupFrame(): void {
1✔
340
    this._resizeViewport();
11✔
341
  }
11✔
342

1✔
343
  // Initialize the  object that will be passed to app callbacks
1✔
344
  _initializeAnimationProps(): void {
1✔
345
    const canvasContext = this.device?.getDefaultCanvasContext();
5✔
346
    if (!this.device || !canvasContext) {
5!
347
      throw new Error('loop');
×
348
    }
×
349

5✔
350
    const canvas = canvasContext?.canvas;
5✔
351
    const useDevicePixels = canvasContext.props.useDevicePixels;
5✔
352

5✔
353
    this.animationProps = {
5✔
354
      animationLoop: this,
5✔
355

5✔
356
      device: this.device,
5✔
357
      canvasContext,
5✔
358
      canvas,
5✔
359
      // @ts-expect-error Deprecated
5✔
360
      useDevicePixels,
5✔
361

5✔
362
      timeline: this.timeline,
5✔
363

5✔
364
      needsRedraw: false,
5✔
365

5✔
366
      // Placeholders
5✔
367
      width: 1,
5✔
368
      height: 1,
5✔
369
      aspect: 1,
5✔
370

5✔
371
      // Animation props
5✔
372
      time: 0,
5✔
373
      startTime: Date.now(),
5✔
374
      engineTime: 0,
5✔
375
      tick: 0,
5✔
376
      tock: 0,
5✔
377

5✔
378
      // Experimental
5✔
379
      _mousePosition: null // Event props
5✔
380
    };
5✔
381
  }
5✔
382

1✔
383
  _getAnimationProps(): AnimationProps {
1✔
384
    if (!this.animationProps) {
27!
385
      throw new Error('animationProps');
×
386
    }
×
387
    return this.animationProps;
27✔
388
  }
27✔
389

1✔
390
  // Update the context object that will be passed to app callbacks
1✔
391
  _updateAnimationProps(): void {
1✔
392
    if (!this.animationProps) {
16!
393
      return;
×
394
    }
×
395

16✔
396
    // Can this be replaced with canvas context?
16✔
397
    const {width, height, aspect} = this._getSizeAndAspect();
16✔
398
    if (width !== this.animationProps.width || height !== this.animationProps.height) {
16!
399
      this.setNeedsRedraw('drawing buffer resized');
×
400
    }
×
401
    if (aspect !== this.animationProps.aspect) {
16!
402
      this.setNeedsRedraw('drawing buffer aspect changed');
×
403
    }
×
404

16✔
405
    this.animationProps.width = width;
16✔
406
    this.animationProps.height = height;
16✔
407
    this.animationProps.aspect = aspect;
16✔
408

16✔
409
    this.animationProps.needsRedraw = this.needsRedraw;
16✔
410

16✔
411
    // Update time properties
16✔
412
    this.animationProps.engineTime = Date.now() - this.animationProps.startTime;
16✔
413

16✔
414
    if (this.timeline) {
16!
415
      this.timeline.update(this.animationProps.engineTime);
×
416
    }
×
417

16✔
418
    this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);
16✔
419
    this.animationProps.tock++;
16✔
420

16✔
421
    // For back compatibility
16✔
422
    this.animationProps.time = this.timeline
16!
423
      ? this.timeline.getTime()
×
424
      : this.animationProps.engineTime;
16✔
425
  }
16✔
426

1✔
427
  /** Wait for supplied device */
1✔
428
  async _initDevice() {
1✔
429
    this.device = await this.props.device;
5✔
430
    if (!this.device) {
5!
431
      throw new Error('No device provided');
×
432
    }
×
433
    this.canvas = this.device.getDefaultCanvasContext().canvas || null;
5!
434
    // this._createInfoDiv();
5✔
435
  }
5✔
436

1✔
437
  _createInfoDiv(): void {
1✔
438
    if (this.canvas && this.props.onAddHTML) {
×
439
      const wrapperDiv = document.createElement('div');
×
440
      document.body.appendChild(wrapperDiv);
×
441
      wrapperDiv.style.position = 'relative';
×
442
      const div = document.createElement('div');
×
443
      div.style.position = 'absolute';
×
444
      div.style.left = '10px';
×
445
      div.style.bottom = '10px';
×
446
      div.style.width = '300px';
×
447
      div.style.background = 'white';
×
448
      if (this.canvas instanceof HTMLCanvasElement) {
×
449
        wrapperDiv.appendChild(this.canvas);
×
450
      }
×
451
      wrapperDiv.appendChild(div);
×
452
      const html = this.props.onAddHTML(div);
×
453
      if (html) {
×
454
        div.innerHTML = html;
×
455
      }
×
456
    }
×
457
  }
×
458

1✔
459
  _getSizeAndAspect(): {width: number; height: number; aspect: number} {
1✔
460
    if (!this.device) {
16!
461
      return {width: 1, height: 1, aspect: 1};
×
462
    }
×
463
    // https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
16✔
464
    const [width, height] = this.device?.getDefaultCanvasContext().getDevicePixelSize() || [1, 1];
16!
465

16✔
466
    // https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html
16✔
467
    let aspect = 1;
16✔
468
    const canvas = this.device?.getDefaultCanvasContext().canvas;
16✔
469

16✔
470
    // @ts-expect-error
16✔
471
    if (canvas && canvas.clientHeight) {
16✔
472
      // @ts-expect-error
16✔
473
      aspect = canvas.clientWidth / canvas.clientHeight;
16✔
474
    } else if (width > 0 && height > 0) {
16!
475
      aspect = width / height;
×
476
    }
×
477

16✔
478
    return {width, height, aspect};
16✔
479
  }
16✔
480

1✔
481
  /** @deprecated Default viewport setup */
1✔
482
  _resizeViewport(): void {
1✔
483
    // TODO can we use canvas context to code this in a portable way?
16✔
484
    // @ts-expect-error Expose on canvasContext
16✔
485
    if (this.props.autoResizeViewport && this.device.gl) {
16!
486
      // @ts-expect-error Expose canvasContext
×
487
      this.device.gl.viewport(
×
488
        0,
×
489
        0,
×
490
        // @ts-expect-error Expose canvasContext
×
491
        this.device.gl.drawingBufferWidth,
×
492
        // @ts-expect-error Expose canvasContext
×
493
        this.device.gl.drawingBufferHeight
×
494
      );
×
495
    }
×
496
  }
16✔
497

1✔
498
  _beginFrameTimers() {
1✔
499
    this.frameRate.timeEnd();
11✔
500
    this.frameRate.timeStart();
11✔
501

11✔
502
    // Check if timer for last frame has completed.
11✔
503
    // GPU timer results are never available in the same
11✔
504
    // frame they are captured.
11✔
505
    // if (
11✔
506
    //   this._gpuTimeQuery &&
11✔
507
    //   this._gpuTimeQuery.isResultAvailable() &&
11✔
508
    //   !this._gpuTimeQuery.isTimerDisjoint()
11✔
509
    // ) {
11✔
510
    //   this.stats.get('GPU Time').addTime(this._gpuTimeQuery.getTimerMilliseconds());
11✔
511
    // }
11✔
512

11✔
513
    // if (this._gpuTimeQuery) {
11✔
514
    //   // GPU time query start
11✔
515
    //   this._gpuTimeQuery.beginTimeElapsedQuery();
11✔
516
    // }
11✔
517

11✔
518
    this.cpuTime.timeStart();
11✔
519
  }
11✔
520

1✔
521
  _endFrameTimers() {
1✔
522
    this.cpuTime.timeEnd();
11✔
523

11✔
524
    // if (this._gpuTimeQuery) {
11✔
525
    //   // GPU time query end. Results will be available on next frame.
11✔
526
    //   this._gpuTimeQuery.end();
11✔
527
    // }
11✔
528
  }
11✔
529

1✔
530
  // Event handling
1✔
531

1✔
532
  _startEventHandling() {
1✔
533
    if (this.canvas) {
5✔
534
      this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));
5✔
535
      this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));
5✔
536
    }
5✔
537
  }
5✔
538

1✔
539
  _onMousemove(event: Event) {
1✔
540
    if (event instanceof MouseEvent) {
×
541
      this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];
×
542
    }
×
543
  }
×
544

1✔
545
  _onMouseleave(event: Event) {
1✔
546
    this._getAnimationProps()._mousePosition = null;
×
547
  }
×
548
}
1✔
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