PlanCaliber 如何在 TypeScript 中將雜亂手繪平面圖修復為封閉 CAD 幾何
Healing Messy Hand-Drawn Floor Plan Graphs into Watertight CAD Geometry in TypeScript
PlanCaliber 以零依賴 TypeScript 建立確定性的四階段圖形修復器,將雜亂的平面圖線段整理成乾淨的平面 CAD 圖形。流程依次焊接端點、校正牆角、分割交叉與 T 形接點、清除退化牆段,最後調整門窗開口,供房間求解、3D 網格生成及 PDF/DXF 匯出使用。
If you ask a vision model to extract wall segments from a photograph of a hand-drawn floor plan — or let a human sketch walls freely with a mouse — the output looks plausible at a glance and fails catastrophically the moment you try to compute room polygons, square footage, 3D wall meshes, or layered AutoCAD .DXF files.
The failures are always the same four geometric defects:
- Open corners: Two walls that visually meet have endpoints 2" to 6" apart, so a planar room solver sees one giant open void instead of two rooms.
- Slightly skewed walls: A horizontal exterior wall comes back at 1.8° or 88.4°, breaking parallel dimension chains and producing ugly miter artifacts in 3D.
- Unsplit T-junctions and X-crossings: An interior partition terminates against the middle of an exterior wall without splitting that exterior wall into two edges — leaving a dangling degree-1 vertex that prevents half-edge face traversal from closing either room.
- Duplicate slivers and orphaned openings: Overlapping strokes create 2"-long zero-area wall stubs, and splitting a wall leaves doors and windows referencing a wall ID that no longer spans their offset.
In PlanCaliber, we built a deterministic 4-pass graph healer (healPlanDocument) in zero-dependency TypeScript that turns raw noisy line segments into a clean planar CAD graph before the room solver, 3D mesh generator, or PDF/DXF exporters ever see it.
Here is how the four passes work and why their ordering matters.
The 4-Pass Pipeline Architecture
Running the passes in the wrong order creates subtle bugs. If you split T-junctions before snapping skewed angles, a 2° wall skew splits the host wall at the wrong station and creates tiny triangular slivers. If you snap angles without re-welding, adjacent endpoints drift apart by 0.5" to 2".
Our orchestrator runs four explicit stages on a cloned document so healing is pure and undo-safe:
export function healPlanDocument(
doc: PlanDocument,
options?: { snapAngles?: boolean; weldRadiusIn?: number }
): PlanDocument {
const healed = cloneDoc(doc);
const snapAngles = options?.snapAngles !== false;
const weldRadiusIn = options?.weldRadiusIn ?? 8;
// Pass 1 & 2: Weld close endpoints within weldRadiusIn, snap wall angles within +/-6 deg, re-weld
weldVerticesInPlace(healed, weldRadiusIn);
if (snapAngles) {
snapWallAnglesInPlace(healed, 6);
weldVerticesInPlace(healed, Math.min(weldRadiusIn, 4));
}
// Pass 3: Split X-intersections and T-junctions within 6", then deduplicate/cull < 4" walls
splitCrossingsAndTJunctionsInPlace(healed, 6);
deduplicateAndCullDegenerateWallsInPlace(healed);
// Re-verify orthogonality after T-junction projections so split stems stay exact
if (snapAngles) {
snapWallAnglesInPlace(healed, 6);
deduplicateAndCullDegenerateWallsInPlace(healed);
}
// Pass 4: Clamp all openings safely >= 3" inside host wall endpoints
clampOpeningsInPlace(healed);
return healed;
}
Every internal coordinate is stored in architectural inches (1/4" precision), so tolerances correspond directly to real physical drafting margins rather than screen pixels.
Pass 1: Connected-Component Vertex Welding (Union-Find + Canonical Bucketing)
A naive vertex weld iterates pairwise and collapses vertex B onto vertex A. That is order-dependent: if three walls meet within 6" in a chain, greedy pairwise welding drifts depending on array order and corrupts already-exact coordinates on untouched walls.
Instead, we build connected components of all vertices within weldRadiusIn (default 8" for noisy hand sketches, tighter for CAD edits) using a disjoint-set (Union-Find) structure with path compression:
const parent = Array.from({ length: n }, (_, i) => i);
const find = (i: number): number => {
let cur = i;
while (parent[cur] !== cur) {
parent[cur] = parent[parent[cur]];
cur = parent[cur];
}
return cur;
};
const union = (i: number, j: number): void => {
const ri = find(i);
const rj = find(j);
if (ri !== rj) parent[rj] = ri;
};
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const dx = doc.vertices[i].x - doc.vertices[j].x;
const dy = doc.vertices[i].y - doc.vertices[j].y;
if (Math.hypot(dx, dy) <= radiusIn) {
union(i, j);
}
}
}
Once a cluster of close endpoints is grouped, how do we pick the merged coordinate? Taking a blind average shifts clean architectural walls off-grid whenever one messy interior wall arrives near a clean exterior corner.
We use a canonical coordinate picker: if two or more vertices in the cluster already agree within 0.05" on X or Y, we preserve that exact agreed coordinate instead of averaging in the noisy outlier. Only when every vertex in the cluster disagrees do we fall back to the cluster mean snapped to 0.25":
function pickCanonicalCoord(values: number[]): number {
if (values.length === 0) return 0;
if (values.length === 1) return values[0];
// If multiple vertices already agree within 0.05", preserve that exact coordinate
const buckets = new Map<number, { sum: number; count: number }>();
for (const v of values) {
const key = Math.round(v * 20) / 20;
const b = buckets.get(key);
if (b) {
b.sum += v;
b.count += 1;
} else {
buckets.set(key, { sum: v, count: 1 });
}
}
let bestCount = 0;
let bestAvg = 0;
for (const b of buckets.values()) {
if (b.count > bestCount) {
bestCount = b.count;
bestAvg = b.sum / b.count;
}
}
if (bestCount >= 2) {
return Number(bestAvg.toFixed(4));
}
const mean = values.reduce((a, b) => a + b, 0) / values.length;
return snapInches(mean, 0.25);
}
This single heuristic makes repeated edits idempotent: clean exterior corners stay locked to exact whole-inch coordinates even when new hand-drawn partitions weld into them.
Pass 2: Orthogonal Angle Snapping Without Tearing Shared Corners
Hand sketches routinely come in with exterior walls tilted at 1° to 5°. You cannot rotate each wall independently around its midpoint without pulling connected walls apart.
Instead, snapWallAnglesInPlace(healed, 6) identifies chains of near-horizontal and near-vertical walls within ±6° of 0° or 90°, groups connected vertices along shared horizontal (Y) or vertical (X) bands, and solves one canonical coordinate per axis band via pickCanonicalCoord.
Because snapping shifts a skewed corner slightly, we immediately run a second, tighter weld pass (Math.min(weldRadiusIn, 4)) so any newly aligned endpoints fuse cleanly before intersection analysis.
Pass 3: Splitting T-Junctions, X-Crossings, and Re-Homing Doors
In a planar room solver (like half-edge minimal cycle extraction), every geometric intersection must be a shared topological vertex. If an interior bedroom partition meets the midpoint of a 36'-0" exterior wall without splitting that exterior wall, the graph has no edge turning from the exterior wall into the partition.
splitCrossingsAndTJunctionsInPlace(healed, 6) handles two cases:
-
Proper X-crossings: Two walls intersect cleanly in their interior (
0 < t < 1,0 < u < 1), creating a shared intersection vertex and splitting both walls. -
Near-miss T-junctions: A wall endpoint falls within
6"perpendicularly of another wall's interior segment. We project that endpoint orthogonally onto the host wall, snap the stem endpoint onto the projection, and callsplitWallAtVertexInPlace.
Whenever a wall splits into two sub-walls (wA and wB), every hosted door and window on the original wall must be re-homed accurately:
- Convert each opening's offset along the original wall (
centerOffsetIn) into its exact position on eitherwA(offset < splitDist) orwB(offset - splitDist). - Keep the opening's
widthIn,swing,sillHeightIn, andkindintact so doors never vanish or invert swing direction when a partition meets a hallway.
Immediately afterward, deduplicateAndCullDegenerateWallsInPlace removes zero-length and < 4" sliver walls and collapses duplicate collinear edges using deterministic priority (exterior > interior > low). Then we re-run orthogonal snapping once more so T-junction stems projected onto newly split walls sit at exact 90.00°.
Pass 4: Clamping Openings Safely Inside Wall Jambs
After welding and T-junction splits shorten a wall segment by a few inches, a 36" door that previously sat 4" from a corner might now protrude past the new corner vertex — which causes broken 3D wall CSG cuts and overlapping door-jamb lines in .DXF export.
Pass 4 (clampOpeningsInPlace) checks every opening against its host wall's solved length and clamps its center offset safely inside [minJamb + width/2, wallLength - minJamb - width/2] with a 3" minimum jamb clearance on both ends.
Verifying the Healer in Unit Tests
The cleanest way to trust a geometry healer is to throw deliberately broken synthetic sketches at it in automated tests. In our test suite (tests/cad.test.ts), we feed a deliberately broken sketch graph containing:
- a
3"open corner gap, - an
88°skewed wall, and - an unsplit interior T-junction
and assert that healPlanDocument plus our planar solver yields watertight rooms, 0 dangling vertices, and 100.00% exterior dimension closure in under 35 milliseconds.
If you want to test the pipeline live on your own sketch photo or floor plan PDF, you can try PlanCaliber Sketch-to-CAD or our PDF-to-CAD Floor Plan converter directly in the browser — or inspect a real compiled AutoCAD R12 (AC1009) .DXF output file generated directly from the healed graph.
Note: PlanCaliber produces preliminary space-planning drawings and estimates for visualization and early contractor discussions. Always verify dimensions and local codes on site with a licensed professional prior to construction or permitting.
來源:DEV Community · dev.to