Skip to content

packages/core/src/features/textures/lib/definitions.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { TextureRecipe } from "../../../lib/textures/texture.js";
2 import { rasterizeField, releaseField } from "./wasm/memory.js";
3 import { defineTexture, type TextureContext } from "@pibbl/core";
4 import {
5   marbleField,
6   paperField,
7   cellularField,
8   type MaterialGenerator,
9 } from "./material-field.js";
10 import { InkSimulation } from "./simulation.js";
11 import { paletteLut, texturePalettes, validateSeed } from "./palette.js";
12 export { useTexture } from "@pibbl/core";
13 /**
14  * Seed, feature scale, and detail controls shared by static material recipes.
15  *
16  * @see {@link marble}
17  * @see {@link paper}
18  * @see {@link cellular}
19  */
20 export interface MaterialOptions {
21   /**
22    * Seed used for deterministic sampling or simulation initialization. See {@link MaterialOptions}
23    * .
24    */
25   readonly seed?: number;
26   /** Feature frequency across the generated material. See {@link MaterialOptions}. */
27   readonly scale?: number;
28   /** Material-specific distortion, grain strength, or cellular jitter. See {@link MaterialOptions}. */
29   readonly detail?: number;
30 }
31 export type { ReactionDiffusionOptions } from "./gray-scott.js";
32 import {
33   grayScottConfig,
34   type ReactionDiffusionOptions,
35 } from "./gray-scott.js";
36 /**
37  * Paint, stir, pause, or reset commands accepted by a reaction-diffusion texture.
38  *
39  * @see {@link reactionDiffusion}
40  */
41 export type InkMessage =
42   | {
43       /** The literal "paint" identifying this variant. See {@link InkMessage}. */
44       readonly type: "paint";
45       /** Normalized horizontal texture coordinate. See {@link InkMessage}. */
46       readonly u: number;
47       /** Normalized vertical texture coordinate. See {@link InkMessage}. */
48       readonly v: number;
49       /** Radius in the coordinate system of this geometry or effect. See {@link InkMessage}. */
50       readonly radius?: number;
51       /** Magnitude of the displacement or brush effect. See {@link InkMessage}. */
52       readonly strength?: number;
53     }
54   | {
55       /** The literal "stir" identifying this variant. See {@link InkMessage}. */
56       readonly type: "stir";
57       /** Normalized horizontal texture coordinate. See {@link InkMessage}. */
58       readonly u: number;
59       /** Normalized vertical texture coordinate. See {@link InkMessage}. */
60       readonly v: number;
61       /** Normalized displacement of the existing field, not a paint dose. */
62       readonly du: number;
63       /** Normalized vertical displacement of the texture field. See {@link InkMessage}. */
64       readonly dv: number;
65       /** Influence radius in texture cells. */
66       readonly radius?: number;
67     }
68   | {
69       /** The literal "pause" identifying this variant. See {@link InkMessage}. */
70       readonly type: "pause";
71       /** Whether simulation or playback advancement is suspended. See {@link InkMessage}. */
72       readonly paused: boolean;
73     }
74   | {
75       /** The literal "reset" identifying this variant. See {@link InkMessage}. */
76       readonly type: "reset";
77     };
78 function colorize(field: Float32Array, context: TextureContext, gain = 1) {
79   const ctx = context.canvas.getContext("2d")!;
80   const lut = paletteLut(context.palette ?? texturePalettes.porcelain);
81   const raster = rasterizeField(field, lut, gain);
82   if (!raster) throw new Error("Texture field has no WASM owner.");
83   ctx.putImageData(raster.image, 0, 0);
84 }
85 function materialConfig(config: MaterialOptions) {
86   const seed = validateSeed(config.seed),
87     scale = config.scale ?? 6,
88     detail = config.detail ?? 0.65;
89   if (
90     !Number.isFinite(scale) ||
91     scale < 1 ||
92     scale > 32 ||
93     !Number.isFinite(detail) ||
94     detail < 0 ||
95     detail > 1
96   )
97     throw new RangeError("Material scale must be 1..32 and detail 0..1.");
98   return { seed, scale, detail };
99 }
100 function material(generate: MaterialGenerator) {
101   const recipe = defineTexture<
102     MaterialOptions,
103     { config: ReturnType<typeof materialConfig>; field: Float32Array }
104   >({
105     create(context, input) {
106       const config = materialConfig(input);
107       return {
108         config,
109         field: generate(
110           context.canvas.width,
111           context.canvas.height,
112           config.seed,
113           config.scale,
114           config.detail,
115         ),
116       };
117     },
118     update(state, input, context) {
119       const config = materialConfig(input);
120       if (JSON.stringify(config) === JSON.stringify(state.config)) return;
121       state.field = generate(
122         context.canvas.width,
123         context.canvas.height,
124         config.seed,
125         config.scale,
126         config.detail,
127         state.field,
128       );
129       state.config = config;
130       context.invalidate();
131     },
132     rasterize(state, context) {
133       colorize(state.field, context);
134     },
135     dispose(state) {
136       releaseField(state.field);
137       state.field = new Float32Array(0);
138     },
139   });
140   return (options: MaterialOptions = {}) => recipe(options);
141 }
142 /**
143  * Creates a seeded marble texture recipe with configurable feature scale and distortion.
144  *
145  * @param options - Seed, feature scale, and detail settings. See {@link MaterialOptions}.
146  * @returns A procedural material recipe for useTexture. See {@link TextureRecipe}.
147  *
148  * @see {@link MaterialOptions}
149  * @see {@link TextureRecipe}
150  */
151 export const marble = /* @__PURE__ */ material(marbleField);
152 /**
153  * Creates a seeded paper texture recipe with configurable feature scale and grain.
154  *
155  * @param options - Seed, feature scale, and detail settings. See {@link MaterialOptions}.
156  * @returns A procedural material recipe for useTexture. See {@link TextureRecipe}.
157  *
158  * @see {@link MaterialOptions}
159  * @see {@link TextureRecipe}
160  */
161 export const paper = /* @__PURE__ */ material(paperField);
162 /**
163  * Creates a seeded cellular texture recipe with configurable feature scale and jitter.
164  *
165  * @param options - Seed, feature scale, and detail settings. See {@link MaterialOptions}.
166  * @returns A procedural material recipe for useTexture. See {@link TextureRecipe}.
167  *
168  * @see {@link MaterialOptions}
169  * @see {@link TextureRecipe}
170  */
171 export const cellular = /* @__PURE__ */ material(cellularField);
172 const inkConfig = grayScottConfig;
173 interface InkState {
174   simulation: InkSimulation;
175   config: ReturnType<typeof inkConfig>;
176   paused: boolean;
177   elapsed: number;
178   fresh: boolean;
179 }
180 function reset(state: InkState, context: TextureContext) {
181   const next = new InkSimulation({
182     width: context.canvas.width,
183     height: context.canvas.height,
184     ...state.config,
185   });
186   state.simulation.dispose();
187   state.simulation = next;
188   state.elapsed = 0;
189   state.fresh = true;
190   context.invalidate();
191 }
192 const inkRecipe = /* @__PURE__ */ defineTexture<
193   ReactionDiffusionOptions,
194   InkState,
195   InkMessage
196 >({
197   defaultPlacement: { mode: "stretch" },
198   create(context, input) {
199     const config = inkConfig(input);
200     context.requestFrame();
201     return {
202       simulation: new InkSimulation({
203         width: context.canvas.width,
204         height: context.canvas.height,
205         ...config,
206       }),
207       config,
208       paused: false,
209       elapsed: 0,
210       fresh: true,
211     };
212   },
213   update(state, input, context) {
214     const config = inkConfig(input);
215     if (JSON.stringify(config) === JSON.stringify(state.config)) return;
216     state.config = config;
217     reset(state, context);
218   },
219   receive(state, message, context) {
220     if (message.type === "pause") {
221       state.paused = message.paused;
222       state.elapsed = 0;
223       state.fresh = true;
224       if (!state.paused) context.requestFrame();
225     } else if (message.type === "reset") reset(state, context);
226     else if (message.type === "stir") {
227       const radius = message.radius ?? 16;
228       if (
229         !(
230           Number.isFinite(message.u) &&
231           Number.isFinite(message.v) &&
232           Number.isFinite(message.du) &&
233           Number.isFinite(message.dv) &&
234           Number.isFinite(radius)
235         ) ||
236         radius <= 0 ||
237         radius > 128 ||
238         Math.abs(message.du) > 1 ||
239         Math.abs(message.dv) > 1
240       )
241         throw new RangeError("Invalid ink stir message.");
242       if (message.u < 0 || message.u > 1 || message.v < 0 || message.v > 1)
243         return;
244       state.simulation.stir(
245         message.u * context.canvas.width,
246         message.v * context.canvas.height,
247         message.du * context.canvas.width,
248         message.dv * context.canvas.height,
249         radius,
250       );
251       context.invalidate();
252     } else if (message.type === "paint") {
253       const radius = message.radius ?? 6,
254         strength = message.strength ?? 0.8;
255       if (
256         !(
257           Number.isFinite(message.u) &&
258           Number.isFinite(message.v) &&
259           Number.isFinite(radius) &&
260           Number.isFinite(strength)
261         ) ||
262         radius <= 0 ||
263         radius > 128 ||
264         strength < 0 ||
265         strength > 1
266       )
267         throw new RangeError("Invalid ink paint message.");
268       if (message.u < 0 || message.v < 0 || message.u > 1 || message.v > 1)
269         return;
270       state.simulation.paint(
271         message.u * context.canvas.width,
272         message.v * context.canvas.height,
273         radius,
274         strength,
275       );
276       context.invalidate();
277     } else throw new TypeError("Unknown ink message.");
278   },
279   advance(state, frame, context) {
280     if (state.paused) return;
281     if (!state.fresh) {
282       state.elapsed += Math.min(50, frame.delta);
283       const steps = Math.min(24, Math.floor(state.elapsed * 0.48 + 1e-9));
284       state.elapsed -= steps / 0.48;
285       if (steps) {
286         state.simulation.advance(steps);
287         context.invalidate();
288       }
289     }
290     state.fresh = false;
291     context.requestFrame();
292   },
293   rasterize(state, context) {
294     colorize(state.simulation.b, context, 650 / 255);
295   },
296   dispose(state) {
297     state.simulation.dispose();
298   },
299 });
300 /**
301  * Creates a stateful reaction-diffusion texture recipe supporting paint, stirring, pause, and
302  * reset
303  * messages.
304  *
305  * @param options - Reaction and diffusion parameters, initialization, and rendering options. See
306  * {@link ReactionDiffusionOptions} .
307  * @returns A reaction-diffusion texture recipe for useTexture.
308  *
309  * @see {@link ReactionDiffusionOptions}
310  */
311 export function reactionDiffusion(options: ReactionDiffusionOptions = {}) {
312   return inkRecipe(options);
313 }
314 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.