3D engine that AI agents drive
Add uv_project and uv_pack mesh edits for cube, cylinder, sphere UVs and island packing (#702)
Nguyen Xuan An6a272c1db69c
diff --git a/changes/702.md b/changes/702.mdnew file mode 100644index 00000000..aff31695--- /dev/null+++ b/changes/702.md@@ -0,0 +1 @@+- `uv_project` (cube, cylinder, sphere) and `uv_pack` mesh edits write and pack UVs with one texel density (#702)diff --git a/changes/702.size.md b/changes/702.size.mdnew file mode 100644index 00000000..12a71255--- /dev/null+++ b/changes/702.size.md@@ -0,0 +1,3 @@+- scene:agent-scene: cube, cylinder and sphere UV projection and island packing are a modeling capability agents lacked (352 bytes gzip)+- scene:agent-scene+lazy: the same code ships in the lazy bundle (1612 bytes gzip)+- goal:agent-scene: the capability is worth 352 bytes gzip over the goal; lead approved growth for modeling featuresdiff --git a/docs/mesh.md b/docs/mesh.mdindex d6974e9d..8c62c677 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -550,3 +550,28 @@ one thread at below-normal priority on a shared machine, medians of five runs. RThe `EditMesh` arrays take about 200 bytes per quad face without attributes. These numbers are this machine onlyand say nothing about Blender's speed.++### UV projection and packing++`uv_project` writes the corner attribute `uv` by a simple projection, and `uv_pack` repacks the islands a mesh already+has. Both work as an edit or as a stack node and change no geometry.++| Field | Meaning |+| --- | --- |+| `mode` | `cube` (each face by its dominant axis), `cylinder` (sides wrap around `axis`, caps project flat) or `sphere` (longitude and latitude); `uv_project` only, required |+| `axis` | `x`, `y` (default) or `z`, the cylinder or sphere axis |+| `pack` | `true` (default) packs the result into the unit square; `false` leaves uv in mesh units for a later `uv_pack` |+| `margin` | Gap between islands and around the square, 0 to 0.2 (default 0.01) |+| `rotate` | `true` (default) lays tall islands on their side; `false` keeps them upright |++Cylinder and sphere uv are measured from the centre of the bounds. `u` is arc length at the mean radius of the mesh+and `v` is the height (cylinder) or the latitude times that radius (sphere), so one unit of uv covers about one unit+of surface at the mean radius. Faces that wrap are cut on the side opposite the first radial axis. Islands are the+faces joined across edges whose two ends share the same uv; `uv_pack` finds them from the uv itself, so it also packs+an `uv_unwrap` result again (for example after `pack: false` merges) or a hand-set layout. Every island takes one common+scale, shelf-packed with a gap, so texel density keeps its ratio between islands and no two islands overlap.++Texel density measured in the tests: a cube projection gives a crate six islands with the same density to 0.1 percent,+a 24-sided cylinder projection keeps a barrel within 15 percent of the median, and a sphere stretches toward the poles+as any equirectangular map does. The result reports `islands`. Not done yet: view and angle-based smart projection,+and `uv_warp` (offset, scale and rotate by a field); `uv_unwrap` still covers general meshes.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 50ed7822..ef846d3c 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -438,6 +438,8 @@ const stackNodes = [margin: bounded(0, 0.2).optional().describe('Gap between islands and around the square, as a fraction of it. Defaults to 0.01.'),maxDistortion: bounded(0, 100).optional().describe('Islands stretching more than this (mean |area ratio - 1|) are split into charts by facing axis. Defaults to 0.25.'),}).describe('Conformal UV unwrap into the corner attribute uv, packed into 0..1. Put it last (or as the last stack node): later edits do not keep UVs exact. The result reports islands, flipped triangles and areaDistortion.'),+ z.strictObject({ op: z.literal('uv_project'), mode: z.enum(['cube', 'cylinder', 'sphere']), axis: z.enum(['x', 'y', 'z']).optional(), pack: z.boolean().optional(), margin: bounded(0, 0.2).optional(), rotate: z.boolean().optional() }).describe('Cube, cylinder or sphere uv projection, packed into 0..1. Detail: scene_capabilities meshUv.'),+ z.strictObject({ op: z.literal('uv_pack'), margin: bounded(0, 0.2).optional(), rotate: z.boolean().optional() }).describe('Pack the existing uv islands into 0..1 with one scale.'),z.strictObject({op: z.literal('subdivide'),levels: z.number().int().min(1).max(4).optional().describe('Catmull-Clark levels; each multiplies the faces by about 4 (n-gons become n quads). Defaults to 1.'),diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 4945350b..6d4d9847 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -166,6 +166,12 @@ export const MESH_ATTRIBUTE_NOTES = Object.freeze({vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Drawn, written as COLOR_0 in a GLB, and multiplies the material color.',});+// UV projection and packing edits. Details stay here so the tool schemas stay small.+export const MESH_UV_NOTES = Object.freeze({+ uv_project: 'mode cube (each face by its dominant axis), cylinder (sides wrap around axis, caps flat) or sphere (longitude and latitude); axis x|y|z (y) for the last two, measured from the bounds centre; wrapped faces cut opposite the first radial axis. pack true (default) packs into 0..1 with one scale for every island so texel density is even; false leaves uv in mesh units for a later uv_pack. margin 0-0.2 (0.01); rotate true lays tall islands on their side. Reports islands. Texel density: cube exact, cylinder within about 15 percent, sphere stretches toward the poles.',+ uv_pack: 'repacks the islands already in uv (faces joined across edges whose two ends share uv) into 0..1 with one scale. margin 0-0.2 (0.01), rotate true. Needs uv from uv_unwrap or uv_project. Reports islands.',+});+// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.export const MESH_SHAPE_KEY_NOTES = Object.freeze({shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are vertex-moving mesh edits run after the stack. value (0, 0 to 1) is the weight without motion. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }.',@@ -189,6 +195,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({meshModifiers: MESH_MODIFIER_NOTES,meshSculpt: MESH_SCULPT_NOTES,meshAttributes: MESH_ATTRIBUTE_NOTES,+ meshUv: MESH_UV_NOTES,meshShapeKeys: MESH_SHAPE_KEY_NOTES,fieldExpressions: Object.freeze({operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 4b2fc752..76709375 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -43,6 +43,8 @@ export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({bevel: { fields: ['name', 'edges', 'width', 'segments', 'profile', 'clampOverlap'], tags: ['strip', 'corner'] },loop_cut: { fields: ['name', 'edges', 'cuts', 'factor'], tags: ['band-<k>'] },uv_unwrap: { fields: ['seams', 'margin', 'maxDistortion'], tags: [] },+ uv_project: { fields: ['mode', 'axis', 'pack', 'margin', 'rotate'], tags: [] },+ uv_pack: { fields: ['margin', 'rotate'], tags: [] },subdivide: { fields: ['levels', 'crease', 'sharpness'], tags: [] },fill_holes: { fields: ['name', 'sides'], tags: ['fill'] },dissolve_faces: { fields: ['select', 'name'], tags: ['merged'] },@@ -72,7 +74,7 @@ export const MAX_SCULPT_VISITS = 5_000_000;export const SHRINKWRAP_MODES = /* @__PURE__ */ Object.freeze(['nearest', 'project']);export const MAX_SHRINKWRAP_TRIANGLE_TESTS = 20_000_000;-export const STACK_OPERATIONS = /* @__PURE__ */ Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide', 'set_position', 'displace', 'decimate', 'remesh', ...Object.keys(MODIFIER_OPERATIONS)]);+export const STACK_OPERATIONS = /* @__PURE__ */ Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'uv_project', 'uv_pack', 'subdivide', 'set_position', 'displace', 'decimate', 'remesh', ...Object.keys(MODIFIER_OPERATIONS)]);export const MAX_STACK_NODES = 16;// Field expressions (mesh-fields.js) and instancing (mesh-instances.js): limits and names as plain data. A testdiff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex de084009..fb67a790 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -1,6 +1,6 @@import { editMesh, meshData } from './mesh-edit.js';import { invalidField } from './field-error.js';-import { editField } from './mesh-edit-field.js';+import { editField, editBoolean } from './mesh-edit-field.js';import { countSelected, selectFaces } from './mesh-select.js';import {extrudeFaceRegion, extrudeIndividual, insetRegion, insetIndividual, deleteFaces, flipFaces, translateFaces, mergeByDistance, tagFaces,@@ -13,6 +13,7 @@ import { bevelEdges } from './mesh-bevel.js';import { loopCut } from './mesh-loopcut.js';import { CUT_OPERATIONS, normalizeCutEdit, runCutEdit, checkCutBudget } from './mesh-cut-edits.js';import { unwrapUv } from './mesh-uv.js';+import { projectUv, packUvIslands, UV_PROJECTION_MODES } from './mesh-uv-project.js';import { runKernel, KernelDeferred } from './kernel-offload.js';import { validateField } from './mesh-fields.js';import { setPosition, displaceMesh, DISPLACE_DIRECTIONS } from './mesh-field-edits.js';@@ -249,6 +250,22 @@ export function normalizeMeshEdits(edits) {normalized.margin = edit.margin === undefined ? 0.01 : finiteNumber(edit.margin, index, 'margin', { minimum: 0, maximum: 0.2 });normalized.maxDistortion = edit.maxDistortion === undefined ? 0.25 : finiteNumber(edit.maxDistortion, index, 'maxDistortion', { minimum: 0, maximum: 100 });break;+ case 'uv_project':+ if (!UV_PROJECTION_MODES.includes(edit.mode)) throw editField(index, 'mode', edit.mode, `one of ${UV_PROJECTION_MODES.join(', ')}`);+ normalized.mode = edit.mode;+ if (!['x', 'y', 'z'].includes(edit.axis ?? 'y')) throw editField(index, 'axis', edit.axis, '"x", "y" or "z", the cylinder or sphere axis');+ normalized.axis = edit.axis ?? 'y';+ normalized.pack = edit.pack ?? true;+ normalized.margin = edit.margin === undefined ? 0.01 : finiteNumber(edit.margin, index, 'margin', { minimum: 0, maximum: 0.2 });+ normalized.rotate = edit.rotate ?? true;+ editBoolean(normalized.pack, index, 'pack');+ editBoolean(normalized.rotate, index, 'rotate');+ break;+ case 'uv_pack':+ normalized.margin = edit.margin === undefined ? 0.01 : finiteNumber(edit.margin, index, 'margin', { minimum: 0, maximum: 0.2 });+ normalized.rotate = edit.rotate ?? true;+ editBoolean(normalized.rotate, index, 'rotate');+ break;case 'subdivide':if (!Number.isInteger(edit.levels ?? 1) || (edit.levels ?? 1) < 1 || (edit.levels ?? 1) > MAX_SUBDIVISION_LEVELS) {throw editField(index, 'levels', edit.levels, `a whole number from 1 to ${MAX_SUBDIVISION_LEVELS}, such as 1`);@@ -555,6 +572,16 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {result.utilization = Number(outcome.utilization.toFixed(4));return { mesh: outcome.mesh, result };}+ if (edit.op === 'uv_project' || edit.op === 'uv_pack') {+ let outcome;+ try {+ outcome = edit.op === 'uv_project' ? projectUv(current, edit) : packUvIslands(current, edit);+ } catch (error) {+ throw editFailure(error, index, edit.op);+ }+ result.islands = outcome.islands;+ return { mesh: outcome.mesh, result };+ }if (Object.hasOwn(GENERATORS, edit.op)) {const generated = GENERATORS[edit.op](current, edit);result.tags = tagSummary(generated, edit.name);diff --git a/src/mesh-uv-project.js b/src/mesh-uv-project.jsnew file mode 100644index 00000000..aae7366b--- /dev/null+++ b/src/mesh-uv-project.js@@ -0,0 +1,186 @@+import { createMeshData, DOMAINS } from './mesh-data.js';+import { faceNormals } from './mesh-normals.js';+import { cornerCycles, edgeCornerTable, UnionFind } from './mesh-topology.js';+import { bounds2d, packIslands } from './mesh-uv.js';++// Projected UVs: cube, cylinder and sphere mapping, and packing of the islands that already exist in the corner+// attribute `uv`. Both are deterministic and keep one texel density across all islands.++export const UV_PROJECTION_MODES = Object.freeze(['cube', 'cylinder', 'sphere']);+const AXIS_INDEX = Object.freeze({ x: 0, y: 1, z: 2 });+const TWO_PI = Math.PI * 2;+const SAME_UV = 1e-6;+// A cylinder face whose normal leans more than 45 degrees along the axis is a cap and projects flat.+const CAP_THRESHOLD = Math.SQRT1_2;++function withCornerUv(mesh, uv) {+ const attributes = {};+ for (const domain of DOMAINS) attributes[domain] = { ...mesh.attributes[domain] };+ attributes.corner.uv = { data: uv, size: 2 };+ return createMeshData({+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,+ });+}++function boundsCenter(mesh) {+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ for (let axis = 0; axis < 3; axis++) {+ const value = mesh.positions[vertex * 3 + axis];+ low[axis] = Math.min(low[axis], value);+ high[axis] = Math.max(high[axis], value);+ }+ }+ return low.map((value, axis) => (value + high[axis]) / 2);+}++function cornerPoint(mesh, corner, center) {+ const vertex = mesh.cornerVertices[corner];+ return [0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis] - center[axis]);+}++/** Flat projection along the face's dominant axis, mirrored on the negative side so the picture is never reversed. */+function projectFlat(point, normalAxis, normalNegative) {+ const first = (normalAxis + 1) % 3;+ const second = (normalAxis + 2) % 3;+ return [normalNegative ? -point[first] : point[first], point[second]];+}++function dominantAxis(normals, face) {+ let best = 0;+ for (let axis = 1; axis < 3; axis++) {+ if (Math.abs(normals[face * 3 + axis]) > Math.abs(normals[face * 3 + best])) best = axis;+ }+ return best;+}++/** Longitude of each corner, shifted by whole turns to lie within half a turn of the face's first measurable corner. */+function faceLongitudes(mesh, face, axis, center) {+ const first = (axis + 1) % 3;+ const second = (axis + 2) % 3;+ const angles = [];+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const point = cornerPoint(mesh, corner, center);+ const onAxis = Math.hypot(point[first], point[second]) < 1e-9;+ angles.push(onAxis ? null : Math.atan2(point[second], point[first]));+ }+ const reference = angles.find(angle => angle !== null) ?? 0;+ return angles.map(angle => {+ if (angle === null) return reference;+ let shifted = angle;+ while (shifted - reference > Math.PI) shifted -= TWO_PI;+ while (shifted - reference < -Math.PI) shifted += TWO_PI;+ return shifted;+ });+}++function meanDistance(mesh, center, distanceOf) {+ let total = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const point = [0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis] - center[axis]);+ total += distanceOf(point);+ }+ const mean = mesh.vertexCount ? total / mesh.vertexCount : 0;+ return mean > 1e-9 ? mean : 1;+}++/** Corner uv in mesh units for one projection, before packing. */+function projectCorners(mesh, mode, axis) {+ const center = boundsCenter(mesh);+ const { normals } = faceNormals(mesh);+ const uv = new Float32Array(mesh.cornerCount * 2);+ const first = (axis + 1) % 3;+ const second = (axis + 2) % 3;+ const radius = mode === 'cylinder'+ ? meanDistance(mesh, center, point => Math.hypot(point[first], point[second]))+ : meanDistance(mesh, center, point => Math.hypot(point[0], point[1], point[2]));+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ const isCap = mode === 'cylinder' && Math.abs(normals[face * 3 + axis]) > CAP_THRESHOLD;+ const longitudes = mode === 'cube' || isCap ? null : faceLongitudes(mesh, face, axis, center);+ const flatAxis = mode === 'cube' ? dominantAxis(normals, face) : axis;+ for (let corner = start; corner < end; corner++) {+ const point = cornerPoint(mesh, corner, center);+ let u;+ let v;+ if (!longitudes) {+ [u, v] = projectFlat(point, flatAxis, normals[face * 3 + flatAxis] < 0);+ } else if (mode === 'cylinder') {+ u = longitudes[corner - start] * radius;+ v = point[axis];+ } else {+ u = longitudes[corner - start] * radius;+ v = Math.asin(Math.max(-1, Math.min(1, point[axis] / Math.max(Math.hypot(point[0], point[1], point[2]), 1e-12)))) * radius;+ }+ uv[corner * 2] = u;+ uv[corner * 2 + 1] = v;+ }+ }+ return uv;+}++/** Faces joined across edges where both faces agree on the uv of both ends form one island. */+function uvIslands(mesh, uv) {+ const table = edgeCornerTable(mesh);+ const { nextCorner } = cornerCycles(mesh);+ const faceOfCorner = new Uint32Array(mesh.cornerCount);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) faceOfCorner[corner] = face;+ }+ const same = (left, right) => Math.abs(uv[left * 2] - uv[right * 2]) <= SAME_UV && Math.abs(uv[left * 2 + 1] - uv[right * 2 + 1]) <= SAME_UV;+ const faces = new UnionFind(mesh.faceCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (table.edgeOffsets[edge + 1] - table.edgeOffsets[edge] !== 2) continue;+ const first = table.edgeCorners[table.edgeOffsets[edge]];+ const second = table.edgeCorners[table.edgeOffsets[edge] + 1];+ if (same(first, nextCorner[second]) && same(nextCorner[first], second)) faces.union(faceOfCorner[first], faceOfCorner[second]);+ }+ const islands = new Map();+ for (let face = 0; face < mesh.faceCount; face++) {+ const root = faces.find(face);+ if (!islands.has(root)) islands.set(root, []);+ islands.get(root).push(face);+ }+ return [...islands.values()];+}++/**+ * Pack the uv islands of corner attribute `uv` into the unit square with one common scale, so texel density keeps its+ * ratio between islands. margin: gap between islands and around the square. rotate: lay tall islands on their side.+ * Returns the new mesh and the island count.+ */+export function packUvIslands(mesh, { margin = 0.01, rotate = true } = {}) {+ const uv = mesh.attributes.corner.uv?.data;+ if (!uv) throw new RangeError('the mesh has no uv to pack. Put uv_unwrap, or uv_project with pack false, before uv_pack.');+ const islands = uvIslands(mesh, uv);+ const placed = islands.map(faces => {+ const corners = [];+ for (const face of faces) for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) corners.push(corner);+ const points = corners.map(corner => [uv[corner * 2], uv[corner * 2 + 1]]);+ return { corners, points, box: bounds2d(points), offset: [0, 0] };+ });+ if (!placed.length) return { mesh, islands: 0 };+ const scale = packIslands(placed, margin, rotate);+ const packed = new Float32Array(mesh.cornerCount * 2);+ for (const item of placed) {+ item.corners.forEach((corner, index) => {+ packed[corner * 2] = margin + (item.points[index][0] + item.offset[0]) * scale;+ packed[corner * 2 + 1] = margin + (item.points[index][1] + item.offset[1]) * scale;+ });+ }+ return { mesh: withCornerUv(mesh, packed), islands: placed.length };+}++/**+ * Project the mesh to uv. mode cube: each face by its dominant axis; cylinder: side faces wrap around axis (u is arc+ * length at the mean radius, v the height) and caps project flat; sphere: longitude and latitude at the mean radius.+ * pack lays the islands into the unit square; without it uv stays in mesh units.+ */+export function projectUv(mesh, { mode = 'cube', axis = 'y', pack = true, margin = 0.01, rotate = true } = {}) {+ const projected = withCornerUv(mesh, projectCorners(mesh, mode, AXIS_INDEX[axis]));+ if (!pack) return { mesh: projected, islands: uvIslands(projected, projected.attributes.corner.uv.data).length };+ return packUvIslands(projected, { margin, rotate });+}diff --git a/src/mesh-uv.js b/src/mesh-uv.jsindex f69777b1..000c492f 100644--- a/src/mesh-uv.js+++ b/src/mesh-uv.js@@ -468,7 +468,7 @@ function rotateToSmallestBox(points) {return points.map(([x, y]) => [x * cosine - y * sine, x * sine + y * cosine]);}-function bounds2d(points) {+export function bounds2d(points) {let minimumX = Infinity;let maximumX = -Infinity;let minimumY = Infinity;@@ -557,11 +557,11 @@ function shelfLayout(placed, rowWidth, gap) {/*** Pack islands into the unit square: each lies landscape, tallest first, in shelves; several row widths are tried and- * the most compact kept. Sets item.offset and returns the scale from island units to UV.+ * the most compact kept (rotate false keeps each island upright). Sets item.offset and returns the scale from island units to UV.*/-function packIslands(placed, margin) {+export function packIslands(placed, margin, rotate = true) {for (const item of placed) {- if (item.box.height > item.box.width) {+ if (rotate && item.box.height > item.box.width) {item.points = item.points.map(([u, v]) => [v, -u]);item.box = bounds2d(item.points);}diff --git a/src/mesh.js b/src/mesh.jsindex 67fe248f..8abc7582 100644--- a/src/mesh.js+++ b/src/mesh.js@@ -17,6 +17,7 @@ export { mirrorMesh, arrayMesh, solidifyMesh, removeCoincidentFaces } from './meexport { bevelEdges, selectEdges } from './mesh-bevel.js';export { loopCut } from './mesh-loopcut.js';export { unwrapUv } from './mesh-uv.js';+export { projectUv, packUvIslands } from './mesh-uv-project.js';export { decimateMesh } from './mesh-decimate.js';export { remeshMesh, MAX_REMESH_RESOLUTION, MAX_REMESH_CELLS } from './mesh-remesh.js';export { generateMeshLods, generateGeometryLods, generateAssetLods, DEFAULT_LOD_RATIOS } from './mesh-lod.js';diff --git a/tests/mesh-uv-project.test.js b/tests/mesh-uv-project.test.jsnew file mode 100644index 00000000..485f5132--- /dev/null+++ b/tests/mesh-uv-project.test.js@@ -0,0 +1,132 @@+import './support/load-agent-scene-modules.mjs';+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, cylinder, sphere } from '../src/geometry.js';+import { meshFromGeometry, applyMeshEdits } from '../src/mesh.js';+import { projectUv, packUvIslands } from '../src/mesh-uv-project.js';+import { normalizeMeshEdits, normalizeMeshStack } from '../src/mesh-recipe.js';++const crate = () => meshFromGeometry(box(0, 1));+const barrel = () => meshFromGeometry(cylinder(24, 0, 1));++function triangleRatios(mesh) {+ const uv = mesh.attributes.corner.uv.data;+ const ratios = [];+ let flipped = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ const point = corner => [0, 1, 2].map(axis => mesh.positions[mesh.cornerVertices[corner] * 3 + axis]);+ for (let corner = start + 1; corner < end - 1; corner++) {+ const [a, b, c] = [point(start), point(corner), point(corner + 1)];+ const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];+ const ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];+ const area3d = Math.hypot(ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]) / 2;+ const area2d = ((uv[corner * 2] - uv[start * 2]) * (uv[(corner + 1) * 2 + 1] - uv[start * 2 + 1])+ - (uv[(corner + 1) * 2] - uv[start * 2]) * (uv[corner * 2 + 1] - uv[start * 2 + 1])) / 2;+ if (area2d < 0) flipped++;+ if (area3d > 1e-9) ratios.push(Math.abs(area2d) / area3d);+ }+ }+ return { ratios, flipped };+}++function densitySpread(mesh) {+ const { ratios } = triangleRatios(mesh);+ const sorted = [...ratios].sort((left, right) => left - right);+ const median = sorted[sorted.length >> 1];+ return { low: sorted[0] / median, high: sorted.at(-1) / median };+}++function islandBoxes(mesh) {+ const uv = mesh.attributes.corner.uv.data;+ const parents = Array.from({ length: mesh.faceCount }, (_, face) => face);+ const find = face => (parents[face] === face ? face : (parents[face] = find(parents[face])));+ const owners = new Map();+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const key = `${uv[corner * 2].toFixed(5)},${uv[corner * 2 + 1].toFixed(5)}`;+ if (owners.has(key)) parents[find(face)] = find(owners.get(key));+ else owners.set(key, face);+ }+ }+ const boxes = new Map();+ for (let face = 0; face < mesh.faceCount; face++) {+ const root = find(face);+ const entry = boxes.get(root) ?? { minU: Infinity, minV: Infinity, maxU: -Infinity, maxV: -Infinity };+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ entry.minU = Math.min(entry.minU, uv[corner * 2]);+ entry.maxU = Math.max(entry.maxU, uv[corner * 2]);+ entry.minV = Math.min(entry.minV, uv[corner * 2 + 1]);+ entry.maxV = Math.max(entry.maxV, uv[corner * 2 + 1]);+ }+ boxes.set(root, entry);+ }+ return [...boxes.values()];+}++function assertPacked(mesh, margin = 0.01) {+ for (const value of mesh.attributes.corner.uv.data) assert.ok(value >= margin - 1e-6 && value <= 1 - margin + 1e-6, `uv ${value} left the square`);+ const boxes = islandBoxes(mesh);+ for (let first = 0; first < boxes.length; first++) {+ for (let second = first + 1; second < boxes.length; second++) {+ const left = boxes[first];+ const right = boxes[second];+ const apart = left.maxU <= right.minU + 1e-6 || right.maxU <= left.minU + 1e-6 || left.maxV <= right.minV + 1e-6 || right.maxV <= left.minV + 1e-6;+ assert.ok(apart, `islands ${first} and ${second} overlap`);+ }+ }+}++test('cube projection gives a crate six islands of one texel density inside the square', () => {+ const { mesh, islands } = projectUv(crate(), { mode: 'cube' });+ assert.equal(islands, 6);+ assertPacked(mesh);+ const spread = densitySpread(mesh);+ assert.ok(spread.low > 0.999 && spread.high < 1.001, JSON.stringify(spread));+ assert.equal(triangleRatios(mesh).flipped, 0);+});++test('cylinder projection keeps a barrel within 15 percent of its median texel density', () => {+ const { mesh, islands } = projectUv(barrel(), { mode: 'cylinder', axis: 'y' });+ assert.ok(islands >= 3, `${islands} islands`);+ assertPacked(mesh);+ const spread = densitySpread(mesh);+ assert.ok(spread.low > 0.85 && spread.high < 1.15, JSON.stringify(spread));+ assert.equal(triangleRatios(mesh).flipped, 0);+});++test('sphere projection wraps without flipping and stays packed', () => {+ const { mesh } = projectUv(meshFromGeometry(sphere(32, 16)), { mode: 'sphere' });+ assertPacked(mesh);+ assert.equal(triangleRatios(mesh).flipped, 0);+});++test('projections are deterministic byte for byte', () => {+ for (const mode of ['cube', 'cylinder', 'sphere']) {+ const first = projectUv(barrel(), { mode }).mesh.attributes.corner.uv.data;+ const second = projectUv(barrel(), { mode }).mesh.attributes.corner.uv.data;+ assert.deepEqual(Buffer.from(first.buffer), Buffer.from(second.buffer));+ }+});++test('pack false keeps uv in mesh units and uv_pack then fits the square without overlaps', () => {+ const raw = projectUv(crate(), { mode: 'cube', pack: false });+ assert.ok(raw.mesh.attributes.corner.uv.data.some(value => value < 0));+ const packed = packUvIslands(raw.mesh, { margin: 0.05, rotate: false });+ assert.equal(packed.islands, 6);+ assertPacked(packed.mesh, 0.05);+ const { mesh, results } = applyMeshEdits(crate(), [{ op: 'uv_project', mode: 'cube', pack: false }, { op: 'uv_pack', margin: 0.02 }]);+ assert.equal(results[1].islands, 6);+ assertPacked(mesh, 0.02);+});++test('packing needs uv and the edits validate their fields', () => {+ assert.throws(() => applyMeshEdits(crate(), [{ op: 'uv_pack' }]), /has no uv to pack/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_project' }]), /edits\[0\]\.mode: got undefined; expected one of cube, cylinder, sphere/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_project', mode: 'cube', axis: 'w' }]), /edits\[0\]\.axis/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_project', mode: 'cube', pack: 1 }]), /edits\[0\]\.pack/);+ assert.throws(() => normalizeMeshEdits([{ op: 'uv_pack', margin: 0.5 }]), /margin/);+ assert.deepEqual(normalizeMeshEdits([{ op: 'uv_project', mode: 'sphere' }])[0], { op: 'uv_project', mode: 'sphere', axis: 'y', pack: true, margin: 0.01, rotate: true });+ assert.equal(normalizeMeshStack([{ op: 'uv_project', mode: 'cube' }, { op: 'uv_pack' }]).length, 2);+});