All files / core/src/RenderingEngine/helpers attachWebGLContextEvents.ts

50% Statements 4/8
33.33% Branches 1/3
33.33% Functions 1/3
50% Lines 4/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                        896x           896x       896x                   896x              
import eventTarget from '../../eventTarget';
import { Events } from '../../enums';
import triggerEvent from '../../utilities/triggerEvent';
import type { VtkOffscreenMultiRenderWindow } from '../../types';
 
/**
 * Forwards WebGL context lost/restored events from a rendering engine's
 * offscreen canvas to the cornerstone eventTarget as WEBGL_CONTEXT_LOST /
 * WEBGL_CONTEXT_RESTORED.
 *
 * Cornerstone never switches render backends on its own: these events exist
 * so applications can detect GPU degradation, prompt the user, and call
 * setRenderBackend('cpu') themselves. vtk.js keeps its own listeners on the
 * same canvas (preventDefault + restore attempt), which these do not disturb.
 */
export function attachWebGLContextEvents(
  offscreenMultiRenderWindow: VtkOffscreenMultiRenderWindow,
  renderingEngineId: string,
  contextIndex = 0
): void {
  const canvas = (
    offscreenMultiRenderWindow.getOpenGLRenderWindow?.() as {
      getCanvas?: () => HTMLCanvasElement | undefined;
    }
  )?.getCanvas?.();
 
  Iif (!canvas) {
    return;
  }
 
  canvas.addEventListener('webglcontextlost', () => {
    console.warn(
      `CornerstoneRender: WebGL context lost (renderingEngine=${renderingEngineId}, context=${contextIndex})`
    );
    triggerEvent(eventTarget, Events.WEBGL_CONTEXT_LOST, {
      renderingEngineId,
      contextIndex,
    });
  });
 
  canvas.addEventListener('webglcontextrestored', () => {
    triggerEvent(eventTarget, Events.WEBGL_CONTEXT_RESTORED, {
      renderingEngineId,
      contextIndex,
    });
  });
}