From faeecc81fe7015d0c933ef69bae9d67288f03bfb Mon Sep 17 00:00:00 2001 From: wouterlucas Date: Wed, 25 Nov 2026 22:48:25 +0100 Subject: [PATCH] feat(webgl): cache vertex attribute state per VAO and reuse per-program VAOs Phase 1 of the L2-style fast paths: behavior-preserving reduction of redundant WebGL attribute setup. - WebGlContextWrapper now keeps per-VAO shadow state (enable flags, full vertexAttribPointer parameter sets, element-buffer binding) and skips native calls when the effective state is unchanged. The ARRAY_BUFFER bind still happens before a skipped pointer call. deleteBuffer/deleteVertexArray invalidate the shadow tables; the constructor seeds them from the live context; context restoration recreates the wrapper, so no stale GL assumptions survive. - WebGlShaderProgram owns a lazily created VAO on WebGL2 and configures it once per BufferCollection layout (identity + layout version), so rebinding the same layout issues zero enable/pointer calls in steady state. WebGL1 keeps the per-attribute path, backed by the wrapper shadow state. detach() unbinds the VAO instead of disabling attributes; destroy() deletes it. - BufferCollection gains a layout version (invalidateLayout) so caches keyed on (collection, version) reconfigure on real layout changes. - createIndexBuffer returns the shared index buffer, stored on the renderer so each program VAO can bind it (ELEMENT_ARRAY_BUFFER is captured per VAO in WebGL2). Tests: WebGlContextWrapper.attribState.test.ts (8) and WebGlShaderProgram.vao.test.ts (4). Full suite 561 passed, build clean. --- src/core/platforms/GlContextWrapper.ts | 6 + .../WebGlContextWrapper.attribState.test.ts | 345 ++++++++++++++++++ src/core/platforms/web/WebGlContextWrapper.ts | 204 ++++++++++- src/core/renderers/webgl/WebGlRenderer.ts | 10 +- .../renderers/webgl/WebGlShaderProgram.ts | 65 +++- .../webgl/WebGlShaderProgram.vao.test.ts | 159 ++++++++ .../webgl/internal/BufferCollection.ts | 24 ++ .../renderers/webgl/internal/RendererUtils.ts | 9 +- 8 files changed, 813 insertions(+), 9 deletions(-) create mode 100644 src/core/platforms/web/WebGlContextWrapper.attribState.test.ts create mode 100644 src/core/renderers/webgl/WebGlShaderProgram.vao.test.ts diff --git a/src/core/platforms/GlContextWrapper.ts b/src/core/platforms/GlContextWrapper.ts index 830832f97..c333c2d0b 100644 --- a/src/core/platforms/GlContextWrapper.ts +++ b/src/core/platforms/GlContextWrapper.ts @@ -174,6 +174,12 @@ export abstract class GlContextWrapper { data: ArrayBufferView, usage: GLenum, ): void; + /** + * Binds the element (index) buffer without uploading. In WebGL2 the binding + * is captured per VAO, so it must be (re)bound while the target VAO is + * active. + */ + abstract bindElementArrayBuffer(buffer: any | null): void; abstract vertexAttribPointer( buffer: any, index: GLuint, diff --git a/src/core/platforms/web/WebGlContextWrapper.attribState.test.ts b/src/core/platforms/web/WebGlContextWrapper.attribState.test.ts new file mode 100644 index 000000000..97b41836d --- /dev/null +++ b/src/core/platforms/web/WebGlContextWrapper.attribState.test.ts @@ -0,0 +1,345 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2026 Comcast Cable Communications, LLC. + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Tests for the per-VAO attribute shadow state in WebGlContextWrapper: + * identical enable/pointer/element-buffer state must not be re-submitted to + * the native context, while any real state transition (buffer, pointer + * params, VAO switch, buffer deletion) must issue the native call. + */ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { WebGlContextWrapper } from './WebGlContextWrapper.js'; + +// The wrapper detects WebGL2 via `gl instanceof WebGL2RenderingContext`, which +// is undefined in the node test environment — install a stand-in class so the +// WebGL2 paths can be exercised. +class FakeWebGL2RenderingContext {} +const g = globalThis as Record; +const hadWebGL2 = 'WebGL2RenderingContext' in g; +const prevWebGL2 = g.WebGL2RenderingContext; + +beforeEach(() => { + g.WebGL2RenderingContext = FakeWebGL2RenderingContext; +}); + +afterAll(() => { + if (hadWebGL2) { + g.WebGL2RenderingContext = prevWebGL2; + } else { + delete g.WebGL2RenderingContext; + } +}); + +const ENUMS: Record = { + ACTIVE_TEXTURE: 0x0b71, + TEXTURE0: 0x84c0, + MAX_TEXTURE_IMAGE_UNITS: 0x8872, + TEXTURE_BINDING_2D: 0x8069, + SCISSOR_TEST: 0x0c11, + SCISSOR_BOX: 0x0c10, + STENCIL_TEST: 0x0b90, + STENCIL_FUNC: 0x0b62, + STENCIL_REF: 0x0b63, + STENCIL_VALUE_MASK: 0x0b64, + STENCIL_FAIL: 0x0b61, + STENCIL_PASS_DEPTH_FAIL: 0x0b65, + STENCIL_PASS_DEPTH_PASS: 0x0b66, + STENCIL_WRITEMASK: 0x0b98, + COLOR_WRITEMASK: 0x0c23, + BLEND: 0x0be2, + BLEND_SRC_RGB: 0x80c9, + BLEND_DST_RGB: 0x80c8, + BLEND_SRC_ALPHA: 0x80cb, + BLEND_DST_ALPHA: 0x80ca, + ARRAY_BUFFER: 0x8892, + ELEMENT_ARRAY_BUFFER: 0x8893, + ARRAY_BUFFER_BINDING: 0x8894, + ELEMENT_ARRAY_BUFFER_BINDING: 0x8895, + CURRENT_PROGRAM: 0x8b8d, + VERTEX_ARRAY_BINDING: 0x85b5, + MAX_RENDERBUFFER_SIZE: 0x84e8, + MAX_TEXTURE_SIZE: 0x0d33, + MAX_VIEWPORT_DIMS: 0x0d3a, + MAX_VERTEX_TEXTURE_IMAGE_UNITS: 0x8b4c, + MAX_COMBINED_TEXTURE_IMAGE_UNITS: 0x8b4d, + MAX_VERTEX_ATTRIBS: 0x8869, + MAX_VARYING_VECTORS: 0x8dfc, + MAX_VERTEX_UNIFORM_VECTORS: 0x8dfb, + MAX_FRAGMENT_UNIFORM_VECTORS: 0x8dfd, + TEXTURE_MAG_FILTER: 0x2800, + TEXTURE_MIN_FILTER: 0x2801, + TEXTURE_WRAP_S: 0x2802, + TEXTURE_WRAP_T: 0x2803, + LINEAR: 0x2601, + LINEAR_MIPMAP_LINEAR: 0x2703, + CLAMP_TO_EDGE: 0x812f, + RGB: 0x1907, + RGBA: 0x1908, + UNSIGNED_BYTE: 0x1401, + UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241, + UNPACK_FLIP_Y_WEBGL: 0x9240, + FLOAT: 0x1406, + TRIANGLES: 0x0004, + UNSIGNED_SHORT: 0x1403, + ONE: 1, + ONE_MINUS_SRC_ALPHA: 0x0303, + VERTEX_SHADER: 0x8b31, + FRAGMENT_SHADER: 0x8b30, + STATIC_DRAW: 0x88e4, + COMPILE_STATUS: 0x8b81, + LINK_STATUS: 0x8b82, + DYNAMIC_DRAW: 0x88e8, + COLOR_ATTACHMENT0: 0x8ce0, + INVALID_ENUM: 0x0500, + INVALID_OPERATION: 0x0502, + STENCIL_BUFFER_BIT: 0x0400, + VERTEX_ATTRIB_ARRAY_ENABLED: 0x8622, + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: 0x889f, + VERTEX_ATTRIB_ARRAY_SIZE: 0x8623, + VERTEX_ATTRIB_ARRAY_TYPE: 0x8625, + VERTEX_ATTRIB_ARRAY_NORMALIZED: 0x886a, + VERTEX_ATTRIB_ARRAY_STRIDE: 0x8624, + VERTEX_ATTRIB_ARRAY_POINTER: 0x8645, +}; + +interface MockGl { + [key: string]: unknown; + getParameter: ReturnType; + isEnabled: ReturnType; + getVertexAttrib: ReturnType; + bindBuffer: ReturnType; + enableVertexAttribArray: ReturnType; + disableVertexAttribArray: ReturnType; + vertexAttribPointer: ReturnType; + bindVertexArray: ReturnType; + deleteBuffer: ReturnType; + deleteVertexArray: ReturnType; + bufferData: ReturnType; + bufferSubData: ReturnType; + createBuffer: ReturnType; + canvas: { width: number; height: number }; +} + +const makeMockGl = (isWebGl2: boolean, maxAttribs = 8): MockGl => { + const base = isWebGl2 ? new FakeWebGL2RenderingContext() : {}; + const gl = Object.assign(base, { + ...ENUMS, + canvas: { width: 1920, height: 1080 }, + getParameter: vi.fn((pname: number) => { + switch (pname) { + case ENUMS.ACTIVE_TEXTURE: + return ENUMS.TEXTURE0; + case ENUMS.MAX_TEXTURE_IMAGE_UNITS: + return 8; + case ENUMS.MAX_VERTEX_ATTRIBS: + return maxAttribs; + case ENUMS.SCISSOR_BOX: + return [0, 0, 1920, 1080]; + case ENUMS.COLOR_WRITEMASK: + return [true, true, true, true]; + default: + return 0; + } + }), + isEnabled: vi.fn(() => false), + getVertexAttrib: vi.fn(() => 0), + activeTexture: vi.fn(), + createBuffer: vi.fn(() => ({})), + bindBuffer: vi.fn(), + bufferData: vi.fn(), + bufferSubData: vi.fn(), + enableVertexAttribArray: vi.fn(), + disableVertexAttribArray: vi.fn(), + vertexAttribPointer: vi.fn(), + bindVertexArray: vi.fn(), + deleteBuffer: vi.fn(), + deleteVertexArray: vi.fn(), + }) as unknown as MockGl; + return gl; +}; + +const FLOAT = ENUMS.FLOAT!; + +describe('WebGlContextWrapper attribute shadow state (WebGL1)', () => { + it('skips repeated enable/disable calls for identical state', () => { + const gl = makeMockGl(false); + const glw = new WebGlContextWrapper(gl as never); + + glw.enableVertexAttribArray(0); + glw.enableVertexAttribArray(0); + expect(gl.enableVertexAttribArray).toHaveBeenCalledTimes(1); + + glw.disableVertexAttribArray(0); + glw.disableVertexAttribArray(0); + expect(gl.disableVertexAttribArray).toHaveBeenCalledTimes(1); + + // Disabling an already-disabled location is a no-op. + glw.disableVertexAttribArray(3); + expect(gl.disableVertexAttribArray).toHaveBeenCalledTimes(1); + }); + + it('skips identical vertexAttribPointer calls but still binds a new ARRAY_BUFFER', () => { + const gl = makeMockGl(false); + const glw = new WebGlContextWrapper(gl as never); + const bufA = {} as WebGLBuffer; + const bufB = {} as WebGLBuffer; + + glw.vertexAttribPointer(bufA, 0, 2, FLOAT, false, 20, 0); + glw.vertexAttribPointer(bufA, 0, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(1); + expect(gl.bindBuffer).toHaveBeenCalledTimes(1); + expect(gl.bindBuffer).toHaveBeenLastCalledWith(ENUMS.ARRAY_BUFFER, bufA); + + // Same pointer params but different buffer: pointer re-issued AND the + // ARRAY_BUFFER bind happens first. + glw.vertexAttribPointer(bufB, 0, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + expect(gl.bindBuffer).toHaveBeenCalledTimes(2); + expect(gl.bindBuffer).toHaveBeenLastCalledWith(ENUMS.ARRAY_BUFFER, bufB); + + // Any single param difference re-issues the pointer call. + glw.vertexAttribPointer(bufB, 0, 2, FLOAT, false, 20, 4); + glw.vertexAttribPointer(bufB, 0, 4, FLOAT, false, 20, 4); + glw.vertexAttribPointer(bufB, 0, 4, FLOAT, true, 20, 4); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(5); + }); + + it('keeps the ARRAY_BUFFER binding for uploads even when pointers are cached', () => { + const gl = makeMockGl(false); + const glw = new WebGlContextWrapper(gl as never); + const buf = {} as WebGLBuffer; + + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + glw.arrayBufferSubData(buf, 0, new Float32Array(4)); + // Buffer already bound by the pointer call — no second bind. + expect(gl.bindBuffer).toHaveBeenCalledTimes(1); + expect(gl.bufferSubData).toHaveBeenCalledTimes(1); + }); + + it('re-issues pointers after the buffer is deleted', () => { + const gl = makeMockGl(false); + const glw = new WebGlContextWrapper(gl as never); + const buf = {} as WebGLBuffer; + + glw.vertexAttribPointer(buf, 1, 2, FLOAT, false, 20, 0); + glw.vertexAttribPointer(buf, 1, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(1); + + glw.deleteBuffer(buf); + glw.vertexAttribPointer(buf, 1, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + }); +}); + +describe('WebGlContextWrapper attribute shadow state (WebGL2 / VAO)', () => { + it('tracks pointer and enable state per VAO', () => { + const gl = makeMockGl(true); + const glw = new WebGlContextWrapper(gl as never); + const vaoA = {} as WebGLVertexArrayObject; + const vaoB = {} as WebGLVertexArrayObject; + const buf = {} as WebGLBuffer; + + glw.bindVertexArray(vaoA); + glw.enableVertexAttribArray(0); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.enableVertexAttribArray).toHaveBeenCalledTimes(1); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(1); + + // Switching VAOs must re-issue the calls: VAO B starts in default state. + glw.bindVertexArray(vaoB); + glw.enableVertexAttribArray(0); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.enableVertexAttribArray).toHaveBeenCalledTimes(2); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + + // Back to VAO A: everything cached, no native calls. + glw.bindVertexArray(vaoA); + glw.enableVertexAttribArray(0); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.enableVertexAttribArray).toHaveBeenCalledTimes(2); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + + // Re-binding the same VAO is skipped too (vaoA, vaoB, vaoA = 3 calls). + glw.bindVertexArray(vaoA); + expect(gl.bindVertexArray).toHaveBeenCalledTimes(3); + }); + + it('tracks the element buffer binding per VAO', () => { + const gl = makeMockGl(true); + const glw = new WebGlContextWrapper(gl as never); + const vaoA = {} as WebGLVertexArrayObject; + const vaoB = {} as WebGLVertexArrayObject; + const idx = {} as WebGLBuffer; + + glw.bindVertexArray(vaoA); + glw.bindElementArrayBuffer(idx); + glw.bindElementArrayBuffer(idx); + expect(gl.bindBuffer).toHaveBeenCalledTimes(1); + expect(gl.bindBuffer).toHaveBeenLastCalledWith( + ENUMS.ELEMENT_ARRAY_BUFFER, + idx, + ); + + glw.bindVertexArray(vaoB); + glw.bindElementArrayBuffer(idx); + expect(gl.bindBuffer).toHaveBeenCalledTimes(2); + + glw.bindVertexArray(vaoA); + glw.bindElementArrayBuffer(idx); + expect(gl.bindBuffer).toHaveBeenCalledTimes(2); + }); + + it('clears deleted-buffer references from every VAO table', () => { + const gl = makeMockGl(true); + const glw = new WebGlContextWrapper(gl as never); + const vaoA = {} as WebGLVertexArrayObject; + const vaoB = {} as WebGLVertexArrayObject; + const buf = {} as WebGLBuffer; + + glw.bindVertexArray(vaoA); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + glw.bindVertexArray(vaoB); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + + glw.deleteBuffer(buf); + + glw.bindVertexArray(vaoA); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + glw.bindVertexArray(vaoB); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(4); + }); + + it('drops the shadow table when a VAO is deleted', () => { + const gl = makeMockGl(true); + const glw = new WebGlContextWrapper(gl as never); + const vaoA = {} as WebGLVertexArrayObject; + const buf = {} as WebGLBuffer; + + glw.bindVertexArray(vaoA); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + glw.deleteVertexArray(vaoA); + + // After deletion the VAO is unbound; binding it again starts fresh. + glw.bindVertexArray(vaoA); + glw.vertexAttribPointer(buf, 0, 2, FLOAT, false, 20, 0); + expect(gl.vertexAttribPointer).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/core/platforms/web/WebGlContextWrapper.ts b/src/core/platforms/web/WebGlContextWrapper.ts index 8b95716c2..505765e25 100644 --- a/src/core/platforms/web/WebGlContextWrapper.ts +++ b/src/core/platforms/web/WebGlContextWrapper.ts @@ -48,6 +48,36 @@ import type { CompressedData } from '../../textures/Texture.js'; * A subset of GLenum constants are also exposed as properties on this class * for convenience. */ +/** + * Shadow copy of the vertex attribute pointer state for one attribute + * location. Keyed by buffer + full pointer parameter set. + */ +interface AttribPointerState { + buffer: WebGLBuffer; + size: GLint; + type: GLenum; + normalized: GLboolean; + stride: GLsizei; + offset: GLintptr; +} + +/** + * Shadow copy of all per-VAO vertex attribute state. + * + * @remarks + * In WebGL2, `enableVertexAttribArray`/`disableVertexAttribArray`, + * `vertexAttribPointer` and the `ELEMENT_ARRAY_BUFFER` binding are captured + * per VAO, so the shadow state must be tracked per VAO as well. In WebGL1 + * there is no VAO; only the `null` (default) table is used. `ARRAY_BUFFER` + * binding is global context state (not VAO state) and stays tracked at the + * wrapper level in `boundArrayBuffer`. + */ +interface AttribStateTable { + enabled: boolean[]; + pointers: (AttribPointerState | null)[]; + elementBuffer: WebGLBuffer | null; +} + export class WebGlContextWrapper extends GlContextWrapper { //#region Cached WebGL State private activeTextureUnit = 0; @@ -79,9 +109,18 @@ export class WebGlContextWrapper extends GlContextWrapper { private blendSrcAlpha: number; private blendDstAlpha: number; private boundArrayBuffer: WebGLBuffer | null; - private boundElementArrayBuffer: WebGLBuffer | null; private curProgram: WebGLProgram | null; private curUniformLocations: Record = {}; + /** + * Currently bound VAO (WebGL2 only; always `null` on WebGL1). Attribute + * pointer/enable state and the element-array binding are captured per VAO, + * so the shadow tables below are keyed by VAO — `null` is the default VAO. + */ + private curVertexArray: WebGLVertexArrayObject | null = null; + private attribTables = new Map< + WebGLVertexArrayObject | null, + AttribStateTable + >(); /** * Memoized `gl.getExtension()` results (including `null` for unsupported). * `getExtension()` activates the extension's enums driver-side, so caching @@ -212,9 +251,6 @@ export class WebGlContextWrapper extends GlContextWrapper { this.boundArrayBuffer = gl.getParameter( gl.ARRAY_BUFFER_BINDING, ) as WebGLBuffer; - this.boundElementArrayBuffer = gl.getParameter( - gl.ELEMENT_ARRAY_BUFFER_BINDING, - ) as WebGLBuffer; this.curProgram = gl.getParameter( gl.CURRENT_PROGRAM, @@ -222,6 +258,18 @@ export class WebGlContextWrapper extends GlContextWrapper { this.canvas = gl.canvas; + // Seed the per-VAO attribute shadow state from the live context so the + // compare-and-skip logic below never skips a call that would actually + // change native state. The element-array binding is VAO state in WebGL2, + // so it is tracked inside each table (default VAO here). + this.curVertexArray = + this.isWebGl2 === true + ? (gl.getParameter( + (gl as WebGL2RenderingContext).VERTEX_ARRAY_BINDING, + ) as WebGLVertexArrayObject | null) + : null; + this.initAttribTable(this.curVertexArray); + // Extract GLenums this.MAX_RENDERBUFFER_SIZE = gl.MAX_RENDERBUFFER_SIZE; this.MAX_TEXTURE_SIZE = gl.MAX_TEXTURE_SIZE; @@ -272,6 +320,70 @@ export class WebGlContextWrapper extends GlContextWrapper { this.STENCIL_BUFFER_BIT = gl.STENCIL_BUFFER_BIT; } + /** + * Returns the shadow attribute table for the currently bound VAO, creating + * it (in the "everything default" state) on first use. + */ + private attribTable(): AttribStateTable { + let table = this.attribTables.get(this.curVertexArray); + if (table === undefined) { + table = { + enabled: new Array(this.MAX_VERTEX_ATTRIBS).fill(false), + pointers: new Array(this.MAX_VERTEX_ATTRIBS).fill(null), + elementBuffer: null, + }; + this.attribTables.set(this.curVertexArray, table); + } + return table; + } + + /** + * Reads the live attribute/enable/element-buffer state of the given VAO into + * a fresh shadow table. Used at construction time so a non-default context + * is mirrored correctly. WebGL1 has no VAOs; the `null` table is the whole + * (global) state. + */ + private initAttribTable(vao: WebGLVertexArrayObject | null): void { + const gl = this.gl; + const maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS) as number; + const enabled = new Array(maxAttribs).fill(false); + const pointers: (AttribPointerState | null)[] = new Array(maxAttribs).fill( + null, + ); + for (let i = 0; i < maxAttribs; i++) { + if (gl.getVertexAttrib(i, gl.VERTEX_ATTRIB_ARRAY_ENABLED) === true) { + enabled[i] = true; + const buffer = gl.getVertexAttrib( + i, + gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, + ) as WebGLBuffer | null; + if (buffer !== null) { + pointers[i] = { + buffer, + size: gl.getVertexAttrib(i, gl.VERTEX_ATTRIB_ARRAY_SIZE) as GLint, + type: gl.getVertexAttrib(i, gl.VERTEX_ATTRIB_ARRAY_TYPE) as GLenum, + normalized: gl.getVertexAttrib( + i, + gl.VERTEX_ATTRIB_ARRAY_NORMALIZED, + ) as GLboolean, + stride: gl.getVertexAttrib( + i, + gl.VERTEX_ATTRIB_ARRAY_STRIDE, + ) as GLsizei, + offset: gl.getVertexAttrib( + i, + gl.VERTEX_ATTRIB_ARRAY_POINTER, + ) as GLintptr, + }; + } + } + } + const elementBuffer = gl.getParameter( + gl.ELEMENT_ARRAY_BUFFER_BINDING, + ) as WebGLBuffer | null; + this.attribTables.set(vao, { enabled, pointers, elementBuffer }); + } + /** * ``` * gl.activeTexture(textureUnit + gl.TEXTURE0); @@ -797,13 +909,36 @@ export class WebGlContextWrapper extends GlContextWrapper { data: ArrayBufferView, usage: GLenum, ) { - if (this.boundElementArrayBuffer !== buffer) { + // ELEMENT_ARRAY_BUFFER binding is captured per VAO in WebGL2, so the + // compare-and-skip uses the current VAO's shadow table. + const table = this.attribTable(); + if (table.elementBuffer !== buffer) { this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, buffer); - this.boundElementArrayBuffer = buffer; + table.elementBuffer = buffer; } this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, data, usage); } + /** + * ``` + * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer); + * ``` + * + * @remarks + * Binds the element (index) buffer without uploading. In WebGL2 the binding + * is stored in the currently bound VAO, so each VAO that draws indexed + * geometry must bind the index buffer once while it is active. + * + * @param buffer + */ + bindElementArrayBuffer(buffer: WebGLBuffer | null) { + const table = this.attribTable(); + if (table.elementBuffer !== buffer) { + this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, buffer); + table.elementBuffer = buffer; + } + } + /** * ``` * gl.bindBuffer(gl.ARRAY_BUFFER, buffer); @@ -830,11 +965,37 @@ export class WebGlContextWrapper extends GlContextWrapper { stride: GLsizei, offset: GLintptr, ) { + // The ARRAY_BUFFER bind is global context state (not VAO state) and must + // happen even when the pointer call itself can be skipped: uploads and + // other consumers rely on it. if (this.boundArrayBuffer !== buffer) { this.gl.bindBuffer(this.gl.ARRAY_BUFFER, buffer); this.boundArrayBuffer = buffer; } + // The pointer itself is captured per VAO (WebGL2) / globally (WebGL1); + // skip the native call when the effective pointer state is unchanged. + const table = this.attribTable(); + const cur = table.pointers[index]; + if ( + cur != null && + cur.buffer === buffer && + cur.size === size && + cur.type === type && + cur.normalized === normalized && + cur.stride === stride && + cur.offset === offset + ) { + return; + } this.gl.vertexAttribPointer(index, size, type, normalized, stride, offset); + table.pointers[index] = { + buffer, + size, + type, + normalized, + stride, + offset, + }; } /** @@ -1278,7 +1439,11 @@ export class WebGlContextWrapper extends GlContextWrapper { */ bindVertexArray(vertexArray: WebGLVertexArrayObject | null) { if (this.isWebGl2 === true) { + if (this.curVertexArray === vertexArray) { + return; + } (this.gl as WebGL2RenderingContext).bindVertexArray(vertexArray); + this.curVertexArray = vertexArray; } } @@ -1316,7 +1481,12 @@ export class WebGlContextWrapper extends GlContextWrapper { * @param index */ enableVertexAttribArray(index: number) { + const table = this.attribTable(); + if (table.enabled[index] === true) { + return; + } this.gl.enableVertexAttribArray(index); + table.enabled[index] = true; } /** @@ -1327,7 +1497,12 @@ export class WebGlContextWrapper extends GlContextWrapper { * @param index */ disableVertexAttribArray(index: number) { + const table = this.attribTable(); + if (table.enabled[index] !== true) { + return; + } this.gl.disableVertexAttribArray(index); + table.enabled[index] = false; } /** @@ -1485,6 +1660,19 @@ export class WebGlContextWrapper extends GlContextWrapper { if (this.boundArrayBuffer === buffer) { this.boundArrayBuffer = null; } + // A deleted buffer must never remain referenced by shadow pointer state: + // clear it from every VAO table so the next vertexAttribPointer re-issues. + for (const table of this.attribTables.values()) { + if (table.elementBuffer === buffer) { + table.elementBuffer = null; + } + const pointers = table.pointers; + for (let i = 0; i < pointers.length; i++) { + if (pointers[i]?.buffer === buffer) { + pointers[i] = null; + } + } + } } /** @@ -1497,6 +1685,10 @@ export class WebGlContextWrapper extends GlContextWrapper { deleteVertexArray(vertexArray: WebGLVertexArrayObject) { if (this.isWebGl2 === true) { (this.gl as WebGL2RenderingContext).deleteVertexArray(vertexArray); + this.attribTables.delete(vertexArray); + if (this.curVertexArray === vertexArray) { + this.curVertexArray = null; + } } } diff --git a/src/core/renderers/webgl/WebGlRenderer.ts b/src/core/renderers/webgl/WebGlRenderer.ts index 6037ec7f5..e20e0b8cc 100644 --- a/src/core/renderers/webgl/WebGlRenderer.ts +++ b/src/core/renderers/webgl/WebGlRenderer.ts @@ -263,6 +263,12 @@ export class WebGlRenderer extends CoreRenderer { defaultShaderNode: WebGlShaderNode | null = null; private shaderPrograms = new Set(); quadBufferCollection!: BufferCollection; + /** + * Shared element (index) buffer for all indexed quad draws. In WebGL2 the + * binding is captured per VAO, so each shader program's VAO binds this once + * when it is configured with a buffer collection. + */ + indexBuffer: WebGLBuffer | null = null; //// Stencil clip program (compiled once, reused every frame) stencilClipProgram: WebGlShaderProgram | null = null; @@ -355,7 +361,9 @@ export class WebGlRenderer extends CoreRenderer { glw.setBlend(true); glw.blendFunc(glw.ONE, glw.ONE_MINUS_SRC_ALPHA); - createIndexBuffer(glw, stage.bufferMemory); + // Kept so per-program VAOs (WebGL2) can bind the shared index buffer — + // the ELEMENT_ARRAY_BUFFER binding is captured per VAO. + this.indexBuffer = createIndexBuffer(glw, stage.bufferMemory); const quadBuffer = glw.createBuffer(); diff --git a/src/core/renderers/webgl/WebGlShaderProgram.ts b/src/core/renderers/webgl/WebGlShaderProgram.ts index 6626affd3..dc53d2305 100644 --- a/src/core/renderers/webgl/WebGlShaderProgram.ts +++ b/src/core/renderers/webgl/WebGlShaderProgram.ts @@ -71,6 +71,15 @@ export class WebGlShaderProgram implements CoreShaderProgram { * Used by WebGL2 Only */ protected vao: WebGLVertexArrayObject | undefined; + /** + * The BufferCollection this program's VAO was last configured with, plus its + * layout version at that time. While the same collection (same layout + * generation) is bound, the VAO already holds the correct pointer/enable + * state and `bindBufferCollection` is a no-op. Only meaningful on WebGL2; + * WebGL1 uses the wrapper-level shadow state instead. + */ + private vaoCollection: BufferCollection | null = null; + private vaoCollectionVersion = -1; protected renderer: WebGlRenderer; glw: GlContextWrapper; protected attributeLocations: string[]; @@ -221,6 +230,9 @@ export class WebGlShaderProgram implements CoreShaderProgram { deferred.attributeLocations = []; deferred.uniformLocations = null; deferred.lifecycle = {}; + deferred.vao = undefined; + deferred.vaoCollection = null; + deferred.vaoCollectionVersion = -1; return deferred; } @@ -423,6 +435,40 @@ export class WebGlShaderProgram implements CoreShaderProgram { bindBufferCollection(buffer: BufferCollection) { const { glw } = this; + + if (glw.isWebGl2 === true) { + // WebGL2: each program owns a VAO. Once the VAO has been configured for + // a buffer collection's layout, rebinding the same collection is a + // no-op — no enable/pointer calls at all in steady state. + if (this.vao === undefined) { + this.vao = glw.createVertexArray(); + } + if ( + this.vaoCollection === buffer && + this.vaoCollectionVersion === buffer.version + ) { + // VAO already holds this layout; make sure it is the bound one. + glw.bindVertexArray(this.vao); + return; + } + glw.bindVertexArray(this.vao); + this.bindAttributesToCurrentVao(buffer); + // Indexed draws capture the element buffer per VAO: bind the renderer's + // shared index buffer into this VAO once per layout change. + glw.bindElementArrayBuffer(this.renderer.indexBuffer); + this.vaoCollection = buffer; + this.vaoCollectionVersion = buffer.version; + return; + } + + // WebGL1 fallback: no VAOs, so program each attribute explicitly. The + // wrapper's shadow state skips the native calls when the effective + // pointer/enable state is already identical. + this.bindAttributesToCurrentVao(buffer); + } + + private bindAttributesToCurrentVao(buffer: BufferCollection) { + const { glw } = this; const attribs = this.attributeLocations; const attribLen = attribs.length; @@ -457,7 +503,10 @@ export class WebGlShaderProgram implements CoreShaderProgram { return; } this.glw.useProgram(this.program, this.uniformLocations!); - if (this.glw.isWebGl2 === true && this.vao) { + if (this.glw.isWebGl2 === true) { + if (this.vao === undefined) { + this.vao = this.glw.createVertexArray(); + } this.glw.bindVertexArray(this.vao); } } @@ -479,6 +528,13 @@ export class WebGlShaderProgram implements CoreShaderProgram { } detach(): void { + if (this.glw.isWebGl2 === true && this.vao !== undefined) { + // On WebGL2 the VAO encapsulates the attribute state; unbinding it + // leaves the program's VAO intact for the next attach. Disabling the + // attributes here would corrupt the per-VAO cache. + this.glw.bindVertexArray(null); + return; + } this.disableAttributes(); } @@ -490,6 +546,13 @@ export class WebGlShaderProgram implements CoreShaderProgram { this.detach(); + if (this.vao !== undefined) { + glw.deleteVertexArray(this.vao); + this.vao = undefined; + } + this.vaoCollection = null; + this.vaoCollectionVersion = -1; + glw.deleteProgram(this.program!); this.program = null; this.uniformLocations = null; diff --git a/src/core/renderers/webgl/WebGlShaderProgram.vao.test.ts b/src/core/renderers/webgl/WebGlShaderProgram.vao.test.ts new file mode 100644 index 000000000..1f7029e6f --- /dev/null +++ b/src/core/renderers/webgl/WebGlShaderProgram.vao.test.ts @@ -0,0 +1,159 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2026 Comcast Cable Communications, LLC. + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Per-program VAO reuse tests: on WebGL2, once a program's VAO is configured + * for a buffer collection layout, rebinding the same collection must not + * re-issue enable/pointer calls; a different collection or a layout-version + * bump must reconfigure. On WebGL1 the wrapper-level shadow state handles the + * skipping instead. + */ +import { describe, expect, it, vi } from 'vitest'; +import { WebGlShaderProgram } from './WebGlShaderProgram.js'; +import { BufferCollection } from './internal/BufferCollection.js'; +import type { WebGlRenderer } from './WebGlRenderer.js'; + +const makeGlw = (isWebGl2: boolean) => ({ + isWebGl2, + createVertexArray: vi.fn(() => ({ vao: true })), + bindVertexArray: vi.fn(), + deleteVertexArray: vi.fn(), + enableVertexAttribArray: vi.fn(), + disableVertexAttribArray: vi.fn(), + vertexAttribPointer: vi.fn(), + bindElementArrayBuffer: vi.fn(), + useProgram: vi.fn(), + deleteProgram: vi.fn(), + deleteBuffer: vi.fn(), +}); + +const makeProgram = (isWebGl2: boolean) => { + const program = Object.create( + WebGlShaderProgram.prototype, + ) as WebGlShaderProgram; + const glw = makeGlw(isWebGl2); + const indexBuffer = {} as WebGLBuffer; + const renderer = { indexBuffer } as unknown as WebGlRenderer; + (program as any).glw = glw; + (program as any).renderer = renderer; + (program as any).attributeLocations = ['a_position', 'a_nodeCoords']; + (program as any).program = { prog: true } as unknown as WebGLProgram; + (program as any).uniformLocations = {}; + (program as any).isDestroyed = false; + return { program, glw, indexBuffer }; +}; + +const makeCollection = () => { + const quadBuffer = { id: 'quad' } as unknown as WebGLBuffer; + const coordsBuffer = { id: 'coords' } as unknown as WebGLBuffer; + const info = (name: string, offset: number) => ({ + name, + size: 2, + type: 0x1406, + normalized: false, + stride: 20, + offset, + }); + return new BufferCollection([ + { buffer: quadBuffer, attributes: { a_position: info('a_position', 0) } }, + { + buffer: coordsBuffer, + attributes: { a_nodeCoords: info('a_nodeCoords', 8) }, + }, + ]); +}; + +describe('WebGlShaderProgram VAO reuse (WebGL2)', () => { + it('configures the program VAO once per buffer collection layout', () => { + const { program, glw } = makeProgram(true); + const collection = makeCollection(); + + program.attach(); + expect(glw.createVertexArray).toHaveBeenCalledTimes(1); + expect(glw.bindVertexArray).toHaveBeenCalledTimes(1); + + program.bindBufferCollection(collection); + expect(glw.enableVertexAttribArray).toHaveBeenCalledTimes(2); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(2); + // The shared index buffer is captured into the VAO. + expect(glw.bindElementArrayBuffer).toHaveBeenCalledTimes(1); + + // Same collection, same layout: no attribute calls at all. + program.bindBufferCollection(collection); + expect(glw.enableVertexAttribArray).toHaveBeenCalledTimes(2); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(2); + expect(glw.bindElementArrayBuffer).toHaveBeenCalledTimes(1); + // The VAO is still (re)bound for the draw. + expect(glw.bindVertexArray).toHaveBeenCalledTimes(3); + }); + + it('reconfigures when a different collection is bound or the layout version bumps', () => { + const { program, glw } = makeProgram(true); + const collectionA = makeCollection(); + const collectionB = makeCollection(); + + program.bindBufferCollection(collectionA); + program.bindBufferCollection(collectionB); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(4); + expect(glw.bindElementArrayBuffer).toHaveBeenCalledTimes(2); + + // Same collection but bumped layout version: reconfigure. + collectionB.invalidateLayout(); + program.bindBufferCollection(collectionB); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(6); + + // And cached again afterwards. + program.bindBufferCollection(collectionB); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(6); + }); + + it('detach unbinds the VAO without disabling its attributes; destroy deletes it', () => { + const { program, glw } = makeProgram(true); + program.attach(); + program.bindBufferCollection(makeCollection()); + + program.detach(); + expect(glw.bindVertexArray).toHaveBeenLastCalledWith(null); + expect(glw.disableVertexAttribArray).not.toHaveBeenCalled(); + + (program as any).renderer = { + indexBuffer: {} as WebGLBuffer, + untrackShaderProgram: vi.fn(), + } as unknown as WebGlRenderer; + program.destroy(); + expect(glw.deleteVertexArray).toHaveBeenCalledTimes(1); + expect((program as any).vao).toBeUndefined(); + }); +}); + +describe('WebGlShaderProgram attribute binding (WebGL1 fallback)', () => { + it('programs attributes through the wrapper on every bind', () => { + const { program, glw } = makeProgram(false); + const collection = makeCollection(); + + program.bindBufferCollection(collection); + program.bindBufferCollection(collection); + // No VAO is created on WebGL1; the wrapper shadow state does the skipping. + expect(glw.createVertexArray).not.toHaveBeenCalled(); + expect(glw.bindVertexArray).not.toHaveBeenCalled(); + expect(glw.bindElementArrayBuffer).not.toHaveBeenCalled(); + expect(glw.enableVertexAttribArray).toHaveBeenCalledTimes(4); + expect(glw.vertexAttribPointer).toHaveBeenCalledTimes(4); + }); +}); diff --git a/src/core/renderers/webgl/internal/BufferCollection.ts b/src/core/renderers/webgl/internal/BufferCollection.ts index f5a4b17a5..d96792019 100644 --- a/src/core/renderers/webgl/internal/BufferCollection.ts +++ b/src/core/renderers/webgl/internal/BufferCollection.ts @@ -54,6 +54,15 @@ export interface BufferAttribute { */ export class BufferCollection { private readonly attributes: Record = {}; + /** + * Layout generation counter. Object identity alone does not prove a + * collection's pointers/offsets are unchanged — anything that mutates the + * effective attribute layout (buffer replacement, offset changes) must bump + * this via {@link invalidateLayout} so VAO caches keyed on (collection, + * version) are reconfigured. Content-only changes (bufferSubData uploads) + * do not affect pointer state and must NOT bump it. + */ + private layoutVersion = 0; constructor(readonly config: ReadonlyArray) { for (let i = 0; i < config.length; i++) { @@ -101,4 +110,19 @@ export class BufferCollection { const attribute = this.attributes[attributeName]; return attribute === undefined ? undefined : attribute.info; } + + /** + * Current layout generation. See {@link layoutVersion}. + */ + get version(): number { + return this.layoutVersion; + } + + /** + * Mark the effective attribute layout as changed so consumers caching + * pointer state keyed by (collection, version) reconfigure. + */ + invalidateLayout(): void { + this.layoutVersion++; + } } diff --git a/src/core/renderers/webgl/internal/RendererUtils.ts b/src/core/renderers/webgl/internal/RendererUtils.ts index 530840d2b..734855a7f 100644 --- a/src/core/renderers/webgl/internal/RendererUtils.ts +++ b/src/core/renderers/webgl/internal/RendererUtils.ts @@ -128,8 +128,14 @@ export function getMaxQuads(bufferMemory: number) { * * @param glw * @param size + * @returns The created element (index) buffer. Callers keep the reference so + * it can be bound into per-program VAOs (WebGL2 captures the element binding + * per VAO) and recreated after context loss. */ -export function createIndexBuffer(glw: GlContextWrapper, size: number) { +export function createIndexBuffer( + glw: GlContextWrapper, + size: number, +): WebGLBuffer { const maxQuads = getMaxQuads(size); const indices = new Uint16Array(maxQuads * 6); @@ -146,6 +152,7 @@ export function createIndexBuffer(glw: GlContextWrapper, size: number) { const buffer = glw.createBuffer(); glw.elementArrayBufferData(buffer, indices, glw.STATIC_DRAW); + return buffer; } /**