3D engine that AI agents drive
Remove three.js from modeling and the agent scene
Nguyen Xuan An7e53f1139e79
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ac5fdef..43c0c06b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Remove three.js from modeling and the agent scene: `lathe`, `extrude` and `tube` no longer import it, and `scene:agent-scene` drops from 185,681 to 117,290 bytes gzip. `lathe` and `tube` output is identical to before, vertex for vertex. `extrude` walls, bevels, UVs, normals and bounds are identical, and volume matches within 1e-4. Extrusion caps use a new ear-clipping triangulation, so a cap can split along other diagonals, and a cap with collinear points can add or drop a seam vertex. A clockwise hole under a clockwise contour is now flipped to face outward, where it used to keep inward walls- Update the bundled `zod` to 4.6.7, which fixes a memory exhaustion advisory in the validation of oversized collections- Make the MCP preview server reject requests with another Host header, which closes DNS rebinding- Check the size of a mesh `array` before it allocates. Before this, the check ran after the copies existeddiff --git a/docs/modeling.md b/docs/modeling.mdindex 2c1d9a34..be891c3f 100644--- a/docs/modeling.md+++ b/docs/modeling.md@@ -1,7 +1,7 @@# Profile, contour and path modelingAvailable from version `0.4.0`.-The optional modeling entry uses the installed Three.js geometry algorithms and converts their output to 67.js meshes.+The optional modeling entry builds its meshes itself and has no dependency on Three.js.The core renderer does not import the modeling addon.```js@@ -63,9 +63,9 @@ Center small geometry near the origin and place it with part transforms when wor## API choice-Plain point arrays keep profiles serializable and avoid exposing Three.js classes through the API.-Accepting Three.js Shape/Curve objects offers custom curve subclasses, but couples callers to that dependency and weakens input bounds.-The addon reuses Three.js triangulation, bevel construction and curve frames. THIRD-PARTY-NOTICES.md contains its license.+Plain point arrays keep profiles serializable and keep any other library's classes out of the API.+Accepting custom curve objects would let callers supply their own curve classes, but weakens input bounds.+Lathe, bevel construction and curve frames follow the formulas Three.js used before, so those outputs are unchanged. Extrusion caps use an ear-clipping triangulation of the addon's own, so a cap can be split along different diagonals than before, with the same area, volume and bounds.The Aster lantern at `/modeling.html` combines these tools with texture channels and the shared scene graph.It is a procedural modeling demonstration, not a mesh editor or a Blender feature parity claim.diff --git a/src/modeling-curve.js b/src/modeling-curve.jsnew file mode 100644index 00000000..7a6700b4--- /dev/null+++ b/src/modeling-curve.js@@ -0,0 +1,174 @@+// Centripetal Catmull-Rom curve with arc-length sampling and rotation-minimizing frames, for the tube generator.+const ARC_LENGTH_DIVISIONS = 200;+const TANGENT_DELTA = 0.0001;++function subtract(first, second) {+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+}++function add(first, second) {+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];+}++function crossProduct(first, second) {+ return [+ first[1] * second[2] - first[2] * second[1],+ first[2] * second[0] - first[0] * second[2],+ first[0] * second[1] - first[1] * second[0],+ ];+}++function dotProduct(first, second) {+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+}++function lengthOf(vector) {+ return Math.sqrt(dotProduct(vector, vector));+}++function normalize(vector) {+ const scale = 1 / (lengthOf(vector) || 1);+ return [vector[0] * scale, vector[1] * scale, vector[2] * scale];+}++function rotateAroundAxis(vector, axis, angle) {+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const remainder = 1 - cosine;+ const [axisX, axisY, axisZ] = axis;+ const xx = remainder * axisX;+ const yy = remainder * axisY;+ return [+ (xx * axisX + cosine) * vector[0] + (xx * axisY - sine * axisZ) * vector[1] + (xx * axisZ + sine * axisY) * vector[2],+ (xx * axisY + sine * axisZ) * vector[0] + (yy * axisY + cosine) * vector[1] + (yy * axisZ - sine * axisX) * vector[2],+ (xx * axisZ - sine * axisY) * vector[0] + (yy * axisZ + sine * axisX) * vector[1] + (remainder * axisZ * axisZ + cosine) * vector[2],+ ];+}++function distanceSquared(first, second) {+ const difference = subtract(first, second);+ return dotProduct(difference, difference);+}++function nonuniformCoefficients(x0, x1, x2, x3, dt0, dt1, dt2) {+ let tangentStart = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;+ let tangentEnd = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2;+ tangentStart *= dt1;+ tangentEnd *= dt1;+ return [x1, tangentStart, -3 * x1 + 3 * x2 - 2 * tangentStart - tangentEnd, 2 * x1 - 2 * x2 + tangentStart + tangentEnd];+}++function createCurve(points, closed) {+ const count = points.length;+ const pointAt = parameter => {+ const scaled = (count - (closed ? 0 : 1)) * parameter;+ let segment = Math.floor(scaled);+ let weight = scaled - segment;+ if (closed) {+ segment += segment > 0 ? 0 : (Math.floor(Math.abs(segment) / count) + 1) * count;+ } else if (weight === 0 && segment === count - 1) {+ segment = count - 2;+ weight = 1;+ }+ const before = closed || segment > 0+ ? points[(segment - 1) % count]+ : add(subtract(points[0], points[1]), points[0]);+ const start = points[segment % count];+ const end = points[(segment + 1) % count];+ const after = closed || segment + 2 < count+ ? points[(segment + 2) % count]+ : add(subtract(points[count - 1], points[count - 2]), points[count - 1]);+ let dt0 = Math.pow(distanceSquared(before, start), 0.25);+ let dt1 = Math.pow(distanceSquared(start, end), 0.25);+ let dt2 = Math.pow(distanceSquared(end, after), 0.25);+ if (dt1 < 1e-4) dt1 = 1.0;+ if (dt0 < 1e-4) dt0 = dt1;+ if (dt2 < 1e-4) dt2 = dt1;+ const squared = weight * weight;+ const cubed = squared * weight;+ return [0, 1, 2].map(axis => {+ const [c0, c1, c2, c3] = nonuniformCoefficients(before[axis], start[axis], end[axis], after[axis], dt0, dt1, dt2);+ return c0 + c1 * weight + c2 * squared + c3 * cubed;+ });+ };+ const cumulativeLengths = [0];+ let previous = pointAt(0);+ let sum = 0;+ for (let division = 1; division <= ARC_LENGTH_DIVISIONS; division++) {+ const current = pointAt(division / ARC_LENGTH_DIVISIONS);+ sum += lengthOf(subtract(current, previous));+ cumulativeLengths.push(sum);+ previous = current;+ }+ const parameterAtFraction = fraction => {+ const target = fraction * cumulativeLengths[ARC_LENGTH_DIVISIONS];+ let low = 0;+ let high = ARC_LENGTH_DIVISIONS;+ while (low <= high) {+ const middle = Math.floor(low + (high - low) / 2);+ const comparison = cumulativeLengths[middle] - target;+ if (comparison < 0) {+ low = middle + 1;+ } else if (comparison > 0) {+ high = middle - 1;+ } else {+ high = middle;+ break;+ }+ }+ if (cumulativeLengths[high] === target) return high / ARC_LENGTH_DIVISIONS;+ const segmentLength = cumulativeLengths[high + 1] - cumulativeLengths[high];+ return (high + (target - cumulativeLengths[high]) / segmentLength) / ARC_LENGTH_DIVISIONS;+ };+ const tangentAt = fraction => {+ const parameter = parameterAtFraction(fraction);+ const before = pointAt(Math.max(parameter - TANGENT_DELTA, 0));+ const after = pointAt(Math.min(parameter + TANGENT_DELTA, 1));+ return normalize(subtract(after, before));+ };+ return { pointAtFraction: fraction => pointAt(parameterAtFraction(fraction)), tangentAt };+}++function initialNormal(tangent) {+ const absolute = tangent.map(Math.abs);+ let axis = 0;+ if (absolute[1] <= absolute[axis]) axis = 1;+ if (absolute[2] <= absolute[axis]) axis = 2;+ const reference = [0, 0, 0];+ reference[axis] = 1;+ return crossProduct(tangent, normalize(crossProduct(tangent, reference)));+}++function frames(tangents, closed) {+ const segments = tangents.length - 1;+ const normals = [initialNormal(tangents[0])];+ for (let index = 1; index <= segments; index++) {+ let normal = normals[index - 1];+ const axis = crossProduct(tangents[index - 1], tangents[index]);+ if (lengthOf(axis) > Number.EPSILON) {+ const angle = Math.acos(Math.min(Math.max(dotProduct(tangents[index - 1], tangents[index]), -1), 1));+ normal = rotateAroundAxis(normal, normalize(axis), angle);+ }+ normals.push(normal);+ }+ if (closed) {+ let angle = Math.acos(Math.min(Math.max(dotProduct(normals[0], normals[segments]), -1), 1));+ angle /= segments;+ if (dotProduct(tangents[0], crossProduct(normals[0], normals[segments])) > 0) angle = -angle;+ for (let index = 1; index <= segments; index++) {+ normals[index] = rotateAroundAxis(normals[index], tangents[index], angle * index);+ }+ }+ return normals.map((normal, index) => ({ normal, binormal: crossProduct(tangents[index], normal) }));+}++/** Samples a tube path at equal arc-length steps: one point and one frame per step, steps + 1 in all. */+export function sampleTubePath(points, closed, steps) {+ const curve = createCurve(points, closed);+ const tangents = Array.from({ length: steps + 1 }, (_, index) => curve.tangentAt(index / steps));+ const sampleFrames = frames(tangents, closed);+ return sampleFrames.map((_, index) => {+ const source = closed && index === steps ? 0 : index;+ return { point: curve.pointAtFraction(source / steps), ...sampleFrames[source] };+ });+}diff --git a/src/modeling-shapes.js b/src/modeling-shapes.jsnew file mode 100644index 00000000..50a9c88c--- /dev/null+++ b/src/modeling-shapes.js@@ -0,0 +1,241 @@+// Geometry builders for lathe, extrude and tube. Each returns raw arrays: indices are null for triangle soup.+import { sampleTubePath } from './modeling-curve.js';+import { signedArea, triangulate } from './triangulate.js';++const MERGE_THRESHOLD = 1e-10;++function normalizeScaled(x, y, z) {+ const scale = 1 / (Math.sqrt(x * x + y * y + z * z) || 1);+ return [x * scale, y * scale, z * scale];+}++export function buildLathe(profile, segments, startAngle, sweep) {+ const normalsAlongProfile = [];+ let previousNormal = [0, 0];+ for (let index = 0; index < profile.length; index++) {+ if (index === profile.length - 1) {+ normalsAlongProfile.push([previousNormal[0], previousNormal[1]]);+ break;+ }+ const currentNormal = [profile[index + 1][1] - profile[index][1], -(profile[index + 1][0] - profile[index][0])];+ const combined = index === 0 ? currentNormal : [currentNormal[0] + previousNormal[0], currentNormal[1] + previousNormal[1]];+ const [x, y] = normalizeScaled(combined[0], combined[1], 0);+ normalsAlongProfile.push([x, y]);+ previousNormal = currentNormal;+ }+ const positions = [];+ const normals = [];+ const uvs = [];+ for (let segment = 0; segment <= segments; segment++) {+ const angle = startAngle + segment * (1 / segments) * sweep;+ const sine = Math.sin(angle);+ const cosine = Math.cos(angle);+ for (let index = 0; index < profile.length; index++) {+ positions.push(profile[index][0] * sine, profile[index][1], profile[index][0] * cosine);+ uvs.push(segment / segments, index / (profile.length - 1));+ normals.push(normalsAlongProfile[index][0] * sine, normalsAlongProfile[index][1], normalsAlongProfile[index][0] * cosine);+ }+ }+ const indices = [];+ for (let segment = 0; segment < segments; segment++) {+ for (let index = 0; index < profile.length - 1; index++) {+ const base = index + segment * profile.length;+ const next = base + profile.length;+ indices.push(base, next, base + 1, next + 1, base + 1, next);+ }+ }+ return { positions: Float32Array.from(positions), normals: Float32Array.from(normals), uvs: Float32Array.from(uvs), indices: Uint32Array.from(indices) };+}++export function buildTube(points, closed, radius, segments, radialSegments) {+ const samples = sampleTubePath(points, closed, segments);+ const positions = [];+ const normals = [];+ const uvs = [];+ for (const { point, normal, binormal } of samples) {+ for (let side = 0; side <= radialSegments; side++) {+ const angle = side / radialSegments * Math.PI * 2;+ const sine = Math.sin(angle);+ const cosine = -Math.cos(angle);+ const outward = normalizeScaled(+ cosine * normal[0] + sine * binormal[0],+ cosine * normal[1] + sine * binormal[1],+ cosine * normal[2] + sine * binormal[2],+ );+ normals.push(...outward);+ positions.push(point[0] + radius * outward[0], point[1] + radius * outward[1], point[2] + radius * outward[2]);+ }+ }+ for (let ring = 0; ring <= segments; ring++) {+ for (let side = 0; side <= radialSegments; side++) uvs.push(ring / segments, side / radialSegments);+ }+ const indices = [];+ for (let ring = 1; ring <= segments; ring++) {+ for (let side = 1; side <= radialSegments; side++) {+ const a = (radialSegments + 1) * (ring - 1) + (side - 1);+ const b = (radialSegments + 1) * ring + (side - 1);+ const c = (radialSegments + 1) * ring + side;+ const d = (radialSegments + 1) * (ring - 1) + side;+ indices.push(a, b, d, b, c, d);+ }+ }+ return { positions: Float32Array.from(positions), normals: Float32Array.from(normals), uvs: Float32Array.from(uvs), indices: Uint32Array.from(indices) };+}++function mergeOverlappingPoints(points) {+ let previous = points[0];+ for (let index = 1; index <= points.length; index++) {+ const currentIndex = index % points.length;+ const current = points[currentIndex];+ const deltaX = current[0] - previous[0];+ const deltaY = current[1] - previous[1];+ const largest = Math.max(Math.abs(current[0]), Math.abs(current[1]), Math.abs(previous[0]), Math.abs(previous[1]));+ if (deltaX * deltaX + deltaY * deltaY <= MERGE_THRESHOLD * MERGE_THRESHOLD * largest * largest) {+ points.splice(currentIndex, 1);+ index--;+ continue;+ }+ previous = current;+ }+}++/** The vector that moves a ring vertex one unit outward along the bisector of its two edges. */+function bevelDirection(point, previous, next) {+ const previousX = point[0] - previous[0];+ const previousY = point[1] - previous[1];+ const nextX = next[0] - point[0];+ const nextY = next[1] - point[1];+ const previousLengthSquared = previousX * previousX + previousY * previousY;+ const turn = previousX * nextY - previousY * nextX;+ let translateX;+ let translateY;+ let shrinkBy;+ if (Math.abs(turn) > Number.EPSILON) {+ const previousLength = Math.sqrt(previousLengthSquared);+ const nextLength = Math.sqrt(nextX * nextX + nextY * nextY);+ const previousShiftX = previous[0] - previousY / previousLength;+ const previousShiftY = previous[1] + previousX / previousLength;+ const nextShiftX = next[0] - nextY / nextLength;+ const nextShiftY = next[1] + nextX / nextLength;+ const factor = ((nextShiftX - previousShiftX) * nextY - (nextShiftY - previousShiftY) * nextX) / (previousX * nextY - previousY * nextX);+ translateX = previousShiftX + previousX * factor - point[0];+ translateY = previousShiftY + previousY * factor - point[1];+ const translateLengthSquared = translateX * translateX + translateY * translateY;+ if (translateLengthSquared <= 2) return [translateX, translateY];+ shrinkBy = Math.sqrt(translateLengthSquared / 2);+ } else {+ let sameDirection = false;+ if (previousX > Number.EPSILON) {+ sameDirection = nextX > Number.EPSILON;+ } else if (previousX < -Number.EPSILON) {+ sameDirection = nextX < -Number.EPSILON;+ } else {+ sameDirection = Math.sign(previousY) === Math.sign(nextY);+ }+ if (sameDirection) {+ translateX = -previousY;+ translateY = previousX;+ shrinkBy = Math.sqrt(previousLengthSquared);+ } else {+ translateX = previousX;+ translateY = previousY;+ shrinkBy = Math.sqrt(previousLengthSquared / 2);+ }+ }+ return [translateX / shrinkBy, translateY / shrinkBy];+}++function ringDirections(ring) {+ return ring.map((point, index) => bevelDirection(point, ring[(index + ring.length - 1) % ring.length], ring[(index + 1) % ring.length]));+}++function faceNormals(positions) {+ const normals = new Float32Array(positions.length);+ for (let offset = 0; offset < positions.length; offset += 9) {+ const ax = positions[offset] - positions[offset + 3];+ const ay = positions[offset + 1] - positions[offset + 4];+ const az = positions[offset + 2] - positions[offset + 5];+ const cx = positions[offset + 6] - positions[offset + 3];+ const cy = positions[offset + 7] - positions[offset + 4];+ const cz = positions[offset + 8] - positions[offset + 5];+ const unnormalized = Float32Array.from([cy * az - cz * ay, cz * ax - cx * az, cx * ay - cy * ax]);+ const stored = Float32Array.from(normalizeScaled(unnormalized[0], unnormalized[1], unnormalized[2]));+ for (let corner = 0; corner < 3; corner++) normals.set(stored, offset + corner * 3);+ }+ return normals;+}++/** Extrusion along +Z as triangle soup with flat normals. Bevel layers follow a quarter-sine profile. */+export function buildExtrusion(contourInput, holeInputs, { depth, steps, bevel, bevelThickness, bevelSegments }) {+ const beveled = bevel > 0 || bevelThickness > 0;+ const thickness = beveled ? bevelThickness : 0;+ const size = beveled ? bevel : 0;+ const segmentCount = beveled ? bevelSegments : 0;+ const contour = contourInput.map(point => [...point]);+ const holes = holeInputs.map(hole => hole.map(point => [...point]));+ if (!(signedArea(contour) < 0)) contour.reverse();+ for (const hole of holes) if (signedArea(hole) < 0) hole.reverse();+ mergeOverlappingPoints(contour);+ holes.forEach(mergeOverlappingPoints);+ const rings = [contour, ...holes];+ const vertices = rings.flat();+ const directions = rings.flatMap(ringDirections);+ const layers = [];+ const addLayer = (distance, height) => layers.push(vertices.map((vertex, index) => [vertex[0] + directions[index][0] * distance, vertex[1] + directions[index][1] * distance, height]));+ const bevelLevel = bevelStep => {+ const fraction = bevelStep / segmentCount;+ return { height: thickness * Math.cos(fraction * Math.PI / 2), distance: size * Math.sin(fraction * Math.PI / 2) };+ };+ for (let bevelStep = 0; bevelStep < segmentCount; bevelStep++) {+ const { height, distance } = bevelLevel(bevelStep);+ addLayer(distance, -height);+ }+ const fullDistance = beveled ? size : 0;+ addLayer(fullDistance, 0);+ for (let step = 1; step <= steps; step++) addLayer(fullDistance, depth / steps * step);+ for (let bevelStep = segmentCount - 1; bevelStep >= 0; bevelStep--) {+ const { height, distance } = bevelLevel(bevelStep);+ addLayer(distance, depth + height);+ }+ const faces = triangulate(contour, holes);+ const topLayer = beveled ? steps + segmentCount * 2 : steps;+ const soup = [];+ const uvs = [];+ const pushVertex = (layer, vertex) => soup.push(...layers[layer][vertex]);+ const pushTopUvs = count => {+ for (let corner = count; corner >= 1; corner--) {+ const base = soup.length - corner * 3;+ uvs.push(soup[base], soup[base + 1]);+ }+ };+ for (const face of faces) {+ pushVertex(0, face[2]);+ pushVertex(0, face[1]);+ pushVertex(0, face[0]);+ pushTopUvs(3);+ }+ for (const face of faces) {+ for (const vertex of face) pushVertex(topLayer, vertex);+ pushTopUvs(3);+ }+ let ringOffset = 0;+ for (const ring of rings) {+ for (let index = ring.length - 1; index >= 0; index--) {+ const previous = index === 0 ? ring.length - 1 : index - 1;+ for (let layer = 0; layer < steps + segmentCount * 2; layer++) {+ const a = layers[layer][ringOffset + index];+ const b = layers[layer][ringOffset + previous];+ const c = layers[layer + 1][ringOffset + previous];+ const d = layers[layer + 1][ringOffset + index];+ soup.push(...a, ...b, ...d, ...b, ...c, ...d);+ const horizontal = Math.abs(a[1] - b[1]) < Math.abs(a[0] - b[0]);+ const axis = horizontal ? 0 : 1;+ const wallUv = corner => [corner[axis], 1 - corner[2]];+ uvs.push(...wallUv(a), ...wallUv(b), ...wallUv(d), ...wallUv(b), ...wallUv(c), ...wallUv(d));+ }+ }+ ringOffset += ring.length;+ }+ const positions = Float32Array.from(soup);+ return { positions, normals: faceNormals(positions), uvs: Float32Array.from(uvs), indices: null };+}diff --git a/src/modeling.js b/src/modeling.jsindex a64d1d59..51165220 100644--- a/src/modeling.js+++ b/src/modeling.js@@ -1,4 +1,4 @@-import { LatheGeometry, ExtrudeGeometry, TubeGeometry, CatmullRomCurve3, Shape, Path, Vector2, Vector3 } from 'three';+import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';const MAX_INPUT_POINTS = 4096;const DEFAULT_VERTEX_LIMIT = 250_000;@@ -31,46 +31,37 @@ function checkBudget(vertices, maximum) {}function meshFrom(source, maximum) {- try {- const position = source.getAttribute('position');- checkBudget(position.count, maximum);- const normal = source.getAttribute('normal');- const uv = source.getAttribute('uv');- const positions = new Float32Array(position.array);- const normals = new Float32Array(normal.array);- const uvs = new Float32Array(uv.array);- const indices = source.index ? new Uint32Array(source.index.array) : Uint32Array.from({ length: position.count }, (_, index) => index);- for (let offset = 0; offset < normals.length; offset += 3) {- const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);- if (!Number.isFinite(length) || length === 0) throw new RangeError('Modeling produced an invalid normal. Adjust the profile or contour.');- for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;- }- for (const value of positions) if (!Number.isFinite(value)) throw new RangeError('Modeling geometry exceeds the finite Float32 range. Reduce coordinates.');- for (const value of uvs) if (!Number.isFinite(value)) throw new RangeError('Modeling produced invalid UVs. Adjust the profile or contour.');- let drawable = false;- for (let offset = 0; offset < indices.length; offset += 3) {- const first = indices[offset] * 3;- const second = indices[offset + 1] * 3;- const third = indices[offset + 2] * 3;- const ax = positions[second] - positions[first];- const ay = positions[second + 1] - positions[first + 1];- const az = positions[second + 2] - positions[first + 2];- const bx = positions[third] - positions[first];- const by = positions[third + 1] - positions[first + 1];- const bz = positions[third + 2] - positions[first + 2];- if (Math.hypot(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) > 0) {- drawable = true;- break;- }+ checkBudget(source.positions.length / 3, maximum);+ const { positions, normals, uvs } = source;+ const indices = source.indices ?? Uint32Array.from({ length: positions.length / 3 }, (_, index) => index);+ for (let offset = 0; offset < normals.length; offset += 3) {+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);+ if (!Number.isFinite(length) || length === 0) throw new RangeError('Modeling produced an invalid normal. Adjust the profile or contour.');+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;+ }+ for (const value of positions) if (!Number.isFinite(value)) throw new RangeError('Modeling geometry exceeds the finite Float32 range. Reduce coordinates.');+ for (const value of uvs) if (!Number.isFinite(value)) throw new RangeError('Modeling produced invalid UVs. Adjust the profile or contour.');+ let drawable = false;+ for (let offset = 0; offset < indices.length; offset += 3) {+ const first = indices[offset] * 3;+ const second = indices[offset + 1] * 3;+ const third = indices[offset + 2] * 3;+ const ax = positions[second] - positions[first];+ const ay = positions[second + 1] - positions[first + 1];+ const az = positions[second + 2] - positions[first + 2];+ const bx = positions[third] - positions[first];+ const by = positions[third + 1] - positions[first + 1];+ const bz = positions[third + 2] - positions[first + 2];+ if (Math.hypot(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) > 0) {+ drawable = true;+ break;}- if (!drawable) throw new RangeError('Modeling collapsed at Float32 precision. Center geometry locally and position it with a transform.');- return { positions, normals, uvs, indices };- } finally {- source.dispose();}+ if (!drawable) throw new RangeError('Modeling collapsed at Float32 precision. Center geometry locally and position it with a transform.');+ return { positions, normals, uvs, indices };}-/** Revolve a radius/height profile around Y, using the installed Three.js geometry implementation. */+/** Revolve a radius/height profile around Y. */export function lathe(profile, { segments = 64, startAngle = 0, sweep = Math.PI * 2, maxVertices = DEFAULT_VERTEX_LIMIT } = {}) {integer(segments, 3, 2048, 'segments');finite(startAngle, 'startAngle');@@ -80,7 +71,7 @@ export function lathe(profile, { segments = 64, startAngle = 0, sweep = Math.PIconst points = pointsFrom(profile, 2, 2, 'profile');if (points.some(point => point[0] < 0) || !points.some(point => point[0] > 0)) throw new RangeError('Profile radii must be nonnegative, with at least one positive radius.');checkBudget((segments + 1) * points.length, maxVertices);- return meshFrom(new LatheGeometry(points.map(point => new Vector2(...point)), segments, startAngle, sweep), maxVertices);+ return meshFrom(buildLathe(points, segments, startAngle, sweep), maxVertices);}function orientation(first, second, third) {@@ -247,11 +238,7 @@ export function extrude(contour, {if (ringsIntersect(inner[index], inner[other]) || inside(inner[index][0], inner[other]) || inside(inner[other][0], inner[index])) throw new RangeError('Holes cannot overlap, touch or contain each other.');}}- const shape = new Shape(outer.map(point => new Vector2(...point)));- shape.holes = inner.map(ring => new Path(ring.map(point => new Vector2(...point))));- return closeTJunctions(meshFrom(new ExtrudeGeometry(shape, {- depth, steps, bevelEnabled: beveled, bevelSize: bevel, bevelThickness, bevelSegments,- }), maxVertices));+ return closeTJunctions(meshFrom(buildExtrusion(outer, inner, { depth, steps, bevel, bevelThickness, bevelSegments }), maxVertices));}/** Sweep a circular tube along a centripetal Catmull-Rom curve. */@@ -267,6 +254,5 @@ export function tube(path, {if (closed && points[0].every((value, axis) => value === points.at(-1)[axis])) points.pop();if (points.length < (closed ? 3 : 2)) throw new RangeError('The path has too few distinct points.');checkBudget((segments + 1) * (radialSegments + 1), maxVertices);- const curve = new CatmullRomCurve3(points.map(point => new Vector3(...point)), closed, 'centripetal');- return meshFrom(new TubeGeometry(curve, segments, radius, radialSegments, closed), maxVertices);+ return meshFrom(buildTube(points, closed, radius, segments, radialSegments), maxVertices);}diff --git a/src/triangulate.js b/src/triangulate.jsnew file mode 100644index 00000000..24557792--- /dev/null+++ b/src/triangulate.js@@ -0,0 +1,149 @@+// Ear clipping for a simple contour with disjoint holes. Points are [x, y]; triangles come back counter-clockwise.+function cross(origin, first, second) {+ return (first[0] - origin[0]) * (second[1] - origin[1]) - (first[1] - origin[1]) * (second[0] - origin[0]);+}++export function signedArea(ring) {+ let area = 0;+ for (let index = 0, previous = ring.length - 1; index < ring.length; previous = index++) {+ area += ring[previous][0] * ring[index][1] - ring[index][0] * ring[previous][1];+ }+ return area / 2;+}++function samePosition(first, second) {+ return first[0] === second[0] && first[1] === second[1];+}++function segmentsTouch(startA, endA, startB, endB) {+ const sideStartB = cross(startA, endA, startB);+ const sideEndB = cross(startA, endA, endB);+ const sideStartA = cross(startB, endB, startA);+ const sideEndA = cross(startB, endB, endA);+ if (Math.sign(sideStartB) * Math.sign(sideEndB) < 0 && Math.sign(sideStartA) * Math.sign(sideEndA) < 0) return true;+ const within = (from, to, point) => point[0] >= Math.min(from[0], to[0]) && point[0] <= Math.max(from[0], to[0]) &&+ point[1] >= Math.min(from[1], to[1]) && point[1] <= Math.max(from[1], to[1]);+ return sideStartB === 0 && within(startA, endA, startB) || sideEndB === 0 && within(startA, endA, endB) ||+ sideStartA === 0 && within(startB, endB, startA) || sideEndA === 0 && within(startB, endB, endA);+}++// True when the direction toward target leaves the vertex into the region on the left of the ring.+function pointsIntoRegion(previous, vertex, next, target) {+ if (cross(previous, vertex, next) > 0) return cross(vertex, next, target) > 0 && cross(vertex, target, previous) > 0;+ return !(cross(vertex, previous, target) > 0 && cross(vertex, target, next) > 0);+}++function crossesBoundary(points, rings, from, to, ignoredA, ignoredB) {+ for (const ring of rings) {+ for (let index = 0; index < ring.length; index++) {+ const start = ring[index];+ const end = ring[(index + 1) % ring.length];+ if (start === ignoredA || end === ignoredA || start === ignoredB || end === ignoredB) continue;+ if (segmentsTouch(points[from], points[to], points[start], points[end])) return true;+ }+ }+ return false;+}++function bridgeHole(points, rings, merged, hole) {+ let holeStart = 0;+ for (let index = 1; index < hole.length; index++) {+ if (points[hole[index]][0] > points[hole[holeStart]][0]) holeStart = index;+ }+ const holeVertex = hole[holeStart];+ const holePrevious = hole[(holeStart + hole.length - 1) % hole.length];+ const holeNext = hole[(holeStart + 1) % hole.length];+ const candidates = [...new Set(merged)]+ .map(vertex => ({ vertex, distance: Math.hypot(points[vertex][0] - points[holeVertex][0], points[vertex][1] - points[holeVertex][1]) }))+ .sort((left, right) => left.distance - right.distance);+ for (const { vertex } of candidates) {+ if (!pointsIntoRegion(points[holePrevious], points[holeVertex], points[holeNext], points[vertex])) continue;+ if (crossesBoundary(points, rings, holeVertex, vertex, holeVertex, vertex)) continue;+ for (let position = 0; position < merged.length; position++) {+ if (merged[position] !== vertex) continue;+ const previous = points[merged[(position + merged.length - 1) % merged.length]];+ const next = points[merged[(position + 1) % merged.length]];+ if (!pointsIntoRegion(previous, points[vertex], next, points[holeVertex])) continue;+ const rotated = hole.map((_, offset) => hole[(holeStart + offset) % hole.length]);+ merged.splice(position + 1, 0, ...rotated, holeVertex, vertex);+ return;+ }+ }+ throw new RangeError('Triangulation could not connect a hole to the contour. Adjust the holes.');+}++function mergeHoles(points, outer, holes) {+ const rings = [outer, ...holes];+ const merged = [...outer];+ const pending = holes.map(hole => hole.slice()).sort((left, right) => {+ const rightmost = ring => Math.max(...ring.map(vertex => points[vertex][0]));+ return rightmost(right) - rightmost(left);+ });+ for (const hole of pending) bridgeHole(points, rings, merged, hole);+ return merged;+}++function clipEars(points, ring) {+ const count = ring.length;+ const previousOf = Array.from({ length: count }, (_, index) => (index + count - 1) % count);+ const nextOf = Array.from({ length: count }, (_, index) => (index + 1) % count);+ const triangles = [];+ const at = slot => points[ring[slot]];+ const isCoincident = (slot, tip) => [previousOf[tip], tip, nextOf[tip]].some(corner => samePosition(at(slot), at(corner)));+ const containsOtherVertex = tip => {+ const first = at(previousOf[tip]);+ const second = at(tip);+ const third = at(nextOf[tip]);+ for (let slot = nextOf[nextOf[tip]]; slot !== previousOf[tip]; slot = nextOf[slot]) {+ if (isCoincident(slot, tip)) continue;+ if (cross(at(previousOf[slot]), at(slot), at(nextOf[slot])) > 0) continue;+ const vertex = at(slot);+ if (cross(first, second, vertex) >= 0 && cross(second, third, vertex) >= 0 && cross(third, first, vertex) >= 0) return true;+ }+ return false;+ };+ const remove = tip => {+ nextOf[previousOf[tip]] = nextOf[tip];+ previousOf[nextOf[tip]] = previousOf[tip];+ return previousOf[tip];+ };+ const emit = tip => triangles.push([ring[previousOf[tip]], ring[tip], ring[nextOf[tip]]]);+ let remaining = count;+ let cursor = 0;+ let missed = 0;+ while (remaining > 3) {+ const area = cross(at(previousOf[cursor]), at(cursor), at(nextOf[cursor]));+ const forced = missed > remaining;+ if (area === 0) {+ cursor = remove(cursor);+ remaining--;+ missed = 0;+ } else if (area > 0 && (forced || !containsOtherVertex(cursor))) {+ emit(cursor);+ cursor = remove(cursor);+ remaining--;+ missed = 0;+ } else {+ cursor = nextOf[cursor];+ missed++;+ if (missed > remaining * 2) throw new RangeError('Triangulation failed. The contour or holes may touch or cross.');+ }+ }+ if (cross(at(previousOf[cursor]), at(cursor), at(nextOf[cursor])) > 0) emit(cursor);+ return triangles;+}++/** Vertex numbers follow the contour, then each hole in order. Returns counter-clockwise [a, b, c] triples. */+export function triangulate(contour, holes) {+ const points = [...contour, ...holes.flat()];+ const outerRing = contour.map((_, index) => index);+ if (signedArea(contour) < 0) outerRing.reverse();+ let offset = contour.length;+ const holeRings = holes.map(hole => {+ const ring = hole.map((_, index) => offset + index);+ offset += hole.length;+ if (signedArea(hole) > 0) ring.reverse();+ return ring;+ });+ return clipEars(points, mergeHoles(points, outerRing, holeRings));+}diff --git a/tests/fixtures/modeling-cases.mjs b/tests/fixtures/modeling-cases.mjsnew file mode 100644index 00000000..2a237c00--- /dev/null+++ b/tests/fixtures/modeling-cases.mjs@@ -0,0 +1,68 @@+// Inputs for lathe, extrude and tube taken from the modeling tests, the mesh recipe tests and the agent suite references.+function circle(radius, points, centerX = 0, centerY = 0, clockwise = false) {+ return Array.from({ length: points }, (_, index) => {+ const angle = (clockwise ? -1 : 1) * index / points * Math.PI * 2;+ return [centerX + radius * Math.cos(angle), centerY + radius * Math.sin(angle)];+ });+}++function rectangle(minimumX, minimumY, maximumX, maximumY, clockwise = false) {+ const ring = [[minimumX, minimumY], [maximumX, minimumY], [maximumX, maximumY], [minimumX, maximumY]];+ return clockwise ? ring.reverse() : ring;+}++function gearContour(teeth, tipRadius, rootRadius) {+ const points = [];+ for (let tooth = 0; tooth < teeth; tooth++) {+ const base = tooth / teeth * Math.PI * 2;+ const step = Math.PI * 2 / teeth;+ for (const [fraction, radius] of [[0, rootRadius], [0.15, rootRadius], [0.3, tipRadius], [0.55, tipRadius], [0.7, rootRadius]]) {+ const angle = base + fraction * step;+ points.push([radius * Math.cos(angle), radius * Math.sin(angle)]);+ }+ }+ return points;+}++const panes = [+ rectangle(-0.44, 0.06, -0.03, 0.57, true), rectangle(0.03, 0.06, 0.44, 0.57, true),+ rectangle(-0.44, 0.63, -0.03, 1.14, true), rectangle(0.03, 0.63, 0.44, 1.14, true),+];+const windowFrame = rectangle(-0.5, 0, 0.5, 1.2);+const lPlate = [[0, 0], [3, 0], [3, 1], [1, 1], [1, 3], [0, 3]];+const boltPipe = [[0.04, 0.3], [0.04, 0], [0.09, 0], [0.09, 0.02], [0.05, 0.02], [0.05, 0.28], [0.09, 0.28], [0.09, 0.3], [0.04, 0.3]];+const comb = [[0, 0], [6, 0], [6, 4], [5, 4], [5, 1], [4, 1], [4, 4], [3, 4], [3, 1], [2, 1], [2, 4], [0, 4]];+const arrow = [[0, 0], [4, 0], [4, 1], [6, 1], [3, 4], [0, 1.5], [1, 1]];++export const MODELING_CASES = [+ { name: 'lathe-cylinder', kind: 'lathe', profile: [[0, 0], [1, 0], [1, 2], [0, 2]], options: { segments: 128 } },+ { name: 'lathe-half-sweep', kind: 'lathe', profile: [[1, 0], [1, 2]], options: { segments: 8, sweep: Math.PI } },+ { name: 'lathe-quarter-offset', kind: 'lathe', profile: [[0, 0], [1, 0], [1, 2], [0, 2]], options: { segments: 16, startAngle: 1, sweep: Math.PI / 2 } },+ { name: 'lathe-pipe', kind: 'lathe', profile: boltPipe, options: { segments: 64 } },+ { name: 'lathe-vase', kind: 'lathe', profile: [[0.5, -1], [1, 0], [0.5, 1]], options: { segments: 8 } },+ { name: 'lathe-large-angle', kind: 'lathe', profile: [[1, 0], [1, 2]], options: { startAngle: 1e20, segments: 8 } },+ { name: 'lathe-cone-tip', kind: 'lathe', profile: [[0, 2], [1, 0]], options: { segments: 12 } },+ { name: 'lathe-tilted-profile', kind: 'lathe', profile: [[1, 1], [2, 0], [1, -1], [0.2, -1]], options: { segments: 20 } },+ { name: 'extrude-square', kind: 'extrude', contour: rectangle(-1, -1, 1, 1), options: { depth: 1 } },+ { name: 'extrude-concave', kind: 'extrude', contour: lPlate, options: { depth: 2 } },+ { name: 'extrude-comb', kind: 'extrude', contour: comb, options: { depth: 1 } },+ { name: 'extrude-arrow', kind: 'extrude', contour: arrow, options: { depth: 0.5, steps: 2 } },+ { name: 'extrude-hollow', kind: 'extrude', contour: rectangle(-2, -2, 2, 2), options: { holes: [[[-1, -1], [-1, 1], [1, 1], [1, -1]]], depth: 0.5 } },+ { name: 'extrude-hollow-reversed', kind: 'extrude', contour: rectangle(-2, -2, 2, 2).reverse(), options: { holes: [[[-1, -1], [-1, 1], [1, 1], [1, -1]].reverse()], depth: 0.5 } },+ { name: 'extrude-bevel', kind: 'extrude', contour: rectangle(-1, -1, 1, 1), options: { depth: 0.5, bevel: 0.1, bevelSegments: 6 } },+ { name: 'extrude-bevel-thickness', kind: 'extrude', contour: lPlate, options: { depth: 1, bevel: 0.05, bevelThickness: 0.1, bevelSegments: 2 } },+ { name: 'extrude-bevel-holes', kind: 'extrude', contour: windowFrame, options: { holes: panes, depth: 0.08, bevel: 0.005, bevelSegments: 2 } },+ { name: 'extrude-window', kind: 'extrude', contour: windowFrame, options: { holes: panes, depth: 0.08 } },+ { name: 'extrude-window-steps', kind: 'extrude', contour: windowFrame, options: { holes: panes, depth: 0.08, steps: 3 } },+ { name: 'extrude-hexagon', kind: 'extrude', contour: circle(0.05 / Math.sqrt(3), 6), options: { depth: 0.02 } },+ { name: 'extrude-gear', kind: 'extrude', contour: gearContour(12, 0.1, 0.085), options: { holes: [circle(0.02, 32, 0, 0, true)], depth: 0.02 } },+ { name: 'extrude-bracket', kind: 'extrude', contour: rectangle(-0.1, -0.05, 0.1, 0.05), options: { holes: [circle(0.01, 32, 0, 0, true), circle(0.01, 32, 0.06, 0, true)], depth: 0.02 } },+ { name: 'extrude-two-holes-bevel', kind: 'extrude', contour: circle(2, 24), options: { holes: [circle(0.5, 12, 1, 0), circle(0.5, 12, -1, 0)], depth: 0.3, bevel: 0.05, bevelSegments: 3 } },+ { name: 'tube-straight', kind: 'tube', path: [[0, 0, 0], [0, 2, 0]], options: { radius: 0.2, segments: 16, radialSegments: 24 } },+ { name: 'tube-closed', kind: 'tube', path: [[1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1]], options: { closed: true, segments: 48 } },+ { name: 'tube-cable', kind: 'tube', path: [[0, 0, 0], [1, 1, 0], [2, 0, 0]], options: { radius: 0.05 } },+ { name: 'tube-bend', kind: 'tube', path: [[0, 0, 0], [0, 1, 0], [1, 2, 0]], options: { segments: 8, radialSegments: 4 } },+ { name: 'tube-helix', kind: 'tube', path: Array.from({ length: 12 }, (_, index) => [Math.cos(index), index * 0.2, Math.sin(index)]), options: { radius: 0.08, segments: 90, radialSegments: 8 } },+ { name: 'tube-uneven-spacing', kind: 'tube', path: [[0, 0, 0], [0.1, 0, 0], [3, 1, 0], [3.1, 1.2, 1], [0, 3, 0]], options: { segments: 40, radialSegments: 6 } },+ { name: 'tube-closed-loop-plane', kind: 'tube', path: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], options: { closed: true, segments: 32, radialSegments: 8, radius: 0.05 } },+];diff --git a/tests/fixtures/modeling-golden.json b/tests/fixtures/modeling-golden.jsonnew file mode 100644index 00000000..daa363d1--- /dev/null+++ b/tests/fixtures/modeling-golden.json@@ -0,0 +1,512 @@+{+ "lathe-cylinder": {+ "vertices": 516,+ "triangles": 768,+ "volume": 6.28066227605207,+ "min": [+ -1,+ 0,+ -1+ ],+ "max": [+ 1,+ 2,+ 1+ ],+ "positions": "4a029d66e2324bbc",+ "normals": "585e151fd04c4ebc",+ "uvs": "f39ed52c122eb06f",+ "indices": "6667553a7e7a43c8"+ },+ "lathe-half-sweep": {+ "vertices": 18,+ "triangles": 16,+ "volume": 2.040978230244363,+ "min": [+ 0,+ 0,+ -1+ ],+ "max": [+ 1,+ 2,+ 1+ ],+ "positions": "fdbd2dbd3327a83e",+ "normals": "5a9273bdd7c8fa47",+ "uvs": "ab378c725e30ffda",+ "indices": "81449012a001cb45"+ },+ "lathe-quarter-offset": {+ "vertices": 68,+ "triangles": 96,+ "volume": 1.5682742255494029,+ "min": [+ 0,+ 0,+ -0.8414709568023682+ ],+ "max": [+ 0.9998334050178528,+ 2,+ 0.5403022766113281+ ],+ "positions": "4f2f186dff762693",+ "normals": "bf0c014bf0eaa79c",+ "uvs": "eca54d5498e351ad",+ "indices": "b4b12f5fd28d306a"+ },+ "lathe-pipe": {+ "vertices": 585,+ "triangles": 1024,+ "volume": 0.0015494553405216377,+ "min": [+ -0.09000000357627869,+ 0,+ -0.09000000357627869+ ],+ "max": [+ 0.09000000357627869,+ 0.30000001192092896,+ 0.09000000357627869+ ],+ "positions": "d12ba8dce57d8046",+ "normals": "faca756a9a830516",+ "uvs": "b4c63937f9addce7",+ "indices": "897e3ea251c175b0"+ },+ "lathe-vase": {+ "vertices": 27,+ "triangles": 32,+ "volume": 2.8284270763397217,+ "min": [+ -1,+ -1,+ -1+ ],+ "max": [+ 1,+ 1,+ 1+ ],+ "positions": "555de2b8412961a6",+ "normals": "caa3fcd0d6fffea1",+ "uvs": "ba0c38080e73ec71",+ "indices": "b73fc82a9ebf7c73"+ },+ "lathe-large-angle": {+ "vertices": 18,+ "triangles": 16,+ "volume": 3.771236155247705,+ "min": [+ -0.9477165937423706,+ 0,+ -0.9477165937423706+ ],+ "max": [+ 0.9477165937423706,+ 2,+ 0.9477165937423706+ ],+ "positions": "3f16a97ea5d9be5a",+ "normals": "0ceeeda27372e240",+ "uvs": "ab378c725e30ffda",+ "indices": "81449012a001cb45"+ },+ "lathe-cone-tip": {+ "vertices": 26,+ "triangles": 24,+ "volume": -1.999999964103537,+ "min": [+ -1,+ 0,+ -1+ ],+ "max": [+ 1,+ 2,+ 1+ ],+ "positions": "d55b8a386442f60b",+ "normals": "b76423c1a1864d17",+ "uvs": "7b8f695143e5b9a6",+ "indices": "a4b4f8db7133a583"+ },+ "lathe-tilted-profile": {+ "vertices": 84,+ "triangles": 120,+ "volume": -13.349534443844357,+ "min": [+ -2,+ -1,+ -2+ ],+ "max": [+ 2,+ 1,+ 2+ ],+ "positions": "831776d2da0b9657",+ "normals": "feb66575e6a69c05",+ "uvs": "86ef86dc2c47c8e7",+ "indices": "9a927e78ce1646ab"+ },+ "extrude-square": {+ "vertices": 36,+ "triangles": 12,+ "volume": 4,+ "min": [+ -1,+ -1,+ 0+ ],+ "max": [+ 1,+ 1,+ 1+ ]+ },+ "extrude-concave": {+ "vertices": 60,+ "triangles": 20,+ "volume": 10,+ "min": [+ 0,+ 0,+ 0+ ],+ "max": [+ 3,+ 3,+ 2+ ]+ },+ "extrude-comb": {+ "vertices": 132,+ "triangles": 44,+ "volume": 17.999999999999993,+ "min": [+ 0,+ 0,+ 0+ ],+ "max": [+ 6,+ 4,+ 1+ ]+ },+ "extrude-arrow": {+ "vertices": 114,+ "triangles": 38,+ "volume": 6.499999999999998,+ "min": [+ 0,+ 0,+ 0+ ],+ "max": [+ 6,+ 4,+ 0.5+ ]+ },+ "extrude-hollow": {+ "vertices": 96,+ "triangles": 32,+ "volume": 5.999999999999998,+ "min": [+ -2,+ -2,+ 0+ ],+ "max": [+ 2,+ 2,+ 0.5+ ]+ },+ "extrude-hollow-reversed": {+ "vertices": 96,+ "triangles": 32,+ "volume": 5.999999999999998,+ "min": [+ -2,+ -2,+ 0+ ],+ "max": [+ 2,+ 2,+ 0.5+ ]+ },+ "extrude-bevel": {+ "vertices": 324,+ "triangles": 108,+ "volume": 3.3494758087827843,+ "min": [+ -1.100000023841858,+ -1.100000023841858,+ -0.10000000149011612+ ],+ "max": [+ 1.100000023841858,+ 1.100000023841858,+ 0.6000000238418579+ ]+ },+ "extrude-bevel-thickness": {+ "vertices": 204,+ "triangles": 68,+ "volume": 6.695990695771738,+ "min": [+ -0.05000000074505806,+ -0.05000000074505806,+ -0.10000000149011612+ ],+ "max": [+ 3.049999952316284,+ 3.049999952316284,+ 1.100000023841858+ ]+ },+ "extrude-bevel-holes": {+ "vertices": 740,+ "triangles": 252,+ "volume": 0.03781807385045756,+ "min": [+ -0.5049999952316284,+ -0.004999999888241291,+ -0.004999999888241291+ ],+ "max": [+ 0.5049999952316284,+ 1.2050000429153442,+ 0.08500000089406967+ ]+ },+ "extrude-window": {+ "vertices": 260,+ "triangles": 92,+ "volume": 0.029088004451036317,+ "min": [+ -0.5,+ 0,+ 0+ ],+ "max": [+ 0.5,+ 1.2000000476837158,+ 0.07999999821186066+ ]+ },+ "extrude-window-steps": {+ "vertices": 500,+ "triangles": 172,+ "volume": 0.029088004451036334,+ "min": [+ -0.5,+ 0,+ 0+ ],+ "max": [+ 0.5,+ 1.2000000476837158,+ 0.07999999821186066+ ]+ },+ "extrude-hexagon": {+ "vertices": 60,+ "triangles": 20,+ "volume": 0.000043301269089421085,+ "min": [+ -0.028867512941360474,+ -0.02500000037252903,+ 0+ ],+ "max": [+ 0.028867512941360474,+ 0.02500000037252903,+ 0.019999999552965164+ ]+ },+ "extrude-gear": {+ "vertices": 1104,+ "triangles": 368,+ "volume": 0.0004953691361417042,+ "min": [+ -0.09876883774995804,+ -0.09876883774995804,+ 0+ ],+ "max": [+ 0.09876883774995804,+ 0.09876883774995804,+ 0.019999999552965164+ ]+ },+ "extrude-bracket": {+ "vertices": 828,+ "triangles": 276,+ "volume": 0.00038751422308239093,+ "min": [+ -0.10000000149011612,+ -0.05000000074505806,+ 0+ ],+ "max": [+ 0.10000000149011612,+ 0.05000000074505806,+ 0.019999999552965164+ ]+ },+ "extrude-two-holes-bevel": {+ "vertices": 2316,+ "triangles": 772,+ "volume": 4.717779643442089,+ "min": [+ -2.050431489944458,+ -2.050431489944458,+ -0.05000000074505806+ ],+ "max": [+ 2.050431489944458,+ 2.050431489944458,+ 0.3500000238418579+ ]+ },+ "tube-straight": {+ "vertices": 425,+ "triangles": 768,+ "volume": 0.1656441914722437,+ "min": [+ -0.20000000298023224,+ 0,+ -0.20000000298023224+ ],+ "max": [+ 0.20000000298023224,+ 2,+ 0.20000000298023224+ ],+ "positions": "1e21eb78f8cd2aa2",+ "normals": "b83eb84ea029546c",+ "uvs": "1eca9572bdc2f273",+ "indices": "8450f32c6d45ad35"+ },+ "tube-closed": {+ "vertices": 637,+ "triangles": 1152,+ "volume": 0.17757045882365696,+ "min": [+ -1.100000023841858,+ -0.10000000149011612,+ -1.100000023841858+ ],+ "max": [+ 1.100000023841858,+ 0.10000000149011612,+ 1.100000023841858+ ],+ "positions": "e1f01e9ad7e89980",+ "normals": "4a0c7043a49646fa",+ "uvs": "a4f13ef46796bc2a",+ "indices": "1a55be1da0a62345"+ },+ "tube-cable": {+ "vertices": 845,+ "triangles": 1536,+ "volume": 0.018122973440457248,+ "min": [+ -0.03535887226462364,+ -0.03535180538892746,+ -0.05000000074505806+ ],+ "max": [+ 2.0353589057922363,+ 1.0499999523162842,+ 0.05000000074505806+ ],+ "positions": "fa4f4562b4a43a42",+ "normals": "7934dbddf85e99b3",+ "uvs": "f7da278e7f87f3af",+ "indices": "cf39ce4fab7d0386"+ },+ "tube-bend": {+ "vertices": 45,+ "triangles": 64,+ "volume": 0.03424469273776702,+ "min": [+ -0.15498220920562744,+ -0.000007680552698730025,+ -0.10000000149011612+ ],+ "max": [+ 1.0707061290740967,+ 2.0707151889801025,+ 0.10000000149011612+ ],+ "positions": "80fbaea3f92246a2",+ "normals": "d043429bcf2f1485",+ "uvs": "64c426c180f9e615",+ "indices": "51a22de4c5aa6497"+ },+ "tube-helix": {+ "vertices": 819,+ "triangles": 1440,+ "volume": 0.19145492106961087,+ "min": [+ -1.0730938911437988,+ -0.07831534743309021,+ -1.0693222284317017+ ],+ "max": [+ 1.0702242851257324,+ 2.27445912361145,+ 1.0747579336166382+ ],+ "positions": "c2f92fd722aa97e2",+ "normals": "f06b959e051d4bff",+ "uvs": "46b684e00b1aae89",+ "indices": "7da571c696f81a0d"+ },+ "tube-uneven-spacing": {+ "vertices": 287,+ "triangles": 480,+ "volume": 0.19583921635733714,+ "min": [+ -0.05452808365225792,+ -0.08660253882408142,+ -0.26232200860977173+ ],+ "max": [+ 3.2907915115356445,+ 3.08392071723938,+ 1.1533440351486206+ ],+ "positions": "fe9c7e1c066313f2",+ "normals": "bdce0b6e190077df",+ "uvs": "42e94cc5633db7ca",+ "indices": "ec303c0abfbef03c"+ },+ "tube-closed-loop-plane": {+ "vertices": 297,+ "triangles": 512,+ "volume": 0.029444279493081458,+ "min": [+ -0.17499999701976776,+ -0.17499999701976776,+ -0.05000000074505806+ ],+ "max": [+ 1.1749999523162842,+ 1.1749999523162842,+ 0.05000000074505806+ ],+ "positions": "6872a7cc8e9bd14c",+ "normals": "17b020d043ebd7a0",+ "uvs": "fb71c4d76c33107e",+ "indices": "333ac23b4896135b"+ }+}diff --git a/tests/modeling-parity.test.js b/tests/modeling-parity.test.jsnew file mode 100644index 00000000..fadd9c2b--- /dev/null+++ b/tests/modeling-parity.test.js@@ -0,0 +1,58 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { lathe, extrude, tube } from '../src/modeling.js';+import { MODELING_CASES } from './fixtures/modeling-cases.mjs';++// modeling-golden.json holds what the former three.js generators produced for each case.+const golden = JSON.parse(readFileSync(new URL('./fixtures/modeling-golden.json', import.meta.url), 'utf8'));+const generators = { lathe, extrude, tube };+const TOLERANCE = 1e-4;++// Adding zero turns -0 into 0: the former generators signed some zeros differently, which no consumer can see.+function hashOf(values) {+ const unsigned = values.constructor.from(values, value => value + 0);+ return createHash('sha256').update(Buffer.from(unsigned.buffer)).digest('hex').slice(0, 16);+}++function measure(mesh) {+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const p = mesh.positions;+ for (let offset = 0; offset < p.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ min[axis] = Math.min(min[axis], p[offset + axis]);+ max[axis] = Math.max(max[axis], p[offset + axis]);+ }+ }+ let volume = 0;+ for (let offset = 0; offset < mesh.indices.length; offset += 3) {+ const a = mesh.indices[offset] * 3;+ const b = mesh.indices[offset + 1] * 3;+ const c = mesh.indices[offset + 2] * 3;+ volume += (p[a] * (p[b + 1] * p[c + 2] - p[b + 2] * p[c + 1]) + p[a + 1] * (p[b + 2] * p[c] - p[b] * p[c + 2]) + p[a + 2] * (p[b] * p[c + 1] - p[b + 1] * p[c])) / 6;+ }+ return { min, max, volume };+}++for (const item of MODELING_CASES) {+ test(`modeling output matches the former generator: ${item.name}`, () => {+ const input = item.kind === 'lathe' ? item.profile : item.kind === 'tube' ? item.path : item.contour;+ const mesh = generators[item.kind](input, item.options);+ const expected = golden[item.name];+ const measured = measure(mesh);+ assert.ok(Math.abs(measured.volume - expected.volume) < TOLERANCE, `volume ${measured.volume} against ${expected.volume}`);+ for (let axis = 0; axis < 3; axis++) {+ assert.ok(Math.abs(measured.min[axis] - expected.min[axis]) < TOLERANCE, `min ${axis}`);+ assert.ok(Math.abs(measured.max[axis] - expected.max[axis]) < TOLERANCE, `max ${axis}`);+ }+ if (item.kind === 'extrude') return;+ assert.equal(mesh.positions.length / 3, expected.vertices);+ assert.equal(mesh.indices.length / 3, expected.triangles);+ assert.equal(hashOf(mesh.positions), expected.positions);+ assert.equal(hashOf(mesh.normals), expected.normals);+ assert.equal(hashOf(mesh.uvs), expected.uvs);+ assert.equal(hashOf(mesh.indices), expected.indices);+ });+}diff --git a/tests/triangulate.test.js b/tests/triangulate.test.jsnew file mode 100644index 00000000..dbe9902a--- /dev/null+++ b/tests/triangulate.test.js@@ -0,0 +1,43 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { signedArea, triangulate } from '../src/triangulate.js';++function starRing(count, center, innerRadius, outerRadius, seed) {+ let state = seed;+ const random = () => {+ state = (state * 1664525 + 1013904223) % 4294967296;+ return state / 4294967296;+ };+ return Array.from({ length: count }, (_, index) => {+ const angle = index / count * Math.PI * 2;+ const radius = innerRadius + (outerRadius - innerRadius) * random();+ return [center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)];+ });+}++function trianglesArea(points, triangles) {+ return triangles.reduce((sum, [a, b, c]) => {+ const area = signedArea([points[a], points[b], points[c]]);+ assert.ok(area > 0, 'triangles must be counter-clockwise');+ return sum + area;+ }, 0);+}++test('ear clipping covers star contours with several holes exactly once', () => {+ for (let seed = 1; seed <= 40; seed++) {+ const contour = starRing(5 + seed % 30, [0, 0], 8, 10, seed);+ const holes = [[-4, 0], [4, 0], [0, 4], [0, -4]].slice(0, seed % 5).map((center, index) =>+ starRing(3 + (seed + index) % 9, center, 0.8, 1.6, seed * 7 + index).reverse());+ const triangles = triangulate(contour, holes);+ const points = [...contour, ...holes.flat()];+ const expected = Math.abs(signedArea(contour)) - holes.reduce((sum, hole) => sum + Math.abs(signedArea(hole)), 0);+ assert.ok(Math.abs(trianglesArea(points, triangles) - expected) < 1e-9, `seed ${seed}`);+ }+});++test('ear clipping accepts clockwise contours and counter-clockwise holes', () => {+ const contour = [[0, 0], [0, 4], [4, 4], [4, 0]];+ const hole = [[1, 1], [3, 1], [3, 3], [1, 3]];+ const points = [...contour, ...hole];+ assert.equal(trianglesArea(points, triangulate(contour, [hole])), 12);+});