Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(image): a picture repeats, and a picture is a surface - tile brings what leaves one edge in at the other (shapes, lines, brush strokes, shadows, blurs, noise), and material draws the relief, roughness and metal as grey pictures of their own, from which a normal map and a surface map are made

yhh486351ac42f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04850ee84..b60c5264e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ published separately; it ships inside the editor.
- **A flower turns to face the eye.** A flat flower faces the sky, so a field of them is seen edge on from a few metres up and has no colour a field away; tipping each far plant's head at random (`farTilt`) showed half of them from behind. `Foliage.faceEyeNear` and `Foliage.faceEye` turn the head of every mesh plant toward the eye, by the first close to and by the second from half the draw distance away, as a clump of flowers shows its colour from the side. It is done the way a pivot painted into a uv is elsewhere: the copies carry in a second uv where each vertex of a head sits from its plant's axis, and a material's vertex hook now reads a mesh's second uv as `es_vertexUv1` (zero on a mesh with none), beside `es_vertexColor`. At 0 and 0, the default, no channel is added and nothing turns.
- **A far field of flowers shows its colour.** A mesh plant kept in a far version grows across the ground to stand for those left out. A flat flower grown that way is a disc facing the sky: from an eye a few metres up it is seen edge on, and a meadow that is all flowers at your feet was plain green a field away. `Foliage.farTilt` tips the top of each far plant over by so many degrees (the last tenth of its height: the flower, not its stem), each plant its own way round, so half the field shows its face. 0, the default, leaves a far plant as it was.
- **A layer with a grain is read without repeat and without hexagons.** Near the eye a terrain layer is read in hexagonal cells, each shifted and turned at random, so no tile shows. A layer with a direction to it (sand in ripples, rock in beds) turned cell by cell has its normal map lit cell by cell, and the ground showed a mosaic of light and dark hexagons a metre wide. `u_antiTileTurn` on the Terrain and Terrain Layers materials is how far round a cell may be turned: 1, the default, is any way as before; 0 shifts the cell and does not turn it, which is the setting for a layer with a grain.
+- **An AI can draw a surface: a picture that repeats, with what the light does on it.** `image_write` drew one picture, and a picture laid beside itself shows its edges; nor is a wall only its colour. `tile: true` on an image source makes it repeat: a shape, a line or a brush stroke that leaves one edge comes in at the opposite one, a shadow and a blur go round with it, and a noise fill meets itself. `material: { relief, height, roughness, metal }` makes it a surface: each of height, roughness and metal is layers drawn as a grey picture of their own (light is high, rough, metal), or the colour's own lightness stands in for the relief, and a normal map, a map of roughness and metal and an `.esmaterial` are written beside the picture. The reply shows the picture laid beside itself two by two, where a join would run through the middle, and the same under a low light, and gives the fields to put on a mesh. A brick wall, a plank floor and a riveted plate, 256 pixels each, drew in under a third of a second apiece and tiled three across in the engine with no join. A `filter` still stops at the edges, and a noise turned or stretched by `transform` does not come round.
- **A model is written once for all its like parts, and a leaf can be a picture.** A model's source was a flat list of steps with plain numbers: a plant of ten fronds wrote out a frond ten times, and every leaf was a thin solid in one colour. Three things change that. `params` names numbers and points, and a value written `"=length * 0.4"` is a sum over them, with points that add and scale, angles in degrees, and makers for what shapes keep asking for: `polar` for a point round the upright axis, `arc` for a line that bends from one lean to another, `part` for a share of a line. `{ op: "repeat", over: [rows], steps: [...] }` runs its steps once for each row, the row's fields being names inside it, and `let` names a value for the steps after it; what is saved and edited is the source as written, so one edit to a name changes every part. The `strip` step carries a band with no thickness along a path, shaped by `widths`, folded by `cup`, with a picture laid along it from root to tip. `material.texture` names that picture, and with `alpha: "cutout"` its alpha is the outline: a leaf with veins and a torn edge, drawn once. `loft` takes an `up` for the way its section stands. The palm that was 386 steps is six steps written in two models of 2.9 and 2.4 KB, and 9,150 triangles where it was 26,814. Drawn in the engine it cost a little more GPU than the solid one all the same (about 1.1 ms against 0.8 for the frame at 1024 by 1024 on an RTX 3060): cut-out leaves draw both sides and test every pixel.
- **An AI can lay leaflets along a stem in one step.** `scatter` along a `path` pointed every copy the way the path runs, turned at random, so the leaflets of a frond, the barbs of a feather or the legs of a centipede had to be written out one step each: a palm was 386 steps and a 749 KB model file. `rows` (1 or 2) stands the copies off the path instead, in a row or in pairs, `sweep` degrees from the way it runs and `lift` out of the plane, each as one number or as a start and an end. A copy's +z faces `up`, so a flat blade keeps its face to the sky whichever way it points. `sizes` shapes them along the path, widest in the middle if you say so. The same palm is 40 steps and 38 KB, and bakes to the same triangle count. A scatter without `rows` is as it was.
- **A game calls its own native code by name.** A packaged Android or iOS game can link an ad SDK, a store or a sign-in library, and had no way to reach it: the native host answered the engine's own calls and nothing else. `NativeChannel.call(method, args)` now runs a handler the app registered (`com.estella.host.NativeChannel.register` in Java, `EstellaNativeChannel` in Objective-C) and resolves with what it answered; `has` says whether a name is answered and `on` hears what the native side raises on its own. Values cross as JSON. `Ads` rides on it: once the app's code answers `ads.show`, `Ads.available` is true on a device and `showRewarded` works as it does in a mini-game. The engine links no ad SDK; which one is the project's choice. An exported Android Studio project keeps your Java under `app/src/game`, which a re-export leaves alone. Elsewhere `has` is false and nothing is called, so a game that asks first runs unchanged on the web.
diff --git a/desktop b/desktop
index 1626f3e05..48b713cac 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 1626f3e055fa07ffb9e96949eb79d2b7655d6d9e
+Subproject commit 48b713cace41f8f56bd56cb0f4c44d30fdebe682
diff --git a/pipeline/src/image/imageMaterial.ts b/pipeline/src/image/imageMaterial.ts
new file mode 100644
index 000000000..8582603ba
--- /dev/null
+++ b/pipeline/src/image/imageMaterial.ts
@@ -0,0 +1,221 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file imageMaterial.ts — a picture as a surface: the maps a lit material reads beside its colour.
+ *
+ * A wall is not only its colour. Light catches the edges of its bricks and slides off its glaze, and a picture
+ * alone draws flat however well it is painted. So a source may say what its surface is as well as what it looks
+ * like: its relief, how rough it is, and where it is metal. Each is drawn with the same layers the colour is, as
+ * a grey picture of its own (light is high, light is rough, light is metal), and what a material needs is made
+ * from them: a normal map from the relief, and one map holding roughness and metal.
+ *
+ * With nothing drawn for the relief, the colour's own lightness stands in for it: dark is low. That is the
+ * cheap guess every texture tool makes, and it is right for mortar and wrong for a painted stripe, which is why
+ * a relief can be drawn instead.
+ */
+import { renderImage, type RenderedImage, type RgbaBitmap, type ImageTextDrawer } from './imageRaster';
+import type { ImageLayer, ImageMaterial, ImageSource } from './imageSource';
+
+export type { ImageMaterial } from './imageSource';
+
+export interface MaterialMaps {
+ /** Tangent space, +z out of the surface, as the engine's lit materials read it. */
+ normal: RgbaBitmap;
+ /** Roughness in green and metal in blue, glTF's layout; null when both are one value everywhere. */
+ surface: RgbaBitmap | null;
+ /** The one value, where it is one. */
+ roughness: number;
+ metal: number;
+ /** The grey pictures the maps were made from, for looking at. */
+ height: RgbaBitmap;
+ notes: string[];
+}
+
+type DrawOptions = { pictures?: Readonly<Record<string, RgbaBitmap>>; text?: ImageTextDrawer };
+
+const lightness = (p: Uint8Array, i: number): number => (p[i * 4]! * 0.2126 + p[i * 4 + 1]! * 0.7152 + p[i * 4 + 2]! * 0.0722) / 255;
+
+/** The layers as a grey picture the size of the source, on black: what is not drawn is low, smooth, not metal. */
+function greyOf(source: ImageSource, layers: readonly ImageLayer[], options: DrawOptions): { values: Float32Array; picture: RenderedImage } {
+ const picture = renderImage({ size: source.size, background: '#000000', ...(source.tile ? { tile: true } : {}), layers }, options);
+ const values = new Float32Array(picture.width * picture.height);
+ for (let i = 0; i < values.length; i++) values[i] = lightness(picture.rgba, i);
+ return { values, picture };
+}
+
+/**
+ * A normal map from heights 0..1. The slope at a pixel is read across its neighbours (a Sobel), going round the edges of
+ * a picture that repeats and stopping at them otherwise. Green is up the picture, which is +v as the engine lays a
+ * texture, so a ridge lit from above is bright on its upper side.
+ */
+export function normalFromHeight(height: Float32Array, w: number, h: number, relief: number, wrap: boolean): RgbaBitmap {
+ const at = (x: number, y: number): number => {
+ const [cx, cy] = wrap ? [((x % w) + w) % w, ((y % h) + h) % h] : [Math.max(0, Math.min(w - 1, x)), Math.max(0, Math.min(h - 1, y))];
+ return height[cy * w + cx]!;
+ };
+ const rgba = new Uint8Array(w * h * 4);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const dx = ((at(x + 1, y - 1) + 2 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2 * at(x - 1, y) + at(x - 1, y + 1))) / 8;
+ // Down the picture is down the surface: a height rising toward the top of the picture slopes toward +v.
+ const dy = ((at(x - 1, y - 1) + 2 * at(x, y - 1) + at(x + 1, y - 1)) - (at(x - 1, y + 1) + 2 * at(x, y + 1) + at(x + 1, y + 1))) / 8;
+ const [nx, ny] = [-dx * relief, -dy * relief];
+ const l = Math.hypot(nx, ny, 1);
+ const o = (y * w + x) * 4;
+ rgba[o] = Math.round((nx / l * 0.5 + 0.5) * 255);
+ rgba[o + 1] = Math.round((ny / l * 0.5 + 0.5) * 255);
+ rgba[o + 2] = Math.round((1 / l * 0.5 + 0.5) * 255);
+ rgba[o + 3] = 255;
+ }
+ }
+ return { width: w, height: h, rgba };
+}
+
+/**
+ * How much the join shows when a picture is laid beside itself, as a share of how much one row or column of it differs
+ * from the next anyway: about 1 is a picture that repeats, well above it is a seam.
+ */
+export function seamOf(image: RgbaBitmap): number {
+ const { width: w, height: h, rgba } = image;
+ if (w < 4 || h < 4) return 1;
+ const step = (a: number, b: number): number => {
+ let d = 0;
+ for (let k = 0; k < 4; k++) d += Math.abs(rgba[a * 4 + k]! - rgba[b * 4 + k]!);
+ return d;
+ };
+ let [across, inside, insideCount] = [0, 0, 0];
+ for (let y = 0; y < h; y++) across += step(y * w + w - 1, y * w);
+ for (let x = 0; x < w; x++) across += step((h - 1) * w + x, x);
+ for (let y = 0; y < h; y++) for (let x = 0; x + 1 < w; x += Math.max(1, Math.floor(w / 16))) { inside += step(y * w + x, y * w + x + 1); insideCount++; }
+ for (let x = 0; x < w; x++) for (let y = 0; y + 1 < h; y += Math.max(1, Math.floor(h / 16))) { inside += step(y * w + x, (y + 1) * w + x); insideCount++; }
+ const usual = inside / Math.max(1, insideCount);
+ const join = across / (w + h);
+ // A flat picture has no usual step to measure against: its join shows only if there is one at all.
+ return usual < 0.25 ? (join < 0.5 ? 1 : join / 0.25) : join / usual;
+}
+
+/** The maps a source's `material` asks for, drawn beside its colour @p color. */
+export function renderMaterialMaps(source: ImageSource, color: RgbaBitmap, options: DrawOptions = {}): MaterialMaps {
+ const material = source.material ?? {};
+ const [w, h] = [color.width, color.height];
+ const notes: string[] = [];
+ let height: Float32Array;
+ let heightPicture: RgbaBitmap;
+ if (material.height) {
+ const drawn = greyOf(source, material.height, options);
+ [height, heightPicture] = [drawn.values, drawn.picture];
+ notes.push(...drawn.picture.notes.map((n) => `height: ${n}`));
+ } else {
+ height = new Float32Array(w * h);
+ const rgba = new Uint8Array(w * h * 4);
+ for (let i = 0; i < w * h; i++) {
+ height[i] = lightness(color.rgba, i);
+ const v = Math.round(height[i]! * 255);
+ rgba.set([v, v, v, 255], i * 4);
+ }
+ heightPicture = { width: w, height: h, rgba };
+ }
+ let [low, high] = [1, 0];
+ for (const v of height) { if (v < low) low = v; if (v > high) high = v; }
+ if (high - low < 1 / 255) notes.push('the relief is flat: its height is one value everywhere, so the normal map says nothing');
+
+ const constant = (v: ImageMaterial['roughness'], fallback: number): number => (typeof v === 'number' ? v : fallback);
+ const drawnMap = (v: ImageMaterial['roughness'], name: string): Float32Array | null => {
+ if (!Array.isArray(v)) return null;
+ const drawn = greyOf(source, v, options);
+ notes.push(...drawn.picture.notes.map((n) => `${name}: ${n}`));
+ return drawn.values;
+ };
+ const [rough, metal] = [drawnMap(material.roughness, 'roughness'), drawnMap(material.metal, 'metal')];
+ let surface: RgbaBitmap | null = null;
+ if (rough || metal) {
+ const rgba = new Uint8Array(w * h * 4);
+ const [r0, m0] = [Math.round(constant(material.roughness, 0.8) * 255), Math.round(constant(material.metal, 0) * 255)];
+ for (let i = 0; i < w * h; i++) {
+ rgba[i * 4] = 255;
+ rgba[i * 4 + 1] = rough ? Math.round(rough[i]! * 255) : r0;
+ rgba[i * 4 + 2] = metal ? Math.round(metal[i]! * 255) : m0;
+ rgba[i * 4 + 3] = 255;
+ }
+ surface = { width: w, height: h, rgba };
+ }
+ return {
+ normal: normalFromHeight(height, w, h, material.relief ?? 4, source.tile === true),
+ surface,
+ roughness: constant(material.roughness, 0.8),
+ metal: constant(material.metal, 0),
+ height: heightPicture,
+ notes,
+ };
+}
+
+/** The `.esmaterial` that reads the maps, by the names they were saved under beside it. */
+export function imageMaterialDoc(maps: MaterialMaps, files: { normal: string; surface: string | null }, constants: { version: string | number; blendNone: number; cullBack: number }): Record<string, unknown> {
+ return {
+ version: constants.version,
+ type: 'material',
+ shader: 'builtin:model',
+ blendMode: constants.blendNone,
+ depthTest: true,
+ depthWrite: true,
+ cull: constants.cullBack,
+ properties: {
+ u_normalMap: files.normal,
+ // A map holds the values and the factors multiply it, so where there is a map they stand aside.
+ ...(files.surface
+ ? { u_metallicRoughnessMap: files.surface, u_roughness: 1, u_metallic: 1 }
+ : { u_roughness: maps.roughness, u_metallic: maps.metal }),
+ },
+ };
+}
+
+/** A picture laid beside itself, two by two: the joins run down and across its middle, where a seam shows if there is one. */
+export function laidTwice(image: RgbaBitmap): RgbaBitmap {
+ const { width: w, height: h, rgba } = image;
+ const out = new Uint8Array(w * 2 * h * 2 * 4);
+ for (let y = 0; y < h * 2; y++) {
+ for (let x = 0; x < w * 2; x++) {
+ const from = ((y % h) * w + (x % w)) * 4;
+ out.set(rgba.subarray(from, from + 4), (y * w * 2 + x) * 4);
+ }
+ }
+ return { width: w * 2, height: h * 2, rgba: out };
+}
+
+/**
+ * The surface under a low light from the upper left, as a flat wall of it would take one: what the relief and the
+ * roughness do, which neither the colour nor the normal map's own colours show. For looking at; the engine's own
+ * shading is what a scene gets.
+ */
+export function litPreview(color: RgbaBitmap, maps: MaterialMaps): RgbaBitmap {
+ const { width: w, height: h } = color;
+ const out = new Uint8Array(w * h * 4);
+ const light = [-0.55, 0.55, 0.63];
+ const half = (() => { const v = [light[0]!, light[1]!, light[2]! + 1]; const l = Math.hypot(...v); return v.map((c) => c / l); })();
+ const srgb = (v: number): number => Math.round(Math.pow(Math.max(0, Math.min(1, v)), 1 / 2.2) * 255);
+ for (let i = 0; i < w * h; i++) {
+ const n = [maps.normal.rgba[i * 4]! / 127.5 - 1, maps.normal.rgba[i * 4 + 1]! / 127.5 - 1, maps.normal.rgba[i * 4 + 2]! / 127.5 - 1];
+ const rough = maps.surface ? maps.surface.rgba[i * 4 + 1]! / 255 : maps.roughness;
+ const metal = maps.surface ? maps.surface.rgba[i * 4 + 2]! / 255 : maps.metal;
+ const diffuse = Math.max(0, n[0]! * light[0]! + n[1]! * light[1]! + n[2]! * light[2]!);
+ const shine = Math.pow(Math.max(0, n[0]! * half[0]! + n[1]! * half[1]! + n[2]! * half[2]!), 2 / Math.max(0.02, rough * rough) - 1) * (1 - rough) * 1.6;
+ for (let k = 0; k < 3; k++) {
+ const base = Math.pow(color.rgba[i * 4 + k]! / 255, 2.2);
+ out[i * 4 + k] = srgb(base * (1 - metal) * (0.18 + 0.95 * diffuse) + (0.04 + (base - 0.04) * metal) * (shine + metal * 0.25 * (0.3 + diffuse)));
+ }
+ out[i * 4 + 3] = 255;
+ }
+ return { width: w, height: h, rgba: out };
+}
+
+/** Two pictures side by side, the second scaled to the first's height. */
+export function sideBySide(a: RgbaBitmap, b: RgbaBitmap): RgbaBitmap {
+ const out = new Uint8Array((a.width + b.width + 8) * a.height * 4).fill(60);
+ for (let y = 0; y < a.height; y++) {
+ out.set(a.rgba.subarray(y * a.width * 4, (y + 1) * a.width * 4), y * (a.width + b.width + 8) * 4);
+ const by = Math.min(b.height - 1, Math.floor((y / a.height) * b.height));
+ out.set(b.rgba.subarray(by * b.width * 4, (by + 1) * b.width * 4), (y * (a.width + b.width + 8) + a.width + 8) * 4);
+ }
+ for (let i = 3; i < out.length; i += 4) out[i] = 255;
+ return { width: a.width + b.width + 8, height: a.height, rgba: out };
+}
diff --git a/pipeline/src/image/imageNoise.ts b/pipeline/src/image/imageNoise.ts
index 944a8c01f..9374b83d4 100644
--- a/pipeline/src/image/imageNoise.ts
+++ b/pipeline/src/image/imageNoise.ts
@@ -10,8 +10,44 @@ export function parseColor(text: string): Rgba {
return [at(0), at(2), at(4), full.length === 8 ? at(6) : 1];
}
+/**
+ * Whether the picture being drawn repeats: what leaves one edge comes in at the opposite one. Set for the length of one
+ * draw (renderImage), and read by everything that looks past an edge, so a tile's blur, shadow and noise all go round.
+ */
+let wrapping = false;
+export const setWrapping = (on: boolean): void => { wrapping = on; };
+export const isWrapping = (): boolean => wrapping;
+
+function blurRound(src: Float32Array, w: number, h: number, sigma: number): Float32Array {
+ const r = Math.max(1, Math.round(sigma * 1.2));
+ let cur = src;
+ for (let pass = 0; pass < 3; pass++) {
+ const a = new Float32Array(w * h);
+ for (let y = 0; y < h; y++) {
+ let sum = 0;
+ for (let x = -r; x <= r; x++) sum += cur[y * w + (((x % w) + w) % w)]!;
+ for (let x = 0; x < w; x++) {
+ a[y * w + x] = sum / (2 * r + 1);
+ sum += cur[y * w + ((x + r + 1) % w)]! - cur[y * w + ((((x - r) % w) + w) % w)]!;
+ }
+ }
+ const b = new Float32Array(w * h);
+ for (let x = 0; x < w; x++) {
+ let sum = 0;
+ for (let y = -r; y <= r; y++) sum += a[(((y % h) + h) % h) * w + x]!;
+ for (let y = 0; y < h; y++) {
+ b[y * w + x] = sum / (2 * r + 1);
+ sum += a[((y + r + 1) % h) * w + x]! - a[((((y - r) % h) + h) % h) * w + x]!;
+ }
+ }
+ cur = b;
+ }
+ return cur;
+}
+
export function blurMask(src: Float32Array, w: number, h: number, sigma: number): Float32Array {
if (sigma <= 0) return src;
+ if (wrapping) return blurRound(src, w, h, sigma);
const r = Math.max(1, Math.round(sigma * 1.2));
let cur = src;
for (let pass = 0; pass < 3; pass++) {
@@ -53,22 +89,26 @@ export function cornerLift(ix: number, iy: number, seed: number, dx: number, dy:
export const fade = (t: number): number => t * t * t * (t * (t * 6 - 15) + 10);
-export function gradientNoise(x: number, y: number, seed: number): number {
+/** @p px, @p py: how many lattice cells before the noise repeats each way; 0 for never. */
+export function gradientNoise(x: number, y: number, seed: number, px = 0, py = 0): number {
const [ix, iy] = [Math.floor(x), Math.floor(y)];
const [fx, fy] = [x - ix, y - iy];
const [sx, sy] = [fade(fx), fade(fy)];
- const top = cornerLift(ix, iy, seed, fx, fy) * (1 - sx) + cornerLift(ix + 1, iy, seed, fx - 1, fy) * sx;
- const bottom = cornerLift(ix, iy + 1, seed, fx, fy - 1) * (1 - sx) + cornerLift(ix + 1, iy + 1, seed, fx - 1, fy - 1) * sx;
+ const wx = (i: number): number => (px > 0 ? ((i % px) + px) % px : i);
+ const wy = (i: number): number => (py > 0 ? ((i % py) + py) % py : i);
+ const top = cornerLift(wx(ix), wy(iy), seed, fx, fy) * (1 - sx) + cornerLift(wx(ix + 1), wy(iy), seed, fx - 1, fy) * sx;
+ const bottom = cornerLift(wx(ix), wy(iy + 1), seed, fx, fy - 1) * (1 - sx) + cornerLift(wx(ix + 1), wy(iy + 1), seed, fx - 1, fy - 1) * sx;
return top * (1 - sy) + bottom * sy;
}
export const NOISE_CONTRAST = [1.15, 1.3, 1.4, 1.45, 1.45, 1.45, 1.45, 1.45];
-export function fractalNoise(x: number, y: number, octaves: number, seed: number): number {
+/** @p px, @p py: cells of the first octave before the noise repeats; each finer octave repeats with it. 0 for never. */
+export function fractalNoise(x: number, y: number, octaves: number, seed: number, px = 0, py = 0): number {
let [sum, weight, amplitude, frequency] = [0, 0, 1, 1];
for (let i = 0; i < octaves; i++) {
// Off the lattice, where this noise is always nothing.
- sum += gradientNoise(x * frequency + 0.37, y * frequency + 0.61, seed + i * 101) * amplitude;
+ sum += gradientNoise(x * frequency + 0.37, y * frequency + 0.61, seed + i * 101, px * frequency, py * frequency) * amplitude;
weight += amplitude;
amplitude *= 0.5;
frequency *= 2;
diff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.ts
index f53e6524f..5c60612a2 100644
--- a/pipeline/src/image/imageRaster.ts
+++ b/pipeline/src/image/imageRaster.ts
@@ -12,13 +12,15 @@ import { figureLight, flattenFigure, type FlatFigure } from './imageFigure';
import { IMAGE_BRUSHES, isGuideLayer, MAX_MARK_STROKES } from './imageSource';
import type { ImageFill, ImageLayer, ImageSource, ImageAlong, ImageBrushSettings, ImageEffect, ImageField, ImageMark, ImageStroke, ImageSweep, ImageTransform } from './imageSource';
import { type Pt, parsePath } from './imagePath';
-import { type Rgba, blurMask, fractalNoise, gradientNoise, parseColor } from './imageNoise';
+import { type Rgba, blurMask, fractalNoise, gradientNoise, isWrapping, parseColor, setWrapping } from './imageNoise';
export interface RgbaBitmap { width: number; height: number; rgba: Uint8Array }
type Matrix = readonly [number, number, number, number, number, number];
const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
const SUBSCANS = 8;
+/** The size of the picture being drawn, for what has to repeat with it (see setWrapping). */
+let tileWidth = 0, tileHeight = 0;
const times = (a: Matrix, b: Matrix): Matrix => [
a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1],
@@ -132,7 +134,40 @@ function outlinesOf(layer: ImageLayer): { runs: { points: Pt[]; closed: boolean
// ---- Masks ----------------------------------------------------------------------
/** What each pixel has of a filled outline, non-zero: a span's ends count for what they cover, so an edge has no stairs. */
+/** The nine places a thing drawn in a repeating picture shows: where it is, and one picture away each way. */
+const ROUND: readonly Pt[] = [[0, 0], [-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]];
+
+/** Whether points moved by (@p dx, @p dy), grown by @p reach, touch the picture at all. */
+function touches(points: Iterable<readonly number[]>, dx: number, dy: number, reach: number, w: number, h: number): boolean {
+ let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity];
+ for (const p of points) {
+ if (p[0]! < x0) x0 = p[0]!;
+ if (p[0]! > x1) x1 = p[0]!;
+ if (p[1]! < y0) y0 = p[1]!;
+ if (p[1]! > y1) y1 = p[1]!;
+ }
+ return x1 + dx + reach > 0 && x0 + dx - reach < w && y1 + dy + reach > 0 && y0 + dy - reach < h;
+}
+
+/** A mask drawn once, or in a repeating picture once for each place it shows, the most of them kept. */
+function goingRound(points: () => Iterable<readonly number[]>, reach: number, w: number, h: number, draw: (dx: number, dy: number) => Float32Array): Float32Array {
+ if (!isWrapping()) return draw(0, 0);
+ let out: Float32Array | null = null;
+ for (const [ox, oy] of ROUND) {
+ const [dx, dy] = [ox * w, oy * h];
+ if ((ox !== 0 || oy !== 0) && !touches(points(), dx, dy, reach, w, h)) continue;
+ const part = draw(dx, dy);
+ if (!out) { out = part; continue; }
+ for (let i = 0; i < out.length; i++) if (part[i]! > out[i]!) out[i] = part[i]!;
+ }
+ return out ?? new Float32Array(w * h);
+}
+
function fillMask(runs: readonly (readonly Pt[])[], w: number, h: number): Float32Array {
+ return goingRound(() => runs.flat(), 1, w, h, (dx, dy) => fillMaskOnce(dx === 0 && dy === 0 ? runs : runs.map((run) => run.map(([x, y]) => [x + dx, y + dy] as Pt)), w, h));
+}
+
+function fillMaskOnce(runs: readonly (readonly Pt[])[], w: number, h: number): Float32Array {
const mask = new Float32Array(w * h);
const edges: { x0: number; y0: number; x1: number; y1: number; dir: number }[] = [];
let top = Infinity, bottom = -Infinity;
@@ -184,6 +219,12 @@ const STROKE_SAMPLES = 6;
/** What each pixel has of a stroke. Round joins and ends come from the distance to the line; the others are built of convex pieces, sampled where a pixel crosses an edge: a distance from the edges would trail a faint tail off a sharp point. */
function strokeMask(runs: readonly { points: readonly Pt[]; closed: boolean }[], width: number, w: number, h: number, join: 'round' | 'miter' | 'bevel' = 'round', cap: 'round' | 'butt' | 'square' = 'round'): Float32Array {
+ // A mitre can reach a good way past its line, so the reach is generous: a copy drawn for nothing costs little.
+ return goingRound(() => runs.flatMap((r) => r.points), width * (join === 'miter' ? MITER_LIMIT : 1) + 2, w, h, (dx, dy) => strokeMaskOnce(
+ dx === 0 && dy === 0 ? runs : runs.map((r) => ({ closed: r.closed, points: r.points.map(([x, y]) => [x + dx, y + dy] as Pt) })), width, w, h, join, cap));
+}
+
+function strokeMaskOnce(runs: readonly { points: readonly Pt[]; closed: boolean }[], width: number, w: number, h: number, join: 'round' | 'miter' | 'bevel' = 'round', cap: 'round' | 'butt' | 'square' = 'round'): Float32Array {
const mask = new Float32Array(w * h);
const half = width / 2;
const capsule = (a: Pt, b: Pt): void => {
@@ -295,6 +336,13 @@ function shifted(src: Float32Array, w: number, h: number, dx: number, dy: number
const [ix, iy] = [Math.round(dx), Math.round(dy)];
if (ix === 0 && iy === 0) return src;
const out = new Float32Array(w * h);
+ if (isWrapping()) {
+ for (let y = 0; y < h; y++) {
+ const fy = (((y - iy) % h) + h) % h;
+ for (let x = 0; x < w; x++) out[y * w + x] = src[fy * w + ((((x - ix) % w) + w) % w)]!;
+ }
+ return out;
+ }
for (let y = 0; y < h; y++) {
const fy = y - iy;
if (fy < 0 || fy >= h) continue;
@@ -438,6 +486,12 @@ function paintOf(fill: ImageFill, m: Matrix, drawn?: Drawn, w = 0): (x: number,
}
if (fill.type === 'noise') {
const [scale, octaves, seed] = [fill.scale ?? 32, fill.octaves ?? 4, fill.seed ?? 0];
+ if (isWrapping() && tileWidth > 0) {
+ // A whole number of cells across the picture, so the last meets the first; the scale gives a little to make it so.
+ // In the picture's own pixels and not the layer's: a noise turned or scaled with its layer would not come round.
+ const [cx, cy] = [Math.max(1, Math.round(tileWidth / scale)), Math.max(1, Math.round(tileHeight / scale))];
+ return (x, y) => at(fractalNoise(((x - 0.5) / tileWidth) * cx, ((y - 0.5) / tileHeight) * cy, octaves, seed, cx, cy));
+ }
return (x, y) => {
const p = apply(inverse, [x - 0.5, y - 0.5]);
return at(fractalNoise(p[0] / scale, p[1] / scale, octaves, seed));
@@ -1081,6 +1135,18 @@ function paintStrand(c: Canvas, s: ImageStroke, path: readonly PathPoint[], stra
}
function paintStroke(c: Canvas, given: ImageStroke, m: Matrix, scale: number, n: number, buffer: StrokeBuffer): void {
+ if (!isWrapping()) { paintStrokeOnce(c, given, m, scale, n, buffer); return; }
+ const placed = given.points.map((p) => apply(m, [p[0]!, p[1]!]));
+ const reach = (given.size ?? 24) * scale * 2 + 4;
+ for (const [ox, oy] of ROUND) {
+ const [dx, dy] = [ox * c.w, oy * c.h];
+ if ((ox !== 0 || oy !== 0) && !touches(placed, dx, dy, reach, c.w, c.h)) continue;
+ // The same stroke, the same hairs: its number seeds it, so each copy is the one stroke seen again.
+ paintStrokeOnce(c, given, times([1, 0, 0, 1, dx, dy], m), scale, n, buffer);
+ }
+}
+
+function paintStrokeOnce(c: Canvas, given: ImageStroke, m: Matrix, scale: number, n: number, buffer: StrokeBuffer): void {
const s: ImageStroke = given.brush ? { ...IMAGE_BRUSHES[given.brush], ...given } : given;
const path = brushPath(s.points, m);
const seed = s.seed ?? n + 1;
@@ -1875,7 +1941,7 @@ export function renderImage(source: ImageSource, options: { guides?: boolean; pi
const canvas = new Canvas(w, h);
const drawn: Drawn = { masks: new Map(), notes: [], bounds: new Map(), painted: new Map(), figures: new Map(), figureJoints: new Map(), showGuides: options.guides === true, pictures: options.pictures ?? {}, images: new Map(), text: options.text, blocks: new Map() };
// What every layer so far amounts to, chained: a layer changed leaves the keys before it as they were.
- let key = textHash(JSON.stringify([w, h, source.background ?? null, options.guides === true, picturesDigest(options.pictures)]));
+ let key = textHash(JSON.stringify([w, h, source.background ?? null, options.guides === true, picturesDigest(options.pictures), source.tile === true]));
const keys = source.layers.map((layer) => (key = textHash(key + JSON.stringify(layer))));
let from = 0;
for (let i = keys.length - 1; i >= 0; i--) {
@@ -1894,13 +1960,20 @@ export function renderImage(source: ImageSource, options: { guides?: boolean; pi
for (let i = 0; i < w * h; i++) put(canvas, i, r, g, b, a, 'normal');
}
let since = Date.now();
- for (let i = from; i < source.layers.length; i++) {
- drawLayer(canvas, source.layers[i]!, IDENTITY, drawn);
- cacheCounters.drawn++;
- if (i === source.layers.length - 1 || Date.now() - since >= SNAPSHOT_AFTER_MS) {
- keepSnapshot(keys[i]!, canvas, drawn);
- since = Date.now();
+ // Set for this draw only, and taken off whatever happens: the next picture drawn may not repeat.
+ setWrapping(source.tile === true);
+ [tileWidth, tileHeight] = [w, h];
+ try {
+ for (let i = from; i < source.layers.length; i++) {
+ drawLayer(canvas, source.layers[i]!, IDENTITY, drawn);
+ cacheCounters.drawn++;
+ if (i === source.layers.length - 1 || Date.now() - since >= SNAPSHOT_AFTER_MS) {
+ keepSnapshot(keys[i]!, canvas, drawn);
+ since = Date.now();
+ }
}
+ } finally {
+ setWrapping(false);
}
const rgba = new Uint8Array(w * h * 4);
for (let i = 0; i < w * h; i++) {
diff --git a/pipeline/src/image/imageSource.ts b/pipeline/src/image/imageSource.ts
index 0d1e99490..4c3c112e2 100644
--- a/pipeline/src/image/imageSource.ts
+++ b/pipeline/src/image/imageSource.ts
@@ -418,9 +418,32 @@ export interface ImageSource {
version?: number;
size: number | readonly [number, number];
background?: string;
+ /**
+ * The picture repeats: laid edge to edge with itself it shows no seam. What is drawn past one edge comes in at the
+ * opposite one, a blur or a shadow goes round with it, and a noise fill repeats with the picture. For a wall, a floor,
+ * a cloth: anything a surface is covered with.
+ */
+ tile?: boolean;
+ /** What the surface is, beside what it looks like: see {@link ImageMaterial}. With it, a normal map and a material are written beside the picture. */
+ material?: ImageMaterial;
layers: readonly ImageLayer[];
}
+/**
+ * A picture as a surface. Each part is a number for the whole of it, or layers drawn as a grey picture of their own:
+ * light is high, light is rough, light is metal.
+ */
+export interface ImageMaterial {
+ /** How far white stands above black, in pixels of the picture. Default 4. */
+ relief?: number;
+ /** The relief, drawn: light is high. Default: the colour picture's own lightness, dark being low. */
+ height?: readonly ImageLayer[];
+ /** How rough, 0..1 everywhere, or drawn: light is rough. Default 0.8. */
+ roughness?: number | readonly ImageLayer[];
+ /** How much metal, 0..1 everywhere, or drawn: light is metal. Default 0. */
+ metal?: number | readonly ImageLayer[];
+}
+
const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const isPair = (v: unknown): boolean => Array.isArray(v) && v.length === 2 && v.every(isNum);
const isColor = (v: unknown): boolean => typeof v === 'string' && /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(v);
@@ -763,7 +786,8 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)
export function validateImageSource(raw: unknown): ImageSource {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new Error('an image source must be { size, layers }');
const s = raw as Record<string, unknown>;
- for (const key of Object.keys(s)) if (!['version', 'size', 'background', 'layers'].includes(key)) throw new Error(`unknown field "${key}"; an image has version, size, background, layers`);
+ for (const key of Object.keys(s)) if (!['version', 'size', 'background', 'tile', 'material', 'layers'].includes(key)) throw new Error(`unknown field "${key}"; an image has version, size, background, tile, material, layers`);
+ if (s.tile !== undefined && typeof s.tile !== 'boolean') throw new Error('tile must be true or false');
if (s.version !== undefined && s.version !== IMAGE_SOURCE_VERSION) throw new Error(`version ${String(s.version)} is not one this editor reads (${IMAGE_SOURCE_VERSION})`);
const [w, h] = typeof s.size === 'number' ? [s.size, s.size] : isPair(s.size) ? (s.size as number[]) : [NaN, NaN];
if (!Number.isInteger(w) || !Number.isInteger(h) || w! < 1 || h! < 1 || w! > MAX_IMAGE_SIZE || h! > MAX_IMAGE_SIZE) throw new Error(`size must be a whole number or [width, height], 1..${MAX_IMAGE_SIZE}`);
@@ -771,6 +795,23 @@ export function validateImageSource(raw: unknown): ImageSource {
if (!Array.isArray(s.layers)) throw new Error('layers must be an array');
const ids = new Set<string>();
(s.layers as Record<string, unknown>[]).forEach((l, i) => checkLayer(l, `layer ${i}${l?.id ? ` "${String(l.id)}"` : ''}`, ids));
+ if (s.material !== undefined) {
+ const m = s.material as Record<string, unknown> | null;
+ if (typeof m !== 'object' || m === null || Array.isArray(m)) throw new Error('material must be { relief?, height?, roughness?, metal? }');
+ for (const key of Object.keys(m)) if (!['relief', 'height', 'roughness', 'metal'].includes(key)) throw new Error(`material has unknown "${key}"; it takes relief, height, roughness, metal`);
+ if (m.relief !== undefined && !(isNum(m.relief) && (m.relief as number) >= 0 && (m.relief as number) <= 64)) throw new Error('material.relief must be 0..64, in pixels');
+ const drawn = (key: string, v: unknown): void => {
+ if (!Array.isArray(v) || v.length === 0) throw new Error(`material.${key} must be layers, one or more`);
+ (v as Record<string, unknown>[]).forEach((l, i) => checkLayer(l, `material.${key} layer ${i}${l?.id ? ` "${String(l.id)}"` : ''}`, ids));
+ };
+ if (m.height !== undefined) drawn('height', m.height);
+ for (const key of ['roughness', 'metal']) {
+ const v = m[key];
+ if (v === undefined) continue;
+ if (isNum(v)) { if (v < 0 || v > 1) throw new Error(`material.${key} must be 0..1, or layers`); }
+ else drawn(key, v);
+ }
+ }
return { version: IMAGE_SOURCE_VERSION, ...(s as unknown as ImageSource) };
}
@@ -789,7 +830,7 @@ export type ImageEdit =
rect?: readonly { x: number; y: number; w?: number; h?: number; text: string }[];
palette?: Readonly<Record<string, string | null>>;
}
- | { op: 'settings'; fields: { size?: ImageSource['size']; background?: string | null } };
+ | { op: 'settings'; fields: { size?: ImageSource['size']; background?: string | null; tile?: boolean | null; material?: ImageMaterial | null } };
/** Every stroke width a source draws with, and how many layers use each: what drifts first across a set of icons. */
export function strokeWidths(source: ImageSource): Record<string, number> {
@@ -958,6 +999,11 @@ export function applyImageEdits(source: ImageSource, edits: readonly ImageEdit[]
if (edit.fields?.size !== undefined) clone.size = edit.fields.size;
if (edit.fields?.background === null) delete clone.background;
else if (edit.fields?.background !== undefined) clone.background = edit.fields.background;
+ // The whole of each, or none: a relief is replaced with the layers that draw it.
+ for (const key of ['tile', 'material'] as const) {
+ if (edit.fields?.[key] === null) delete (clone as Record<string, unknown>)[key];
+ else if (edit.fields?.[key] !== undefined) (clone as Record<string, unknown>)[key] = edit.fields[key];
+ }
break;
default:
throw new Error(`an edit has op ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, move, paint, wrap, unwrap, pixels, settings`);
diff --git a/pipeline/tests/image-material.test.ts b/pipeline/tests/image-material.test.ts
new file mode 100644
index 000000000..b72eeaf59
--- /dev/null
+++ b/pipeline/tests/image-material.test.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * A picture that repeats, and a picture as a surface: that what leaves one edge comes in at the other, that the join
+ * shows no more than any other row of the picture, and that the maps say what the layers drew.
+ */
+import { describe, expect, it } from 'vitest';
+import { renderImage } from '../src/image/imageRaster';
+import { applyImageEdits, validateImageSource, type ImageLayer, type ImageSource } from '../src/image/imageSource';
+import { laidTwice, litPreview, normalFromHeight, renderMaterialMaps, seamOf } from '../src/image/imageMaterial';
+
+const draw = (source: Partial<ImageSource> & { layers: ImageLayer[] }) => renderImage(validateImageSource({ size: 64, ...source }));
+const at = (img: { width: number; rgba: Uint8Array }, x: number, y: number): number[] => [...img.rgba.subarray((y * img.width + x) * 4, (y * img.width + x) * 4 + 4)];
+const noise: ImageLayer = { shape: 'rect', at: [0, 0], size: [64, 64], fill: { type: 'noise', scale: 12, octaves: 3, seed: 5, stops: [[0, '#101010'], [1, '#f0f0f0']] } } as never;
+
+describe('a picture that repeats', () => {
+ it('brings what leaves one edge in at the opposite one', () => {
+ const disc: ImageLayer = { shape: 'ellipse', at: [0, 32], radii: [10, 10], fill: '#ff0000' } as never;
+ const plain = draw({ layers: [disc] });
+ const tiled = draw({ tile: true, layers: [disc] });
+ // Centred on the left edge: half of it is in the picture either way, and the other half only when it repeats.
+ expect(at(plain, 3, 32)[3]).toBe(255);
+ expect(at(plain, 60, 32)[3]).toBe(0);
+ expect(at(tiled, 3, 32)[3]).toBe(255);
+ expect(at(tiled, 60, 32)[3]).toBe(255);
+ expect(at(tiled, 32, 32)[3]).toBe(0);
+ });
+
+ it('does so at a corner, in all four', () => {
+ const tiled = draw({ tile: true, layers: [{ shape: 'ellipse', at: [0, 0], radii: [8, 8], fill: '#00ff00' } as never] });
+ for (const [x, y] of [[2, 2], [61, 2], [2, 61], [61, 61]]) expect(at(tiled, x!, y!)[3]).toBe(255);
+ });
+
+ it('brings a line round, and a brush stroke', () => {
+ const line = draw({ tile: true, layers: [{ shape: 'line', points: [[50, 10], [80, 10]], stroke: { color: '#ffffff', width: 4 } } as never] });
+ expect(at(line, 8, 10)[3]).toBe(255);
+ expect(at(line, 30, 10)[3]).toBe(0);
+ const stroke = draw({ tile: true, layers: [{ shape: 'paint', strokes: [{ points: [[50, 40], [80, 40]], color: '#ffffff', size: 8 }] } as never] });
+ expect(at(stroke, 8, 40)[3]).toBeGreaterThan(100);
+ const once = draw({ layers: [{ shape: 'paint', strokes: [{ points: [[50, 40], [80, 40]], color: '#ffffff', size: 8 }] } as never] });
+ expect(at(once, 8, 40)[3]).toBe(0);
+ });
+
+ it('carries a shadow and a blur round with it', () => {
+ const shadowed: ImageLayer = { shape: 'rect', at: [44, 24], size: [16, 16], fill: '#ffffff', effects: [{ type: 'shadow', x: 10, y: 0, blur: 0, color: '#000000' }] } as never;
+ const tiled = draw({ tile: true, layers: [shadowed] });
+ // The shadow runs off the right edge and lands on the left.
+ expect(at(tiled, 3, 32)[3]).toBeGreaterThan(200);
+ expect(at(draw({ layers: [shadowed] }), 3, 32)[3]).toBe(0);
+ });
+
+ it('makes a noise that meets itself, where one that does not repeat shows its join', () => {
+ expect(seamOf(draw({ layers: [noise] }))).toBeGreaterThan(2.5);
+ expect(seamOf(draw({ tile: true, layers: [noise] }))).toBeLessThan(1.6);
+ });
+
+ it('is the same picture drawn twice, and leaves the next picture alone', () => {
+ const a = draw({ tile: true, layers: [noise] });
+ const plain = draw({ layers: [noise] });
+ const b = draw({ tile: true, layers: [noise] });
+ expect(Buffer.from(a.rgba).equals(Buffer.from(b.rgba))).toBe(true);
+ // A picture drawn after a repeating one does not repeat: the setting is the draw's, not the module's.
+ expect(Buffer.from(plain.rgba).equals(Buffer.from(draw({ layers: [noise] }).rgba))).toBe(true);
+ expect(Buffer.from(plain.rgba).equals(Buffer.from(a.rgba))).toBe(false);
+ });
+
+ it('measures a join against the picture it is in', () => {
+ const flat = draw({ background: '#808080', layers: [] });
+ expect(seamOf(flat)).toBe(1);
+ const halves = draw({ background: '#000000', layers: [{ shape: 'rect', at: [32, 0], size: [32, 64], fill: '#ffffff' } as never] });
+ expect(seamOf(halves)).toBeGreaterThan(3);
+ expect(laidTwice(flat).width).toBe(128);
+ });
+});
+
+describe('a picture as a surface', () => {
+ it('turns a height into a normal map: flat is straight out, a slope leans away from the rise', () => {
+ const [w, h] = [16, 16];
+ const flat = normalFromHeight(new Float32Array(w * h).fill(0.5), w, h, 4, false);
+ expect(at(flat, 8, 8)).toEqual([128, 128, 255, 255]);
+ // Rising to the right: the surface faces left, so red is below the middle.
+ const ramp = new Float32Array(w * h).map((_, i) => (i % w) / (w - 1));
+ const right = normalFromHeight(ramp, w, h, 8, false);
+ expect(at(right, 8, 8)[0]).toBeLessThan(110);
+ expect(at(right, 8, 8)[1]).toBe(128);
+ // Rising toward the top of the picture: the surface faces down it, so green is below the middle.
+ const up = normalFromHeight(new Float32Array(w * h).map((_, i) => 1 - Math.floor(i / w) / (h - 1)), w, h, 8, false);
+ expect(at(up, 8, 8)[1]).toBeLessThan(110);
+ expect(at(up, 8, 8)[0]).toBe(128);
+ });
+
+ it('reads a deeper relief as a steeper normal, and none as flat', () => {
+ const [w, h] = [16, 16];
+ const ramp = new Float32Array(w * h).map((_, i) => (i % w) / (w - 1));
+ const lean = (relief: number): number => 128 - at(normalFromHeight(ramp, w, h, relief, false), 8, 8)[0]!;
+ expect(lean(16)).toBeGreaterThan(lean(4));
+ expect(lean(0)).toBe(0);
+ });
+
+ it('goes round the edge of a picture that repeats, and stops at it otherwise', () => {
+ const [w, h] = [16, 16];
+ // High on the left edge only: across the join the right-hand column sees the rise when the picture repeats.
+ const edge = new Float32Array(w * h).map((_, i) => (i % w === 0 ? 1 : 0));
+ expect(at(normalFromHeight(edge, w, h, 8, true), 15, 8)[0]).toBeLessThan(110);
+ expect(at(normalFromHeight(edge, w, h, 8, false), 15, 8)[0]).toBe(128);
+ });
+
+ it('takes the relief from the colour when none is drawn, and from the layers when one is', () => {
+ const stripe: ImageLayer = { shape: 'rect', at: [24, 0], size: [16, 64], fill: '#ffffff' } as never;
+ const fromColour = renderMaterialMaps(validateImageSource({ size: 64, background: '#000000', material: {}, layers: [stripe] }), draw({ background: '#000000', layers: [stripe] }));
+ expect(at(fromColour.normal, 24, 32)[0]).toBeLessThan(120);
+ expect(at(fromColour.normal, 8, 32)).toEqual([128, 128, 255, 255]);
+ // A painted stripe that is not a ridge: the relief is drawn flat, and the normal map is flat with it.
+ const source = validateImageSource({ size: 64, background: '#000000', material: { height: [{ shape: 'rect', at: [0, 0], size: [64, 64], fill: '#808080' }] }, layers: [stripe] });
+ const drawn = renderMaterialMaps(source, renderImage(source));
+ expect(at(drawn.normal, 24, 32)).toEqual([128, 128, 255, 255]);
+ expect(drawn.notes.join(' ')).toMatch(/relief is flat/);
+ });
+
+ it('holds roughness in green and metal in blue, drawn or one value', () => {
+ const half: ImageLayer[] = [{ shape: 'rect', at: [0, 0], size: [32, 64], fill: '#ffffff' } as never];
+ const source = validateImageSource({ size: 64, background: '#444444', material: { roughness: half, metal: 0.25 }, layers: [] });
+ const maps = renderMaterialMaps(source, renderImage(source));
+ expect(at(maps.surface!, 8, 8)).toEqual([255, 255, 64, 255]);
+ expect(at(maps.surface!, 56, 8)).toEqual([255, 0, 64, 255]);
+ const plain = validateImageSource({ size: 64, background: '#444444', material: { roughness: 0.3 }, layers: [] });
+ const constant = renderMaterialMaps(plain, renderImage(plain));
+ expect(constant.surface).toBeNull();
+ expect(constant.roughness).toBe(0.3);
+ expect(constant.metal).toBe(0);
+ });
+
+ it('draws a preview that the relief changes', () => {
+ const stripe: ImageLayer = { shape: 'rect', at: [24, 0], size: [16, 64], fill: '#b0b0b0' } as never;
+ const source = validateImageSource({ size: 64, background: '#808080', material: { relief: 12 }, layers: [stripe] });
+ const colour = renderImage(source);
+ const lit = litPreview(colour, renderMaterialMaps(source, colour));
+ // The stripe's left edge faces the light from the upper left, and its right edge faces away.
+ expect(at(lit, 24, 32)[0]).toBeGreaterThan(at(lit, 39, 32)[0]! + 20);
+ });
+
+ it('keeps one set of ids across the picture and its maps, and says what is wrong', () => {
+ const rect = { shape: 'rect', at: [0, 0], size: [8, 8], fill: '#ffffff' };
+ expect(() => validateImageSource({ size: 64, material: { height: [{ ...rect, id: 'a' }] }, layers: [{ ...rect, id: 'a' }] })).toThrow(/material\.height layer 0 "a"/);
+ expect(() => validateImageSource({ size: 64, material: { depth: 2 }, layers: [] })).toThrow(/material has unknown "depth"; it takes relief, height, roughness, metal/);
+ expect(() => validateImageSource({ size: 64, material: { relief: 100 }, layers: [] })).toThrow(/material\.relief must be 0\.\.64/);
+ expect(() => validateImageSource({ size: 64, material: { roughness: 2 }, layers: [] })).toThrow(/material\.roughness must be 0\.\.1, or layers/);
+ expect(() => validateImageSource({ size: 64, material: { height: [] }, layers: [] })).toThrow(/material\.height must be layers, one or more/);
+ expect(() => validateImageSource({ size: 64, tile: 'yes', layers: [] })).toThrow(/tile must be true or false/);
+ });
+
+ it('is set, replaced and taken off by an edit', () => {
+ const source = validateImageSource({ size: 64, layers: [] });
+ const made = applyImageEdits(source, [{ op: 'settings', fields: { tile: true, material: { relief: 6, roughness: 0.4 } } }]);
+ expect(made.tile).toBe(true);
+ expect(made.material).toEqual({ relief: 6, roughness: 0.4 });
+ const off = applyImageEdits(made, [{ op: 'settings', fields: { tile: null, material: null } }]);
+ expect(off.tile).toBeUndefined();
+ expect(off.material).toBeUndefined();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 7c291f967..8b74d4f66 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4582,6 +4582,10 @@ export const NOTED = {
{"note": "A model is written once for all its like parts, and a leaf can be a picture."},
"fix(repo): put back the modeling commit the last one took out - 'a flower turns to face the eye' was built on the tree as it stood before 641f0da4e landed and committed on top of it, so it reverted that commit's files; they are as that commit left them, with both commits' notes":
{"internal": "Repairs the repository after one commit reverted another; the feature it restores has its own note."},
+ "feat(image): a picture repeats, and a picture is a surface - tile brings what leaves one edge in at the other (shapes, lines, brush strokes, shadows, blurs, noise), and material draws the relief, roughness and metal as grey pictures of their own, from which a normal map and a surface map are made":
+ {"note": "An AI can draw a surface: a picture that repeats, with what the light does on it."},
+ "feat(image): image_write makes a surface - a repeating picture is shown laid beside itself and under a light, and its normal map, surface map and material are written with it":
+ {"note": "An AI can draw a surface: a picture that repeats, with what the light does on it."},
"feat(sky): a sky of your own shades the ground under its clouds - defineSkyEffect takes groundShadow and a second function, skyShadow(world, sun), what is left of the light at a world position, and the sky pass multiplies every surface it finds by it, as Sky Atmosphere does with its own clouds":
{"note": "A sky of your own shades the ground under its clouds."},
"fix(terrain): a colour map and an occlusion map lie the way the heightmap does - Terrain.colorMap, Terrain.occlusionMap and Foliage.colorMap were sampled with their rows turned over, so a picture painted to match a heightmap, a splatmap or a density map came out mirrored north to south under them; an image over an area now has its first row along the least z whoever reads it":