@weasel-js/core 1.7.3 → 1.8.1
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/CHANGELOG.md +82 -0
- package/dist/animation/colorHelpers.js +58 -58
- package/dist/animation/colorHelpers.js.map +1 -1
- package/dist/animation/engine/axes.js +36 -0
- package/dist/animation/engine/axes.js.map +1 -0
- package/dist/animation/engine/codec.js +170 -0
- package/dist/animation/engine/codec.js.map +1 -0
- package/dist/animation/engine/integrator.js +12 -0
- package/dist/animation/engine/integrator.js.map +1 -0
- package/dist/animation/useAnimator.js +209 -160
- package/dist/animation/useAnimator.js.map +1 -1
- package/dist/{builtins-C-gRyVRx.d.ts → builtins-CMEh6-Oc.d.ts} +81 -8
- package/dist/canvas/SceneCanvas/defaultNodeProperties.js +12 -12
- package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -1
- package/dist/canvas/pickWalk.js +2 -2
- package/dist/canvas/pickWalk.js.map +1 -1
- package/dist/canvas/sceneSlotWiring.js +1 -1
- package/dist/canvas/sceneSlotWiring.js.map +1 -1
- package/dist/canvas/sceneViewRender.js +1 -1
- package/dist/canvas/sceneViewRender.js.map +1 -1
- package/dist/core/scene/effectivePose.js +1 -1
- package/dist/core/scene/effectivePose.js.map +1 -1
- package/dist/core/scene/poseOverrides.js +42 -22
- package/dist/core/scene/poseOverrides.js.map +1 -1
- package/dist/core/scene/scene.js +9 -0
- package/dist/core/scene/scene.js.map +1 -1
- package/dist/core/scene/types.js.map +1 -1
- package/dist/core/selection/useSelection.js +27 -33
- package/dist/core/selection/useSelection.js.map +1 -1
- package/dist/core/stableStringify.js +8 -0
- package/dist/core/stableStringify.js.map +1 -0
- package/dist/index.d.ts +35 -25
- package/dist/index.js +269 -268
- package/dist/renderer/WeaselRenderer.js +4 -1
- package/dist/renderer/WeaselRenderer.js.map +1 -1
- package/dist/renderer/batchClip.js +46 -0
- package/dist/renderer/batchClip.js.map +1 -0
- package/dist/renderer/draw.js +367 -294
- package/dist/renderer/draw.js.map +1 -1
- package/dist/renderer/drawBatch.js +75 -45
- package/dist/renderer/drawBatch.js.map +1 -1
- package/dist/renderer/shaders/batchFill.js +3 -2
- package/dist/renderer/shaders/batchFill.js.map +1 -1
- package/dist/renderer.d.ts +1 -1
- package/dist/tools/builtin/text/useTextTool.js +8 -8
- package/dist/tools/builtin/text/useTextTool.js.map +1 -1
- package/dist/tools/prefs.js.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +17 -15
|
@@ -229,6 +229,7 @@ var ae = {
|
|
|
229
229
|
widthCss: this.widthCss,
|
|
230
230
|
heightCss: this.heightCss,
|
|
231
231
|
clipDepth: 0,
|
|
232
|
+
clipStack: [],
|
|
232
233
|
flattenTolerance: this.flattenTolerance,
|
|
233
234
|
textOutlineMinScreenSize: this.textOutlineMinScreenSize,
|
|
234
235
|
viewMatrix: t,
|
|
@@ -240,7 +241,9 @@ var ae = {
|
|
|
240
241
|
restoreTargetRect: () => this.applyTarget(),
|
|
241
242
|
paintResources: this.paintResources,
|
|
242
243
|
stats: i
|
|
243
|
-
}
|
|
244
|
+
};
|
|
245
|
+
this.drawBatch.clip = null;
|
|
246
|
+
let c = n?.spans ?? [], l = 0;
|
|
244
247
|
for (let t = 0; t < c.length; t++) {
|
|
245
248
|
let n = c[t];
|
|
246
249
|
for (; l < n.start; l++) z(s, e[l]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeaselRenderer.js","names":["customUniformNames","CUSTOM_KIT_UNIFORMS","extractUniformNames","vertSrc","fragSrc","compileCustomProgram","src","CUSTOM_VERT_SRC","program","ShaderProgram","gl","extractUniformArrays","CUSTOM_ATTRIBUTES","now","GLYPH_PAINT_SOURCES","GLYPH_PATTERN_FRAG_SRC","GLYPH_PATTERN_UNIFORMS","GLYPH_GRAD_FRAG_SRC","GLYPH_GRAD_UNIFORMS","GLYPH_TEXTURE_FRAG_SRC","GLYPH_TEXTURE_UNIFORMS","WeaselRenderer","GroupState","createPaintResources","opts","EffectTargets","PaintScratch","attrs","DEFAULT_BAKE_BUDGET","OUTLINE_MIN_SCREEN_PX","VERT_SRC","FRAG_SRC","PATH_FILL_UNIFORMS","PATH_FILL_ATTRIBUTES","VCOLOR_VERT_SRC","VCOLOR_FRAG_SRC","PATH_FILL_VCOLOR_ATTRIBUTES","IMAGE_VERT_SRC","IMAGE_FRAG_SRC","IMAGE_FILL_UNIFORMS","IMAGE_FILL_ATTRIBUTES","BATCH_VERT_SRC","BATCH_FRAG_SRC","BATCH_FILL_UNIFORMS","BATCH_FILL_ATTRIBUTES","GRAD_VERT_SRC","GRAD_FRAG_SRC","GRAD_FILL_UNIFORMS","GRAD_FILL_ATTRIBUTES","PATTERN_VERT_SRC","PATTERN_FRAG_SRC","PATTERN_FILL_UNIFORMS","PATTERN_FILL_ATTRIBUTES","aPos","GLMeshCache","GLTextureCache","GLImageCache","GradientRampAtlas","DrawBatch","createWhiteTexture","QUAD_VERTICES","QUAD_INDICES","getProgramSource","handle","previous","id","compiled","e","existing","kind","frag","uniforms","GLYPH_PAINT_VERT_SRC","GLYPH_PAINT_ATTRIBUTES","w","h","x","y","target","markAllFontsNotUploaded","prog","t0","counters","spanStats","resetBakeBudget","ctx","spans","next","si","span","commands","drawsBefore","spanT0","flushBatch","tolerance","dims","tex"],"sources":["../../src/renderer/WeaselRenderer.ts"],"sourcesContent":["import { createPaintResources, type OwnedPaintResources } from './paintResources';\nimport { ShaderProgram } from './shaders/ShaderProgram';\nimport {\n VERT_SRC,\n FRAG_SRC,\n VCOLOR_VERT_SRC,\n VCOLOR_FRAG_SRC,\n PATH_FILL_UNIFORMS,\n PATH_FILL_ATTRIBUTES,\n PATH_FILL_VCOLOR_ATTRIBUTES,\n} from './shaders/pathFill';\nimport {\n markAllFontsNotUploaded,\n resetBakeBudget,\n DEFAULT_BAKE_BUDGET,\n} from '@weasel-js/font';\nimport {\n IMAGE_VERT_SRC,\n IMAGE_FRAG_SRC,\n IMAGE_FILL_UNIFORMS,\n IMAGE_FILL_ATTRIBUTES,\n} from './shaders/imageFill';\nimport {\n BATCH_VERT_SRC,\n BATCH_FRAG_SRC,\n BATCH_FILL_UNIFORMS,\n BATCH_FILL_ATTRIBUTES,\n} from './shaders/batchFill';\nimport {\n GRAD_VERT_SRC,\n GRAD_FRAG_SRC,\n GRAD_FILL_UNIFORMS,\n GRAD_FILL_ATTRIBUTES,\n} from './shaders/gradFill';\nimport {\n PATTERN_VERT_SRC,\n PATTERN_FRAG_SRC,\n PATTERN_FILL_UNIFORMS,\n PATTERN_FILL_ATTRIBUTES,\n} from './shaders/patternFill';\nimport {\n GLYPH_PAINT_VERT_SRC,\n GLYPH_PATTERN_FRAG_SRC,\n GLYPH_GRAD_FRAG_SRC,\n GLYPH_TEXTURE_FRAG_SRC,\n GLYPH_PATTERN_UNIFORMS,\n GLYPH_GRAD_UNIFORMS,\n GLYPH_TEXTURE_UNIFORMS,\n GLYPH_PAINT_ATTRIBUTES,\n} from './shaders/glyphPaint';\nimport { PaintScratch } from './paintScratch';\nimport { GLMeshCache } from './cache/GLMeshCache';\nimport { GLTextureCache } from './cache/GLTextureCache';\nimport { GLImageCache, type ImageMinification } from './cache/GLImageCache';\nimport { GradientRampAtlas } from './cache/GradientRampAtlas';\nimport { GroupState } from './state/GroupState';\nimport type { DrawCommand } from './DrawCommand';\nimport type { GlMat3 } from './math/mat3';\nimport {\n dispatch, flushBatch, OUTLINE_MIN_SCREEN_PX, type DrawContext, type GlyphPaintKind,\n} from './draw';\nimport { DrawBatch } from './drawBatch';\nimport {\n CUSTOM_VERT_SRC, CUSTOM_ATTRIBUTES, CUSTOM_KIT_UNIFORMS,\n QUAD_VERTICES, QUAD_INDICES,\n} from './shaders/customPrelude';\nimport { getProgramSource, type ProgramSource, type ShaderProgramHandle } from './shaders/registerProgram';\nimport { EffectTargets } from './effects/EffectTargets';\nimport { extractUniformArrays, extractUniformNames } from './shaders/extractUniformNames';\n\n/** Every uniform a custom program may be written through. Both stages, not\n * just the fragment one: a name never looked up is written through `null`,\n * which GL accepts silently, so the uniform keeps its zero default. */\nfunction customUniformNames(vertSrc: string, fragSrc: string): string[] {\n return [...CUSTOM_KIT_UNIFORMS, ...extractUniformNames(vertSrc), ...extractUniformNames(fragSrc)];\n}\n\n/** Compile a registered program's source against `gl`, with every uniform\n * location and array base it may be written through. */\nfunction compileCustomProgram(gl: WebGL2RenderingContext, src: ProgramSource): ShaderProgram {\n const vertSrc = src.vert === '' ? CUSTOM_VERT_SRC : src.vert;\n const program = new ShaderProgram(gl, vertSrc, src.frag);\n program.lookupUniforms(customUniformNames(vertSrc, src.frag));\n program.lookupUniformArrays(new Map([...extractUniformArrays(vertSrc), ...extractUniformArrays(src.frag)]));\n program.lookupAttributes(CUSTOM_ATTRIBUTES);\n return program;\n}\n\n/** How to construct a `WeaselRenderer`: the GL context or canvas to draw\n * into, the output size, and the quality knobs that separate screen\n * rendering from print. */\n/** A run of top-level commands, `[start, end)` by index, that\n * {@link WeaselRenderer.lastFrameStats} accounts for separately — one render\n * layer's commands, say. Spans are in order and do not overlap. */\nexport interface RenderSpan {\n id: string;\n start: number;\n end: number;\n}\n\n/** Per-frame options for {@link WeaselRenderer.render}. */\nexport interface RenderOptions {\n spans?: readonly RenderSpan[];\n}\n\n/** What one span cost. A batched run is drawn when something closes it, so\n * its draw call counts toward the span that closed it. */\nexport interface RenderSpanStats {\n id: string;\n drawCalls: number;\n ms: number;\n}\n\n/** What one `render()` cost. See {@link WeaselRenderer.lastFrameStats}. */\nexport interface RenderStats {\n drawCalls: number;\n ms: number;\n spans: RenderSpanStats[];\n}\n\nfunction now(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\n\n/** Construction options for {@link WeaselRenderer}. Pass `gl` or `canvas`;\n * a context passed in must have a stencil buffer. */\nexport interface WeaselRendererOptions {\n /** A WebGL2 context to draw with. Wins over `canvas`. */\n gl?: WebGL2RenderingContext;\n /** A canvas to open a stencil-backed WebGL2 context on, when `gl` is absent. */\n canvas?: HTMLCanvasElement;\n /** Drawing size in CSS pixels. */\n width: number;\n /** Drawing size in CSS pixels. */\n height: number;\n /** Device pixels per CSS pixel. */\n dpr: number;\n /** MIN_FILTER strategy for image/pattern textures (`GLImageCache`).\n * Default `'linear'` — the existing screen behavior. The headless\n * `renderSceneToPixels` path passes `'mipmap'` for print-quality\n * minification. Explicitly passing `'linear'` is always valid. */\n imageMinification?: ImageMinification;\n /** Flatness tolerance for curve tessellation, in WORLD units (see\n * `TessellateOptions.flattenTolerance`). When set, path fills are\n * tessellated fresh at this tolerance per frame (transient pool) instead\n * of served from the Path-identity mesh cache — the cache key does not\n * include tolerance. Default: unset — the existing cached behavior at\n * `DEFAULT_FLATTEN_TOLERANCE`. The headless path derives this from the\n * requested output scale; screen callers normally leave it unset. */\n flattenTolerance?: number;\n /** Per-render synchronous bake budget for dynamic canvas-SDF glyphs.\n * Default DEFAULT_BAKE_BUDGET (16). The headless renderSceneToPixels\n * path passes Infinity so print never defers a glyph. */\n bakeBudget?: number;\n /** On-screen glyph size, in CSS pixels, at or above which text renders from\n * tessellated font outlines instead of a distance field — see\n * `OUTLINE_MIN_SCREEN_PX`. Only faces registered with\n * `registerFontOutlines` are affected; everything else keeps its SDF tier\n * whatever this says. Pass `Infinity` to disable the tier outright, or 0\n * to use outlines wherever they exist (what the headless path does, since\n * print has no reason to sample a field it could evaluate exactly). */\n textOutlineMinScreenSize?: number;\n}\n\n/** Where a renderer draws inside a buffer it does not own.\n *\n * The rect's SIZE is the renderer's own `width`/`height` — `resize()` owns\n * that, and a second copy here could disagree with the one `DrawContext`\n * reports to screen-space layers. */\nexport interface RenderTarget {\n /** Top-left of this renderer's output within the drawing buffer, in CSS\n * pixels, with the origin at the buffer's top-left. GL's bottom-left origin\n * is handled internally. */\n origin: { x: number; y: number };\n /** Clear colour and stencil within the rect before drawing. Default true.\n * Pass false only when the caller clears the whole buffer itself on behalf\n * of every co-tenant — a frame that clears neither inherits its neighbour's\n * stencil bits, and even-odd fills then fill their holes. */\n clear?: boolean;\n}\n\n/** Each glyph-paint program's fragment stage and the uniforms it looks up. */\nconst GLYPH_PAINT_SOURCES: Record<GlyphPaintKind, readonly [string, readonly string[]]> = {\n pattern: [GLYPH_PATTERN_FRAG_SRC, GLYPH_PATTERN_UNIFORMS],\n gradient: [GLYPH_GRAD_FRAG_SRC, GLYPH_GRAD_UNIFORMS],\n texture: [GLYPH_TEXTURE_FRAG_SRC, GLYPH_TEXTURE_UNIFORMS],\n};\n\n/**\n * The WebGL2 renderer: takes a list of draw commands and paints them.\n *\n * It knows nothing about the scene — commands are the whole interface, which\n * is what lets layers, HUD widgets and overlays all draw through the same\n * pipeline. GPU resources (meshes, textures, gradient ramps) are cached across\n * frames and keyed by identity, so re-issuing the same command is cheap.\n */\nexport class WeaselRenderer {\n private readonly gl: WebGL2RenderingContext;\n private stats: RenderStats = { drawCalls: 0, ms: 0, spans: [] };\n private pathFill: ShaderProgram;\n private pathFillVColor: ShaderProgram;\n private imageFill: ShaderProgram;\n private batchFill: ShaderProgram;\n private gradFill: ShaderProgram;\n private patternFill: ShaderProgram;\n /** Compiled on first use: only atlas text under a texture paint needs one. */\n private glyphPaintPrograms = new Map<GlyphPaintKind, ShaderProgram>();\n private meshCache: GLMeshCache;\n private textureCache: GLTextureCache;\n private imageCache: GLImageCache;\n private gradRamps: GradientRampAtlas;\n private programRegistry = new Map<string, ShaderProgram>();\n /** The source each compiled custom program was built from — or, after a\n * failed recompile, the source that failed, so it is not retried every frame. */\n private programSources = new Map<string, ProgramSource>();\n private quadVbo: WebGLBuffer | null = null;\n private quadIbo: WebGLBuffer | null = null;\n private drawBatch: DrawBatch;\n /** 1x1 white, so a batch flush sampling no image still samples something —\n * see `shaders/batchFill.ts`. */\n private whiteTexture: WebGLTexture | null = null;\n private readonly groupState = new GroupState();\n private widthCss: number;\n private heightCss: number;\n private dpr: number;\n private canvas: HTMLCanvasElement | null = null;\n private target: RenderTarget | null = null;\n /** Offscreen buffers for group effects. Allocates nothing until a group\n * with effects asks, so a canvas without them pays no memory. */\n private readonly effectTargets: EffectTargets;\n private readonly paintScratch: PaintScratch;\n private readonly imageMinification: ImageMinification;\n private flattenTolerance?: number;\n private readonly bakeBudget: number;\n private readonly textOutlineMinScreenSize: number;\n private contextLost = false;\n private boundOnLost = (e: Event) => this.onContextLost(e);\n private boundOnRestored = () => this.onContextRestored();\n /** True after `dispose()`. A disposed renderer ignores further `render()`\n * calls and `registerProgram()` calls. */\n private disposed = false;\n /** What registered paint kinds hang their GPU state on. One per context\n * generation: a restore releases it and opens the next. */\n private paintResources: OwnedPaintResources = createPaintResources();\n\n constructor(opts: WeaselRendererOptions) {\n if (!opts.gl && !opts.canvas) {\n throw new Error('WeaselRenderer requires either gl or canvas');\n }\n const gl = opts.gl ?? opts.canvas!.getContext('webgl2', { stencil: true });\n if (!gl) throw new Error('WeaselRenderer: WebGL2 not available');\n this.gl = gl as WebGL2RenderingContext;\n this.effectTargets = new EffectTargets(this.gl);\n this.paintScratch = new PaintScratch(this.gl);\n\n // Bits 0-7 are load-bearing: bit 0 for even-odd fills and stenciled\n // strokes, bits 1-7 for clip depth (`renderer/draw.ts`). Without a stencil\n // buffer both render wrong rather than not at all, so refuse the context\n // instead of painting a plausible lie. A stub that cannot answer is not a\n // stencil-less context — only an explicit `false` is.\n const attrs = typeof this.gl.getContextAttributes === 'function'\n ? this.gl.getContextAttributes()\n : null;\n if (attrs && attrs.stencil === false) {\n throw new Error(\n 'WeaselRenderer: the supplied WebGL2 context has no stencil buffer. '\n + 'Create it with { stencil: true } — clips and even-odd fills need one.',\n );\n }\n\n this.widthCss = opts.width;\n this.heightCss = opts.height;\n this.dpr = opts.dpr;\n this.imageMinification = opts.imageMinification ?? 'linear';\n this.flattenTolerance = opts.flattenTolerance;\n this.bakeBudget = opts.bakeBudget ?? DEFAULT_BAKE_BUDGET;\n this.textOutlineMinScreenSize = opts.textOutlineMinScreenSize ?? OUTLINE_MIN_SCREEN_PX;\n\n this.canvas = opts.canvas ?? null;\n if (this.canvas) {\n this.canvas.width = Math.round(opts.width * opts.dpr);\n this.canvas.height = Math.round(opts.height * opts.dpr);\n if (this.canvas.style) {\n this.canvas.style.width = `${opts.width}px`;\n this.canvas.style.height = `${opts.height}px`;\n }\n this.canvas.addEventListener('webglcontextlost', this.boundOnLost);\n this.canvas.addEventListener('webglcontextrestored', this.boundOnRestored);\n }\n\n this.applyGlState();\n this.applyTarget();\n\n this.pathFill = new ShaderProgram(this.gl, VERT_SRC, FRAG_SRC);\n this.pathFill.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFill.lookupAttributes(PATH_FILL_ATTRIBUTES);\n\n this.pathFillVColor = new ShaderProgram(this.gl, VCOLOR_VERT_SRC, VCOLOR_FRAG_SRC);\n this.pathFillVColor.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFillVColor.lookupAttributes(PATH_FILL_VCOLOR_ATTRIBUTES);\n\n this.imageFill = new ShaderProgram(this.gl, IMAGE_VERT_SRC, IMAGE_FRAG_SRC);\n this.imageFill.lookupUniforms(IMAGE_FILL_UNIFORMS);\n this.imageFill.lookupAttributes(IMAGE_FILL_ATTRIBUTES);\n\n this.batchFill = new ShaderProgram(this.gl, BATCH_VERT_SRC, BATCH_FRAG_SRC);\n this.batchFill.lookupUniforms(BATCH_FILL_UNIFORMS);\n this.batchFill.lookupAttributes(BATCH_FILL_ATTRIBUTES);\n\n this.gradFill = new ShaderProgram(this.gl, GRAD_VERT_SRC, GRAD_FRAG_SRC);\n this.gradFill.lookupUniforms(GRAD_FILL_UNIFORMS);\n this.gradFill.lookupAttributes(GRAD_FILL_ATTRIBUTES);\n\n this.patternFill = new ShaderProgram(this.gl, PATTERN_VERT_SRC, PATTERN_FRAG_SRC);\n this.patternFill.lookupUniforms(PATTERN_FILL_UNIFORMS);\n this.patternFill.lookupAttributes(PATTERN_FILL_ATTRIBUTES);\n\n const aPos = this.pathFill.attribute('a_position');\n if (aPos === undefined) throw new Error('WeaselRenderer: a_position not found in path-fill shader');\n this.meshCache = new GLMeshCache(this.gl, aPos);\n this.textureCache = new GLTextureCache(this.gl);\n this.imageCache = new GLImageCache(this.gl, this.imageMinification);\n this.gradRamps = new GradientRampAtlas(this.gl);\n this.uploadQuadGeometry();\n this.drawBatch = new DrawBatch(this.gl, this.batchFill);\n this.whiteTexture = createWhiteTexture(this.gl);\n }\n\n private uploadQuadGeometry(): void {\n const gl = this.gl;\n this.quadVbo = gl.createBuffer();\n this.quadIbo = gl.createBuffer();\n if (!this.quadVbo || !this.quadIbo) {\n throw new Error('WeaselRenderer: failed to create quad geometry buffers');\n }\n gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVbo);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_VERTICES, gl.STATIC_DRAW);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.quadIbo);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, QUAD_INDICES, gl.STATIC_DRAW);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n }\n\n /**\n * Compile a consumer-registered shader program against this renderer's GL context.\n *\n * Call once per renderer after the module-level `registerProgram()`.\n * Throws `ShaderCompileError` if compilation fails.\n *\n * In dev mode, calling again with the same handle replaces the compiled program.\n *\n * @experimental\n */\n registerProgram(handle: ShaderProgramHandle): void {\n // A disposed renderer must not compile programs into the cleared registry.\n if (this.disposed) return;\n const src = getProgramSource(handle.id);\n if (!src) {\n throw new Error(\n `WeaselRenderer.registerProgram: program \"${handle.id}\" not found in source registry. ` +\n `Call the module-level registerProgram() first.`,\n );\n }\n this.installProgram(handle.id, src, compileCustomProgram(this.gl, src));\n }\n\n private installProgram(id: string, src: ProgramSource, program: ShaderProgram): void {\n const previous = this.programRegistry.get(id);\n if (previous) this.gl.deleteProgram(previous.handle);\n this.programRegistry.set(id, program);\n this.programSources.set(id, src);\n }\n\n /** Recompile every program whose module-level source was re-registered\n * since it was compiled. A source that fails keeps the old program drawing. */\n private refreshPrograms(): void {\n for (const [id, compiled] of this.programSources) {\n const src = getProgramSource(id);\n if (!src || src === compiled) continue;\n if (src.vert === compiled.vert && src.frag === compiled.frag) {\n this.programSources.set(id, src);\n continue;\n }\n try {\n this.installProgram(id, src, compileCustomProgram(this.gl, src));\n } catch (e) {\n this.programSources.set(id, src);\n console.error(`weasel: failed to recompile re-registered program \"${id}\"; still drawing the previous one:`, e);\n }\n }\n }\n\n /**\n * The compiled program for `id`, compiling it against this context on first\n * use. Unlike {@link registerProgram} this neither throws on a missing\n * source nor on a compile failure: a paint kind asking for a program it\n * never registered must decline the paint, not take down the frame.\n */\n private ensureProgram(id: string): ShaderProgram | null {\n const existing = this.programRegistry.get(id);\n if (existing) return existing;\n if (this.disposed || !getProgramSource(id)) return null;\n try {\n this.registerProgram({ id });\n } catch (e) {\n console.error(`weasel: failed to compile paint program \"${id}\":`, e);\n return null;\n }\n return this.programRegistry.get(id) ?? null;\n }\n\n private glyphPaintProgram(kind: GlyphPaintKind): ShaderProgram {\n const existing = this.glyphPaintPrograms.get(kind);\n if (existing) return existing;\n const [frag, uniforms] = GLYPH_PAINT_SOURCES[kind];\n const program = new ShaderProgram(this.gl, GLYPH_PAINT_VERT_SRC, frag);\n program.lookupUniforms(uniforms);\n program.lookupAttributes(GLYPH_PAINT_ATTRIBUTES);\n this.glyphPaintPrograms.set(kind, program);\n return program;\n }\n\n /** The GL state every frame assumes. Applied per `render()` rather than once\n * at construction because a co-tenant sharing this context moves all of it\n * between our frames. */\n private applyGlState(): void {\n const gl = this.gl;\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.CULL_FACE);\n gl.clearColor(0, 0, 0, 0);\n }\n\n /** Viewport and scissor for this frame. Re-applied inside `render()` because\n * a co-tenant on the same context moves both between our frames. */\n private applyTarget(): void {\n const gl = this.gl;\n const w = Math.round(this.widthCss * this.dpr);\n const h = Math.round(this.heightCss * this.dpr);\n if (!this.target) {\n gl.disable(gl.SCISSOR_TEST);\n gl.viewport(0, 0, w, h);\n return;\n }\n const x = Math.round(this.target.origin.x * this.dpr);\n const y = gl.drawingBufferHeight - Math.round(this.target.origin.y * this.dpr) - h;\n gl.viewport(x, y, w, h);\n gl.scissor(x, y, w, h);\n gl.enable(gl.SCISSOR_TEST);\n }\n\n /** Confine this renderer to a rect of its drawing buffer, or pass null to\n * give it the whole buffer back. Takes effect from the next `render()`. */\n setTarget(target: RenderTarget | null): void {\n this.target = target;\n this.applyTarget();\n }\n\n getTarget(): RenderTarget | null {\n return this.target;\n }\n\n isContextLost(): boolean {\n return this.contextLost;\n }\n\n private onContextLost(e: Event): void {\n e.preventDefault();\n this.contextLost = true;\n }\n\n private onContextRestored(): void {\n this.contextLost = false;\n this.applyGlState();\n this.applyTarget();\n // Every framebuffer, texture and renderbuffer the pool held died with the\n // context. `releaseAll` deletes handles that are already gone, which is a\n // no-op, and drops the bookkeeping that would otherwise hand a dead FBO to\n // the next group with effects.\n this.effectTargets.releaseAll();\n this.paintScratch.release();\n this.paintResources.release();\n this.paintResources = createPaintResources();\n this.pathFill = new ShaderProgram(this.gl, VERT_SRC, FRAG_SRC);\n this.pathFill.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFill.lookupAttributes(PATH_FILL_ATTRIBUTES);\n this.pathFillVColor = new ShaderProgram(this.gl, VCOLOR_VERT_SRC, VCOLOR_FRAG_SRC);\n this.pathFillVColor.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFillVColor.lookupAttributes(PATH_FILL_VCOLOR_ATTRIBUTES); this.imageFill = new ShaderProgram(this.gl, IMAGE_VERT_SRC, IMAGE_FRAG_SRC);\n this.imageFill.lookupUniforms(IMAGE_FILL_UNIFORMS);\n this.imageFill.lookupAttributes(IMAGE_FILL_ATTRIBUTES);\n\n this.batchFill = new ShaderProgram(this.gl, BATCH_VERT_SRC, BATCH_FRAG_SRC);\n this.batchFill.lookupUniforms(BATCH_FILL_UNIFORMS);\n this.batchFill.lookupAttributes(BATCH_FILL_ATTRIBUTES);\n this.gradFill = new ShaderProgram(this.gl, GRAD_VERT_SRC, GRAD_FRAG_SRC);\n this.gradFill.lookupUniforms(GRAD_FILL_UNIFORMS);\n this.gradFill.lookupAttributes(GRAD_FILL_ATTRIBUTES);\n\n this.patternFill = new ShaderProgram(this.gl, PATTERN_VERT_SRC, PATTERN_FRAG_SRC);\n this.patternFill.lookupUniforms(PATTERN_FILL_UNIFORMS);\n this.patternFill.lookupAttributes(PATTERN_FILL_ATTRIBUTES);\n this.glyphPaintPrograms.clear();\n const aPos = this.pathFill.attribute('a_position');\n if (aPos === undefined) throw new Error('a_position missing after restore');\n this.meshCache = new GLMeshCache(this.gl, aPos);\n this.textureCache = new GLTextureCache(this.gl);\n this.imageCache.abandon();\n this.imageCache = new GLImageCache(this.gl, this.imageMinification);\n this.gradRamps = new GradientRampAtlas(this.gl);\n markAllFontsNotUploaded();\n\n this.uploadQuadGeometry();\n this.drawBatch = new DrawBatch(this.gl, this.batchFill);\n this.whiteTexture = createWhiteTexture(this.gl);\n for (const id of this.programRegistry.keys()) {\n const src = getProgramSource(id);\n if (!src) continue;\n try {\n this.programRegistry.set(id, compileCustomProgram(this.gl, src));\n this.programSources.set(id, src);\n } catch (e) {\n console.error(`weasel: failed to recompile program \"${id}\" after context restore:`, e);\n }\n }\n }\n\n /** Free every GL resource this renderer created and detach context-loss\n * listeners when a canvas was supplied. Idempotent.\n *\n * That covers the built-in and consumer-registered programs (their shaders\n * go with them), the shared quad geometry, the batch, the effect targets,\n * and every cache: atlas and gradient-ramp textures, bitmap and pattern\n * textures, and meshes — transient, persistent, and those whose Path was\n * already collected. The context itself is left alone, so a caller-owned\n * context can host renderer after renderer without accumulating anything.\n *\n * A disposed renderer ignores further `render()` and `registerProgram()`\n * calls. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n const gl = this.gl;\n if (this.canvas) {\n this.canvas.removeEventListener('webglcontextlost', this.boundOnLost);\n this.canvas.removeEventListener('webglcontextrestored', this.boundOnRestored);\n }\n this.meshCache.dispose();\n this.paintResources.release();\n for (const prog of [\n this.pathFill, this.pathFillVColor, this.imageFill, this.batchFill, this.gradFill, this.patternFill,\n ...this.glyphPaintPrograms.values(),\n ]) {\n gl.deleteProgram(prog.handle);\n }\n this.glyphPaintPrograms.clear();\n for (const prog of this.programRegistry.values()) {\n gl.deleteProgram(prog.handle);\n }\n this.programRegistry.clear();\n this.programSources.clear();\n this.textureCache.free();\n this.imageCache.dispose();\n this.gradRamps.free();\n if (this.quadVbo) gl.deleteBuffer(this.quadVbo);\n if (this.quadIbo) gl.deleteBuffer(this.quadIbo);\n this.drawBatch.dispose();\n if (this.whiteTexture) gl.deleteTexture(this.whiteTexture);\n this.whiteTexture = null;\n this.effectTargets.releaseAll();\n this.paintScratch.release();\n }\n\n /**\n * Draw one frame.\n *\n * `viewMatrix` is the frame's world→screen transform. It is only consulted\n * by `units: 'world'` gradients, which fall back to screen space without\n * it — every other command carries its own transform in the stream, so\n * callers with no view concept can keep calling `render(commands)`.\n */\n render(commands: DrawCommand[], viewMatrix?: GlMat3, opts?: RenderOptions): void {\n if (this.contextLost || this.disposed) return;\n const t0 = now();\n const counters = { drawCalls: 0 };\n const spanStats: RenderSpanStats[] = [];\n this.stats = { drawCalls: 0, ms: 0, spans: spanStats };\n const gl = this.gl;\n // Free GL resources whose Mesh was GC'd since the last frame. Done here\n // (top of render, before any draws) because GL state is known clean —\n // no VAO bound, no draw in flight. Deleting from the FinalizationRegistry\n // callback directly was racy and caused mid-draw crashes.\n this.meshCache.drainPendingDeletes();\n this.refreshPrograms();\n // New frame: refill the dynamic-glyph synchronous bake budget.\n resetBakeBudget(this.bakeBudget);\n this.groupState.reset();\n this.applyGlState();\n this.applyTarget();\n // Ensure all stencil bits are cleared regardless of any mask left over\n // from the previous frame's clip ops.\n if (this.target?.clear !== false) {\n gl.stencilMask(0xFF);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);\n }\n const ctx: DrawContext = {\n gl,\n pathFill: this.pathFill,\n pathFillVColor: this.pathFillVColor,\n imageFill: this.imageFill,\n batchFill: this.batchFill,\n gradFill: this.gradFill,\n patternFill: this.patternFill,\n meshCache: this.meshCache,\n textureCache: this.textureCache,\n imageCache: this.imageCache,\n gradRamps: this.gradRamps,\n programRegistry: this.programRegistry,\n ensureProgram: (id) => this.ensureProgram(id),\n glyphPaintProgram: (kind) => this.glyphPaintProgram(kind),\n quadVbo: this.quadVbo,\n quadIbo: this.quadIbo,\n drawBatch: this.drawBatch,\n whiteTexture: this.whiteTexture,\n state: this.groupState,\n widthCss: this.widthCss,\n heightCss: this.heightCss,\n clipDepth: 0,\n flattenTolerance: this.flattenTolerance,\n textOutlineMinScreenSize: this.textOutlineMinScreenSize,\n viewMatrix,\n effectTargets: this.effectTargets,\n paintScratch: this.paintScratch,\n renderTarget: null,\n deviceWidth: Math.round(this.widthCss * this.dpr),\n deviceHeight: Math.round(this.heightCss * this.dpr),\n restoreTargetRect: () => this.applyTarget(),\n paintResources: this.paintResources,\n stats: counters,\n };\n const spans = opts?.spans ?? [];\n let next = 0;\n for (let si = 0; si < spans.length; si++) {\n const span = spans[si];\n for (; next < span.start; next++) dispatch(ctx, commands[next]);\n const drawsBefore = counters.drawCalls;\n const spanT0 = now();\n for (; next < span.end; next++) dispatch(ctx, commands[next]);\n // The stream's closing flush belongs to whatever it closes.\n if (si === spans.length - 1 && next >= commands.length) flushBatch(ctx);\n spanStats.push({ id: span.id, drawCalls: counters.drawCalls - drawsBefore, ms: now() - spanT0 });\n }\n for (; next < commands.length; next++) dispatch(ctx, commands[next]);\n // The stream ended, so whatever is still staged has nothing left that\n // could merge with it.\n flushBatch(ctx);\n // Free transient resources allocated during this frame (e.g. per-frame\n // stroke ribbons from tessellateStroke). Done after all draws complete\n // so we never delete a buffer that's still bound to a pending draw.\n this.meshCache.freeTransient();\n this.stats.drawCalls = counters.drawCalls;\n this.stats.ms = now() - t0;\n }\n\n /** What the last `render()` cost: GL draw calls issued and CPU milliseconds\n * spent issuing them, in total and per requested span. GPU time is not\n * measured; the GPU runs asynchronously. */\n lastFrameStats(): RenderStats {\n return this.stats;\n }\n\n /** Change the curve-flattening tolerance after construction. `undefined`\n * restores the cached `DEFAULT_FLATTEN_TOLERANCE` route. */\n setFlattenTolerance(tolerance: number | undefined): void {\n this.flattenTolerance = tolerance;\n }\n\n resize(dims: { width: number; height: number; dpr: number }): void {\n this.widthCss = dims.width;\n this.heightCss = dims.height;\n this.dpr = dims.dpr;\n if (this.canvas) {\n this.canvas.width = Math.round(dims.width * dims.dpr);\n this.canvas.height = Math.round(dims.height * dims.dpr);\n if (this.canvas.style) {\n this.canvas.style.width = `${dims.width}px`;\n this.canvas.style.height = `${dims.height}px`;\n }\n }\n this.applyTarget();\n }\n\n /** @internal */ _gl(): WebGL2RenderingContext { return this.gl; }\n /** @internal */ _pathFill(): ShaderProgram { return this.pathFill; }\n /** @internal */ _pathFillVColor(): ShaderProgram { return this.pathFillVColor; }\n /** @internal */ _drawBatch(): DrawBatch { return this.drawBatch; }\n /** @internal */ _imageFill(): ShaderProgram { return this.imageFill; }\n /** @internal */ _batchFill(): ShaderProgram { return this.batchFill; }\n /** @internal */ _gradFill(): ShaderProgram { return this.gradFill; }\n /** @internal */ _patternFill(): ShaderProgram { return this.patternFill; }\n /** @internal */ _meshCache(): GLMeshCache { return this.meshCache; }\n /** @internal */ _textureCache(): GLTextureCache { return this.textureCache; }\n /** @internal */ _imageCache(): GLImageCache { return this.imageCache; }\n /** @internal */ _gradRamps(): GradientRampAtlas { return this.gradRamps; }\n /** @internal */ _groupState(): GroupState { return this.groupState; }\n /** @internal */ _widthCss(): number { return this.widthCss; }\n /** @internal */ _heightCss(): number { return this.heightCss; }\n /** @internal */ _dpr(): number { return this.dpr; }\n}\n\n/** The 1x1 opaque white texture a batch flush binds when its run samples no\n * image. NEAREST both ways: one texel, so there is nothing to filter, and a\n * mipmap filter on a texture with no mipmaps is incomplete. */\nfunction createWhiteTexture(gl: WebGL2RenderingContext): WebGLTexture | null {\n const tex = gl.createTexture();\n if (!tex) return null;\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,\n new Uint8Array([255, 255, 255, 255]),\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return tex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyEA,SAASA,GAAmB,GAAiB,GAA2B;CACtE,OAAO;EAAC,GAAGC;EAAqB,GAAGC,EAAoBC,CAAO;EAAG,GAAGD,EAAoBE,CAAO;CAAC;AAClG;AAIA,SAASC,EAAqB,GAA4B,GAAmC;CAC3F,IAAMF,IAAUG,EAAI,SAAS,KAAKC,IAAkBD,EAAI,MAClDE,IAAU,IAAIC,EAAcC,GAAIP,GAASG,EAAI,IAAI;CAIvD,OAHAE,EAAQ,eAAeR,GAAmBG,GAASG,EAAI,IAAI,CAAC,GAC5DE,EAAQ,oBAAoB,IAAI,IAAI,CAAC,GAAGG,EAAqBR,CAAO,GAAG,GAAGQ,EAAqBL,EAAI,IAAI,CAAC,CAAC,CAAC,GAC1GE,EAAQ,iBAAiBI,CAAiB,GACnCJ;AACT;AAkCA,SAASK,IAAc;CACrB,OAAO,OAAO,cAAgB,MAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AA4DA,IAAMC,KAAoF;CACxF,SA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nD,kBAAiC;EAAE,OAAO,KAAK;CAAgB;CAC/D,aAAwB;EAAE,OAAO,KAAK;CAAW;CACjD,aAA4B;EAAE,OAAO,KAAK;CAAW;CACrD,aAA4B;EAAE,OAAO,KAAK;CAAW;CACrD,YAA2B;EAAE,OAAO,KAAK;CAAU;CACnD,eAA8B;EAAE,OAAO,KAAK;CAAa;CACzD,aAA0B;EAAE,OAAO,KAAK;CAAW;CACnD,gBAAgC;EAAE,OAAO,KAAK;CAAc;CAC5D,cAA4B;EAAE,OAAO,KAAK;CAAY;CACtD,aAAgC;EAAE,OAAO,KAAK;CAAW;CACzD,cAA0B;EAAE,OAAO,KAAK;CAAY;CACpD,YAAoB;EAAE,OAAO,KAAK;CAAU;CAC5C,aAAqB;EAAE,OAAO,KAAK;CAAW;CAC9C,OAAe;EAAE,OAAO,KAAK;CAAK;AACrD;AAKA,SAASpC,EAAmB,GAAiD;CAC3E,IAAMqC,IAAMtF,EAAG,cAAc;CAY7B,OAXKsF,KACLtF,EAAG,YAAYA,EAAG,YAAYsF,CAAG,GACjCtF,EAAG,WACDA,EAAG,YAAY,GAAGA,EAAG,MAAM,GAAG,GAAG,GAAGA,EAAG,MAAMA,EAAG,eAChD,IAAI,WAAW;EAAC;EAAK;EAAK;EAAK;CAAG,CAAC,CACrC,GACAA,EAAG,cAAcA,EAAG,YAAYA,EAAG,oBAAoBA,EAAG,OAAO,GACjEA,EAAG,cAAcA,EAAG,YAAYA,EAAG,oBAAoBA,EAAG,OAAO,GACjEA,EAAG,cAAcA,EAAG,YAAYA,EAAG,gBAAgBA,EAAG,aAAa,GACnEA,EAAG,cAAcA,EAAG,YAAYA,EAAG,gBAAgBA,EAAG,aAAa,GACnEA,EAAG,YAAYA,EAAG,YAAY,IAAI,GAC3BsF,KAXU;AAYnB"}
|
|
1
|
+
{"version":3,"file":"WeaselRenderer.js","names":["customUniformNames","CUSTOM_KIT_UNIFORMS","extractUniformNames","vertSrc","fragSrc","compileCustomProgram","src","CUSTOM_VERT_SRC","program","ShaderProgram","gl","extractUniformArrays","CUSTOM_ATTRIBUTES","now","GLYPH_PAINT_SOURCES","GLYPH_PATTERN_FRAG_SRC","GLYPH_PATTERN_UNIFORMS","GLYPH_GRAD_FRAG_SRC","GLYPH_GRAD_UNIFORMS","GLYPH_TEXTURE_FRAG_SRC","GLYPH_TEXTURE_UNIFORMS","WeaselRenderer","GroupState","createPaintResources","opts","EffectTargets","PaintScratch","attrs","DEFAULT_BAKE_BUDGET","OUTLINE_MIN_SCREEN_PX","VERT_SRC","FRAG_SRC","PATH_FILL_UNIFORMS","PATH_FILL_ATTRIBUTES","VCOLOR_VERT_SRC","VCOLOR_FRAG_SRC","PATH_FILL_VCOLOR_ATTRIBUTES","IMAGE_VERT_SRC","IMAGE_FRAG_SRC","IMAGE_FILL_UNIFORMS","IMAGE_FILL_ATTRIBUTES","BATCH_VERT_SRC","BATCH_FRAG_SRC","BATCH_FILL_UNIFORMS","BATCH_FILL_ATTRIBUTES","GRAD_VERT_SRC","GRAD_FRAG_SRC","GRAD_FILL_UNIFORMS","GRAD_FILL_ATTRIBUTES","PATTERN_VERT_SRC","PATTERN_FRAG_SRC","PATTERN_FILL_UNIFORMS","PATTERN_FILL_ATTRIBUTES","aPos","GLMeshCache","GLTextureCache","GLImageCache","GradientRampAtlas","DrawBatch","createWhiteTexture","QUAD_VERTICES","QUAD_INDICES","getProgramSource","handle","previous","id","compiled","e","existing","kind","frag","uniforms","GLYPH_PAINT_VERT_SRC","GLYPH_PAINT_ATTRIBUTES","w","h","x","y","target","markAllFontsNotUploaded","prog","t0","counters","spanStats","resetBakeBudget","ctx","spans","next","si","span","commands","drawsBefore","spanT0","flushBatch","tolerance","dims","tex"],"sources":["../../src/renderer/WeaselRenderer.ts"],"sourcesContent":["import { createPaintResources, type OwnedPaintResources } from './paintResources';\nimport { ShaderProgram } from './shaders/ShaderProgram';\nimport {\n VERT_SRC,\n FRAG_SRC,\n VCOLOR_VERT_SRC,\n VCOLOR_FRAG_SRC,\n PATH_FILL_UNIFORMS,\n PATH_FILL_ATTRIBUTES,\n PATH_FILL_VCOLOR_ATTRIBUTES,\n} from './shaders/pathFill';\nimport {\n markAllFontsNotUploaded,\n resetBakeBudget,\n DEFAULT_BAKE_BUDGET,\n} from '@weasel-js/font';\nimport {\n IMAGE_VERT_SRC,\n IMAGE_FRAG_SRC,\n IMAGE_FILL_UNIFORMS,\n IMAGE_FILL_ATTRIBUTES,\n} from './shaders/imageFill';\nimport {\n BATCH_VERT_SRC,\n BATCH_FRAG_SRC,\n BATCH_FILL_UNIFORMS,\n BATCH_FILL_ATTRIBUTES,\n} from './shaders/batchFill';\nimport {\n GRAD_VERT_SRC,\n GRAD_FRAG_SRC,\n GRAD_FILL_UNIFORMS,\n GRAD_FILL_ATTRIBUTES,\n} from './shaders/gradFill';\nimport {\n PATTERN_VERT_SRC,\n PATTERN_FRAG_SRC,\n PATTERN_FILL_UNIFORMS,\n PATTERN_FILL_ATTRIBUTES,\n} from './shaders/patternFill';\nimport {\n GLYPH_PAINT_VERT_SRC,\n GLYPH_PATTERN_FRAG_SRC,\n GLYPH_GRAD_FRAG_SRC,\n GLYPH_TEXTURE_FRAG_SRC,\n GLYPH_PATTERN_UNIFORMS,\n GLYPH_GRAD_UNIFORMS,\n GLYPH_TEXTURE_UNIFORMS,\n GLYPH_PAINT_ATTRIBUTES,\n} from './shaders/glyphPaint';\nimport { PaintScratch } from './paintScratch';\nimport { GLMeshCache } from './cache/GLMeshCache';\nimport { GLTextureCache } from './cache/GLTextureCache';\nimport { GLImageCache, type ImageMinification } from './cache/GLImageCache';\nimport { GradientRampAtlas } from './cache/GradientRampAtlas';\nimport { GroupState } from './state/GroupState';\nimport type { DrawCommand } from './DrawCommand';\nimport type { GlMat3 } from './math/mat3';\nimport {\n dispatch, flushBatch, OUTLINE_MIN_SCREEN_PX, type DrawContext, type GlyphPaintKind,\n} from './draw';\nimport { DrawBatch } from './drawBatch';\nimport {\n CUSTOM_VERT_SRC, CUSTOM_ATTRIBUTES, CUSTOM_KIT_UNIFORMS,\n QUAD_VERTICES, QUAD_INDICES,\n} from './shaders/customPrelude';\nimport { getProgramSource, type ProgramSource, type ShaderProgramHandle } from './shaders/registerProgram';\nimport { EffectTargets } from './effects/EffectTargets';\nimport { extractUniformArrays, extractUniformNames } from './shaders/extractUniformNames';\n\n/** Every uniform a custom program may be written through. Both stages, not\n * just the fragment one: a name never looked up is written through `null`,\n * which GL accepts silently, so the uniform keeps its zero default. */\nfunction customUniformNames(vertSrc: string, fragSrc: string): string[] {\n return [...CUSTOM_KIT_UNIFORMS, ...extractUniformNames(vertSrc), ...extractUniformNames(fragSrc)];\n}\n\n/** Compile a registered program's source against `gl`, with every uniform\n * location and array base it may be written through. */\nfunction compileCustomProgram(gl: WebGL2RenderingContext, src: ProgramSource): ShaderProgram {\n const vertSrc = src.vert === '' ? CUSTOM_VERT_SRC : src.vert;\n const program = new ShaderProgram(gl, vertSrc, src.frag);\n program.lookupUniforms(customUniformNames(vertSrc, src.frag));\n program.lookupUniformArrays(new Map([...extractUniformArrays(vertSrc), ...extractUniformArrays(src.frag)]));\n program.lookupAttributes(CUSTOM_ATTRIBUTES);\n return program;\n}\n\n/** How to construct a `WeaselRenderer`: the GL context or canvas to draw\n * into, the output size, and the quality knobs that separate screen\n * rendering from print. */\n/** A run of top-level commands, `[start, end)` by index, that\n * {@link WeaselRenderer.lastFrameStats} accounts for separately — one render\n * layer's commands, say. Spans are in order and do not overlap. */\nexport interface RenderSpan {\n id: string;\n start: number;\n end: number;\n}\n\n/** Per-frame options for {@link WeaselRenderer.render}. */\nexport interface RenderOptions {\n spans?: readonly RenderSpan[];\n}\n\n/** What one span cost. A batched run is drawn when something closes it, so\n * its draw call counts toward the span that closed it. */\nexport interface RenderSpanStats {\n id: string;\n drawCalls: number;\n ms: number;\n}\n\n/** What one `render()` cost. See {@link WeaselRenderer.lastFrameStats}. */\nexport interface RenderStats {\n drawCalls: number;\n ms: number;\n spans: RenderSpanStats[];\n}\n\nfunction now(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\n\n/** Construction options for {@link WeaselRenderer}. Pass `gl` or `canvas`;\n * a context passed in must have a stencil buffer. */\nexport interface WeaselRendererOptions {\n /** A WebGL2 context to draw with. Wins over `canvas`. */\n gl?: WebGL2RenderingContext;\n /** A canvas to open a stencil-backed WebGL2 context on, when `gl` is absent. */\n canvas?: HTMLCanvasElement;\n /** Drawing size in CSS pixels. */\n width: number;\n /** Drawing size in CSS pixels. */\n height: number;\n /** Device pixels per CSS pixel. */\n dpr: number;\n /** MIN_FILTER strategy for image/pattern textures (`GLImageCache`).\n * Default `'linear'` — the existing screen behavior. The headless\n * `renderSceneToPixels` path passes `'mipmap'` for print-quality\n * minification. Explicitly passing `'linear'` is always valid. */\n imageMinification?: ImageMinification;\n /** Flatness tolerance for curve tessellation, in WORLD units (see\n * `TessellateOptions.flattenTolerance`). When set, path fills are\n * tessellated fresh at this tolerance per frame (transient pool) instead\n * of served from the Path-identity mesh cache — the cache key does not\n * include tolerance. Default: unset — the existing cached behavior at\n * `DEFAULT_FLATTEN_TOLERANCE`. The headless path derives this from the\n * requested output scale; screen callers normally leave it unset. */\n flattenTolerance?: number;\n /** Per-render synchronous bake budget for dynamic canvas-SDF glyphs.\n * Default DEFAULT_BAKE_BUDGET (16). The headless renderSceneToPixels\n * path passes Infinity so print never defers a glyph. */\n bakeBudget?: number;\n /** On-screen glyph size, in CSS pixels, at or above which text renders from\n * tessellated font outlines instead of a distance field — see\n * `OUTLINE_MIN_SCREEN_PX`. Only faces registered with\n * `registerFontOutlines` are affected; everything else keeps its SDF tier\n * whatever this says. Pass `Infinity` to disable the tier outright, or 0\n * to use outlines wherever they exist (what the headless path does, since\n * print has no reason to sample a field it could evaluate exactly). */\n textOutlineMinScreenSize?: number;\n}\n\n/** Where a renderer draws inside a buffer it does not own.\n *\n * The rect's SIZE is the renderer's own `width`/`height` — `resize()` owns\n * that, and a second copy here could disagree with the one `DrawContext`\n * reports to screen-space layers. */\nexport interface RenderTarget {\n /** Top-left of this renderer's output within the drawing buffer, in CSS\n * pixels, with the origin at the buffer's top-left. GL's bottom-left origin\n * is handled internally. */\n origin: { x: number; y: number };\n /** Clear colour and stencil within the rect before drawing. Default true.\n * Pass false only when the caller clears the whole buffer itself on behalf\n * of every co-tenant — a frame that clears neither inherits its neighbour's\n * stencil bits, and even-odd fills then fill their holes. */\n clear?: boolean;\n}\n\n/** Each glyph-paint program's fragment stage and the uniforms it looks up. */\nconst GLYPH_PAINT_SOURCES: Record<GlyphPaintKind, readonly [string, readonly string[]]> = {\n pattern: [GLYPH_PATTERN_FRAG_SRC, GLYPH_PATTERN_UNIFORMS],\n gradient: [GLYPH_GRAD_FRAG_SRC, GLYPH_GRAD_UNIFORMS],\n texture: [GLYPH_TEXTURE_FRAG_SRC, GLYPH_TEXTURE_UNIFORMS],\n};\n\n/**\n * The WebGL2 renderer: takes a list of draw commands and paints them.\n *\n * It knows nothing about the scene — commands are the whole interface, which\n * is what lets layers, HUD widgets and overlays all draw through the same\n * pipeline. GPU resources (meshes, textures, gradient ramps) are cached across\n * frames and keyed by identity, so re-issuing the same command is cheap.\n */\nexport class WeaselRenderer {\n private readonly gl: WebGL2RenderingContext;\n private stats: RenderStats = { drawCalls: 0, ms: 0, spans: [] };\n private pathFill: ShaderProgram;\n private pathFillVColor: ShaderProgram;\n private imageFill: ShaderProgram;\n private batchFill: ShaderProgram;\n private gradFill: ShaderProgram;\n private patternFill: ShaderProgram;\n /** Compiled on first use: only atlas text under a texture paint needs one. */\n private glyphPaintPrograms = new Map<GlyphPaintKind, ShaderProgram>();\n private meshCache: GLMeshCache;\n private textureCache: GLTextureCache;\n private imageCache: GLImageCache;\n private gradRamps: GradientRampAtlas;\n private programRegistry = new Map<string, ShaderProgram>();\n /** The source each compiled custom program was built from — or, after a\n * failed recompile, the source that failed, so it is not retried every frame. */\n private programSources = new Map<string, ProgramSource>();\n private quadVbo: WebGLBuffer | null = null;\n private quadIbo: WebGLBuffer | null = null;\n private drawBatch: DrawBatch;\n /** 1x1 white, so a batch flush sampling no image still samples something —\n * see `shaders/batchFill.ts`. */\n private whiteTexture: WebGLTexture | null = null;\n private readonly groupState = new GroupState();\n private widthCss: number;\n private heightCss: number;\n private dpr: number;\n private canvas: HTMLCanvasElement | null = null;\n private target: RenderTarget | null = null;\n /** Offscreen buffers for group effects. Allocates nothing until a group\n * with effects asks, so a canvas without them pays no memory. */\n private readonly effectTargets: EffectTargets;\n private readonly paintScratch: PaintScratch;\n private readonly imageMinification: ImageMinification;\n private flattenTolerance?: number;\n private readonly bakeBudget: number;\n private readonly textOutlineMinScreenSize: number;\n private contextLost = false;\n private boundOnLost = (e: Event) => this.onContextLost(e);\n private boundOnRestored = () => this.onContextRestored();\n /** True after `dispose()`. A disposed renderer ignores further `render()`\n * calls and `registerProgram()` calls. */\n private disposed = false;\n /** What registered paint kinds hang their GPU state on. One per context\n * generation: a restore releases it and opens the next. */\n private paintResources: OwnedPaintResources = createPaintResources();\n\n constructor(opts: WeaselRendererOptions) {\n if (!opts.gl && !opts.canvas) {\n throw new Error('WeaselRenderer requires either gl or canvas');\n }\n const gl = opts.gl ?? opts.canvas!.getContext('webgl2', { stencil: true });\n if (!gl) throw new Error('WeaselRenderer: WebGL2 not available');\n this.gl = gl as WebGL2RenderingContext;\n this.effectTargets = new EffectTargets(this.gl);\n this.paintScratch = new PaintScratch(this.gl);\n\n // Bits 0-7 are load-bearing: bit 0 for even-odd fills and stenciled\n // strokes, bits 1-7 for clip depth (`renderer/draw.ts`). Without a stencil\n // buffer both render wrong rather than not at all, so refuse the context\n // instead of painting a plausible lie. A stub that cannot answer is not a\n // stencil-less context — only an explicit `false` is.\n const attrs = typeof this.gl.getContextAttributes === 'function'\n ? this.gl.getContextAttributes()\n : null;\n if (attrs && attrs.stencil === false) {\n throw new Error(\n 'WeaselRenderer: the supplied WebGL2 context has no stencil buffer. '\n + 'Create it with { stencil: true } — clips and even-odd fills need one.',\n );\n }\n\n this.widthCss = opts.width;\n this.heightCss = opts.height;\n this.dpr = opts.dpr;\n this.imageMinification = opts.imageMinification ?? 'linear';\n this.flattenTolerance = opts.flattenTolerance;\n this.bakeBudget = opts.bakeBudget ?? DEFAULT_BAKE_BUDGET;\n this.textOutlineMinScreenSize = opts.textOutlineMinScreenSize ?? OUTLINE_MIN_SCREEN_PX;\n\n this.canvas = opts.canvas ?? null;\n if (this.canvas) {\n this.canvas.width = Math.round(opts.width * opts.dpr);\n this.canvas.height = Math.round(opts.height * opts.dpr);\n if (this.canvas.style) {\n this.canvas.style.width = `${opts.width}px`;\n this.canvas.style.height = `${opts.height}px`;\n }\n this.canvas.addEventListener('webglcontextlost', this.boundOnLost);\n this.canvas.addEventListener('webglcontextrestored', this.boundOnRestored);\n }\n\n this.applyGlState();\n this.applyTarget();\n\n this.pathFill = new ShaderProgram(this.gl, VERT_SRC, FRAG_SRC);\n this.pathFill.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFill.lookupAttributes(PATH_FILL_ATTRIBUTES);\n\n this.pathFillVColor = new ShaderProgram(this.gl, VCOLOR_VERT_SRC, VCOLOR_FRAG_SRC);\n this.pathFillVColor.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFillVColor.lookupAttributes(PATH_FILL_VCOLOR_ATTRIBUTES);\n\n this.imageFill = new ShaderProgram(this.gl, IMAGE_VERT_SRC, IMAGE_FRAG_SRC);\n this.imageFill.lookupUniforms(IMAGE_FILL_UNIFORMS);\n this.imageFill.lookupAttributes(IMAGE_FILL_ATTRIBUTES);\n\n this.batchFill = new ShaderProgram(this.gl, BATCH_VERT_SRC, BATCH_FRAG_SRC);\n this.batchFill.lookupUniforms(BATCH_FILL_UNIFORMS);\n this.batchFill.lookupAttributes(BATCH_FILL_ATTRIBUTES);\n\n this.gradFill = new ShaderProgram(this.gl, GRAD_VERT_SRC, GRAD_FRAG_SRC);\n this.gradFill.lookupUniforms(GRAD_FILL_UNIFORMS);\n this.gradFill.lookupAttributes(GRAD_FILL_ATTRIBUTES);\n\n this.patternFill = new ShaderProgram(this.gl, PATTERN_VERT_SRC, PATTERN_FRAG_SRC);\n this.patternFill.lookupUniforms(PATTERN_FILL_UNIFORMS);\n this.patternFill.lookupAttributes(PATTERN_FILL_ATTRIBUTES);\n\n const aPos = this.pathFill.attribute('a_position');\n if (aPos === undefined) throw new Error('WeaselRenderer: a_position not found in path-fill shader');\n this.meshCache = new GLMeshCache(this.gl, aPos);\n this.textureCache = new GLTextureCache(this.gl);\n this.imageCache = new GLImageCache(this.gl, this.imageMinification);\n this.gradRamps = new GradientRampAtlas(this.gl);\n this.uploadQuadGeometry();\n this.drawBatch = new DrawBatch(this.gl, this.batchFill);\n this.whiteTexture = createWhiteTexture(this.gl);\n }\n\n private uploadQuadGeometry(): void {\n const gl = this.gl;\n this.quadVbo = gl.createBuffer();\n this.quadIbo = gl.createBuffer();\n if (!this.quadVbo || !this.quadIbo) {\n throw new Error('WeaselRenderer: failed to create quad geometry buffers');\n }\n gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVbo);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_VERTICES, gl.STATIC_DRAW);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.quadIbo);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, QUAD_INDICES, gl.STATIC_DRAW);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n }\n\n /**\n * Compile a consumer-registered shader program against this renderer's GL context.\n *\n * Call once per renderer after the module-level `registerProgram()`.\n * Throws `ShaderCompileError` if compilation fails.\n *\n * In dev mode, calling again with the same handle replaces the compiled program.\n *\n * @experimental\n */\n registerProgram(handle: ShaderProgramHandle): void {\n // A disposed renderer must not compile programs into the cleared registry.\n if (this.disposed) return;\n const src = getProgramSource(handle.id);\n if (!src) {\n throw new Error(\n `WeaselRenderer.registerProgram: program \"${handle.id}\" not found in source registry. ` +\n `Call the module-level registerProgram() first.`,\n );\n }\n this.installProgram(handle.id, src, compileCustomProgram(this.gl, src));\n }\n\n private installProgram(id: string, src: ProgramSource, program: ShaderProgram): void {\n const previous = this.programRegistry.get(id);\n if (previous) this.gl.deleteProgram(previous.handle);\n this.programRegistry.set(id, program);\n this.programSources.set(id, src);\n }\n\n /** Recompile every program whose module-level source was re-registered\n * since it was compiled. A source that fails keeps the old program drawing. */\n private refreshPrograms(): void {\n for (const [id, compiled] of this.programSources) {\n const src = getProgramSource(id);\n if (!src || src === compiled) continue;\n if (src.vert === compiled.vert && src.frag === compiled.frag) {\n this.programSources.set(id, src);\n continue;\n }\n try {\n this.installProgram(id, src, compileCustomProgram(this.gl, src));\n } catch (e) {\n this.programSources.set(id, src);\n console.error(`weasel: failed to recompile re-registered program \"${id}\"; still drawing the previous one:`, e);\n }\n }\n }\n\n /**\n * The compiled program for `id`, compiling it against this context on first\n * use. Unlike {@link registerProgram} this neither throws on a missing\n * source nor on a compile failure: a paint kind asking for a program it\n * never registered must decline the paint, not take down the frame.\n */\n private ensureProgram(id: string): ShaderProgram | null {\n const existing = this.programRegistry.get(id);\n if (existing) return existing;\n if (this.disposed || !getProgramSource(id)) return null;\n try {\n this.registerProgram({ id });\n } catch (e) {\n console.error(`weasel: failed to compile paint program \"${id}\":`, e);\n return null;\n }\n return this.programRegistry.get(id) ?? null;\n }\n\n private glyphPaintProgram(kind: GlyphPaintKind): ShaderProgram {\n const existing = this.glyphPaintPrograms.get(kind);\n if (existing) return existing;\n const [frag, uniforms] = GLYPH_PAINT_SOURCES[kind];\n const program = new ShaderProgram(this.gl, GLYPH_PAINT_VERT_SRC, frag);\n program.lookupUniforms(uniforms);\n program.lookupAttributes(GLYPH_PAINT_ATTRIBUTES);\n this.glyphPaintPrograms.set(kind, program);\n return program;\n }\n\n /** The GL state every frame assumes. Applied per `render()` rather than once\n * at construction because a co-tenant sharing this context moves all of it\n * between our frames. */\n private applyGlState(): void {\n const gl = this.gl;\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.CULL_FACE);\n gl.clearColor(0, 0, 0, 0);\n }\n\n /** Viewport and scissor for this frame. Re-applied inside `render()` because\n * a co-tenant on the same context moves both between our frames. */\n private applyTarget(): void {\n const gl = this.gl;\n const w = Math.round(this.widthCss * this.dpr);\n const h = Math.round(this.heightCss * this.dpr);\n if (!this.target) {\n gl.disable(gl.SCISSOR_TEST);\n gl.viewport(0, 0, w, h);\n return;\n }\n const x = Math.round(this.target.origin.x * this.dpr);\n const y = gl.drawingBufferHeight - Math.round(this.target.origin.y * this.dpr) - h;\n gl.viewport(x, y, w, h);\n gl.scissor(x, y, w, h);\n gl.enable(gl.SCISSOR_TEST);\n }\n\n /** Confine this renderer to a rect of its drawing buffer, or pass null to\n * give it the whole buffer back. Takes effect from the next `render()`. */\n setTarget(target: RenderTarget | null): void {\n this.target = target;\n this.applyTarget();\n }\n\n getTarget(): RenderTarget | null {\n return this.target;\n }\n\n isContextLost(): boolean {\n return this.contextLost;\n }\n\n private onContextLost(e: Event): void {\n e.preventDefault();\n this.contextLost = true;\n }\n\n private onContextRestored(): void {\n this.contextLost = false;\n this.applyGlState();\n this.applyTarget();\n // Every framebuffer, texture and renderbuffer the pool held died with the\n // context. `releaseAll` deletes handles that are already gone, which is a\n // no-op, and drops the bookkeeping that would otherwise hand a dead FBO to\n // the next group with effects.\n this.effectTargets.releaseAll();\n this.paintScratch.release();\n this.paintResources.release();\n this.paintResources = createPaintResources();\n this.pathFill = new ShaderProgram(this.gl, VERT_SRC, FRAG_SRC);\n this.pathFill.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFill.lookupAttributes(PATH_FILL_ATTRIBUTES);\n this.pathFillVColor = new ShaderProgram(this.gl, VCOLOR_VERT_SRC, VCOLOR_FRAG_SRC);\n this.pathFillVColor.lookupUniforms(PATH_FILL_UNIFORMS);\n this.pathFillVColor.lookupAttributes(PATH_FILL_VCOLOR_ATTRIBUTES); this.imageFill = new ShaderProgram(this.gl, IMAGE_VERT_SRC, IMAGE_FRAG_SRC);\n this.imageFill.lookupUniforms(IMAGE_FILL_UNIFORMS);\n this.imageFill.lookupAttributes(IMAGE_FILL_ATTRIBUTES);\n\n this.batchFill = new ShaderProgram(this.gl, BATCH_VERT_SRC, BATCH_FRAG_SRC);\n this.batchFill.lookupUniforms(BATCH_FILL_UNIFORMS);\n this.batchFill.lookupAttributes(BATCH_FILL_ATTRIBUTES);\n this.gradFill = new ShaderProgram(this.gl, GRAD_VERT_SRC, GRAD_FRAG_SRC);\n this.gradFill.lookupUniforms(GRAD_FILL_UNIFORMS);\n this.gradFill.lookupAttributes(GRAD_FILL_ATTRIBUTES);\n\n this.patternFill = new ShaderProgram(this.gl, PATTERN_VERT_SRC, PATTERN_FRAG_SRC);\n this.patternFill.lookupUniforms(PATTERN_FILL_UNIFORMS);\n this.patternFill.lookupAttributes(PATTERN_FILL_ATTRIBUTES);\n this.glyphPaintPrograms.clear();\n const aPos = this.pathFill.attribute('a_position');\n if (aPos === undefined) throw new Error('a_position missing after restore');\n this.meshCache = new GLMeshCache(this.gl, aPos);\n this.textureCache = new GLTextureCache(this.gl);\n this.imageCache.abandon();\n this.imageCache = new GLImageCache(this.gl, this.imageMinification);\n this.gradRamps = new GradientRampAtlas(this.gl);\n markAllFontsNotUploaded();\n\n this.uploadQuadGeometry();\n this.drawBatch = new DrawBatch(this.gl, this.batchFill);\n this.whiteTexture = createWhiteTexture(this.gl);\n for (const id of this.programRegistry.keys()) {\n const src = getProgramSource(id);\n if (!src) continue;\n try {\n this.programRegistry.set(id, compileCustomProgram(this.gl, src));\n this.programSources.set(id, src);\n } catch (e) {\n console.error(`weasel: failed to recompile program \"${id}\" after context restore:`, e);\n }\n }\n }\n\n /** Free every GL resource this renderer created and detach context-loss\n * listeners when a canvas was supplied. Idempotent.\n *\n * That covers the built-in and consumer-registered programs (their shaders\n * go with them), the shared quad geometry, the batch, the effect targets,\n * and every cache: atlas and gradient-ramp textures, bitmap and pattern\n * textures, and meshes — transient, persistent, and those whose Path was\n * already collected. The context itself is left alone, so a caller-owned\n * context can host renderer after renderer without accumulating anything.\n *\n * A disposed renderer ignores further `render()` and `registerProgram()`\n * calls. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n const gl = this.gl;\n if (this.canvas) {\n this.canvas.removeEventListener('webglcontextlost', this.boundOnLost);\n this.canvas.removeEventListener('webglcontextrestored', this.boundOnRestored);\n }\n this.meshCache.dispose();\n this.paintResources.release();\n for (const prog of [\n this.pathFill, this.pathFillVColor, this.imageFill, this.batchFill, this.gradFill, this.patternFill,\n ...this.glyphPaintPrograms.values(),\n ]) {\n gl.deleteProgram(prog.handle);\n }\n this.glyphPaintPrograms.clear();\n for (const prog of this.programRegistry.values()) {\n gl.deleteProgram(prog.handle);\n }\n this.programRegistry.clear();\n this.programSources.clear();\n this.textureCache.free();\n this.imageCache.dispose();\n this.gradRamps.free();\n if (this.quadVbo) gl.deleteBuffer(this.quadVbo);\n if (this.quadIbo) gl.deleteBuffer(this.quadIbo);\n this.drawBatch.dispose();\n if (this.whiteTexture) gl.deleteTexture(this.whiteTexture);\n this.whiteTexture = null;\n this.effectTargets.releaseAll();\n this.paintScratch.release();\n }\n\n /**\n * Draw one frame.\n *\n * `viewMatrix` is the frame's world→screen transform. It is only consulted\n * by `units: 'world'` gradients, which fall back to screen space without\n * it — every other command carries its own transform in the stream, so\n * callers with no view concept can keep calling `render(commands)`.\n */\n render(commands: DrawCommand[], viewMatrix?: GlMat3, opts?: RenderOptions): void {\n if (this.contextLost || this.disposed) return;\n const t0 = now();\n const counters = { drawCalls: 0 };\n const spanStats: RenderSpanStats[] = [];\n this.stats = { drawCalls: 0, ms: 0, spans: spanStats };\n const gl = this.gl;\n // Free GL resources whose Mesh was GC'd since the last frame. Done here\n // (top of render, before any draws) because GL state is known clean —\n // no VAO bound, no draw in flight. Deleting from the FinalizationRegistry\n // callback directly was racy and caused mid-draw crashes.\n this.meshCache.drainPendingDeletes();\n this.refreshPrograms();\n // New frame: refill the dynamic-glyph synchronous bake budget.\n resetBakeBudget(this.bakeBudget);\n this.groupState.reset();\n this.applyGlState();\n this.applyTarget();\n // Ensure all stencil bits are cleared regardless of any mask left over\n // from the previous frame's clip ops.\n if (this.target?.clear !== false) {\n gl.stencilMask(0xFF);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);\n }\n const ctx: DrawContext = {\n gl,\n pathFill: this.pathFill,\n pathFillVColor: this.pathFillVColor,\n imageFill: this.imageFill,\n batchFill: this.batchFill,\n gradFill: this.gradFill,\n patternFill: this.patternFill,\n meshCache: this.meshCache,\n textureCache: this.textureCache,\n imageCache: this.imageCache,\n gradRamps: this.gradRamps,\n programRegistry: this.programRegistry,\n ensureProgram: (id) => this.ensureProgram(id),\n glyphPaintProgram: (kind) => this.glyphPaintProgram(kind),\n quadVbo: this.quadVbo,\n quadIbo: this.quadIbo,\n drawBatch: this.drawBatch,\n whiteTexture: this.whiteTexture,\n state: this.groupState,\n widthCss: this.widthCss,\n heightCss: this.heightCss,\n clipDepth: 0,\n clipStack: [],\n flattenTolerance: this.flattenTolerance,\n textOutlineMinScreenSize: this.textOutlineMinScreenSize,\n viewMatrix,\n effectTargets: this.effectTargets,\n paintScratch: this.paintScratch,\n renderTarget: null,\n deviceWidth: Math.round(this.widthCss * this.dpr),\n deviceHeight: Math.round(this.heightCss * this.dpr),\n restoreTargetRect: () => this.applyTarget(),\n paintResources: this.paintResources,\n stats: counters,\n };\n // A frame that threw part-way left its clip here.\n this.drawBatch.clip = null;\n const spans = opts?.spans ?? [];\n let next = 0;\n for (let si = 0; si < spans.length; si++) {\n const span = spans[si];\n for (; next < span.start; next++) dispatch(ctx, commands[next]);\n const drawsBefore = counters.drawCalls;\n const spanT0 = now();\n for (; next < span.end; next++) dispatch(ctx, commands[next]);\n // The stream's closing flush belongs to whatever it closes.\n if (si === spans.length - 1 && next >= commands.length) flushBatch(ctx);\n spanStats.push({ id: span.id, drawCalls: counters.drawCalls - drawsBefore, ms: now() - spanT0 });\n }\n for (; next < commands.length; next++) dispatch(ctx, commands[next]);\n // The stream ended, so whatever is still staged has nothing left that\n // could merge with it.\n flushBatch(ctx);\n // Free transient resources allocated during this frame (e.g. per-frame\n // stroke ribbons from tessellateStroke). Done after all draws complete\n // so we never delete a buffer that's still bound to a pending draw.\n this.meshCache.freeTransient();\n this.stats.drawCalls = counters.drawCalls;\n this.stats.ms = now() - t0;\n }\n\n /** What the last `render()` cost: GL draw calls issued and CPU milliseconds\n * spent issuing them, in total and per requested span. GPU time is not\n * measured; the GPU runs asynchronously. */\n lastFrameStats(): RenderStats {\n return this.stats;\n }\n\n /** Change the curve-flattening tolerance after construction. `undefined`\n * restores the cached `DEFAULT_FLATTEN_TOLERANCE` route. */\n setFlattenTolerance(tolerance: number | undefined): void {\n this.flattenTolerance = tolerance;\n }\n\n resize(dims: { width: number; height: number; dpr: number }): void {\n this.widthCss = dims.width;\n this.heightCss = dims.height;\n this.dpr = dims.dpr;\n if (this.canvas) {\n this.canvas.width = Math.round(dims.width * dims.dpr);\n this.canvas.height = Math.round(dims.height * dims.dpr);\n if (this.canvas.style) {\n this.canvas.style.width = `${dims.width}px`;\n this.canvas.style.height = `${dims.height}px`;\n }\n }\n this.applyTarget();\n }\n\n /** @internal */ _gl(): WebGL2RenderingContext { return this.gl; }\n /** @internal */ _pathFill(): ShaderProgram { return this.pathFill; }\n /** @internal */ _pathFillVColor(): ShaderProgram { return this.pathFillVColor; }\n /** @internal */ _drawBatch(): DrawBatch { return this.drawBatch; }\n /** @internal */ _imageFill(): ShaderProgram { return this.imageFill; }\n /** @internal */ _batchFill(): ShaderProgram { return this.batchFill; }\n /** @internal */ _gradFill(): ShaderProgram { return this.gradFill; }\n /** @internal */ _patternFill(): ShaderProgram { return this.patternFill; }\n /** @internal */ _meshCache(): GLMeshCache { return this.meshCache; }\n /** @internal */ _textureCache(): GLTextureCache { return this.textureCache; }\n /** @internal */ _imageCache(): GLImageCache { return this.imageCache; }\n /** @internal */ _gradRamps(): GradientRampAtlas { return this.gradRamps; }\n /** @internal */ _groupState(): GroupState { return this.groupState; }\n /** @internal */ _widthCss(): number { return this.widthCss; }\n /** @internal */ _heightCss(): number { return this.heightCss; }\n /** @internal */ _dpr(): number { return this.dpr; }\n}\n\n/** The 1x1 opaque white texture a batch flush binds when its run samples no\n * image. NEAREST both ways: one texel, so there is nothing to filter, and a\n * mipmap filter on a texture with no mipmaps is incomplete. */\nfunction createWhiteTexture(gl: WebGL2RenderingContext): WebGLTexture | null {\n const tex = gl.createTexture();\n if (!tex) return null;\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,\n new Uint8Array([255, 255, 255, 255]),\n );\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n return tex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyEA,SAASA,GAAmB,GAAiB,GAA2B;CACtE,OAAO;EAAC,GAAGC;EAAqB,GAAGC,EAAoBC,CAAO;EAAG,GAAGD,EAAoBE,CAAO;CAAC;AAClG;AAIA,SAASC,EAAqB,GAA4B,GAAmC;CAC3F,IAAMF,IAAUG,EAAI,SAAS,KAAKC,IAAkBD,EAAI,MAClDE,IAAU,IAAIC,EAAcC,GAAIP,GAASG,EAAI,IAAI;CAIvD,OAHAE,EAAQ,eAAeR,GAAmBG,GAASG,EAAI,IAAI,CAA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AG,oBAAoBA,EAAG,OAAO,GACjEA,EAAG,cAAcA,EAAG,YAAYA,EAAG,gBAAgBA,EAAG,aAAa,GACnEA,EAAG,cAAcA,EAAG,YAAYA,EAAG,gBAAgBA,EAAG,aAAa,GACnEA,EAAG,YAAYA,EAAG,YAAY,IAAI,GAC3BsF,KAXU;AAYnB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//#region src/renderer/batchClip.ts
|
|
2
|
+
function e(e, t) {
|
|
3
|
+
if (e.kind !== "rect" || !(t[1] === 0 && t[3] === 0 || t[0] === 0 && t[4] === 0)) return null;
|
|
4
|
+
let n = t[0] * e.x + t[3] * e.y + t[6], r = t[1] * e.x + t[4] * e.y + t[7], i = e.x + e.width, a = e.y + e.height, o = t[0] * i + t[3] * a + t[6], s = t[1] * i + t[4] * a + t[7];
|
|
5
|
+
return {
|
|
6
|
+
x0: Math.min(n, o),
|
|
7
|
+
y0: Math.min(r, s),
|
|
8
|
+
x1: Math.max(n, o),
|
|
9
|
+
y1: Math.max(r, s)
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function t(e, t) {
|
|
13
|
+
return {
|
|
14
|
+
x0: Math.max(e.x0, t.x0),
|
|
15
|
+
y0: Math.max(e.y0, t.y0),
|
|
16
|
+
x1: Math.min(e.x1, t.x1),
|
|
17
|
+
y1: Math.min(e.y1, t.y1)
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function n(e, t, n, i, a, o) {
|
|
21
|
+
let s = r(e, t, n, 0, i.x0, 1, o);
|
|
22
|
+
return s = r(o, s, n, 0, i.x1, -1, a), s = r(a, s, n, 1, i.y0, 1, o), r(o, s, n, 1, i.y1, -1, a);
|
|
23
|
+
}
|
|
24
|
+
function r(e, t, n, r, i, a, o) {
|
|
25
|
+
if (t === 0) return 0;
|
|
26
|
+
let s = 0, c = t - 1, l = a * (e[c * n + r] - i) >= 0;
|
|
27
|
+
for (let u = 0; u < t; u++) {
|
|
28
|
+
let t = a * (e[u * n + r] - i) >= 0;
|
|
29
|
+
if (t !== l) {
|
|
30
|
+
let t = c * n, a = u * n, l = (i - e[t + r]) / (e[a + r] - e[t + r]), d = s * n;
|
|
31
|
+
for (let r = 0; r < n; r++) o[d + r] = e[t + r] + l * (e[a + r] - e[t + r]);
|
|
32
|
+
o[d + r] = i, s++;
|
|
33
|
+
}
|
|
34
|
+
if (t) {
|
|
35
|
+
let t = s * n, r = u * n;
|
|
36
|
+
for (let i = 0; i < n; i++) o[t + i] = e[r + i];
|
|
37
|
+
s++;
|
|
38
|
+
}
|
|
39
|
+
c = u, l = t;
|
|
40
|
+
}
|
|
41
|
+
return s;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { e as axisAlignedClipRect, n as clipConvexPolygon, t as intersectClipRects };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=batchClip.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batchClip.js","names":["axisAlignedClipRect","path","m","ax","ay","x1","y1","bx","by","intersectClipRects","a","b","clipConvexPolygon","count","clipEdge","src","n","stride","rect","tmp","dst","prev","prevIn","sign","axis","at","cur","curIn","t","o","k","c"],"sources":["../../src/renderer/batchClip.ts"],"sourcesContent":["/**\n * Clipping staged geometry to an axis-aligned rect on the CPU, so a rect clip\n * needs no stencil and does not break the run.\n *\n * A stencil clip is GL state, so content inside one cannot share a draw with\n * content outside it, and every clipped group paid a flush on the way in and\n * another on the way out. A rect under a transform that keeps it axis-aligned\n * is the common clip, and for that one the clip can ride the geometry instead:\n * cut each staged polygon to the rect before it joins the run.\n *\n * Exact, not approximate: every attribute a batch vertex carries is affine\n * across the polygon it belongs to, so interpolating along a cut edge gives\n * the value the rasterizer would have produced there, and the cut polygon\n * covers the same pixel centers the stencil would have passed.\n */\n\nimport type { Path } from '@weasel-js/geom';\nimport type { GlMat3 } from './math/mat3';\n\n/** In the space batch vertices are staged in: after the model transform,\n * before the projection. */\nexport interface ClipRect {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\n/**\n * `path` under `m` as a `ClipRect`, or `null` when it is not one: not a rect\n * path, or a transform that rotates or skews it off the axes.\n */\nexport function axisAlignedClipRect(path: Path, m: GlMat3): ClipRect | null {\n if (path.kind !== 'rect') return null;\n const keepsAxes = (m[1] === 0 && m[3] === 0) || (m[0] === 0 && m[4] === 0);\n if (!keepsAxes) return null;\n const ax = m[0] * path.x + m[3] * path.y + m[6];\n const ay = m[1] * path.x + m[4] * path.y + m[7];\n const x1 = path.x + path.width;\n const y1 = path.y + path.height;\n const bx = m[0] * x1 + m[3] * y1 + m[6];\n const by = m[1] * x1 + m[4] * y1 + m[7];\n return {\n x0: Math.min(ax, bx), y0: Math.min(ay, by),\n x1: Math.max(ax, bx), y1: Math.max(ay, by),\n };\n}\n\nexport function intersectClipRects(a: ClipRect, b: ClipRect): ClipRect {\n return {\n x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0),\n x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1),\n };\n}\n\n/**\n * Cut the convex polygon of `n` vertices in `src` (each `stride` floats, x and\n * y first) to `rect`, writing the result to `dst`. Returns the vertex count,\n * which is below 3 when nothing is left. `tmp` must hold as many floats as\n * `dst`; both need room for `n + 4` vertices.\n */\nexport function clipConvexPolygon(\n src: Float32Array, n: number, stride: number, rect: ClipRect,\n dst: Float32Array, tmp: Float32Array,\n): number {\n // Four passes, ping-ponging so the last one lands in `dst`.\n let count = clipEdge(src, n, stride, 0, rect.x0, 1, tmp);\n count = clipEdge(tmp, count, stride, 0, rect.x1, -1, dst);\n count = clipEdge(dst, count, stride, 1, rect.y0, 1, tmp);\n return clipEdge(tmp, count, stride, 1, rect.y1, -1, dst);\n}\n\n/** One Sutherland–Hodgman pass: keep the side of `axis = at` where\n * `sign * (v - at) >= 0`. */\nfunction clipEdge(\n src: Float32Array, n: number, stride: number,\n axis: 0 | 1, at: number, sign: 1 | -1, out: Float32Array,\n): number {\n if (n === 0) return 0;\n let m = 0;\n let prev = n - 1;\n let prevIn = sign * (src[prev * stride + axis] - at) >= 0;\n for (let cur = 0; cur < n; cur++) {\n const curIn = sign * (src[cur * stride + axis] - at) >= 0;\n if (curIn !== prevIn) {\n const a = prev * stride;\n const b = cur * stride;\n const t = (at - src[a + axis]) / (src[b + axis] - src[a + axis]);\n const o = m * stride;\n for (let k = 0; k < stride; k++) out[o + k] = src[a + k] + t * (src[b + k] - src[a + k]);\n // On the line exactly, whatever the interpolation rounded to.\n out[o + axis] = at;\n m++;\n }\n if (curIn) {\n const o = m * stride;\n const c = cur * stride;\n for (let k = 0; k < stride; k++) out[o + k] = src[c + k];\n m++;\n }\n prev = cur;\n prevIn = curIn;\n }\n return m;\n}\n"],"mappings":";AAgCA,SAAgBA,EAAoB,GAAY,GAA4B;CAG1E,IAFIC,EAAK,SAAS,UAEd,EADeC,EAAE,OAAO,KAAKA,EAAE,OAAO,KAAOA,EAAE,OAAO,KAAKA,EAAE,OAAO,IACxD,OAAO;CACvB,IAAMC,IAAKD,EAAE,KAAKD,EAAK,IAAIC,EAAE,KAAKD,EAAK,IAAIC,EAAE,IACvCE,IAAKF,EAAE,KAAKD,EAAK,IAAIC,EAAE,KAAKD,EAAK,IAAIC,EAAE,IACvCG,IAAKJ,EAAK,IAAIA,EAAK,OACnBK,IAAKL,EAAK,IAAIA,EAAK,QACnBM,IAAKL,EAAE,KAAKG,IAAKH,EAAE,KAAKI,IAAKJ,EAAE,IAC/BM,IAAKN,EAAE,KAAKG,IAAKH,EAAE,KAAKI,IAAKJ,EAAE;CACrC,OAAO;EACL,IAAI,KAAK,IAAIC,GAAII,CAAE;EAAG,IAAI,KAAK,IAAIH,GAAII,CAAE;EACzC,IAAI,KAAK,IAAIL,GAAII,CAAE;EAAG,IAAI,KAAK,IAAIH,GAAII,CAAE;CAC3C;AACF;AAEA,SAAgBC,EAAmB,GAAa,GAAuB;CACrE,OAAO;EACL,IAAI,KAAK,IAAIC,EAAE,IAAIC,EA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