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(modeling): a displace step carves wrinkles, cracks, scales and weave into a surface

yhh8641be4e38a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8c88839c..91303093f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,8 @@ published separately; it ships inside the editor.
- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.
- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.
+- **An AI building a model can carve fine detail into it.** A `displace` step pushes bumps, wrinkles, cracks, scales, pores, ribs, weave or scratches out of a surface along its normal. A pattern needs no UV and has no seams, can be limited to some faces or to around a point, stacks with others, and splits the surface as far as it needs. Followed by `decimate` and `normalBake`, half a million triangles of detail draw on 1,500.
+
- **An AI building a model can make it light and keep its detail.** A `decimate` step thins a model to a share or a number of triangles, keeping paint and tags on the side they were on, and rigs and shapes are found on what it leaves. `normalBake` writes the surface as it stood before that as a normal map on the thinned one, rigged or not: a 77,000-triangle rock at 800 triangles lights close to the original, and the map bakes in about a second.
- **A mesh can have 256 joints, up from 64.** A rig with fingers, a face and hair no longer imports as a statue. A draw sends only the joints it has, so a small rig costs what it did.
diff --git a/desktop b/desktop
index c6b086bd5..87d92ce38 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c6b086bd5ab414d10f3295ae5a94d84bcf8ae5c6
+Subproject commit 87d92ce3817a477eed31aa636109ba5f142c6f34
diff --git a/pipeline/src/modeling/displace.ts b/pipeline/src/modeling/displace.ts
new file mode 100644
index 000000000..efeeaba87
--- /dev/null
+++ b/pipeline/src/modeling/displace.ts
@@ -0,0 +1,387 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file displace.ts — the `displace` step: small detail pushed out of the surface along its normal.
+ *
+ * A pattern is a function of where a point is, not of a UV, so it runs across a
+ * model with no seams and survives any edit further up. It can only show where
+ * there are vertices to move, so the step first splits what it acts on until the
+ * pattern's finest feature has triangles to land on. That count is what a
+ * `decimate` and a `normalBake` afterwards exist to pay back.
+ */
+import { boundsOf, compact, dot, faceArea, faceNormal, length, normalize, selectFaces, sub, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
+import { hash3 } from './organic';
+import { triangulateFace } from './triangulate';
+
+export const DISPLACE_PATTERNS = ['bumps', 'wrinkles', 'cracks', 'scales', 'pores', 'ribs', 'weave', 'scratches'] as const;
+export type DisplacePattern = typeof DISPLACE_PATTERNS[number];
+
+export interface DisplaceParams {
+ faces?: FaceSelector;
+ /** Only around here, fading to nothing at `radius`. */
+ near?: { at: Vec3; radius: number };
+ pattern: DisplacePattern;
+ /** How far the pattern moves the surface. Negative turns it over: a crease becomes a ridge. */
+ amplitude: number;
+ /** The size of one feature, in model units. */
+ scale: number;
+ /** Layers of finer detail, each half the size of the last. bumps and wrinkles. Default 3. */
+ octaves?: number;
+ seed?: number;
+ /** Multiplies `scale` along each axis: [4, 1, 1] draws a pattern out along x, as wrinkles across a forehead. */
+ stretch?: Vec3;
+ /** Bends the pattern's lines, as a share of `scale`, so they stop looking drawn with a ruler. Default 0. */
+ warp?: number;
+ /** How wide a line or dot is, as a share of a feature: cracks, pores, scratches. */
+ width?: number;
+ /** The axis ribs run across. Default y. */
+ axis?: 'x' | 'y' | 'z';
+ /** The same pattern on both sides of this axis, as a face wants. */
+ mirror?: 'x' | 'y' | 'z';
+ /** The longest edge to leave. Default a third of the pattern's finest feature. */
+ detail?: number;
+}
+
+/** What one step may grow a model to. A dense model is a stage on the way to a decimate, and a model this size takes a few seconds a step. */
+export const MAX_DISPLACE_TRIANGLES = 1_500_000;
+
+const GRADIENTS: readonly Vec3[] = [
+ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1],
+ [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1],
+];
+
+const fade = (t: number): number => t * t * t * (t * (t * 6 - 15) + 10);
+const mix = (a: number, b: number, t: number): number => a + (b - a) * t;
+const smooth = (lo: number, hi: number, x: number): number => {
+ const t = Math.max(0, Math.min(1, (x - lo) / (hi - lo)));
+ return t * t * (3 - 2 * t);
+};
+/** A hash in 0..1. */
+const unit = (x: number, y: number, z: number, seed: number): number => hash3(x, y, z, seed) * 0.5 + 0.5;
+
+/**
+ * Gradient noise, near -1..1. Not organic's value noise: where this one crosses zero it draws a line that wanders
+ * freely, and those lines are what a wrinkle is. Value noise's run along its grid.
+ */
+function gradientNoise(x: number, y: number, z: number, seed: number): number {
+ const [ix, iy, iz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
+ const [fx, fy, fz] = [x - ix, y - iy, z - iz];
+ const corner = (dx: number, dy: number, dz: number): number => {
+ const g = GRADIENTS[Math.floor(unit(ix + dx, iy + dy, iz + dz, seed) * 11.999)]!;
+ return g[0] * (fx - dx) + g[1] * (fy - dy) + g[2] * (fz - dz);
+ };
+ const [u, v, w] = [fade(fx), fade(fy), fade(fz)];
+ return mix(
+ mix(mix(corner(0, 0, 0), corner(1, 0, 0), u), mix(corner(0, 1, 0), corner(1, 1, 0), u), v),
+ mix(mix(corner(0, 0, 1), corner(1, 0, 1), u), mix(corner(0, 1, 1), corner(1, 1, 1), u), v),
+ w,
+ ) * 1.1;
+}
+
+/** The distance to the nearest and second-nearest scattered point, and which cell the nearest is in. */
+function scattered(x: number, y: number, z: number, seed: number): { f1: number; f2: number; cell: number } {
+ const [ix, iy, iz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
+ let f1 = Infinity, f2 = Infinity, cell = 0;
+ for (let dz = -1; dz <= 1; dz++) {
+ for (let dy = -1; dy <= 1; dy++) {
+ for (let dx = -1; dx <= 1; dx++) {
+ const [cx, cy, cz] = [ix + dx, iy + dy, iz + dz];
+ const d = Math.hypot(cx + unit(cx, cy, cz, seed) - x, cy + unit(cx, cy, cz, seed + 1) - y, cz + unit(cx, cy, cz, seed + 2) - z);
+ if (d < f1) { f2 = f1; f1 = d; cell = unit(cx, cy, cz, seed + 3); } else if (d < f2) f2 = d;
+ }
+ }
+ }
+ return { f1, f2, cell };
+}
+
+const SCRATCH_LAYERS = 3;
+/** How much longer than wide a scratch's cell is. */
+const SCRATCH_LENGTH = 8;
+
+function scratches(x: number, y: number, z: number, seed: number, width: number, n: Vec3): number {
+ let deepest = 0;
+ for (let layer = 0; layer < SCRATCH_LAYERS; layer++) {
+ const s = seed + layer * 7;
+ // A way for this layer's scratches to run, and two more square to it.
+ const along = normalize([hash3(1, layer, 3, s), hash3(5, layer, 7, s), hash3(11, layer, 13, s)]);
+ const side = normalize(Math.abs(along[1]) < 0.9 ? [along[2], 0, -along[0]] : [0, -along[2], along[1]]);
+ const up: Vec3 = [along[1] * side[2] - along[2] * side[1], along[2] * side[0] - along[0] * side[2], along[0] * side[1] - along[1] * side[0]];
+ const p: Vec3 = [x, y, z];
+ // A thin sheet and not a thin line: a line in space meets a surface at a point, and a sheet meets it along a curve.
+ const b = dot(p, side);
+ const ib = Math.floor(b);
+ const a = dot(p, along) / SCRATCH_LENGTH + unit(ib, 0, 0, s + 1) * 13;
+ const c = dot(p, up) / SCRATCH_LENGTH + unit(ib, 1, 0, s + 1) * 13;
+ const [ia, ic] = [Math.floor(a), Math.floor(c)];
+ // Each slice across holds one sheet, and most patches of it are missing.
+ if (unit(ib, ia, ic, s + 2) < 0.65) continue;
+ const dist = Math.abs(b - ib - 0.2 - unit(ib, ia, ic, s + 3) * 0.6);
+ // Tapers toward its ends, as something dragged across a surface does.
+ const taper = Math.sin(Math.PI * (a - ia)) * Math.sin(Math.PI * (c - ic));
+ // Where the sheet lies along the surface it would cut a wide patch and not a line, so it fades there.
+ const across = 1 - smooth(0.4, 0.75, Math.abs(dot(n, side)));
+ deepest = Math.max(deepest, (1 - smooth(0, width, dist)) * Math.min(1, taper * 3) * across);
+ }
+ return -deepest;
+}
+
+function weaveAt(u: number, v: number): number {
+ const [iu, iv] = [Math.floor(u), Math.floor(v)];
+ const [a, b] = [Math.sin(Math.PI * (u - iu)), Math.sin(Math.PI * (v - iv))];
+ // A thread rises over its crossing and dives under the next, and the two directions take turns.
+ return (iu + iv) % 2 === 0 ? b * (0.55 + 0.45 * a) : a * (0.55 + 0.45 * b);
+}
+
+/** The pattern at a point of pattern space, where one unit is one feature. Up to about 1 either way. */
+function patternAt(p: DisplaceParams, x: number, y: number, z: number, n: Vec3): number {
+ const seed = p.seed ?? 1;
+ const octaves = p.octaves ?? 3;
+ switch (p.pattern) {
+ case 'bumps': {
+ let sum = 0, amp = 1, total = 0, f = 1;
+ for (let o = 0; o < octaves; o++) {
+ sum += amp * gradientNoise(x * f, y * f, z * f, seed + o);
+ total += amp;
+ amp *= 0.5;
+ f *= 2;
+ }
+ return (sum / total) * 1.6;
+ }
+ case 'wrinkles': {
+ // Each layer's zero crossings are its creases; the finer ones weigh less and break up the long ones.
+ let sum = 0, amp = 1, total = 0, f = 1;
+ for (let o = 0; o < octaves; o++) {
+ const ridge = 1 - Math.min(1, Math.abs(gradientNoise(x * f, y * f, z * f, seed + o)) * 2.5);
+ sum += amp * ridge * ridge * ridge;
+ total += amp;
+ amp *= 0.45;
+ f *= 2.1;
+ }
+ return -Math.min(1, (sum / total) * 1.5);
+ }
+ case 'cracks': {
+ const { f1, f2 } = scattered(x, y, z, seed);
+ return smooth(0, p.width ?? 0.08, f2 - f1) - 1;
+ }
+ case 'scales': {
+ const { f1, f2 } = scattered(x, y, z, seed);
+ // A dome on each cell, falling to a groove where two cells meet.
+ return smooth(0, 0.12, f2 - f1) * (1 - Math.min(1, f1 * f1 * 1.2)) - 0.5;
+ }
+ case 'pores': {
+ const { f1, cell } = scattered(x, y, z, seed);
+ const w = p.width ?? 0.25;
+ // Not every cell has one: an even field of dots reads as a pattern and not as skin.
+ return cell < 0.55 ? 0 : -Math.pow(1 - Math.min(1, f1 / w), 2);
+ }
+ case 'ribs': {
+ const across = p.axis === 'x' ? x : p.axis === 'z' ? z : y;
+ return Math.sin(2 * Math.PI * across);
+ }
+ case 'weave': {
+ // Three projections, each weighted by how squarely the surface faces it: no axis to stretch along and no seam.
+ const w: Vec3 = [Math.pow(Math.abs(n[0]), 4), Math.pow(Math.abs(n[1]), 4), Math.pow(Math.abs(n[2]), 4)];
+ const total = w[0] + w[1] + w[2] || 1;
+ return ((w[0] * weaveAt(y, z) + w[1] * weaveAt(x, z) + w[2] * weaveAt(x, y)) / total) * 2 - 1;
+ }
+ case 'scratches':
+ return scratches(x, y, z, seed, p.width ?? 0.12, n);
+ }
+}
+
+/** The longest edge that still draws the pattern, as a share of one feature: a rise and fall needs several points, and a line needs some across its width. */
+function finestShare(p: DisplaceParams): number {
+ const layers = 2 ** ((p.octaves ?? 3) - 1);
+ switch (p.pattern) {
+ case 'bumps': return 1 / (4 * layers);
+ case 'wrinkles': return 1 / (6 * layers);
+ case 'cracks': return (p.width ?? 0.08) / 2;
+ case 'scales': return 0.06;
+ case 'pores': return (p.width ?? 0.25) / 4;
+ case 'ribs': return 1 / 8;
+ case 'weave': return 1 / 6;
+ case 'scratches': return (p.width ?? 0.12) / 2;
+ }
+}
+
+/**
+ * Splits the faces in @p chosen until no edge of theirs is longer than @p longest. An edge a face outside shares is split
+ * like any other, and the new vertex joins that face's outline: it keeps its shape and no gap opens. Left whole, such an edge
+ * could never get short, and the triangles against it would go on splitting for as long as there was budget.
+ */
+function refine(mesh: PolyMesh, chosen: ReadonlySet<number>, longest: number): { mesh: PolyMesh; short: boolean } {
+ const positions: Vec3[] = [...mesh.positions];
+ // Room for every vertex the budget could make, in a number that stays exact.
+ const keyOf = (a: number, b: number): number => (a < b ? a * 67108864 + b : b * 67108864 + a);
+ /** Every edge ever split, and the vertex in its middle: what a face outside reads its new outline from. */
+ const middles = new Map<number, number>();
+ let tris: number[] = [];
+ let from: Face[] = [];
+ mesh.faces.forEach((face, f) => {
+ if (!chosen.has(f)) return;
+ for (const [a, b, c] of triangulateFace(mesh, face)) { tris.push(a, b, c); from.push(face); }
+ });
+ const outside = mesh.faces.length - chosen.size;
+ const limit = longest * longest;
+ let short = false;
+ let moved = false;
+ for (;;) {
+ const made = new Map<number, number>();
+ const wants = (a: number, b: number): boolean => {
+ const key = keyOf(a, b);
+ if (made.has(key)) return true;
+ const [p, q] = [positions[a]!, positions[b]!];
+ const d = (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2;
+ if (d <= limit) return false;
+ made.set(key, -1);
+ return true;
+ };
+ let after = 0;
+ const count = from.length;
+ const split = new Uint8Array(count);
+ for (let t = 0; t < count; t++) {
+ const [a, b, c] = [tris[t * 3]!, tris[t * 3 + 1]!, tris[t * 3 + 2]!];
+ const mask = (wants(a, b) ? 1 : 0) | (wants(b, c) ? 2 : 0) | (wants(c, a) ? 4 : 0);
+ split[t] = mask;
+ after += 1 + (mask & 1) + ((mask >> 1) & 1) + ((mask >> 2) & 1);
+ }
+ if (made.size === 0) break;
+ if (after + outside > MAX_DISPLACE_TRIANGLES) { short = true; break; }
+ moved = true;
+ const middle = (a: number, b: number): number => {
+ const key = keyOf(a, b);
+ let m = made.get(key)!;
+ if (m < 0) {
+ const [p, q] = [positions[a]!, positions[b]!];
+ m = positions.length;
+ positions.push([(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]);
+ made.set(key, m);
+ middles.set(key, m);
+ }
+ return m;
+ };
+ const nextTris: number[] = [];
+ const nextFrom: Face[] = [];
+ const out = (a: number, b: number, c: number, face: Face): void => { nextTris.push(a, b, c); nextFrom.push(face); };
+ for (let t = 0; t < count; t++) {
+ const [a, b, c] = [tris[t * 3]!, tris[t * 3 + 1]!, tris[t * 3 + 2]!];
+ const face = from[t]!;
+ const mask = split[t]!;
+ if (mask === 0) { out(a, b, c, face); continue; }
+ if (mask === 7) {
+ const [ab, bc, ca] = [middle(a, b), middle(b, c), middle(c, a)];
+ out(a, ab, ca, face); out(ab, b, bc, face); out(ca, bc, c, face); out(ab, bc, ca, face);
+ continue;
+ }
+ // One or two edges: turn the triangle so the first is a-b, and the second, if any, is b-c.
+ const single = mask === 1 || mask === 2 || mask === 4;
+ const turn = single ? (mask === 1 ? 0 : mask === 2 ? 1 : 2) : (mask === 3 ? 0 : mask === 6 ? 1 : 2);
+ const [p, q, r] = turn === 0 ? [a, b, c] : turn === 1 ? [b, c, a] : [c, a, b];
+ const pq = middle(p, q);
+ if (single) { out(p, pq, r, face); out(pq, q, r, face); continue; }
+ const qr = middle(q, r);
+ out(pq, q, qr, face); out(p, pq, qr, face); out(p, qr, r, face);
+ }
+ tris = nextTris;
+ from = nextFrom;
+ }
+ if (!moved) return { mesh, short };
+ const outline = (a: number, b: number, into: number[]): void => {
+ const m = middles.get(keyOf(a, b));
+ if (m === undefined) { into.push(a); return; }
+ outline(a, m, into);
+ outline(m, b, into);
+ };
+ const faces: Face[] = [];
+ mesh.faces.forEach((face, f) => {
+ if (chosen.has(f)) return;
+ const v: number[] = [];
+ for (let i = 0; i < face.v.length; i++) outline(face.v[i]!, face.v[(i + 1) % face.v.length]!, v);
+ faces.push(v.length === face.v.length ? face : { ...face, v });
+ });
+ for (let t = 0; t < from.length; t++) faces.push({ ...from[t]!, v: [tris[t * 3]!, tris[t * 3 + 1]!, tris[t * 3 + 2]!] });
+ return { mesh: { positions, faces }, short };
+}
+
+export function displace(mesh: PolyMesh, p: DisplaceParams): PolyMesh {
+ if (!DISPLACE_PATTERNS.includes(p.pattern)) throw new Error(`pattern ${JSON.stringify(p.pattern)} must be one of ${DISPLACE_PATTERNS.join(', ')}`);
+ if (!(p.scale > 0)) throw new Error(`scale ${p.scale} must be positive`);
+ if (p.octaves !== undefined && !(p.octaves >= 1 && p.octaves <= 6)) throw new Error(`octaves ${p.octaves} must be 1..6`);
+ if (p.detail !== undefined && !(p.detail > 0)) throw new Error(`detail ${p.detail} must be positive`);
+ if (p.width !== undefined && !(p.width > 0)) throw new Error(`width ${p.width} must be positive`);
+ if (p.stretch && !p.stretch.every((s) => s > 0)) throw new Error(`stretch ${JSON.stringify(p.stretch)} must be positive`);
+ if (p.near && !(p.near.radius > 0)) throw new Error(`near.radius ${p.near.radius} must be positive`);
+
+ const selector = p.faces ?? 'all';
+ let hit = selectFaces(mesh, selector);
+ if (hit.length === 0) throw new Error(`\`faces\` ${JSON.stringify(selector)} matched no face`);
+ if (p.near) {
+ const { at, radius } = p.near;
+ // By the box round a face: one large face can cross the ball with every corner far outside it.
+ hit = hit.filter((f) => {
+ const { min, max } = boundsOf(mesh, mesh.faces[f]!.v);
+ const gap = [0, 1, 2].map((k) => Math.max(min[k]! - at[k]!, 0, at[k]! - max[k]!));
+ return Math.hypot(gap[0]!, gap[1]!, gap[2]!) < radius;
+ });
+ if (hit.length === 0) throw new Error(`no surface of \`faces\` within ${radius} of ${JSON.stringify(at)}`);
+ }
+
+ const smallest = Math.min(...(p.stretch ?? [1, 1, 1])) * p.scale;
+ const longest = p.detail ?? smallest * finestShare(p);
+ const { mesh: fine, short } = refine(mesh, new Set(hit), longest);
+
+ // Splitting puts the step's faces last, in place of the ones it was given; with nothing to split they are where they were.
+ const chosen = new Set(hit);
+ const isChosen = (f: number): boolean => (fine === mesh ? chosen.has(f) : f >= mesh.faces.length - hit.length);
+ const inside = new Uint8Array(fine.positions.length);
+ fine.faces.forEach((face, f) => {
+ if (isChosen(f)) for (const v of face.v) inside[v] = 1;
+ });
+ // A vertex a face outside also uses stays put, or the surface opens.
+ fine.faces.forEach((face, f) => {
+ if (!isChosen(f)) for (const v of face.v) inside[v] = 0;
+ });
+
+ const normals = new Float64Array(fine.positions.length * 3);
+ for (const face of fine.faces) {
+ const n = faceNormal(fine, face);
+ const area = faceArea(fine, face);
+ for (const v of face.v) {
+ normals[v * 3]! += n[0] * area;
+ normals[v * 3 + 1]! += n[1] * area;
+ normals[v * 3 + 2]! += n[2] * area;
+ }
+ }
+ const stretch = p.stretch ?? [1, 1, 1];
+ const [sx, sy, sz] = [p.scale * stretch[0], p.scale * stretch[1], p.scale * stretch[2]];
+ const seed = p.seed ?? 1;
+ const warp = p.warp ?? 0;
+ const positions: Vec3[] = fine.positions.map((at, v) => {
+ if (!inside[v]) return at;
+ let weight = 1;
+ if (p.near) {
+ const t = 1 - length(sub(at, p.near.at)) / p.near.radius;
+ if (t <= 0) return at;
+ weight = t * t * (3 - 2 * t);
+ }
+ const n = normalize([normals[v * 3]!, normals[v * 3 + 1]!, normals[v * 3 + 2]!]);
+ let [x, y, z] = [at[0], at[1], at[2]];
+ if (p.mirror === 'x') x = Math.abs(x);
+ if (p.mirror === 'y') y = Math.abs(y);
+ if (p.mirror === 'z') z = Math.abs(z);
+ x /= sx; y /= sy; z /= sz;
+ if (warp > 0) {
+ const [wx, wy, wz] = [
+ gradientNoise(x * 0.7 + 3.1, y * 0.7, z * 0.7, seed + 40),
+ gradientNoise(x * 0.7, y * 0.7 + 5.7, z * 0.7, seed + 41),
+ gradientNoise(x * 0.7, y * 0.7, z * 0.7 + 9.3, seed + 42),
+ ];
+ x += wx * warp; y += wy * warp; z += wz * warp;
+ }
+ const push = patternAt(p, x, y, z, n) * p.amplitude * weight;
+ return [at[0] + n[0] * push, at[1] + n[1] * push, at[2] + n[2] * push];
+ });
+
+ const out = compact({ positions, faces: fine.faces });
+ return short ? { ...out, notes: [`this pattern wants edges of ${longest.toPrecision(3)} and stopped at ${MAX_DISPLACE_TRIANGLES} triangles, so its finest detail is lost: raise \`scale\`, narrow it with \`faces\` or \`near\`, or give a larger \`detail\``] } : out;
+}
diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.ts
index 643055bab..7f5a092da 100644
--- a/pipeline/src/modeling/modelBake.ts
+++ b/pipeline/src/modeling/modelBake.ts
@@ -22,6 +22,8 @@ import {
const DEFAULT_SMOOTH_ANGLE = 30;
const DEFAULT_NORMAL_SIZE = 1024;
+const HEAVY_TRIANGLES = 300000;
+const LIGHTMAP_TRIANGLES = 150000;
export interface ModelReport {
vertices: number;
@@ -257,7 +259,7 @@ function withTangents(mesh: MeshData): MeshData {
/** Validates, builds and bakes @p raw. Throws a ModelBuildError naming the step that failed; writes nothing, so a failure leaves nothing half made. */
export function bakeModel(raw: unknown): BakedModel {
const source = validateModelSource(raw);
- const { mesh, steps, high } = buildPolyMesh(source);
+ const { mesh, steps, high, notes } = buildPolyMesh(source);
if (mesh.faces.length === 0) throw new Error('the steps leave no faces; a model starts with a box, cylinder, cone, sphere, plane or prism');
const triangles = mesh.faces.map((f) => triangulateFace(mesh, f));
@@ -271,8 +273,28 @@ export function bakeModel(raw: unknown): BakedModel {
const size = bake?.size ?? DEFAULT_NORMAL_SIZE;
// A mesh that moves takes no lightmap: a bake holds still. A normal map moves with it, and needs texels of its own all the same.
const baked = toMeshData(mesh, triangles, source, rig, shapes);
- let unwrapped = bake ? unwrapLightmapUV(baked, { atlasSize: size, paddingTexels: 4 }).mesh : rig || shapes ? baked : unwrapLightmapUV(baked).mesh;
- if (source.uvAtlas || bake) copyLightmapUvToBase(unwrapped);
+ const triangleCount = triangles.reduce((n, t) => n + t.length, 0);
+ let layoutNote: string | null = null;
+ let unwrapped = baked;
+ if (bake || source.uvAtlas) {
+ try {
+ unwrapped = unwrapLightmapUV(baked, bake ? { atlasSize: size, paddingTexels: 4 } : {}).mesh;
+ } catch {
+ throw new Error(`${triangleCount} triangles break into too many pieces to lay out in one texture: decimate further, or give the surface less to carve before it`);
+ }
+ copyLightmapUvToBase(unwrapped);
+ } else if (!rig && !shapes) {
+ // This is optional, and costs minutes past a point where nobody would bake light onto the model anyway. Nothing else needs it.
+ layoutNote = 'it has no lightmap UV: baked light will not land on it, and is not worth it at this density';
+ if (triangleCount <= LIGHTMAP_TRIANGLES) {
+ try {
+ unwrapped = unwrapLightmapUV(baked).mesh;
+ layoutNote = null;
+ } catch {
+ layoutNote = 'it has no lightmap UV: its surface breaks into too many pieces to lay out';
+ }
+ }
+ }
if (bake) unwrapped = withTangents(unwrapped);
const edges = [...collectEdges(mesh).values()];
@@ -297,9 +319,9 @@ export function bakeModel(raw: unknown): BakedModel {
const { min, max } = boundsOf(mesh);
const tags: Record<string, number> = {};
for (const f of mesh.faces) if (f.tag) tags[f.tag] = (tags[f.tag] ?? 0) + 1;
- const triangleCount = triangles.reduce((n, t) => n + t.length, 0);
- const warnings: string[] = [];
+ const warnings: string[] = [...notes, ...(layoutNote ? [layoutNote] : [])];
+ if (triangleCount > HEAVY_TRIANGLES) warnings.push(`${triangleCount} triangles is a lot to draw: end with a \`decimate\`, and \`normalBake\` to keep the detail`);
if (openEdges) warnings.push(`${openEdges} open edge${openEdges > 1 ? 's' : ''}: the surface has holes you can see into`);
if (nonManifoldEdges) warnings.push(`${nonManifoldEdges} edge${nonManifoldEdges > 1 ? 's' : ''} shared by more than two faces, which a later bevel refuses: \`weld\` may have joined things that should stay apart, or on an organic skin two parts just touch, so overlap them or raise blend`);
if (flippedEdges) warnings.push(`${flippedEdges} edge${flippedEdges > 1 ? 's' : ''} between faces wound opposite ways: part of the surface faces inward`);
diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.ts
index 66e18cd25..ccef4b268 100644
--- a/pipeline/src/modeling/modelSource.ts
+++ b/pipeline/src/modeling/modelSource.ts
@@ -19,6 +19,7 @@ import { uvStep } from './modelUv';
import { lathe, loft } from './surfaces';
import { subdivide } from './subdivide';
import { decimate, triangleCount } from './decimate';
+import { displace, DISPLACE_PATTERNS } from './displace';
import { checkAnimations, checkController, checkRig, checkShapes, type AnimationSource, type ControllerSource, type RigSource, type ShapeSource } from './rig';
import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
@@ -63,7 +64,7 @@ export interface NormalBakeSource {
}
type Kind = 'number' | 'integer' | 'boolean' | 'string' | 'vec3' | 'number|vec3' | 'number|vec2' | 'number|numbers'
- | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2';
+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2' | 'pattern' | 'near';
interface OpSpec {
params: Record<string, Kind>;
@@ -95,6 +96,7 @@ export const MODEL_OPS: Record<string, OpSpec> = {
slice: { params: { faces: 'faces', axis: 'axis', at: 'number|numbers' }, required: ['axis', 'at'], run: ops.slice as OpSpec['run'], says: 'cuts faces across planes, making the seams a window sits between' },
boolean: { params: { operation: 'operation', with: 'faces', from: 'faces', keep: 'boolean', tag: 'string', color: 'color' }, required: ['operation', 'with'], run: booleanOp as unknown as OpSpec['run'], says: 'cuts or joins closed solids: subtract `with` from `from` makes a real hole' },
subdivide: { params: { faces: 'faces', levels: 'integer', crease: 'number' }, required: [], run: subdivide as unknown as OpSpec['run'], says: 'rounds whole shells into smooth surfaces, keeping edges sharper than `crease` degrees' },
+ displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', axis: 'axis', mirror: 'axis', detail: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: displace as unknown as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave or scratches' },
decimate: { params: { faces: 'faces', ratio: 'number', triangles: 'integer', error: 'number' }, required: [], run: decimate as unknown as OpSpec['run'], says: 'leaves fewer triangles over the same surface: `ratio` to keep or `triangles` to end with, stopping sooner if the surface would move more than `error` (default 0.02) of its size' },
uv: { params: { faces: 'faces', mode: 'uvmode', axis: 'string', at: 'vec3', scale: 'number|vec2only', repeat: 'number|vec2only', offset: 'vec2', rotate: 'number' }, required: ['mode'], run: uvStep as unknown as OpSpec['run'], says: 'sets how faces take a texture: box, planar, cylinder or sphere' },
delete: { params: { faces: 'faces' }, required: ['faces'], run: ops.deleteFaces as OpSpec['run'], says: 'removes faces, leaving a hole' },
@@ -252,6 +254,11 @@ const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {
uvmode: (v) => (['box', 'planar', 'cylinder', 'sphere'].includes(v as string) ? null : 'must be box, planar, cylinder or sphere'),
'number|vec2only': (v) => (isNum(v) || isNums(v, 2) ? null : 'must be a number or [u, v]'),
vec2: (v) => (isNums(v, 2) ? null : 'must be [u, v]'),
+ pattern: (v) => (DISPLACE_PATTERNS.includes(v as never) ? null : `must be one of ${DISPLACE_PATTERNS.join(', ')}`),
+ near: (v) => {
+ const n = v as { at?: unknown; radius?: unknown } | null;
+ return typeof n === 'object' && n !== null && isNums(n.at, 3) && isNum(n.radius) && Object.keys(n).every((k) => k === 'at' || k === 'radius') ? null : 'must be { at: [x, y, z], radius }';
+ },
noise: checkNoise,
pivot: (v) => (v === 'center' || v === 'base' || isNums(v, 3) ? null : 'must be "center", "base" or [x, y, z]'),
};
@@ -368,6 +375,8 @@ export interface ModelBuild {
steps: StepReport[];
/** The surface `normalBake` carries, as the steps stood then. */
high?: PolyMesh;
+ /** What steps wanted said, in their order. */
+ notes: string[];
}
/** Runs the steps in order. A step that cannot run throws a {@link ModelBuildError} naming it. */
@@ -378,6 +387,7 @@ export function buildPolyMesh(source: ModelSource): ModelBuild {
// After this step, the surface is the one to carry: the one named, or the one before the last decimate.
const highAfter = !bake ? -2 : bake.from !== undefined ? source.steps.findIndex((s) => s.id === bake.from) : source.steps.map((s) => s.op).lastIndexOf('decimate') - 1;
let high: PolyMesh | undefined;
+ const notes: string[] = [];
source.steps.forEach((step, index) => {
const { id, op, ...params } = step;
const before = op === 'decimate' ? triangleCount(mesh) : 0;
@@ -386,10 +396,14 @@ export function buildPolyMesh(source: ModelSource): ModelBuild {
} catch (e) {
throw new ModelBuildError(`${stepLabel(step, index)}: ${e instanceof Error ? e.message : String(e)}`, index, id ?? null, op);
}
+ if (mesh.notes) {
+ for (const note of mesh.notes) notes.push(`${stepLabel(step, index)}: ${note}`);
+ mesh = { positions: mesh.positions, faces: mesh.faces };
+ }
steps.push({ index, ...(id ? { id } : {}), op, faces: mesh.faces.length, ...(op === 'decimate' ? { trianglesBefore: before, trianglesAfter: triangleCount(mesh) } : {}) });
if (index === highAfter) high = compact(mesh);
});
- return { mesh: compact(mesh), steps, ...(high ? { high } : {}) };
+ return { mesh: compact(mesh), steps, notes, ...(high ? { high } : {}) };
}
// ---- Edits: changing a source without restating it ------------------------------
diff --git a/pipeline/src/modeling/normalBake.ts b/pipeline/src/modeling/normalBake.ts
index 64e554e54..26fecd866 100644
--- a/pipeline/src/modeling/normalBake.ts
+++ b/pipeline/src/modeling/normalBake.ts
@@ -25,6 +25,10 @@ const GUTTER = 16;
const LEAF = 4;
/** Above this share of texels finding no surface, the map is probably missing what it was made for. */
const MISSED_WARNING = 0.05;
+/** Degrees of mean bend past which a map is mostly slopes too steep to shade. */
+const STEEP_BEND = 25;
+/** Share of the image below which the surface broke into so many pieces that the map's resolution is mostly gone. */
+const SPARSE_COVERAGE = 0.1;
export interface NormalBakeReport {
size: number;
@@ -292,6 +296,8 @@ export function bakeNormalMap(model: BakedModel): NormalMap {
const warnings: string[] = [];
const missedShare = inside ? missed / inside : 1;
if (missedShare > MISSED_WARNING) warnings.push(`${Math.round(missedShare * 100)}% of the normal map found no surface within ${distance.toPrecision(3)} and is flat: raise normalBake.distance, or decimate less`);
+ if (hits && (bend / hits) * 180 / Math.PI > STEEP_BEND) warnings.push(`the map bends light by ${Math.round((bend / hits) * 180 / Math.PI)} degrees on average, steeper than a normal map draws well: dark bands and lost shape. Lower the amplitude of a displace against its scale`);
+ if (inside / (size * size) < SPARSE_COVERAGE) warnings.push(`the surface broke into so many pieces that they fill only ${Math.round((inside / (size * size)) * 100)}% of the map, so most of its resolution is lost: lower the amplitude before the decimate, or keep more triangles`);
if (from <= to) warnings.push(`the surface baked from has ${from} triangles and this one ${to}: there is no detail to carry. normalBake.from should name a step before the decimate`);
return {
size, rgba, warnings,
diff --git a/pipeline/src/modeling/organic.ts b/pipeline/src/modeling/organic.ts
index bc84e036e..1d88e9595 100644
--- a/pipeline/src/modeling/organic.ts
+++ b/pipeline/src/modeling/organic.ts
@@ -76,7 +76,7 @@ type Eval = (x: number, y: number, z: number) => number;
// ---- Noise: value noise, seeded and platform-independent, so a bake is the same everywhere ----
-function hash3(x: number, y: number, z: number, seed: number): number {
+export function hash3(x: number, y: number, z: number, seed: number): number {
let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(z, 2147483647 - 1274126177) + Math.imul(seed, 1442695041);
h = Math.imul(h ^ (h >>> 13), 1274126177);
h ^= h >>> 16;
diff --git a/pipeline/src/modeling/polyMesh.ts b/pipeline/src/modeling/polyMesh.ts
index e46335524..9008b7773 100644
--- a/pipeline/src/modeling/polyMesh.ts
+++ b/pipeline/src/modeling/polyMesh.ts
@@ -42,6 +42,8 @@ export interface FaceUv {
export interface PolyMesh {
positions: Vec3[];
faces: Face[];
+ /** What the step that just ran wants said in the report. Taken off before the next one runs. */
+ notes?: string[];
}
export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
diff --git a/pipeline/tests/modeling-displace.test.ts b/pipeline/tests/modeling-displace.test.ts
new file mode 100644
index 000000000..58442d48a
--- /dev/null
+++ b/pipeline/tests/modeling-displace.test.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Fine detail pushed out of a surface: that it moves what was asked, by what was asked, and stays one surface. */
+import { beforeAll, describe, expect, it } from 'vitest';
+import { bakeModel, bakeNormalMap, prepareModeling, validateModelSource, type BakedModel, type ModelStep } from '../src/modeling';
+import { DISPLACE_PATTERNS, MAX_DISPLACE_TRIANGLES } from '../src/modeling/displace';
+
+beforeAll(() => prepareModeling());
+
+const model = (...steps: ModelStep[]): BakedModel => bakeModel({ version: 1, steps });
+const ball: ModelStep = { op: 'sphere', radius: 1, rings: 32, sides: 64, tag: 'ball' };
+const sheet: ModelStep = { op: 'plane', size: 2, tag: 'sheet' };
+
+/** Not Math.min(...values): a dense model has more vertices than a call has room for arguments. */
+const range = (values: readonly number[]): [number, number] => values.reduce<[number, number]>(([lo, hi], x) => [Math.min(lo, x), Math.max(hi, x)], [Infinity, -Infinity]);
+
+const radii = (m: BakedModel): number[] => m.poly.positions.map((p) => Math.hypot(p[0], p[1], p[2]));
+
+/** Spread of the heights over a flat sheet, and their average. */
+function heights(m: BakedModel): { min: number; max: number; mean: number } {
+ const [min, max] = range(m.poly.positions.map((p) => p[1]));
+ return { min, max, mean: m.poly.positions.reduce((sum, p) => sum + p[1], 0) / m.poly.positions.length };
+}
+
+describe('displace', () => {
+ it.each(DISPLACE_PATTERNS)('%s moves a closed ball within its amplitude, and leaves it closed', (pattern) => {
+ const m = model(ball, { op: 'displace', pattern, amplitude: 0.05, scale: 0.3 });
+ expect(m.report.openEdges).toBe(0);
+ expect(m.report.nonManifoldEdges).toBe(0);
+ expect(m.report.insideOutShells).toBe(0);
+ const [lo, hi] = range(radii(m));
+ expect(hi - lo).toBeGreaterThan(0.005);
+ expect(hi).toBeLessThan(1 + 0.05 * 1.5);
+ expect(lo).toBeGreaterThan(0.95 - 0.05 * 1.5);
+ });
+
+ it('is the same every time, and a seed makes another', () => {
+ const a = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.4 });
+ const b = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.4 });
+ const c = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.4, seed: 9 });
+ expect(a.poly.positions).toEqual(b.poly.positions);
+ expect(a.poly.positions).not.toEqual(c.poly.positions);
+ });
+
+ it('splits a flat plane enough to show the pattern, and the rim does not move', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'scales', amplitude: 0.1, scale: 0.5 });
+ expect(m.report.triangles).toBeGreaterThan(100);
+ // Nothing but the rim is open, and each of its corners is where it was.
+ for (const corner of [[-1, 0, 1], [1, 0, 1], [1, 0, -1], [-1, 0, -1]]) {
+ expect(m.poly.positions.some((p) => p.every((x, k) => Math.abs(x - corner[k]!) < 1e-3 + 0.2))).toBe(true);
+ }
+ expect(m.report.flippedEdges).toBe(0);
+ expect(heights(m).max - heights(m).min).toBeGreaterThan(0.05);
+ });
+
+ it('cracks and wrinkles are dents at a positive amplitude and ridges at a negative one', () => {
+ for (const pattern of ['cracks', 'wrinkles', 'pores', 'scratches'] as const) {
+ const down = heights(model(sheet, { op: 'displace', pattern, amplitude: 0.1, scale: 0.5 }));
+ const up = heights(model(sheet, { op: 'displace', pattern, amplitude: -0.1, scale: 0.5 }));
+ expect(down.max).toBeLessThan(0.001);
+ expect(down.min).toBeLessThan(-0.01);
+ expect(up.min).toBeGreaterThan(-0.001);
+ expect(up.max).toBeGreaterThan(0.01);
+ }
+ });
+
+ it('`near` moves only inside its radius', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.2, near: { at: [0.5, 0, 0], radius: 0.3 } });
+ let moved = 0;
+ for (const p of m.poly.positions) {
+ const inside = Math.hypot(p[0] - 0.5, p[2]) < 0.3 + 0.03;
+ if (Math.abs(p[1]) > 1e-6) { moved++; expect(inside).toBe(true); }
+ }
+ expect(moved).toBeGreaterThan(20);
+ });
+
+ it('`faces` leaves the others where they were, with no gap between', () => {
+ const m = model(
+ { op: 'box', size: 2, tag: 'body' },
+ { op: 'tag', faces: '+y', tag: 'top' },
+ { op: 'displace', faces: 'top', pattern: 'bumps', amplitude: 0.1, scale: 0.4 },
+ );
+ expect(m.report.openEdges).toBe(0);
+ expect(m.report.nonManifoldEdges).toBe(0);
+ expect(m.report.tags.body).toBe(5);
+ expect(m.report.tags.top).toBeGreaterThan(50);
+ // The walls are still the walls, well below anywhere the top can dent to.
+ for (const p of m.poly.positions) if (p[1] < 0.8) expect(Math.max(Math.abs(p[0]), Math.abs(p[2]))).toBeCloseTo(1, 5);
+ // And the rim they meet the top at stayed at the top's height.
+ const rim = m.poly.positions.filter((p) => Math.max(Math.abs(p[0]), Math.abs(p[2])) > 0.9999 && p[1] > 0.8);
+ expect(rim.length).toBeGreaterThan(8);
+ for (const p of rim) expect(p[1]).toBeCloseTo(1, 5);
+ });
+
+ it('splits only what its pattern needs: an edge shared with a face outside does not make it run away', () => {
+ const m = model({ op: 'box', size: 2 }, { op: 'tag', faces: '+y', tag: 'top' }, { op: 'displace', faces: 'top', pattern: 'bumps', amplitude: 0.1, scale: 0.4 });
+ expect(m.report.triangles).toBeLessThan(100000);
+ expect(m.report.warnings.join()).not.toMatch(/stopped at/);
+ });
+
+ it('`near` reaches a large face with every corner outside it', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.1, near: { at: [0, 0, 0], radius: 0.2 } });
+ expect(m.poly.positions.some((p) => Math.abs(p[1]) > 0.005)).toBe(true);
+ });
+
+ it('a model too dense to lay out for light still builds, and says what it went without', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.01, scale: 0.1, detail: 0.004 });
+ expect(m.report.warnings.join()).toMatch(/no lightmap UV/);
+ }, 60000);
+
+ it('keeps paint and tags on what it splits', () => {
+ const m = model({ ...sheet, color: [0.2, 0.4, 0.6] }, { op: 'displace', pattern: 'bumps', amplitude: 0.05, scale: 0.3 });
+ for (const f of m.poly.faces) { expect(f.color).toEqual([0.2, 0.4, 0.6, 1]); expect(f.tag).toBe('sheet'); }
+ });
+
+ it('`stretch` draws features out along an axis', () => {
+ const rough = (stretch: [number, number, number]) => {
+ const m = model(sheet, { op: 'displace', pattern: 'ribs', amplitude: 0.1, scale: 0.4, axis: 'x', stretch, detail: 0.05 });
+ return heights(m).max - heights(m).min;
+ };
+ // Stretched past the sheet's size along the axis it runs across, ribs barely have room to rise and fall.
+ expect(rough([1, 1, 1])).toBeGreaterThan(0.15);
+ expect(rough([40, 1, 1])).toBeLessThan(0.15);
+ });
+
+ it('`mirror` gives both sides the same', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.1, scale: 0.3, mirror: 'x' });
+ const at = new Map(m.poly.positions.map((p) => [`${p[0].toFixed(4)},${p[2].toFixed(4)}`, p[1]]));
+ let pairs = 0;
+ for (const p of m.poly.positions) {
+ const other = at.get(`${(-p[0]).toFixed(4)},${p[2].toFixed(4)}`);
+ if (other !== undefined) { expect(other).toBeCloseTo(p[1], 5); pairs++; }
+ }
+ expect(pairs).toBeGreaterThan(50);
+ });
+
+ it('`detail` sets how far it splits', () => {
+ const coarse = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.05, scale: 0.5, detail: 0.5 });
+ const fine = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.05, scale: 0.5, detail: 0.1 });
+ expect(fine.report.triangles).toBeGreaterThan(coarse.report.triangles * 4);
+ });
+
+ it('stops at its budget and says so, rather than asking for more memory than there is', () => {
+ const m = model({ op: 'plane', size: 100 }, { op: 'displace', pattern: 'bumps', amplitude: 0.01, scale: 0.05 });
+ expect(m.report.triangles).toBeLessThanOrEqual(MAX_DISPLACE_TRIANGLES);
+ expect(m.report.warnings.join()).toMatch(/stopped at 1500000 triangles/);
+ }, 60000);
+
+ it('a heavy result says what to do about it', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'bumps', amplitude: 0.01, scale: 0.1, detail: 0.004 });
+ expect(m.report.triangles).toBeGreaterThan(300000);
+ expect(m.report.warnings.join()).toMatch(/end with a `decimate`/);
+ }, 60000);
+
+ it('says when a pattern is too steep for a map to draw', () => {
+ const steep = bakeModel({ version: 1, normalBake: { size: 128 }, steps: [ball, { op: 'displace', pattern: 'ribs', amplitude: 0.1, scale: 0.1 }, { op: 'decimate', triangles: 400, error: 0.5 }] });
+ const map = bakeNormalMap(steep);
+ expect(map.report.meanBend, JSON.stringify(map.report)).toBeGreaterThan(25);
+ expect(map.warnings.join()).toMatch(/steeper than a normal map draws well/);
+ }, 60000);
+
+ it('scratches are lines, not dots: where one is, it runs on', () => {
+ const m = model(sheet, { op: 'displace', pattern: 'scratches', amplitude: 0.1, scale: 0.5, width: 0.1, detail: 0.008 });
+ // Bin the cut into a grid. Dots would leave cells apart; lines run through the grid, so most cut cells have a cut neighbour and the longest run is long.
+ const N = 125;
+ const cut = new Uint8Array(N * N);
+ for (const p of m.poly.positions) if (p[1] < -0.02) cut[Math.min(N - 1, Math.floor((p[2] + 1) / 2 * N)) * N + Math.min(N - 1, Math.floor((p[0] + 1) / 2 * N))] = 1;
+ const seen = new Uint8Array(N * N);
+ let largest = 0;
+ for (let i = 0; i < N * N; i++) {
+ if (!cut[i] || seen[i]) continue;
+ let size = 0;
+ const stack = [i];
+ seen[i] = 1;
+ while (stack.length) {
+ const at = stack.pop()!;
+ size++;
+ const [x, y] = [at % N, Math.floor(at / N)];
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+ const [qx, qy] = [x + dx, y + dy];
+ if (qx < 0 || qy < 0 || qx >= N || qy >= N) continue;
+ const q = qy * N + qx;
+ if (cut[q] && !seen[q]) { seen[q] = 1; stack.push(q); }
+ }
+ }
+ largest = Math.max(largest, size);
+ }
+ // A pore of this width would cover a handful of cells.
+ expect(largest).toBeGreaterThan(15);
+ }, 60000);
+
+ it('what it adds survives a decimate as a normal map', () => {
+ const without = bakeModel({ version: 1, normalBake: { size: 128 }, steps: [ball, { op: 'decimate', triangles: 400, error: 0.3 }] });
+ const withIt = bakeModel({ version: 1, normalBake: { size: 128 }, steps: [ball, { op: 'displace', pattern: 'wrinkles', amplitude: 0.03, scale: 0.3 }, { op: 'decimate', triangles: 400, error: 0.3 }] });
+ expect(bakeNormalMap(withIt).report.meanBend).toBeGreaterThan(bakeNormalMap(without).report.meanBend + 2);
+ }, 60000);
+
+ it('refuses what cannot be meant, naming the step', () => {
+ expect(() => model(ball, { op: 'displace', pattern: 'tartan', amplitude: 1, scale: 1 })).toThrow(/pattern must be one of/);
+ expect(() => model(ball, { op: 'displace', pattern: 'bumps', amplitude: 1 })).toThrow(/scale is required/);
+ expect(() => model(ball, { op: 'displace', pattern: 'bumps', amplitude: 1, scale: -1 })).toThrow(/step 1.*must be positive/);
+ expect(() => model(ball, { op: 'displace', pattern: 'bumps', amplitude: 1, scale: 1, near: { at: [9, 9, 9], radius: 1 } })).toThrow(/no surface/);
+ expect(() => validateModelSource({ steps: [ball, { op: 'displace', pattern: 'bumps', amplitude: 1, scale: 1, near: { at: [0, 0], radius: 1 } }] })).toThrow(/near must be/);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index e054ac249..aba132556 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3872,6 +3872,10 @@ export const NOTED = {
{"note":"A linear game looks the same on every Play."},
"test(editor): a scene draws the same on every Play, with effects or without":
{"internal":"a check, for a fix the engine commit carries"},
+ "feat(modeling): a displace step carves wrinkles, cracks, scales and weave into a surface":
+ {"note":"An AI building a model can carve fine detail into it."},
+ "feat(mcp): model_write carves fine detail, and a check takes every pattern through the bake":
+ {"note":"An AI building a model can carve fine detail into it."},
"feat(modeling): a model thins to a few triangles and keeps its detail as a normal map":
{"note":"An AI building a model can make it light and keep its detail."},
"feat(mcp): model_write thins a model and bakes its detail, and a check compares it lit against the dense one":