Skip to content

3D engine that AI agents drive

Replace the rim caps with one world-unit fade band beside sharp edges (#2224)

Nguyen Xuan Andfb0aa6794ca
diff --git a/changes/2224.md b/changes/2224.md
index df7bba74..5ec90420 100644
--- a/changes/2224.md
+++ b/changes/2224.md
@@ -1 +1 @@
-- `displace` along the normal no longer folds a welded, sharp-edged mesh over at its edges: sharp vertices move to the meeting point of their sides, the move fades in over a band beside the edge so the face eases into its rim, a deep inward move near an edge is limited to a slope, and a rim vertex stays within a slope of its neighbours on each side; smooth meshes are unchanged (#2224).
+- `displace` along the normal no longer folds a welded, sharp-edged mesh over at its edges: sharp vertices move to the meeting point of their sides and the move fades to zero toward the edge over a band of twice the largest move, so the face eases into its rim with no lip or fold; smooth meshes are unchanged (#2224).
diff --git a/changes/2224.size.md b/changes/2224.size.md
index b6637505..66ff70bf 100644
--- a/changes/2224.size.md
+++ b/changes/2224.size.md
@@ -1 +1 @@
-- scene:agent-scene+lazy: the sharp-edge miter for displace (#2224) adds 877 bytes gzip (first version 1,213) so a noise displace of a welded box stops folding over at its edges and no rim stands out from its side face; the agent scene carries the mesh stack and nothing smaller keeps the faces unfolded
+- scene:agent-scene+lazy: the sharp-edge miter and the fade band beside sharp edges for displace (#2224) add 876 bytes gzip so a noise displace of a welded box stops folding over at its edges, no rim stands out from its side face and no squared lip stands at the rim; the agent scene carries the mesh stack and nothing smaller keeps the faces unfolded
diff --git a/docs/mesh.md b/docs/mesh.md
index 754be87f..f62f49a8 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -309,10 +309,10 @@ Uses:
the texture: each vertex moves by `(field - midlevel) * strength` along `normal` (default), `x`, `y` or `z`.
`displace` also takes `group`, the name of a vertex group: each move is scaled by the vertex's weight.
Along `normal`, a vertex on a sharp edge (faces that bend apart by more than 60 degrees) moves to the meeting point of the
- offset planes of its sides, so the faces stay unfolded. The move fades to zero toward such an edge over a band as wide
- as the largest requested move (at most a quarter of the mesh size), so a face eases into its rim instead of stepping up
- from it; a move inward there is also limited to half the edge length, growing by 0.4 per unit of distance from the edge,
- because a deeper move would push the vertex past its neighbours. Smooth surfaces are unchanged.
+ offset planes of its sides, so the faces stay unfolded. The move fades to zero toward such an edge over a band, measured
+ along the surface, twice as wide as the largest requested move, so a face eases into its rim instead of stepping up from it
+ and the look does not change with the segment count; the rim's own inward move stays within half its shortest edge.
+ Smooth surfaces are unchanged.
- Both are also stack nodes, so a late change reuses the cached earlier nodes.
- `vertex_group` (`name`, `select`, and one of `weight`, `field`, `gradient` or `measure`) writes the weights, 0 to 1, of a named group for the
vertices of the selected faces; the others keep theirs (0 in a new group). `gradient` is `{ "axis": "y", "range": [0, 1], "weights": [0, 1] }`,
diff --git a/src/mesh-displace-directions.js b/src/mesh-displace-directions.js
index a2afe88f..3e4f2234 100644
--- a/src/mesh-displace-directions.js
+++ b/src/mesh-displace-directions.js
@@ -4,14 +4,11 @@ import { faceNormals, vertexNormals } from './mesh-normals.js';
// on a sharp edge or corner would move diagonally while its neighbours on each flat face move along that face's normal,
// and the surface folds over at the edge (#2224). So a sharp vertex goes to the meeting point of its sides' offset
// planes (a miter): each flat side keeps its shape and moves by the depth its own neighbours move by.
-// A miter slides the vertex along the sides by that depth, so an inward move of more than the spacing would push the
-// vertex past its neighbours and fold the surface again. Inward depth near a sharp vertex is therefore limited to half
-// the shortest edge there, growing by SIDE_SLOPE per unit of distance along the surface, so it stays a slope. Outward,
-// a sharp vertex may rise above its neighbours on a side by at most SIDE_SLOPE per unit of edge length, so no rim
-// overhangs the face below it.
-// A rim that may slide only a little cannot follow a face that wants to move far, and the face would stand a hard lip above it.
-// So every move fades to zero toward a sharp vertex over a band measured along the surface in world units (the largest
-// requested move wide, at most a quarter of the mesh), and the face eases into its rim at any segment count.
+// A miter slides the vertex along the sides by that depth, so a move of more than the spacing would push the vertex past
+// its neighbours and fold the surface again, and a rim that rises on its own leaves a hard lip above the face next to it.
+// So every move fades to zero toward a sharp vertex over a band measured along the surface in world units (twice the
+// largest requested move wide), the face eases into its rim at any segment count, and the depth of a rim stays within
+// half its shortest edge inward.
/** Adjacent faces that bend apart by more than 60 degrees make their shared vertices sharp. */
const SHARP_BEND_COSINE = Math.cos(60 * Math.PI / 180);
@@ -21,12 +18,8 @@ const MAX_SIDES = 3;
/** A miter longer than this many times the largest side depth (a very acute edge) is shortened, so a spike cannot shoot off. */
const MAX_MITER_RATIO = 2;
const SINGULAR_DETERMINANT = 1e-4;
-/** How much deeper an inward move may get, and how far a sharp vertex may stand out from a neighbour, per unit of edge length. Below 1 so no strip tilts past 22 degrees from its side. */
-const SIDE_SLOPE = 0.4;
/** The fade band beside a sharp edge is this many times the largest requested distance wide. */
-const EDGE_BAND_PER_AMPLITUDE = 1;
-/** The fade band never exceeds this fraction of the mesh size. */
-const EDGE_BAND_MAX_EXTENT = 0.25;
+const EDGE_BAND_PER_AMPLITUDE = 2;
/**
* The move of every vertex as xyz triples, given the signed distance each one is asked to move (positive is outward).
@@ -36,19 +29,13 @@ const EDGE_BAND_MAX_EXTENT = 0.25;
export function displacementOffsets(mesh, distances) {
const normals = vertexNormals(mesh);
const sharpVertices = findSharpVertices(mesh);
- let limits = null;
- if (sharpVertices.size) {
- const neighbours = edgeNeighbours(mesh);
- const distanceToSharp = surfaceDistanceToSharp(neighbours, sharpVertices);
- fadeDistancesNearSharp(mesh, distances, distanceToSharp);
- limits = limitInwardDistances(mesh, distances, neighbours, distanceToSharp, sharpVertices);
- }
+ if (sharpVertices.size) easeDistancesNearSharp(mesh, distances, sharpVertices);
const offsets = new Float64Array(mesh.vertexCount * 3);
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
for (let axis = 0; axis < 3; axis++) offsets[vertex * 3 + axis] = distances[vertex] * normals[vertex * 3 + axis];
}
for (const [vertex, corner] of sharpVertices) {
- const miter = miterOffset(mesh, vertex, corner, distances, sharpVertices, limits[vertex]);
+ const miter = miterOffset(mesh, vertex, corner, distances, sharpVertices);
if (miter) offsets.set(miter, vertex * 3);
}
return offsets;
@@ -101,95 +88,44 @@ function edgeLength(mesh, first, second) {
return Math.hypot(...[0, 1, 2].map(axis => mesh.positions[first * 3 + axis] - mesh.positions[second * 3 + axis]));
}
-/** The edge neighbours of every vertex as a flat [neighbour, length, neighbour, length, ...] list. */
-function edgeNeighbours(mesh) {
- const neighbours = Array.from({ length: mesh.vertexCount }, () => []);
- for (let edge = 0; edge < mesh.edgeCount; edge++) {
- const first = mesh.edgeVertices[edge * 2];
- const second = mesh.edgeVertices[edge * 2 + 1];
- const length = edgeLength(mesh, first, second);
- neighbours[first].push(second, length);
- neighbours[second].push(first, length);
- }
- return neighbours;
-}
-
-/** Distance along the surface from every vertex to the nearest sharp vertex. */
-function surfaceDistanceToSharp(neighbours, sharpVertices) {
- const distanceToSharp = new Float64Array(neighbours.length).fill(Infinity);
- const waiting = new Uint8Array(neighbours.length);
- const queue = [...sharpVertices.keys()];
- for (const vertex of queue) {
- distanceToSharp[vertex] = 0;
- waiting[vertex] = 1;
- }
- // Label-correcting relaxation: a vertex is queued again, once, whenever a shorter route lowers its distance.
- for (let head = 0; head < queue.length; head++) {
- const vertex = queue[head];
- waiting[vertex] = 0;
- const list = neighbours[vertex];
- for (let index = 0; index < list.length; index += 2) {
- const reached = distanceToSharp[vertex] + list[index + 1];
- if (reached >= distanceToSharp[list[index]]) continue;
- distanceToSharp[list[index]] = reached;
- if (waiting[list[index]]) continue;
- waiting[list[index]] = 1;
- queue.push(list[index]);
- }
- }
- return distanceToSharp;
-}
-
/**
- * Fade the distances to zero toward every sharp vertex over a band of EDGE_BAND_PER_AMPLITUDE times the largest distance,
- * so a face eases into its rim instead of stepping up from it: a rim cannot follow a face that moves further than its
- * neighbours allow, and the face would stand a hard lip above it. The band is measured along the surface in world
- * units, so it is the same at any segment count, and it never exceeds EDGE_BAND_MAX_EXTENT of the mesh size.
+ * Ease the distances toward every sharp vertex, in place. They fade to zero over a band EDGE_BAND_PER_AMPLITUDE times the
+ * largest distance wide, so a face eases into its rim instead of stepping up from it: a rim cannot follow a face that
+ * moves further than its neighbours allow, and the face would stand a hard lip above it. The band is measured along the
+ * surface in world units, so it is the same at any segment count, and the largest distance bounds it. Each sharp vertex
+ * also gets an inwardLimit of half its shortest edge, which keeps a vertex from sliding past a close neighbour.
*/
-function fadeDistancesNearSharp(mesh, distances, distanceToSharp) {
- const amplitude = distances.reduce((largest, distance) => Math.max(largest, Math.abs(distance)), 0);
- const bandWidth = Math.min(EDGE_BAND_PER_AMPLITUDE * amplitude, EDGE_BAND_MAX_EXTENT * meshExtent(mesh));
- if (!(bandWidth > 0)) return;
- for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
- const along = distanceToSharp[vertex] / bandWidth;
- if (along < 1) distances[vertex] *= along * along * (3 - 2 * along);
- }
-}
-
-function meshExtent(mesh) {
- let extent = 0;
- for (let axis = 0; axis < 3; axis++) {
- let low = Infinity;
- let high = -Infinity;
- for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
- low = Math.min(low, mesh.positions[vertex * 3 + axis]);
- high = Math.max(high, mesh.positions[vertex * 3 + axis]);
+function easeDistancesNearSharp(mesh, distances, sharpVertices) {
+ const bandWidth = EDGE_BAND_PER_AMPLITUDE * distances.reduce((largest, distance) => Math.max(largest, Math.abs(distance)), 0);
+ const lengths = Float64Array.from({ length: mesh.edgeCount }, (_, edge) => edgeLength(mesh, mesh.edgeVertices[edge * 2], mesh.edgeVertices[edge * 2 + 1]));
+ const shortest = new Float64Array(mesh.vertexCount).fill(Infinity);
+ const distanceToSharp = new Float64Array(mesh.vertexCount).fill(Infinity);
+ for (const vertex of sharpVertices.keys()) distanceToSharp[vertex] = 0;
+ // Relax every edge both ways until no vertex gets closer; routes longer than the band cannot matter.
+ for (let changed = true; changed;) {
+ changed = false;
+ for (let edge = 0; edge < mesh.edgeCount * 2; edge++) {
+ const from = mesh.edgeVertices[edge];
+ const to = mesh.edgeVertices[edge ^ 1];
+ const reached = distanceToSharp[from] + lengths[edge >> 1];
+ shortest[to] = Math.min(shortest[to], lengths[edge >> 1]);
+ if (reached >= Math.min(distanceToSharp[to], bandWidth)) continue;
+ distanceToSharp[to] = reached;
+ changed = true;
}
- extent = Math.max(extent, high - low);
}
- return extent;
-}
-
-/**
- * Clamp inward distances (negative) to half the shortest edge at a sharp vertex plus SIDE_SLOPE per unit of distance from
- * it. Returns the limit of every vertex.
- */
-function limitInwardDistances(mesh, distances, neighbours, distanceToSharp, sharpVertices) {
- const limits = new Float64Array(mesh.vertexCount);
- for (let vertex = 0; vertex < mesh.vertexCount; vertex++) limits[vertex] = SIDE_SLOPE * distanceToSharp[vertex];
- for (const vertex of sharpVertices.keys()) limits[vertex] = Math.min(...neighbours[vertex].filter((_, index) => index % 2)) / 2;
+ for (const [vertex, corner] of sharpVertices) corner.inwardLimit = shortest[vertex] / 2;
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
- if (distances[vertex] < -limits[vertex]) distances[vertex] = -limits[vertex];
+ const along = Math.min(distanceToSharp[vertex] / bandWidth || 1, 1);
+ distances[vertex] *= along * along * (3 - 2 * along);
}
- return limits;
}
/**
* The move that puts a sharp vertex on the offset plane of every side. A side moves by the mean distance of the smooth
- * vertices of its faces (the vertex's own distance when it has none), held within SIDE_SLOPE of each neighbour along an
- * edge and above the inward limit. Null when the sides are dependent.
+ * vertices of its faces (the vertex's own distance when it has none), kept above the inward limit. Null when the sides are dependent.
*/
-function miterOffset(mesh, vertex, { sides }, distances, sharpVertices, inwardLimit) {
+function miterOffset(mesh, vertex, { sides, inwardLimit }, distances, sharpVertices) {
const depths = sides.map(side => sideDepth(mesh, vertex, side.faces, distances, sharpVertices, inwardLimit));
// Three planes n_i . x = depth_i meet at x = sum(depth_i * (n_j x n_k)) / (n_1 . (n_2 x n_3)); two sides get the third plane
// along their edge, which holds no depth.
@@ -202,16 +138,14 @@ function miterOffset(mesh, vertex, { sides }, distances, sharpVertices, inwardLi
const across = cross(normals[(side + 1) % 3], normals[(side + 2) % 3]);
for (let axis = 0; axis < 3; axis++) offset[axis] += (depths[side] ?? 0) * across[axis] / determinant;
}
- const largestDepth = Math.max(...depths.map(Math.abs));
+ const longest = MAX_MITER_RATIO * Math.max(...depths.map(Math.abs));
const length = Math.hypot(...offset);
- const scale = length > MAX_MITER_RATIO * largestDepth ? MAX_MITER_RATIO * largestDepth / length : 1;
- return offset.map(value => value * scale);
+ return length > longest ? offset.map(value => value * longest / length) : offset;
}
function sideDepth(mesh, vertex, faces, distances, sharpVertices, inwardLimit) {
const seen = new Set();
let sum = 0;
- let highest = Infinity;
for (const face of faces) {
const start = mesh.faceOffsets[face];
const size = mesh.faceOffsets[face + 1] - start;
@@ -222,12 +156,10 @@ function sideDepth(mesh, vertex, faces, distances, sharpVertices, inwardLimit) {
if (sharpVertices.has(other) || seen.has(other)) continue;
seen.add(other);
sum += distances[other];
- // Along an edge from the vertex, the neighbour sets how far above or below it the vertex may stand.
- if (step === 1 || step === size - 1) highest = Math.min(highest, distances[other] + SIDE_SLOPE * edgeLength(mesh, vertex, other));
}
}
if (!seen.size) return distances[vertex];
- return Math.max(Math.min(sum / seen.size, highest), -inwardLimit);
+ return Math.max(sum / seen.size, -inwardLimit);
}
const dot = (first, second) => first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
diff --git a/tests/mesh-displace-sharp-edges.test.js b/tests/mesh-displace-sharp-edges.test.js
index 821d5bfa..92754c35 100644
--- a/tests/mesh-displace-sharp-edges.test.js
+++ b/tests/mesh-displace-sharp-edges.test.js
@@ -61,11 +61,11 @@ test('a smooth sphere still moves each vertex by distance times its angle-weight
assert.deepEqual(Buffer.from(displaced.positions.buffer), Buffer.from(reference.buffer));
});
-test('a rim vertex stays within 0.75 edge lengths of the face beside it, so no squared lip stands at the edge (#2224)', () => {
+test('a rim vertex stays within 0.5 edge lengths of the face beside it, so no squared lip stands at the edge (#2224)', () => {
for (const [spans, scale] of [[64, 3], [24, 6]]) {
const box = sharpSubdividedBox(spans);
const displaced = applyMeshEdits(box, [{ op: 'displace', field: { noise: { scale, seed: 7 } }, strength: 0.4 }]).mesh;
const stretch = largestRimStretch(box, displaced);
- assert.ok(stretch <= 0.75, `${spans} spans, noise scale ${scale}: rim stretch ${stretch.toFixed(2)}`);
+ assert.ok(stretch <= 0.5, `${spans} spans, noise scale ${scale}: rim stretch ${stretch.toFixed(2)}`);
}
});