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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(modeling): a model source names its numbers and repeats its steps, and a leaf is a strip that reads a picture - params, sums written "=length * 0.4", repeat over rows and let; a strip step for a band with no thickness and a picture along it, material.texture for the picture, and an up for loft; a palm is six steps written and a third of the triangles
yhh641f0da4e09f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d0b1c4b52..04850ee84 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,8 +16,10 @@ published separately; it ships inside the editor.### Added+- **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.+- **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.- **Text has letter spacing.** `Text.letterSpacing` is extra space after every glyph, in the same px as `fontSize`; a negative value draws the glyphs closer. The layout always took a spacing, and `measureText` did, but the component had no field for it and nothing handed one over, so a label could not be spaced. Wrapping, alignment, `Ellipsis` and `Shrink` measure with it, `Shrink` scales it with the type, and it is in the Details panel beside Line Height. The default, 0, is the text as it was.diff --git a/desktop b/desktopindex 1cfa0589b..1626f3e05 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 1cfa0589b8e81741bd8cb8f77a1e10ba8093aca7+Subproject commit 1626f3e055fa07ffb9e96949eb79d2b7655d6d9ediff --git a/pipeline/src/modeling/booleans.ts b/pipeline/src/modeling/booleans.tsindex eaab23863..54dc67aba 100644--- a/pipeline/src/modeling/booleans.ts+++ b/pipeline/src/modeling/booleans.ts@@ -34,7 +34,9 @@ interface ManifoldEngine {let engine: ManifoldEngine | null = null;/** Whether any step of a parsed source needs {@link prepareModeling} first. */-export const needsPreparing = (steps: readonly { op: string }[]): boolean => steps.some((s) => s.op === 'boolean' || s.op === 'decimate');+export const needsPreparing = (steps: readonly { op: string; steps?: unknown }[]): boolean => steps.some((s) => s.op === 'boolean' || s.op === 'decimate'+ // What a repeat holds runs too.+ || (Array.isArray(s.steps) && needsPreparing(s.steps as { op: string }[])));/*** Loads what `boolean` and `decimate` steps run on; once is enough. `wasmUrl` is for a bundled host,diff --git a/pipeline/src/modeling/index.ts b/pipeline/src/modeling/index.tsindex fd75c2537..19e0e137e 100644--- a/pipeline/src/modeling/index.ts+++ b/pipeline/src/modeling/index.ts@@ -5,7 +5,7 @@* Pure: no filesystem and no engine instance, so the editor and a test run the same code.*/export {- MODEL_OPS, MODEL_SOURCE_EXT, MODEL_SOURCE_VERSION, ModelBuildError, UNOFFERED_OPS, applyModelEdits, buildPolyMesh, describeModelOps, validateModelSource,+ MODEL_OPS, MODEL_SOURCE_EXT, MODEL_SOURCE_VERSION, ModelBuildError, UNOFFERED_OPS, applyModelEdits, buildPolyMesh, describeModelOps, expandModelSource, validateModelSource,type ModelEdit, type ModelSource, type NormalBakeSource, type ModelStep, type StepReport,} from './modelSource';export { organic, ORGANIC_DEFAULT_RESOLUTION, ORGANIC_MAX_RESOLUTION, type OrganicParams, type OrganicPart } from './organic';@@ -15,3 +15,4 @@ export { bakeNormalMap, type NormalBakeReport, type NormalMap } from './normalBaexport type { FaceSelector } from './polyMesh';export { DEFAULT_MODEL_VIEWS, MODEL_VIEWS, renderModelSheet, renderRigSheet, type ModelSheet, type ModelViewName, type RigViewOptions } from './modelViews';export { controllerOf, jointPositions, morphedPositions, posedPositions, prefabOf, timelineOf, type AnimationSource, type ControllerSource, type PoseSolve, type PreviewGround, type RigSource, type ShapeSource } from './rig';+export { EXPR_HELP } from './modelExpr';diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.tsindex baa4b7fa1..17af0078b 100644--- a/pipeline/src/modeling/modelBake.ts+++ b/pipeline/src/modeling/modelBake.ts@@ -15,7 +15,7 @@ import { triangulateFace } from './triangulate';import { faceUvs } from './modelUv';import { adjustWeights, bindMatrices, computeWeights, computeWornWeights, drapeRig, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type RigSpring, type SkinWeights } from './rig';import type { NormalBakeReport } from './normalBake';-import { buildPolyMesh, validateModelSource, type ModelSource, type StepReport } from './modelSource';+import { buildPolyMesh, expandModelSource, validateModelSource, type ModelSource, type StepReport } from './modelSource';import {boundsOf, collectEdges, cross, dot, faceArea, faceNormal, length, normalize, sub,type PolyMesh, type Vec3,@@ -330,7 +330,8 @@ export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, ma/** 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);+ // The plain steps: the report counts them, and a step's own fields are read back by its index among them.+ const source = expandModelSource(validateModelSource(raw));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');diff --git a/pipeline/src/modeling/modelExpand.ts b/pipeline/src/modeling/modelExpand.tsnew file mode 100644index 000000000..82eb6a455--- /dev/null+++ b/pipeline/src/modeling/modelExpand.ts@@ -0,0 +1,180 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelExpand.ts — a model source's names, sums and repeats, turned into the plain steps the build runs.+ *+ * A model is the steps that build it, and a shape with ten fronds was ten times the steps: the numbers that make a+ * frond were written out for each, so making every frond a little longer was ten edits. Three things take that away,+ * and none of them is a programming language:+ *+ * * `params` names numbers once: `{ "length": 1.9 }`.+ * * A value written `"=length * 0.4"` is a sum over those names (modelExpr.ts).+ * * `{ "op": "repeat", "over": [ ...rows ], "steps": [ ... ] }` runs its steps once for each row, the row's fields+ * being names inside it; `count` in place of `over` runs them that many times. `{ "op": "let", ... }` names a+ * value for the steps that follow it.+ *+ * What comes out is a source of plain steps with plain numbers, which is what everything downstream reads. What+ * is saved, and what an edit changes, is the source as written.+ */+import { evaluate, type ExprScope, type ExprValue } from './modelExpr';++const MAX_STEPS = 5000;+const MAX_DEPTH = 6;+const RESERVED = new Set(['i', 't', 'n', 'pi']);++/** Where an expanded step came from, for a refusal to name: "step 3 (repeat) row 2 > step 1 (loft)". */+export interface ExpandedStep {+ step: Record<string, unknown>;+ where: string;+ /** The top-level step of the source as written. */+ index: number;+}++export interface Expansion {+ steps: ExpandedStep[];+ /** Whether the source used a name, a sum or a repeat at all. */+ used: boolean;+}++export class ModelExpandError extends Error {+ constructor(message: string, readonly index: number | null) { super(message); }+}++const isSum = (v: unknown): v is string => typeof v === 'string' && v.startsWith('=');++function resolve(value: unknown, scope: ExprScope, what: string): unknown {+ if (isSum(value)) {+ try {+ return evaluate(value.slice(1), scope);+ } catch (e) {+ throw new Error(`${what} ${JSON.stringify(value)}: ${(e as Error).message}`);+ }+ }+ if (Array.isArray(value)) return value.map((v, i) => resolve(v, scope, `${what}[${i}]`));+ if (typeof value === 'object' && value !== null) {+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolve(v, scope, `${what}.${k}`)]));+ }+ return value;+}++const holdsSum = (value: unknown): boolean =>+ isSum(value) || (Array.isArray(value) ? value.some(holdsSum) : typeof value === 'object' && value !== null && Object.values(value).some(holdsSum));++function asValue(value: unknown, what: string): ExprValue {+ const ok = (v: unknown): boolean => (typeof v === 'number' ? Number.isFinite(v) : Array.isArray(v) && v.every(ok));+ if (!ok(value)) throw new Error(`${what} must be a number, or a list of them`);+ return value as ExprValue;+}++/** Whether @p steps hold anything this file turns into something else. */+export function needsExpanding(source: { params?: unknown; steps?: unknown }): boolean {+ if (source.params !== undefined) return true;+ return Array.isArray(source.steps) && source.steps.some((s) => typeof s === 'object' && s !== null+ && ((s as { op?: unknown }).op === 'repeat' || (s as { op?: unknown }).op === 'let' || holdsSum(s)));+}++/** The names a source's `params` give, each worked out in the order written: a later one may use an earlier. */+export function paramScope(params: unknown): Map<string, ExprValue> {+ const scope = new Map<string, ExprValue>();+ if (params === undefined) return scope;+ if (typeof params !== 'object' || params === null || Array.isArray(params)) throw new ModelExpandError('params must be an object of names', null);+ for (const [name, raw] of Object.entries(params)) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ModelExpandError(`params: "${name}" is not a name; letters, digits and _, not starting with a digit`, null);+ if (RESERVED.has(name)) throw new ModelExpandError(`params: "${name}" is taken: a repeat gives i, t and n, and pi is pi`, null);+ try {+ scope.set(name, asValue(resolve(raw, scope, `params.${name}`), `params.${name}`));+ } catch (e) {+ throw new ModelExpandError((e as Error).message, null);+ }+ }+ return scope;+}++/** The plain steps @p source builds from. Throws a {@link ModelExpandError} naming the step as written. */+export function expandSteps(source: { params?: unknown; steps: readonly unknown[] }): Expansion {+ const out: ExpandedStep[] = [];+ let used = source.params !== undefined;++ const run = (steps: readonly unknown[], outer: ExprScope, path: string, top: number | null, depth: number): void => {+ // A `let` names a value for the steps after it in this list, and in the lists inside them.+ const scope = new Map(outer);+ steps.forEach((raw, i) => {+ const index = top ?? i;+ const fail = (what: string): never => { throw new ModelExpandError(`${where}: ${what}`, index); };+ const op = typeof raw === 'object' && raw !== null ? (raw as { op?: unknown }).op : undefined;+ const where = `${path}step ${i}${typeof op === 'string' ? ` (${op})` : ''}`;+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ out.push({ step: raw as never, where, index });+ return;+ }+ const step = raw as Record<string, unknown>;++ if (op === 'let') {+ used = true;+ for (const [name, value] of Object.entries(step)) {+ if (name === 'op') continue;+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) fail(`"${name}" is not a name`);+ if (RESERVED.has(name)) fail(`"${name}" is taken: a repeat gives i, t and n, and pi is pi`);+ try {+ scope.set(name, asValue(resolve(value, scope, name), name));+ } catch (e) {+ fail((e as Error).message);+ }+ }+ return;+ }++ if (op === 'repeat') {+ used = true;+ if (depth >= MAX_DEPTH) fail(`repeats go ${MAX_DEPTH} deep and no further`);+ for (const key of Object.keys(step)) if (!['op', 'count', 'over', 'steps'].includes(key)) fail(`unknown field "${key}"; repeat takes count or over, and steps`);+ if (!Array.isArray(step.steps) || step.steps.length === 0) fail('`steps` is what it repeats: give one or more');+ if ((step.count === undefined) === (step.over === undefined)) fail('say how many times with one of `count` or `over`');+ let rows: Record<string, unknown>[];+ try {+ if (step.over !== undefined) {+ if (!Array.isArray(step.over) || step.over.length === 0 || step.over.some((r) => typeof r !== 'object' || r === null || Array.isArray(r))) {+ throw new Error('`over` must be a list of rows, each an object of names');+ }+ rows = step.over as Record<string, unknown>[];+ } else {+ const count = resolve(step.count, scope, 'count');+ if (!Number.isInteger(count) || (count as number) < 1) throw new Error(`count ${JSON.stringify(count)} must be a whole number of 1 or more`);+ rows = Array.from({ length: count as number }, () => ({}));+ }+ } catch (e) {+ return fail((e as Error).message);+ }+ rows.forEach((row, r) => {+ const inner = new Map(scope);+ inner.set('i', r);+ inner.set('n', rows.length);+ inner.set('t', rows.length > 1 ? r / (rows.length - 1) : 0);+ for (const [name, value] of Object.entries(row)) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || RESERVED.has(name)) fail(`row ${r}: "${name}" cannot be a name`);+ try {+ inner.set(name, asValue(resolve(value, inner, name), `row ${r}: ${name}`));+ } catch (e) {+ fail((e as Error).message);+ }+ }+ run(step.steps as unknown[], inner, `${where} row ${r} > `, index, depth + 1);+ });+ return;+ }++ if (!used && holdsSum(step)) used = true;+ let plain: Record<string, unknown>;+ try {+ plain = Object.fromEntries(Object.entries(step).map(([k, v]) => [k, k === 'op' || k === 'id' ? v : resolve(v, scope, `\`${k}\``)]));+ } catch (e) {+ return fail((e as Error).message);+ }+ out.push({ step: plain, where, index });+ if (out.length > MAX_STEPS) fail(`the repeats come to more than ${MAX_STEPS} steps`);+ });+ };++ run(source.steps, paramScope(source.params), '', null, 0);+ return { steps: out, used };+}diff --git a/pipeline/src/modeling/modelExpr.ts b/pipeline/src/modeling/modelExpr.tsnew file mode 100644index 000000000..3eea31b48--- /dev/null+++ b/pipeline/src/modeling/modelExpr.ts@@ -0,0 +1,298 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelExpr.ts — the sums a model source may hold in place of a number.+ *+ * A value written `"=length * 0.4"` is worked out when the model is built. It is arithmetic and nothing more: no+ * assignment, no branching, no way to loop. What it adds to plain numbers is vectors (a point is `[x, y, z]`,+ * and points add and scale) and the few makers a shape keeps asking for: a point round an axis, a line that+ * bends, a part of a line.+ *+ * Angles are degrees everywhere, as they are in every step.+ */+import { hash3 } from './hash';++export type ExprValue = number | ExprValue[];+export type ExprScope = ReadonlyMap<string, ExprValue>;++const DEG = Math.PI / 180;+const isVec = (v: ExprValue): v is number[] => Array.isArray(v) && v.every((x) => typeof x === 'number');++function num(v: ExprValue, what: string): number {+ if (typeof v !== 'number') throw new Error(`${what} must be a number, not a list`);+ return v;+}++function vec3(v: ExprValue, what: string): [number, number, number] {+ if (!isVec(v) || v.length !== 3) throw new Error(`${what} must be a point [x, y, z]`);+ return v as [number, number, number];+}++function points(v: ExprValue, what: string): [number, number, number][] {+ if (!Array.isArray(v) || v.length < 2 || !v.every((p) => isVec(p as ExprValue) && (p as number[]).length === 3)) {+ throw new Error(`${what} must be a line of two points or more`);+ }+ return v as [number, number, number][];+}++/** Number with number, or a list with a number or a list of its own length, item by item. */+function each(a: ExprValue, b: ExprValue, f: (x: number, y: number) => number, sign: string): ExprValue {+ if (typeof a === 'number' && typeof b === 'number') return f(a, b);+ if (Array.isArray(a) && typeof b === 'number') return a.map((x) => each(x, b, f, sign));+ if (typeof a === 'number' && Array.isArray(b)) return b.map((y) => each(a, y, f, sign));+ const [x, y] = [a as ExprValue[], b as ExprValue[]];+ if (x.length !== y.length) throw new Error(`\`${sign}\` between lists of ${x.length} and ${y.length}`);+ return x.map((v, i) => each(v, y[i]!, f, sign));+}++const len = (v: number[]): number => Math.hypot(...v);++/** Where a line of points is at @p t of its length, 0..1. */+function alongLine(line: [number, number, number][], t: number): [number, number, number] {+ const walked = [0];+ for (let i = 1; i < line.length; i++) walked.push(walked[i - 1]! + len(line[i]!.map((v, k) => v - line[i - 1]![k]!)));+ const want = Math.min(1, Math.max(0, t)) * walked.at(-1)!;+ let k = 1;+ while (k < line.length - 1 && walked[k]! < want) k++;+ const span = walked[k]! - walked[k - 1]!;+ const w = span > 0 ? (want - walked[k - 1]!) / span : 0;+ return line[k - 1]!.map((v, i) => v + (line[k]![i]! - v) * w) as [number, number, number];+}++type Fn = (args: ExprValue[]) => ExprValue;+const unary = (name: string, f: (x: number) => number): Fn => (a) => {+ if (a.length !== 1) throw new Error(`${name} takes one value`);+ return f(num(a[0]!, name));+};+const takes = (name: string, a: ExprValue[], min: number, max = min): void => {+ if (a.length < min || a.length > max) throw new Error(`${name} takes ${min === max ? min : `${min} to ${max}`} values, not ${a.length}`);+};++/** What a sum may call. Each says, in {@link EXPR_HELP}, what it gives. */+const FUNCTIONS: Record<string, Fn> = {+ sin: unary('sin', (x) => Math.sin(x * DEG)),+ cos: unary('cos', (x) => Math.cos(x * DEG)),+ tan: unary('tan', (x) => Math.tan(x * DEG)),+ asin: unary('asin', (x) => Math.asin(x) / DEG),+ acos: unary('acos', (x) => Math.acos(x) / DEG),+ atan: unary('atan', (x) => Math.atan(x) / DEG),+ sqrt: unary('sqrt', Math.sqrt),+ abs: unary('abs', Math.abs),+ floor: unary('floor', Math.floor),+ ceil: unary('ceil', Math.ceil),+ round: unary('round', Math.round),+ atan2: (a) => { takes('atan2', a, 2); return Math.atan2(num(a[0]!, 'atan2'), num(a[1]!, 'atan2')) / DEG; },+ min: (a) => { takes('min', a, 1, 99); return Math.min(...a.map((v) => num(v, 'min'))); },+ max: (a) => { takes('max', a, 1, 99); return Math.max(...a.map((v) => num(v, 'max'))); },+ clamp: (a) => { takes('clamp', a, 3); return Math.min(num(a[2]!, 'clamp'), Math.max(num(a[1]!, 'clamp'), num(a[0]!, 'clamp'))); },+ mix: (a) => {+ takes('mix', a, 3);+ const t = num(a[2]!, 'mix');+ return each(a[0]!, a[1]!, (x, y) => x + (y - x) * t, 'mix');+ },+ smooth: unary('smooth', (x) => { const t = Math.min(1, Math.max(0, x)); return t * t * (3 - 2 * t); }),+ /** The same number for the same key, 0..1 or between two given: a size that differs from copy to copy and not from build to build. */+ rand: (a) => {+ takes('rand', a, 1, 3);+ const r = hash3(num(a[0]!, 'rand'), 17, 91, 5) * 0.5 + 0.5;+ return a.length === 3 ? num(a[1]!, 'rand') + (num(a[2]!, 'rand') - num(a[1]!, 'rand')) * r : r;+ },+ len: (a) => { takes('len', a, 1); if (!isVec(a[0]!)) throw new Error('len takes a point'); return len(a[0] as number[]); },+ count: (a) => { takes('count', a, 1); if (!Array.isArray(a[0])) throw new Error('count takes a list'); return (a[0] as ExprValue[]).length; },+ norm: (a) => {+ takes('norm', a, 1);+ if (!isVec(a[0]!)) throw new Error('norm takes a point');+ const l = len(a[0] as number[]);+ if (!(l > 0)) throw new Error('norm of a point at the origin has no direction');+ return (a[0] as number[]).map((v) => v / l);+ },+ dot: (a) => { takes('dot', a, 2); const [p, q] = [vec3(a[0]!, 'dot'), vec3(a[1]!, 'dot')]; return p[0] * q[0] + p[1] * q[1] + p[2] * q[2]; },+ cross: (a) => {+ takes('cross', a, 2);+ const [p, q] = [vec3(a[0]!, 'cross'), vec3(a[1]!, 'cross')];+ return [p[1] * q[2] - p[2] * q[1], p[2] * q[0] - p[0] * q[2], p[0] * q[1] - p[1] * q[0]];+ },+ /** A point round the upright axis: `angle` from +z toward +x, `radius` out, `y` up. */+ polar: (a) => {+ takes('polar', a, 2, 3);+ const [angle, radius] = [num(a[0]!, 'polar'), num(a[1]!, 'polar')];+ return [Math.sin(angle * DEG) * radius, a[2] === undefined ? 0 : num(a[2], 'polar'), Math.cos(angle * DEG) * radius];+ },+ /**+ * A line that bends: from `start`, `length` long, leaning `from` degrees off upright where it begins and `to` where it+ * ends, toward `toward`. `power` above 1 keeps it straight for longer before it turns. A frond, a horn, a tail, a cable.+ */+ arc: (a) => {+ takes('arc', a, 5, 7);+ const start = vec3(a[0]!, 'arc start');+ const toward = vec3(a[1]!, 'arc toward');+ const flat = len([toward[0], toward[2]]);+ if (!(flat > 1e-9)) throw new Error('arc leans toward a direction, and straight up or down is not one');+ const lean: [number, number, number] = [toward[0] / flat, 0, toward[2] / flat];+ const [length, from, to] = [num(a[2]!, 'arc length'), num(a[3]!, 'arc from'), num(a[4]!, 'arc to')];+ const power = a[5] === undefined ? 1 : num(a[5], 'arc power');+ const steps = a[6] === undefined ? 10 : num(a[6], 'arc points');+ if (!(length > 0)) throw new Error('arc length must be positive');+ if (!Number.isInteger(steps) || steps < 1 || steps > 200) throw new Error('arc points must be a whole number, 1..200');+ const line: [number, number, number][] = [start];+ let at = start;+ for (let k = 1; k <= steps; k++) {+ const angle = (from + (to - from) * Math.pow((k - 0.5) / steps, power)) * DEG;+ const [up, out] = [(Math.cos(angle) * length) / steps, (Math.sin(angle) * length) / steps];+ at = [at[0] + lean[0] * out, at[1] + up, at[2] + lean[2] * out];+ line.push(at);+ }+ return line;+ },+ /** The part of a line between two shares of its length: where a stem carries its leaves. */+ part: (a) => {+ takes('part', a, 3);+ const line = points(a[0]!, 'part');+ const [from, to] = [num(a[1]!, 'part from'), num(a[2]!, 'part to')];+ if (!(from >= 0 && to <= 1 && from < to)) throw new Error('part takes shares of the length, 0..1, the first below the second');+ const walked = [0];+ for (let i = 1; i < line.length; i++) walked.push(walked[i - 1]! + len(line[i]!.map((v, k) => v - line[i - 1]![k]!)));+ const whole = walked.at(-1)!;+ const inside = line.filter((_, i) => walked[i]! > from * whole + 1e-9 && walked[i]! < to * whole - 1e-9);+ return [alongLine(line, from), ...inside, alongLine(line, to)];+ },+ /** Where a line is at a share of its length. */+ along: (a) => { takes('along', a, 2); return alongLine(points(a[0]!, 'along'), num(a[1]!, 'along')); },+ /** The way a line runs at a share of its length, one unit long. */+ heading: (a) => {+ takes('heading', a, 2);+ const line = points(a[0]!, 'heading');+ const t = num(a[1]!, 'heading');+ const [p, q] = [alongLine(line, Math.max(0, t - 0.01)), alongLine(line, Math.min(1, t + 0.01))];+ const d = q.map((v, i) => v - p[i]!);+ const l = len(d);+ if (!(l > 0)) throw new Error('heading of a line with no length');+ return d.map((v) => v / l);+ },+};++/** One line for the tool text: what a sum may use. */+export const EXPR_HELP = '+ - * / % ^ and ( ); points as [x, y, z], which add, and scale by a number; angles in degrees; pi; '+ + 'sin cos tan asin acos atan atan2 sqrt abs floor ceil round min max clamp(v, lo, hi) mix(a, b, t) smooth(t) rand(key, lo?, hi?); '+ + 'len norm dot cross; polar(angle, radius, y?) a point round the upright axis; '+ + 'arc(start, toward, length, from, to, power?, points?) a line that bends from one lean to another; '+ + 'part(line, from, to), along(line, t), heading(line, t); count(list); list[i]';++interface Token { kind: 'num' | 'name' | 'op'; text: string; at: number }++function tokens(source: string): Token[] {+ const out: Token[] = [];+ let i = 0;+ while (i < source.length) {+ const c = source[i]!;+ if (c === ' ' || c === '\t' || c === '\n') { i++; continue; }+ const number = /^(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?/.exec(source.slice(i));+ if (number) { out.push({ kind: 'num', text: number[0], at: i }); i += number[0].length; continue; }+ const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));+ if (name) { out.push({ kind: 'name', text: name[0], at: i }); i += name[0].length; continue; }+ if ('+-*/%^()[],'.includes(c)) { out.push({ kind: 'op', text: c, at: i }); i++; continue; }+ throw new Error(`"${c}" at ${i} is not part of a sum`);+ }+ return out;+}++/** Works @p source out against @p scope. Throws an Error that says what is wrong with it. */+export function evaluate(source: string, scope: ExprScope): ExprValue {+ const list = tokens(source);+ let at = 0;+ const peek = (): Token | undefined => list[at];+ const is = (text: string): boolean => peek()?.kind === 'op' && peek()!.text === text;+ const take = (text: string): void => {+ if (!is(text)) throw new Error(peek() ? `expected "${text}" at ${peek()!.at}, found "${peek()!.text}"` : `expected "${text}" at the end`);+ at++;+ };++ const listOf = (close: string): ExprValue[] => {+ const items: ExprValue[] = [];+ if (!is(close)) {+ do items.push(sum()); while (is(',') && ++at);+ }+ take(close);+ return items;+ };++ function primary(): ExprValue {+ const t = peek();+ if (!t) throw new Error('the sum stops short');+ at++;+ if (t.kind === 'num') return Number(t.text);+ if (t.kind === 'name') {+ if (is('(')) {+ at++;+ const fn = FUNCTIONS[t.text];+ if (!fn) throw new Error(`there is no ${t.text}(); there are ${Object.keys(FUNCTIONS).join(', ')}`);+ return fn(listOf(')'));+ }+ if (t.text === 'pi') return Math.PI;+ const value = scope.get(t.text);+ if (value === undefined) throw new Error(`"${t.text}" is not a name here; there are ${[...scope.keys()].join(', ') || 'none'}`);+ return value;+ }+ if (t.text === '(') { const v = sum(); take(')'); return v; }+ if (t.text === '[') return listOf(']');+ throw new Error(`"${t.text}" at ${t.at} is not where a value goes`);+ }++ function indexed(): ExprValue {+ let v = primary();+ while (is('[')) {+ at++;+ const i = num(sum(), 'an index');+ take(']');+ if (!Array.isArray(v)) throw new Error('only a list has items');+ if (!Number.isInteger(i) || i < 0 || i >= v.length) throw new Error(`item ${i} of a list of ${v.length}`);+ v = v[i]!;+ }+ return v;+ }++ function signed(): ExprValue {+ if (is('-')) { at++; return each(0, signed(), (x, y) => x - y, '-'); }+ if (is('+')) { at++; return signed(); }+ const base = indexed();+ if (is('^')) { at++; return Math.pow(num(base, 'what is raised'), num(signed(), 'a power')); }+ return base;+ }++ function product(): ExprValue {+ let v = signed();+ for (;;) {+ if (is('*')) {+ at++;+ const r = signed();+ if (Array.isArray(v) && Array.isArray(r)) throw new Error('two lists do not multiply; use dot(a, b), or scale one by a number');+ v = each(v, r, (x, y) => x * y, '*');+ } else if (is('/')) {+ at++;+ const r = num(signed(), 'what divides');+ if (r === 0) throw new Error('division by zero');+ v = each(v, r, (x, y) => x / y, '/');+ } else if (is('%')) {+ at++;+ const r = num(signed(), 'what divides');+ if (r === 0) throw new Error('division by zero');+ v = ((num(v, 'what is divided') % r) + r) % r;+ } else return v;+ }+ }++ function sum(): ExprValue {+ let v = product();+ for (;;) {+ if (is('+')) { at++; v = each(v, product(), (x, y) => x + y, '+'); }+ else if (is('-')) { at++; v = each(v, product(), (x, y) => x - y, '-'); }+ else return v;+ }+ }++ const value = sum();+ if (peek()) throw new Error(`"${peek()!.text}" at ${peek()!.at} is left over`);+ const finite = (v: ExprValue): boolean => (typeof v === 'number' ? Number.isFinite(v) : v.every(finite));+ if (!finite(value)) throw new Error('it comes to a value that is not a number');+ return value;+}diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex bbf2fc0d4..343b02685 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -28,6 +28,8 @@ import { HUMANOID_TAGS, humanoid, humanoidJoints, type HumanoidBuild } from './himport { VIEW_NAMES } from './surfaceLine';import { cardsOnly, hair, hasCards, type HairSway } from './hair';import { scatter } from './scatter';+import { strip } from './strip';+import { expandSteps, ModelExpandError, needsExpanding } from './modelExpand';import { checkAnimations, checkController, checkRig, checkShapes, resolveJoints, type AnimationSource, type ControllerSource, type RigSource, type ShapeSource } from './rig';import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';@@ -65,6 +67,12 @@ export interface ModelSource {shapes?: ShapeSource[];/** Which clip plays when: an `.esanimator` the prefab's Animator runs. */controller?: ControllerSource;+ /**+ * Numbers and points named once, for the sums in the steps: `{ "length": 1.9, "tip": [0, 2, 0] }`. A value written+ * `"=length * 0.4"` is worked out from them, and a later name may use an earlier one.+ */+ params?: Record<string, unknown>;+ /** As well as the ops, a step may be `repeat` (its `steps` once for each row of `over`, or `count` times) or `let` (names for the steps after it). */steps: ModelStep[];}@@ -79,6 +87,11 @@ export interface ModelMaterial {cutoff?: number;/** Light it gives off, linear [r, g, b], past 1 for what glows and blooms: fire, a lit window. With a colour bake, multiplied by the paint. */emissive?: readonly number[];+ /**+ * A picture the faces read where their mapping puts it, by project path: a leaf drawn with image_write, its alpha+ * the leaf's outline under `alpha: "cutout"`. A `strip` lays it from root to tip; other faces take it by their `uv`.+ */+ texture?: string;}export interface ModelAttachment {@@ -136,7 +149,8 @@ export const MODEL_OPS: Record<string, OpSpec> = {sphere: { params: { radius: 'number', rings: 'integer', sides: 'integer', ...PLACED }, required: ['radius'], run: ops.sphere as OpSpec['run'], says: 'adds a sphere' },prism: { params: { points: 'points', height: 'number', ...PLACED }, required: ['points', 'height'], run: ops.prism as OpSpec['run'], says: 'stands a floor plan of [x, z] points up to `height`' },lathe: { params: { profile: 'points', sides: 'integer', arc: 'number', closed: 'boolean', curve: 'integer', axis: 'axis', ...PLACED }, required: ['profile'], run: lathe as unknown as OpSpec['run'], says: 'turns a half-outline of [distance from axis, height] round an axis: a vase, a glass, a column' },- loft: { params: { sections: 'sections', path: 'vec3s', section: 'section', scales: 'numbers', sides: 'integer', closed: 'boolean', curve: 'integer', ...PLACED }, required: [], run: loft as unknown as OpSpec['run'], says: 'joins cross-sections along a path: a pipe, a handle, a bottle, a hull' },+ loft: { params: { sections: 'sections', path: 'vec3s', section: 'section', scales: 'numbers', sides: 'integer', closed: 'boolean', curve: 'integer', up: 'vec3', ...PLACED }, required: [], run: loft as unknown as OpSpec['run'], says: 'joins cross-sections along a path: a pipe, a handle, a bottle, a hull; `up` says which way a section stands where the path starts' },+ strip: { params: { path: 'vec3s', width: 'number', widths: 'numbers', up: 'vec3', cup: 'number', twist: 'number', curve: 'integer', region: 'numbers', ...PLACED }, required: ['path', 'width'], run: strip as unknown as OpSpec['run'], says: 'carries a flat band along a `path`, `width` wide and shaped by `widths` from root to tip, its face to `up`, folded by `cup`: a leaf, a blade of grass, a ribbon. It has no thickness and both sides draw; a picture lies along it root to tip (`region` for one of a sheet), which with `material.texture` and `alpha` gives it the picture\'s outline' },organic: { params: { parts: 'parts', resolution: 'integer', blend: 'number', noise: 'noise', at: 'vec3', tag: 'string', color: 'color' }, required: ['parts'], run: organic as unknown as OpSpec['run'], says: 'adds one continuous skin over a body of parts that melt into each other' },humanoid: { params: { height: 'number', head: 'number', shoulders: 'number', chest: 'number', waist: 'number', hips: 'number', limbs: 'number', resolution: 'integer', eyes: 'string', skin: 'color', sclera: 'color', iris: 'color', lips: 'color', tag: 'string' }, required: [], run: humanoid as unknown as OpSpec['run'], says: 'adds a whole person standing in an A-pose, facing +z with feet on y 0, whole from every side, with fingers, a face and ears; `rig: { humanoid: {...} }` gives bones that fit the same build' },garment: { params: { faces: 'faces', ease: 'number', relax: 'number', loose: 'loose', cut: 'cuts', thickness: 'number', hide: 'boolean', color: 'color', tag: 'string' }, required: ['faces'], run: garment as unknown as OpSpec['run'], says: 'makes clothes from a piece of the surface already there: relaxed, stood off by `ease`, `loose` for a bell sleeve, `cut` for a hem, with a thickness; they fit from every side and move with the same bones' },@@ -379,16 +393,53 @@ function checkNormalBake(v: unknown, steps: readonly Partial<ModelStep>[]): strireturn last === 0 ? 'has nothing to carry: the decimate is the first step' : null;}+/** Where each step that came out of a repeat or a sum was written, and the step of the source it belongs to. */+const WRITTEN = new WeakMap<object, { where: string; index: number }>();const stepLabel = (step: Partial<ModelStep> | null, index: number): string =>- `step ${index}${step?.id ? ` "${step.id}"` : ''}${step?.op ? ` (${step.op})` : ''}`;+ (step && WRITTEN.get(step)?.where) || `step ${index}${step?.id ? ` "${step.id}"` : ''}${step?.op ? ` (${step.op})` : ''}`;+/** The step of the source as written that @p step belongs to: what an edit would name. */+const writtenIndex = (step: Partial<ModelStep> | null, index: number): number => (step && WRITTEN.get(step)?.index) ?? index;-/** The source if it is well formed; otherwise throws, naming the step and the field. */+/**+ * The source as plain steps: its names, sums and repeats worked out (modelExpand.ts). A source with none is itself.+ * What a build runs and what a report counts; what is saved and edited is the source as written.+ */+export function expandModelSource(source: ModelSource): ModelSource {+ if (!Array.isArray(source.steps) || !needsExpanding(source)) return source;+ let expanded;+ try {+ expanded = expandSteps(source);+ } catch (e) {+ if (e instanceof ModelExpandError) throw new ModelBuildError(e.message, e.index, null, null);+ throw e;+ }+ const { params: _params, ...rest } = source;+ return {+ ...rest,+ steps: expanded.steps.map(({ step, where, index }) => {+ if (typeof step === 'object' && step !== null) WRITTEN.set(step, { where, index });+ return step as ModelStep;+ }),+ };+}++/**+ * The source if it is well formed; otherwise throws, naming the step and the field. A source with names, sums or+ * repeats is checked as the plain steps it comes to and handed back as written, since that is what is saved.+ */export function validateModelSource(raw: unknown): ModelSource {+ const written = raw as { steps?: unknown; params?: unknown } | null;+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || !Array.isArray(written!.steps) || !needsExpanding(written!)) return validatePlain(raw);+ const checked = validatePlain(expandModelSource(raw as ModelSource));+ return { ...checked, ...(written!.params !== undefined ? { params: written!.params as Record<string, unknown> } : {}), steps: written!.steps as ModelStep[] };+}++function validatePlain(raw: unknown): ModelSource {if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new ModelBuildError('a model source must be an object with `steps`', null, null, null);const source = raw as Record<string, unknown>;for (const key of Object.keys(source)) {- if (!['version', 'smoothAngle', 'uvScale', 'uvAtlas', 'material', 'hairSway', 'attach', 'normalBake', 'rig', 'shapes', 'animations', 'controller', 'steps'].includes(key)) {- throw new ModelBuildError(`unknown field "${key}"; a model source has version, smoothAngle, uvScale, uvAtlas, material, hairSway, attach, normalBake, rig, shapes, animations, controller, steps`, null, null, null);+ if (!['version', 'smoothAngle', 'uvScale', 'uvAtlas', 'material', 'hairSway', 'attach', 'normalBake', 'rig', 'shapes', 'animations', 'controller', 'params', 'steps'].includes(key)) {+ throw new ModelBuildError(`unknown field "${key}"; a model source has version, smoothAngle, uvScale, uvAtlas, material, hairSway, attach, normalBake, rig, shapes, animations, controller, params, steps`, null, null, null);}}if (source.version !== undefined && source.version !== MODEL_SOURCE_VERSION) {@@ -432,7 +483,7 @@ export function validateModelSource(raw: unknown): ModelSource {if (!Array.isArray(source.steps)) throw new ModelBuildError('`steps` must be an array', null, null, null);if (source.material !== undefined) {const m = source.material as Record<string, unknown> | null;- if (typeof m !== 'object' || m === null || Array.isArray(m)) throw new ModelBuildError('material must be { roughness?, metallic?, alpha?, cutoff?, emissive? }', null, null, null);+ if (typeof m !== 'object' || m === null || Array.isArray(m)) throw new ModelBuildError('material must be { roughness?, metallic?, alpha?, cutoff?, emissive?, texture? }', null, null, null);for (const [key, value] of Object.entries(m)) {if (key === 'alpha') {if (value !== 'cutout' && value !== 'blend') throw new ModelBuildError('material.alpha must be cutout or blend', null, null, null);@@ -442,7 +493,11 @@ export function validateModelSource(raw: unknown): ModelSource {if (!(isNums(value, 3) && (value as number[]).every((c) => c >= 0))) throw new ModelBuildError('material.emissive must be [r, g, b], none below 0', null, null, null);continue;}- if (!['roughness', 'metallic', 'cutoff'].includes(key)) throw new ModelBuildError(`material has an unknown field "${key}"; it takes roughness, metallic, alpha, cutoff, emissive`, null, null, null);+ if (key === 'texture') {+ if (typeof value !== 'string' || !/\.(png|jpg|jpeg|webp)$/i.test(value)) throw new ModelBuildError('material.texture must be a project path to a picture (.png, .jpg, .webp)', null, null, null);+ continue;+ }+ if (!['roughness', 'metallic', 'cutoff'].includes(key)) throw new ModelBuildError(`material has an unknown field "${key}"; it takes roughness, metallic, alpha, cutoff, emissive, texture`, null, null, null);if (!(isNum(value) && value >= 0 && value <= 1)) throw new ModelBuildError(`material.${key} must be 0..1`, null, null, null);}}@@ -484,15 +539,15 @@ export function validateModelSource(raw: unknown): ModelSource {const ids = new Set<string>();source.steps.forEach((step: Partial<ModelStep> | null, index: number) => {const refuse = (what: string): never => {- throw new ModelBuildError(`${stepLabel(step, index)}: ${what}`, index, step?.id ?? null, step?.op ?? null);+ throw new ModelBuildError(`${stepLabel(step, index)}: ${what}`, writtenIndex(step, index), step?.id ?? null, step?.op ?? null);};if (typeof step !== 'object' || step === null) return refuse('must be an object');if (typeof step.id === 'string') {- if (ids.has(step.id)) refuse(`the id "${step.id}" is already used by an earlier step`);+ if (ids.has(step.id)) refuse(`the id "${step.id}" is already used by an earlier step${WRITTEN.has(step) ? '; a step inside a repeat is made once for each row, so it cannot have an id' : ''}`);ids.add(step.id);} else if (step.id !== undefined) refuse('id must be a string');const spec = typeof step.op === 'string' ? MODEL_OPS[step.op] : undefined;- if (!spec) return refuse(`unknown op ${JSON.stringify(step.op)}; there are ${Object.keys(MODEL_OPS).join(', ')}`);+ if (!spec) return refuse(`unknown op ${JSON.stringify(step.op)}; there are ${Object.keys(MODEL_OPS).join(', ')}, and repeat and let`);for (const [key, value] of Object.entries(step)) {if (key === 'id' || key === 'op') continue;const kind = spec.params[key];@@ -528,7 +583,8 @@ export interface ModelBuild {}/** Runs the steps in order. A step that cannot run throws a {@link ModelBuildError} naming it. */-export function buildPolyMesh(source: ModelSource): ModelBuild {+export function buildPolyMesh(written: ModelSource): ModelBuild {+ const source = expandModelSource(written);let mesh: PolyMesh = { positions: [], faces: [] };const steps: StepReport[] = [];const bake = source.normalBake;@@ -550,7 +606,7 @@ export function buildPolyMesh(source: ModelSource): ModelBuild {? stain(input, params as never, undefined, { roughness: source.material?.roughness ?? 1, metallic: source.material?.metallic ?? 0 }): MODEL_OPS[op]!.run(input, (op === 'decimate' ? rest : params) as never);} catch (e) {- throw new ModelBuildError(`${stepLabel(step, index)}: ${e instanceof Error ? e.message : String(e)}`, index, id ?? null, op);+ throw new ModelBuildError(`${stepLabel(step, index)}: ${e instanceof Error ? e.message : String(e)}`, writtenIndex(step, index), id ?? null, op);}if (mesh.notes) {for (const note of mesh.notes) notes.push(`${stepLabel(step, index)}: ${note}`);@@ -569,7 +625,7 @@ export type ModelEdit =| { op: 'set'; step: string | number; fields: Record<string, unknown> }| { op: 'insert'; step: ModelStep; before?: string | number; after?: string | number }| { op: 'remove'; step: string | number }- | { op: 'settings'; fields: Pick<ModelSource, 'smoothAngle' | 'uvScale' | 'uvAtlas' | 'material' | 'attach' | 'normalBake' | 'rig' | 'shapes' | 'animations' | 'controller'> };+ | { op: 'settings'; fields: Pick<ModelSource, 'smoothAngle' | 'uvScale' | 'uvAtlas' | 'material' | 'attach' | 'normalBake' | 'rig' | 'shapes' | 'animations' | 'controller' | 'params'> };function indexOfStep(source: ModelSource, ref: string | number): number {const i = typeof ref === 'number' ? ref : source.steps.findIndex((s) => s.id === ref);diff --git a/pipeline/src/modeling/strip.ts b/pipeline/src/modeling/strip.tsnew file mode 100644index 000000000..101b7722a--- /dev/null+++ b/pipeline/src/modeling/strip.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file strip.ts — the `strip` step: a band of one thickness, none, carried along a path.+ *+ * A leaf, a blade of grass, a ribbon, a banner, a strap. A `loft` makes these as thin solids, six faces round+ * where two would do, and with no place for a picture: its texture comes from a projection. A strip is the+ * surface itself, with a picture laid along it from end to end, so a leaf drawn once (its veins, its torn edge+ * cut out by its alpha) is the leaf on every strip that reads it.+ *+ * It is open, so a model of strips draws both sides, and a model that wants its other steps closed should keep+ * its strips to themselves.+ */+import { append, type Placed } from './modelOps';+import { curveThrough } from './surfaces';+import { add, cross, dot, length, normalize, scale, sub, type PolyMesh, type Vec3 } from './polyMesh';++export interface StripParams extends Placed {+ /** The line down its middle, from its root to its tip. */+ path: readonly Vec3[];+ /** Its width where `widths` is 1. */+ width: number;+ /** Width along it at even steps from root to tip, as shares of `width`: [0.4, 1, 0.1] is a leaf. Default 1 all along. */+ widths?: readonly number[];+ /** The side its face looks to where it starts; it is carried along from there. Default [0, 1, 0]. */+ up?: Vec3;+ /** How far its edges rise above its middle, as a share of half its width: a folded leaf. Default 0, flat. */+ cup?: number;+ /** Degrees it turns about its own length, from root to tip. */+ twist?: number;+ /** Segments between the path's points; 1 keeps them straight. */+ curve?: number;+ /** The part of the picture it shows, [u0, v0, u1, v1], across then along: one leaf out of a sheet of them. Default the whole of it. */+ region?: readonly number[];+}++function widthAt(widths: readonly number[] | undefined, t: number): number {+ if (!widths || widths.length === 0) return 1;+ if (widths.length === 1) return widths[0]!;+ const f = Math.min(1, Math.max(0, t)) * (widths.length - 1);+ const i = Math.min(widths.length - 2, Math.floor(f));+ return widths[i]! + (widths[i + 1]! - widths[i]!) * (f - i);+}++export function strip(mesh: PolyMesh, p: StripParams): PolyMesh {+ if (!(p.width > 0)) throw new Error(`width ${p.width} must be positive`);+ if (p.widths?.some((w) => !(w >= 0))) throw new Error('`widths` must each be 0 or more');+ if (p.region && (p.region.length !== 4 || p.region.some((v) => !(v >= 0 && v <= 1)))) throw new Error('`region` must be [u0, v0, u1, v1], each 0..1');+ const cup = p.cup ?? 0;+ const centres = curveThrough(p.path, p.curve ?? 1, false) as unknown as Vec3[];+ if (centres.length < 2) throw new Error(`a strip needs a path of at least 2 points, not ${centres.length}`);+ const walked = [0];+ for (let i = 1; i < centres.length; i++) {+ const step = length(sub(centres[i]!, centres[i - 1]!));+ if (step < 1e-9) throw new Error(`points ${i - 1} and ${i} of the path are at the same place`);+ walked.push(walked[i - 1]! + step);+ }+ const whole = walked.at(-1)!;++ const tangentAt = (i: number): Vec3 => normalize(sub(centres[Math.min(centres.length - 1, i + 1)]!, centres[Math.max(0, i - 1)]!));+ const first = tangentAt(0);+ const wanted = p.up ?? [0, 1, 0];+ let across = cross(wanted, first);+ if (length(across) < 1e-6) {+ if (p.up) throw new Error('`up` runs along the path where it starts: give one that points off it');+ across = cross([0, 0, -1], first);+ }+ across = normalize(across);++ // Two columns flat, three folded: the fold needs a line down the middle to fold on.+ const columns = cup !== 0 ? [-1, 0, 1] : [-1, 1];+ const [u0, v0, u1, v1] = p.region ?? [0, 0, 1, 1];+ const positions: Vec3[] = [];+ const uvs: [number, number][] = [];+ centres.forEach((centre, i) => {+ const t = walked[i]! / whole;+ const tangent = tangentAt(i);+ // Carried, not found afresh: a bend then does not roll the strip about its own length.+ across = normalize(sub(across, scale(tangent, dot(across, tangent))));+ const turn = ((p.twist ?? 0) * t * Math.PI) / 180;+ const face = cross(tangent, across);+ const right = add(scale(across, Math.cos(turn)), scale(face, Math.sin(turn)));+ const up = cross(tangent, right);+ // Never quite nothing: a tip of no width is faces of no area, which shade as noise.+ const half = Math.max(p.width * 1e-4, (p.width / 2) * widthAt(p.widths, t));+ for (const c of columns) {+ positions.push(add(add(centre, scale(right, c * half)), scale(up, Math.abs(c) * cup * half)));+ uvs.push([u0 + (u1 - u0) * (c + 1) / 2, v0 + (v1 - v0) * t]);+ }+ });++ const per = columns.length;+ const loops: number[][] = [];+ for (let r = 0; r < centres.length - 1; r++) {+ for (let c = 0; c < per - 1; c++) loops.push([r * per + c, r * per + c + 1, (r + 1) * per + c + 1, (r + 1) * per + c]);+ }+ const base = mesh.faces.length;+ const out = append(mesh, positions, loops, p);+ return {+ positions: out.positions,+ faces: out.faces.map((f, i) => (i < base ? f : { ...f, cornerUvs: loops[i - base]!.map((v) => uvs[v]!) })),+ };+}diff --git a/pipeline/src/modeling/surfaces.ts b/pipeline/src/modeling/surfaces.tsindex 092b262e4..8d61c5fee 100644--- a/pipeline/src/modeling/surfaces.ts+++ b/pipeline/src/modeling/surfaces.ts@@ -221,6 +221,8 @@ export interface LoftParams extends Placed {closed?: boolean;/** Segments between sections; 1 keeps them straight. */curve?: number;+ /** The way a section's "up" points where the path starts; it is carried along from there. Default: as near upright as the path allows. */+ up?: Vec3;}function outlineOf(s: LoftSection, sides: number): { ring: [number, number][]; corners: boolean } {@@ -342,6 +344,12 @@ export function loft(mesh: PolyMesh, p: LoftParams): PolyMesh {const first = tangentAt(0);let right = normalize(cross(Math.abs(first[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0], first));if (Math.abs(first[1]) > 0.99) right = normalize(cross([0, 0, -1], first));+ if (p.up) {+ // A section's up is the given one with what runs along the path taken out, so its across is their cross.+ const across = cross(p.up, first);+ if (length(across) < EPS) throw new Error('`up` runs along the path where it starts: give one that points off it');+ right = normalize(across);+ }const world: number[][][] = sections.map((_, i) => {const t = tangentAt(i);right = normalize(sub(right, scale(t, dot(right, t))));diff --git a/pipeline/tests/modeling-expand.test.ts b/pipeline/tests/modeling-expand.test.tsnew file mode 100644index 000000000..cbbe9356a--- /dev/null+++ b/pipeline/tests/modeling-expand.test.ts@@ -0,0 +1,300 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * A model source's names, sums and repeats: what a sum comes to, what a repeat makes, that the result is the same+ * model as the steps written out, and that what is saved is the source as written.+ */+import { describe, expect, it } from 'vitest';+import { applyModelEdits, bakeModel, expandModelSource, validateModelSource, type ModelSource, type ModelStep } from '../src/modeling';+import { evaluate } from '../src/modeling/modelExpr';++const scope = new Map<string, number | number[]>([['length', 2], ['tip', [0, 2, 0]]]);+const sum = (text: string) => evaluate(text, scope);++describe('a sum in a model source', () => {+ it('does arithmetic in the usual order', () => {+ expect(sum('1 + 2 * 3')).toBe(7);+ expect(sum('(1 + 2) * 3')).toBe(9);+ expect(sum('-2 ^ 2')).toBe(-4);+ expect(sum('2 ^ -1')).toBe(0.5);+ expect(sum('7 % 3')).toBe(1);+ expect(sum('-1 % 3')).toBe(2);+ expect(sum('1.5e1 - .5')).toBe(14.5);+ });++ it('reads the names it is given', () => {+ expect(sum('length * 0.4')).toBeCloseTo(0.8);+ expect(sum('tip[1] + 1')).toBe(3);+ });++ it('works in degrees', () => {+ expect(sum('sin(30)')).toBeCloseTo(0.5);+ expect(sum('atan2(1, 1)')).toBeCloseTo(45);+ expect(sum('cos(pi * 0)')).toBe(1);+ });++ it('adds points and scales them', () => {+ expect(sum('tip + [1, 0, 0]')).toEqual([1, 2, 0]);+ expect(sum('tip * 0.5')).toEqual([0, 1, 0]);+ expect(sum('2 * tip - tip')).toEqual([0, 2, 0]);+ expect(sum('mix([0, 0, 0], tip, 0.25)')).toEqual([0, 0.5, 0]);+ expect(sum('len(tip)')).toBe(2);+ expect(sum('cross([1, 0, 0], [0, 1, 0])')).toEqual([0, 0, 1]);+ });++ it('puts a point round the upright axis, from +z toward +x', () => {+ const p = sum('polar(90, 2, 1)') as number[];+ expect(p[0]).toBeCloseTo(2);+ expect(p[1]).toBe(1);+ expect(p[2]).toBeCloseTo(0);+ });++ it('bends a line from one lean to another, as long as it was asked', () => {+ const line = sum('arc([0, 0, 0], [1, 0, 0], 2, 0, 90, 1, 20)') as number[][];+ expect(line).toHaveLength(21);+ let walked = 0;+ for (let i = 1; i < line.length; i++) walked += Math.hypot(...line[i]!.map((v, k) => v - line[i - 1]![k]!));+ expect(walked).toBeCloseTo(2, 5);+ // It leaves going up and arrives going out, never leaving the plane it leans in.+ expect(line[1]![1]! - line[0]![1]!).toBeGreaterThan(0.09);+ expect(line[20]![0]! - line[19]![0]!).toBeGreaterThan(0.09);+ for (const p of line) expect(p[2]).toBeCloseTo(0);+ });++ it('takes a part of a line, and says where a line is and which way it runs', () => {+ expect(sum('part([[0, 0, 0], [1, 0, 0], [2, 0, 0], [4, 0, 0]], 0.5, 1)')).toEqual([[2, 0, 0], [4, 0, 0]]);+ expect(sum('part([[0, 0, 0], [4, 0, 0]], 0.25, 0.5)')).toEqual([[1, 0, 0], [2, 0, 0]]);+ expect(sum('along([[0, 0, 0], [0, 4, 0]], 0.25)')).toEqual([0, 1, 0]);+ expect(sum('heading([[0, 0, 0], [0, 4, 0]], 0.5)')).toEqual([0, 1, 0]);+ });++ it('gives the same number for the same key', () => {+ expect(sum('rand(3)')).toBe(sum('rand(3)'));+ expect(sum('rand(3)')).not.toBe(sum('rand(4)'));+ const r = sum('rand(7, 10, 20)') as number;+ expect(r).toBeGreaterThanOrEqual(10);+ expect(r).toBeLessThanOrEqual(20);+ });++ it('says what is wrong with one', () => {+ expect(() => sum('width * 2')).toThrow(/"width" is not a name here; there are length, tip/);+ expect(() => sum('spin(3)')).toThrow(/there is no spin\(\)/);+ expect(() => sum('1 +')).toThrow(/stops short/);+ expect(() => sum('(1 + 2')).toThrow(/expected "\)"/);+ expect(() => sum('1 2')).toThrow(/left over/);+ expect(() => sum('tip * tip')).toThrow(/two lists do not multiply/);+ expect(() => sum('tip + [1, 2]')).toThrow(/lists of 3 and 2/);+ expect(() => sum('1 / 0')).toThrow(/division by zero/);+ expect(() => sum('tip[5]')).toThrow(/item 5 of a list of 3/);+ expect(() => sum('sqrt(-1)')).toThrow(/not a number/);+ expect(() => sum('length; 1')).toThrow(/";" at 6 is not part of a sum/);+ });+});++const facesOf = (source: unknown): number => bakeModel(source).poly.faces.length;+const positionsOf = (source: unknown): number[][] => bakeModel(source).poly.positions.map((p) => p.map((v) => Math.round(v * 1e6) / 1e6));++describe('names and repeats in a model source', () => {+ it('builds the same model as the steps written out', () => {+ const written = {+ version: 1,+ params: { size: 0.5, gap: 2 },+ steps: [{ op: 'repeat', count: 3, steps: [{ op: 'box', size: '=size', at: ['=i * gap', 0, 0] }] }],+ };+ const plain = { version: 1, steps: [0, 2, 4].map((x) => ({ op: 'box', size: 0.5, at: [x, 0, 0] })) };+ expect(positionsOf(written)).toEqual(positionsOf(plain));+ });++ it('runs its steps once for each row, the row naming what differs', () => {+ const source = {+ version: 1,+ steps: [{+ op: 'repeat',+ over: [{ angle: 0, height: 1 }, { angle: 90, height: 2 }, { angle: 180, height: 3 }],+ steps: [{ op: 'cylinder', radius: 0.1, height: '=height', sides: 6, at: '=polar(angle, 2, height / 2)' }],+ }],+ };+ const m = bakeModel(source);+ expect(m.report.shells).toBe(3);+ expect(m.report.bounds.max[1]).toBeCloseTo(3);+ expect(m.report.bounds.min[2]).toBeCloseTo(-2.1, 1);+ });++ it('gives a repeat its place in the run: i, t from 0 to 1, and n', () => {+ const plain = expandModelSource(validateModelSource({+ version: 1,+ steps: [{ op: 'repeat', count: 3, steps: [{ op: 'box', size: 1, at: ['=i', '=t', '=n'] }] }],+ }));+ expect(plain.steps.map((s) => s.at)).toEqual([[0, 0, 3], [1, 0.5, 3], [2, 1, 3]]);+ });++ it('names a value for the steps that follow, and not for those outside the repeat it is in', () => {+ const plain = expandModelSource(validateModelSource({+ version: 1,+ params: { base: 2 },+ steps: [+ { op: 'let', twice: '=base * 2' },+ { op: 'repeat', count: 2, steps: [{ op: 'let', here: '=twice + i' }, { op: 'box', size: '=here' }] },+ { op: 'box', size: '=twice' },+ ],+ }));+ expect(plain.steps.map((s) => s.size)).toEqual([4, 5, 4]);+ expect(() => bakeModel({+ version: 1,+ steps: [{ op: 'repeat', count: 2, steps: [{ op: 'let', here: 1 }, { op: 'box', size: '=here' }] }, { op: 'box', size: '=here' }],+ })).toThrow(/step 1 \(box\): `size` "=here": "here" is not a name here/);+ });++ it('repeats inside a repeat', () => {+ expect(facesOf({+ version: 1,+ steps: [{ op: 'repeat', count: 3, steps: [{ op: 'let', x: '=i' }, { op: 'repeat', count: 2, steps: [{ op: 'box', size: 0.2, at: ['=x', '=i', 0] }] }] }],+ })).toBe(3 * 2 * 6);+ });++ it('lets a later param use an earlier one', () => {+ const plain = expandModelSource(validateModelSource({ version: 1, params: { a: 2, b: '=a * 3', c: '=[a, b, 0]' }, steps: [{ op: 'box', size: 1, at: '=c' }] }));+ expect(plain.steps[0]!.at).toEqual([2, 6, 0]);+ });++ it('hands back the source as written, which is what is saved', () => {+ const written = { version: 1, params: { size: 2 }, steps: [{ op: 'box', size: '=size' }] };+ const checked = validateModelSource(structuredClone(written));+ expect(checked.steps).toEqual(written.steps);+ expect(checked.params).toEqual(written.params);+ // And an edit changes the name once, where ten steps would have been ten edits.+ const edited = applyModelEdits(checked, [{ op: 'settings', fields: { params: { size: 4 } } }]);+ expect(edited.params).toEqual({ size: 4 });+ expect(bakeModel(edited).report.bounds.size[0]).toBeCloseTo(4);+ });++ it('leaves a source without any of it exactly as it was', () => {+ const source: ModelSource = { version: 1, steps: [{ op: 'box', size: 1 }] };+ expect(expandModelSource(source)).toBe(source);+ });++ it('names a failing step by where it was written, and the step an edit would change', () => {+ const source = {+ version: 1,+ steps: [{ op: 'box', size: 1 }, { op: 'repeat', over: [{ w: 1 }, { w: -1 }], steps: [{ op: 'box', size: '=w' }] }],+ };+ let caught: { message: string; stepIndex: number | null } | null = null;+ try { bakeModel(source); } catch (e) { caught = e as never; }+ expect(caught!.message).toMatch(/^step 1 \(repeat\) row 1 > step 0 \(box\): /);+ expect(caught!.stepIndex).toBe(1);+ expect(() => validateModelSource({ version: 1, steps: [{ op: 'repeat', count: 2, steps: [{ op: 'box', size: 1, nope: 3 }] }] }))+ .toThrow(/step 0 \(repeat\) row 0 > step 0 \(box\): unknown field "nope"/);+ });++ it('refuses what it cannot make sense of', () => {+ const repeat = (fields: Record<string, unknown>) => () => validateModelSource({ version: 1, steps: [{ op: 'repeat', steps: [{ op: 'box', size: 1 }], ...fields }] });+ expect(repeat({})).toThrow(/one of `count` or `over`/);+ expect(repeat({ count: 2, over: [{}] })).toThrow(/one of `count` or `over`/);+ expect(repeat({ count: 0 })).toThrow(/count 0 must be a whole number of 1 or more/);+ expect(repeat({ count: 2, times: 3 })).toThrow(/unknown field "times"/);+ expect(repeat({ over: [1, 2] })).toThrow(/`over` must be a list of rows/);+ expect(repeat({ count: 2, steps: [] })).toThrow(/`steps` is what it repeats/);+ expect(repeat({ count: 2, steps: [{ op: 'box', size: 1, id: 'a' }] })).toThrow(/a step inside a repeat is made once for each row, so it cannot have an id/);+ expect(repeat({ count: 6000 })).toThrow(/more than 5000 steps/);+ expect(() => validateModelSource({ version: 1, params: { i: 1 }, steps: [] })).toThrow(/"i" is taken/);+ expect(() => validateModelSource({ version: 1, params: { '2x': 1 }, steps: [] })).toThrow(/"2x" is not a name/);+ expect(() => validateModelSource({ version: 1, params: { a: 'big' }, steps: [] })).toThrow(/params\.a must be a number/);+ expect(() => validateModelSource({ version: 1, steps: [{ op: 'let', x: '=nope' }] })).toThrow(/step 0 \(let\): x "=nope"/);+ });+});++describe('strip', () => {+ const strip = (fields: Record<string, unknown> = {}): ModelStep => ({ op: 'strip', path: [[0, 0, 0], [0, 0, 1], [0, 0, 2]], width: 0.4, ...fields });+ const built = (fields?: Record<string, unknown>) => bakeModel({ version: 1, smoothAngle: 0, steps: [strip(fields)] }).poly;++ it('is a band of no thickness, as wide as asked, facing up', () => {+ const m = built();+ expect(m.faces).toHaveLength(2);+ const xs = m.positions.map((p) => p[0]!), ys = m.positions.map((p) => p[1]!);+ expect(Math.min(...xs)).toBeCloseTo(-0.2);+ expect(Math.max(...xs)).toBeCloseTo(0.2);+ expect(Math.max(...ys.map(Math.abs))).toBeCloseTo(0);+ });++ it('is shaped along its length by `widths`, and never quite to nothing', () => {+ const m = built({ widths: [0.5, 1, 0] });+ const widthAt = (z: number): number => {+ const row = m.positions.filter((p) => Math.abs(p[2]! - z) < 1e-6).map((p) => p[0]!);+ return Math.max(...row) - Math.min(...row);+ };+ expect(widthAt(0)).toBeCloseTo(0.2);+ expect(widthAt(1)).toBeCloseTo(0.4);+ expect(widthAt(2)).toBeGreaterThan(0);+ expect(widthAt(2)).toBeLessThan(0.001);+ });++ it('folds along its middle by `cup`', () => {+ const m = built({ cup: 0.5 });+ expect(m.faces).toHaveLength(4);+ expect(Math.max(...m.positions.map((p) => p[1]!))).toBeCloseTo(0.5 * 0.2);+ expect(Math.min(...m.positions.map((p) => p[1]!))).toBeCloseTo(0);+ });++ it('faces the way `up` says', () => {+ const m = built({ up: [1, 0, 0] });+ // Its width now runs along y, and it has no extent along x.+ expect(Math.max(...m.positions.map((p) => Math.abs(p[0]!)))).toBeCloseTo(0);+ expect(Math.max(...m.positions.map((p) => p[1]!))).toBeCloseTo(0.2);+ expect(() => built({ up: [0, 0, 1] })).toThrow(/`up` runs along the path/);+ });++ it('lays a picture along it from root to tip, or one part of a sheet', () => {+ const uvs = (m: ReturnType<typeof built>): number[][] => m.faces.flatMap((f) => f.cornerUvs!.map((uv) => [...uv]));+ const whole = uvs(built());+ expect(Math.min(...whole.map((u) => u[1]!))).toBe(0);+ expect(Math.max(...whole.map((u) => u[1]!))).toBe(1);+ expect(new Set(whole.map((u) => u[0]))).toEqual(new Set([0, 1]));+ const part = uvs(built({ region: [0.5, 0, 1, 0.25] }));+ expect(Math.min(...part.map((u) => u[0]!))).toBe(0.5);+ expect(Math.max(...part.map((u) => u[1]!))).toBe(0.25);+ });++ it('keeps its picture when it is scattered', () => {+ const m = bakeModel({ version: 1, steps: [{ ...strip(), tag: 'leaf' }, { op: 'scatter', source: 'leaf', path: [[0, 0, 0], [5, 0, 0]], count: 3, rows: 2, tag: 'copy' }] }).poly;+ expect(m.faces.filter((f) => f.tag === 'copy')).toHaveLength(12);+ for (const f of m.faces) expect(f.cornerUvs).toHaveLength(4);+ });++ it('says what is wrong', () => {+ expect(() => built({ width: 0 })).toThrow(/width 0 must be positive/);+ expect(() => built({ path: [[0, 0, 0]] })).toThrow(/at least 2 points/);+ expect(() => built({ path: [[0, 0, 0], [0, 0, 0]] })).toThrow(/same place/);+ expect(() => built({ region: [0, 0, 2, 1] })).toThrow(/`region` must be/);+ expect(() => built({ widths: [1, -1] })).toThrow(/`widths` must each be 0 or more/);+ });+});++describe('loft with an `up`', () => {+ const loft = (up?: number[]) => bakeModel({+ version: 1, smoothAngle: 0,+ steps: [{ op: 'loft', path: [[0, 0, 0], [0, 0, 2]], section: { size: [1, 0.1] }, ...(up ? { up } : {}) }],+ }).poly;+ const extent = (m: ReturnType<typeof loft>, axis: number): number => Math.max(...m.positions.map((p) => p[axis]!)) - Math.min(...m.positions.map((p) => p[axis]!));++ it('stands its section the way it is told, where it stood upright before', () => {+ // Across 1 and up 0.1: by default the thin way is y.+ expect(extent(loft(), 1)).toBeCloseTo(0.1);+ expect(extent(loft(), 0)).toBeCloseTo(1);+ // With up along x, the thin way is x.+ expect(extent(loft([1, 0, 0]), 0)).toBeCloseTo(0.1);+ expect(extent(loft([1, 0, 0]), 1)).toBeCloseTo(1);+ });++ it('refuses an up that runs along the path', () => {+ expect(() => loft([0, 0, 1])).toThrow(/`up` runs along the path/);+ });+});++describe('a material with a picture', () => {+ it('takes a project path to one, and nothing else', () => {+ const source = (texture: unknown) => ({ version: 1, material: { alpha: 'cutout', texture }, steps: [{ op: 'box', size: 1 }] });+ expect(validateModelSource(source('art/leaf.png')).material?.texture).toBe('art/leaf.png');+ expect(() => validateModelSource(source('art/leaf.txt'))).toThrow(/material\.texture must be a project path to a picture/);+ expect(() => validateModelSource(source(3))).toThrow(/material\.texture must be a project path to a picture/);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 19cf5676a..ddb3c9904 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4576,6 +4576,10 @@ export const NOTED = {{"note": "An AI can lay leaflets along a stem in one step."},"feat(modeling): the model tools say scatter's rows - rows, sweep, lift, up and sizes are in what model_write offers":{"note": "An AI can lay leaflets along a stem in one step."},+ "feat(modeling): a model source names its numbers and repeats its steps, and a leaf is a strip that reads a picture - params, sums written \"=length * 0.4\", repeat over rows and let; a strip step for a band with no thickness and a picture along it, material.texture for the picture, and an up for loft; a palm is six steps written and a third of the triangles":+ {"note": "A model is written once for all its like parts, and a leaf can be a picture."},+ "feat(modeling): the model tools say names, sums and repeats, strip, and a material's picture - and a model whose picture is not in the project is refused before anything is written":+ {"note": "A model is written once for all its like parts, and a leaf can be a picture."},"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":@@ -4602,6 +4606,8 @@ export const NOTED = {{"note": "Grass on a hill is not thinned under your feet."},"feat(foliage): a far field of flowers shows its colour - a far mesh plant grows across the ground, so a flat flower was a disc facing the sky, edge on to a low eye, and a meadow lost its colour a field away; Foliage.farTilt tips the top of each far plant over, its own way round, and its stem stays upright":{"note": "A far field of flowers shows its colour."},+ "feat(foliage): a flower turns to face the eye - a material's vertex hook reads the mesh's second uv as es_vertexUv1, and a Foliage with faceEye puts there where each vertex of a plant's head sits from its axis; the Foliage shader turns the head about it, by faceEyeNear close to and faceEye far off, so a far field of flat flowers shows its colour from a low eye":+ {"note": "A flower turns to face the eye."},"fix(terrain): a detail the pages cannot hold no longer cracks the ground - a tree that wanted more nodes than the atlas has pages was drawn in part by coarser pages standing in, which do not meet their finer neighbours' edges, and the pages were fought over every frame; the ground is now drawn at the share of its detail's range that fits, and says so once":{"note": "A detail the pages cannot hold no longer cracks the ground."},"fix(foliage): a far plant grows across the ground, not taller - a mesh plant kept in a far version was grown the same every way to cover the ground of those left out, so a flower that stood for ten stood ten times as high and a far meadow was a field of poles; it now grows across the ground only, and Foliage.farGrowUp gives its height a share of the growth back":