@weasel-js/renderer 0.0.0-stage → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1062 @@
1
+ import { S as ShaderProgramHandle, a as ShaderUniform, b as ShaderProgram, F as FillPoseBox } from './paintKinds-BmPAT51k.js';
2
+ export { P as PaintBindContext, c as PaintDrawKind, d as PaintDrawKindLoader, e as PaintProgram, f as PaintResources, g as ProgramSource, h as ShaderCompileError, i as ShaderStage, U as UniformArray, j as fillInPoseFrame, k as fillToBoundsFrame, l as getPaintDrawKind, m as getProgramSource, n as isPaintKindKnown, p as paintDrawKindRegistry, o as programSourceRegistry, r as registerPaintDrawKind, q as registerPaintDrawKindLoader, s as registerProgram, w as warmPaintKinds } from './paintKinds-BmPAT51k.js';
3
+ import { Mesh } from '@weasel-js/geom/tessellate';
4
+ export { Mesh, TessellateOptions, tessellate } from '@weasel-js/geom/tessellate';
5
+ import { GradStop, ColorSpace, CommandFill, CommandStroke, Stroke, Fill, Paint, CommandPaint, TextureHandle } from '@weasel-js/paint';
6
+ export { CommandFill, CommandPaint, CommandPaintUnits, CommandStroke, PosedPaint, SolidPaint, TextureHandle } from '@weasel-js/paint';
7
+ import { GlMat3, Path } from '@weasel-js/geom';
8
+ export { GlMat3, View as ViewLike, mat3, viewToMat3 } from '@weasel-js/geom';
9
+ import { ResolvedRun, TextAlign, TextDirection, TextStyle, TextVerticalAlign, TextPaint, TextPose, StyledRun } from '@weasel-js/text';
10
+ import { D as DrawBatch } from './imageCache-DYcWftY8.js';
11
+ export { I as ImageNodeData, a as ImageRasterSize, b as ImageStatus, T as TextureEntry, g as getImageBitmap, i as imageStatus, c as isVectorImageSrc, r as registerTexture, d as releaseImage, e as resolveFillPattern, f as resolvePatternSpec, h as retryImage, s as setImageCacheBudget, j as subscribeImageReady, t as textureRegistry, u as unregisterTexture } from './imageCache-DYcWftY8.js';
12
+ export { StrokeOptions, tessellateStroke } from '@weasel-js/stroke';
13
+ export { RegisterFontOptions, canQueryLocalFonts, cssFontFamily, cssFontFamilyLoading, enableLocalFontOutlines, fontOutlineRegistry, fontRegistry, hasFontOutlines, isCanvasFont, listFontOutlines, loadFontOutlines, outlineStatus, registerCanvasFont, registerFont, registerFontOutlines, subscribeGlyphReady, unregisterCanvasFont, unregisterFontOutlines } from '@weasel-js/font';
14
+ import '@weasel-js/registry';
15
+
16
+ interface GLMeshHandle {
17
+ readonly vao: WebGLVertexArrayObject;
18
+ readonly indexCount: number;
19
+ readonly requiresStencil: boolean;
20
+ readonly anchorA?: Uint32Array;
21
+ readonly anchorB?: Uint32Array;
22
+ readonly anchorT?: Float32Array;
23
+ }
24
+ /** Resources to release when a Mesh is reclaimed by GC. */
25
+ interface MeshResources {
26
+ vao: WebGLVertexArrayObject;
27
+ vbo: WebGLBuffer;
28
+ ibo: WebGLBuffer;
29
+ }
30
+ /**
31
+ * Caches GL-side buffers + VAO per `Mesh` identity. Upload happens lazily
32
+ * on first `handleFor(mesh)` call.
33
+ *
34
+ * **GC-aware cleanup (deferred-delete queue):** we register each Mesh with a
35
+ * `FinalizationRegistry`; when the Mesh is reclaimed, the finalizer pushes
36
+ * its GL resources (VAO, VBO, IBO) onto an internal queue. The renderer
37
+ * drains this queue at the start of each `render()` call (via
38
+ * `drainPendingDeletes()`), when GL is in a known state — no VAO bound, no
39
+ * draw mid-flight. Finalizer timing is non-deterministic; resources may live
40
+ * for a frame or two beyond their Mesh.
41
+ *
42
+ * The cache is GL-context-bound; if the context is lost and re-created, the
43
+ * renderer should construct a new GLMeshCache.
44
+ */
45
+ declare class GLMeshCache {
46
+ private readonly gl;
47
+ private readonly map;
48
+ /** Meshes this context has drawn at least once; see `uploadRecurring`. */
49
+ private readonly seen;
50
+ private readonly finalizer;
51
+ /** Every persistent upload not yet freed, so `dispose` can reach them. */
52
+ private readonly persistent;
53
+ private readonly pendingDeletes;
54
+ private disposed;
55
+ /** Transient resources allocated this frame; freed at end of render(). */
56
+ private readonly transientThisFrame;
57
+ constructor(gl: WebGL2RenderingContext);
58
+ handleFor(mesh: Mesh): GLMeshHandle;
59
+ /**
60
+ * Upload a Mesh that the caller knows is single-use. Returns a handle backed
61
+ * by fresh GL resources that the renderer frees at the end of the current
62
+ * frame via `freeTransient()`, so transient meshes never wait on GC.
63
+ */
64
+ uploadTransient(mesh: Mesh): GLMeshHandle;
65
+ /**
66
+ * Upload a Mesh that may or may not recur across frames. Its first sight in
67
+ * *this* context takes `uploadTransient`; every later one takes the
68
+ * persistent handle. One transient upload to find out is cheaper than
69
+ * stranding a persistent VAO on a mesh that never returns, whose release
70
+ * would wait on GC. The transient upload does not populate the persistent
71
+ * map, so steady-state reuse begins on the third frame.
72
+ */
73
+ uploadRecurring(mesh: Mesh): GLMeshHandle;
74
+ /**
75
+ * Free all transient resources allocated since the last call. Called by
76
+ * the renderer at the end of each `render()`. Safe under context loss.
77
+ */
78
+ freeTransient(): void;
79
+ /** @internal — for tests asserting the transient-list size. */
80
+ _transientCount(): number;
81
+ /**
82
+ * Free GL resources whose Mesh has been GC'd since the last drain.
83
+ * Called by the renderer at the top of each `render()`, before any draws.
84
+ */
85
+ drainPendingDeletes(): void;
86
+ /**
87
+ * Free every GL resource this cache holds — persistent, pending and
88
+ * transient — and ignore finalizers from here on. Idempotent. Unlike the
89
+ * other paths this does not wait on GC, which is what lets a renderer on a
90
+ * context it does not own give back everything it uploaded.
91
+ */
92
+ dispose(): void;
93
+ /** @internal — for tests asserting the queue size. */
94
+ _pendingDeleteCount(): number;
95
+ /** @internal — for tests that need to simulate the finalizer firing. */
96
+ _enqueueDeleteForTest(resources: MeshResources): void;
97
+ private upload;
98
+ }
99
+
100
+ /** A texture source the browser decodes. */
101
+ type ImageTexSource = ImageBitmap | ImageData | HTMLCanvasElement | HTMLImageElement;
102
+
103
+ /**
104
+ * GL texture upload + cache, keyed by a string id (the font family name or
105
+ * image id). The cache is GL-context-bound; discard and create a new one on
106
+ * context loss.
107
+ *
108
+ * Atlas format: RGBA UNSIGNED_BYTE, linear filtering, no mipmaps: mipmap
109
+ * resampling corrupts the multi-channel SDF signal.
110
+ */
111
+
112
+ type TexSource$1 = ImageTexSource;
113
+ /** How a texture samples outside `0..1`. Pattern tiles need `'repeat'`;
114
+ * everything else clamps. WebGL2 allows `REPEAT` on NPOT textures, so a
115
+ * tile of any size tiles correctly. */
116
+ type TextureWrap = 'clamp' | 'repeat';
117
+ /** The part of the texture registry a sweep reads. */
118
+ interface RegisteredTextureIds {
119
+ getVersion(): number;
120
+ has(id: string): boolean;
121
+ }
122
+ declare class GLTextureCache {
123
+ private readonly gl;
124
+ private readonly map;
125
+ private readonly wraps;
126
+ /** The source each registry-backed id was last uploaded from. */
127
+ private readonly registered;
128
+ private sweptVersion;
129
+ constructor(gl: WebGL2RenderingContext);
130
+ has(id: string): boolean;
131
+ /** Uploads the pixels once per id. `wrap` is re-applied whenever it differs
132
+ * from what the id was last uploaded under: the same registered image can
133
+ * be a clamped shader texture in one draw and a repeating pattern tile in
134
+ * the next. */
135
+ upload(id: string, source: TexSource$1, wrap?: TextureWrap): string;
136
+ private ensure;
137
+ /** `upload` for an id from the texture registry, whose image can be replaced
138
+ * under the same id: a changed source sends its pixels again. A registered
139
+ * texture is an image, so its texels are premultiplied. */
140
+ uploadRegistered(id: string, source: TexSource$1, wrap?: TextureWrap): string;
141
+ /**
142
+ * Delete the texture of every registry-backed id the registry has dropped.
143
+ * The renderer calls this at the top of `render()`, before any draw, so a
144
+ * texture is never deleted under a draw that has it bound.
145
+ */
146
+ sweep(registry: RegisteredTextureIds): void;
147
+ private applyWrap;
148
+ /** Create a single-channel R8 texture from raw bytes (full upload).
149
+ * No-op if `id` already exists. Same LINEAR/CLAMP params as `upload`;
150
+ * UNPACK_ALIGNMENT dropped to 1 for non-4-aligned row widths. */
151
+ uploadR8(id: string, width: number, height: number, data: Uint8Array): void;
152
+ /** Patch a rect of an existing R8 texture with tightly-packed w×h bytes. */
153
+ subImageR8(id: string, x: number, y: number, w: number, h: number, data: Uint8Array): void;
154
+ /** Create a texture from premultiplied RGBA bytes that are a color: a page
155
+ * of color glyphs. Mipmapped, as a font atlas must never be, because one is
156
+ * drawn well below the size it was baked at. No-op if `id` already exists. */
157
+ uploadRGBA(id: string, width: number, height: number, data: Uint8Array): void;
158
+ /** Patch a rect of an existing RGBA texture with tightly-packed w×h texels. */
159
+ subImageRGBA(id: string, x: number, y: number, w: number, h: number, data: Uint8Array): void;
160
+ bind(id: string, unit: number): void;
161
+ /**
162
+ * Delete every uploaded GL texture and clear the map. The cache is
163
+ * refillable afterward.
164
+ */
165
+ free(): void;
166
+ }
167
+
168
+ /**
169
+ * GL texture upload cache for ImageBitmap objects, keyed by source identity
170
+ * (WeakMap) so GC can reclaim unreferenced bitmaps. A collected source's
171
+ * texture is queued and deleted at the renderer's next frame; GC timing is
172
+ * not prompt, so a source's owner that knows it will never be drawn again
173
+ * frees it at once with {@link releaseImageSource}, and `dispose` frees them
174
+ * all.
175
+ *
176
+ * Wrapping is set once at upload time. Texels are stored premultiplied,
177
+ * whatever the source: see `uploadPremultiplied`.
178
+ */
179
+
180
+ type PatternRepetition = 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat';
181
+ /**
182
+ * MIN_FILTER strategy for uploaded textures: `'linear'` never mipmaps,
183
+ * `'mipmap'` does at upload, and `'auto'` uploads linear and builds a
184
+ * texture's mipmaps the first time a frame draws it at half size or smaller.
185
+ */
186
+ type ImageMinification = 'linear' | 'mipmap' | 'auto';
187
+ type TexSource = ImageTexSource;
188
+ /** Free `key`'s texture in every live renderer. For an owner that has replaced
189
+ * a source and will never draw the old one again — a later draw of it simply
190
+ * re-uploads. */
191
+ declare function releaseImageSource(key: object): void;
192
+ declare class GLImageCache {
193
+ private readonly gl;
194
+ private readonly minification;
195
+ /** This context's `MAX_TEXTURE_SIZE`. */
196
+ readonly maxTextureSide: number;
197
+ private readonly map;
198
+ /** Every texture `map` holds, so `dispose` can reach them — a WeakMap
199
+ * cannot be enumerated. */
200
+ private readonly textures;
201
+ /**
202
+ * MAG_FILTER each texture currently carries, so a redundant write can be
203
+ * skipped. The batch sets this per flush — the same bitmap can be drawn at
204
+ * both filters in one frame — but filtering is state on the *texture
205
+ * object*, not on the unit, so re-asserting a value it already has is a
206
+ * write to a live texture for no reason.
207
+ */
208
+ private readonly magFilters;
209
+ private readonly finalizer;
210
+ private readonly pendingDeletes;
211
+ /** Under `'auto'`, the sources whose mipmaps are built. */
212
+ private readonly mipped;
213
+ private frame;
214
+ private readonly lastDrawn;
215
+ /** `minification` selects the MIN_FILTER strategy for uploaded textures.
216
+ * `'mipmap'` generates mipmaps and filters LINEAR_MIPMAP_LINEAR: when a
217
+ * large source bitmap is drawn small, bilinear-only minification
218
+ * undersamples and produces moiré. `'auto'` pays for that only on the
219
+ * textures a frame draws small, when it first does. */
220
+ constructor(gl: WebGL2RenderingContext, minification?: ImageMinification);
221
+ /** Open a frame: what {@link drewInLatestFrame} answers about from here on.
222
+ * The renderer calls this at the top of each `render()`. */
223
+ beginFrame(): void;
224
+ /** Whether `key` was uploaded or bound since the last {@link beginFrame}. */
225
+ drewInLatestFrame(key: object): boolean;
226
+ /** Delete the textures of sources collected since the last call. */
227
+ drainPendingDeletes(): void;
228
+ /** Delete `key`'s texture, if it has one. */
229
+ release(key: object): void;
230
+ /** Delete every texture this cache uploaded and stop answering
231
+ * {@link releaseImageSource} and {@link maxImageTextureSide}. Idempotent. */
232
+ dispose(): void;
233
+ /** {@link dispose} without the deletes, for a cache whose context was lost:
234
+ * its textures died with it. */
235
+ abandon(): void;
236
+ upload(key: object, source: TexSource, repetition?: PatternRepetition): WebGLTexture;
237
+ /** Whether `key` would gain from {@link buildMipmaps}: only under `'auto'`,
238
+ * and only until they are built. */
239
+ lacksMipmaps(key: object): boolean;
240
+ /** Build `key`'s mipmaps and filter minification through them from here
241
+ * on. Its texture must be uploaded. Leaves no texture bound. */
242
+ buildMipmaps(key: object): void;
243
+ bind(key: object, unit: number): void;
244
+ /** Set `key`'s MAG_FILTER, skipping the call when it already holds that
245
+ * value. Its texture must be bound to the active unit — callers pair this
246
+ * with `bind`. */
247
+ setMagFilter(key: object, filter: number): void;
248
+ }
249
+
250
+ /**
251
+ * CPU gradient-ramp builder + the GL texture every baked ramp lives in.
252
+ *
253
+ * Each unique stop list is baked once into a 256-texel strip and written to its
254
+ * own **row** of one RGBA texture, keyed by `JSON.stringify(stops)`. One
255
+ * texture rather than one per ramp is what lets a gradient take a batch texture
256
+ * slot the way a bitmap or a font atlas does: every gradient in a frame samples
257
+ * the same unit, so a run does not break per gradient. The atlas is
258
+ * GL-context-bound; discard and recreate on context loss.
259
+ *
260
+ * Texels are stored as straight RGBA. The fragment shader applies
261
+ * premultiplication before writing outColor.
262
+ */
263
+
264
+ /** Bake gradient stops into a 256-entry RGBA lookup strip, which the shader
265
+ * samples instead of evaluating stops per fragment. `space` is the gradient's
266
+ * `interpolate` — the ramp is where a non-sRGB blend is paid for, once. */
267
+ declare function buildGradientRamp(stops: GradStop[], space?: ColorSpace): Uint8ClampedArray;
268
+ declare class GradientRampAtlas {
269
+ private readonly gl;
270
+ /** Row per stop list, in least-recently-used order: a hit re-inserts, so the
271
+ * first entry is the row a full atlas recycles. */
272
+ private readonly rowByKey;
273
+ private texture;
274
+ private rows;
275
+ /** Mirror of the texture, so growth can respecify it without re-baking every
276
+ * ramp it already holds. */
277
+ private pixels;
278
+ private totalQueries;
279
+ private cacheHits;
280
+ constructor(gl: WebGL2RenderingContext);
281
+ /** Rows the atlas currently holds — its texture height. */
282
+ get height(): number;
283
+ /**
284
+ * Bake `stops` into a row and return it, reusing the row an identical stop
285
+ * list already holds.
286
+ *
287
+ * **A returned row outlives the frame only while the atlas has room.** Past
288
+ * `RAMP_ATLAS_MAX_ROWS` an upload recycles the least recently used row, which
289
+ * rewrites texels a row handed out earlier still names. Nothing that defers
290
+ * its draw past this call may hold a row across another `upload` without
291
+ * arranging to be flushed first.
292
+ */
293
+ upload(stops: GradStop[], space?: ColorSpace): number;
294
+ /**
295
+ * Whether uploading `stops` would move where existing rows sit — by growing
296
+ * the atlas, which changes every row's `v`, or by recycling one, which
297
+ * rewrites its texels.
298
+ *
299
+ * Anything holding a row past this call asks first and gets itself out of
300
+ * the way, because neither can be undone once it has happened.
301
+ */
302
+ wouldReshape(stops: GradStop[], space?: ColorSpace): boolean;
303
+ /**
304
+ * The `v` a row is sampled at — its center.
305
+ *
306
+ * The center is load-bearing: the atlas filters LINEAR, so a `v` anywhere
307
+ * else blends the ramp beside it into this one. At the center the neighbor's
308
+ * weight is exactly zero.
309
+ */
310
+ rowV(row: number): number;
311
+ bind(unit: number): void;
312
+ hitRate(): number;
313
+ resetStats(): void;
314
+ /**
315
+ * Delete the atlas texture and forget every row in it. The CPU mirror goes
316
+ * with it, so the atlas is refillable afterward. Stats are left as-is.
317
+ */
318
+ free(): void;
319
+ /** The row the next ramp is written to: a free one, a taller atlas, or the
320
+ * least recently used row of a full one. */
321
+ private claimRow;
322
+ /** Grow to `rows`, keeping every row at the index it already had — a row
323
+ * index is a stable name, and callers hold them. */
324
+ private resize;
325
+ private writeRow;
326
+ }
327
+
328
+ /** Row-major 4×5 color matrix identity. */
329
+ declare const IDENTITY_COLOR_MATRIX: Float32Array<ArrayBuffer>;
330
+ interface GroupFrame {
331
+ transform?: GlMat3;
332
+ alpha?: number;
333
+ /** Row-major 4×5 color matrix (20 floats). Absent leaves the stack unchanged. */
334
+ colorMatrix?: Float32Array | number[];
335
+ }
336
+ declare class GroupState {
337
+ private transformStack;
338
+ private alphaStack;
339
+ private colorMatrixStack;
340
+ get transform(): GlMat3;
341
+ get alpha(): number;
342
+ get colorMatrix(): Float32Array;
343
+ push(frame: GroupFrame): void;
344
+ /**
345
+ * Push a frame whose children paint into a surface of their own. The
346
+ * transform still accumulates. Alpha and color do not: applying them on the
347
+ * way in would fade the pixels an effect is about to read, then fade them
348
+ * again on the way out.
349
+ *
350
+ * Returns the pair the caller must apply at composite time — what `push`
351
+ * would have left on the stack.
352
+ */
353
+ pushIsolated(frame: GroupFrame): {
354
+ alpha: number;
355
+ colorMatrix: Float32Array;
356
+ };
357
+ /** Drop every pushed frame, leaving the root. A frame that throws part-way
358
+ * down the tree never pops, and the next frame would draw under leftovers. */
359
+ reset(): void;
360
+ pop(): void;
361
+ }
362
+
363
+ /**
364
+ * One full-screen pass over what a group has already drawn. A group's effects
365
+ * run in order, each reading the previous one's output through `u_source`.
366
+ *
367
+ * `uniforms` are the effect's own; `u_source`, `u_resolution`, and `u_texel`
368
+ * come from the renderer and must not be passed here.
369
+ */
370
+ interface Effect {
371
+ program: ShaderProgramHandle;
372
+ uniforms?: Record<string, ShaderUniform>;
373
+ }
374
+ /**
375
+ * Register a fragment shader as an effect. An effect registered through
376
+ * `registerProgram` with the *custom-shader* vertex shader compiles, runs, and
377
+ * samples its source upside down.
378
+ *
379
+ * The fragment shader reads `v_uv` and `u_source`, may declare `u_resolution` /
380
+ * `u_texel`, and must write premultiplied alpha. See `effectPrelude.ts`.
381
+ *
382
+ * @experimental
383
+ */
384
+ declare function registerEffect(id: string, frag: string): ShaderProgramHandle;
385
+
386
+ /**
387
+ * How an isolated group's finished surface joins what is already drawn.
388
+ *
389
+ * Every color the renderer writes is premultiplied, so each Porter-Duff
390
+ * operator is `source * Fa + destination * Fb` with both factors read off one
391
+ * alpha or the other, which is a blend function and needs no second pass.
392
+ */
393
+ /** A Porter-Duff operator, named as canvas 2D's `globalCompositeOperation` names it. */
394
+ type CompositeOp = 'source-over' | 'source-in' | 'source-out' | 'source-atop' | 'destination-over' | 'destination-in' | 'destination-out' | 'destination-atop' | 'xor' | 'lighter' | 'copy';
395
+ /** What one side of the blend is scaled by. */
396
+ type BlendFactor = 'zero' | 'one' | 'source-alpha' | 'one-minus-source-alpha' | 'destination-alpha' | 'one-minus-destination-alpha';
397
+ /** An operator with no name: `source * source + destination * destination`, on premultiplied color. */
398
+ interface BlendFactors {
399
+ source: BlendFactor;
400
+ destination: BlendFactor;
401
+ }
402
+
403
+ /** DrawCommand variants implemented through step 6. */
404
+ type DrawCommand = PathDrawCommand | GroupDrawCommand | TextDrawCommand | ImageDrawCommand | SpritesDrawCommand | ShaderDrawCommand;
405
+ /** Draw a path, filled and/or stroked. The workhorse command: every shape the
406
+ * kit draws that is not text, an image, or a custom shader is one of these. */
407
+ interface PathDrawCommand {
408
+ kind: 'path';
409
+ path: Path;
410
+ /** Solid, pattern, or gradient (linear/radial/conic), resolved for the
411
+ * renderer: `commandPaint` makes one from a node's `Paint`. */
412
+ fill?: CommandFill;
413
+ /** Stroke spec. Its `paint` takes what `fill` does. */
414
+ stroke?: CommandStroke;
415
+ /**
416
+ * Optional flat RGBA-per-path-anchor color array (length =
417
+ * `4 × countPathAnchors(path)`, floats in 0..1), arc-length-interpolated
418
+ * across the mesh between consecutive anchors.
419
+ *
420
+ * **`fill` must also be set when using `vertexColors`.** The renderer
421
+ * only enters the per-vertex shader path when the command has a fill
422
+ * (the fill provides the opacity uniform). Pass any solid `fill` (e.g.
423
+ * `{ paint: { color: '#fff' } }`) as the placeholder; the per-vertex colors
424
+ * win in the shader.
425
+ */
426
+ vertexColors?: number[];
427
+ }
428
+ /** Draw a list of commands under a shared transform, opacity, color matrix
429
+ * and clip. Groups nest, and their effects accumulate down the stack — this
430
+ * is how a container node's transform reaches its descendants. */
431
+ interface GroupDrawCommand {
432
+ kind: 'group';
433
+ transform?: GlMat3;
434
+ alpha?: number;
435
+ /**
436
+ * Optional 4×5 color matrix (row-major, 20 numbers) — `out = M₄ₓ₄ * in + bias`.
437
+ * Accumulated multiplicatively down the group stack. Defaults to identity.
438
+ */
439
+ colorMatrix?: number[];
440
+ /** Optional clip path. When set, the renderer rasterizes this path into
441
+ * the stencil buffer before drawing `children`; the children paint only
442
+ * where the clip covers. Nested groups with clips intersect — a child
443
+ * cannot escape an ancestor's clip. Max 7 nesting levels; the renderer
444
+ * throws if exceeded. */
445
+ clip?: Path;
446
+ /**
447
+ * Full-screen passes run over this group's own pixels, in order, before it
448
+ * is composited into its parent.
449
+ *
450
+ * Unlike every other field here, this does not accumulate down the group
451
+ * stack — it is a render-target boundary. The children draw into a buffer of
452
+ * their own, each effect reads the previous one's output, and the result is
453
+ * composited back under this group's `transform`, `alpha`, `colorMatrix` and
454
+ * whatever clip encloses it. So a blur here blurs this group and nothing
455
+ * around it, which is what a CSS `filter` on the canvas cannot do.
456
+ *
457
+ * An empty or absent list costs nothing: no buffer is allocated until a
458
+ * group asks for one.
459
+ */
460
+ effects?: readonly Effect[];
461
+ /**
462
+ * Draw the children into a buffer of their own and composite it once, the
463
+ * render-target boundary `effects` makes, with no pass run over it. `alpha`
464
+ * and `colorMatrix` then apply to the finished surface, so overlapping
465
+ * children do not show through each other as they do when each is faded on
466
+ * its own. Costs a device-resolution buffer and a full-screen composite.
467
+ */
468
+ isolate?: boolean;
469
+ /**
470
+ * How the group's finished surface joins what is already drawn. Default
471
+ * `source-over`. Any other operator isolates the group, and its composite
472
+ * covers the whole target inside the enclosing clip, so an operator that
473
+ * scales the destination by the source's alpha (`source-in`,
474
+ * `destination-in`, `destination-atop`, `copy`) also clears everything the
475
+ * group left empty. Operators reading the destination's alpha need a target
476
+ * that has one: a context created with `alpha: false` reads as opaque.
477
+ */
478
+ composite?: CompositeOp | BlendFactors;
479
+ children: DrawCommand[];
480
+ }
481
+ /**
482
+ * Text draw command. Renders one or more runs at (`x`, `y`) in screen
483
+ * space, optionally word-wrapping at `maxWidth`. `style` carries node-level
484
+ * defaults (`lineHeight`, anti-alias width) that don't belong on individual
485
+ * runs.
486
+ */
487
+ interface TextDrawCommand {
488
+ kind: 'text';
489
+ x: number;
490
+ y: number;
491
+ runs: ResolvedRun[];
492
+ /** Wrap width. Absent never wraps. */
493
+ maxWidth?: number;
494
+ align?: TextAlign;
495
+ /** What `start` / `end` resolve against, and the base direction of bidi
496
+ * reordering — see `LayoutRunsOpts.direction`. Default `style`'s. */
497
+ direction?: TextDirection | 'auto';
498
+ /** Spread each wrapped line across `width` — see `LayoutRunsOpts.justify`.
499
+ * `align` then sets only the lines it does not spread. Default `false`. */
500
+ justify?: boolean;
501
+ /** Box width `align` resolves within, from `x`. Default `maxWidth`; with
502
+ * neither, `x` is the line's left edge, midpoint or right edge. */
503
+ width?: number;
504
+ style: TextStyle;
505
+ /** Box height for vertical alignment. When set with `verticalAlign`,
506
+ * the laid-out block shifts within `[y, y+height]`. */
507
+ height?: number;
508
+ /** Default 'top' — the legacy top-anchored behavior. */
509
+ verticalAlign?: TextVerticalAlign;
510
+ }
511
+ /**
512
+ * Image draw command — renders `image` at screen-space rect (x, y, w, h).
513
+ * The image is stretched to fit; no tiling. Use a pattern Paint on a path
514
+ * for tiling.
515
+ */
516
+ interface ImageDrawCommand {
517
+ kind: 'image';
518
+ /** A bitmap holding premultiplied pixels, which is what `createImageBitmap`
519
+ * makes unless told otherwise. One made with `premultiplyAlpha: 'none'`
520
+ * draws too bright wherever it is translucent: a browser uploads a bitmap
521
+ * as it stands, and nothing reports which kind it is. */
522
+ image: ImageBitmap;
523
+ x: number;
524
+ y: number;
525
+ w: number;
526
+ h: number;
527
+ opacity?: number;
528
+ /** Magnification filter. `'linear'` (default) smooths; `'nearest'` shows
529
+ * device pixels as hard squares — required by anything magnifying a
530
+ * framebuffer readback, where blur destroys the point of the readback. */
531
+ sampling?: 'linear' | 'nearest';
532
+ /** Sub-rectangle of `image` to draw, in bitmap pixels from the top-left.
533
+ * Omitted draws the whole bitmap. Not range-checked: a rect past the edge
534
+ * samples outside [0..1], which CLAMP_TO_EDGE smears. With
535
+ * `sampling: 'linear'` the filter reaches half a texel beyond `source`, so
536
+ * atlas frames need a gutter (see `SpriteSheet.spacing`) or `'nearest'`. */
537
+ source?: {
538
+ x: number;
539
+ y: number;
540
+ w: number;
541
+ h: number;
542
+ };
543
+ /** Mirror the sampled region within the destination rect. The quad does not
544
+ * move — a flipped draw covers exactly the pixels an unflipped one does. */
545
+ flipX?: boolean;
546
+ flipY?: boolean;
547
+ }
548
+ /** Floats per sprite in `SpritesDrawCommand.sprites`. */
549
+ declare const SPRITE_STRIDE = 9;
550
+ /**
551
+ * Draw many quads sampling one bitmap — an atlas, a sprite sheet, a wall of
552
+ * thumbnails. The same picture as a run of `ImageDrawCommand`s the renderer
553
+ * would coalesce anyway, handed over already packed so it never walks a
554
+ * command object per quad. Reach for it past a few thousand sprites: at
555
+ * 20,000 the object walk is about half the frame.
556
+ *
557
+ * The sprites are one run: they share a texture, a filter, and whatever group
558
+ * transform, alpha, color matrix and clip are live. Anything varying per
559
+ * sprite is in the array.
560
+ */
561
+ interface SpritesDrawCommand {
562
+ kind: 'sprites';
563
+ image: ImageBitmap;
564
+ /** Magnification filter for the whole run, as `ImageDrawCommand.sampling`. */
565
+ sampling?: 'linear' | 'nearest';
566
+ /**
567
+ * `SPRITE_STRIDE` floats per sprite:
568
+ * `dx, dy, dw, dh, sx, sy, sw, sh, opacity`.
569
+ *
570
+ * Destination is in the group's coordinates; source is in bitmap pixels,
571
+ * like `ImageDrawCommand.source`. A negative `sw` or `sh` mirrors that axis
572
+ * within the source rect, which is what `flipX` / `flipY` do. A trailing
573
+ * partial sprite is ignored.
574
+ */
575
+ sprites: Float32Array;
576
+ }
577
+ /**
578
+ * Custom shader draw command. The renderer generates a quad over `bounds`
579
+ * and dispatches the consumer's fragment shader with the kit's vertex prelude.
580
+ *
581
+ * `uniforms` keys must match names declared in the consumer's fragment shader.
582
+ * The kit automatically sets `u_bounds`, `u_view`, and `u_proj` — do not
583
+ * declare those in `uniforms`.
584
+ *
585
+ * `program` is the handle the module-level `registerProgram()` returned. Each
586
+ * renderer compiles it the first time it draws one, so a layer emits this
587
+ * command with nothing set up on the canvas or the renderer beforehand.
588
+ */
589
+ interface ShaderDrawCommand {
590
+ kind: 'shader';
591
+ program: ShaderProgramHandle;
592
+ uniforms: Record<string, ShaderUniform>;
593
+ /** Screen-space bounding rect in CSS pixels. */
594
+ bounds: {
595
+ x: number;
596
+ y: number;
597
+ w: number;
598
+ h: number;
599
+ };
600
+ }
601
+
602
+ /** A run of top-level commands, `[start, end)` by index, that
603
+ * {@link WeaselRenderer.lastFrameStats} accounts for separately — one render
604
+ * layer's commands, say. Spans are in order and do not overlap. */
605
+ interface RenderSpan {
606
+ id: string;
607
+ start: number;
608
+ end: number;
609
+ }
610
+ /** Per-frame options for {@link WeaselRenderer.render}. */
611
+ interface RenderOptions {
612
+ spans?: readonly RenderSpan[];
613
+ }
614
+ /** What one span cost. A batched run is drawn when something closes it, so
615
+ * its draw call counts toward the span that closed it. */
616
+ interface RenderSpanStats {
617
+ id: string;
618
+ drawCalls: number;
619
+ ms: number;
620
+ }
621
+ /** What one `render()` cost. See {@link WeaselRenderer.lastFrameStats}. */
622
+ interface RenderStats {
623
+ drawCalls: number;
624
+ ms: number;
625
+ spans: RenderSpanStats[];
626
+ }
627
+ /** Construction options for {@link WeaselRenderer}. Pass `gl` or `canvas`;
628
+ * a context passed in must have a stencil buffer. */
629
+ interface WeaselRendererOptions {
630
+ /** A WebGL2 context to draw with. Wins over `canvas`. */
631
+ gl?: WebGL2RenderingContext;
632
+ /** A canvas to open a stencil-backed WebGL2 context on, when `gl` is absent.
633
+ * The renderer sets its drawing buffer and never its CSS size. */
634
+ canvas?: HTMLCanvasElement;
635
+ /** Drawing size in CSS pixels. */
636
+ width: number;
637
+ /** Drawing size in CSS pixels. */
638
+ height: number;
639
+ /** Device pixels per CSS pixel. */
640
+ dpr: number;
641
+ /** MIN_FILTER strategy for image textures (`GLImageCache`). Default
642
+ * `'linear'`. `'mipmap'` builds mipmaps for every image at upload, as
643
+ * the headless `renderSceneToPixels` path does; `'auto'` builds them
644
+ * for an image the first time a frame draws it at half size or smaller. */
645
+ imageMinification?: ImageMinification;
646
+ /** Flatness tolerance for curve tessellation, in WORLD units (see
647
+ * `TessellateOptions.flattenTolerance`). When set, path fills are
648
+ * tessellated fresh at this tolerance per frame (transient pool) instead
649
+ * of served from the Path-identity mesh cache — the cache key does not
650
+ * include tolerance. Default: unset — the existing cached behavior at
651
+ * `DEFAULT_FLATTEN_TOLERANCE`. The headless path derives this from the
652
+ * requested output scale; screen callers normally leave it unset. */
653
+ flattenTolerance?: number;
654
+ /** Per-render synchronous bake budget for dynamic canvas-SDF glyphs.
655
+ * Default DEFAULT_BAKE_BUDGET (16). The headless renderSceneToPixels
656
+ * path passes Infinity so print never defers a glyph. */
657
+ bakeBudget?: number;
658
+ /** On-screen glyph size, in CSS pixels, at or above which text renders from
659
+ * tessellated font outlines instead of a distance field — see
660
+ * `OUTLINE_MIN_SCREEN_PX`. Only faces registered with
661
+ * `registerFontOutlines` are affected; everything else keeps its SDF tier
662
+ * whatever this says. Pass `Infinity` to disable the tier outright, or 0
663
+ * to use outlines wherever they exist (what the headless path does, since
664
+ * print has no reason to sample a field it could evaluate exactly). */
665
+ textOutlineMinScreenSize?: number;
666
+ }
667
+ /** Where a renderer draws inside a buffer it does not own.
668
+ *
669
+ * The rect's SIZE is the renderer's own `width`/`height` — `resize()` owns
670
+ * that, and a second copy here could disagree with the one `DrawContext`
671
+ * reports to screen-space layers. */
672
+ interface RenderTarget {
673
+ /** Top-left of this renderer's output within the drawing buffer, in CSS
674
+ * pixels, with the origin at the buffer's top-left. GL's bottom-left origin
675
+ * is handled internally. */
676
+ origin: {
677
+ x: number;
678
+ y: number;
679
+ };
680
+ /** Clear colour and stencil within the rect before drawing. Default true.
681
+ * Pass false only when the caller clears the whole buffer itself on behalf
682
+ * of every co-tenant — a frame that clears neither inherits its neighbour's
683
+ * stencil bits, and even-odd fills then fill their holes. */
684
+ clear?: boolean;
685
+ }
686
+ /**
687
+ * The WebGL2 renderer: takes a list of draw commands and paints them.
688
+ *
689
+ * It knows nothing about the scene — commands are the whole interface, which
690
+ * is what lets layers, HUD widgets and overlays all draw through the same
691
+ * pipeline. GPU resources (meshes, textures, gradient ramps) are cached across
692
+ * frames and keyed by identity, so re-issuing the same command is cheap.
693
+ */
694
+ declare class WeaselRenderer {
695
+ private readonly gl;
696
+ private stats;
697
+ private pathFill;
698
+ private pathFillVColor;
699
+ private batchFill;
700
+ private gradFill;
701
+ private patternFill;
702
+ /** Compiled on first use: only atlas text under a texture paint needs one. */
703
+ private glyphPaintPrograms;
704
+ private meshCache;
705
+ private textureCache;
706
+ private imageCache;
707
+ private gradRamps;
708
+ private programRegistry;
709
+ /** The source each compiled custom program was built from — or, after a
710
+ * failed recompile, the source that failed, so it is not retried every frame. */
711
+ private programSources;
712
+ private quadVbo;
713
+ private quadIbo;
714
+ private drawBatch;
715
+ /** 1x1 white, so a batch flush sampling no image still samples something —
716
+ * see `shaders/batchFill.ts`. */
717
+ private whiteTexture;
718
+ private readonly groupState;
719
+ private widthCss;
720
+ private heightCss;
721
+ private dpr;
722
+ private canvas;
723
+ /** Where context loss is announced: the context's own canvas, which the
724
+ * renderer need not own the size of. */
725
+ private lossTarget;
726
+ private target;
727
+ /** Offscreen buffers for group effects. Allocates nothing until a group
728
+ * with effects asks, so a canvas without them pays no memory. */
729
+ private readonly effectTargets;
730
+ private readonly paintScratch;
731
+ private readonly imageMinification;
732
+ private flattenTolerance?;
733
+ private readonly bakeBudget;
734
+ private readonly textOutlineMinScreenSize;
735
+ private contextLost;
736
+ private boundOnLost;
737
+ private boundOnRestored;
738
+ /** True after `dispose()`. A disposed renderer ignores further `render()`
739
+ * calls and `registerProgram()` calls. */
740
+ private disposed;
741
+ /** What registered paint kinds hang their GPU state on. One per context
742
+ * generation: a restore releases it and opens the next. */
743
+ private paintResources;
744
+ constructor(opts: WeaselRendererOptions);
745
+ private uploadQuadGeometry;
746
+ /**
747
+ * Compile a consumer-registered shader program against this renderer's GL context.
748
+ *
749
+ * Optional: a program compiles on the first frame that draws with it. Call
750
+ * this after the module-level `registerProgram()` to pay for the compile
751
+ * before that frame, or to catch the `ShaderCompileError` it throws.
752
+ *
753
+ * In dev mode, calling again with the same handle replaces the compiled program.
754
+ */
755
+ registerProgram(handle: ShaderProgramHandle): void;
756
+ private installProgram;
757
+ /** Recompile every program whose module-level source was re-registered
758
+ * since it was compiled. A source that fails keeps the old program drawing. */
759
+ private refreshPrograms;
760
+ /**
761
+ * The compiled program for `id`, compiling it against this context on first
762
+ * use. Unlike {@link registerProgram} this neither throws on a missing
763
+ * source nor on a compile failure: a paint kind asking for a program it
764
+ * never registered must decline the paint, not take down the frame.
765
+ */
766
+ private ensureProgram;
767
+ private glyphPaintProgram;
768
+ /** The blend, depth, cull, clear-color, color-mask, VAO, and unpack-flip
769
+ * state every frame assumes.
770
+ * Applied per `render()` rather than once at construction because a
771
+ * co-tenant sharing this context moves all of it between our frames. */
772
+ private applyGlState;
773
+ /** This renderer's rect in device pixels, top-left origin. A tile rounds its
774
+ * edges rather than its size, so two that share a CSS edge share a device one. */
775
+ private deviceRect;
776
+ /** Viewport and scissor for this frame. Re-applied inside `render()` because
777
+ * a co-tenant on the same context moves both between our frames. */
778
+ private applyTarget;
779
+ /** Confine this renderer to a rect of its drawing buffer, or pass null to
780
+ * give it the whole buffer back. Takes effect from the next `render()`. */
781
+ setTarget(target: RenderTarget | null): void;
782
+ getTarget(): RenderTarget | null;
783
+ isContextLost(): boolean;
784
+ private onContextLost;
785
+ private onContextRestored;
786
+ /** Free every GL resource this renderer created and detach its
787
+ * context-loss listeners. Idempotent. The context itself is left alone, so
788
+ * a caller-owned context can host renderer after renderer without
789
+ * accumulating anything.
790
+ *
791
+ * A disposed renderer ignores further `render()` and `registerProgram()`
792
+ * calls. */
793
+ dispose(): void;
794
+ /**
795
+ * Draw one frame.
796
+ *
797
+ * `viewMatrix` is the frame's world→screen transform. It is only consulted
798
+ * by `units: 'world'` gradients, which fall back to screen space without
799
+ * it — every other command carries its own transform in the stream, so
800
+ * callers with no view concept can keep calling `render(commands)`.
801
+ */
802
+ render(commands: DrawCommand[], viewMatrix?: GlMat3, opts?: RenderOptions): void;
803
+ /** What the last `render()` cost: GL draw calls issued and CPU milliseconds
804
+ * spent issuing them, in total and per requested span. GPU time is not
805
+ * measured; the GPU runs asynchronously. */
806
+ lastFrameStats(): RenderStats;
807
+ /** Change the curve-flattening tolerance after construction. `undefined`
808
+ * restores the cached `DEFAULT_FLATTEN_TOLERANCE` route. */
809
+ setFlattenTolerance(tolerance: number | undefined): void;
810
+ resize(dims: {
811
+ width: number;
812
+ height: number;
813
+ dpr: number;
814
+ }): void;
815
+ /** @internal */ _gl(): WebGL2RenderingContext;
816
+ /** @internal */ _pathFill(): ShaderProgram;
817
+ /** @internal */ _pathFillVColor(): ShaderProgram;
818
+ /** @internal */ _drawBatch(): DrawBatch;
819
+ /** @internal */ _batchFill(): ShaderProgram;
820
+ /** @internal */ _gradFill(): ShaderProgram;
821
+ /** @internal */ _patternFill(): ShaderProgram;
822
+ /** @internal */ _meshCache(): GLMeshCache;
823
+ /** @internal */ _textureCache(): GLTextureCache;
824
+ /** @internal */ _imageCache(): GLImageCache;
825
+ /** @internal */ _gradRamps(): GradientRampAtlas;
826
+ /** @internal */ _groupState(): GroupState;
827
+ /** @internal */ _widthCss(): number;
828
+ /** @internal */ _heightCss(): number;
829
+ /** @internal */ _dpr(): number;
830
+ }
831
+
832
+ /**
833
+ * Uniform-grid sprite sheet layout — frame index to the source rect an
834
+ * `ImageDrawCommand` samples. Pure arithmetic over the grid description; it
835
+ * never touches the bitmap.
836
+ */
837
+ /** A sprite sheet's grid. `margin` and `spacing` follow the Tiled / Aseprite
838
+ * tileset convention, so a sheet exported from either describes itself here. */
839
+ interface SpriteSheet {
840
+ frameWidth: number;
841
+ frameHeight: number;
842
+ columns: number;
843
+ /** Empty pixels around the whole grid. Default 0. */
844
+ margin?: number;
845
+ /** Empty pixels between adjacent cells — the gutter that keeps linear
846
+ * sampling off the neighboring frame. Default 0. */
847
+ spacing?: number;
848
+ }
849
+ /**
850
+ * Row-major source rect for frame `index`, counting from 0 at the top-left.
851
+ *
852
+ * `index` is not range-checked and does not wrap: past the last cell this
853
+ * returns a rect below the sheet, which draws as an edge smear. Wrapping is
854
+ * the animation's business (`frameRect(sheet, tick % count)`) — a sheet does
855
+ * not know how many of its cells are filled.
856
+ */
857
+ declare function frameRect(sheet: SpriteSheet, index: number): {
858
+ x: number;
859
+ y: number;
860
+ w: number;
861
+ h: number;
862
+ };
863
+
864
+ /** A screen-space rectangle, CSS pixels. */
865
+ interface CullRect {
866
+ x: number;
867
+ y: number;
868
+ width: number;
869
+ height: number;
870
+ }
871
+ /**
872
+ * `cmds` without the commands that cannot put a pixel inside `rect`, where
873
+ * `transform` maps the commands' space to screen space — `viewToMat3(view)`
874
+ * for a world-space layer.
875
+ *
876
+ * Conservative by construction: a command is dropped only when a bound that
877
+ * encloses everything it can paint misses `rect`. Paths are bounded by their
878
+ * control hull plus the farthest a stroke can reach (miter spikes and square
879
+ * caps included), images and sprites by their quads, and every bound is taken
880
+ * through the accumulated transform as the AABB of its corners, so rotation
881
+ * only enlarges it. Text and shader commands are always kept, and so is a
882
+ * group with `effects` — an effect may move pixels — or its own `composite`,
883
+ * which changes the destination even where the group drew nothing. Clips are ignored, which
884
+ * can only keep more. A group whose children all go is dropped.
885
+ *
886
+ * Returns `cmds` itself when nothing was dropped.
887
+ */
888
+ declare function cullDrawCommands(cmds: DrawCommand[], transform: GlMat3, rect: CullRect): DrawCommand[];
889
+ /**
890
+ * How far a stroke reaches past its geometry at a known world-to-screen scale — what a painter
891
+ * bounding its own output before it paints can know. `least` is the scale
892
+ * along the axis the transform shrinks most, where it differs from `scale`.
893
+ *
894
+ * A `{ px }` ribbon or head is built to its screen size in every direction,
895
+ * so in world it reaches farthest along that axis. A head with a world size is
896
+ * built in world, whatever the line's width is in.
897
+ */
898
+ declare function strokeReachAt(stroke: Stroke, scale: number, least?: number): number;
899
+ /**
900
+ * True when `bounds`, taken through `transform` to screen space, cannot put a
901
+ * pixel inside `rect` — the per-command test above, for a caller holding a box
902
+ * rather than a command. Same slack, same NaN-keeps rule.
903
+ */
904
+ declare function boundsMissRect(bounds: {
905
+ x: number;
906
+ y: number;
907
+ width: number;
908
+ height: number;
909
+ }, transform: GlMat3, rect: CullRect): boolean;
910
+
911
+ /**
912
+ * On-screen glyph size (CSS px) at or above which a face with registered
913
+ * outlines is drawn as geometry instead of sampled from a distance field.
914
+ *
915
+ * 48 is the dynamic tier's own `BAKE_SIZE`, which makes it the size at which
916
+ * that tier stops being an interpolation and starts being a magnification:
917
+ * `glyphRasterizer.ts` measures coverage error bottoming out *at* the bake
918
+ * size and rising on both sides, and past a few times it the reconstructed
919
+ * field shows the raster as contour wobble. The same number is a safe
920
+ * crossing for the baked MSDF atlas, which is still crisp here — outlines are
921
+ * exact, so switching early costs nothing but the tessellation, and the
922
+ * hinting the atlas has and outlines don't stopped mattering well below this.
923
+ */
924
+ declare const OUTLINE_MIN_SCREEN_PX = 48;
925
+
926
+ /**
927
+ * Effects that ship with the kit.
928
+ *
929
+ * Each is a function returning `Effect[]`, not a single `Effect`, because a
930
+ * separable kernel is genuinely two passes and hiding that behind one entry
931
+ * would make the cost invisible at the callsite:
932
+ *
933
+ * effects={[...blur({ radius: 4 }), ...vignette({ amount: 0.6 })]}
934
+ */
935
+
936
+ /**
937
+ * Gaussian blur, as a horizontal pass followed by a vertical one.
938
+ *
939
+ * `radius` is in device pixels and is the distance of the outermost tap, not a
940
+ * standard deviation — 0 is a copy, and the falloff is the same nine-tap
941
+ * kernel at every radius, so a large one is a wide blur rather than a better
942
+ * one. Two passes at O(9) beat one at O(81) and look the same.
943
+ */
944
+ declare function blur({ radius }: {
945
+ radius: number;
946
+ }): Effect[];
947
+ /**
948
+ * Darken toward the corners. `amount` is how dark the corner gets (0..1) and
949
+ * `feather` how much of the radius the falloff occupies.
950
+ */
951
+ declare function vignette({ amount, feather }: {
952
+ amount: number;
953
+ feather?: number;
954
+ }): Effect[];
955
+
956
+ /**
957
+ * Kit-supplied vertex shader for a full-screen effect pass.
958
+ *
959
+ * Distinct from `CUSTOM_VERT_SRC` on purpose. That one's `v_uv` runs top-down
960
+ * in *screen* space; an effect samples a texture the scene was just rendered
961
+ * into, whose v axis runs the other way.
962
+ *
963
+ * PUBLIC CONTRACT — what every effect fragment shader may read:
964
+ *
965
+ * in vec2 v_uv 0..1 across the source texture
966
+ * uniform sampler2D u_source what has been drawn so far
967
+ * uniform vec2 u_resolution source size in device pixels
968
+ * uniform vec2 u_texel 1.0 / u_resolution — one texel step
969
+ *
970
+ * PREMULTIPLIED ALPHA: `u_source` holds premultiplied RGBA. An effect that
971
+ * weights neighboring samples (a blur) is doing the right thing on
972
+ * premultiplied values; one that manipulates rgb against a must premultiply
973
+ * its own output.
974
+ */
975
+ declare const EFFECT_VERT_SRC = "#version 300 es\nin vec2 a_position;\nin vec2 a_uv;\nout vec2 v_uv;\n\nvoid main() {\n v_uv = a_uv;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";
976
+ /** Uniforms the renderer sets on every effect pass. An effect must not
977
+ * redeclare them with different meanings; it may leave any of them out. */
978
+ declare const EFFECT_KIT_UNIFORMS: readonly ["u_source", "u_resolution", "u_texel"];
979
+
980
+ /**
981
+ * A node's paint, resolved into what a draw command takes. One place composes
982
+ * the two resolutions so every painter and layer applies both.
983
+ */
984
+
985
+ /**
986
+ * `paint` as a draw command's paint: `'bounds'` units mapped onto `box`, and
987
+ * a tile kind swapped for its texture. `null` when a tile cannot rasterize.
988
+ */
989
+ declare function commandPaint(paint: Paint, box: FillPoseBox): CommandPaint | null;
990
+ /**
991
+ * `fill` as a draw command's fill, its paint resolved by {@link commandPaint}.
992
+ * `null` when the fill carries no paint, or its paint cannot be resolved.
993
+ */
994
+ declare function commandFill(fill: Fill, box: FillPoseBox): CommandFill | null;
995
+ /**
996
+ * `stroke` as a draw command's stroke, its paint resolved as
997
+ * {@link commandPaint} resolves one. `null` when the stroke carries no
998
+ * paint, or its paint cannot be resolved.
999
+ */
1000
+ declare function commandStroke(stroke: Stroke, box: FillPoseBox): CommandStroke | null;
1001
+
1002
+ /**
1003
+ * Tile-pattern primitive — a small helper for building repeating texture
1004
+ * tiles from a draw callback. The result plugs into a `Paint` of
1005
+ * `{ kind: 'texture', texture }` (see `@weasel-js/paint`).
1006
+ *
1007
+ * For ready-to-use named patterns (hatch, crosshatch, dots, chunks),
1008
+ * see the `@weasel-js/renderer/patterns-builtin` subpath.
1009
+ */
1010
+
1011
+ /** Options for `createTilePattern`. */
1012
+ interface TilePatternOpts {
1013
+ /** Edge length (in pixels) of the square offscreen tile. */
1014
+ size: number;
1015
+ /** Paint one tile at integer-pixel coordinates `(0, 0) .. (size, size)`. */
1016
+ draw: (oc: CanvasRenderingContext2D, size: number) => void;
1017
+ }
1018
+ /**
1019
+ * Render a single tile and register it as a GL texture, returning a
1020
+ * `TextureHandle` you can wrap in a `Paint` of
1021
+ * `{ kind: 'texture', texture }`. Returns `null` only when an
1022
+ * `OffscreenCanvas`/2D context can't be acquired.
1023
+ */
1024
+ declare function createTilePattern(opts: TilePatternOpts): TextureHandle | null;
1025
+
1026
+ /**
1027
+ * Build a `TextDrawCommand`. `textCommandFromPose` is the command for a text
1028
+ * node; `textCommand` takes a plain string and wraps it in one run;
1029
+ * `textCommandFromRuns` takes the styled runs directly, for text that has no
1030
+ * pose. All three resolve through `resolveTextStyle` + `resolveRuns` — a
1031
+ * caller that assembles the command by hand is one field away from a
1032
+ * silently different result.
1033
+ *
1034
+ * `paint` is the node's `data.fill` / `data.stroke`. A caller with no node —
1035
+ * a HUD widget, a debug overlay — states its color on the run instead.
1036
+ *
1037
+ * `scale` is the view scale a `{ px }` `fontSize` or `letterSpacing` resolves
1038
+ * against — for a world-space layer, the mean of `view.scale.x` and
1039
+ * `view.scale.y`. It has to be applied here and not at draw time, because a
1040
+ * screen-pixel size moves the glyph advances and so the wrap points.
1041
+ */
1042
+
1043
+ /** Build a draw command from styled runs, for text with no pose. `style`
1044
+ * supplies the defaults each run inherits; the rest match `textCommand`. */
1045
+ declare function textCommandFromRuns(x: number, y: number, runs: readonly StyledRun[], style?: TextStyle, maxWidth?: number, height?: number, verticalAlign?: TextVerticalAlign, paint?: TextPaint, width?: number, scale?: number): DrawCommand;
1046
+ /** Build a draw command for a single unstyled string. Text is laid out with
1047
+ * the registered font's metrics, wrapped at `maxWidth`, aligned across
1048
+ * `width` (default `maxWidth`) and within `height` when `verticalAlign` is
1049
+ * given. */
1050
+ declare function textCommand(x: number, y: number, text: string, style?: TextStyle, maxWidth?: number, height?: number, verticalAlign?: TextVerticalAlign, paint?: TextPaint, width?: number, scale?: number): DrawCommand;
1051
+ /**
1052
+ * The draw command for a text pose. Its wrap width, alignment box and runs
1053
+ * come from `textPoseLayoutInput`, so the renderer lays it out into exactly
1054
+ * the lines `layoutTextPose` reports for the same pose.
1055
+ *
1056
+ * Each run's paints are resolved against the pose box the way every other
1057
+ * node's are — a `'bounds'` paint mapped onto it, a pattern spec swapped for
1058
+ * its texture — since the renderer can do neither.
1059
+ */
1060
+ declare function textCommandFromPose(pose: TextPose, scale?: number): TextDrawCommand;
1061
+
1062
+ export { type BlendFactor, type BlendFactors, type CompositeOp, type CullRect, type DrawCommand, EFFECT_KIT_UNIFORMS, EFFECT_VERT_SRC, type Effect, FillPoseBox, type GroupDrawCommand, IDENTITY_COLOR_MATRIX, type ImageDrawCommand, type ImageMinification, OUTLINE_MIN_SCREEN_PX, type PathDrawCommand, type RenderOptions, type RenderSpan, type RenderSpanStats, type RenderStats, type RenderTarget, SPRITE_STRIDE, type ShaderDrawCommand, ShaderProgram, ShaderProgramHandle, ShaderUniform, type SpriteSheet, type SpritesDrawCommand, type TextDrawCommand, type TilePatternOpts, WeaselRenderer, type WeaselRendererOptions, blur, boundsMissRect, buildGradientRamp, commandFill, commandPaint, commandStroke, createTilePattern, cullDrawCommands, frameRect, registerEffect, releaseImageSource, strokeReachAt, textCommand, textCommandFromPose, textCommandFromRuns, vignette };