diff --git a/docs/design.md b/docs/design.md index 9e807b9..41fd7ae 100644 --- a/docs/design.md +++ b/docs/design.md @@ -62,7 +62,13 @@ top of the viewport, with Studio as the default. Smaller screens use collapsible - Offer a Refine tool (E) that rebuilds softened edges on a scanned part from line, arc and spline guides, treats painted regions (smooth, flatten or snap to a shape) while keeping detail, offers crease, flatten and smooth brushes, - and proposes guides and regions for review. Apply bakes the result as one + proposes guides and regions for review, and cleans the whole part or a + painted area at once: bilateral normal filtering removes noise, an unsharp + mask on the normals narrows softened edges, edge flips line triangles up with + the edges it sharpens, an unsharp mask along the normal deepens relief up + to a set size, and Square rebuilds roundings between faces at about 90 + degrees, outside and inside, as sharp corners cut into the mesh. Apply bakes + the result as one undo step without modifying pins, anchors, joints, or any other part. Cancel discards it. - Paint only edge-connected mesh patches; optional fixed seed-plane angle and diff --git a/src/App.tsx b/src/App.tsx index 4a10146..37d42b8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -653,6 +653,8 @@ function refineHints(mode: RefineMode | 'building', smaller: string, larger: str return `Drag across the surface.${smaller && larger ? ` ${smaller} and ${larger} change the brush size.` : ''}`; case 'detect': return 'Find edges and surfaces, then accept the proposals you want.'; + case 'clean': + return 'Clean the whole part, or paint the area to clean. Undo steps back.'; } } diff --git a/src/components/RefineControls.tsx b/src/components/RefineControls.tsx index 754da3f..0503fdb 100644 --- a/src/components/RefineControls.tsx +++ b/src/components/RefineControls.tsx @@ -5,6 +5,7 @@ import { isTaskActive, useActivity } from '../core/activity'; import type { EdgeInput, EdgePosition, EdgeSolve } from '../core/refine-edge'; import type { RegionInput, RegionSolve, RegionShape, Treatment } from '../core/refine-region'; import { + cleanTitle, refineDraftLimit, refineFailure, refinePickingPrompt, @@ -17,6 +18,8 @@ import { } from '../core/store'; import { autoRule, + cleanDepthMax, + cleanSizeRange, draftSkippedHint, endLabels, endOption, @@ -58,6 +61,7 @@ const panelView = (refine: RefineSession | null) => region: refine.region, brush: refine.brush, detect: refine.detect, + clean: refine.clean, folds: refine.folds.length, skipped: refine.skipped.length, edited: refineEdited(refine), @@ -74,8 +78,8 @@ function currentTarget() { const ownedBy = (target: string) => () => currentTarget() === target; /** - * A slider with a number field. A percent setting holds 0 to 1 and shows 0 to 100; a setting with - * `range` is in mm on a logarithmic slider. Unless `live`, a drag sets its value once on release; + * A slider with a number field. A percent setting holds 0 to `most` (1 unless set) and shows it as + * a percentage; a setting with `range` is in mm on a logarithmic slider. Unless `live`, a drag sets its value once on release; * a live one gives `begin` to put the value back on Escape. */ function SliderSetting({ @@ -83,6 +87,7 @@ function SliderSetting({ value, mixed = false, range, + most = 1, live = false, begin, owned, @@ -92,6 +97,7 @@ function SliderSetting({ value: number; mixed?: boolean; range?: { min: number; max: number }; + most?: number; live?: boolean; begin?: () => () => void; owned: () => boolean; @@ -131,7 +137,7 @@ function SliderSetting({ aria-label={`${label} slider`} aria-valuetext={hidden ? 'Mixed' : undefined} min={0} - max={100} + max={Math.round(most * 100)} step={1} value={hidden ? 0 : Math.round(shown * 100)} onChange={(event) => slider.change(Number(event.target.value) / 100)} @@ -142,7 +148,7 @@ function SliderSetting({ value={range ? shown : Math.round(shown * 100)} mixed={hidden} min={range ? range.min : 0} - max={range ? range.max : 100} + max={range ? range.max : Math.round(most * 100)} step={range ? 0.01 : 1} onCommit={(next) => owned() && onSet(range ? next : next / 100)} /> @@ -984,6 +990,107 @@ function DetectControls({ view, targets, owned }: ModeProps) { ); } +function CleanControls({ view, owned }: ModeProps) { + const { clean } = view; + const model = view.model!; + const painted = useEditor((s) => (s.refine?.triangles.length ?? 0) > 0); + const task = useActivity((s) => + s.tasks.find((task) => task.title === cleanTitle && isTaskActive(task)), + ); + const set = (options: Partial>) => + editor().setRefineClean(options); + const idle = !clean.smooth && !clean.sharpen && !clean.depth && !clean.square; + return ( + <> +

+ Removes scan noise, crisps edges and deepens detail, as sharpening does for a photo. Square + rebuilds rounded edges between faces at about 90° as sharp corners. +

+ set({ where })} + /> + {clean.where === 'painted' ? : null} + set({ smooth })} + /> + set({ sharpen })} + /> + set({ depth })} + /> + set({ square })} + /> + { + const start = manualStart(autoRule('size', model), cleanSizeRange); + set({ size: start.value }); + return start.adjusted; + }} + onSet={(size) => set({ size })} + > + {(size, mixed, setSize) => ( + + )} + + {clean.running ? ( + <> +
+

+ {cleanTitle} + {task?.progress != null ? ` · ${Math.round(task.progress * 100)}%` : ''} +

+ +
+ + + ) : ( + + )} + + ); +} + /** Ends the session without a notice and leaves the tool. */ function cancel() { const state = editor(); @@ -991,7 +1098,13 @@ function cancel() { state.setTool('select'); } -const modeTitles = { edge: 'Edge', region: 'Region', brush: 'Brush', detect: 'Detect' } as const; +const modeTitles = { + edge: 'Edge', + region: 'Region', + brush: 'Brush', + detect: 'Detect', + clean: 'Clean', +} as const; export function RefineControls() { const view = useEditor(useShallow((s) => panelView(s.refine))); @@ -1045,6 +1158,7 @@ export function RefineControls() { { id: 'region', label: 'Region' }, { id: 'brush', label: 'Brush' }, { id: 'detect', label: 'Detect' }, + { id: 'clean', label: 'Clean' }, ]} onChange={(mode) => editor().setRefineMode(mode)} /> @@ -1059,8 +1173,10 @@ export function RefineControls() { ) : view.mode === 'brush' ? ( - ) : ( + ) : view.mode === 'detect' ? ( + ) : ( + )} )} @@ -1100,7 +1216,7 @@ export function RefineControls() { ? `Unlock ${part.name} to apply the refinement.` : view.edited ? undefined - : 'Accept a feature or make a stroke first.' + : 'Accept a feature, make a stroke or clean the surface first.' } onClick={() => editor().applyRefine()} > diff --git a/src/components/RefinePointer.tsx b/src/components/RefinePointer.tsx index 3a4869d..03579b0 100644 --- a/src/components/RefinePointer.tsx +++ b/src/components/RefinePointer.tsx @@ -1233,7 +1233,9 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) after.redo !== before.redo || after.selected.length !== before.selected.length || after.selected.some((id, i) => id !== before.selected[i]) || - (d.kind === 'paint' && after.detect.where !== before.detect.where) + (d.kind === 'paint' && + (after.detect.where !== before.detect.where || + after.clean.where !== before.clean.where)) ) return discard(); } diff --git a/src/components/refine-panel.ts b/src/components/refine-panel.ts index 6c570eb..4237527 100644 --- a/src/components/refine-panel.ts +++ b/src/components/refine-panel.ts @@ -35,10 +35,12 @@ export const endOption = (chosen: EdgeEnd | undefined) => * where a setting taken off Auto starts when no solve says what it used. */ export function autoRule( - setting: 'width' | 'scale' | 'detail' | 'blend', + setting: 'width' | 'scale' | 'detail' | 'blend' | 'size', model: Pick, ) { switch (setting) { + case 'size': + return 8 * model.step; case 'width': return Math.min(1, 6 * model.step); case 'scale': @@ -50,6 +52,10 @@ export function autoRule( } } +/** Clean's largest Depth, and the range of its Size in mm, as refine-clean holds them. */ +export const cleanDepthMax = 3; +export const cleanSizeRange = { min: 0.05, max: 5 }; + /** A setting's first manual value: `start` held to the control's range, and whether that moved it. */ export function manualStart(start: number, range: { min: number; max: number }) { const value = Math.min(range.max, Math.max(range.min, start)); diff --git a/src/core/refine-clean.ts b/src/core/refine-clean.ts new file mode 100644 index 0000000..6736d0a --- /dev/null +++ b/src/core/refine-clean.ts @@ -0,0 +1,1167 @@ +import { remapTriangles } from './refine-cut'; +import { + type RefineMesh, + type RefineTopology, + buildTopology, + cloneRefineMesh, + moveVertex, +} from './refine-mesh'; +import { squareCorners } from './refine-square'; + +/** How Clean treats the surface. Each setting reads 0 as leaving that part of the job out. */ +export interface CleanSettings { + /** How much noise and small unevenness to remove, 0 to 1. */ + smooth: number; + /** How crisp edges and corners become, 0 to 1. */ + sharpen: number; + /** How much deeper features become, 0 to `maxCleanDepth`: 1 doubles their relief. */ + depth: number; + /** How far rounded edges between faces at about 90 degrees move to a sharp corner, 0 to 1. */ + square: number; + /** + * The widest feature, mm, that Depth deepens and the widest rounding Square rebuilds; null takes + * `autoCleanSize` of the scan. + */ + size: number | null; +} + +export interface CleanInput extends CleanSettings { + /** The painted triangles to clean, or null for the whole part. */ + triangles: Uint32Array | null; +} + +export interface CleanResult { + /** Welded vertices that moved, ascending. */ + moved: Uint32Array; + /** Their new positions, three values each. */ + position: Float64Array; + /** The feature size Depth used, mm. */ + size: number; + /** Vertices kept in place because moving them would fold or collapse a triangle. */ + held: number; + /** Triangles whose corners changed to follow a sharpened edge, ascending. */ + triangles: Uint32Array; + /** Their new geometry vertices, three each. */ + corners: Uint32Array; + /** The topology of the mesh with those corners, or with `mesh`; null when no triangle changed. */ + topology: RefineTopology | null; + /** + * The whole cleaned mesh when Square cut it, which then stands in for `moved`, `position`, + * `triangles` and `corners`; null otherwise. + */ + mesh: RefineMesh | null; + /** With `mesh`: each triangle the cut added and the triangle it was cut from, two values each. */ + split: Uint32Array; + /** Vertices on edges Square rebuilt sharp. */ + squared: number; +} + +export const cleanDefaults: CleanSettings = { + smooth: 0.5, + sharpen: 0.5, + depth: 1, + square: 0, + size: null, +}; +export const maxCleanDepth = 3; +/** Depth's feature size when none is set: a few triangles across, where scans lose relief. */ +export const autoCleanSize = (step: number) => 8 * step; +export const minCleanSize = 0.05; +export const maxCleanSize = 5; + +/** Edge lengths over which a painted area eases from untouched to fully cleaned. */ +const featherRings = 4; +/** Bilateral normal filtering rounds at full Smooth. */ +const smoothRounds = 10; +/** Filtering rounds that settle the surface around corners Square rebuilt. */ +const squareRounds = 5; +/** Normal difference (chord length) that still averages: differences across an edge are larger. */ +const range = 0.35; +/** Sharpen's passes, the rounds of averaging that blur the normals it sharpens against, and the + * amount of the difference it adds at full Sharpen. */ +const sharpenPasses = 3; +const blurRounds = 3; +const sharpenAmount = 1.2; +/** Rounds fitting vertices to the filtered normals. */ +const fitRounds = 10; +/** Relief within this many times the scan's noise is noise, and is not deepened. */ +const reliefNoise = 1.5; +/** Passes averaging the relief field before it is deepened, so no single vertex is pushed alone. */ +const reliefPasses = 2; +/** Taubin smoothing of the base Depth measures relief from: lambda, and the most rounds. */ +const lambda = 0.5; +const maxBaseRounds = 300; +/** A moved triangle may keep no less than this fraction of its area. */ +const collapse = 1e-3; +/** Times a vertex's move is halved for a triangle it would fold or collapse before it is dropped. */ +const halvings = 6; +/** Rounds of edge flips that line triangles up with sharpened edges. */ +const flipRounds = 4; +/** An edge flips when that leaves at most this share of the bending around it. */ +const flipGain = 0.85; +/** Edges whose two triangles turn less than this (cosine of 8 degrees) are left alone. */ +const flipBend = Math.cos((8 * Math.PI) / 180); +/** The least shape quality (1 for an equilateral triangle) a flip may make. */ +const flipQuality = 0.15; + +const cancelled = () => new DOMException('Refine cancelled', 'AbortError'); + +/** What the settings run, for a scan of median edge `step` mm. */ +export function cleanPlan(settings: CleanSettings, step: number) { + const smooth = clamp01(settings.smooth), + sharpen = clamp01(settings.sharpen); + const rounds = Math.round(smoothRounds * smooth); + const size = Math.min( + maxCleanSize, + Math.max(minCleanSize, settings.size ?? autoCleanSize(step), step), + ); + // The base keeps wavelengths longer than about four times the size, so relief up to the size + // stands off it whole (measured on a rippled grid: a quarter of the cutoff passes at 0.09). + const pass = 0.5 * ((Math.PI * step) / (4 * size)) ** 2; + return { + rounds, + passes: sharpen > 0 ? sharpenPasses : 0, + amount: sharpenAmount * sharpen, + depth: Math.min(maxCleanDepth, Math.max(0, settings.depth)), + square: clamp01(settings.square), + size, + pass, + baseRounds: Math.min(maxBaseRounds, Math.ceil(2 / pass)), + }; +} + +type Plan = ReturnType; + +const clamp01 = (value: number) => Math.min(1, Math.max(0, value || 0)); + +/** + * Removes noise, sharpens edges and deepens relief, as a sharpen filter does for a photo. + * + * Smooth filters the face normals bilaterally (Zheng et al. 2011): each face takes the area- and + * distance-weighted mean of the normals around it that are near its own, so noise averages out + * while the two sides of an edge stay apart. The vertices are then refitted to the filtered normals + * (Sun et al. 2007). More Smooth runs more rounds. + * + * Sharpen is an unsharp mask on the normals: each face's normal moves away from a blurred copy of + * the normals around it, which steepens the turn of a softened edge as sharpening steepens a + * blurred edge in a photo, and the vertices are refitted. Each of its passes first filters the + * normals once, so it sharpens edges and not noise. + * + * Depth is an unsharp mask along the surface normal. A Taubin-smoothed base, which keeps shapes + * longer than about four times Size without shrinking them, stands in for the surface without its + * relief; each vertex's height above or below it is averaged with its neighbours', faded to nothing + * where it is within the noise, and added again `depth` times. + * + * Square rebuilds rounded edges between faces at about 90 degrees as sharp corners and cuts the mesh + * along them (see `squareCorners`). It runs after Smooth, then the surface around the new edges is + * settled with a few more filtering rounds, and Sharpen and Depth run with the new edges held. + * + * A painted area eases in over `featherRings` edges from its border; everything outside it, every + * vertex on an open border or a refined edge, keeps its exact position. A vertex whose move would + * fold or collapse a triangle moves less, or not at all. + */ +export function cleanSurface( + mesh: RefineMesh, + topology: RefineTopology, + noise: number, + step: number, + input: CleanInput, + report: (fraction: number) => void = () => {}, + signal?: AbortSignal, +): CleanResult { + const plan = cleanPlan(input, step); + const check = () => { + if (signal?.aborted) throw cancelled(); + }; + if (plan.square) return squaredClean(mesh, topology, noise, step, input, plan, report, check); + return cleanPass(mesh, topology, noise, step, input.triangles, plan, true, report, check); +} + +const emptyResult = (size: number): CleanResult => ({ + moved: new Uint32Array(0), + position: new Float64Array(0), + size, + held: 0, + triangles: new Uint32Array(0), + corners: new Uint32Array(0), + topology: null, + mesh: null, + split: new Uint32Array(0), + squared: 0, +}); + +/** Writes a pass's moves and turned triangles into `mesh`; returns the topology it now has, or null. */ +function applyPass(mesh: RefineMesh, result: CleanResult) { + const { moved, position, triangles, corners } = result; + for (let i = 0; i < moved.length; i++) + moveVertex(mesh, moved[i], position[i * 3], position[i * 3 + 1], position[i * 3 + 2]); + triangles.forEach((t, i) => mesh.corners.set(corners.subarray(i * 3, i * 3 + 3), t * 3)); + return result.topology; +} + +/** + * Smooth, then Square, then a few filtering rounds around the new edges, then Sharpen and Depth with + * the new edges held as refined edges are. Each pass reads the surface the last one left. + */ +function squaredClean( + mesh: RefineMesh, + topology: RefineTopology, + noise: number, + step: number, + input: CleanInput, + plan: Plan, + report: (fraction: number) => void, + check: () => void, +): CleanResult { + const work = cloneRefineMesh(mesh, true); + let held = 0; + const band = (from: number, to: number) => (f: number) => report(from + (to - from) * f); + if (plan.rounds) { + const smoothed = cleanPass( + work, + topology, + noise, + step, + input.triangles, + { ...plan, passes: 0, depth: 0 }, + false, + band(0, 0.3), + check, + ); + applyPass(work, smoothed); + held += smoothed.held; + } + check(); + const squared = squareCorners( + work, + topology, + noise, + step, + { + strength: plan.square, + reach: plan.size, + free: freeVertices(work, topology, input.triangles), + }, + band(0.3, 0.55), + check, + ); + held += squared.held; + const cut = squared.mesh.triangleCount !== mesh.triangleCount; + const result = squared.mesh; + let shape = squared.topology; + const painted = input.triangles && remapTriangles(input.triangles, squared.children); + if (squared.moved) { + const settled = cleanPass( + result, + shape, + noise, + step, + painted, + { ...plan, rounds: squareRounds, passes: 0, depth: 0 }, + false, + band(0.55, 0.65), + check, + ); + applyPass(result, settled); + held += settled.held; + for (const v of squared.edge) result.crease[v] = 1; + } + const last = cleanPass( + result, + shape, + noise, + step, + painted, + { ...plan, rounds: 0 }, + true, + band(0.65, 1), + check, + ); + shape = applyPass(result, last) ?? shape; + held += last.held; + report(1); + const out: CleanResult = { ...emptyResult(plan.size), held, squared: squared.edge.length }; + if (cut || last.triangles.length || squared.edge.length) { + const split: number[] = []; + for (const [t, list] of squared.children) + for (const child of list) if (child !== t) split.push(child, t); + return { ...out, mesh: result, topology: shape, split: Uint32Array.from(split) }; + } + // Nothing was cut: the moves alone, against the mesh as it came. + const moved: number[] = []; + for (let v = 0; v < mesh.weldedCount; v++) + if ( + result.position[v * 3] !== mesh.position[v * 3] || + result.position[v * 3 + 1] !== mesh.position[v * 3 + 1] || + result.position[v * 3 + 2] !== mesh.position[v * 3 + 2] + ) + moved.push(v); + out.moved = Uint32Array.from(moved); + out.position = new Float64Array(moved.length * 3); + moved.forEach((v, i) => out.position.set(result.position.subarray(v * 3, v * 3 + 3), i * 3)); + return out; +} + +/** + * Vertices Square may move: in the painted area when there is one, away from its border, and not on + * an open or non-manifold edge or a refined edge. + */ +function freeVertices(mesh: RefineMesh, topology: RefineTopology, painted: Uint32Array | null) { + const { triangleStart, trianglesOf, neighbourStart } = topology; + const n = mesh.weldedCount; + const inside = painted ? new Uint8Array(mesh.triangleCount) : null; + if (inside && painted) for (const t of painted) if (t < mesh.triangleCount) inside[t] = 1; + const free = new Uint8Array(n); + for (let v = 0; v < n; v++) { + const around = triangleStart[v + 1] - triangleStart[v]; + if (!around || around !== neighbourStart[v + 1] - neighbourStart[v] || mesh.crease[v]) continue; + let all = true; + if (inside) + for (let i = triangleStart[v]; i < triangleStart[v + 1] && all; i++) + all = inside[trianglesOf[i]] === 1; + free[v] = +all; + } + return free; +} + +/** One run of Smooth, Sharpen and Depth over the mesh as it stands, turning triangles when `flips`. */ +function cleanPass( + mesh: RefineMesh, + topology: RefineTopology, + noise: number, + step: number, + painted: Uint32Array | null, + plan: Plan, + flips: boolean, + report: (fraction: number) => void, + check: () => void, +): CleanResult { + const empty = emptyResult(plan.size); + if (!plan.rounds && !plan.passes && !plan.depth) return empty; + const work = workingSet(mesh, topology, painted, plan, step); + if (!work) return empty; + check(); + report(0.05); + const { count, weight } = work; + const start = new Float64Array(count * 3); + for (let i = 0; i < count; i++) + for (let a = 0; a < 3; a++) start[i * 3 + a] = mesh.position[work.vertex[i] * 3 + a]; + let position = start.slice(); + if (plan.rounds || plan.passes) { + // Progress: Smooth's rounds and fit, then each Sharpen pass, share 0.05 to 0.6. + const units = (plan.rounds ? plan.rounds + 2 : 0) + 4 * plan.passes; + let done = 0; + const advance = (amount: number) => { + check(); + done += amount; + report(Math.min(0.6, 0.05 + (0.55 * done) / units)); + }; + if (plan.rounds) { + const normals = filterNormals(work, position, plan.rounds, () => advance(1)); + fitToNormals(work, position, normals, fitRounds); + advance(2); + } + for (let pass = 0; pass < plan.passes; pass++) { + const filtered = filterNormals(work, position, 1, () => advance(1)); + const sharpened = sharpenNormals(work, position, filtered, plan.amount); + advance(1); + fitToNormals(work, position, sharpened, fitRounds); + advance(2); + } + for (let i = 0; i < count; i++) + for (let a = 0; a < 3; a++) { + const k = i * 3 + a; + position[k] = start[k] + weight[i] * (position[k] - start[k]); + } + } + report(0.6); + if (plan.depth) { + const threshold = reliefNoise * Math.max(noise, 0.05 * step); + position = deepen(work, position, plan, threshold, (f) => { + check(); + report(0.6 + 0.35 * f); + }); + } + check(); + const held = holdFolds(work, start, position); + report(0.97); + const flipped = + flips && (plan.rounds || plan.passes) ? alignEdges(work, start, position) : new Uint32Array(0); + let moved = 0; + for (let i = 0; i < count; i++) if (changed(start, position, i)) moved++; + const result: CleanResult = { + ...empty, + moved: new Uint32Array(moved), + position: new Float64Array(moved * 3), + held, + }; + if (flipped.length) { + // Each flipped triangle takes its corners' geometry vertices from the two it was made from, + // which `alignEdges` carried along in `work.geometry`. + const order = Array.from(flipped).sort((a, b) => work.triangle[a] - work.triangle[b]); + result.triangles = Uint32Array.from(order, (f) => work.triangle[f]); + result.corners = new Uint32Array(order.length * 3); + order.forEach((f, i) => result.corners.set(work.geometry.subarray(f * 3, f * 3 + 3), i * 3)); + const corners = mesh.corners.slice(0, mesh.triangleCount * 3); + result.triangles.forEach((t, i) => + corners.set(result.corners.subarray(i * 3, i * 3 + 3), t * 3), + ); + result.topology = buildTopology({ ...mesh, corners }); + } + report(1); + // The working set is in ascending welded order, so the moved list is too. + for (let i = 0, j = 0; i < count; i++) { + if (!changed(start, position, i)) continue; + result.moved[j] = work.vertex[i]; + for (let a = 0; a < 3; a++) result.position[j * 3 + a] = position[i * 3 + a]; + j++; + } + return result; +} + +const changed = (a: Float64Array, b: Float64Array, i: number) => + a[i * 3] !== b[i * 3] || a[i * 3 + 1] !== b[i * 3 + 1] || a[i * 3 + 2] !== b[i * 3 + 2]; + +/** + * The vertices and triangles a run reads, indexed locally: what it may move with the margin its + * filters read around it. `weight` is how far each vertex moves toward its cleaned position; + * `fixed` marks the vertices the base smoothing must hold, those with a neighbour outside the set. + */ +interface WorkingSet { + count: number; + /** Welded vertex of each local vertex, ascending. */ + vertex: Uint32Array; + weight: Float32Array; + fixed: Uint8Array; + /** Local corners of each local triangle. */ + corners: Uint32Array; + /** The geometry vertex of each of those corners. */ + geometry: Uint32Array; + /** Global triangle of each local triangle. */ + triangle: Uint32Array; + /** CSR: local triangles around each local vertex. */ + faceStart: Uint32Array; + faces: Uint32Array; + /** CSR: local neighbours of each local vertex. */ + neighbourStart: Uint32Array; + neighbours: Uint32Array; + /** The sign that turns each triangle's winding normal outward. */ + sign: number; +} + +function workingSet( + mesh: RefineMesh, + topology: RefineTopology, + painted: Uint32Array | null, + plan: Plan, + step: number, +): WorkingSet | null { + const { weldedCount, triangleCount, weldOf, corners: geometryCorners } = mesh; + const { triangleStart, trianglesOf, neighbourStart, neighbours } = topology; + const corner = (t: number, k: number) => weldOf[geometryCorners[t * 3 + k]]; + const inside = painted ? new Uint8Array(triangleCount) : null; + const region = new Uint8Array(weldedCount); + if (inside) { + for (const t of painted!) + if (t < triangleCount) { + inside[t] = 1; + for (let k = 0; k < 3; k++) region[corner(t, k)] = 1; + } + } else + for (let v = 0; v < weldedCount; v++) + if (triangleStart[v + 1] > triangleStart[v]) region[v] = 1; + // Ring distance inside the region from the vertices that stay put: the painted border, open and + // non-manifold edges, and refined edges. -1 outside the region. + const ring = new Int32Array(weldedCount).fill(-1); + const queue = new Uint32Array(weldedCount); + let head = 0, + tail = 0; + for (let v = 0; v < weldedCount; v++) { + if (!region[v]) continue; + const around = triangleStart[v + 1] - triangleStart[v]; + let held = !!mesh.crease[v] || around !== neighbourStart[v + 1] - neighbourStart[v]; + if (inside) + for (let i = triangleStart[v]; i < triangleStart[v + 1] && !held; i++) + held = !inside[trianglesOf[i]]; + if (!held) continue; + ring[v] = 0; + queue[tail++] = v; + } + while (head < tail) { + const v = queue[head++]; + if (ring[v] >= featherRings) continue; + for (let i = neighbourStart[v]; i < neighbourStart[v + 1]; i++) { + const w = neighbours[i]; + if (!region[w] || ring[w] >= 0) continue; + ring[w] = ring[v] + 1; + queue[tail++] = w; + } + } + for (let v = 0; v < weldedCount; v++) if (region[v] && ring[v] < 0) ring[v] = featherRings; + // The margin the filters read: a ring for each normal round, with room for the fit, and Depth's + // base, which reaches about three sizes. + const margin = Math.max( + plan.rounds || plan.passes ? 2 * (plan.rounds + plan.passes * (1 + blurRounds)) + 2 : 0, + plan.depth ? Math.ceil((3 * plan.size) / Math.max(1e-9, step)) : 0, + ); + const reach = new Int32Array(weldedCount).fill(-1); + head = tail = 0; + for (let v = 0; v < weldedCount; v++) + if (ring[v] >= 0) { + reach[v] = 0; + queue[tail++] = v; + } + if (!tail) return null; + const whole = !painted; + if (!whole) + while (head < tail) { + const v = queue[head++]; + if (reach[v] >= margin) continue; + for (let i = neighbourStart[v]; i < neighbourStart[v + 1]; i++) { + const w = neighbours[i]; + if (reach[w] >= 0) continue; + reach[w] = reach[v] + 1; + queue[tail++] = w; + } + } + const local = new Int32Array(weldedCount).fill(-1); + let count = 0; + for (let v = 0; v < weldedCount; v++) if (reach[v] >= 0) local[v] = count++; + const vertex = new Uint32Array(count); + for (let v = 0; v < weldedCount; v++) if (local[v] >= 0) vertex[local[v]] = v; + // Triangles with every corner in the set. + let faceCount = 0; + const keep = (t: number) => { + const a = corner(t, 0), + b = corner(t, 1), + c = corner(t, 2); + return local[a] >= 0 && local[b] >= 0 && local[c] >= 0 && a !== b && b !== c && a !== c; + }; + for (let t = 0; t < triangleCount; t++) if (keep(t)) faceCount++; + const triangle = new Uint32Array(faceCount); + const corners = new Uint32Array(faceCount * 3); + const geometry = new Uint32Array(faceCount * 3); + for (let t = 0, f = 0; t < triangleCount; t++) { + if (!keep(t)) continue; + triangle[f] = t; + for (let k = 0; k < 3; k++) { + corners[f * 3 + k] = local[corner(t, k)]; + geometry[f * 3 + k] = geometryCorners[t * 3 + k]; + } + f++; + } + const faceStart = new Uint32Array(count + 1); + for (let i = 0; i < corners.length; i++) faceStart[corners[i] + 1]++; + for (let i = 0; i < count; i++) faceStart[i + 1] += faceStart[i]; + const faces = new Uint32Array(corners.length); + const fill = faceStart.slice(0, count); + for (let i = 0; i < corners.length; i++) faces[fill[corners[i]]++] = (i / 3) | 0; + const localStart = new Uint32Array(count + 1); + const fixed = new Uint8Array(count); + for (let i = 0; i < count; i++) { + const v = vertex[i]; + for (let j = neighbourStart[v]; j < neighbourStart[v + 1]; j++) + if (local[neighbours[j]] >= 0) localStart[i + 1]++; + else fixed[i] = 1; + } + for (let i = 0; i < count; i++) localStart[i + 1] += localStart[i]; + const localNeighbours = new Uint32Array(localStart[count]); + for (let i = 0, o = 0; i < count; i++) { + const v = vertex[i]; + for (let j = neighbourStart[v]; j < neighbourStart[v + 1]; j++) + if (local[neighbours[j]] >= 0) localNeighbours[o++] = local[neighbours[j]]; + } + const weight = new Float32Array(count); + for (let i = 0; i < count; i++) { + const v = vertex[i]; + // Open borders, refined edges, non-manifold vertices and those whose triangles are not all in + // the set stay where they are. + const around = triangleStart[v + 1] - triangleStart[v]; + const closedFan = around > 0 && around === neighbourStart[v + 1] - neighbourStart[v]; + if (ring[v] < 0 || !closedFan || faceStart[i + 1] - faceStart[i] !== around) continue; + const t = Math.min(1, ring[v] / featherRings); + weight[i] = t * t * (3 - 2 * t); + } + return { + count, + vertex, + weight, + fixed, + corners, + geometry, + triangle, + faceStart, + faces, + neighbourStart: localStart, + neighbours: localNeighbours, + sign: mesh.flipped ? -1 : 1, + }; +} + +/** Unit normal, centroid and area of each local triangle at `position`. */ +function faceGeometry(work: WorkingSet, position: Float64Array) { + const n = work.triangle.length; + const normal = new Float64Array(n * 3); + const centre = new Float64Array(n * 3); + const area = new Float64Array(n); + faceNormals(work, position, normal, area); + faceCentres(work, position, centre); + return { normal, centre, area }; +} + +function faceNormals(work: WorkingSet, p: Float64Array, normal: Float64Array, area: Float64Array) { + const { corners, sign } = work; + for (let f = 0; f < area.length; f++) { + const a = corners[f * 3] * 3, + b = corners[f * 3 + 1] * 3, + c = corners[f * 3 + 2] * 3; + const ux = p[b] - p[a], + uy = p[b + 1] - p[a + 1], + uz = p[b + 2] - p[a + 2]; + const vx = p[c] - p[a], + vy = p[c + 1] - p[a + 1], + vz = p[c + 2] - p[a + 2]; + const x = uy * vz - uz * vy, + y = uz * vx - ux * vz, + z = ux * vy - uy * vx; + const length = Math.sqrt(x * x + y * y + z * z); + area[f] = length / 2; + const scale = length > 0 ? sign / length : 0; + normal[f * 3] = x * scale; + normal[f * 3 + 1] = y * scale; + normal[f * 3 + 2] = z * scale; + } +} + +function faceCentres(work: WorkingSet, p: Float64Array, centre: Float64Array) { + const { corners } = work; + for (let f = 0; f < centre.length / 3; f++) { + const a = corners[f * 3] * 3, + b = corners[f * 3 + 1] * 3, + c = corners[f * 3 + 2] * 3; + for (let k = 0; k < 3; k++) centre[f * 3 + k] = (p[a + k] + p[b + k] + p[c + k]) / 3; + } +} + +/** + * Bilateral filtering of the face normals over the triangles that share a vertex with each face, + * weighted by area, by distance between centroids against their mean spacing, and by how near the + * two normals are against `range`. + */ +function filterNormals( + work: WorkingSet, + position: Float64Array, + rounds: number, + progress: () => void, +) { + const { corners, faceStart, faces } = work; + const { normal, centre, area } = faceGeometry(work, position); + const n = area.length; + const stamp = new Int32Array(n).fill(-1); + const around = (f: number, visit: (g: number) => void) => { + stamp[f] = f; + for (let k = 0; k < 3; k++) { + const v = corners[f * 3 + k]; + for (let i = faceStart[v]; i < faceStart[v + 1]; i++) { + const g = faces[i]; + if (stamp[g] === f) continue; + stamp[g] = f; + visit(g); + } + } + }; + let total = 0, + samples = 0; + const stride = Math.max(1, Math.floor(n / 20000)); + for (let f = 0; f < n; f += stride) + around(f, (g) => { + total += Math.hypot( + centre[g * 3] - centre[f * 3], + centre[g * 3 + 1] - centre[f * 3 + 1], + centre[g * 3 + 2] - centre[f * 3 + 2], + ); + samples++; + }); + stamp.fill(-1); + const spacing = samples ? total / samples : 1; + const spatial = 1 / (2 * spacing * spacing); + const similar = 1 / (2 * range * range); + let current = normal; + let next = new Float64Array(n * 3); + for (let round = 0; round < rounds; round++) { + for (let f = 0; f < n; f++) { + const cx = centre[f * 3], + cy = centre[f * 3 + 1], + cz = centre[f * 3 + 2]; + const nx = current[f * 3], + ny = current[f * 3 + 1], + nz = current[f * 3 + 2]; + let sx = area[f] * nx, + sy = area[f] * ny, + sz = area[f] * nz; + stamp[f] = f + round * n; + for (let k = 0; k < 3; k++) { + const v = corners[f * 3 + k]; + for (let i = faceStart[v]; i < faceStart[v + 1]; i++) { + const g = faces[i]; + if (stamp[g] === f + round * n) continue; + stamp[g] = f + round * n; + const dx = centre[g * 3] - cx, + dy = centre[g * 3 + 1] - cy, + dz = centre[g * 3 + 2] - cz; + const mx = current[g * 3] - nx, + my = current[g * 3 + 1] - ny, + mz = current[g * 3 + 2] - nz; + const w = + area[g] * + Math.exp( + -(dx * dx + dy * dy + dz * dz) * spatial - (mx * mx + my * my + mz * mz) * similar, + ); + sx += w * current[g * 3]; + sy += w * current[g * 3 + 1]; + sz += w * current[g * 3 + 2]; + } + } + const length = Math.sqrt(sx * sx + sy * sy + sz * sz); + const scale = length > 0 ? 1 / length : 0; + next[f * 3] = sx * scale; + next[f * 3 + 1] = sy * scale; + next[f * 3 + 2] = sz * scale; + } + [current, next] = [next, current]; + progress(); + } + return current; +} + +/** + * Each face's normal plus `amount` times its difference from the area-weighted mean of the normals + * within `blurRounds` rounds of averaging over the faces that share a vertex with it. + */ +function sharpenNormals( + work: WorkingSet, + position: Float64Array, + normals: Float64Array, + amount: number, +) { + const { corners, faceStart, faces } = work; + const n = normals.length / 3; + const area = new Float64Array(n); + faceNormals(work, position, new Float64Array(n * 3), area); + const stamp = new Int32Array(n).fill(-1); + let blur = normals.slice(); + let next = new Float64Array(n * 3); + for (let round = 0; round < blurRounds; round++) { + for (let f = 0; f < n; f++) { + let sx = area[f] * blur[f * 3], + sy = area[f] * blur[f * 3 + 1], + sz = area[f] * blur[f * 3 + 2]; + const mark = f + round * n; + stamp[f] = mark; + for (let k = 0; k < 3; k++) { + const v = corners[f * 3 + k]; + for (let i = faceStart[v]; i < faceStart[v + 1]; i++) { + const g = faces[i]; + if (stamp[g] === mark) continue; + stamp[g] = mark; + sx += area[g] * blur[g * 3]; + sy += area[g] * blur[g * 3 + 1]; + sz += area[g] * blur[g * 3 + 2]; + } + } + const length = Math.sqrt(sx * sx + sy * sy + sz * sz); + const scale = length > 0 ? 1 / length : 0; + next[f * 3] = sx * scale; + next[f * 3 + 1] = sy * scale; + next[f * 3 + 2] = sz * scale; + } + [blur, next] = [next, blur]; + } + const out = next; + for (let f = 0; f < n; f++) { + const k = f * 3; + const x = normals[k] + amount * (normals[k] - blur[k]), + y = normals[k + 1] + amount * (normals[k + 1] - blur[k + 1]), + z = normals[k + 2] + amount * (normals[k + 2] - blur[k + 2]); + const length = Math.sqrt(x * x + y * y + z * z); + const scale = length > 0 ? 1 / length : 0; + out[k] = x * scale; + out[k + 1] = y * scale; + out[k + 2] = z * scale; + } + return out; +} + +/** Moves each weighted vertex toward the planes of its triangles under their filtered normals. */ +function fitToNormals( + work: WorkingSet, + position: Float64Array, + normals: Float64Array, + rounds: number, +) { + const { count, weight, faceStart, faces } = work; + const centre = new Float64Array(normals.length); + for (let round = 0; round < rounds; round++) { + faceCentres(work, position, centre); + for (let i = 0; i < count; i++) { + if (!weight[i]) continue; + const from = faceStart[i], + to = faceStart[i + 1]; + const px = position[i * 3], + py = position[i * 3 + 1], + pz = position[i * 3 + 2]; + let dx = 0, + dy = 0, + dz = 0; + for (let j = from; j < to; j++) { + const f = faces[j] * 3; + const nx = normals[f], + ny = normals[f + 1], + nz = normals[f + 2]; + const d = nx * (centre[f] - px) + ny * (centre[f + 1] - py) + nz * (centre[f + 2] - pz); + dx += nx * d; + dy += ny * d; + dz += nz * d; + } + const scale = 1 / (to - from); + position[i * 3] = px + dx * scale; + position[i * 3 + 1] = py + dy * scale; + position[i * 3 + 2] = pz + dz * scale; + } + } +} + +/** One uniform Laplacian step over the set, holding fixed vertices: out = p + factor * (mean - p). */ +function laplacian(work: WorkingSet, p: Float64Array, out: Float64Array, factor: number) { + const { count, fixed, neighbourStart, neighbours } = work; + for (let i = 0; i < count; i++) { + const from = neighbourStart[i], + to = neighbourStart[i + 1]; + const k = i * 3; + if (fixed[i] || to === from) { + out[k] = p[k]; + out[k + 1] = p[k + 1]; + out[k + 2] = p[k + 2]; + continue; + } + let x = 0, + y = 0, + z = 0; + for (let j = from; j < to; j++) { + const u = neighbours[j] * 3; + x += p[u]; + y += p[u + 1]; + z += p[u + 2]; + } + const inverse = 1 / (to - from); + out[k] = p[k] + factor * (x * inverse - p[k]); + out[k + 1] = p[k + 1] + factor * (y * inverse - p[k + 1]); + out[k + 2] = p[k + 2] + factor * (z * inverse - p[k + 2]); + } +} + +/** Area-weighted vertex normals of the set at `p`, outward. */ +function vertexNormals(work: WorkingSet, p: Float64Array) { + const { count, faceStart, faces } = work; + const normal = new Float64Array(work.triangle.length * 3); + const area = new Float64Array(work.triangle.length); + faceNormals(work, p, normal, area); + const out = new Float64Array(count * 3); + for (let i = 0; i < count; i++) { + let x = 0, + y = 0, + z = 0; + for (let j = faceStart[i]; j < faceStart[i + 1]; j++) { + const f = faces[j]; + x += area[f] * normal[f * 3]; + y += area[f] * normal[f * 3 + 1]; + z += area[f] * normal[f * 3 + 2]; + } + const length = Math.sqrt(x * x + y * y + z * z); + const scale = length > 0 ? 1 / length : 0; + out[i * 3] = x * scale; + out[i * 3 + 1] = y * scale; + out[i * 3 + 2] = z * scale; + } + return out; +} + +/** The unsharp mask: relief above a Taubin base, averaged, thresholded and added `depth` times. */ +function deepen( + work: WorkingSet, + position: Float64Array, + plan: Plan, + threshold: number, + progress: (fraction: number) => void, +) { + const { count, weight, neighbourStart, neighbours } = work; + const mu = 1 / (plan.pass - 1 / lambda); + let base = position.slice(), + spare = new Float64Array(position.length); + for (let round = 0; round < plan.baseRounds; round++) { + laplacian(work, base, spare, lambda); + laplacian(work, spare, base, mu); + if (round % 16 === 15) progress((0.9 * (round + 1)) / plan.baseRounds); + } + const normal = vertexNormals(work, base); + let relief = new Float64Array(count); + for (let i = 0; i < count; i++) { + const k = i * 3; + relief[i] = + (position[k] - base[k]) * normal[k] + + (position[k + 1] - base[k + 1]) * normal[k + 1] + + (position[k + 2] - base[k + 2]) * normal[k + 2]; + } + let averaged = new Float64Array(count); + for (let pass = 0; pass < reliefPasses; pass++) { + for (let i = 0; i < count; i++) { + let sum = relief[i], + n = 1; + for (let j = neighbourStart[i]; j < neighbourStart[i + 1]; j++) { + sum += relief[neighbours[j]]; + n++; + } + averaged[i] = sum / n; + } + [relief, averaged] = [averaged, relief]; + } + const out = position.slice(); + const t2 = threshold * threshold; + for (let i = 0; i < count; i++) { + if (!weight[i]) continue; + const h = relief[i]; + const lift = weight[i] * plan.depth * h * ((h * h) / (h * h + t2)); + const k = i * 3; + out[k] += lift * normal[k]; + out[k + 1] += lift * normal[k + 1]; + out[k + 2] += lift * normal[k + 2]; + } + progress(1); + return out; +} + +/** + * Halves the moves of the corners of each triangle that would turn over or collapse, up to + * `halvings` times, then returns those still at fault to where they started. Returns how many + * vertices did not move as far as cleaning asked. + */ +function holdFolds(work: WorkingSet, start: Float64Array, position: Float64Array) { + const { corners } = work; + const n = work.triangle.length; + const before = new Float64Array(n * 3); + const area = new Float64Array(n); + faceNormals(work, start, before, area); + const startArea = area.slice(); + const after = new Float64Array(n * 3); + const flagged = new Uint8Array(work.count); + const reduced = new Uint8Array(work.count); + for (let round = 0; round <= halvings; round++) { + faceNormals(work, position, after, area); + flagged.fill(0); + let any = false; + for (let f = 0; f < n; f++) { + const a = corners[f * 3], + b = corners[f * 3 + 1], + c = corners[f * 3 + 2]; + if ( + !changed(start, position, a) && + !changed(start, position, b) && + !changed(start, position, c) + ) + continue; + const turned = + before[f * 3] * after[f * 3] + + before[f * 3 + 1] * after[f * 3 + 1] + + before[f * 3 + 2] * after[f * 3 + 2] <= + 0; + if (!turned && area[f] >= collapse * startArea[f]) continue; + flagged[a] = flagged[b] = flagged[c] = 1; + any = true; + } + if (!any) break; + for (let i = 0; i < work.count; i++) { + if (!flagged[i]) continue; + reduced[i] = 1; + const last = round === halvings; + for (let a = 0; a < 3; a++) { + const k = i * 3 + a; + position[k] = last ? start[k] : start[k] + 0.5 * (position[k] - start[k]); + } + } + } + let held = 0; + for (let i = 0; i < work.count; i++) if (reduced[i]) held++; + return held; +} + +/** + * Flips edges between moved vertices where the other diagonal of their two triangles bends the + * surface less, so an edge that sharpening made crisp runs along triangle edges instead of + * zigzagging across them. The bending of the five edges a flip changes is each edge's length times + * the angle between the normals of its two triangles; minimising its sum recovers sharp edges from a + * triangulation (Dyn, Hormann, Kim and Levin 2001). A flip must keep both triangles facing the way + * the pair did, keep them well shaped, and not join two vertices already joined. Vertices do not + * move. Returns the local triangles whose corners changed; `work.corners` and `work.geometry` are + * updated in place. + */ +function alignEdges(work: WorkingSet, start: Float64Array, p: Float64Array): Uint32Array { + const { corners: tri, geometry, faceStart, faces, weight, neighbourStart } = work; + const slots = tri.length; + const next = (s: number) => (s % 3 === 2 ? s - 2 : s + 1); + const prev = (s: number) => (s % 3 === 0 ? s + 2 : s - 1); + // The slot across each slot's edge, from the triangles around its far end. + const opposite = new Int32Array(slots).fill(-1); + for (let s = 0; s < slots; s++) { + const a = tri[s], + b = tri[next(s)]; + for (let i = faceStart[b]; i < faceStart[b + 1] && opposite[s] < 0; i++) { + const t = faces[i] * 3; + for (let k = 0; k < 3; k++) + if (tri[t + k] === b && tri[t + ((k + 1) % 3)] === a) opposite[s] = t + k; + } + } + const degree = new Int32Array(work.count); + for (let i = 0; i < work.count; i++) degree[i] = neighbourStart[i + 1] - neighbourStart[i]; + const moved = (i: number) => weight[i] > 0 && changed(start, p, i); + const faceCount = slots / 3; + const normal = new Float64Array(slots); + const area = new Float64Array(faceCount); + faceNormals(work, p, normal, area); + const unit = (a: number, b: number, c: number, out: Float64Array) => { + const ux = p[b * 3] - p[a * 3], + uy = p[b * 3 + 1] - p[a * 3 + 1], + uz = p[b * 3 + 2] - p[a * 3 + 2]; + const vx = p[c * 3] - p[a * 3], + vy = p[c * 3 + 1] - p[a * 3 + 1], + vz = p[c * 3 + 2] - p[a * 3 + 2]; + const x = uy * vz - uz * vy, + y = uz * vx - ux * vz, + z = ux * vy - uy * vx; + const length = Math.sqrt(x * x + y * y + z * z); + const scale = length > 0 ? work.sign / length : 0; + out[0] = x * scale; + out[1] = y * scale; + out[2] = z * scale; + return length / 2; + }; + const length = (a: number, b: number) => + Math.hypot(p[a * 3] - p[b * 3], p[a * 3 + 1] - p[b * 3 + 1], p[a * 3 + 2] - p[b * 3 + 2]); + const angle = (x: ArrayLike, i: number, y: ArrayLike, j: number) => + Math.acos(Math.max(-1, Math.min(1, x[i] * y[j] + x[i + 1] * y[j + 1] + x[i + 2] * y[j + 2]))); + const quality = (area: number, a: number, b: number, c: number) => + (4 * Math.sqrt(3) * area) / (a * a + b * b + c * c); + /** Whether `c` and `d` are joined, turning around `c` from its slot `from` both ways. */ + const joined = (from: number, d: number) => { + let s = from; + do { + if (tri[next(s)] === d) return true; + const o = opposite[prev(s)]; + if (o < 0) break; + s = o; + } while (s !== from); + for (s = from; ;) { + const o = opposite[s]; + if (o < 0) return false; + s = next(o); + if (s === from) return false; + if (tri[next(s)] === d) return true; + } + }; + const m1 = new Float64Array(3), + m2 = new Float64Array(3); + const flipped = new Uint8Array(faceCount); + for (let round = 0; round < flipRounds; round++) { + let flips = 0; + for (let s1 = 0; s1 < slots; s1++) { + const s2 = opposite[s1]; + if (s2 < s1) continue; + const t1 = (s1 / 3) | 0, + t2 = (s2 / 3) | 0; + const a = tri[s1], + b = tri[next(s1)], + c = tri[prev(s1)], + d = tri[prev(s2)]; + if (c === d || degree[a] <= 3 || degree[b] <= 3) continue; + if (!moved(a) || !moved(b) || !moved(c) || !moved(d)) continue; + const n1 = t1 * 3, + n2 = t2 * 3; + const bend = + normal[n1] * normal[n2] + normal[n1 + 1] * normal[n2 + 1] + normal[n1 + 2] * normal[n2 + 2]; + if (bend > flipBend) continue; + const bc = next(s1), + ca = prev(s1), + ad = next(s2), + db = prev(s2); + const obc = opposite[bc], + oca = opposite[ca], + oad = opposite[ad], + odb = opposite[db]; + if (obc < 0 || oca < 0 || oad < 0 || odb < 0) continue; + const area1 = unit(c, a, d, m1), + area2 = unit(d, b, c, m2); + // Both new triangles face the way the pair does. + const sx = normal[n1] + normal[n2], + sy = normal[n1 + 1] + normal[n2 + 1], + sz = normal[n1 + 2] + normal[n2 + 2]; + if (m1[0] * sx + m1[1] * sy + m1[2] * sz <= 0 || m2[0] * sx + m2[1] * sy + m2[2] * sz <= 0) + continue; + const lab = length(a, b), + lcd = length(c, d), + lbc = length(b, c), + lca = length(c, a), + lad = length(a, d), + ldb = length(d, b); + if ( + quality(area1, lca, lad, lcd) < flipQuality || + quality(area2, ldb, lbc, lcd) < flipQuality + ) + continue; + const face = (slot: number) => ((slot / 3) | 0) * 3; + const before = + lab * angle(normal, n1, normal, n2) + + lbc * angle(normal, n1, normal, face(obc)) + + lca * angle(normal, n1, normal, face(oca)) + + lad * angle(normal, n2, normal, face(oad)) + + ldb * angle(normal, n2, normal, face(odb)); + const after = + lcd * angle(m1, 0, m2, 0) + + lbc * angle(m2, 0, normal, face(obc)) + + lca * angle(m1, 0, normal, face(oca)) + + lad * angle(m1, 0, normal, face(oad)) + + ldb * angle(m2, 0, normal, face(odb)); + if (after >= flipGain * before || joined(prev(s1), d)) continue; + // t1 becomes (c, a, d) and t2 (d, b, c), each corner keeping a geometry vertex it had. + const gc = geometry[prev(s1)], + ga = geometry[s1], + gb = geometry[s2], + gd = geometry[prev(s2)]; + tri.set([c, a, d], n1); + tri.set([d, b, c], n2); + geometry.set([gc, ga, gd], n1); + geometry.set([gd, gb, gc], n2); + const link = (x: number, y: number) => { + opposite[x] = y; + opposite[y] = x; + }; + link(n1, oca); + link(n1 + 1, oad); + link(n2, odb); + link(n2 + 1, obc); + link(n1 + 2, n2 + 2); + normal.set(m1, n1); + normal.set(m2, n2); + degree[a]--; + degree[b]--; + degree[c]++; + degree[d]++; + flipped[t1] = flipped[t2] = 1; + flips++; + } + if (!flips) break; + } + let total = 0; + for (let f = 0; f < faceCount; f++) total += flipped[f]; + const out = new Uint32Array(total); + for (let f = 0, i = 0; f < faceCount; f++) if (flipped[f]) out[i++] = f; + return out; +} diff --git a/src/core/refine-job.ts b/src/core/refine-job.ts index 74da31a..8e966d0 100644 --- a/src/core/refine-job.ts +++ b/src/core/refine-job.ts @@ -1,3 +1,4 @@ +import type { CleanInput, CleanResult } from './refine-clean'; import type { DetectOptions, RefineProposal } from './refine-detect'; import { type RefineModel, @@ -6,6 +7,7 @@ import { buffersOf, packRefineModel, runRefineRequest, + unpackClean, unpackProposals, unpackRefineModel, } from './refine-model'; @@ -37,6 +39,22 @@ export function detectRefineJob( return run(request, signal, report, unpackProposals); } +/** Cleans copies of the model's arrays and returns the vertices that moved, with their positions. */ +export function cleanRefineJob( + model: RefineModel, + input: CleanInput, + signal: AbortSignal, + report: (fraction: number) => void, +): Promise { + if (signal.aborted) return Promise.reject(cancelled()); + const request: RefineRequest = { + type: 'clean', + model: packRefineModel(model), + input: { ...input, triangles: input.triangles?.slice() ?? null }, + }; + return run(request, signal, report, unpackClean); +} + function run( request: RefineRequest, signal: AbortSignal, diff --git a/src/core/refine-model.ts b/src/core/refine-model.ts index 29d50a5..91ae9b4 100644 --- a/src/core/refine-model.ts +++ b/src/core/refine-model.ts @@ -1,4 +1,5 @@ import { BufferAttribute, BufferGeometry, Matrix4 } from 'three'; +import { type CleanInput, type CleanResult, cleanSurface } from './refine-clean'; import { type DetectOptions, type RefineProposal, detectFeatures } from './refine-detect'; import { solveEdge } from './refine-edge'; import { estimateNoise, noiseRings } from './refine-fit'; @@ -115,7 +116,8 @@ export function keepSolvable( export type RefineRequest = | { type: 'build'; input: RefineModelInput } - | { type: 'detect'; model: RefineModel; options: DetectOptions }; + | { type: 'detect'; model: RefineModel; options: DetectOptions } + | { type: 'clean'; model: RefineModel; input: CleanInput }; /** The buffers of every typed array in `value`, for a transfer list. */ export function buffersOf(value: unknown): ArrayBuffer[] { @@ -170,14 +172,52 @@ export function unpackProposals(value: unknown): RefineProposal[] { return value as RefineProposal[]; } +/** The cleaned positions, or the cleaned mesh, a message carried. */ +export function unpackClean(value: unknown): CleanResult { + const result = value as CleanResult; + const topology = result?.topology; + const mesh = result?.mesh; + if ( + !(result?.moved instanceof Uint32Array) || + !(result.position instanceof Float64Array) || + result.position.length !== result.moved.length * 3 || + !(result.triangles instanceof Uint32Array) || + !(result.corners instanceof Uint32Array) || + result.corners.length !== result.triangles.length * 3 || + !(result.split instanceof Uint32Array) || + result.split.length % 2 !== 0 || + (result.triangles.length > 0 || !!mesh) !== !!topology || + (topology && + (Object.keys(topology).length !== 4 || + !Object.values(topology).every((array) => array instanceof Uint32Array))) || + (mesh !== null && + (!arrayFields.every(([key, Class]) => mesh?.[key] instanceof Class) || + !(mesh.color === null || mesh.color instanceof Float32Array) || + result.moved.length > 0 || + result.triangles.length > 0)) + ) + throw new Error('The cleaned surface came back unreadable.'); + return result; +} + /** Runs a request as the worker does, both in the worker and in-thread. */ export function runRefineRequest( request: RefineRequest, report: (fraction: number) => void, signal?: AbortSignal, -): RefineModel | RefineProposal[] { +): RefineModel | RefineProposal[] | CleanResult { if (request.type === 'build') return buildRefineModel(request.input); const model = unpackRefineModel(request.model); + if (request.type === 'clean') + return cleanSurface( + model.mesh, + model.topology, + model.noise, + model.step, + request.input, + report, + signal, + ); const { mesh, topology, noise } = model; const found = detectFeatures( mesh, diff --git a/src/core/refine-square.ts b/src/core/refine-square.ts new file mode 100644 index 0000000..3e2c19f --- /dev/null +++ b/src/core/refine-square.ts @@ -0,0 +1,1308 @@ +import { cutAlongField } from './refine-cut'; +import { + type RefineMesh, + type RefineTopology, + buildTopology, + cloneRefineMesh, + moveVertex, + trimRefineMesh, +} from './refine-mesh'; + +export interface SquareInput { + /** How far each rounding moves to its sharp corner, 0 to 1. */ + strength: number; + /** The widest rounding, mm, measured across its arc. */ + reach: number; + /** 1 for each welded vertex that may move; null lets every vertex move. */ + free: Uint8Array | null; +} + +export interface SquareOutcome { + /** The mesh with its corners rebuilt and cut along the new edges. */ + mesh: RefineMesh; + topology: RefineTopology; + /** Each triangle the cut split, with the triangles that now cover it, itself first. */ + children: Map; + /** Welded vertices on the rebuilt edges, where the rounding moved most of the way. */ + edge: Uint32Array; + /** Welded vertices that moved. */ + moved: number; + /** Vertices that moved less so that no triangle turns over. */ + held: number; +} + +const degree = Math.PI / 180; +/** Faces meet at 90 degrees give or take this many. */ +const angleTolerance = 25; +/** A face patch grows to faces within this angle of its mean normal... */ +const patchAngle = 10; +/** ...across edges whose two faces turn by less than this. */ +const stepAngle = 8; +/** A patch smaller than this many median edges squared is not a face... */ +const patchEdges = 12; +/** ...nor is one narrower than this many median edges, such as a strip along a rounding. */ +const faceEdges = 3; +/** Faces a patch's plane is fitted from lie within this many median edges of where it is read. */ +const fitEdges = 4; +/** Plane fits leave out this many rings of faces at a patch's rim, where it turns into the rounding. */ +const rimRings = 2; +/** Fitted planes are averaged with their neighbours' this many times. */ +const settleRounds = 4; +/** A run of rebuilt corner shorter than this many median edges is left out. */ +const runEdges = 10; +/** Moves ease in over this many median edges from where a run of corner ends. */ +const taperEdges = 3; +/** The cut follows the corner where a vertex lands within this many median edges of it. */ +const bandEdges = 2; +/** A circular rounding's middle moves 0.41 of its radius and its arc is 1.57 radii: moves longer than + * this share of the distance to the two faces are misfits. */ +const spanShare = 0.35; +/** A rebuilt edge vertex is marked a crease when it moved at least this share of the way. */ +const creaseShare = 0.75; +/** Times a vertex's move is halved for a triangle it would turn over before it is dropped. */ +const halvings = 6; +const none = -1; +const maxPlanes = 3; + +/** + * Rebuilds rounded edges where two faces meet at about 90 degrees, outside and inside, as sharp + * corners, and cuts the mesh along them. + * + * The surface is first split into patches of faces whose normals stay within `patchAngle` of their + * mean; a patch that curves tighter than `reach` is a rounding, not a face. Each vertex finds the + * nearest patches within `reach` and fits each one's plane from that patch's faces near it. Between + * two faces at 90 degrees, a rounding vertex lies inside both planes (an outside corner) or outside + * both (an inside one); it moves along its normal until it meets the sharp corner the planes make, + * as a ray cast against them. Three faces at 90 degrees make a box corner, cast against all three. + * Planes are averaged with matching neighbours' so the corner runs smoothly, runs shorter than + * `runEdges` are dropped, and moves ease in where a run ends. The mesh is then cut where vertices + * change from landing on one plane to the other, and each new vertex is placed on the corner line, so + * the edge runs along triangle edges. A move that would turn a triangle over is halved until it does + * not. + */ +export function squareCorners( + source: RefineMesh, + topology: RefineTopology, + noise: number, + step: number, + input: SquareInput, + progress: (fraction: number) => void = () => {}, + check: () => void = () => {}, +): SquareOutcome { + const strength = Math.min(1, Math.max(0, input.strength || 0)); + const reach = Math.max(input.reach, 2 * step); + const tri = weldedTriangles(source); + const position = source.position; + const n = source.weldedCount; + const sign = source.flipped ? -1 : 1; + const face = faceData(tri, position, sign); + const adjacent = faceNeighbours(tri, topology); + check(); + const patches = growPatches(adjacent, face, step, reach); + progress(0.15); + check(); + const near = nearestPatches(n, topology, position, patches.label, reach); + progress(0.3); + check(); + const normal = vertexNormals(n, topology, face); + const inner = interiorVertices(n, topology, patches.label); + const solve = new Solve(n); + fitVertices(topology, position, face, patches, near, normal, inner, solve, { + noise, + step, + reach, + free: input.free, + check, + }); + progress(0.6); + check(); + const tolerance = Math.max(3 * noise, 0.5 * step); + const slack = Math.max(2 * noise, 0.05 * step); + settle(topology, position, normal, solve, tolerance, slack, reach); + fillGaps(topology, position, normal, solve, inner, tolerance, slack, reach, input.free); + dropShortRuns(topology, position, solve, runEdges * step); + const weight = taper(topology, position, solve, inner, taperEdges * step); + for (let v = 0; v < n; v++) weight[v] *= strength; + progress(0.7); + check(); + const field = cornerField(topology, position, normal, solve, bandEdges * step, tolerance); + const listed: number[] = []; + for (let v = 0; v < n; v++) if (!Number.isNaN(field[v])) listed.push(v); + const mesh = cloneRefineMesh(source, true); + const plane = new Float64Array(8); + const corner = new Float64Array(3); + const cut = listed.length + ? cutAlongField( + mesh, + topology, + Uint32Array.from(listed), + Float32Array.from(listed, (v) => field[v]), + (x, y, z, out, a, b, t) => { + for (let k = 0; k < 8; k++) + plane[k] = solve.planes[a * 12 + k] * (1 - t) + solve.planes[b * 12 + k] * t; + for (const o of [0, 4]) { + const length = Math.hypot(plane[o], plane[o + 1], plane[o + 2]); + for (let k = 0; k < 3; k++) plane[o + k] /= length; + } + onCorner(x, y, z, plane, 0, corner); + const w = weight[a] * (1 - t) + weight[b] * t; + out[0] = x + w * (corner[0] - x); + out[1] = y + w * (corner[1] - y); + out[2] = z + w * (corner[2] - z); + }, + ) + : null; + progress(0.85); + check(); + const children = cut?.children ?? new Map(); + const onEdge = new Set(cut?.chain ?? []); + const movers: number[] = []; + for (let v = 0; v < n; v++) if (solve.K[v] && weight[v] > 0 && !onEdge.has(v)) movers.push(v); + const grown = trimRefineMesh(mesh); + const grownTopology = cut ? buildTopology(grown) : topology; + const held = moveHoldingFolds(source, grown, grownTopology, children, movers, solve, weight); + // Edge vertices where the rounding moved most of the way become creases, so later steps hold + // them and shading keeps the edge sharp. + const edge: number[] = []; + for (const v of onEdge) { + let sum = 0, + count = 0; + for (let i = grownTopology.neighbourStart[v]; i < grownTopology.neighbourStart[v + 1]; i++) { + const w = grownTopology.neighbours[i]; + if (w < n && solve.K[w]) { + sum += weight[w]; + count++; + } + } + if (count && sum / count >= creaseShare) edge.push(v); + } + edge.sort((a, b) => a - b); + let moved = 0; + for (let v = 0; v < grown.weldedCount; v++) + if ( + v >= n || + grown.position[v * 3] !== source.position[v * 3] || + grown.position[v * 3 + 1] !== source.position[v * 3 + 1] || + grown.position[v * 3 + 2] !== source.position[v * 3 + 2] + ) + moved++; + progress(1); + return { + mesh: grown, + topology: grownTopology, + children, + edge: Uint32Array.from(edge), + moved, + held, + }; +} + +function weldedTriangles(mesh: RefineMesh) { + const tri = new Uint32Array(mesh.triangleCount * 3); + for (let i = 0; i < tri.length; i++) tri[i] = mesh.weldOf[mesh.corners[i]]; + return tri; +} + +interface Faces { + tri: Uint32Array; + normal: Float64Array; + area: Float64Array; + centre: Float64Array; +} + +/** Outward unit normal, area and centroid of each triangle. */ +function faceData(tri: Uint32Array, p: Float64Array, sign: number): Faces { + const count = tri.length / 3; + const normal = new Float64Array(count * 3), + area = new Float64Array(count), + centre = new Float64Array(count * 3); + for (let t = 0; t < count; t++) { + const a = tri[t * 3] * 3, + b = tri[t * 3 + 1] * 3, + c = tri[t * 3 + 2] * 3; + const ux = p[b] - p[a], + uy = p[b + 1] - p[a + 1], + uz = p[b + 2] - p[a + 2]; + const vx = p[c] - p[a], + vy = p[c + 1] - p[a + 1], + vz = p[c + 2] - p[a + 2]; + const x = uy * vz - uz * vy, + y = uz * vx - ux * vz, + z = ux * vy - uy * vx; + const length = Math.sqrt(x * x + y * y + z * z); + area[t] = length / 2; + const scale = length > 0 ? sign / length : 0; + normal[t * 3] = x * scale; + normal[t * 3 + 1] = y * scale; + normal[t * 3 + 2] = z * scale; + for (let k = 0; k < 3; k++) centre[t * 3 + k] = (p[a + k] + p[b + k] + p[c + k]) / 3; + } + return { tri, normal, area, centre }; +} + +/** The triangle across each triangle's edge from corner k to k + 1, or -1 on an open or shared edge. */ +function faceNeighbours(tri: Uint32Array, topology: RefineTopology) { + const count = tri.length / 3; + const adjacent = new Int32Array(count * 3).fill(none); + const { triangleStart, trianglesOf } = topology; + for (let t = 0; t < count; t++) + for (let k = 0; k < 3; k++) { + const a = tri[t * 3 + k], + b = tri[t * 3 + ((k + 1) % 3)]; + let other = none, + found = 0; + for (let i = triangleStart[a]; i < triangleStart[a + 1]; i++) { + const s = trianglesOf[i]; + if (s !== t && (tri[s * 3] === b || tri[s * 3 + 1] === b || tri[s * 3 + 2] === b)) { + other = s; + found++; + } + } + if (found === 1) adjacent[t * 3 + k] = other; + } + return adjacent; +} + +function vertexNormals(n: number, topology: RefineTopology, face: Faces) { + const { triangleStart, trianglesOf } = topology; + const out = new Float64Array(n * 3); + for (let v = 0; v < n; v++) { + let x = 0, + y = 0, + z = 0; + for (let i = triangleStart[v]; i < triangleStart[v + 1]; i++) { + const t = trianglesOf[i]; + x += face.normal[t * 3] * face.area[t]; + y += face.normal[t * 3 + 1] * face.area[t]; + z += face.normal[t * 3 + 2] * face.area[t]; + } + const length = Math.sqrt(x * x + y * y + z * z); + const scale = length > 0 ? 1 / length : 0; + out[v * 3] = x * scale; + out[v * 3 + 1] = y * scale; + out[v * 3 + 2] = z * scale; + } + return out; +} + +interface Patches { + /** Patch of each triangle, or -1. */ + label: Int32Array; + count: number; + /** Rings of faces in from each face's patch rim, up to 255. */ + depth: Uint8Array; +} + +/** + * Grows patches from the flattest faces outward over edges that turn less than `stepAngle`, keeping + * each face within `patchAngle` of the patch's mean normal. Normals are first averaged twice with + * edge neighbours within 30 degrees so noise does not stop growth. A patch is kept when it is at least + * `patchEdges` squared median edges and curves no tighter than `reach`: its normals' spread over its + * extent, across the direction they spread in. + */ +function growPatches(adjacent: Int32Array, face: Faces, step: number, reach: number): Patches { + const { area, centre } = face; + const count = area.length; + let normal = face.normal; + const within = Math.cos(30 * degree); + for (let round = 0; round < 2; round++) { + const next = normal.slice(); + for (let t = 0; t < count; t++) { + let x = normal[t * 3] * area[t], + y = normal[t * 3 + 1] * area[t], + z = normal[t * 3 + 2] * area[t]; + for (let k = 0; k < 3; k++) { + const s = adjacent[t * 3 + k]; + if (s < 0 || dot(normal, t, normal, s) < within) continue; + x += normal[s * 3] * area[s]; + y += normal[s * 3 + 1] * area[s]; + z += normal[s * 3 + 2] * area[s]; + } + const length = Math.sqrt(x * x + y * y + z * z); + const scale = length > 0 ? 1 / length : 0; + next[t * 3] = x * scale; + next[t * 3 + 1] = y * scale; + next[t * 3 + 2] = z * scale; + } + normal = next; + } + const bend = new Float64Array(count); + for (let t = 0; t < count; t++) { + let worst = 0; + for (let k = 0; k < 3; k++) { + const s = adjacent[t * 3 + k]; + if (s >= 0) worst = Math.max(worst, 1 - dot(normal, t, normal, s)); + } + bend[t] = worst; + } + const order = Uint32Array.from({ length: count }, (_, i) => i).sort((a, b) => bend[a] - bend[b]); + const label = new Int32Array(count).fill(none); + const meanLimit = Math.cos(patchAngle * degree), + stepLimit = Math.cos(stepAngle * degree); + const seedLimit = 1 - stepLimit; + const queue = new Uint32Array(count); + // Per patch: area, then sums for the normal's and the centroid's mean and second moments. + const moments: number[] = []; + let patches = 0; + for (const seed of order) { + if (bend[seed] > seedLimit) break; + if (label[seed] >= 0) continue; + const id = patches++; + let head = 0, + tail = 0; + queue[tail++] = seed; + label[seed] = id; + let mx = 0, + my = 0, + mz = 0; + const sums = new Float64Array(moment); + while (head < tail) { + const t = queue[head++]; + const a = area[t]; + const nx = normal[t * 3], + ny = normal[t * 3 + 1], + nz = normal[t * 3 + 2]; + mx += nx * a; + my += ny * a; + mz += nz * a; + const n = [nx, ny, nz], + c = [centre[t * 3], centre[t * 3 + 1], centre[t * 3 + 2]]; + sums[0] += a; + for (let i = 0; i < 3; i++) { + sums[1 + i] += a * n[i]; + sums[4 + i] += a * c[i]; + for (let j = 0; j < 3; j++) { + sums[7 + i * 3 + j] += a * c[i] * c[j]; + sums[16 + i * 3 + j] += a * n[i] * c[j]; + } + } + const ml = Math.sqrt(mx * mx + my * my + mz * mz) || 1; + for (let k = 0; k < 3; k++) { + const s = adjacent[t * 3 + k]; + if (s < 0 || label[s] >= 0) continue; + if (dot(normal, t, normal, s) < stepLimit) continue; + if ((normal[s * 3] * mx + normal[s * 3 + 1] * my + normal[s * 3 + 2] * mz) / ml < meanLimit) + continue; + label[s] = id; + queue[tail++] = s; + } + } + moments.push(...sums); + } + const minArea = patchEdges * step * step; + const remap = new Int32Array(patches).fill(none); + let kept = 0; + for (let i = 0; i < patches; i++) { + const m = moments.slice(i * moment, (i + 1) * moment); + const shape = patchShape(m, step); + if (m[0] < minArea || shape.width < faceEdges * step || shape.curvature * reach > 1) continue; + remap[i] = kept++; + } + for (let t = 0; t < count; t++) if (label[t] >= 0) label[t] = remap[label[t]]; + const depth = new Uint8Array(count).fill(255); + let ring: number[] = []; + for (let t = 0; t < count; t++) { + if (label[t] < 0) continue; + for (let k = 0; k < 3; k++) { + const s = adjacent[t * 3 + k]; + if (s < 0 || label[s] !== label[t]) { + depth[t] = 0; + ring.push(t); + break; + } + } + } + for (let d = 1; d <= rimRings && ring.length; d++) { + const next: number[] = []; + for (const t of ring) + for (let k = 0; k < 3; k++) { + const s = adjacent[t * 3 + k]; + if (s >= 0 && label[s] === label[t] && depth[s] === 255) { + depth[s] = d; + next.push(s); + } + } + ring = next; + } + return { label, count: kept, depth }; +} + +/** Area-weighted sums kept per patch: area, normal, centroid, centroid by centroid, normal by centroid. */ +const moment = 25; + +/** + * A patch's narrowest width, mm, from the spread of its centroids across its tangent plane, and how + * tightly it curves, 1/mm at most: the largest singular value of the least-squares linear map from + * position to normal in that plane (its shape operator), with the spread padded by a quarter edge so + * a narrow patch does not read as sharp. + */ +function patchShape(m: ArrayLike, step: number) { + const flat = { width: Infinity, curvature: 0 }; + const w = m[0]; + if (!(w > 0)) return flat; + const n = [m[1] / w, m[2] / w, m[3] / w]; + const c = [m[4] / w, m[5] / w, m[6] / w]; + const xx = (i: number, j: number) => m[7 + i * 3 + j] / w - c[i] * c[j]; + const nx = (i: number, j: number) => m[16 + i * 3 + j] / w - n[i] * c[j]; + const length = Math.hypot(n[0], n[1], n[2]); + if (!(length > 0)) return flat; + const normal = n.map((v) => v / length); + const helper = Math.abs(normal[0]) < 0.6 ? [1, 0, 0] : [0, 1, 0]; + const u = [ + normal[1] * helper[2] - normal[2] * helper[1], + normal[2] * helper[0] - normal[0] * helper[2], + normal[0] * helper[1] - normal[1] * helper[0], + ]; + const ul = Math.hypot(u[0], u[1], u[2]); + for (let i = 0; i < 3; i++) u[i] /= ul; + const v = [ + normal[1] * u[2] - normal[2] * u[1], + normal[2] * u[0] - normal[0] * u[2], + normal[0] * u[1] - normal[1] * u[0], + ]; + const axes = [u, v]; + const project = (f: (i: number, j: number) => number, a: number[], b: number[]) => { + let sum = 0; + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) sum += a[i] * f(i, j) * b[j]; + return sum; + }; + // Positions' covariance in the tangent plane, and the normals' covariance with them. + const p11 = project(xx, u, u), + p12 = project(xx, u, v), + p22 = project(xx, v, v); + const least = (p11 + p22) / 2 - Math.sqrt(((p11 - p22) / 2) ** 2 + p12 * p12); + // A strip of uniform width spreads its centroids by width^2 / 12 across it. + const width = Math.sqrt(12 * Math.max(0, least)); + const pad = (step / 4) ** 2; + const a11 = p11 + pad, + a22 = p22 + pad; + const det = a11 * a22 - p12 * p12; + if (!(det > 0)) return { width, curvature: 0 }; + const inverse = [ + [a22 / det, -p12 / det], + [-p12 / det, a11 / det], + ]; + const q = axes.map((a) => axes.map((b) => project(nx, a, b))); + const s = [0, 1].map((i) => [0, 1].map((j) => q[i][0] * inverse[0][j] + q[i][1] * inverse[1][j])); + // Largest singular value of the 2 x 2 map. + const a = s[0][0] ** 2 + s[1][0] ** 2, + b = s[0][0] * s[0][1] + s[1][0] * s[1][1], + d = s[0][1] ** 2 + s[1][1] ** 2; + return { width, curvature: Math.sqrt((a + d) / 2 + Math.sqrt(((a - d) / 2) ** 2 + b * b)) }; +} + +/** A binary min-heap of entries (key, vertex, patch, source). */ +class Heap { + private key: number[] = []; + private data: number[] = []; + get size() { + return this.key.length; + } + push(key: number, a: number, b: number, c: number) { + let i = this.key.length; + this.key.push(key); + this.data.push(a, b, c); + while (i > 0) { + const parent = (i - 1) >> 1; + if (this.key[parent] <= key) break; + this.swap(i, parent); + i = parent; + } + } + /** Pops the least entry into `out` as key, a, b, c. */ + pop(out: number[]) { + out[0] = this.key[0]; + out[1] = this.data[0]; + out[2] = this.data[1]; + out[3] = this.data[2]; + const last = this.key.length - 1; + this.swap(0, last); + this.key.pop(); + this.data.length -= 3; + const size = this.key.length; + for (let i = 0; ;) { + const l = i * 2 + 1, + r = l + 1; + let m = i; + if (l < size && this.key[l] < this.key[m]) m = l; + if (r < size && this.key[r] < this.key[m]) m = r; + if (m === i) break; + this.swap(i, m); + i = m; + } + } + private swap(i: number, j: number) { + const k = this.key[i]; + this.key[i] = this.key[j]; + this.key[j] = k; + for (let a = 0; a < 3; a++) { + const d = this.data[i * 3 + a]; + this.data[i * 3 + a] = this.data[j * 3 + a]; + this.data[j * 3 + a] = d; + } + } +} + +interface Nearest { + /** Up to `maxPlanes` per vertex, nearest first: patch, distance along the surface, and the + * vertex of that patch it was reached from. */ + patch: Int32Array; + distance: Float64Array; + from: Int32Array; + count: Uint8Array; +} + +/** The nearest patches to each vertex within `reach`, by distance along mesh edges. */ +function nearestPatches( + n: number, + topology: RefineTopology, + p: Float64Array, + label: Int32Array, + reach: number, +): Nearest { + const { triangleStart, trianglesOf, neighbourStart, neighbours } = topology; + const patch = new Int32Array(n * maxPlanes).fill(none); + const distance = new Float64Array(n * maxPlanes).fill(Infinity); + const from = new Int32Array(n * maxPlanes).fill(none); + const count = new Uint8Array(n); + const heap = new Heap(); + for (let v = 0; v < n; v++) + for (let i = triangleStart[v]; i < triangleStart[v + 1]; i++) { + const l = label[trianglesOf[i]]; + if (l < 0) continue; + let seen = false; + for (let j = triangleStart[v]; j < i && !seen; j++) seen = label[trianglesOf[j]] === l; + if (!seen) heap.push(0, v, l, v); + } + const has = (v: number, l: number) => { + for (let k = 0; k < count[v]; k++) if (patch[v * maxPlanes + k] === l) return true; + return false; + }; + const entry = [0, 0, 0, 0]; + while (heap.size) { + heap.pop(entry); + const [d, v, l, s] = entry; + if (count[v] >= maxPlanes || has(v, l)) continue; + const k = v * maxPlanes + count[v]++; + patch[k] = l; + distance[k] = d; + from[k] = s; + for (let i = neighbourStart[v]; i < neighbourStart[v + 1]; i++) { + const w = neighbours[i]; + if (count[w] >= maxPlanes || has(w, l)) continue; + const next = + d + + Math.hypot(p[w * 3] - p[v * 3], p[w * 3 + 1] - p[v * 3 + 1], p[w * 3 + 2] - p[v * 3 + 2]); + if (next <= reach) heap.push(next, w, l, s); + } + } + return { patch, distance, from, count }; +} + +/** Per vertex: how many planes it is squared against (0, 2 or 3), the planes, and its target. */ +class Solve { + readonly K: Uint8Array; + /** Up to three planes per vertex, each a unit normal and offset. */ + readonly planes: Float64Array; + /** 1 for an outside corner, -1 for an inside one. */ + readonly kind: Int8Array; + readonly target: Float64Array; + constructor(n: number) { + this.K = new Uint8Array(n); + this.planes = new Float64Array(n * 12); + this.kind = new Int8Array(n); + this.target = new Float64Array(n * 3); + } +} + +/** + * Casts a ray from `p` along the normal, out of an outside corner or into an inside one, against + * `count` planes from `base`, to where it leaves the region inside them all or enters the region + * inside any. Null when `p` is not inside them all, or outside them all, by `slack`, or the normal + * turns from a plane. + */ +function rayCast( + p: ArrayLike, + normal: ArrayLike, + planes: Float64Array, + base: number, + count: number, + slack: number, +) { + let sum = 0, + inside = true, + outside = true; + for (let i = 0; i < count; i++) { + const o = base + i * 4; + const s = planes[o] * p[0] + planes[o + 1] * p[1] + planes[o + 2] * p[2] - planes[o + 3]; + if (planes[o] * normal[0] + planes[o + 1] * normal[1] + planes[o + 2] * normal[2] < 0.05) + return null; + sum += s; + if (s > slack) inside = false; + if (s < -slack) outside = false; + } + const kind = inside && sum < 0 ? 1 : outside && sum > 0 ? -1 : 0; + if (!kind) return null; + let t = Infinity; + for (let i = 0; i < count; i++) { + const o = base + i * 4; + const s = planes[o] * p[0] + planes[o + 1] * p[1] + planes[o + 2] * p[2] - planes[o + 3]; + const c = planes[o] * normal[0] + planes[o + 1] * normal[1] + planes[o + 2] * normal[2]; + t = Math.min(t, Math.max(0, (-kind * s) / c)); + } + return { kind, t }; +} + +interface FitOptions { + noise: number; + step: number; + reach: number; + free: Uint8Array | null; + check: () => void; +} + +/** Whether every triangle around `v` is in one patch. */ +function interiorVertices(n: number, topology: RefineTopology, label: Int32Array) { + const { triangleStart, trianglesOf } = topology; + const inner = new Uint8Array(n); + for (let v = 0; v < n; v++) { + let l = none - 1; + let one = triangleStart[v + 1] > triangleStart[v]; + for (let i = triangleStart[v]; i < triangleStart[v + 1] && one; i++) { + const f = label[trianglesOf[i]]; + if (f < 0 || (l !== none - 1 && f !== l)) one = false; + l = f; + } + inner[v] = +one; + } + return inner; +} + +/** Fits each vertex in a rounding between faces at 90 degrees, and casts it to their corner. */ +function fitVertices( + topology: RefineTopology, + position: Float64Array, + face: Faces, + patches: Patches, + near: Nearest, + normal: Float64Array, + inner: Uint8Array, + solve: Solve, + options: FitOptions, +) { + const n = inner.length; + const { noise, step, reach, free, check } = options; + const cache = new Map(); + const stamp = new Int32Array(n); + const mark = { value: 0 }; + const planeOf = (s: number, l: number) => { + const key = s * (patches.count + 1) + l; + let plane = cache.get(key); + if (plane === undefined) { + plane = localPlane(topology, position, face, patches, s, l, fitEdges * step, stamp, mark); + cache.set(key, plane); + } + return plane; + }; + const slack = Math.max(2 * noise, 0.05 * step); + const low = Math.cos((90 + angleTolerance) * degree), + high = Math.cos((90 - angleTolerance) * degree); + const square = (a: Float64Array, b: Float64Array) => { + const d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + return d >= low && d <= high; + }; + const trial = new Float64Array(12); + const found: (Float64Array | null)[] = [null, null, null]; + const pairs = [ + [0, 1], + [0, 2], + [1, 2], + ]; + for (let v = 0; v < n; v++) { + if ((v & 4095) === 0) check(); + const count = near.count[v]; + if (count < 2 || inner[v] || (free && !free[v])) continue; + let planes = 0; + for (let k = 0; k < count; k++) { + found[k] = planeOf(near.from[v * maxPlanes + k], near.patch[v * maxPlanes + k]); + if (found[k]) planes++; + } + if (planes < 2) continue; + const p = position.subarray(v * 3, v * 3 + 3), + nv = normal.subarray(v * 3, v * 3 + 3); + let chosen: number[] | null = null; + let cast: ReturnType = null; + if ( + count === 3 && + found[0] && + found[1] && + found[2] && + square(found[0], found[1]) && + square(found[0], found[2]) && + square(found[1], found[2]) + ) { + for (let k = 0; k < 3; k++) trial.set(found[k]!, k * 4); + cast = rayCast(p, nv, trial, 0, 3, slack); + if (cast) chosen = [0, 1, 2]; + } + for (const [i, j] of pairs) { + if (chosen) break; + if (j >= count || !found[i] || !found[j] || !square(found[i]!, found[j]!)) continue; + trial.set(found[i]!, 0); + trial.set(found[j]!, 4); + cast = rayCast(p, nv, trial, 0, 2, slack); + if (cast) chosen = [i, j]; + } + if (!chosen || !cast) continue; + let span = 0; + for (const c of chosen) span += near.distance[v * maxPlanes + c]; + if (cast.t > 0.6 * reach || cast.t > spanShare * span + 2 * noise) continue; + solve.K[v] = chosen.length; + chosen.forEach((c, i) => solve.planes.set(found[c]!, v * 12 + i * 4)); + solve.kind[v] = cast.kind; + } +} + +/** + * The plane of patch `l` around vertex `s`: from that patch's faces within `radius`, leaving out its + * rim where it can, the area-weighted mean normal of the faces within 8 degrees of their mean, through + * their area-weighted mean centroid. + */ +function localPlane( + topology: RefineTopology, + position: Float64Array, + face: Faces, + patches: Patches, + s: number, + l: number, + radius: number, + stamp: Int32Array, + mark: { value: number }, +): Float64Array | null { + const { triangleStart, trianglesOf, neighbourStart, neighbours } = topology; + const { label, depth } = patches; + const px = position[s * 3], + py = position[s * 3 + 1], + pz = position[s * 3 + 2]; + const r2 = radius * radius; + const id = ++mark.value; + const queue = [s]; + stamp[s] = id; + const faces = new Set(); + for (let q = 0; q < queue.length; q++) { + const u = queue[q]; + let inPatch = false; + for (let i = triangleStart[u]; i < triangleStart[u + 1]; i++) { + const t = trianglesOf[i]; + if (label[t] !== l) continue; + inPatch = true; + faces.add(t); + } + if (!inPatch) continue; + for (let i = neighbourStart[u]; i < neighbourStart[u + 1]; i++) { + const w = neighbours[i]; + if (stamp[w] === id) continue; + const dx = position[w * 3] - px, + dy = position[w * 3 + 1] - py, + dz = position[w * 3 + 2] - pz; + if (dx * dx + dy * dy + dz * dz > r2) continue; + stamp[w] = id; + queue.push(w); + } + } + let list = [...faces]; + if (list.length < 3) return null; + for (let least = rimRings; least > 0; least--) { + const inner = list.filter((t) => depth[t] >= least); + if (inner.length >= 6) { + list = inner; + break; + } + } + const { normal, area, centre } = face; + let mx = 0, + my = 0, + mz = 0; + for (const t of list) { + mx += normal[t * 3] * area[t]; + my += normal[t * 3 + 1] * area[t]; + mz += normal[t * 3 + 2] * area[t]; + } + let length = Math.sqrt(mx * mx + my * my + mz * mz); + if (!(length > 0)) return null; + mx /= length; + my /= length; + mz /= length; + const close = Math.cos(8 * degree); + let nx = 0, + ny = 0, + nz = 0, + cx = 0, + cy = 0, + cz = 0, + total = 0, + kept = 0; + for (const t of list) { + if (normal[t * 3] * mx + normal[t * 3 + 1] * my + normal[t * 3 + 2] * mz < close) continue; + const a = area[t]; + nx += normal[t * 3] * a; + ny += normal[t * 3 + 1] * a; + nz += normal[t * 3 + 2] * a; + cx += centre[t * 3] * a; + cy += centre[t * 3 + 1] * a; + cz += centre[t * 3 + 2] * a; + total += a; + kept++; + } + if (kept < 3 || !(total > 0)) return null; + length = Math.sqrt(nx * nx + ny * ny + nz * nz); + nx /= length; + ny /= length; + nz /= length; + return Float64Array.of(nx, ny, nz, (nx * cx + ny * cy + nz * cz) / total); +} + +/** Whether plane j of w is plane i of v: normals within 12 degrees and heights at `p` within `tolerance`. */ +function matches( + planes: Float64Array, + v: number, + i: number, + w: number, + j: number, + p: ArrayLike, + tolerance: number, +) { + const a = v * 12 + i * 4, + b = w * 12 + j * 4; + if (planes[a] * planes[b] + planes[a + 1] * planes[b + 1] + planes[a + 2] * planes[b + 2] < 0.978) + return false; + const sa = planes[a] * p[0] + planes[a + 1] * p[1] + planes[a + 2] * p[2] - planes[a + 3]; + const sb = planes[b] * p[0] + planes[b + 1] * p[1] + planes[b + 2] * p[2] - planes[b + 3]; + return Math.abs(sa - sb) < tolerance; +} + +/** Casts a fitted vertex to its target, or unfits it. */ +function cast( + v: number, + position: Float64Array, + normal: Float64Array, + solve: Solve, + slack: number, + reach: number, +) { + const p = position.subarray(v * 3, v * 3 + 3), + nv = normal.subarray(v * 3, v * 3 + 3); + const result = rayCast(p, nv, solve.planes, v * 12, solve.K[v], slack); + if (!result || result.t > 0.6 * reach) { + solve.K[v] = 0; + return; + } + solve.kind[v] = result.kind; + for (let a = 0; a < 3; a++) solve.target[v * 3 + a] = p[a] + result.kind * result.t * nv[a]; +} + +/** Averages each plane with the matching planes of fitted neighbours, then casts again. */ +function settle( + topology: RefineTopology, + position: Float64Array, + normal: Float64Array, + solve: Solve, + tolerance: number, + slack: number, + reach: number, +) { + const { neighbourStart, neighbours } = topology; + const { K, planes, kind } = solve; + const n = K.length; + for (let round = 0; round < settleRounds; round++) { + const next = planes.slice(); + for (let v = 0; v < n; v++) { + if (!K[v]) continue; + const p = position.subarray(v * 3, v * 3 + 3); + for (let i = 0; i < K[v]; i++) { + const base = v * 12 + i * 4; + let x = planes[base], + y = planes[base + 1], + z = planes[base + 2]; + // Offsets are averaged as each plane's height at v, so planes read far along do not skew it. + let height = x * p[0] + y * p[1] + z * p[2] - planes[base + 3]; + let count = 1; + for (let e = neighbourStart[v]; e < neighbourStart[v + 1]; e++) { + const w = neighbours[e]; + if (!K[w] || kind[w] !== kind[v]) continue; + for (let j = 0; j < K[w]; j++) { + if (!matches(planes, v, i, w, j, p, tolerance)) continue; + const b = w * 12 + j * 4; + x += planes[b]; + y += planes[b + 1]; + z += planes[b + 2]; + height += + planes[b] * p[0] + planes[b + 1] * p[1] + planes[b + 2] * p[2] - planes[b + 3]; + count++; + break; + } + } + const length = Math.sqrt(x * x + y * y + z * z); + x /= length; + y /= length; + z /= length; + next[base] = x; + next[base + 1] = y; + next[base + 2] = z; + next[base + 3] = x * p[0] + y * p[1] + z * p[2] - height / count; + } + } + planes.set(next); + } + for (let v = 0; v < n; v++) if (K[v]) cast(v, position, normal, solve, slack, reach); +} + +/** A vertex in a rounding left unfitted between fitted neighbours on one pair of planes takes them. */ +function fillGaps( + topology: RefineTopology, + position: Float64Array, + normal: Float64Array, + solve: Solve, + inner: Uint8Array, + tolerance: number, + slack: number, + reach: number, + free: Uint8Array | null, +) { + const { neighbourStart, neighbours } = topology; + const { K, planes, kind } = solve; + const n = K.length; + const mean = new Float64Array(8); + for (let round = 0; round < 2; round++) { + const added: [number, Float64Array][] = []; + for (let v = 0; v < n; v++) { + if (K[v] || inner[v] || (free && !free[v])) continue; + let first = none; + for (let e = neighbourStart[v]; e < neighbourStart[v + 1] && first < 0; e++) + if (K[neighbours[e]] === 2) first = neighbours[e]; + if (first < 0) continue; + const p = position.subarray(v * 3, v * 3 + 3); + mean.fill(0); + let count = 0; + for (let e = neighbourStart[v]; e < neighbourStart[v + 1]; e++) { + const w = neighbours[e]; + if (K[w] !== 2 || kind[w] !== kind[first]) continue; + let swap: boolean; + if ( + matches(planes, first, 0, w, 0, p, tolerance) && + matches(planes, first, 1, w, 1, p, tolerance) + ) + swap = false; + else if ( + matches(planes, first, 0, w, 1, p, tolerance) && + matches(planes, first, 1, w, 0, p, tolerance) + ) + swap = true; + else continue; + for (let h = 0; h < 2; h++) { + const from = w * 12 + (swap ? 1 - h : h) * 4; + for (let k = 0; k < 4; k++) mean[h * 4 + k] += planes[from + k]; + } + count++; + } + if (count < 2) continue; + for (const b of [0, 4]) { + const length = Math.hypot(mean[b], mean[b + 1], mean[b + 2]); + for (let k = 0; k < 3; k++) mean[b + k] /= length; + mean[b + 3] /= count; + } + const result = rayCast(p, normal.subarray(v * 3, v * 3 + 3), mean, 0, 2, slack); + if (result && result.t <= 0.6 * reach) added.push([v, mean.slice()]); + } + for (const [v, plane] of added) { + K[v] = 2; + planes.set(plane, v * 12); + cast(v, position, normal, solve, slack, reach); + } + if (!added.length) break; + } +} + +/** Unfits runs of fitted vertices whose extent is under `least` mm. */ +function dropShortRuns( + topology: RefineTopology, + position: Float64Array, + solve: Solve, + least: number, +) { + const { neighbourStart, neighbours } = topology; + const { K } = solve; + const n = K.length; + const seen = new Uint8Array(n); + const queue: number[] = []; + for (let seed = 0; seed < n; seed++) { + if (!K[seed] || seen[seed]) continue; + seen[seed] = 1; + queue.length = 0; + queue.push(seed); + const low = [Infinity, Infinity, Infinity], + high = [-Infinity, -Infinity, -Infinity]; + for (let q = 0; q < queue.length; q++) { + const v = queue[q]; + for (let a = 0; a < 3; a++) { + low[a] = Math.min(low[a], position[v * 3 + a]); + high[a] = Math.max(high[a], position[v * 3 + a]); + } + for (let e = neighbourStart[v]; e < neighbourStart[v + 1]; e++) { + const w = neighbours[e]; + if (!K[w] || seen[w]) continue; + seen[w] = 1; + queue.push(w); + } + } + if (Math.hypot(high[0] - low[0], high[1] - low[1], high[2] - low[2]) < least) + for (const v of queue) K[v] = 0; + } +} + +/** + * The share of its move each fitted vertex makes: none beside an unfitted vertex in a rounding, + * easing to all `length` mm from it along fitted vertices. + */ +function taper( + topology: RefineTopology, + position: Float64Array, + solve: Solve, + inner: Uint8Array, + length: number, +) { + const { neighbourStart, neighbours } = topology; + const { K } = solve; + const n = K.length; + const distance = new Float64Array(n).fill(Infinity); + const heap = new Heap(); + for (let v = 0; v < n; v++) { + if (K[v] || inner[v]) continue; + let beside = false; + for (let e = neighbourStart[v]; e < neighbourStart[v + 1] && !beside; e++) + beside = K[neighbours[e]] > 0; + if (!beside) continue; + distance[v] = 0; + heap.push(0, v, 0, 0); + } + const entry = [0, 0, 0, 0]; + while (heap.size) { + heap.pop(entry); + const d = entry[0], + v = entry[1]; + if (d > distance[v]) continue; + for (let e = neighbourStart[v]; e < neighbourStart[v + 1]; e++) { + const w = neighbours[e]; + if (!K[w]) continue; + const next = + d + + Math.hypot( + position[w * 3] - position[v * 3], + position[w * 3 + 1] - position[v * 3 + 1], + position[w * 3 + 2] - position[v * 3 + 2], + ); + if (next >= distance[w] || next > length) continue; + distance[w] = next; + heap.push(next, w, 0, 0); + } + } + const weight = new Float64Array(n); + for (let v = 0; v < n; v++) { + if (!K[v]) continue; + const x = Math.min(1, distance[v] / length); + weight[v] = x * x * (3 - 2 * x); + } + return weight; +} + +/** + * The field the cut follows: for each vertex squared against two planes whose target lies within + * `band` of their corner, positive where it lands on its first plane and negative on its second. + * Neighbours' first planes are matched so the sign means the same along a run; a vertex beside one on + * another pair of planes is left out, so the cut never joins two edges. + */ +function cornerField( + topology: RefineTopology, + position: Float64Array, + normal: Float64Array, + solve: Solve, + band: number, + tolerance: number, +) { + const { K, planes, target, kind } = solve; + const n = K.length; + const field = new Float64Array(n).fill(NaN); + const corner = new Float64Array(3); + for (let v = 0; v < n; v++) { + if (K[v] !== 2) continue; + onCorner(target[v * 3], target[v * 3 + 1], target[v * 3 + 2], planes, v * 12, corner); + if ( + Math.hypot( + corner[0] - target[v * 3], + corner[1] - target[v * 3 + 1], + corner[2] - target[v * 3 + 2], + ) > band + ) + continue; + const b = v * 12; + const px = position[v * 3], + py = position[v * 3 + 1], + pz = position[v * 3 + 2]; + const nx = normal[v * 3], + ny = normal[v * 3 + 1], + nz = normal[v * 3 + 2]; + const sA = planes[b] * px + planes[b + 1] * py + planes[b + 2] * pz - planes[b + 3]; + const sB = planes[b + 4] * px + planes[b + 5] * py + planes[b + 6] * pz - planes[b + 7]; + const cA = planes[b] * nx + planes[b + 1] * ny + planes[b + 2] * nz; + const cB = planes[b + 4] * nx + planes[b + 5] * ny + planes[b + 6] * nz; + // Outside a corner the ray meets the first plane first where this is positive; inside, the + // second, so the inside sign is turned. + field[v] = (sA * cB - sB * cA) * kind[v]; + } + const { neighbourStart, neighbours } = topology; + const swap = (v: number) => { + const first = planes.slice(v * 12, v * 12 + 4); + planes.copyWithin(v * 12, v * 12 + 4, v * 12 + 8); + planes.set(first, v * 12 + 4); + field[v] = -field[v]; + }; + const seen = new Uint8Array(n); + const drop = new Uint8Array(n); + const queue: number[] = []; + for (let seed = 0; seed < n; seed++) { + if (Number.isNaN(field[seed]) || seen[seed]) continue; + seen[seed] = 1; + queue.length = 0; + queue.push(seed); + for (let q = 0; q < queue.length; q++) { + const v = queue[q]; + const p = position.subarray(v * 3, v * 3 + 3); + for (let e = neighbourStart[v]; e < neighbourStart[v + 1]; e++) { + const w = neighbours[e]; + if (Number.isNaN(field[w])) continue; + const same = + matches(planes, v, 0, w, 0, p, tolerance) && matches(planes, v, 1, w, 1, p, tolerance); + const crossed = + !same && + matches(planes, v, 0, w, 1, p, tolerance) && + matches(planes, v, 1, w, 0, p, tolerance); + if ((!same && !crossed) || (seen[w] && crossed)) { + drop[v] = drop[w] = 1; + continue; + } + if (seen[w]) continue; + if (crossed) swap(w); + seen[w] = 1; + queue.push(w); + } + } + } + for (let v = 0; v < n; v++) if (drop[v]) field[v] = NaN; + return field; +} + +/** The nearest point to (x, y, z) on the line where the two planes from `base` meet. */ +function onCorner( + x: number, + y: number, + z: number, + planes: ArrayLike, + base: number, + out: Float64Array, +) { + const b = base; + const sA = planes[b] * x + planes[b + 1] * y + planes[b + 2] * z - planes[b + 3], + sB = planes[b + 4] * x + planes[b + 5] * y + planes[b + 6] * z - planes[b + 7]; + const g = + planes[b] * planes[b + 4] + planes[b + 1] * planes[b + 5] + planes[b + 2] * planes[b + 6]; + const det = 1 - g * g; + const alpha = (sA - g * sB) / det, + beta = (sB - g * sA) / det; + out[0] = x - alpha * planes[b] - beta * planes[b + 4]; + out[1] = y - alpha * planes[b + 1] - beta * planes[b + 5]; + out[2] = z - alpha * planes[b + 2] - beta * planes[b + 6]; +} + +/** + * Moves each mover its weighted share toward its target in `mesh`, halving the moves of the corners + * of any triangle that would face against the triangle it was cut from in `source`, up to `halvings` + * times, then leaving those still at fault where they were. Returns how many moved less. + */ +function moveHoldingFolds( + source: RefineMesh, + mesh: RefineMesh, + topology: RefineTopology, + children: Map, + movers: number[], + solve: Solve, + weight: Float64Array, +) { + if (!movers.length) return 0; + const sourceTri = weldedTriangles(source); + const parent = new Int32Array(mesh.triangleCount); + for (let t = 0; t < mesh.triangleCount; t++) parent[t] = t; + for (const [t, kids] of children) for (const kid of kids) parent[kid] = t; + const p0 = source.position; + const reference = (t: number, out: Float64Array) => { + const s = parent[t]; + cross(p0, sourceTri[s * 3], sourceTri[s * 3 + 1], sourceTri[s * 3 + 2], out); + }; + const corner = (t: number, k: number) => mesh.weldOf[mesh.corners[t * 3 + k]]; + const start = new Float64Array(movers.length * 3); + movers.forEach((v, i) => start.set(mesh.position.subarray(v * 3, v * 3 + 3), i * 3)); + const share = new Float64Array(movers.length).fill(1); + const index = new Map(); + movers.forEach((v, i) => index.set(v, i)); + const place = () => + movers.forEach((v, i) => { + for (let a = 0; a < 3; a++) { + const from = start[i * 3 + a]; + mesh.position[v * 3 + a] = from + share[i] * weight[v] * (solve.target[v * 3 + a] - from); + } + }); + const was = new Float64Array(3), + now = new Float64Array(3); + const flagged = new Set(); + const reduced = new Uint8Array(movers.length); + for (let round = 0; round <= halvings; round++) { + place(); + flagged.clear(); + for (const v of movers) + for (let e = topology.triangleStart[v]; e < topology.triangleStart[v + 1]; e++) { + const t = topology.trianglesOf[e]; + reference(t, was); + cross(mesh.position, corner(t, 0), corner(t, 1), corner(t, 2), now); + if (was[0] * now[0] + was[1] * now[1] + was[2] * now[2] > 0) continue; + for (let k = 0; k < 3; k++) { + const i = index.get(corner(t, k as 0 | 1 | 2)); + if (i !== undefined) flagged.add(i); + } + } + if (!flagged.size) break; + for (const i of flagged) { + reduced[i] = 1; + share[i] = round === halvings ? 0 : share[i] / 2; + } + if (round === halvings) place(); + } + for (const v of movers) + moveVertex(mesh, v, mesh.position[v * 3], mesh.position[v * 3 + 1], mesh.position[v * 3 + 2]); + let held = 0; + for (let i = 0; i < movers.length; i++) held += reduced[i]; + return held; +} + +function cross(p: Float64Array, a: number, b: number, c: number, out: Float64Array) { + const ux = p[b * 3] - p[a * 3], + uy = p[b * 3 + 1] - p[a * 3 + 1], + uz = p[b * 3 + 2] - p[a * 3 + 2]; + const vx = p[c * 3] - p[a * 3], + vy = p[c * 3 + 1] - p[a * 3 + 1], + vz = p[c * 3 + 2] - p[a * 3 + 2]; + out[0] = uy * vz - uz * vy; + out[1] = uz * vx - ux * vz; + out[2] = ux * vy - uy * vx; +} + +const dot = (x: Float64Array, i: number, y: Float64Array, j: number) => + x[i * 3] * y[j * 3] + x[i * 3 + 1] * y[j * 3 + 1] + x[i * 3 + 2] * y[j * 3 + 2]; diff --git a/src/core/store.ts b/src/core/store.ts index 268594e..4106138 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -83,6 +83,7 @@ import { import type { FreeTransformMode, TransformAxis, TransformPatch } from './free-transform'; import type { GuidePoint } from './refine-band'; import type { RefineBrush } from './refine-brush'; +import type { CleanResult, CleanSettings } from './refine-clean'; import type { EdgeCurve, GuideJoint, GuideKind } from './refine-curve'; import type { RefineProposal } from './refine-detect'; import type { @@ -97,6 +98,7 @@ import { type RefineMesh, cloneRefineMesh, foldedTriangles, + moveVertex, trimRefineMesh, writeRefinedGeometry, } from './refine-mesh'; @@ -417,7 +419,7 @@ interface WarpRecovery { session: WarpSession; } -export type RefineMode = 'edge' | 'region' | 'brush' | 'detect'; +export type RefineMode = 'edge' | 'region' | 'brush' | 'detect' | 'clean'; type DistributiveOmit = T extends unknown ? Omit : never; export interface RefineFeature { id: string; @@ -512,6 +514,7 @@ export interface RefineSession { region: Omit; brush: { kind: RefineBrush; strength: number }; detect: { where: 'part' | 'painted'; sensitivity: number; minLength: number; running: boolean }; + clean: CleanSettings & { where: 'part' | 'painted'; running: boolean }; /** Triangles of the working surface that the last accept folded over. */ folds: Uint32Array; /** Triangles of the working surface that the last accept's cuts left straddling an edge. */ @@ -740,6 +743,7 @@ interface EditorState { ) => void; setRefineBrush: (options: Partial) => void; setRefineDetect: (options: Partial>) => void; + setRefineClean: (options: Partial>) => void; /** Adds a point to the guide being drawn, starting one if none is selected. `close` is set when the point is the path's first point. */ addRefinePoint: (point: GuidePoint, close?: boolean) => void; /** `begin` starts a new undo step for a drag; moves without it extend the current drag. */ @@ -807,6 +811,9 @@ interface EditorState { endRefineDrag: () => void; detectRefine: () => Promise; cancelRefineDetect: () => void; + /** Cleans the whole working surface or its painted area as one session step. */ + cleanRefine: () => Promise; + cancelRefineClean: () => void; setRefineBrushRadius: (radius: number) => void; setOperation: (patch: Partial) => void; resetPicks: () => void; @@ -3718,7 +3725,7 @@ export const useEditor = create((set, get) => ({ // Without a cut, triangle t is still the source's, so its tree only needs new bounds. if (mesh.corners === refine.start?.mesh.corners) refitWarpTree(refine.source, geometry); const refined: Part = { ...part, geometry, source: `Refine · ${part.source}` }; - const { mode, edge, region, brush, detect } = refine; + const { mode, edge, region, brush, detect, clean } = refine; const next: RefineSession = { ...newRefineSession(refined, state.sceneEpoch), mode, @@ -3726,6 +3733,7 @@ export const useEditor = create((set, get) => ({ region, brush, detect: { ...detect, running: false }, + clean: { ...clean, running: false }, }; disposeRefinePreview(refine.preview); const build = refineBuild(); @@ -3863,6 +3871,16 @@ export const useEditor = create((set, get) => ({ }, }); }, + setRefineClean: (options) => { + const { refine } = get(); + if (refine) + set({ + refine: { + ...refine, + clean: { ...refine.clean, ...options, running: refine.clean.running }, + }, + }); + }, addRefinePoint: (placed, close = false) => { const refine = readyRefine(); if (!refine || refine.mode !== 'edge') return; @@ -4601,6 +4619,122 @@ export const useEditor = create((set, get) => ({ scheduleRefineDraft(); }, cancelRefineDetect: () => refineDetect?.abort(), + cleanRefine: async () => { + const refine = readyRefine(); + if (!refine || refine.clean.running) return; + const { where, smooth, sharpen, depth, square, size } = refine.clean; + if (where === 'painted' && !refine.triangles.length) return; + const model = refine.model!; + const controller = new AbortController(); + refineJobs.add(controller); + refineClean = controller; + const taskId = startTask({ + title: cleanTitle, + progress: 0, + notify: false, + cancel: () => controller.abort(), + }); + set({ refine: { ...refine, clean: { ...refine.clean, running: true } } }); + let result: CleanResult | null = null; + let failure: unknown = null; + try { + result = await refineCode!.job.cleanRefineJob( + model, + { + smooth, + sharpen, + depth, + square, + size, + triangles: where === 'painted' ? Uint32Array.from(refine.triangles) : null, + }, + controller.signal, + (progress) => updateTask(taskId, { progress }), + ); + } catch (error) { + failure = error; + } + refineJobs.delete(controller); + if (refineClean === controller) refineClean = null; + // Checked here, just before publishing: a cancel may come after the job has replied. + const current = get().refine; + const clean = current?.id === refine.id ? { ...current.clean, running: false } : null; + if (failure !== null && !controller.signal.aborted) { + failTask(taskId, failure instanceof Error ? failure.message : String(failure)); + if (clean) set({ refine: { ...current!, clean } }); + return; + } + if (!result || !clean || controller.signal.aborted) { + cancelTask(taskId); + if (clean) set({ refine: { ...current!, clean } }); + return; + } + set({ refine: { ...current!, clean } }); + if (current!.model !== model || readyRefine() !== get().refine) { + cancelTask(taskId); + get().notify('The surface changed, so cleaning was stopped.', 'info'); + return; + } + completeTask(taskId); + if (!result.moved.length && !result.mesh) { + get().notify( + square > 0 && !result.squared + ? noSquareNotice + : 'These settings leave the surface as it is.', + 'info', + ); + return; + } + // A stroke or drag under way began on the surface this replaces. + discardRefineStroke(); + const latest = get().refine!; + if (result.mesh) { + // Square cut the surface: paint, regions and marked folds follow each split triangle into + // the triangles it became. + const mesh = result.mesh; + const children = new Map(); + for (let i = 0; i < result.split.length; i += 2) { + const child = result.split[i], + parent = result.split[i + 1]; + children.set(parent, [...(children.get(parent) ?? [parent]), child]); + } + const remap = (t: Uint32Array) => refineCode!.cut.remapTriangles(t, children); + commitRefine({ + model: { ...model, mesh, topology: result.topology ?? model.topology }, + features: latest.features.map((f) => + refreshSketchTriangles( + f.feature.type === 'region' + ? { + ...f, + feature: { + type: 'region', + input: { ...f.feature.input, triangles: remap(f.feature.input.triangles) }, + }, + } + : f, + mesh, + ), + ), + triangles: [...remap(Uint32Array.from(latest.triangles))], + folds: remap(latest.folds), + skipped: remap(latest.skipped), + }); + } else { + const { moved, position, triangles, corners, topology } = result; + // Triangles turned to follow a sharpened edge take new corners and the topology made for them. + const mesh = cloneRefineMesh(model.mesh, triangles.length > 0); + triangles.forEach((t, i) => mesh.corners.set(corners.subarray(i * 3, i * 3 + 3), t * 3)); + for (let i = 0; i < moved.length; i++) + moveVertex(mesh, moved[i], position[i * 3], position[i * 3 + 1], position[i * 3 + 2]); + commitRefine({ + model: { ...model, mesh, topology: topology ?? model.topology }, + features: latest.features.map((f) => refreshSketchTriangles(f, mesh)), + }); + } + if (square > 0 && !result.squared) get().notify(noSquareNotice, 'info'); + else if (result.held) get().notify(heldNotice(result.held), 'info'); + }, + cancelRefineClean: () => refineClean?.abort(), setRefineBrushRadius: (radius) => set((state) => state.refine && Number.isFinite(radius) @@ -6103,6 +6237,16 @@ const newRefineSession = (part: Part, epoch: number): RefineSession => ({ brush: { kind: 'smooth', strength: 0.5 }, // detectDefaults, written out so the store does not load detection before a session needs it. detect: { where: 'part', sensitivity: 0.5, minLength: 1.5, running: false }, + // cleanDefaults, written out for the same reason. + clean: { + where: 'part', + smooth: 0.5, + sharpen: 0.5, + depth: 1, + square: 0, + size: null, + running: false, + }, folds: noFolds, skipped: noFolds, drawing: false, @@ -6373,6 +6517,15 @@ export function commitRefine(next: Partial) { /** The detection running in the session, which Cancel aborts. */ let refineDetect: AbortController | null = null; +/** The clean running in the session, which Cancel aborts. */ +let refineClean: AbortController | null = null; +/** The activity title of a clean, which the panel finds its progress by. */ +export const cleanTitle = 'Cleaning the surface'; +/** Said when Square found nothing to rebuild. */ +export const noSquareNotice = 'No rounded edge between faces at about 90° was found to square.'; +/** Said when a clean kept some vertices short of where it would have moved them. */ +export const heldNotice = (n: number) => + `${n === 1 ? '1 vertex' : `${n} vertices`} moved less so no triangle folds over.`; /** The point last dragged and the step its drag recorded, so a drag is one step. */ let refineDrag: { @@ -6461,6 +6614,7 @@ function releaseRefineState() { refineStroke = null; refineDrag = null; refineDetect = null; + refineClean = null; builtDraft = null; cancelRefineDraft(); clearRefineRest(); @@ -6473,6 +6627,7 @@ export const heldRefineState = () => refineStroke && 'stroke', refineDrag && 'drag', refineDetect && 'detection', + refineClean && 'clean', draftFrame && 'frame', draftRest && 'rest', ].filter(Boolean); @@ -7313,11 +7468,12 @@ export function refineBrushRadius(state: Pick) => state.tool === 'refine' && (state.refine?.mode === 'region' || - (state.refine?.mode === 'detect' && state.refine.detect.where === 'painted')); + (state.refine?.mode === 'detect' && state.refine.detect.where === 'painted') || + (state.refine?.mode === 'clean' && state.refine.clean.where === 'painted')); /** Whether a press on the part makes a brush stroke. */ export const brushingRefine = (state: Pick) => diff --git a/src/docs/assembly-guides.ts b/src/docs/assembly-guides.ts index 650c492..aaf7246 100644 --- a/src/docs/assembly-guides.ts +++ b/src/docs/assembly-guides.ts @@ -521,11 +521,11 @@ export const assemblyGuides: DocArticle[] = [ id: 'refine', title: 'Refine edges and surfaces on a scan', description: - 'Rebuild softened edges, clean up painted areas, and review proposed fixes on a scanned part.', + 'Rebuild softened edges, clean up painted areas or the whole part, and review proposed fixes on a scanned part.', group: 'Build & assemble', icon: 'zap', intro: - 'A scan of a small part often rounds off edges that should be sharp and leaves ripples on faces that should be flat or round. Refine rebuilds an edge from a guide you lay along it, treats a painted area so it is smooth, flat or a true shape and can keep rivets and other detail, and offers brushes for local fixes. Review a selected guide or region on the part, accept the ones you want, and choose Apply to save the session’s working surface to the part.', + 'A scan of a small part often rounds off edges that should be sharp and leaves ripples on faces that should be flat or round. Refine rebuilds an edge from a guide you lay along it, treats a painted area so it is smooth, flat or a true shape and can keep rivets and other detail, offers brushes for local fixes, and cleans the whole part at once, the way sharpening cleans up a photo. Review a selected guide or region on the part, accept the ones you want, and choose Apply to save the session’s working surface to the part.', image: referenceImages.refine, sections: [ { @@ -537,7 +537,7 @@ export const assemblyGuides: DocArticle[] = [ steps: [ 'Select one visible, unlocked part and press E, or choose Refine (the sparkles button) in the toolbar.', 'Wait while the panel shows Preparing the surface…', - 'Choose a mode: Edge, Region, Brush, or Detect.', + 'Choose a mode: Edge, Region, Brush, Detect, or Clean.', ], note: { title: 'What the settings change', @@ -738,12 +738,54 @@ export const assemblyGuides: DocArticle[] = [ text: 'Select a pending proposal to preview its fit on the part. With more than 8 pending proposals selected, the preview is off. In Detect the panel says Preview is off while more than 8 are selected. Accepting still works. Accept selected keeps the changes that fit in the session’s working surface as one undo step. Each press of Accept or Accept selected shows at most one notice. Apply saves the working surface to the part. A completed search replaces untouched pending proposals from Detect. It keeps accepted features, edited proposals and guides or regions you made. It skips edges and regions those features already mostly cover.', }, }, + { + id: 'clean', + title: 'Clean and sharpen a scan', + paragraphs: [ + 'Clean treats the whole part, or a painted area, in one step, the way sharpening treats a photo: it removes scan noise, crisps softened edges, and makes recessed and raised detail deeper. Square goes further on parts built from flat faces: it rebuilds rounded edges where faces meet at about 90° as sharp corners.', + ], + steps: [ + 'In Clean mode, choose Whole part or Painted area under Area. For Painted area, paint where to clean.', + 'Set Smooth, Sharpen, Depth, and Square. Size is automatic; turn off Automatic size to set it in mm.', + 'Choose Clean surface. Progress shows in the panel, and the Cancel button below it stops the clean.', + 'Compare the result with Ctrl/⌘ + Z and Ctrl/⌘ + Shift + Z. To try other settings, undo, change them, and clean again. Choose Apply to keep the result.', + ], + table: { + headers: ['Setting', 'Result'], + rows: [ + [ + 'Smooth', + 'Removes noise and small unevenness while keeping edges. Higher values also soften gentle edges and remove more small detail.', + ], + [ + 'Sharpen', + 'Narrows softened edges and corners so they turn more crisply. It also brings out any ripple that Smooth leaves.', + ], + [ + 'Depth', + 'Makes recesses deeper and raised detail higher, up to Size across. 100% doubles their relief; detail within the scan’s noise is left as it is.', + ], + [ + 'Square', + 'Rebuilds rounded edges where two flat faces meet at about 90°, outside and inside, as sharp corners, and box corners where three meet. The edge is cut into the mesh, so it runs along triangle edges. 100% makes the corner sharp; lower values move the rounding part of the way. It is off by default.', + ], + [ + 'Size', + 'The widest feature Depth deepens and the widest rounding Square rebuilds. Raise it for larger recesses, such as an eye socket or a panel line, or for wider roundings.', + ], + ], + }, + note: { + title: 'What Clean keeps', + text: 'A painted area eases into the surface around it, and nothing outside it moves. Edges the tool has rebuilt and open borders stay where they are. Where moving a vertex would fold a triangle over, it moves less, and the app says how many vertices it held back. Along an edge it sharpens, Clean can turn triangles so the edge runs along them instead of zigzagging across them. Without Square the number of triangles stays the same; Square adds triangles along the edges it cuts, keeps those edges sharp in later steps as it keeps rebuilt edges, and the app says when it finds no rounded corner to square. A clean is one session undo step. On a very large part it can take a while: a 700,000-triangle scan takes several seconds, and nearly twice as long with Square.', + }, + }, { id: 'apply-or-cancel', title: 'Apply or cancel', paragraphs: [ - 'While the tool is open, Ctrl/⌘ + Z and Ctrl/⌘ + Shift + Z undo and redo session steps, such as placing or dragging guide points, painting, accepting, and strokes that change the surface. These shortcuts use session history first. Changing a setting is not a step. Pressing Esc, or switching to another window, during a brush stroke or a drag of a guide point discards that stroke or drag, leaving nothing to undo.', - 'Apply saves the working surface to the part as one undo step in the scene. It becomes available once you have accepted a feature or made a stroke that changed the surface. Pins, anchors, joints, and other parts are not modified, and Refine stays open so you can continue.', + 'While the tool is open, Ctrl/⌘ + Z and Ctrl/⌘ + Shift + Z undo and redo session steps, such as placing or dragging guide points, painting, accepting, strokes that change the surface, and cleaning. These shortcuts use session history first. Changing a setting is not a step. Pressing Esc, or switching to another window, during a brush stroke or a drag of a guide point discards that stroke or drag, leaving nothing to undo.', + 'Apply saves the working surface to the part as one undo step in the scene. It becomes available once you have accepted a feature, made a stroke that changed the surface, or cleaned it. Pins, anchors, joints, and other parts are not modified, and Refine stays open so you can continue.', 'Cancel discards the work you have not applied and leaves the tool. When Esc has nothing else to end, such as a stroke, a drag, an unfinished guide, or a waiting Crease guide, it returns to Select, unless the session holds work. Then Esc stays in Refine and the status line shows Apply to keep your changes, or Cancel to discard them. Leaving Refine another way, such as choosing another tool, discards this session. If you leave that way while the session holds work you made, such as accepted changes, guides you drew, proposals you edited, or paint, the app shows Refinement discarded. Use Apply to keep it. Cancel shows no notice. Changes you applied earlier stay on the part.', ], }, @@ -751,6 +793,8 @@ export const assemblyGuides: DocArticle[] = [ id: 'good-results', title: 'Getting good results', bullets: [ + 'Clean gives the most on soft, noisy scans. Start from the default settings and raise one setting at a time: high Sharpen and Depth together can make a noisy area rough.', + 'Use Square on parts built from flat faces, or paint the area to square. On rounded shapes such as faces, skulls or cables it can cut ledges where faces happen to meet near 90°. Where a face is only a few triangles wide, the scan has too little to fit, and Square leaves the edge rounded or eases off along it.', 'Restore edges before smoothing or flattening across them. Smoothing or flattening across an edge that has not been rebuilt can soften it further; rebuilt edges are held.', 'On a plate with rivets, use a painted region with Flatten and Keep detail rather than the Flatten brush. The brush can flatten rivets, and clipping one can leave a step at its rim.', 'A guide needs surface on both sides to work with. Lay it along the rounded edge itself or close beside it. A line laid along an edge that clearly curves follows the curve instead of cutting straight across it. If the tool says no edge was found, move the guide onto the rounding or change Width. A lip or rib rounded right over, with no flat top left, has no edge for the tool to find.', diff --git a/src/docs/changelog.ts b/src/docs/changelog.ts index 8c5a2aa..74bcfa1 100644 --- a/src/docs/changelog.ts +++ b/src/docs/changelog.ts @@ -19,6 +19,22 @@ export interface Release { // Newest first. Each title must be unique: it names the release's link. export const releases: Release[] = [ + { + date: '2026-11-25', + title: 'Clean and sharpen scans', + changes: [ + { + kind: 'new', + text: 'Refine has a Clean mode that treats the whole part, or a painted area, the way sharpening treats a photo. Smooth removes scan noise while keeping edges, Sharpen makes softened edges turn more crisply, and Depth makes recessed and raised detail deeper, up to a Size you can set.', + guide: 'refine', + }, + { + kind: 'new', + text: 'Clean can square corners: Square rebuilds rounded edges where faces meet at about 90°, outside and inside, as sharp corners, and box corners where three faces meet.', + guide: 'refine', + }, + ], + }, { date: '2026-11-24', title: 'Crease finds the edge', diff --git a/src/styles.css b/src/styles.css index e85dfc2..13241d3 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6703,7 +6703,7 @@ optgroup { } /* Refine: Warp's controls, with four modes, a shared label column and selects. */ .display-segmented.refine-modes { - grid-template-columns: repeat(4, minmax(0, 1fr)); + grid-template-columns: repeat(5, minmax(0, 1fr)); } .display-segmented.refine-pair { grid-template-columns: repeat(2, minmax(0, 1fr)); diff --git a/tests/e2e/refine.spec.ts b/tests/e2e/refine.spec.ts index bd838e0..8b84b9b 100644 --- a/tests/e2e/refine.spec.ts +++ b/tests/e2e/refine.spec.ts @@ -1693,3 +1693,85 @@ test('a Parallel constraint holds through a drag, and its icon deletes it', asyn await iconMenu.getByRole('menuitem', { name: 'Delete constraint' }).click(); await expect.poll(async () => (await parallelism())?.kinds).toEqual([]); }); + +test('cleans the whole part, steps back, then cleans a painted area and applies', async ({ + page, +}) => { + await openRefine(page, { scene: plateFixture, view: '7' }); + const original = await partMesh(page); + await page.getByRole('radio', { name: 'Clean', exact: true }).click(); + const clean = page.getByRole('button', { name: 'Clean surface' }); + const setting = async (name: string, percent: number) => { + const field = page.getByRole('spinbutton', { name, exact: true }); + await field.fill(String(percent)); + await field.press('Enter'); + }; + const run = async () => { + await clean.click(); + await expect.poll(() => inStore(page, (s) => s.refine!.clean.running)).toBe(false); + }; + const before = await rivetMeasure(page); + // Smooth alone evens out the plate's ripple. + await setting('Sharpen', 0); + await setting('Depth', 0); + await expect + .poll(() => inStore(page, (s) => s.refine!.clean)) + .toMatchObject({ smooth: 0.5, sharpen: 0, depth: 0 }); + await run(); + expect(await steps(page)).toEqual({ undo: 1, redo: 0 }); + expect((await rivetMeasure(page)).spread).toBeLessThan(before.spread / 2); + await undo(page); + expect(await steps(page)).toEqual({ undo: 0, redo: 1 }); + expect(await rivetMeasure(page)).toEqual(before); + // Depth alone raises the rivet off the plate. + await setting('Smooth', 0); + await setting('Depth', 150); + await expect.poll(() => inStore(page, (s) => s.refine!.clean.depth)).toBe(1.5); + await run(); + expect((await rivetMeasure(page)).height).toBeGreaterThan(1.1 * before.height); + await undo(page); + + await page.getByRole('radio', { name: 'Painted area', exact: true }).click(); + await expect(clean).toBeDisabled(); + await brushRadius(page, 0.5); + await paintRivet(page); + await expect(clean).toBeEnabled(); + // Each paint stroke is a step of its own; the clean is one more. + const painted = (await steps(page)).undo; + await run(); + expect(await steps(page)).toEqual({ undo: painted + 1, redo: 0 }); + expect((await rivetMeasure(page)).height).toBeGreaterThan(1.1 * before.height); + await page.getByRole('button', { name: 'Apply' }).click(); + await expect.poll(async () => (await partMesh(page)).sum).not.toBe(original.sum); + expect((await partMesh(page)).source).toBe(`Refine · ${original.source}`); +}); + +test('squares the rounded edges of a plate and applies', async ({ page }) => { + await openRefine(page, { scene: plateFixture, view: '7' }); + const original = await partMesh(page); + await page.getByRole('radio', { name: 'Clean', exact: true }).click(); + const setting = async (name: string, percent: number) => { + const field = page.getByRole('spinbutton', { name, exact: true }); + await field.fill(String(percent)); + await field.press('Enter'); + }; + const triangles = () => inStore(page, (s) => s.refine!.model!.mesh.triangleCount); + const before = await triangles(); + await setting('Sharpen', 0); + await setting('Depth', 0); + await setting('Square', 100); + await expect + .poll(() => inStore(page, (s) => s.refine!.clean)) + .toMatchObject({ smooth: 0.5, sharpen: 0, depth: 0, square: 1 }); + await page.getByRole('button', { name: 'Clean surface' }).click(); + await expect.poll(() => inStore(page, (s) => s.refine!.clean.running)).toBe(false); + // The rebuilt corners are cut into the surface along their new edges. + expect(await steps(page)).toEqual({ undo: 1, redo: 0 }); + expect(await triangles()).toBeGreaterThan(before); + await undo(page); + expect(await triangles()).toBe(before); + await redo(page); + await expect.poll(triangles).toBeGreaterThan(before); + await page.getByRole('button', { name: 'Apply' }).click(); + await expect.poll(async () => (await partMesh(page)).sum).not.toBe(original.sum); +}); diff --git a/tests/unit/refine-clean.test.ts b/tests/unit/refine-clean.test.ts new file mode 100644 index 0000000..9b76d4d --- /dev/null +++ b/tests/unit/refine-clean.test.ts @@ -0,0 +1,549 @@ +import { describe, expect, it } from 'vitest'; +import { Matrix4 } from 'three'; +import { + type CleanResult, + type CleanSettings, + autoCleanSize, + cleanDefaults, + cleanPlan, + cleanSurface, + maxCleanDepth, + maxCleanSize, + minCleanSize, +} from '../../src/core/refine-clean'; +import { cleanRefineJob } from '../../src/core/refine-job'; +import { type RefineMesh, buildTopology, weldedCorner } from '../../src/core/refine-mesh'; +import { autoRule, cleanDepthMax, cleanSizeRange } from '../../src/components/refine-panel'; +import { closedMesh, modelOf } from '../helpers/refine'; +import { heightField, rippledSphere, rivetedPlate, softBox, softStep } from '../helpers/soft-edges'; + +type Model = ReturnType; +const off: CleanSettings = { smooth: 0, sharpen: 0, depth: 0, square: 0, size: null }; + +/** The model's mesh with a clean applied: new positions and corners, and the result. */ +function cleaned( + model: Model, + settings: Partial, + triangles: Uint32Array | null = null, +) { + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + ...settings, + triangles, + }); + const position = model.mesh.position.slice(); + result.moved.forEach((v, i) => { + for (let a = 0; a < 3; a++) position[v * 3 + a] = result.position[i * 3 + a]; + }); + const corners = model.mesh.corners.slice(); + result.triangles.forEach((t, i) => corners.set(result.corners.subarray(i * 3, i * 3 + 3), t * 3)); + const mesh: RefineMesh = { ...model.mesh, position, corners }; + return { position, corners, mesh, result }; +} + +/** Each rivet's height over the plate top (y = 0.5), and the RMS height of the plate far from them. */ +function plate(position: Float64Array, rivets: { x: number; z: number }[], top = 0.5, yScale = 1) { + const peaks = rivets.map(() => -Infinity); + let squares = 0, + count = 0; + for (let v = 0; v < position.length / 3; v++) { + const x = position[v * 3], + y = position[v * 3 + 1] / yScale, + z = position[v * 3 + 2]; + if (y < top - 0.2) continue; + rivets.forEach((r, i) => { + if (Math.hypot(x - r.x, z - r.z) < 0.15) peaks[i] = Math.max(peaks[i], y - top); + }); + if (rivets.every((r) => Math.hypot(x - r.x, z - r.z) > 0.8) && Math.abs(x) < 2.6) + if (Math.abs(z) < 1.6) { + squares += (y - top) ** 2; + count++; + } + } + return { peak: Math.min(...peaks), roughness: Math.sqrt(squares / count) }; +} + +/** Width across x of the part of a step from y 0 to `height` that lies between 10 and 90 %. */ +function stepWidth(position: Float64Array, height: number) { + const xs: number[] = []; + for (let v = 0; v < position.length / 3; v++) { + const x = position[v * 3], + y = position[v * 3 + 1], + z = position[v * 3 + 2]; + if (Math.abs(z) < 1 && y > 0.1 * height && y < 0.9 * height) xs.push(x); + } + xs.sort((a, b) => a - b); + return xs[Math.floor(xs.length * 0.95)] - xs[Math.floor(xs.length * 0.05)]; +} + +/** A triangle's normal times twice its area. */ +function cross(mesh: RefineMesh, t: number) { + const p = mesh.position; + const [a, b, c] = [0, 1, 2].map((k) => weldedCorner(mesh, t, k as 0 | 1 | 2) * 3); + const u = [0, 1, 2].map((i) => p[b + i] - p[a + i]), + w = [0, 1, 2].map((i) => p[c + i] - p[a + i]); + return [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]; +} + +/** + * Triangles of `after` facing away from the source surface around them: the sum of the source + * normals of the triangles around their corners. + */ +function inverted(model: Model, after: RefineMesh) { + const { mesh, topology } = model; + const source = Array.from({ length: mesh.triangleCount }, (_, t) => cross(mesh, t)); + let count = 0; + for (let t = 0; t < after.triangleCount; t++) { + const reference = [0, 0, 0]; + for (let k = 0; k < 3; k++) { + const v = weldedCorner(after, t, k as 0 | 1 | 2); + for (let i = topology.triangleStart[v]; i < topology.triangleStart[v + 1]; i++) + source[topology.trianglesOf[i]].forEach((x, a) => (reference[a] += x)); + } + const n = cross(after, t); + if (n[0] * reference[0] + n[1] * reference[1] + n[2] * reference[2] <= 0) count++; + } + return count; +} + +/** Sum over interior edges of length times the angle between their two triangles' normals. */ +function bending(mesh: RefineMesh) { + const first = new Map(); + let sum = 0; + for (let t = 0; t < mesh.triangleCount; t++) + for (let k = 0; k < 3; k++) { + const a = weldedCorner(mesh, t, k as 0 | 1 | 2), + b = weldedCorner(mesh, t, ((k + 1) % 3) as 0 | 1 | 2); + const key = a < b ? `${a},${b}` : `${b},${a}`; + const other = first.get(key); + if (other === undefined) { + first.set(key, t); + continue; + } + const [m, n] = [cross(mesh, t), cross(mesh, other)]; + const cos = (m[0] * n[0] + m[1] * n[1] + m[2] * n[2]) / (Math.hypot(...m) * Math.hypot(...n)); + const p = mesh.position; + sum += + Math.hypot(p[a * 3] - p[b * 3], p[a * 3 + 1] - p[b * 3 + 1], p[a * 3 + 2] - p[b * 3 + 2]) * + Math.acos(Math.max(-1, Math.min(1, cos))); + } + return sum; +} + +describe('refine clean', () => { + it('removes noise from a flat face without changing the part', () => { + const { geometry, rivets } = rivetedPlate({ noise: 0.01, ripple: 0 }); + const model = modelOf(geometry); + const before = plate(model.mesh.position, rivets); + const { position } = cleaned(model, { smooth: 0.5 }); + const after = plate(position, rivets); + expect(after.roughness).toBeLessThan(0.4 * before.roughness); + expect(after.peak).toBeGreaterThan(0.85 * before.peak); + let moved = 0; + for (let i = 0; i < position.length; i++) + moved = Math.max(moved, Math.abs(position[i] - model.mesh.position[i])); + expect(moved).toBeLessThan(0.1); + }); + + it('narrows a softened edge', () => { + const height = 0.15; + const model = modelOf( + heightField(1.5, (x) => (height * (1 + Math.tanh(x / 0.1))) / 2, { noise: 0.003, ripple: 0 }), + ); + const before = stepWidth(model.mesh.position, height); + const half = stepWidth(cleaned(model, { sharpen: 0.5 }).position, height); + const full = stepWidth(cleaned(model, { sharpen: 1 }).position, height); + expect(half).toBeLessThan(before); + expect(full).toBeLessThan(0.85 * before); + expect(full).toBeLessThan(half); + // The defaults sharpen it on balance, though Smooth alone softens a gentle edge. + expect(stepWidth(cleaned(model, cleanDefaults).position, height)).toBeLessThan(before); + }); + + it('deepens relief up to Size, more for a larger Size', () => { + const { geometry, rivets } = rivetedPlate({ ripple: 0 }); + const model = modelOf(geometry); + const before = plate(model.mesh.position, rivets); + const auto = cleaned(model, { depth: 1 }); + expect(auto.result.size).toBeCloseTo(autoCleanSize(model.step), 12); + const deeper = plate(auto.position, rivets); + expect(deeper.peak).toBeGreaterThan(1.1 * before.peak); + const wide = plate(cleaned(model, { depth: 1, size: 1 }).position, rivets); + expect(wide.peak).toBeGreaterThan(deeper.peak); + // The plate around the rivets stays where it was. + expect(deeper.roughness).toBeLessThan(before.roughness + 0.003); + expect(plate(cleaned(model, { depth: 2 }).position, rivets).peak).toBeGreaterThan(deeper.peak); + }); + + it('cleans a mirrored, stretched part in world space', () => { + const { geometry, rivets } = rivetedPlate({ ripple: 0 }); + const model = modelOf(geometry, new Matrix4().makeScale(-1, 2, 1)); + const flipped = rivets.map((r) => ({ x: -r.x, z: r.z })); + const before = plate(model.mesh.position, flipped, 0.5, 2); + const { position, mesh } = cleaned(model, { ...cleanDefaults, depth: 1 }); + expect(plate(position, flipped, 0.5, 2).peak).toBeGreaterThan(1.05 * before.peak); + expect(inverted(model, mesh)).toBe(0); + }); + + it('turns no triangle over at the strongest settings', () => { + for (const geometry of [rivetedPlate().geometry, softBox([2, 1.5, 1], 0.2)]) { + const model = modelOf(geometry); + const { mesh } = cleaned(model, { + smooth: 1, + sharpen: 1, + depth: maxCleanDepth, + size: maxCleanSize, + }); + expect(inverted(model, mesh)).toBe(0); + expect(closedMesh(mesh)).toBe(true); + } + }); + + it('moves only the painted area, easing in from its border', () => { + const { geometry } = rivetedPlate({ noise: 0.01, ripple: 0 }); + const model = modelOf(geometry); + const { mesh } = model; + const painted: number[] = []; + for (let t = 0; t < mesh.triangleCount; t++) { + const centre = [0, 1, 2].map( + (a) => + [0, 1, 2].reduce( + (sum, k) => sum + mesh.position[weldedCorner(mesh, t, k as 0 | 1 | 2) * 3 + a], + 0, + ) / 3, + ); + if (centre[1] > 0.45 && Math.hypot(centre[0] + 1, centre[2]) < 0.8) painted.push(t); + } + const inside = new Set(), + border = new Set(); + const paintedSet = new Set(painted); + for (const t of painted) + for (let k = 0; k < 3; k++) inside.add(weldedCorner(mesh, t, k as 0 | 1 | 2)); + for (let t = 0; t < mesh.triangleCount; t++) + if (!paintedSet.has(t)) + for (let k = 0; k < 3; k++) { + const v = weldedCorner(mesh, t, k as 0 | 1 | 2); + if (inside.has(v)) border.add(v); + } + const { position, result } = cleaned( + model, + { ...cleanDefaults, depth: 1 }, + Uint32Array.from(painted), + ); + expect(result.moved.length).toBeGreaterThan(inside.size / 3); + for (const v of result.moved) { + expect(inside.has(v)).toBe(true); + expect(border.has(v)).toBe(false); + } + // Only triangles between moved vertices turn. + const moved = new Set(result.moved); + for (let i = 0; i < result.corners.length; i++) + expect(moved.has(mesh.weldOf[result.corners[i]])).toBe(true); + // Everything else keeps its exact position. + for (let v = 0; v < mesh.weldedCount; v++) + if (!inside.has(v) || border.has(v)) + for (let a = 0; a < 3; a++) expect(position[v * 3 + a]).toBe(mesh.position[v * 3 + a]); + }); + + it('keeps refined-edge and open-border vertices in place', () => { + const model = modelOf(heightField(1, (x, z) => 0.05 * Math.sin(4 * x) * Math.cos(3 * z))); + const { mesh, topology } = model; + const held = new Set(); + for (let v = 0; v < mesh.weldedCount; v += 7) { + mesh.crease[v] = 1; + held.add(v); + } + for (let v = 0; v < mesh.weldedCount; v++) + if ( + topology.triangleStart[v + 1] - topology.triangleStart[v] !== + topology.neighbourStart[v + 1] - topology.neighbourStart[v] + ) + held.add(v); + const { result } = cleaned(model, { ...cleanDefaults, depth: 2 }); + expect(result.moved.length).toBeGreaterThan(0); + for (const v of result.moved) expect(held.has(v)).toBe(false); + }); + + it('turns triangles to follow a sharpened edge, keeping the mesh closed', () => { + for (const indexed of [false, true]) { + const model = modelOf(softBox([2, 1.5, 1], 0.12, { indexed })); + const { mesh, result } = cleaned(model, { smooth: 0.5, sharpen: 1 }); + expect(result.triangles.length).toBeGreaterThan(0); + expect(closedMesh(mesh)).toBe(true); + expect(result.topology).toEqual(buildTopology(mesh)); + expect(inverted(model, mesh)).toBe(0); + // The turned triangles bend the surface less than the old ones at the same positions. + expect(bending(mesh)).toBeLessThan(bending({ ...mesh, corners: model.mesh.corners })); + // Each corner keeps a geometry vertex of its own welded vertex. + const before = new Set(model.mesh.corners); + for (const g of result.corners) expect(before.has(g)).toBe(true); + } + }); + + it('changes nothing when every setting is off', () => { + const model = modelOf(softBox([1, 1, 1], 0.2)); + expect(cleaned(model, off).result.moved).toHaveLength(0); + }); + + it('stops when cancelled', () => { + const model = modelOf(softBox([1, 1, 1], 0.2)); + const controller = new AbortController(); + controller.abort(); + expect(() => + cleanSurface( + model.mesh, + model.topology, + model.noise, + model.step, + { ...cleanDefaults, triangles: null }, + () => {}, + controller.signal, + ), + ).toThrow(expect.objectContaining({ name: 'AbortError' })); + }); + + it('runs as a job the same as in-thread', async () => { + const model = modelOf(softBox([1, 1, 1], 0.2)); + const input = { ...cleanDefaults, triangles: null }; + const direct = cleanSurface(model.mesh, model.topology, model.noise, model.step, input); + const progress: number[] = []; + const job = await cleanRefineJob(model, input, new AbortController().signal, (f) => + progress.push(f), + ); + expect(job.moved).toEqual(direct.moved); + expect(job.position).toEqual(direct.position); + expect(job.corners).toEqual(direct.corners); + expect(job.topology).toEqual(direct.topology); + expect(progress.at(-1)).toBe(1); + expect(progress.every((f, i) => i === 0 || f >= progress[i - 1])).toBe(true); + }); + + it('holds Size to its range and matches the panel', () => { + expect(cleanPlan({ ...cleanDefaults, size: 100 }, 0.06).size).toBe(maxCleanSize); + expect(cleanPlan({ ...cleanDefaults, size: 0.001 }, 0.06).size).toBe(0.06); + expect(cleanPlan({ ...cleanDefaults, size: 0.001 }, 0.01).size).toBe(minCleanSize); + expect(autoRule('size', { step: 0.06, noise: 0.01 })).toBe(autoCleanSize(0.06)); + expect(cleanDepthMax).toBe(maxCleanDepth); + expect(cleanSizeRange).toEqual({ min: minCleanSize, max: maxCleanSize }); + }); +}); + +/** The mesh a clean left, cut or not, with the source triangle each of its triangles came from. */ +function after(model: Model, result: CleanResult) { + if (!result.mesh) { + const { mesh } = cleanedMesh(model, result); + return { mesh, parent: (t: number) => t }; + } + const parents = new Map(); + for (let i = 0; i < result.split.length; i += 2) + parents.set(result.split[i], result.split[i + 1]); + return { mesh: result.mesh, parent: (t: number) => parents.get(t) ?? t }; +} + +function cleanedMesh(model: Model, result: CleanResult) { + const position = model.mesh.position.slice(); + result.moved.forEach((v, i) => { + for (let a = 0; a < 3; a++) position[v * 3 + a] = result.position[i * 3 + a]; + }); + const corners = model.mesh.corners.slice(); + result.triangles.forEach((t, i) => corners.set(result.corners.subarray(i * 3, i * 3 + 3), t * 3)); + return { mesh: { ...model.mesh, position, corners } as RefineMesh }; +} + +/** Triangles that face against the source triangle they came from. */ +function turned(model: Model, result: CleanResult) { + const { mesh, parent } = after(model, result); + let count = 0; + for (let t = 0; t < mesh.triangleCount; t++) { + const was = cross(model.mesh, parent(t)), + now = cross(mesh, t); + if (was[0] * now[0] + was[1] * now[1] + was[2] * now[2] <= 0) count++; + } + return count; +} + +/** The L profile softStep rounds: its distance in x and y from a point, and its corners. */ +const profile = [ + [-2, -1.5], + [2, -1.5], + [2, 0], + [0, 0], + [0, 1.5], + [-2, 1.5], +]; +function fromProfile(x: number, y: number) { + let best = Infinity; + profile.forEach(([ax, ay], i) => { + const [bx, by] = profile[(i + 1) % profile.length]; + const dx = bx - ax, + dy = by - ay; + const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / (dx * dx + dy * dy))); + best = Math.min(best, Math.hypot(x - ax - t * dx, y - ay - t * dy)); + }); + return best; +} + +/** Furthest any vertex in the middle of the extrusion lies from the sharp profile, and how near + * a vertex comes to each of the two given corners. */ +function squareness(mesh: RefineMesh, corners: number[][]) { + let worst = 0; + const nearest = corners.map(() => Infinity); + const p = mesh.position; + for (let v = 0; v < mesh.weldedCount; v++) { + if (Math.abs(p[v * 3 + 2]) > 1) continue; + worst = Math.max(worst, fromProfile(p[v * 3], p[v * 3 + 1])); + corners.forEach(([x, y], i) => { + nearest[i] = Math.min(nearest[i], Math.hypot(p[v * 3] - x, p[v * 3 + 1] - y)); + }); + } + return { worst, nearest }; +} + +describe('refine clean square', () => { + // An outside corner of the L and its one inside corner. + const corners = [ + [2, 0], + [0, 0], + ]; + + it('rebuilds rounded edges outside and inside as sharp corners', () => { + const model = modelOf(softStep(0.3, { ripple: 0 })); + const before = squareness(model.mesh, corners); + expect(before.worst).toBeGreaterThan(0.08); + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + smooth: 0.5, + square: 1, + triangles: null, + }); + expect(result.mesh).not.toBeNull(); + expect(result.squared).toBeGreaterThan(0); + const { mesh } = after(model, result); + expect(mesh.triangleCount).toBeGreaterThan(model.mesh.triangleCount); + const now = squareness(mesh, corners); + expect(now.worst).toBeLessThan(0.015); + for (const [i, distance] of now.nearest.entries()) { + expect(before.nearest[i]).toBeGreaterThan(0.1); + expect(distance).toBeLessThan(0.01); + } + expect(closedMesh(mesh)).toBe(true); + expect(result.topology).toEqual(buildTopology(mesh)); + expect(turned(model, result)).toBe(0); + // The new edges are creases, so later steps hold them and shading keeps them sharp. + let creased = 0; + for (let v = 0; v < mesh.weldedCount; v++) creased += mesh.crease[v]; + expect(creased).toBe(result.squared); + }); + + it('squares a box, edges and corners', () => { + const half = [1.5, 1, 1]; + const model = modelOf(softBox(half as [number, number, number], 0.25, { ripple: 0 })); + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + smooth: 0.5, + square: 1, + triangles: null, + }); + const { mesh } = after(model, result); + const p = mesh.position; + // Distance from the sharp box's surface, and how near a vertex comes to each corner. + let worst = 0; + const nearest = new Array(8).fill(Infinity); + for (let v = 0; v < mesh.weldedCount; v++) { + const q = [0, 1, 2].map((a) => Math.abs(p[v * 3 + a]) - half[a]); + const outside = Math.hypot(...q.map((x) => Math.max(x, 0))); + worst = Math.max(worst, Math.abs(outside + Math.min(Math.max(...q), 0))); + for (let c = 0; c < 8; c++) { + const corner = [0, 1, 2].map((a) => (c & (1 << a) ? half[a] : -half[a])); + nearest[c] = Math.min( + nearest[c], + Math.hypot(...[0, 1, 2].map((a) => p[v * 3 + a] - corner[a])), + ); + } + } + expect(worst).toBeLessThan(0.03); + for (const distance of nearest) expect(distance).toBeLessThan(0.05); + expect(closedMesh(mesh)).toBe(true); + expect(turned(model, result)).toBe(0); + }); + + it('leaves a part with no faces meeting at 90 degrees as it is', () => { + const model = modelOf(rippledSphere(1, { ripple: 0 })); + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + square: 1, + triangles: null, + }); + expect(result.mesh).toBeNull(); + expect(result.squared).toBe(0); + expect(result.moved).toHaveLength(0); + }); + + it('squares a mirrored part the same way', () => { + const model = modelOf(softStep(0.3, { ripple: 0 }), new Matrix4().makeScale(-1, 1, 1)); + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + smooth: 0.5, + square: 1, + triangles: null, + }); + const { mesh } = after(model, result); + const mirrored = { ...mesh, position: mesh.position.map((x, i) => (i % 3 === 0 ? -x : x)) }; + expect(squareness(mirrored, corners).worst).toBeLessThan(0.015); + expect(turned(model, result)).toBe(0); + }); + + it('squares only the painted area', () => { + const model = modelOf(softStep(0.3, { ripple: 0 })); + const { mesh: source } = model; + const painted: number[] = []; + for (let t = 0; t < source.triangleCount; t++) { + let z = 0; + for (let k = 0; k < 3; k++) + z += source.position[weldedCorner(source, t, k as 0 | 1 | 2) * 3 + 2]; + if (z / 3 > 0) painted.push(t); + } + const inPaint = new Set(); + for (const t of painted) + for (let k = 0; k < 3; k++) inPaint.add(weldedCorner(source, t, k as 0 | 1 | 2)); + const result = cleanSurface(model.mesh, model.topology, model.noise, model.step, { + ...off, + smooth: 0.5, + square: 1, + triangles: Uint32Array.from(painted), + }); + const { mesh } = after(model, result); + for (let v = 0; v < source.weldedCount; v++) + if (!inPaint.has(v)) + for (let a = 0; a < 3; a++) + expect(mesh.position[v * 3 + a]).toBe(source.position[v * 3 + a]); + // The painted half is square, the rest as rounded as it was. + let paintedWorst = 0, + restWorst = 0; + for (let v = 0; v < mesh.weldedCount; v++) { + const z = mesh.position[v * 3 + 2]; + const d = fromProfile(mesh.position[v * 3], mesh.position[v * 3 + 1]); + if (z > 0.5 && z < 1.5) paintedWorst = Math.max(paintedWorst, d); + if (z < -0.5 && z > -1.5) restWorst = Math.max(restWorst, d); + } + expect(paintedWorst).toBeLessThan(0.015); + expect(restWorst).toBeGreaterThan(0.08); + }); + + it('runs as a job the same as in-thread', async () => { + const model = modelOf(softStep(0.3, { ripple: 0 })); + const input = { ...cleanDefaults, square: 1, triangles: null }; + const direct = cleanSurface(model.mesh, model.topology, model.noise, model.step, input); + const progress: number[] = []; + const job = await cleanRefineJob(model, input, new AbortController().signal, (f) => + progress.push(f), + ); + expect(progress.at(-1)).toBe(1); + expect(progress.every((f, i) => i === 0 || f >= progress[i - 1])).toBe(true); + expect(job.mesh!.position).toEqual(direct.mesh!.position); + expect(job.mesh!.corners).toEqual(direct.mesh!.corners); + expect(job.mesh!.crease).toEqual(direct.mesh!.crease); + expect(job.split).toEqual(direct.split); + expect(job.topology).toEqual(direct.topology); + }); +}); diff --git a/tests/unit/refine-session.test.ts b/tests/unit/refine-session.test.ts index 276f3c7..e4c37b9 100644 --- a/tests/unit/refine-session.test.ts +++ b/tests/unit/refine-session.test.ts @@ -19,7 +19,7 @@ import { dismissNotification, requestTaskCancellation, useActivity } from '../.. import { editorCommands, undoTarget } from '../../src/core/commands'; import { partMatrix, triangleCount } from '../../src/core/geometry'; import { detectDefaults } from '../../src/core/refine-detect'; -import { writeRefinedGeometry } from '../../src/core/refine-mesh'; +import { buildTopology, writeRefinedGeometry } from '../../src/core/refine-mesh'; import { fitCurve, GuideLengthError, type EdgeCurve } from '../../src/core/refine-curve'; import type { GuidePoint } from '../../src/core/refine-band'; import type { RefineProposal } from '../../src/core/refine-detect'; @@ -32,6 +32,7 @@ import { commitRefine, fittedWarpBrushRadius, heldRefineState, + noSquareNotice, paintingRefine, refineBrushRadius, refineDraftLimit, @@ -47,7 +48,14 @@ import { } from '../../src/core/store'; import { useXR } from '../../src/core/xr-session'; import type { Joint, Part } from '../../src/core/types'; -import { changedVertices, closed, edgeNeighbours, modelOf, splitEdge } from '../helpers/refine'; +import { + changedVertices, + closed, + closedMesh, + edgeNeighbours, + modelOf, + splitEdge, +} from '../helpers/refine'; import { alongPreset, boxPart, @@ -64,7 +72,7 @@ import { toast, trianglesArea, } from '../helpers/refine-session'; -import { rivetedPlate, softBox, softCylinder } from '../helpers/soft-edges'; +import { rippledSphere, rivetedPlate, softBox, softCylinder } from '../helpers/soft-edges'; const job = vi.hoisted(() => ({ failure: null as Error | null })); vi.mock('../../src/core/refine-job', async (importOriginal) => { @@ -1088,6 +1096,173 @@ describe('refine detection', () => { }); }); +describe('refine clean', () => { + const cleanTask = () => + useActivity.getState().tasks.find((t) => t.title === 'Cleaning the surface')!; + + it('cleans the whole working surface as one undo step', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + expect(paintingRefine(editor())).toBe(false); + const start = session().model!; + const position = start.mesh.position.slice(); + const undo = session().undo.length; + const cleaning = editor().cleanRefine(); + expect(session().clean.running).toBe(true); + await cleaning; + expect(session().clean.running).toBe(false); + expect(cleanTask().status).toBe('completed'); + expect(session().undo.length).toBe(undo + 1); + const { mesh } = session().model!; + expect(mesh.position).not.toEqual(position); + // Triangles turned to follow the sharpened edges come with the topology made for them. + expect(mesh.corners).not.toEqual(start.mesh.corners); + expect(closedMesh(mesh)).toBe(true); + expect(session().model!.topology).toEqual(buildTopology(mesh)); + expect(refineEdited(session())).toBe(true); + expect(differingAttributes(session().preview!, fresh())).toEqual([]); + editor().undoRefine(); + expect(session().model).toBe(start); + expect(differingAttributes(session().preview!, fresh())).toEqual([]); + editor().redoRefine(); + const cleaned = fresh(); + expect(editor().applyRefine()).toBe(true); + expect(differingAttributes(editor().scene.parts[0].geometry, cleaned)).toEqual([]); + expect(closed(editor().scene.parts[0].geometry)).toBe(true); + await vi.waitFor(() => expect(session().stage).toBe('ready')); + expect(session().mode).toBe('clean'); + }); + + it('cleans only a painted area, and nothing before one is painted', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + editor().setRefineClean({ where: 'painted' }); + expect(paintingRefine(editor())).toBe(true); + const model = session().model; + await editor().cleanRefine(); + expect(session().model).toBe(model); + paint([[0.3, 1.5, 0.2]]); + const painted = new Set(); + const { mesh } = session().model!; + for (const t of session().triangles) + for (let k = 0; k < 3; k++) painted.add(mesh.weldOf[mesh.corners[t * 3 + k]]); + expect(painted.size).toBeGreaterThan(0); + await editor().cleanRefine(); + const after = session().model!.mesh; + let moved = 0; + for (let v = 0; v < after.weldedCount; v++) { + const same = [0, 1, 2].every((a) => after.position[v * 3 + a] === mesh.position[v * 3 + a]); + if (same) continue; + moved++; + expect(painted.has(v)).toBe(true); + } + expect(moved).toBeGreaterThan(0); + }); + + it('squares rounded edges, cutting the surface, as one undo step', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + // Paint made before the clean follows the triangles the cut splits. + editor().setRefineClean({ where: 'painted' }); + paint([[0.3, 1.5, 0.2]]); + const paintBefore = [...session().triangles]; + expect(paintBefore.length).toBeGreaterThan(0); + editor().setRefineClean({ where: 'part', square: 1 }); + const start = session().model!; + const undo = session().undo.length; + await editor().cleanRefine(); + expect(cleanTask().status).toBe('completed'); + expect(session().undo.length).toBe(undo + 1); + const { mesh, topology } = session().model!; + expect(mesh.triangleCount).toBeGreaterThan(start.mesh.triangleCount); + expect(closedMesh(mesh)).toBe(true); + expect(topology).toEqual(buildTopology(mesh)); + let creased = 0; + for (let v = 0; v < mesh.weldedCount; v++) creased += mesh.crease[v]; + expect(creased).toBeGreaterThan(0); + const paintAfter = new Set(session().triangles); + for (const t of paintBefore) expect(paintAfter.has(t)).toBe(true); + expect(differingAttributes(session().preview!, fresh())).toEqual([]); + editor().undoRefine(); + expect(session().model).toBe(start); + expect(session().triangles).toEqual(paintBefore); + expect(differingAttributes(session().preview!, fresh())).toEqual([]); + editor().redoRefine(); + const squared = fresh(); + expect(editor().applyRefine()).toBe(true); + expect(differingAttributes(editor().scene.parts[0].geometry, squared)).toEqual([]); + expect(closed(editor().scene.parts[0].geometry)).toBe(true); + }); + + it('says so when Square finds no rounded corner', async () => { + setup([boxPart({ geometry: rippledSphere(1) })], ['box']); + await ready(); + editor().setRefineMode('clean'); + editor().setRefineClean({ smooth: 0, sharpen: 0, depth: 0, square: 1 }); + const model = session().model; + await editor().cleanRefine(); + expect(session().model).toBe(model); + expect(toast()).toBe(noSquareNotice); + }); + + it('says so when the settings leave the surface as it is', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + editor().setRefineClean({ smooth: 0, sharpen: 0, depth: 0 }); + const model = session().model; + await editor().cleanRefine(); + expect(session().model).toBe(model); + expect(toast()).toBe('These settings leave the surface as it is.'); + }); + + it('drops a clean that finished after the model changed', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + const cleaning = editor().cleanRefine(); + commitRefine({ model: movedModel(session().model!, topVertices(), [0, 0.01, 0]) }); + const model = session().model; + await cleaning; + expect(session().model).toBe(model); + expect(toast()).toBe('The surface changed, so cleaning was stopped.'); + expect(session().clean.running).toBe(false); + }); + + it('stops a running clean and its worker on cancel', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().setRefineMode('clean'); + const terminate = vi.fn(); + class StuckWorker { + onmessage = null; + onerror = null; + onmessageerror = null; + postMessage() {} + terminate = terminate; + } + vi.stubGlobal('Worker', StuckWorker); + const model = session().model; + try { + const cleaning = editor().cleanRefine(); + expect(session().clean.running).toBe(true); + expect(heldRefineState()).toContain('clean'); + editor().cancelRefineClean(); + await cleaning; + } finally { + vi.unstubAllGlobals(); + } + expect(terminate).toHaveBeenCalled(); + expect(session().clean.running).toBe(false); + expect(session().model).toBe(model); + expect(cleanTask().status).toBe('cancelled'); + expect(heldRefineState()).toEqual([]); + }); +}); + describe('refine lifecycle edges', () => { const preparing = () => useActivity.getState().tasks.filter((t) => t.title === 'Preparing to refine');