DEV Community

Cover image for Building a Planar-Graph Floor Plan Room Solver in Pure TypeScript
Clara Sutton
Clara Sutton

Posted on Originally published at plancaliber.hashnode.dev

Building a Planar-Graph Floor Plan Room Solver in Pure TypeScript

When a user drags walls on a 2D canvas—or uploads a hand-drawn sketch that gets parsed into approximate wall segments—you do not start with clean room polygons. You start with a messy soup of line segments:

  • Endpoints that almost touch (2 to 6 inches apart)
  • Walls drawn at 87.4 degrees instead of 90 degrees
  • Interior partitions that terminate mid-span against an exterior wall (T-junctions) without sharing a vertex
  • Two walls crossing in an X without a shared intersection node
  • Half-walls and wing walls that dangle into an open living room without closing a face
  • Nested freestanding closets or pantries sitting entirely inside a larger room

If you try to run polygon detection straight on raw wall segments, room areas vanish, doors float off their host walls, and exterior square footage breaks. You do not need a multi-megabyte WebAssembly CAD kernel to solve this cleanly in the browser. A deterministic planar-graph pipeline in pure TypeScript handles the whole topology problem in under a millisecond on typical residential plans.

Here is the exact architecture we built in src/lib/cad/healer.ts for PlanCaliber, our browser-based 2D/3D floor plan CAD engine.


1. The Four-Pass Topology Healer

Before extracting a single room polygon, we run a deterministic four-pass healer (healPlanDocument) on a cloned wall graph. Order matters—welding before splitting prevents near-coincident corners from creating microscopic triangles when T-junctions get projected:

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, straighten near-orthogonal walls, re-weld
  weldVerticesInPlace(healed, weldRadiusIn);
  if (snapAngles) {
    snapWallAnglesInPlace(healed, 6);
    weldVerticesInPlace(healed, Math.min(weldRadiusIn, 4));
  }

  // Pass 3: Split X-crossings & T-junctions within 6", cull < 4" slivers
  splitCrossingsAndTJunctionsInPlace(healed, 6);
  deduplicateAndCullDegenerateWallsInPlace(healed);

  // Re-verify orthogonality after T-junction projections
  if (snapAngles) {
    snapWallAnglesInPlace(healed, 6);
    deduplicateAndCullDegenerateWallsInPlace(healed);
  }

  // Pass 4: Keep all doors/windows >= 3" inside host wall endpoints
  clampOpeningsInPlace(healed);

  return healed;
}
Enter fullscreen mode Exit fullscreen mode

Why Union-Find + Consensus Coordinates Beat Naive Averaging

In Pass 1 (weldVerticesInPlace), vertices within weldRadiusIn (default 8" for rough sketch imports, tighter for direct CAD drags) are grouped using a disjoint-set (Union-Find) with path compression.

A subtle trap when merging a cluster of vertices is taking a blind arithmetic mean. If three existing CAD vertices already sit cleanly at x = 144.000" and one sloppy hand-drawn endpoint lands at x = 146.500", averaging drags all four vertices to 144.625", nudging perpendicular walls out of square.

Instead, we bucket candidate coordinates at 0.05" precision first:

function pickCanonicalCoord(values: number[]): number {
  if (values.length === 0) return 0;
  if (values.length === 1) return values[0];

  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);
}
Enter fullscreen mode Exit fullscreen mode

If two or more vertices already agree within 0.05", that exact coordinate wins and the stray vertex snaps to it. Only when every vertex in the cluster disagrees do we fall back to a quarter-inch snapped mean.

Splitting T-Junctions Without Losing Doors and Windows

When an interior partition terminates within 6" of an exterior wall's span, we project the endpoint perpendicularly onto the host wall, insert a shared vertex, and split the host wall into two child segments.

Because doors and windows are stored parametrically (wallId + offsetIn measured from startId), splitting a wall must remap every attached opening onto the child segment that now contains its center—recomputing offsetIn relative to the new split vertex—and Pass 4 (clampOpeningsInPlace) ensures no door jamb overlaps a mitered corner (>= 3" margin from both ends).


2. Peeling Dangling Filaments Before Walking Faces

Once every intersection and T-junction shares a vertex, the wall graph is planar—except for dangling wing walls, kitchen peninsulas, and open closets whose endpoints have degree 1.

If you leave degree-1 edges in the graph while tracing half-edge faces, the traversal walks down the dangling wall, spins 180 degrees around the dead end, and walks back along its twin—producing degenerate slit polygons that ruin label placement and interior offset geometry.

Before creating half-edges, we iteratively prune every wall touching a degree-1 vertex (a standard 2-core peel):

let activeWalls = doc.walls.filter((w) => {
  const a = vMap.get(w.startId);
  const b = vMap.get(w.endId);
  return a && b && w.startId !== w.endId && Math.hypot(b.x - a.x, b.y - a.y) >= 1;
});

let pruned = true;
while (pruned) {
  pruned = false;
  const deg = new Map<string, number>();
  for (const w of activeWalls) {
    deg.set(w.startId, (deg.get(w.startId) ?? 0) + 1);
    deg.set(w.endId, (deg.get(w.endId) ?? 0) + 1);
  }
  const next = activeWalls.filter(
    (w) => (deg.get(w.startId) ?? 0) >= 2 && (deg.get(w.endId) ?? 0) >= 2
  );
  if (next.length < activeWalls.length) {
    activeWalls = next;
    pruned = true;
  }
}
Enter fullscreen mode Exit fullscreen mode

Crucially, the pruned walls are not deleted from the plan document—they still render in 2D, extrude in 3D, appear in wall stud/drywall takeoffs, and export to AutoCAD R12 .DXF. They are simply omitted from the closed-face cycle extractor.


3. Half-Edge Minimal Cycle Extraction (DCEL Walk)

Every surviving undirected wall becomes two directed half-edges (A -> B and B -> A) linked by twinId, storing their outgoing angle Math.atan2(dy, dx).

At every vertex, we sort all outgoing half-edges in ascending angular order. Then, starting from each unvisited half-edge cur:

  1. Arrive at cur.toId
  2. Locate cur.twinId in the sorted outgoing list at cur.toId
  3. Take the previous entry cyclically: (twinIdx - 1 + list.length) % list.length

In screen/canvas coordinates (+x right, +y down), stepping one index backward from the incoming twin always chooses the sharpest interior turn, walking strictly around the boundary of a single minimal face:

for (const list of outgoing.values()) {
  list.sort((a, b) => a.angle - b.angle);
}

const visited = new Uint8Array(halfEdges.length);
const cycles: ExtractedCycle[] = [];

for (let i = 0; i < halfEdges.length; i++) {
  if (visited[i]) continue;

  const cycleHes: HalfEdge[] = [];
  let cur = halfEdges[i];
  let safeSteps = 0;
  let closed = false;

  while (safeSteps++ <= halfEdges.length + 2) {
    if (visited[cur.id]) {
      closed = cur.id === i;
      break;
    }
    visited[cur.id] = 1;
    cycleHes.push(cur);

    const listAtTo = outgoing.get(cur.toId);
    if (!listAtTo || listAtTo.length === 0) break;

    const twinIdx = listAtTo.findIndex((he) => he.id === cur.twinId);
    if (twinIdx === -1) break;

    // Sharpest interior turn for signedArea > 0 faces in (+x right, +y down)
    const nextIdx = (twinIdx - 1 + listAtTo.length) % listAtTo.length;
    cur = listAtTo[nextIdx];
    if (cur.id === i) {
      closed = true;
      break;
    }
  }

  if (!closed || cycleHes.length < 3) continue;

  const polygon = cycleHes.map((he) => {
    const v = vMap.get(he.fromId)!;
    return { x: v.x, y: v.y };
  });
  const signedArea = shoelaceSignedArea(polygon);

  // Discard outer unbounded perimeter face (signedArea < 0)
  // and tiny framing slivers (< 4 sq ft = 576 sq in)
  if (signedArea <= 576) continue;

  cycles.push({ polygon, signedArea, edgeWalls: cycleHes.map((he) => he.wall) });
}
Enter fullscreen mode Exit fullscreen mode

Notice how elegantly the Shoelace signed area solves the "outer perimeter" problem in a single line:

  • Every bounded interior room traces with signedArea > 0
  • The infinite exterior perimeter around the whole building automatically traces with the opposite winding (signedArea < 0) and drops out cleanly via if (signedArea <= 576) continue

4. Three Real-World Edge Cases That Trip Up Floor Plan Engines

Getting the basic half-edge walk right is only half the story. Residential plans immediately hit three practical geometry edge cases:

A. Centerline Area vs. Net Interior Area vs. ANSI Z765 Heated GLA

Walls have physical thickness—typically 6" for exterior framed walls and 4.5" for interior 2×4 stud partitions.

  • Room dimensions & flooring takeoff need net interior clear space (buildInsetInteriorPolygon), offsetting each wall edge inward by wall.thicknessIn / 2 and intersecting adjacent offset lines at corners.
  • US residential Gross Living Area (ANSI Z765-2021) is measured to the exterior finished face of exterior walls (+thicknessIn / 2 outward on exterior boundaries), includes heated living rooms/bedrooms/hallways/closets, and strictly excludes garages, unheated porches, decks, and unfinished basements.

Separating these three measurements in the solver—rather than fudging one number—is why you can simultaneously get accurate interior drywall/flooring takeoffs and a real exterior-face GLA total. (We also broke the standalone ANSI rules out into a free ANSI Z765 Gross Living Area Calculator.)

B. Nested Rooms (Freestanding Closets & Core Islands)

If a homeowner draws a freestanding pantry or fireplace chase completely inside an open-concept great room without walls connecting it to the outer shell, the half-edge extractor yields two separate closed cycles: the pantry and the great room.

Using point-in-polygon checks across extracted faces (findEnclosingParentIndices), we detect when cycle B sits strictly inside cycle A, subtract B's footprint from A's net floor area, and pass B's polygon as a hole when placing A's room label.

C. Label Placement Inside L-Shaped Rooms & Rooms With Holes

A polygon's naive centroid frequently lands outside an L-shaped hallway or right on top of an island hole. ensureInteriorLabelPoint(poly, holes) tests the centroid first; if it falls outside the polygon, inside a hole, or too close to a wall, it sweeps interior grid candidates and picks the point maximizing minimum distance to every boundary and hole edge—so room tags and 12'-4" × 15'-8" callouts always sit in open floor space.


Try the Engine (and Inspect the Output)

This entire healer, planar face extractor, clearance auditor, 3D cutaway extruder, pdf-lib scaled PDF writer, and zero-dependency AutoCAD R12 .DXF serializer runs live in PlanCaliber—no account required to draw, drag walls, calibrate a sketch, and watch rooms re-solve in real time.

If you want to inspect the downstream CAD artifact generated directly from the solved wall & room graph, you can download a live unwatermarked specimen here: Sample AutoCAD R12 .DXF Specimen (pure ASCII AC1009, $INSUNITS = 1 inches across 8 AIA layers).

(All PlanCaliber outputs are for preliminary space planning and drafting—always verify dimensions and local building codes on site.)

Top comments (0)