@babylonjs/lite-gl 1.14.0 → 1.16.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/README.md CHANGED
@@ -57,6 +57,49 @@ runRenderLoop(engine, () => {
57
57
  });
58
58
  ```
59
59
 
60
+ ## Effect readiness and errors
61
+
62
+ `createEffect` / `createEffectWrapper` submit compilation and linking without
63
+ querying their results. With `KHR_parallel_shader_compile`, readiness checks
64
+ poll completion before inspecting link status. Shader status and info logs are
65
+ queried only after link failure, avoiding premature compilation stalls.
66
+ Without the extension, checking link status can block.
67
+
68
+ Manual polling stays available: call `isEffectReady(engine, effect)` in your
69
+ render loop and inspect `getEffectCompilationError(engine, effect)` when it
70
+ returns false. The error accessor also polls once; `null` means no failure has
71
+ been recorded, not necessarily that the effect is ready. Errors include the
72
+ program log and failing shader stages' logs and are logged once. Neither this
73
+ accessor nor `executeWhenCompiled` starts automatic polling.
74
+
75
+ To wait before starting a render loop, opt into the tree-shakeable helper:
76
+
77
+ ```ts
78
+ import { waitForEffect } from "@babylonjs/lite-gl";
79
+
80
+ const controller = new AbortController();
81
+ try {
82
+ await waitForEffect(engine, wrapper.effect, { signal: controller.signal });
83
+ // The effect is finalized; rendering can now start.
84
+ } catch (error) {
85
+ console.error("Effect could not become ready:", error);
86
+ }
87
+ ```
88
+
89
+ The helper polls once per animation frame without registering a render loop.
90
+ It rejects on compile/link/restore failure, context loss, disposal (on the next
91
+ poll), or cancellation via `controller.abort()`, and cleans up its frame and
92
+ listeners on every exit. Cancelling a wait does not dispose a shared effect.
93
+ After context restoration, call it again to wait for the replacement program.
94
+ Already ready effects resolve without scheduling a frame; consumers that only
95
+ use manual polling ship none of the helper's scheduling code.
96
+
97
+ **Migration:** shader syntax errors no longer throw synchronously from
98
+ `createEffect` or `createEffectWrapper`. Poll `isEffectReady` and inspect
99
+ `getEffectCompilationError`, or catch a rejected `waitForEffect` promise instead.
100
+ For wrappers, pass `wrapper.effect` to these readiness/error APIs.
101
+ Shader/program allocation failures still throw synchronously.
102
+
60
103
  ## Entry points
61
104
 
62
105
  The entire public API is available from the single `@babylonjs/lite-gl` entry:
@@ -74,13 +117,15 @@ use.
74
117
  `getRenderingCanvas`, and `on/offContextLost` + `on/offContextRestored`
75
118
  (context-loss is handled: effects and textures are rebuilt on restore).
76
119
  - **Render loop** — `runRenderLoop`, `stopRenderLoop`.
77
- - **Effects** — `createEffect`, `isEffectReady`, `executeWhenCompiled`,
120
+ - **Effects** — `createEffect`, `isEffectReady`, `getEffectCompilationError`,
121
+ `executeWhenCompiled`, `waitForEffect` (optional cancellable readiness promise),
78
122
  `useEffect`, `disposeEffect`, and the cached uniform setters
79
123
  `setEffectFloat` / `…Float2` / `…Float3` / `…Float4` / `…Int` /
80
124
  `…Color3` / `…Color4` / `…Texture`.
81
125
  - **Fullscreen renderer** — `createEffectWrapper`, `applyEffectWrapper`,
82
126
  `drawEffect`, `setViewport`, `disposeEffectWrapper`.
83
127
  - **Textures** — `createRawTexture` (typed-array upload, LDR byte formats),
128
+ `createTextureFromSource` (single upload from already-decoded bitmaps/canvases/images),
84
129
  `createTexture3DFromPixels` + `setEffectTexture3D` (optional native RGBA8
85
130
  LUT volumes with trilinear sampling and zero 2D-only bundle cost),
86
131
  `createFloatTexture` (float / half-float HDR opt-in), `generateTextureMipMaps`,
@@ -102,6 +147,42 @@ use.
102
147
  - **Blend** — `setBlendMode` + `GLBlendMode` (`DISABLE` / `ADD` / `ALPHA` /
103
148
  `PREMULTIPLIED`), matching Babylon's `setAlphaMode` parameters.
104
149
 
150
+ ### Already-decoded textures
151
+
152
+ ```ts
153
+ import { createTextureFromSource, disposeTexture } from "@babylonjs/lite-gl";
154
+
155
+ const texture = createTextureFromSource(engine, bitmap);
156
+ // One texImage2D upload, linear filtering and clamp-to-edge by default.
157
+ // Later, release the GPU resource:
158
+ disposeTexture(engine, texture);
159
+ ```
160
+
161
+ The factory accepts `TexImageSource` (including `ImageBitmap`, `ImageData`,
162
+ canvas/offscreen canvas, decoded images, video and video frames), derives the
163
+ intrinsic size, and performs no placeholder or blank allocation first.
164
+ Video elements must have a decoded current frame (`readyState >= 2`,
165
+ `HAVE_CURRENT_DATA`), not just metadata with positive dimensions. A retained
166
+ video that loses its current frame restores as transparent black with a logged
167
+ error, like other unusable retained sources.
168
+ `GLTextureSourceOptions` configures filtering/wrapping and unpack flags.
169
+ For `ImageBitmap`, WebGL ignores unpack flip/premultiplication; choose those
170
+ settings during decoding instead. Convert SVG or density-selected (`srcset`)
171
+ images to an `ImageBitmap` first, since WebGL may upload them at a size other
172
+ than their natural size.
173
+
174
+ Sources are retained for automatic context restoration by default, so keep
175
+ retained bitmaps/frames open while their texture is live. Pass
176
+ `{ retainSource: false }` when your application owns recovery: the source
177
+ reference is dropped after upload and can be closed, but context restoration
178
+ produces a ready, transparent-black texture at the original size. Recreate
179
+ the texture after restore (for example from `onContextRestored`) to recover its
180
+ content. Mutable retained sources replay their current pixels and intrinsic
181
+ size. If a retained source was closed anyway, restore logs an error and falls
182
+ back to transparent black for that texture only. Mipmaps generated with
183
+ `generateTextureMipMaps` are not replayed; regenerate them after restore. No
184
+ source is closed by lite-gl.
185
+
105
186
  ## Demos
106
187
 
107
188
  Runnable scenes for every feature live in the repo's GL **lab**
package/context.js CHANGED
@@ -31,7 +31,7 @@ export function createGLEngine(canvas, options) {
31
31
  _state: createGLState(caps.maxTextureUnits),
32
32
  _effects: [],
33
33
  _effectCache: new Map(),
34
- _textures: [],
34
+ _textures: new Set(),
35
35
  _renderTargets: [],
36
36
  _currentRenderTarget: null,
37
37
  _buffers: [],
@@ -66,7 +66,9 @@ export function disposeGLEngine(engine) {
66
66
  engine.canvas.removeEventListener("webglcontextlost", engine._lostHandler, false);
67
67
  engine.canvas.removeEventListener("webglcontextrestored", engine._restoredHandler, false);
68
68
  const gl = engine.gl;
69
- // Iterate snapshots — the dispose paths splice into the registries.
69
+ const textures = Array.from(engine._textures);
70
+ engine._textures.clear();
71
+ // Iterate snapshots — dispose paths can mutate the live registries.
70
72
  const effects = engine._effects.slice();
71
73
  for (const eff of effects) {
72
74
  if (!eff._disposed) {
@@ -79,14 +81,12 @@ export function disposeGLEngine(engine) {
79
81
  }
80
82
  engine._effects.length = 0;
81
83
  engine._effectCache.clear();
82
- const textures = engine._textures.slice();
83
84
  for (const tex of textures) {
84
- if (!tex._disposed) {
85
- tex._disposed = true;
86
- gl.deleteTexture(tex.handle);
87
- }
85
+ // The snapshot contains live textures only. Force-delete every handle,
86
+ // even if reentrant disposal marks a later texture disposed first.
87
+ tex._disposed = true;
88
+ gl.deleteTexture(tex.handle);
88
89
  }
89
- engine._textures.length = 0;
90
90
  // Render targets own their FBO + renderbuffer + color texture; free them via
91
91
  // the per-RT closure so context.ts needs no runtime import of render-target.
92
92
  const rts = engine._renderTargets.slice();
package/context.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,iBAAiB,EAAgB,MAAM,YAAY,CAAC;AAyM1F;;;uCAGuC;AACvC,MAAM,UAAU,cAAc,CAAC,MAA2C,EAAE,OAAyB;IACjG,MAAM,CAAC,GAAG,OAAO,IAAI,EAAE,CAAC;IACxB,MAAM,KAAK,GAA2B;QAClC,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI;QACtB,kBAAkB,EAAE,CAAC,CAAC,kBAAkB,IAAI,IAAI;QAChD,SAAS,EAAE,CAAC,CAAC,SAAS,IAAI,KAAK;QAC/B,qBAAqB,EAAE,CAAC,CAAC,qBAAqB,IAAI,KAAK;QACvD,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,KAAK;QACvB,OAAO,EAAE,CAAC,CAAC,OAAO,IAAI,KAAK;QAC3B,eAAe,EAAE,CAAC,CAAC,eAAe,IAAI,SAAS;QAC/C,4BAA4B,EAAE,CAAC,CAAC,4BAA4B,IAAI,KAAK;KACxE,C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AE,CAAC,YAAY,CAAC,wBAAwB,CAAC,KAAK,IAAI,CAAC;IAC5E,MAAM,oBAAoB,GAAG,EAAE,CAAC,YAAY,CAAC,6BAA6B,CAAC,KAAK,IAAI,CAAC;IACrF,MAAM,WAAW,GAAG,EAAE,CAAC,YAAY,CAAC,0BAA0B,CAAC,KAAK,IAAI,CAAC;IACzE,OAAO;QACH,cAAc,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,gBAAgB,CAAW;QAC9D,eAAe,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,gCAAgC,CAAW;QAC/E,qBAAqB,EAAE,WAAW;QAClC,kBAAkB,EAAE,gBAAgB;QACpC,2BAA2B,EAAE,WAAW;QACxC,sBAAsB,EAAE,gBAAgB,IAAI,oBAAoB;QAChE,+BAA+B,EAAE,IAAI;QACrC,eAAe,EAAE,KAAK;KACzB,CAAC;AACN,CAAC;AAED,SAAS,WAAW,CAAC,CAA2B;IAC5C,KAAK,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;QAClB,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC;IAClB,CAAC;AACL,CAAC","sourcesContent":["import type { GLEffect } from \"./effect.js\";\nimport type { GLTexture } from \"./texture.js\";\nimport type { GLTexture3D } from \"./texture-3d.js\";\nimport type { GLRenderTarget } from \"./render-target.js\";\nimport { createGLState, resetGLState, resetGLStateCache, type GLState } from \"./state.js\";\n\n/**\n * Minimal shape of a context-restorable GL buffer (vertex / index), kept local\n * to this module so the public `GLEngineContext` type carries no dependency on\n * the tree-shakeable `mesh` entry. `mesh.ts`'s `GLVertexBuffer` /\n * `GLIndexBuffer` satisfy it structurally.\n * @internal\n */\nexport interface GLManagedBuffer {\n handle: WebGLBuffer;\n /** @internal */\n _disposed: boolean;\n /** @internal */\n _deleteGpu: (gl: WebGL2RenderingContext) => void;\n /** @internal */\n _restore: (engine: GLEngineContext) => void;\n}\n\n/** Constructor options forwarded to `canvas.getContext('webgl2', …)`. */\nexport interface GLEngineOptions {\n /** Default: true. */\n alpha?: boolean;\n /** Default: true. */\n premultipliedAlpha?: boolean;\n /** Default: false. */\n antialias?: boolean;\n /** Default: false. */\n preserveDrawingBuffer?: boolean;\n /** Default: false — disabled for fullscreen-quad workloads. */\n depth?: boolean;\n /** Default: false. */\n stencil?: boolean;\n /** Default: \"default\". */\n powerPreference?: WebGLPowerPreference;\n /** Default: false. */\n failIfMajorPerformanceCaveat?: boolean;\n}\n\n/** Read-only WebGL2 capability limits, queried at creation and refreshed after\n * context restoration because extension objects do not survive context loss. */\nexport interface GLEngineCaps {\n /** `gl.MAX_TEXTURE_SIZE` — largest supported texture dimension, in texels. */\n readonly maxTextureSize: number;\n /** `gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS` — number of sampler binding slots. */\n readonly maxTextureUnits: number;\n /** The `KHR_parallel_shader_compile` extension used for async link polling,\n * or null when unsupported — linking is then treated as synchronous. */\n readonly parallelShaderCompile: { COMPLETION_STATUS_KHR: number } | null;\n /** True when 32-bit float color attachments are renderable\n * (`EXT_color_buffer_float`). Mirrors Babylon's `caps.textureFloatRender`. */\n readonly textureFloatRender: boolean;\n /** True when 32-bit float textures support linear filtering\n * (`OES_texture_float_linear`). Mirrors `caps.textureFloatLinearFiltering`. */\n readonly textureFloatLinearFiltering: boolean;\n /** True when 16-bit half-float color attachments are renderable\n * (`EXT_color_buffer_float` or `EXT_color_buffer_half_float`). Mirrors\n * `caps.textureHalfFloatRender`. */\n readonly textureHalfFloatRender: boolean;\n /** Half-float linear filtering — always `true` in WebGL2 (it is core).\n * Kept as a field to mirror Babylon's `caps.textureHalfFloatLinearFiltering`. */\n readonly textureHalfFloatLinearFiltering: boolean;\n /** Whether non-power-of-two textures need POT dimensions for mips / wrap.\n * Always `false` in WebGL2 (NPOT is core). Mirrors `engine.needPOTTextures`. */\n readonly needPOTTextures: boolean;\n}\n\n/**\n * Pure-state handle for a WebGL2 canvas + its cached GL state.\n *\n * INVARIANT: consumers MUST NOT mutate GL state directly through `engine.gl`.\n * Doing so silently corrupts the cache in `_state`. The package owns every\n * GL call. (`engine.gl` is exposed only so downstream code that already has the\n * pattern of poking `engine._gl.getExtension(...)` can do that, but must NOT\n * call `bindTexture`/`useProgram`/`bindBuffer`/`viewport`/etc.)\n */\nexport interface GLEngineContext {\n /** The canvas the WebGL2 context was acquired from. An `OffscreenCanvas` is\n * supported for worker render paths (e.g. the Lottie player); it has no CSS\n * box, so it must be sized explicitly via `setGLEngineSize` rather than the\n * CSS-derived `resizeGLEngine`. */\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** The raw WebGL2 context. Do NOT mutate GL state through it — see the\n * type-level invariant above; the package owns every state-changing call. */\n readonly gl: WebGL2RenderingContext;\n /** Queried capability limits for this context. */\n readonly caps: GLEngineCaps;\n /**\n * Hardware-scaling-level — drawingBufferWidth = clientWidth * dpr / _hsl.\n * @internal\n */\n _hsl: number;\n /**\n * rAF id when a render loop is active, 0 otherwise.\n * @internal\n */\n _rafId: number;\n /**\n * Per-frame callbacks. `runRenderLoop` is a no-op if `fn` is already\n * registered (matches Babylon `AbstractEngine.runRenderLoop`).\n * @internal\n */\n _loops: ((dt: number) => void)[];\n /**\n * Timestamp of last frame for delta computation.\n * @internal\n */\n _prevNow: number;\n /**\n * Cached GL state. See §4 of 00-lite-gl.md.\n * @internal\n */\n _state: GLState;\n /**\n * Live effect registry — populated by `createEffect`, removed by\n * `disposeEffect`. Used by the context-restored protocol to rebuild\n * programs.\n * @internal\n */\n _effects: GLEffect[];\n /**\n * Per-engine effect cache keyed by source descriptor (vertex+fragment\n * source, defines, attribute/uniform/sampler names). `createEffect` returns\n * (and ref-counts) the cached `GLEffect` when an identical descriptor is\n * requested, so identical shaders share ONE WebGLProgram — letting\n * `useEffect`'s current-program cache elide redundant `gl.useProgram`.\n * @internal\n */\n _effectCache: Map<string, GLEffect>;\n /**\n * Live texture registry — populated by `createRawTexture` /\n * `loadTexture2D` / `createHtmlElementTexture`. Used by the\n * context-restored protocol to replay uploads.\n * @internal\n */\n _textures: (GLTexture | GLTexture3D)[];\n /**\n * Live render-target registry — populated by `createRenderTarget`. Used by\n * the context-restored protocol to rebuild framebuffers + attachments after\n * their color textures have been replayed. Empty (and tree-shaken) when the\n * render-target module is unused.\n * @internal\n */\n _renderTargets: GLRenderTarget[];\n /**\n * The render target currently bound for drawing (`bindRenderTarget`), or\n * `null` for the default canvas framebuffer. Tracked so that leaving a\n * mipmapped target (`bindRenderTarget(engine, null)` or switching to\n * another target) can regenerate its mip chain — mirroring Babylon's\n * auto-mipmap on `unBindFramebuffer`. Reset to `null` on context-lost.\n * @internal\n */\n _currentRenderTarget: GLRenderTarget | null;\n /**\n * Live vertex / index buffer registry — populated by `createVertexBuffer` /\n * `createIndexBuffer`. Used by the context-restored protocol to re-upload\n * the retained CPU data into fresh GL buffers. Empty (and tree-shaken) when\n * the mesh module is unused.\n * @internal\n */\n _buffers: GLManagedBuffer[];\n /** @internal */\n _onLost: (() => void)[];\n /** @internal */\n _onRestored: (() => void)[];\n /**\n * True between `webglcontextlost` and `webglcontextrestored`. While\n * true, every `setEffect*` / `bindTexture` / `drawEffect` is a no-op.\n * @internal\n */\n _isLost: boolean;\n /**\n * True once the context has been disposed; subsequent calls become no-ops.\n * @internal\n */\n _disposed: boolean;\n /**\n * DOM handlers — retained so dispose can `removeEventListener` them.\n * @internal\n */\n _lostHandler: (e: Event) => void;\n /** @internal */\n _restoredHandler: () => void;\n /**\n * True when a render loop was active at the moment of `webglcontextlost`,\n * so we can resume it from the restored handler.\n * @internal\n */\n _wasLoopActive: boolean;\n /**\n * Installed by `runRenderLoop` on first call. Lets the context-restored\n * handler resume a loop without a circular runtime import from render-loop.\n * Null if the render-loop module is tree-shaken out.\n * @internal\n */\n _scheduleFrame: ((engine: GLEngineContext) => void) | null;\n /** Optional feature-owned state-cache invalidators. Allocated lazily by the first feature that needs one.\n * @internal */\n _stateCacheInvalidators?: (() => void)[];\n}\n\n/** Acquire a WebGL2 context on the canvas and build the pure-state handle.\n * Accepts an `HTMLCanvasElement` or an `OffscreenCanvas` (worker render paths —\n * e.g. the Lottie player — which size the drawing buffer via `setGLEngineSize`).\n * Throws if WebGL2 is unsupported. */\nexport function createGLEngine(canvas: HTMLCanvasElement | OffscreenCanvas, options?: GLEngineOptions): GLEngineContext {\n const o = options ?? {};\n const attrs: WebGLContextAttributes = {\n alpha: o.alpha ?? true,\n premultipliedAlpha: o.premultipliedAlpha ?? true,\n antialias: o.antialias ?? false,\n preserveDrawingBuffer: o.preserveDrawingBuffer ?? false,\n depth: o.depth ?? false,\n stencil: o.stencil ?? false,\n powerPreference: o.powerPreference ?? \"default\",\n failIfMajorPerformanceCaveat: o.failIfMajorPerformanceCaveat ?? false,\n };\n const gl = canvas.getContext(\"webgl2\", attrs) as WebGL2RenderingContext | null;\n if (gl === null) {\n throw new Error(\"lite-gl: WebGL2 is not supported on this canvas\");\n }\n\n const caps = queryCaps(gl);\n\n const engine: GLEngineContext = {\n canvas,\n gl,\n caps,\n _hsl: 1,\n _rafId: 0,\n _loops: [],\n _prevNow: 0,\n _state: createGLState(caps.maxTextureUnits),\n _effects: [],\n _effectCache: new Map(),\n _textures: [],\n _renderTargets: [],\n _currentRenderTarget: null,\n _buffers: [],\n _onLost: [],\n _onRestored: [],\n _isLost: false,\n _disposed: false,\n _lostHandler: () => {},\n _restoredHandler: () => {},\n _wasLoopActive: false,\n _scheduleFrame: null,\n };\n\n engine._lostHandler = (e: Event) => handleContextLost(engine, e);\n engine._restoredHandler = () => handleContextRestored(engine);\n canvas.addEventListener(\"webglcontextlost\", engine._lostHandler as EventListener, false);\n canvas.addEventListener(\"webglcontextrestored\", engine._restoredHandler, false);\n\n return engine;\n}\n\n/** Stops the render loop, removes DOM listeners, releases all known effects\n * and textures, then marks the context disposed. The browser-owned canvas\n * is left intact. */\nexport function disposeGLEngine(engine: GLEngineContext): void {\n if (engine._disposed) {\n return;\n }\n engine._disposed = true;\n if (engine._rafId !== 0) {\n cancelAnimationFrame(engine._rafId);\n engine._rafId = 0;\n }\n engine._loops.length = 0;\n engine.canvas.removeEventListener(\"webglcontextlost\", engine._lostHandler as EventListener, false);\n engine.canvas.removeEventListener(\"webglcontextrestored\", engine._restoredHandler, false);\n\n const gl = engine.gl;\n // Iterate snapshots — the dispose paths splice into the registries.\n const effects = engine._effects.slice();\n for (const eff of effects) {\n if (!eff._disposed) {\n eff._disposed = true;\n eff.isReady = false;\n gl.deleteProgram(eff.program);\n gl.deleteShader(eff._vs);\n gl.deleteShader(eff._fs);\n }\n }\n engine._effects.length = 0;\n engine._effectCache.clear();\n const textures = engine._textures.slice();\n for (const tex of textures) {\n if (!tex._disposed) {\n tex._disposed = true;\n gl.deleteTexture(tex.handle);\n }\n }\n engine._textures.length = 0;\n // Render targets own their FBO + renderbuffer + color texture; free them via\n // the per-RT closure so context.ts needs no runtime import of render-target.\n const rts = engine._renderTargets.slice();\n for (const rt of rts) {\n if (!rt._disposed) {\n rt._disposed = true;\n rt._deleteGpu(gl);\n }\n }\n engine._renderTargets.length = 0;\n\n // Mesh vertex/index buffers own a single GL buffer each; free via closure.\n const buffers = engine._buffers.slice();\n for (const buf of buffers) {\n if (!buf._disposed) {\n buf._disposed = true;\n buf._deleteGpu(gl);\n }\n }\n engine._buffers.length = 0;\n\n resetGLState(engine._state);\n engine._currentRenderTarget = null;\n engine._onLost.length = 0;\n engine._onRestored.length = 0;\n engine._stateCacheInvalidators?.splice(0);\n}\n\n/** Match drawing-buffer size to (clientSize × devicePixelRatio / _hsl). No-op\n * if size already matches. Never touches viewport — `setViewport` owns that. */\nexport function resizeGLEngine(engine: GLEngineContext): void {\n if (engine._disposed || engine._isLost) {\n return;\n }\n const canvas = engine.canvas;\n // An OffscreenCanvas has no CSS box (no clientWidth/clientHeight); it is sized\n // explicitly via setGLEngineSize, so CSS-derived auto-resize is a no-op for it.\n if (!(\"clientWidth\" in canvas)) {\n return;\n }\n const dpr = typeof devicePixelRatio === \"number\" ? devicePixelRatio : 1;\n const w = Math.max(1, Math.floor((canvas.clientWidth * dpr) / engine._hsl));\n const h = Math.max(1, Math.floor((canvas.clientHeight * dpr) / engine._hsl));\n if (canvas.width !== w) {\n canvas.width = w;\n }\n if (canvas.height !== h) {\n canvas.height = h;\n }\n}\n\n/**\n * Set the drawing-buffer size to an EXPLICIT width/height in physical pixels\n * (each divided by `_hsl`), independent of the canvas client/CSS size — the\n * counterpart of Babylon's `ThinEngine.setSize`. Use when the render resolution\n * is computed directly (e.g. animation dimensions × scale × dpr) rather than\n * derived from CSS layout via {@link resizeGLEngine}. No-op on a disposed\n * engine. Never touches the viewport — `setViewport` owns that.\n *\n * @param engine - The engine to resize.\n * @param width - Target drawing-buffer width in physical pixels.\n * @param height - Target drawing-buffer height in physical pixels.\n */\nexport function setGLEngineSize(engine: GLEngineContext, width: number, height: number): void {\n if (engine._disposed) {\n return;\n }\n const canvas = engine.canvas;\n const w = Math.max(1, Math.floor(width / engine._hsl));\n const h = Math.max(1, Math.floor(height / engine._hsl));\n if (canvas.width !== w) {\n canvas.width = w;\n }\n if (canvas.height !== h) {\n canvas.height = h;\n }\n}\n\n/**\n * Invalidate lite-gl's cached GL state so the next state-setting call in each\n * category (program / buffer / texture / VAO / framebuffer bindings, blend,\n * depth, stencil, scissor, color-mask, viewport, unpack) is re-issued instead\n * of elided.\n *\n * Use this when a host application that SHARES this WebGL2 context mutates raw\n * `gl.*` state outside lite-gl — e.g. a save/restore wrapper that resets the\n * context to GL defaults around each render scope, or any interop layer that\n * issues GL calls directly. Without it, lite-gl's redundant-call elision would\n * skip the state changes needed to re-establish the scope, producing corrupted\n * output. Owned GPU resources (the shared quad, render targets, meshes,\n * effects, textures) are preserved — only the cached \"current GL state\" is\n * reset. Mirrors Babylon's `Engine.wipeCaches()`.\n *\n * No-op while the context is lost or the engine is disposed.\n */\nexport function wipeGLStateCache(engine: GLEngineContext): void {\n if (engine._disposed || engine._isLost) {\n return;\n }\n resetGLStateCache(engine._state);\n const invalidators = engine._stateCacheInvalidators;\n if (invalidators) {\n for (const invalidate of invalidators) {\n invalidate();\n }\n }\n}\n\n/** Drawing-buffer width in physical pixels (`canvas.width`). */\nexport function getRenderWidth(engine: GLEngineContext): number {\n return engine.canvas.width;\n}\n\n/** Drawing-buffer height in physical pixels (`canvas.height`). */\nexport function getRenderHeight(engine: GLEngineContext): number {\n return engine.canvas.height;\n}\n\n/** Current hardware-scaling factor — drawing-buffer = clientSize × dpr / level. */\nexport function getHardwareScalingLevel(engine: GLEngineContext): number {\n return engine._hsl;\n}\n\n/** Updates the hardware-scaling factor and triggers a resize. */\nexport function setHardwareScalingLevel(engine: GLEngineContext, level: number): void {\n if (level <= 0 || !isFinite(level)) {\n return;\n }\n engine._hsl = level;\n resizeGLEngine(engine);\n}\n\n/** The backing canvas element (an `HTMLCanvasElement`, or an `OffscreenCanvas`\n * for worker render paths). */\nexport function getRenderingCanvas(engine: GLEngineContext): HTMLCanvasElement | OffscreenCanvas {\n return engine.canvas;\n}\n\n/** Register a `webglcontextlost` callback. Duplicate registrations are ignored. */\nexport function onContextLost(engine: GLEngineContext, cb: () => void): void {\n if (engine._onLost.indexOf(cb) === -1) {\n engine._onLost.push(cb);\n }\n}\n\n/** Remove a previously-registered context-lost callback. */\nexport function offContextLost(engine: GLEngineContext, cb: () => void): void {\n const i = engine._onLost.indexOf(cb);\n if (i !== -1) {\n engine._onLost.splice(i, 1);\n }\n}\n\n/** Register a `webglcontextrestored` callback. Duplicate registrations are ignored. */\nexport function onContextRestored(engine: GLEngineContext, cb: () => void): void {\n if (engine._onRestored.indexOf(cb) === -1) {\n engine._onRestored.push(cb);\n }\n}\n\n/** Remove a previously-registered context-restored callback. */\nexport function offContextRestored(engine: GLEngineContext, cb: () => void): void {\n const i = engine._onRestored.indexOf(cb);\n if (i !== -1) {\n engine._onRestored.splice(i, 1);\n }\n}\n\n/* ───────────────────────── internal: loss / restore ───────────────────── */\n\nfunction handleContextLost(engine: GLEngineContext, e: Event): void {\n // Opt-in to restore. Without preventDefault() the browser will NOT fire\n // webglcontextrestored later.\n e.preventDefault();\n if (engine._isLost || engine._disposed) {\n return;\n }\n engine._isLost = true;\n // `tick` clears `_rafId` while callbacks run, so a loss event delivered in\n // that window still represents an active loop when callbacks remain.\n engine._wasLoopActive = engine._loops.length > 0;\n if (engine._rafId !== 0) {\n cancelAnimationFrame(engine._rafId);\n engine._rafId = 0;\n }\n resetGLState(engine._state);\n engine._currentRenderTarget = null;\n for (const eff of engine._effects) {\n eff.isReady = false;\n eff._samplersAssigned = false;\n eff.uniformLocations = {};\n eff.attributeLocations = {};\n // Clear value caches so the first frame after restore re-uploads\n // every uniform into the freshly-linked program.\n clearObject(eff._lastF1);\n clearObject(eff._lastVec);\n clearObject(eff._lastI1);\n // Do NOT gl.deleteProgram — handle is already dead per WebGL spec.\n }\n for (const tex of engine._textures) {\n tex._wasReady = tex.isReady;\n tex.isReady = false;\n }\n const cbs = engine._onLost.slice();\n for (const cb of cbs) {\n try {\n cb();\n } catch (err) {\n console.error(\"lite-gl: onLost callback threw\", err);\n }\n }\n}\n\nfunction handleContextRestored(engine: GLEngineContext): void {\n if (engine._disposed) {\n return;\n }\n Object.assign(engine.caps, queryCaps(engine.gl));\n for (const eff of engine._effects) {\n if (!eff._disposed) {\n eff._restore(engine);\n }\n }\n for (const tex of engine._textures) {\n if (!tex._disposed) {\n const newHandle = engine.gl.createTexture();\n if (newHandle !== null) {\n tex.handle = newHandle;\n tex._upload(engine);\n tex._initializeParameters?.(engine);\n tex.isReady = tex._wasReady;\n }\n }\n }\n // Clear the lost flag BEFORE the render-target / buffer rebuilds: their\n // `_restore` closures route through the same guarded build/upload paths used\n // at create time (which no-op while `_isLost`), whereas the effect / texture\n // replay above is unguarded and unaffected by the flag's value.\n engine._isLost = false;\n // Render targets rebuild their own color texture + FBO + renderbuffer AFTER\n // the standalone texture replay above (an RT's color texture is owned by the\n // RT, not the `_textures` registry).\n for (const rt of engine._renderTargets) {\n if (!rt._disposed) {\n rt._restore(engine);\n }\n }\n // Mesh buffers re-upload their retained CPU data into fresh GL buffers.\n for (const buf of engine._buffers) {\n if (!buf._disposed) {\n buf._restore(engine);\n }\n }\n if (engine._wasLoopActive && engine._loops.length > 0 && engine._scheduleFrame !== null) {\n engine._scheduleFrame(engine);\n }\n const cbs = engine._onRestored.slice();\n for (const cb of cbs) {\n try {\n cb();\n } catch (err) {\n console.error(\"lite-gl: onRestored callback threw\", err);\n }\n }\n}\n\nfunction queryCaps(gl: WebGL2RenderingContext): GLEngineCaps {\n const parallelExt = gl.getExtension(\"KHR_parallel_shader_compile\") as { COMPLETION_STATUS_KHR: number } | null;\n // `getExtension` both queries and enables these capabilities, so they must\n // be reacquired after context restoration before resources are rebuilt.\n const colorBufferFloat = gl.getExtension(\"EXT_color_buffer_float\") !== null;\n const colorBufferHalfFloat = gl.getExtension(\"EXT_color_buffer_half_float\") !== null;\n const floatLinear = gl.getExtension(\"OES_texture_float_linear\") !== null;\n return {\n maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE) as number,\n maxTextureUnits: gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS) as number,\n parallelShaderCompile: parallelExt,\n textureFloatRender: colorBufferFloat,\n textureFloatLinearFiltering: floatLinear,\n textureHalfFloatRender: colorBufferFloat || colorBufferHalfFloat,\n textureHalfFloatLinearFiltering: true,\n needPOTTextures: false,\n };\n}\n\nfunction clearObject(o: { [k: string]: unknown }): void {\n for (const key in o) {\n delete o[key];\n }\n}\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,iBAAiB,EAAgB,MAAM,YAAY,CAAC;AAyM1F;;;uCAGuC;AACvC,MAAM,UAAU,cAAc,CAAC,MAA2C,EAAE,OAAyB;IACjG,MAAM,CAAC,GAAG,OAAO,IAAI,EAAE,CAAC;IACxB,MAAM,KAAK,GAA2B;QAClC,KAAK,EAAE,CAAC,CAAC,KAA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E,IAAI,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC;YACD,EAAE,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,GAAG,CAAC,CAAC;QAC7D,CAAC;IACL,CAAC;AACL,CAAC;AAED,SAAS,SAAS,CAAC,EAA0B;IACzC,MAAM,WAAW,GAAG,EAAE,CAAC,YAAY,CAAC,6BAA6B,CAA6C,CAAC;IAC/G,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,gBAAgB,GAAG,EAAE,CAAC,YAAY,CAAC,wBAAwB,CAAC,KAAK,IAAI,CAAC;IAC5E,MAAM,oBAAoB,GAAG,EAAE,CAAC,YAAY,CAAC,6BAA6B,CAAC,KAAK,IAAI,CAAC;IACrF,MAAM,WAAW,GAAG,EAAE,CAAC,YAAY,CAAC,0BAA0B,CAAC,KAAK,IAAI,CAAC;IACzE,OAAO;QACH,cAAc,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,gBAAgB,CAAW;QAC9D,eAAe,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,CAAC,gCAAgC,CAAW;QAC/E,qBAAqB,EAAE,WAAW;QAClC,kBAAkB,EAAE,gBAAgB;QACpC,2BAA2B,EAAE,WAAW;QACxC,sBAAsB,EAAE,gBAAgB,IAAI,oBAAoB;QAChE,+BAA+B,EAAE,IAAI;QACrC,eAAe,EAAE,KAAK;KACzB,CAAC;AACN,CAAC;AAED,SAAS,WAAW,CAAC,CAA2B;IAC5C,KAAK,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;QAClB,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC;IAClB,CAAC;AACL,CAAC","sourcesContent":["import type { GLEffect } from \"./effect.js\";\nimport type { GLTexture } from \"./texture.js\";\nimport type { GLTexture3D } from \"./texture-3d.js\";\nimport type { GLRenderTarget } from \"./render-target.js\";\nimport { createGLState, resetGLState, resetGLStateCache, type GLState } from \"./state.js\";\n\n/**\n * Minimal shape of a context-restorable GL buffer (vertex / index), kept local\n * to this module so the public `GLEngineContext` type carries no dependency on\n * the tree-shakeable `mesh` entry. `mesh.ts`'s `GLVertexBuffer` /\n * `GLIndexBuffer` satisfy it structurally.\n * @internal\n */\nexport interface GLManagedBuffer {\n handle: WebGLBuffer;\n /** @internal */\n _disposed: boolean;\n /** @internal */\n _deleteGpu: (gl: WebGL2RenderingContext) => void;\n /** @internal */\n _restore: (engine: GLEngineContext) => void;\n}\n\n/** Constructor options forwarded to `canvas.getContext('webgl2', …)`. */\nexport interface GLEngineOptions {\n /** Default: true. */\n alpha?: boolean;\n /** Default: true. */\n premultipliedAlpha?: boolean;\n /** Default: false. */\n antialias?: boolean;\n /** Default: false. */\n preserveDrawingBuffer?: boolean;\n /** Default: false — disabled for fullscreen-quad workloads. */\n depth?: boolean;\n /** Default: false. */\n stencil?: boolean;\n /** Default: \"default\". */\n powerPreference?: WebGLPowerPreference;\n /** Default: false. */\n failIfMajorPerformanceCaveat?: boolean;\n}\n\n/** Read-only WebGL2 capability limits, queried at creation and refreshed after\n * context restoration because extension objects do not survive context loss. */\nexport interface GLEngineCaps {\n /** `gl.MAX_TEXTURE_SIZE` — largest supported texture dimension, in texels. */\n readonly maxTextureSize: number;\n /** `gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS` — number of sampler binding slots. */\n readonly maxTextureUnits: number;\n /** The `KHR_parallel_shader_compile` extension used for async link polling,\n * or null when unsupported — linking is then treated as synchronous. */\n readonly parallelShaderCompile: { COMPLETION_STATUS_KHR: number } | null;\n /** True when 32-bit float color attachments are renderable\n * (`EXT_color_buffer_float`). Mirrors Babylon's `caps.textureFloatRender`. */\n readonly textureFloatRender: boolean;\n /** True when 32-bit float textures support linear filtering\n * (`OES_texture_float_linear`). Mirrors `caps.textureFloatLinearFiltering`. */\n readonly textureFloatLinearFiltering: boolean;\n /** True when 16-bit half-float color attachments are renderable\n * (`EXT_color_buffer_float` or `EXT_color_buffer_half_float`). Mirrors\n * `caps.textureHalfFloatRender`. */\n readonly textureHalfFloatRender: boolean;\n /** Half-float linear filtering — always `true` in WebGL2 (it is core).\n * Kept as a field to mirror Babylon's `caps.textureHalfFloatLinearFiltering`. */\n readonly textureHalfFloatLinearFiltering: boolean;\n /** Whether non-power-of-two textures need POT dimensions for mips / wrap.\n * Always `false` in WebGL2 (NPOT is core). Mirrors `engine.needPOTTextures`. */\n readonly needPOTTextures: boolean;\n}\n\n/**\n * Pure-state handle for a WebGL2 canvas + its cached GL state.\n *\n * INVARIANT: consumers MUST NOT mutate GL state directly through `engine.gl`.\n * Doing so silently corrupts the cache in `_state`. The package owns every\n * GL call. (`engine.gl` is exposed only so downstream code that already has the\n * pattern of poking `engine._gl.getExtension(...)` can do that, but must NOT\n * call `bindTexture`/`useProgram`/`bindBuffer`/`viewport`/etc.)\n */\nexport interface GLEngineContext {\n /** The canvas the WebGL2 context was acquired from. An `OffscreenCanvas` is\n * supported for worker render paths (e.g. the Lottie player); it has no CSS\n * box, so it must be sized explicitly via `setGLEngineSize` rather than the\n * CSS-derived `resizeGLEngine`. */\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** The raw WebGL2 context. Do NOT mutate GL state through it — see the\n * type-level invariant above; the package owns every state-changing call. */\n readonly gl: WebGL2RenderingContext;\n /** Queried capability limits for this context. */\n readonly caps: GLEngineCaps;\n /**\n * Hardware-scaling-level — drawingBufferWidth = clientWidth * dpr / _hsl.\n * @internal\n */\n _hsl: number;\n /**\n * rAF id when a render loop is active, 0 otherwise.\n * @internal\n */\n _rafId: number;\n /**\n * Per-frame callbacks. `runRenderLoop` is a no-op if `fn` is already\n * registered (matches Babylon `AbstractEngine.runRenderLoop`).\n * @internal\n */\n _loops: ((dt: number) => void)[];\n /**\n * Timestamp of last frame for delta computation.\n * @internal\n */\n _prevNow: number;\n /**\n * Cached GL state. See §4 of 00-lite-gl.md.\n * @internal\n */\n _state: GLState;\n /**\n * Live effect registry — populated by `createEffect`, removed by\n * `disposeEffect`. Used by the context-restored protocol to rebuild\n * programs.\n * @internal\n */\n _effects: GLEffect[];\n /**\n * Per-engine effect cache keyed by source descriptor (vertex+fragment\n * source, defines, attribute/uniform/sampler names). `createEffect` returns\n * (and ref-counts) the cached `GLEffect` when an identical descriptor is\n * requested, so identical shaders share ONE WebGLProgram — letting\n * `useEffect`'s current-program cache elide redundant `gl.useProgram`.\n * @internal\n */\n _effectCache: Map<string, GLEffect>;\n /**\n * Live managed 2D/3D texture registry. Set deletion avoids linear searches\n * and array shifts during eviction; iteration preserves creation order\n * among survivors for context-restore replay.\n * @internal\n */\n _textures: Set<GLTexture | GLTexture3D>;\n /**\n * Live render-target registry — populated by `createRenderTarget`. Used by\n * the context-restored protocol to rebuild framebuffers + attachments after\n * their color textures have been replayed. Empty (and tree-shaken) when the\n * render-target module is unused.\n * @internal\n */\n _renderTargets: GLRenderTarget[];\n /**\n * The render target currently bound for drawing (`bindRenderTarget`), or\n * `null` for the default canvas framebuffer. Tracked so that leaving a\n * mipmapped target (`bindRenderTarget(engine, null)` or switching to\n * another target) can regenerate its mip chain — mirroring Babylon's\n * auto-mipmap on `unBindFramebuffer`. Reset to `null` on context-lost.\n * @internal\n */\n _currentRenderTarget: GLRenderTarget | null;\n /**\n * Live vertex / index buffer registry — populated by `createVertexBuffer` /\n * `createIndexBuffer`. Used by the context-restored protocol to re-upload\n * the retained CPU data into fresh GL buffers. Empty (and tree-shaken) when\n * the mesh module is unused.\n * @internal\n */\n _buffers: GLManagedBuffer[];\n /** @internal */\n _onLost: (() => void)[];\n /** @internal */\n _onRestored: (() => void)[];\n /**\n * True between `webglcontextlost` and `webglcontextrestored`. While\n * true, every `setEffect*` / `bindTexture` / `drawEffect` is a no-op.\n * @internal\n */\n _isLost: boolean;\n /**\n * True once the context has been disposed; subsequent calls become no-ops.\n * @internal\n */\n _disposed: boolean;\n /**\n * DOM handlers — retained so dispose can `removeEventListener` them.\n * @internal\n */\n _lostHandler: (e: Event) => void;\n /** @internal */\n _restoredHandler: () => void;\n /**\n * True when a render loop was active at the moment of `webglcontextlost`,\n * so we can resume it from the restored handler.\n * @internal\n */\n _wasLoopActive: boolean;\n /**\n * Installed by `runRenderLoop` on first call. Lets the context-restored\n * handler resume a loop without a circular runtime import from render-loop.\n * Null if the render-loop module is tree-shaken out.\n * @internal\n */\n _scheduleFrame: ((engine: GLEngineContext) => void) | null;\n /** Optional feature-owned state-cache invalidators. Allocated lazily by the first feature that needs one.\n * @internal */\n _stateCacheInvalidators?: (() => void)[];\n}\n\n/** Acquire a WebGL2 context on the canvas and build the pure-state handle.\n * Accepts an `HTMLCanvasElement` or an `OffscreenCanvas` (worker render paths —\n * e.g. the Lottie player — which size the drawing buffer via `setGLEngineSize`).\n * Throws if WebGL2 is unsupported. */\nexport function createGLEngine(canvas: HTMLCanvasElement | OffscreenCanvas, options?: GLEngineOptions): GLEngineContext {\n const o = options ?? {};\n const attrs: WebGLContextAttributes = {\n alpha: o.alpha ?? true,\n premultipliedAlpha: o.premultipliedAlpha ?? true,\n antialias: o.antialias ?? false,\n preserveDrawingBuffer: o.preserveDrawingBuffer ?? false,\n depth: o.depth ?? false,\n stencil: o.stencil ?? false,\n powerPreference: o.powerPreference ?? \"default\",\n failIfMajorPerformanceCaveat: o.failIfMajorPerformanceCaveat ?? false,\n };\n const gl = canvas.getContext(\"webgl2\", attrs) as WebGL2RenderingContext | null;\n if (gl === null) {\n throw new Error(\"lite-gl: WebGL2 is not supported on this canvas\");\n }\n\n const caps = queryCaps(gl);\n\n const engine: GLEngineContext = {\n canvas,\n gl,\n caps,\n _hsl: 1,\n _rafId: 0,\n _loops: [],\n _prevNow: 0,\n _state: createGLState(caps.maxTextureUnits),\n _effects: [],\n _effectCache: new Map(),\n _textures: new Set(),\n _renderTargets: [],\n _currentRenderTarget: null,\n _buffers: [],\n _onLost: [],\n _onRestored: [],\n _isLost: false,\n _disposed: false,\n _lostHandler: () => {},\n _restoredHandler: () => {},\n _wasLoopActive: false,\n _scheduleFrame: null,\n };\n\n engine._lostHandler = (e: Event) => handleContextLost(engine, e);\n engine._restoredHandler = () => handleContextRestored(engine);\n canvas.addEventListener(\"webglcontextlost\", engine._lostHandler as EventListener, false);\n canvas.addEventListener(\"webglcontextrestored\", engine._restoredHandler, false);\n\n return engine;\n}\n\n/** Stops the render loop, removes DOM listeners, releases all known effects\n * and textures, then marks the context disposed. The browser-owned canvas\n * is left intact. */\nexport function disposeGLEngine(engine: GLEngineContext): void {\n if (engine._disposed) {\n return;\n }\n engine._disposed = true;\n if (engine._rafId !== 0) {\n cancelAnimationFrame(engine._rafId);\n engine._rafId = 0;\n }\n engine._loops.length = 0;\n engine.canvas.removeEventListener(\"webglcontextlost\", engine._lostHandler as EventListener, false);\n engine.canvas.removeEventListener(\"webglcontextrestored\", engine._restoredHandler, false);\n\n const gl = engine.gl;\n const textures = Array.from(engine._textures);\n engine._textures.clear();\n // Iterate snapshots — dispose paths can mutate the live registries.\n const effects = engine._effects.slice();\n for (const eff of effects) {\n if (!eff._disposed) {\n eff._disposed = true;\n eff.isReady = false;\n gl.deleteProgram(eff.program);\n gl.deleteShader(eff._vs);\n gl.deleteShader(eff._fs);\n }\n }\n engine._effects.length = 0;\n engine._effectCache.clear();\n for (const tex of textures) {\n // The snapshot contains live textures only. Force-delete every handle,\n // even if reentrant disposal marks a later texture disposed first.\n tex._disposed = true;\n gl.deleteTexture(tex.handle);\n }\n // Render targets own their FBO + renderbuffer + color texture; free them via\n // the per-RT closure so context.ts needs no runtime import of render-target.\n const rts = engine._renderTargets.slice();\n for (const rt of rts) {\n if (!rt._disposed) {\n rt._disposed = true;\n rt._deleteGpu(gl);\n }\n }\n engine._renderTargets.length = 0;\n\n // Mesh vertex/index buffers own a single GL buffer each; free via closure.\n const buffers = engine._buffers.slice();\n for (const buf of buffers) {\n if (!buf._disposed) {\n buf._disposed = true;\n buf._deleteGpu(gl);\n }\n }\n engine._buffers.length = 0;\n\n resetGLState(engine._state);\n engine._currentRenderTarget = null;\n engine._onLost.length = 0;\n engine._onRestored.length = 0;\n engine._stateCacheInvalidators?.splice(0);\n}\n\n/** Match drawing-buffer size to (clientSize × devicePixelRatio / _hsl). No-op\n * if size already matches. Never touches viewport — `setViewport` owns that. */\nexport function resizeGLEngine(engine: GLEngineContext): void {\n if (engine._disposed || engine._isLost) {\n return;\n }\n const canvas = engine.canvas;\n // An OffscreenCanvas has no CSS box (no clientWidth/clientHeight); it is sized\n // explicitly via setGLEngineSize, so CSS-derived auto-resize is a no-op for it.\n if (!(\"clientWidth\" in canvas)) {\n return;\n }\n const dpr = typeof devicePixelRatio === \"number\" ? devicePixelRatio : 1;\n const w = Math.max(1, Math.floor((canvas.clientWidth * dpr) / engine._hsl));\n const h = Math.max(1, Math.floor((canvas.clientHeight * dpr) / engine._hsl));\n if (canvas.width !== w) {\n canvas.width = w;\n }\n if (canvas.height !== h) {\n canvas.height = h;\n }\n}\n\n/**\n * Set the drawing-buffer size to an EXPLICIT width/height in physical pixels\n * (each divided by `_hsl`), independent of the canvas client/CSS size — the\n * counterpart of Babylon's `ThinEngine.setSize`. Use when the render resolution\n * is computed directly (e.g. animation dimensions × scale × dpr) rather than\n * derived from CSS layout via {@link resizeGLEngine}. No-op on a disposed\n * engine. Never touches the viewport — `setViewport` owns that.\n *\n * @param engine - The engine to resize.\n * @param width - Target drawing-buffer width in physical pixels.\n * @param height - Target drawing-buffer height in physical pixels.\n */\nexport function setGLEngineSize(engine: GLEngineContext, width: number, height: number): void {\n if (engine._disposed) {\n return;\n }\n const canvas = engine.canvas;\n const w = Math.max(1, Math.floor(width / engine._hsl));\n const h = Math.max(1, Math.floor(height / engine._hsl));\n if (canvas.width !== w) {\n canvas.width = w;\n }\n if (canvas.height !== h) {\n canvas.height = h;\n }\n}\n\n/**\n * Invalidate lite-gl's cached GL state so the next state-setting call in each\n * category (program / buffer / texture / VAO / framebuffer bindings, blend,\n * depth, stencil, scissor, color-mask, viewport, unpack) is re-issued instead\n * of elided.\n *\n * Use this when a host application that SHARES this WebGL2 context mutates raw\n * `gl.*` state outside lite-gl — e.g. a save/restore wrapper that resets the\n * context to GL defaults around each render scope, or any interop layer that\n * issues GL calls directly. Without it, lite-gl's redundant-call elision would\n * skip the state changes needed to re-establish the scope, producing corrupted\n * output. Owned GPU resources (the shared quad, render targets, meshes,\n * effects, textures) are preserved — only the cached \"current GL state\" is\n * reset. Mirrors Babylon's `Engine.wipeCaches()`.\n *\n * No-op while the context is lost or the engine is disposed.\n */\nexport function wipeGLStateCache(engine: GLEngineContext): void {\n if (engine._disposed || engine._isLost) {\n return;\n }\n resetGLStateCache(engine._state);\n const invalidators = engine._stateCacheInvalidators;\n if (invalidators) {\n for (const invalidate of invalidators) {\n invalidate();\n }\n }\n}\n\n/** Drawing-buffer width in physical pixels (`canvas.width`). */\nexport function getRenderWidth(engine: GLEngineContext): number {\n return engine.canvas.width;\n}\n\n/** Drawing-buffer height in physical pixels (`canvas.height`). */\nexport function getRenderHeight(engine: GLEngineContext): number {\n return engine.canvas.height;\n}\n\n/** Current hardware-scaling factor — drawing-buffer = clientSize × dpr / level. */\nexport function getHardwareScalingLevel(engine: GLEngineContext): number {\n return engine._hsl;\n}\n\n/** Updates the hardware-scaling factor and triggers a resize. */\nexport function setHardwareScalingLevel(engine: GLEngineContext, level: number): void {\n if (level <= 0 || !isFinite(level)) {\n return;\n }\n engine._hsl = level;\n resizeGLEngine(engine);\n}\n\n/** The backing canvas element (an `HTMLCanvasElement`, or an `OffscreenCanvas`\n * for worker render paths). */\nexport function getRenderingCanvas(engine: GLEngineContext): HTMLCanvasElement | OffscreenCanvas {\n return engine.canvas;\n}\n\n/** Register a `webglcontextlost` callback. Duplicate registrations are ignored. */\nexport function onContextLost(engine: GLEngineContext, cb: () => void): void {\n if (engine._onLost.indexOf(cb) === -1) {\n engine._onLost.push(cb);\n }\n}\n\n/** Remove a previously-registered context-lost callback. */\nexport function offContextLost(engine: GLEngineContext, cb: () => void): void {\n const i = engine._onLost.indexOf(cb);\n if (i !== -1) {\n engine._onLost.splice(i, 1);\n }\n}\n\n/** Register a `webglcontextrestored` callback. Duplicate registrations are ignored. */\nexport function onContextRestored(engine: GLEngineContext, cb: () => void): void {\n if (engine._onRestored.indexOf(cb) === -1) {\n engine._onRestored.push(cb);\n }\n}\n\n/** Remove a previously-registered context-restored callback. */\nexport function offContextRestored(engine: GLEngineContext, cb: () => void): void {\n const i = engine._onRestored.indexOf(cb);\n if (i !== -1) {\n engine._onRestored.splice(i, 1);\n }\n}\n\n/* ───────────────────────── internal: loss / restore ───────────────────── */\n\nfunction handleContextLost(engine: GLEngineContext, e: Event): void {\n // Opt-in to restore. Without preventDefault() the browser will NOT fire\n // webglcontextrestored later.\n e.preventDefault();\n if (engine._isLost || engine._disposed) {\n return;\n }\n engine._isLost = true;\n // `tick` clears `_rafId` while callbacks run, so a loss event delivered in\n // that window still represents an active loop when callbacks remain.\n engine._wasLoopActive = engine._loops.length > 0;\n if (engine._rafId !== 0) {\n cancelAnimationFrame(engine._rafId);\n engine._rafId = 0;\n }\n resetGLState(engine._state);\n engine._currentRenderTarget = null;\n for (const eff of engine._effects) {\n eff.isReady = false;\n eff._samplersAssigned = false;\n eff.uniformLocations = {};\n eff.attributeLocations = {};\n // Clear value caches so the first frame after restore re-uploads\n // every uniform into the freshly-linked program.\n clearObject(eff._lastF1);\n clearObject(eff._lastVec);\n clearObject(eff._lastI1);\n // Do NOT gl.deleteProgram — handle is already dead per WebGL spec.\n }\n for (const tex of engine._textures) {\n tex._wasReady = tex.isReady;\n tex.isReady = false;\n }\n const cbs = engine._onLost.slice();\n for (const cb of cbs) {\n try {\n cb();\n } catch (err) {\n console.error(\"lite-gl: onLost callback threw\", err);\n }\n }\n}\n\nfunction handleContextRestored(engine: GLEngineContext): void {\n if (engine._disposed) {\n return;\n }\n Object.assign(engine.caps, queryCaps(engine.gl));\n for (const eff of engine._effects) {\n if (!eff._disposed) {\n eff._restore(engine);\n }\n }\n for (const tex of engine._textures) {\n if (!tex._disposed) {\n const newHandle = engine.gl.createTexture();\n if (newHandle !== null) {\n tex.handle = newHandle;\n tex._upload(engine);\n tex._initializeParameters?.(engine);\n tex.isReady = tex._wasReady;\n }\n }\n }\n // Clear the lost flag BEFORE the render-target / buffer rebuilds: their\n // `_restore` closures route through the same guarded build/upload paths used\n // at create time (which no-op while `_isLost`), whereas the effect / texture\n // replay above is unguarded and unaffected by the flag's value.\n engine._isLost = false;\n // Render targets rebuild their own color texture + FBO + renderbuffer AFTER\n // the standalone texture replay above (an RT's color texture is owned by the\n // RT, not the `_textures` registry).\n for (const rt of engine._renderTargets) {\n if (!rt._disposed) {\n rt._restore(engine);\n }\n }\n // Mesh buffers re-upload their retained CPU data into fresh GL buffers.\n for (const buf of engine._buffers) {\n if (!buf._disposed) {\n buf._restore(engine);\n }\n }\n if (engine._wasLoopActive && engine._loops.length > 0 && engine._scheduleFrame !== null) {\n engine._scheduleFrame(engine);\n }\n const cbs = engine._onRestored.slice();\n for (const cb of cbs) {\n try {\n cb();\n } catch (err) {\n console.error(\"lite-gl: onRestored callback threw\", err);\n }\n }\n}\n\nfunction queryCaps(gl: WebGL2RenderingContext): GLEngineCaps {\n const parallelExt = gl.getExtension(\"KHR_parallel_shader_compile\") as { COMPLETION_STATUS_KHR: number } | null;\n // `getExtension` both queries and enables these capabilities, so they must\n // be reacquired after context restoration before resources are rebuilt.\n const colorBufferFloat = gl.getExtension(\"EXT_color_buffer_float\") !== null;\n const colorBufferHalfFloat = gl.getExtension(\"EXT_color_buffer_half_float\") !== null;\n const floatLinear = gl.getExtension(\"OES_texture_float_linear\") !== null;\n return {\n maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE) as number,\n maxTextureUnits: gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS) as number,\n parallelShaderCompile: parallelExt,\n textureFloatRender: colorBufferFloat,\n textureFloatLinearFiltering: floatLinear,\n textureHalfFloatRender: colorBufferFloat || colorBufferHalfFloat,\n textureHalfFloatLinearFiltering: true,\n needPOTTextures: false,\n };\n}\n\nfunction clearObject(o: { [k: string]: unknown }): void {\n for (const key in o) {\n delete o[key];\n }\n}\n"]}
@@ -88,7 +88,7 @@ export function createDynamicTexture(engine, width, height, options) {
88
88
  _dynPremultiplyAlpha: false,
89
89
  };
90
90
  upload(engine);
91
- engine._textures.push(tex);
91
+ engine._textures.add(tex);
92
92
  return tex;
93
93
  }
94
94
  /** Push 2D pixels into a {@link createDynamicTexture} texture from a canvas /
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-texture.js","sourceRoot":"","sources":["../src/dynamic-texture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,cAAc,EAAyC,MAAM,cAAc,CAAC;AAGlI;;;;;;;;;;;;;;;;;;;0CAmB0C;AAC1C,MAAM,UAAU,oBAAoB,CAAC,MAAuB,EAAE,KAAa,EAAE,MAAc,EAAE,OAA0D;IACnJ,MAAM,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC;IACrB,MAAM,MAAM,GAAG,EAAE,CAAC,aAAa,EAAE,CAAC;IAClC,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC/D,CAAC;IACD,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IACjC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,OAAO,IAAI,EAAE,CAAC;IAC3B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC,MAAM,CAAC;IAC9C,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC,MAAM,CAAC;IAC9C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,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AI,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Dynamic (canvas-/bitmap-backed) textures.\n *\n * Part of the public API via the `@babylonjs/lite-gl` barrel. The package is\n * `sideEffects: false`, so consumers that never push 2D pixel sources into a\n * texture tree-shake this code out.\n *\n * The WebGL counterpart of Babylon's `ThinEngine.createDynamicTexture` +\n * `updateDynamicTexture`. A dynamic texture is a blank RGBA8 allocation whose\n * pixels are pushed on demand from a canvas / `OffscreenCanvas` / image / video\n * / `ImageBitmap` / `ImageData` source. The most recent source is retained\n * internally and replayed into the fresh handle on `webglcontextrestored` by the\n * engine's standard context-restore protocol.\n */\nimport { bindTextureForUpload, setBoundTextureParams, setUnpackState, type GLTexture, type GLTextureOptions } from \"./texture.js\";\nimport type { GLEngineContext } from \"./context.js\";\n\n/** Create a texture backed by an empty (blank) `width × height` RGBA8\n * allocation, whose pixels are pushed on demand with\n * {@link updateDynamicTexture} — the WebGL counterpart of Babylon's\n * `ThinEngine.createDynamicTexture` + `ThinTexture` wrapper.\n *\n * The texture is immediately sampleable (reads as transparent black until the\n * first update). It is context-restore-safe: the most recent source pushed via\n * {@link updateDynamicTexture} is replayed into the fresh handle on\n * `webglcontextrestored` (and re-blanked if no update happened yet).\n *\n * `options.invertY` is ignored here (the blank allocation is flip-invariant);\n * per-update flip is controlled by {@link updateDynamicTexture}'s `invertY`.\n *\n * @param engine - The engine to create GL resources on.\n * @param width - Texture width in texels (clamped to ≥ 1).\n * @param height - Texture height in texels (clamped to ≥ 1).\n * @param options - Optional sampling/wrap config (see {@link GLTextureOptions})\n * plus this factory's own `generateMipMaps` flag (mipmaps are built after an\n * update when a source is present; defaults to `false`).\n * @returns The new {@link GLTexture}. */\nexport function createDynamicTexture(engine: GLEngineContext, width: number, height: number, options?: GLTextureOptions & { generateMipMaps?: boolean }): GLTexture {\n const gl = engine.gl;\n const handle = gl.createTexture();\n if (handle === null) {\n throw new Error(\"lite-gl: gl.createTexture returned null\");\n }\n const w = Math.max(1, width | 0);\n const h = Math.max(1, height | 0);\n const opts = options ?? {};\n const minFilter = opts.minFilter ?? gl.LINEAR;\n const magFilter = opts.magFilter ?? gl.LINEAR;\n const wrapS = opts.wrapS ?? gl.CLAMP_TO_EDGE;\n const wrapT = opts.wrapT ?? gl.CLAMP_TO_EDGE;\n const generateMipMaps = opts.generateMipMaps ?? false;\n\n // Single `_upload` closure used for both the initial allocation AND every\n // `webglcontextrestored` replay AND every `updateDynamicTexture`. The pixel\n // upload runs every time; the four `texParameteri` calls run ONLY when the\n // handle changed (initial create + restore install a fresh, GL-default\n // handle) — a per-frame pixel update keeps the same handle, whose filter/wrap\n // GL retains, so re-applying them would be a pure redundant cost.\n const upload = (target: GLEngineContext): void => {\n const g = target.gl;\n bindTextureForUpload(target, tex.handle);\n const src = tex._dynSource;\n if (src !== null && src !== undefined) {\n setUnpackState(target, tex._dynInvertY === true, tex._dynPremultiplyAlpha === true);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, g.RGBA, g.UNSIGNED_BYTE, src);\n } else {\n setUnpackState(target, false, false);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA8, w, h, 0, g.RGBA, g.UNSIGNED_BYTE, null);\n }\n if (tex._dynParamsHandle !== tex.handle) {\n setBoundTextureParams(g, minFilter, magFilter, wrapS, wrapT);\n tex._dynParamsHandle = tex.handle;\n }\n if (generateMipMaps && src !== null && src !== undefined) {\n g.generateMipmap(g.TEXTURE_2D);\n }\n };\n\n const tex: GLTexture = {\n handle,\n target: gl.TEXTURE_2D,\n width: w,\n height: h,\n isReady: true,\n _disposed: false,\n _refCount: 1,\n _upload: upload,\n _wasReady: true,\n _dynSource: null,\n _dynInvertY: false,\n _dynPremultiplyAlpha: false,\n };\n upload(engine);\n engine._textures.push(tex);\n return tex;\n}\n\n/** Push 2D pixels into a {@link createDynamicTexture} texture from a canvas /\n * `OffscreenCanvas` / image / video / `ImageBitmap` / `ImageData` source — the\n * WebGL counterpart of Babylon's `ThinEngine.updateDynamicTexture`. The source\n * is retained on the texture so it is replayed on `webglcontextrestored`.\n * No-op when the context is lost/disposed or the texture is disposed.\n *\n * @param engine - The engine that owns the texture.\n * @param tex - A texture created by {@link createDynamicTexture}.\n * @param source - The 2D pixel source to upload.\n * @param invertY - Flip vertically on upload (`UNPACK_FLIP_Y_WEBGL`). Default `false`.\n * @param premultiplyAlpha - Premultiply on upload (`UNPACK_PREMULTIPLY_ALPHA_WEBGL`).\n * Default `false`, matching Babylon's `updateDynamicTexture` default. */\nexport function updateDynamicTexture(engine: GLEngineContext, tex: GLTexture, source: TexImageSource, invertY = false, premultiplyAlpha = false): void {\n if (engine._isLost || engine._disposed || tex._disposed) {\n return;\n }\n tex._dynSource = source;\n tex._dynInvertY = invertY;\n tex._dynPremultiplyAlpha = premultiplyAlpha;\n tex._upload(engine);\n}\n\n/** Forget the source a dynamic texture retained for context-restore replay.\n * The current GPU pixels are kept (no re-upload), but the source reference is\n * dropped so it can be garbage-collected — and a subsequent\n * `webglcontextrestored` will re-blank the texture instead of replaying. Use\n * after the final {@link updateDynamicTexture} once the source (e.g. a large\n * atlas canvas) is no longer needed. No-op on a non-dynamic texture. */\nexport function clearDynamicTextureSource(tex: GLTexture): void {\n tex._dynSource = null;\n}\n"]}
1
+ {"version":3,"file":"dynamic-texture.js","sourceRoot":"","sources":["../src/dynamic-texture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,cAAc,EAAyC,MAAM,cAAc,CAAC;AAGlI;;;;;;;;;;;;;;;;;;;0CAmB0C;AAC1C,MAAM,UAAU,oBAAoB,CAAC,MAAuB,EAAE,KAAa,EAAE,MAAc,EAAE,OAA0D;IACnJ,MAAM,EAAE,GAAG,MAAM,CAAC,EAAE,CAAC;IACrB,MAAM,MAAM,GAAG,EAAE,CAAC,aAAa,EAAE,CAAC;IAClC,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC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AAE,MAAsB,EAAE,OAAO,GAAG,KAAK,EAAE,gBAAgB,GAAG,KAAK;IAC3I,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,SAAS,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QACtD,OAAO;IACX,CAAC;IACD,GAAG,CAAC,UAAU,GAAG,MAAM,CAAC;IACxB,GAAG,CAAC,WAAW,GAAG,OAAO,CAAC;IAC1B,GAAG,CAAC,oBAAoB,GAAG,gBAAgB,CAAC;IAC5C,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC;AAED;;;;;yEAKyE;AACzE,MAAM,UAAU,yBAAyB,CAAC,GAAc;IACpD,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC;AAC1B,CAAC","sourcesContent":["/**\n * Dynamic (canvas-/bitmap-backed) textures.\n *\n * Part of the public API via the `@babylonjs/lite-gl` barrel. The package is\n * `sideEffects: false`, so consumers that never push 2D pixel sources into a\n * texture tree-shake this code out.\n *\n * The WebGL counterpart of Babylon's `ThinEngine.createDynamicTexture` +\n * `updateDynamicTexture`. A dynamic texture is a blank RGBA8 allocation whose\n * pixels are pushed on demand from a canvas / `OffscreenCanvas` / image / video\n * / `ImageBitmap` / `ImageData` source. The most recent source is retained\n * internally and replayed into the fresh handle on `webglcontextrestored` by the\n * engine's standard context-restore protocol.\n */\nimport { bindTextureForUpload, setBoundTextureParams, setUnpackState, type GLTexture, type GLTextureOptions } from \"./texture.js\";\nimport type { GLEngineContext } from \"./context.js\";\n\n/** Create a texture backed by an empty (blank) `width × height` RGBA8\n * allocation, whose pixels are pushed on demand with\n * {@link updateDynamicTexture} — the WebGL counterpart of Babylon's\n * `ThinEngine.createDynamicTexture` + `ThinTexture` wrapper.\n *\n * The texture is immediately sampleable (reads as transparent black until the\n * first update). It is context-restore-safe: the most recent source pushed via\n * {@link updateDynamicTexture} is replayed into the fresh handle on\n * `webglcontextrestored` (and re-blanked if no update happened yet).\n *\n * `options.invertY` is ignored here (the blank allocation is flip-invariant);\n * per-update flip is controlled by {@link updateDynamicTexture}'s `invertY`.\n *\n * @param engine - The engine to create GL resources on.\n * @param width - Texture width in texels (clamped to ≥ 1).\n * @param height - Texture height in texels (clamped to ≥ 1).\n * @param options - Optional sampling/wrap config (see {@link GLTextureOptions})\n * plus this factory's own `generateMipMaps` flag (mipmaps are built after an\n * update when a source is present; defaults to `false`).\n * @returns The new {@link GLTexture}. */\nexport function createDynamicTexture(engine: GLEngineContext, width: number, height: number, options?: GLTextureOptions & { generateMipMaps?: boolean }): GLTexture {\n const gl = engine.gl;\n const handle = gl.createTexture();\n if (handle === null) {\n throw new Error(\"lite-gl: gl.createTexture returned null\");\n }\n const w = Math.max(1, width | 0);\n const h = Math.max(1, height | 0);\n const opts = options ?? {};\n const minFilter = opts.minFilter ?? gl.LINEAR;\n const magFilter = opts.magFilter ?? gl.LINEAR;\n const wrapS = opts.wrapS ?? gl.CLAMP_TO_EDGE;\n const wrapT = opts.wrapT ?? gl.CLAMP_TO_EDGE;\n const generateMipMaps = opts.generateMipMaps ?? false;\n\n // Single `_upload` closure used for both the initial allocation AND every\n // `webglcontextrestored` replay AND every `updateDynamicTexture`. The pixel\n // upload runs every time; the four `texParameteri` calls run ONLY when the\n // handle changed (initial create + restore install a fresh, GL-default\n // handle) — a per-frame pixel update keeps the same handle, whose filter/wrap\n // GL retains, so re-applying them would be a pure redundant cost.\n const upload = (target: GLEngineContext): void => {\n const g = target.gl;\n bindTextureForUpload(target, tex.handle);\n const src = tex._dynSource;\n if (src !== null && src !== undefined) {\n setUnpackState(target, tex._dynInvertY === true, tex._dynPremultiplyAlpha === true);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, g.RGBA, g.UNSIGNED_BYTE, src);\n } else {\n setUnpackState(target, false, false);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA8, w, h, 0, g.RGBA, g.UNSIGNED_BYTE, null);\n }\n if (tex._dynParamsHandle !== tex.handle) {\n setBoundTextureParams(g, minFilter, magFilter, wrapS, wrapT);\n tex._dynParamsHandle = tex.handle;\n }\n if (generateMipMaps && src !== null && src !== undefined) {\n g.generateMipmap(g.TEXTURE_2D);\n }\n };\n\n const tex: GLTexture = {\n handle,\n target: gl.TEXTURE_2D,\n width: w,\n height: h,\n isReady: true,\n _disposed: false,\n _refCount: 1,\n _upload: upload,\n _wasReady: true,\n _dynSource: null,\n _dynInvertY: false,\n _dynPremultiplyAlpha: false,\n };\n upload(engine);\n engine._textures.add(tex);\n return tex;\n}\n\n/** Push 2D pixels into a {@link createDynamicTexture} texture from a canvas /\n * `OffscreenCanvas` / image / video / `ImageBitmap` / `ImageData` source — the\n * WebGL counterpart of Babylon's `ThinEngine.updateDynamicTexture`. The source\n * is retained on the texture so it is replayed on `webglcontextrestored`.\n * No-op when the context is lost/disposed or the texture is disposed.\n *\n * @param engine - The engine that owns the texture.\n * @param tex - A texture created by {@link createDynamicTexture}.\n * @param source - The 2D pixel source to upload.\n * @param invertY - Flip vertically on upload (`UNPACK_FLIP_Y_WEBGL`). Default `false`.\n * @param premultiplyAlpha - Premultiply on upload (`UNPACK_PREMULTIPLY_ALPHA_WEBGL`).\n * Default `false`, matching Babylon's `updateDynamicTexture` default. */\nexport function updateDynamicTexture(engine: GLEngineContext, tex: GLTexture, source: TexImageSource, invertY = false, premultiplyAlpha = false): void {\n if (engine._isLost || engine._disposed || tex._disposed) {\n return;\n }\n tex._dynSource = source;\n tex._dynInvertY = invertY;\n tex._dynPremultiplyAlpha = premultiplyAlpha;\n tex._upload(engine);\n}\n\n/** Forget the source a dynamic texture retained for context-restore replay.\n * The current GPU pixels are kept (no re-upload), but the source reference is\n * dropped so it can be garbage-collected — and a subsequent\n * `webglcontextrestored` will re-blank the texture instead of replaying. Use\n * after the final {@link updateDynamicTexture} once the source (e.g. a large\n * atlas canvas) is no longer needed. No-op on a non-dynamic texture. */\nexport function clearDynamicTextureSource(tex: GLTexture): void {\n tex._dynSource = null;\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { type GLEngineContext } from "./context.js";
2
+ import { type GLEffect } from "./effect.js";
3
+ /** Options for the opt-in `waitForEffect` readiness scheduler. */
4
+ export interface GLEffectWaitOptions {
5
+ /** Cancels only this wait. Error reasons are preserved; other reasons are
6
+ * the cause of a native AbortError DOMException. Does not dispose or cancel the effect. */
7
+ signal?: AbortSignal;
8
+ }
9
+ /** Wait for readiness without starting a render loop. Polls immediately and
10
+ * then once per animation frame; resolves with the finalized effect.
11
+ * Rejects on compile/link/restore failure, context loss, disposal (observed
12
+ * on the next poll), or signal cancellation. All exits cancel the pending
13
+ * frame and remove listeners. Call again after context restoration to wait
14
+ * for the replacement program. Scheduling code is tree-shaken when unused.
15
+ * @param engine - Engine owning the effect.
16
+ * @param effect - Effect to finalize.
17
+ * @param options - Optional cancellation signal.
18
+ * @returns The ready effect, or a rejected promise with the failure reason.
19
+ */
20
+ export declare function waitForEffect(engine: GLEngineContext, effect: GLEffect, options?: GLEffectWaitOptions): Promise<GLEffect>;
@@ -0,0 +1,94 @@
1
+ import { offContextLost, onContextLost } from "./context.js";
2
+ import { getEffectCompilationError } from "./effect.js";
3
+ /** Wait for readiness without starting a render loop. Polls immediately and
4
+ * then once per animation frame; resolves with the finalized effect.
5
+ * Rejects on compile/link/restore failure, context loss, disposal (observed
6
+ * on the next poll), or signal cancellation. All exits cancel the pending
7
+ * frame and remove listeners. Call again after context restoration to wait
8
+ * for the replacement program. Scheduling code is tree-shaken when unused.
9
+ * @param engine - Engine owning the effect.
10
+ * @param effect - Effect to finalize.
11
+ * @param options - Optional cancellation signal.
12
+ * @returns The ready effect, or a rejected promise with the failure reason.
13
+ */
14
+ export function waitForEffect(engine, effect, options) {
15
+ return new Promise((resolve, reject) => {
16
+ const signal = options?.signal;
17
+ let frame = null;
18
+ let settled = false;
19
+ const cleanup = () => {
20
+ settled = true;
21
+ if (frame !== null) {
22
+ cancelAnimationFrame(frame);
23
+ frame = null;
24
+ }
25
+ offContextLost(engine, lost);
26
+ signal?.removeEventListener("abort", abort);
27
+ };
28
+ const fail = (error) => {
29
+ if (settled) {
30
+ return;
31
+ }
32
+ cleanup();
33
+ reject(error);
34
+ };
35
+ const lost = () => fail(new Error(`lite-gl: ${effect.name} context lost while waiting for compilation`));
36
+ const abort = () => {
37
+ const reason = signal?.reason;
38
+ if (reason instanceof Error) {
39
+ fail(reason);
40
+ }
41
+ else {
42
+ fail(Object.assign(new DOMException(`lite-gl: ${effect.name} compilation wait aborted`, "AbortError"), { cause: reason }));
43
+ }
44
+ };
45
+ const poll = () => {
46
+ frame = null;
47
+ if (settled) {
48
+ return;
49
+ }
50
+ try {
51
+ // Registering an abort listener does not replay a prior abort.
52
+ if (signal?.aborted) {
53
+ abort();
54
+ return;
55
+ }
56
+ // Disposal has no callback; these guards also cover already-disposed/lost inputs.
57
+ if (engine._disposed || effect._disposed) {
58
+ fail(new Error(`lite-gl: ${effect.name} disposed while waiting for compilation`));
59
+ return;
60
+ }
61
+ if (engine._isLost) {
62
+ lost();
63
+ return;
64
+ }
65
+ const error = getEffectCompilationError(engine, effect);
66
+ // Abort/loss callbacks set settled synchronously during finalization.
67
+ if (settled) {
68
+ return;
69
+ }
70
+ // Finalization callbacks can dispose without any notification.
71
+ if (engine._disposed || effect._disposed) {
72
+ fail(new Error(`lite-gl: ${effect.name} disposed while waiting for compilation`));
73
+ }
74
+ else if (error !== null) {
75
+ fail(new Error(`lite-gl: ${effect.name} ${error}`));
76
+ }
77
+ else if (effect.isReady) {
78
+ cleanup();
79
+ resolve(effect);
80
+ }
81
+ else {
82
+ frame = requestAnimationFrame(poll);
83
+ }
84
+ }
85
+ catch (error) {
86
+ fail(error instanceof Error ? error : new Error(`lite-gl: ${effect.name} compilation wait failed`, { cause: error }));
87
+ }
88
+ };
89
+ onContextLost(engine, lost);
90
+ signal?.addEventListener("abort", abort, { once: true });
91
+ poll();
92
+ });
93
+ }
94
+ //# sourceMappingURL=effect-ready.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eff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I,MAAM,CAAC,OAAO,EAAE,CAAC;oBACxB,OAAO,EAAE,CAAC;oBACV,OAAO,CAAC,MAAM,CAAC,CAAC;gBACpB,CAAC;qBAAM,CAAC;oBACJ,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;gBACxC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,IAAI,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,MAAM,CAAC,IAAI,0BAA0B,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;YAC1H,CAAC;QACL,CAAC,CAAC;QAEF,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC5B,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACzD,IAAI,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { offContextLost, onContextLost, type GLEngineContext } from \"./context.js\";\nimport { getEffectCompilationError, type GLEffect } from \"./effect.js\";\n\n/** Options for the opt-in `waitForEffect` readiness scheduler. */\nexport interface GLEffectWaitOptions {\n /** Cancels only this wait. Error reasons are preserved; other reasons are\n * the cause of a native AbortError DOMException. Does not dispose or cancel the effect. */\n signal?: AbortSignal;\n}\n\n/** Wait for readiness without starting a render loop. Polls immediately and\n * then once per animation frame; resolves with the finalized effect.\n * Rejects on compile/link/restore failure, context loss, disposal (observed\n * on the next poll), or signal cancellation. All exits cancel the pending\n * frame and remove listeners. Call again after context restoration to wait\n * for the replacement program. Scheduling code is tree-shaken when unused.\n * @param engine - Engine owning the effect.\n * @param effect - Effect to finalize.\n * @param options - Optional cancellation signal.\n * @returns The ready effect, or a rejected promise with the failure reason.\n */\nexport function waitForEffect(engine: GLEngineContext, effect: GLEffect, options?: GLEffectWaitOptions): Promise<GLEffect> {\n return new Promise((resolve, reject) => {\n const signal = options?.signal;\n let frame: number | null = null;\n let settled = false;\n\n const cleanup = (): void => {\n settled = true;\n if (frame !== null) {\n cancelAnimationFrame(frame);\n frame = null;\n }\n offContextLost(engine, lost);\n signal?.removeEventListener(\"abort\", abort);\n };\n const fail = (error: Error): void => {\n if (settled) {\n return;\n }\n cleanup();\n reject(error);\n };\n const lost = (): void => fail(new Error(`lite-gl: ${effect.name} context lost while waiting for compilation`));\n const abort = (): void => {\n const reason: unknown = signal?.reason;\n if (reason instanceof Error) {\n fail(reason);\n } else {\n fail(Object.assign(new DOMException(`lite-gl: ${effect.name} compilation wait aborted`, \"AbortError\"), { cause: reason }));\n }\n };\n const poll = (): void => {\n frame = null;\n if (settled) {\n return;\n }\n try {\n // Registering an abort listener does not replay a prior abort.\n if (signal?.aborted) {\n abort();\n return;\n }\n // Disposal has no callback; these guards also cover already-disposed/lost inputs.\n if (engine._disposed || effect._disposed) {\n fail(new Error(`lite-gl: ${effect.name} disposed while waiting for compilation`));\n return;\n }\n if (engine._isLost) {\n lost();\n return;\n }\n const error = getEffectCompilationError(engine, effect);\n // Abort/loss callbacks set settled synchronously during finalization.\n if (settled) {\n return;\n }\n // Finalization callbacks can dispose without any notification.\n if (engine._disposed || effect._disposed) {\n fail(new Error(`lite-gl: ${effect.name} disposed while waiting for compilation`));\n } else if (error !== null) {\n fail(new Error(`lite-gl: ${effect.name} ${error}`));\n } else if (effect.isReady) {\n cleanup();\n resolve(effect);\n } else {\n frame = requestAnimationFrame(poll);\n }\n } catch (error) {\n fail(error instanceof Error ? error : new Error(`lite-gl: ${effect.name} compilation wait failed`, { cause: error }));\n }\n };\n\n onContextLost(engine, lost);\n signal?.addEventListener(\"abort\", abort, { once: true });\n poll();\n });\n}\n"]}
package/effect.d.ts CHANGED
@@ -56,16 +56,23 @@ export interface GLEffect {
56
56
  * `setEffect*` setters are no-ops until then. Poll `isEffectReady` to advance it. */
57
57
  isReady: boolean;
58
58
  }
59
- /** Compile + link a new effect. Does NOT block on link completion — `isReady`
60
- * starts false; consumers poll `isEffectReady` (typically from their render
61
- * callback) to drive finalization. */
59
+ /** Submit compilation + linking without querying their results. `isReady`
60
+ * starts false; poll `isEffectReady` or opt into `waitForEffect` to finalize.
61
+ * Allocation failures throw synchronously. Shader syntax/link errors are
62
+ * recorded during polling and exposed by `getEffectCompilationError`. */
62
63
  export declare function createEffect(engine: GLEngineContext, options: GLEffectOptions): GLEffect;
63
64
  /** Poll the link state and, on first success, run finalization (uniform-
64
65
  * location resolution + one-shot sampler-unit `uniform1i` assignment +
65
66
  * `_onCompiled` callbacks). Returns `true` once the effect is usable. */
66
67
  export declare function isEffectReady(engine: GLEngineContext, effect: GLEffect): boolean;
68
+ /** Poll readiness once and return the recorded compile/link/restore diagnostic.
69
+ * Returns null while pending or when no failure has been recorded; this is
70
+ * not a readiness guarantee. Does not schedule polling. A successful restore
71
+ * allocation clears the previous diagnostic before the new link is checked. */
72
+ export declare function getEffectCompilationError(engine: GLEngineContext, effect: GLEffect): string | null;
67
73
  /** Fires `cb` synchronously if the effect is already ready; otherwise queues
68
- * it for the next finalization. */
74
+ * it for the next finalization. Does not start polling: call `isEffectReady`
75
+ * from the render loop or opt into `waitForEffect`. */
69
76
  export declare function executeWhenCompiled(engine: GLEngineContext, effect: GLEffect, cb: (e: GLEffect) => void): void;
70
77
  /** Decrement the share count and, on the last release, delete the effect's
71
78
  * program + shaders, unregister it from the context + cache, and clear the