packages/core/src/lib/textures/texture.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { GLOBAL_STATE } from "../global-state.js";
2 import {
3 requireHookContext,
4 useHookSlot,
5 withHooksForbidden,
6 } from "../hooks/hook-slot.js";
7 import { registerAdvanceParticipant } from "../scheduler/realm-scheduler.js";
8 import { signal } from "../signals/graph.js";
9 import type { PibblInstance, RenderingContext2D } from "../types.js";
10 import {
11 registerTexturePaint,
12 type BorrowedTextureRaster,
13 type TexturePaint,
14 type TexturePlacement,
15 } from "./texture-protocol.js";
16 const placementKeys = [
17 "tileWidth",
18 "tileHeight",
19 "offsetX",
20 "offsetY",
21 "rotation",
22 ] as const;
23
24 export type { TexturePaint, TexturePlacement } from "./texture-protocol.js";
25
26 declare const recipeBrand: unique symbol;
27 /**
28 * A mount-owned texture handle that provides paint and accepts recipe messages.
29 *
30 * @see {@link TexturePaint}
31 * @see {@link TexturePlacement}
32 * @see {@link useTexture}
33 */
34 export interface Texture<Message = never> extends TexturePaint {
35 /**
36 * Delivers a typed message to the mounted recipe instance. See {@link Texture}.
37 * @param message - Message delivered to the texture definition's receive callback.
38 */
39 send(message: Message): void;
40 /**
41 * Returns a paint view with the requested placement while retaining the same texture ownership.
42 * See {@link TexturePaint}.
43 * @param placement - Destination bounds and texture placement policy. See
44 * {@link TexturePlacement} .
45 * @returns A paint descriptor referencing this mounted texture. See {@link TexturePaint}.
46 */
47 paint(placement: TexturePlacement): TexturePaint;
48 }
49 /**
50 * Resolution and runtime configuration for a mounted texture recipe.
51 *
52 * @see {@link useTexture}
53 */
54 export interface TextureOptions {
55 /** Dimensions of the simulation or raster grid. See {@link TextureOptions}. */
56 readonly resolution?: {
57 /**
58 * Horizontal extent in the units of the containing geometry or surface. See
59 * {@link TextureOptions}.
60 */
61 readonly width: number;
62 /**
63 * Vertical extent in the units of the containing geometry or surface. See
64 * {@link TextureOptions}.
65 */
66 readonly height: number;
67 };
68 /** Ordered colors used to present texture intensity. See {@link TextureOptions}. */
69 readonly palette?: readonly string[];
70 }
71 /**
72 * Surface and invalidation facilities supplied to texture lifecycle callbacks.
73 *
74 * @see {@link TextureDefinition}
75 */
76 export interface TextureContext {
77 /** Canvas surface associated with this resource or mount. See {@link TextureContext}. */
78 readonly canvas: OffscreenCanvas;
79 /** Ordered colors used to present texture intensity. See {@link TextureContext}. */
80 readonly palette: readonly string[] | undefined;
81 /** Marks the source pixels dirty and requests a Pibbl update. */
82 invalidate(): void;
83 /** Requests another Pibbl frame; implementations stop by not requesting again. */
84 requestFrame(): void;
85 }
86 /**
87 * Shared logical time and elapsed milliseconds supplied while advancing a texture.
88 *
89 * @see {@link TextureDefinition}
90 */
91 export interface TextureFrame {
92 /** Elapsed time since the preceding texture frame, in milliseconds. See {@link TextureFrame}. */
93 readonly delta: number;
94 /** Current shared logical time, in milliseconds. See {@link TextureFrame}. */
95 readonly time: number;
96 }
97 /**
98 * Lifecycle callbacks for creating, updating, painting, and disposing texture resources.
99 *
100 * @see {@link TexturePlacement}
101 * @see {@link TextureContext}
102 * @see {@link TextureFrame}
103 * @see {@link defineTexture}
104 */
105 export interface TextureDefinition<Config, State, Message = never> {
106 /**
107 * Texture placement used when no paint-specific override is supplied. See
108 * {@link TexturePlacement}.
109 */
110 readonly defaultPlacement?: TexturePlacement;
111 /**
112 * Allocates state for a mounted texture recipe. See {@link TextureDefinition}.
113 * @param context - Texture-owned drawing surface and scheduling services. See
114 * {@link TextureContext} .
115 * @param config - Initial recipe configuration.
116 * @returns State retained for this mounted texture lifetime.
117 */
118 create(context: TextureContext, config: Readonly<Config>): State;
119 /**
120 * Updates existing state when the recipe configuration changes. See {@link TextureDefinition}.
121 * @param state - State returned by create.
122 * @param config - Latest recipe configuration.
123 * @param context - Texture-owned drawing surface and scheduling services. See
124 * {@link TextureContext} .
125 */
126 update?(state: State, config: Readonly<Config>, context: TextureContext): void;
127 /**
128 * Handles a typed application message for this recipe instance. See {@link TextureDefinition}.
129 * @param state - State returned by create.
130 * @param message - Message sent through the mounted texture handle.
131 * @param context - Texture-owned drawing surface and scheduling services. See
132 * {@link TextureContext} .
133 */
134 receive?(state: State, message: Message, context: TextureContext): void;
135 /**
136 * Advances simulation using the shared Pibbl frame timing. See {@link TextureDefinition}.
137 * @param state - State returned by create.
138 * @param frame - Shared animation time and delta. See {@link TextureFrame}.
139 * @param context - Texture-owned drawing surface and scheduling services. See
140 * {@link TextureContext} .
141 */
142 advance?(state: State, frame: TextureFrame, context: TextureContext): void;
143 /**
144 * Draws current texture pixels into the owned offscreen surface. See {@link TextureDefinition}.
145 * @param state - State returned by create.
146 * @param context - Texture-owned drawing surface and scheduling services. See
147 * {@link TextureContext} .
148 */
149 rasterize(state: State, context: TextureContext): void;
150 /**
151 * Releases state and resources when the mounted texture is disposed. See
152 * {@link TextureDefinition}.
153 * @param state - State returned by create.
154 * @param context - Texture-owned drawing surface and scheduling services. See
155 * {@link TextureContext} .
156 */
157 dispose?(state: State, context: TextureContext): void;
158 }
159 /**
160 * A reusable texture definition together with the options used to instantiate it.
161 *
162 * @see {@link defineTexture}
163 * @see {@link useTexture}
164 */
165 export interface TextureRecipe<Message = never> {
166 readonly [recipeBrand]: (message: Message) => Message;
167 }
168 type Definition = TextureDefinition<any, any, any>;
169 interface Recipe {
170 definition: Definition;
171 config: any;
172 }
173 const recipes = new WeakMap<object, Recipe>();
174
175 /**
176 * Defines a pure recipe factory; resource allocation starts at useTexture.
177 *
178 * @param definition - State creation, update, simulation, rasterization, and disposal callbacks.
179 * See {@link TextureDefinition} .
180 * @returns A configuration-to-recipe factory; resources are allocated when a recipe is mounted.
181 * See {@link TextureRecipe} .
182 *
183 * @see {@link TextureDefinition}
184 * @see {@link TextureRecipe}
185 */
186 export function defineTexture<Config, State, Message = never>(
187 definition: TextureDefinition<Config, State, Message>,
188 ): (config: Config) => TextureRecipe<Message> {
189 const stable = Object.freeze({ ...definition });
190 return (config) => {
191 const recipe = Object.freeze({}) as TextureRecipe<Message>;
192 recipes.set(recipe, {
193 definition: stable,
194 config: structuredClone(config),
195 });
196 return recipe;
197 };
198 }
199 function placement(value: TexturePlacement = {}): Readonly<TexturePlacement> {
200 if (
201 value.mode !== undefined &&
202 value.mode !== "repeat" &&
203 value.mode !== "stretch"
204 )
205 throw new TypeError("Unknown texture placement mode.");
206 for (let keyIndex = 0; keyIndex < placementKeys.length; keyIndex++) {
207 const key = placementKeys[keyIndex];
208 const n = value[key];
209 if (
210 n !== undefined &&
211 (!Number.isFinite(n) ||
212 ((key === "tileWidth" || key === "tileHeight") && n <= 0))
213 )
214 throw new RangeError(`Invalid texture placement ${key}.`);
215 }
216 return Object.freeze({ ...value });
217 }
218 function dimensions(options: TextureOptions): [number, number] {
219 const width = options.resolution?.width ?? 256,
220 height = options.resolution?.height ?? 160;
221 if (
222 !(
223 Number.isInteger(width) &&
224 width >= 8 &&
225 width <= 1024 &&
226 Number.isInteger(height) &&
227 height >= 8 &&
228 height <= 1024
229 ) ||
230 width * height > 262144
231 )
232 throw new RangeError(
233 "Texture resolution must be 8..1024 cells per axis, at most 262144 cells.",
234 );
235 return [width, height];
236 }
237 class Resource {
238 readonly revision = signal(0);
239 readonly canvas: OffscreenCanvas;
240 private committed: OffscreenCanvas | undefined;
241 private spare: OffscreenCanvas | undefined;
242 private provisional: { canvas: OffscreenCanvas; transaction: NonNullable<typeof GLOBAL_STATE.renderTransaction> } | undefined;
243 readonly context: TextureContext;
244 readonly handle: Texture<any>;
245 state: any;
246 definition: Definition;
247 disposed = false;
248 private hasState = false;
249 dirty = true;
250 private sequence = 0;
251 private publicationCanvasesCreated = 0;
252 private messages: unknown[] = [];
253 private unregister?: () => void;
254 private continuing = false;
255 private lastTime?: number;
256 private initializing = true;
257 private retryScheduled = false;
258 private palette?: readonly string[];
259 private optionsKey: string;
260 constructor(
261 private owner: PibblInstance | undefined,
262 recipe: Recipe,
263 options: TextureOptions,
264 ) {
265 const [width, height] = dimensions(options);
266 this.optionsKey = JSON.stringify(options);
267 this.palette = options.palette && Object.freeze([...options.palette]);
268 this.canvas = new OffscreenCanvas(width, height);
269 this.definition = recipe.definition;
270 const self = this;
271 this.context = Object.freeze({
272 canvas: this.canvas,
273 get palette() {
274 return self.palette;
275 },
276 invalidate() {
277 if (!self.disposed) {
278 self.dirty = true;
279 if (!self.initializing) self.schedule();
280 }
281 },
282 requestFrame() {
283 if (!self.disposed) {
284 self.continuing = true;
285 self.schedule();
286 }
287 },
288 });
289 const registerPaint = (value: TexturePaint, placement: Readonly<TexturePlacement>) =>
290 registerTexturePaint(value, {
291 resolvePaint: (ctx, bounds) => this.resolvePaint(ctx, bounds, placement),
292 validate: () => this.assertOwner(),
293 borrow: callback => callback(this.borrow(placement)),
294 });
295 this.handle = Object.freeze({
296 send: (message: unknown) => {
297 if (this.disposed) return;
298 if (GLOBAL_STATE.currentPibblInstance)
299 throw new Error("Texture.send cannot run during Pibbl evaluation.");
300 if (!this.definition.receive)
301 throw new Error("This texture does not accept messages.");
302 if (this.messages.length >= 8192)
303 throw new RangeError("Texture message queue is full.");
304 this.messages.push(structuredClone(message));
305 this.schedule();
306 },
307 paint: (value: TexturePlacement) => {
308 const paint = Object.freeze({}) as TexturePaint;
309 registerPaint(paint, placement(value));
310 return paint;
311 },
312 }) as Texture<any>;
313 registerPaint(this.handle, placement(this.definition.defaultPlacement));
314 try {
315 this.state = this.call(() =>
316 this.definition.create(this.context, recipe.config),
317 );
318 this.hasState = true;
319 this.publishInitial();
320 this.initializing = false;
321 } catch (error) {
322 try {
323 this.dispose();
324 } catch {
325 // The initialization failure remains the actionable error.
326 }
327 throw error;
328 }
329 }
330 private call<T>(fn: () => T): T {
331 return withHooksForbidden(
332 "Texture implementations cannot call Pibbl hooks.",
333 fn,
334 );
335 }
336 update(recipe: Recipe, options: TextureOptions) {
337 if (this.disposed) return;
338 if (recipe.definition !== this.definition)
339 throw new Error(
340 "Changing a texture definition requires a new keyed owner.",
341 );
342 const [width, height] = dimensions(options);
343 const nextKey = JSON.stringify(options);
344 if (nextKey !== this.optionsKey) {
345 this.palette = options.palette && Object.freeze([...options.palette]);
346 this.optionsKey = nextKey;
347 if (width !== this.canvas.width || height !== this.canvas.height) {
348 try {
349 this.disposeState();
350 this.canvas.width = width;
351 this.canvas.height = height;
352 this.messages.length = 0;
353 this.lastTime = undefined;
354 this.state = this.call(() =>
355 this.definition.create(this.context, recipe.config),
356 );
357 this.hasState = true;
358 } catch (error) {
359 try { this.dispose(); } catch { /* Preserve the recreate failure. */ }
360 throw error;
361 }
362 }
363 this.context.invalidate();
364 }
365 this.call(() =>
366 this.definition.update?.(this.state, recipe.config, this.context),
367 );
368 }
369 private unschedule() {
370 this.unregister?.();
371 this.unregister = undefined;
372 }
373 private schedule() {
374 if (this.unregister || this.disposed) return;
375 const participant = (frame: { logicalTime: number }, batch: any) => {
376 const retryAtEntry = this.retryScheduled;
377 this.unschedule();
378 const wasContinuing = this.continuing;
379 this.continuing = false;
380 try {
381 const messages = this.messages;
382 this.messages = [];
383 for (const message of messages)
384 this.call(() =>
385 this.definition.receive?.(this.state, message, this.context),
386 );
387 if (wasContinuing)
388 this.call(() =>
389 this.definition.advance?.(
390 this.state,
391 {
392 delta:
393 this.lastTime === undefined
394 ? 0
395 : Math.max(0, frame.logicalTime - this.lastTime),
396 time: frame.logicalTime,
397 },
398 this.context,
399 ),
400 );
401 this.lastTime = this.continuing ? frame.logicalTime : undefined;
402 if (this.dirty) {
403 const candidate = this.rasterizeCandidate();
404 let previous: OffscreenCanvas | undefined;
405 batch.stage(this.revision, ++this.sequence, participant);
406 batch.registerLifecycle(participant, {
407 apply: () => {
408 if (this.disposed) {
409 candidate.width = candidate.height = 0;
410 } else {
411 previous = this.committed;
412 this.committed = candidate;
413 this.spare = previous;
414 this.retryScheduled = false;
415 }
416 },
417 rollback: () => {
418 if (!this.disposed) {
419 this.committed = previous;
420 this.spare = candidate;
421 }
422 },
423 abort: () => {
424 this.spare = candidate;
425 if (!this.disposed) {
426 this.dirty = true;
427 this.schedule();
428 }
429 },
430 });
431 }
432 if (!this.continuing && this.messages.length === 0) {
433 this.unschedule();
434 }
435 } catch (error) {
436 this.unschedule();
437 this.continuing = false;
438 if (this.retryScheduled && !retryAtEntry) this.schedule();
439 throw error;
440 }
441 };
442 this.unregister = registerAdvanceParticipant(participant);
443 }
444 private rasterizeCandidate(): OffscreenCanvas {
445 const ctx = this.canvas.getContext("2d");
446 if (!ctx) throw new Error("Textures require OffscreenCanvas 2D.");
447 ctx.save();
448 try {
449 ctx.resetTransform();
450 ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
451 this.call(() => this.definition.rasterize(this.state, this.context));
452 this.dirty = false;
453 } finally {
454 ctx.restore();
455 }
456 const spare = this.spare;
457 this.spare = undefined;
458 const reusable = spare?.width === this.canvas.width && spare.height === this.canvas.height ?
459 spare : undefined;
460 if (spare && spare !== reusable) spare.width = spare.height = 0;
461 let candidate: OffscreenCanvas | undefined;
462 try {
463 candidate = reusable ?? this.createPublicationCanvas();
464 const candidateContext = candidate.getContext("2d");
465 if (!candidateContext) throw new Error("Textures require OffscreenCanvas 2D.");
466 // Publication canvases are reused; transparent source pixels must erase old paint.
467 candidateContext.clearRect(0, 0, candidate.width, candidate.height);
468 candidateContext.drawImage(this.canvas, 0, 0);
469 return candidate;
470 } catch (error) {
471 if (candidate) candidate.width = candidate.height = 0;
472 this.dirty = true;
473 if (!this.retryScheduled) {
474 this.retryScheduled = true;
475 this.schedule();
476 }
477 throw error;
478 }
479 }
480 private createPublicationCanvas(): OffscreenCanvas {
481 this.publicationCanvasesCreated++;
482 return new OffscreenCanvas(this.canvas.width, this.canvas.height);
483 }
484 /** @internal Structural ownership evidence for texture publication tests. */
485 publicationSnapshot(): Readonly<{ publicationCanvasesCreated: number; hasOwner: boolean }> {
486 return Object.freeze({ publicationCanvasesCreated: this.publicationCanvasesCreated, hasOwner: this.owner !== undefined });
487 }
488 private publishInitial(): void {
489 const candidate = this.rasterizeCandidate();
490 const transaction = GLOBAL_STATE.renderTransaction;
491 if (!transaction) {
492 this.committed = candidate;
493 return;
494 }
495 this.provisional = { canvas: candidate, transaction };
496 transaction.onFinish(success => {
497 if (this.provisional?.transaction !== transaction) return;
498 const provisional = this.provisional;
499 this.provisional = undefined;
500 if (success && !this.disposed) this.committed = provisional.canvas;
501 else provisional.canvas.width = provisional.canvas.height = 0;
502 });
503 }
504 private assertOwner(): void {
505 if (this.disposed) throw new Error("Cannot paint with a disposed texture.");
506 let root = GLOBAL_STATE.currentPibblInstance;
507 while (root?.parent) root = GLOBAL_STATE.pibblInstances.get(root.parent);
508 let owner = this.owner;
509 while (owner?.parent) owner = GLOBAL_STATE.pibblInstances.get(owner.parent);
510 if (root !== owner) throw new Error("Textures may only be shared within their owning Pibbl tree.");
511 }
512 private borrow(placement: Readonly<TexturePlacement>): BorrowedTextureRaster {
513 this.assertOwner();
514 const revision = this.revision.get();
515 const provisional = this.provisional;
516 const source =
517 provisional !== undefined && provisional.transaction === GLOBAL_STATE.renderTransaction ?
518 provisional.canvas : this.committed;
519 if (!source) throw new Error("Texture pixels are not committed for this render transaction.");
520 return Object.freeze({ source, width: source.width, height: source.height, revision, resource: this, placement });
521 }
522 private resolvePaint(ctx: RenderingContext2D, bounds: { x: number; y: number; width: number; height: number }, p: Readonly<TexturePlacement>): string | CanvasGradient | CanvasPattern {
523 const borrowed = this.borrow(p);
524 const pattern = ctx.createPattern(borrowed.source, "repeat");
525 if (!pattern) throw new Error("Could not create texture paint.");
526 const stretch = p.mode === "stretch";
527 const width = stretch ? bounds.width : (p.tileWidth ?? borrowed.width);
528 const height = stretch ? bounds.height : (p.tileHeight ?? borrowed.height);
529 pattern.setTransform(new DOMMatrix().translate(bounds.x + (p.offsetX ?? 0), bounds.y + (p.offsetY ?? 0)).rotate(p.rotation ?? 0).scale(Math.max(0.000001, width) / borrowed.width, Math.max(0.000001, height) / borrowed.height));
530 return pattern;
531 }
532 dispose() {
533 if (this.disposed) return;
534 this.disposed = true;
535 this.unschedule();
536 this.messages.length = 0;
537 try {
538 this.disposeState();
539 } finally {
540 this.canvas.width = this.canvas.height = 0;
541 this.committed && (this.committed.width = this.committed.height = 0);
542 this.spare && (this.spare.width = this.spare.height = 0);
543 this.provisional && (this.provisional.canvas.width = this.provisional.canvas.height = 0);
544 this.state = undefined;
545 this.hasState = false;
546 this.committed = undefined;
547 this.spare = undefined;
548 this.provisional = undefined;
549 this.owner = undefined;
550 }
551 }
552 private disposeState() {
553 if (!this.hasState) return;
554 this.hasState = false;
555 const state = this.state;
556 this.state = undefined;
557 this.call(() => this.definition.dispose?.(state, this.context));
558 }
559 }
560
561 /**
562 * Owns one persistent texture resource for the current mounted hook slot.
563 *
564 * @param input - Texture recipe to mount or update. See {@link TextureRecipe}.
565 * @param options - Resolution and lifecycle options for the mounted texture. See
566 * {@link TextureOptions} .
567 * @returns A mount-owned texture handle for sending messages and creating paint placements. See
568 * {@link Texture} .
569 *
570 * @see {@link TextureRecipe}
571 * @see {@link TextureOptions}
572 * @see {@link Texture}
573 */
574 export function useTexture<Message>(
575 input: TextureRecipe<Message>,
576 options: TextureOptions = {},
577 ): Texture<Message> {
578 const recipe = recipes.get(input);
579 if (!recipe)
580 throw new TypeError("useTexture requires a defineTexture recipe.");
581 const { pibblInstance } = requireHookContext();
582 let created = false;
583 const resource = useHookSlot("texture", (teardowns) => {
584 created = true;
585 const value = new Resource(pibblInstance, recipe, options);
586 teardowns.add(() => value.dispose());
587 return value;
588 }).value;
589 if (!created)
590 GLOBAL_STATE.renderTransaction!.onFinish((success) => {
591 if (success) resource.update(recipe, options);
592 });
593 return resource.handle;
594 }
595
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.