Most web floor plan apps force users to draw rooms as isolated boxes. The moment you sketch an L-shaped hallway, split a bedroom with a T-junction partition wall, or import an existing .DXF blueprint, box-based room tools break down.
In TrueDraft CAD — an open-source (AGPL-3.0) browser CAD studio (GitHub) built as a zero-subscription alternative to desktop floor plan software — users draw freeform walls, trace sketches, or import layered .DXF plans, and the geometry engine automatically detects enclosed rooms, places readable room labels inside concave L-shapes, computes clean wall miter joins, and updates framing/drywall/paint takeoffs in real time on every drag frame.
Here is how the pure-TypeScript planar half-edge geometry engine in src/lib/cad/geometry.ts works with zero native/WASM dependencies.
1. Planarizing Freeform Walls (Snapping, T-Junctions, and Crossings)
Users rarely terminate every interior partition cleanly at another wall's vertex. They drag a new partition straight into the midpoint of an existing exterior wall (a T-junction), or cross two walls when laying out a hallway. Before we can extract faces, we have to turn a raw Wall[] list into a proper planar graph:
-
Endpoint snapping (
SNAP_TOL): Merge endpoints within tolerance into shared vertex indices. -
T-junction splitting: For every vertex $v$ that lies within
SNAP_TOLof the interior of segment $(a, b)$, record a parametric split $t \in (0, 1)$ on that segment. - Crossing splits: For every pair of segments with a proper intersection $(t, u) \in (0, 1)^2$, create a new vertex at the intersection and record split points on both segments.
- Dangling-edge pruning: Iteratively strip degree-1 vertices (stub walls or partial dividers) so open spurs never corrupt cycle traversal.
function segmentIntersection(
a: Point2D,
b: Point2D,
c: Point2D,
d: Point2D
): { t: number; u: number; point: Point2D } | null {
const rX = b.x - a.x;
const rY = b.y - a.y;
const sX = d.x - c.x;
const sY = d.y - c.y;
const denom = rX * sY - rY * sX;
if (Math.abs(denom) < 1e-9) return null;
const qpX = c.x - a.x;
const qpY = c.y - a.y;
const t = (qpX * sY - qpY * sX) / denom;
const u = (qpX * rY - qpY * rX) / denom;
if (t > 1e-4 && t < 1 - 1e-4 && u > 1e-4 && u < 1 - 1e-4) {
return { t, u, point: { x: a.x + rX * t, y: a.y + rY * t } };
}
return null;
}
2. Walking Minimal Cycles via Twin Half-Edges
Once split segments are deduplicated into undirected edges, we emit two directed half-edges ($u \to v$ and its twin $v \to u$) per edge and sort every vertex's outgoing half-edges counter-clockwise by Math.atan2(dy, dx).
To trace minimal faces, at each vertex we take the sharpest left turn from the incoming edge's twin: (twinIdx - 1 + outList.length) % outList.length.
const posInOutgoing = new Int32Array(halfEdges.length);
for (const list of outgoing.values()) {
list.sort((a, b) => halfEdges[a].angle - halfEdges[b].angle);
for (let i = 0; i < list.length; i++) {
posInOutgoing[list[i]] = i;
}
}
for (let startId = 0; startId < halfEdges.length; startId++) {
if (visited[startId]) continue;
const cycleNodeIds: number[] = [];
let curr = startId;
let steps = 0;
let closed = false;
while (steps <= halfEdges.length + 1) {
if (visited[curr]) {
closed = curr === startId;
break;
}
visited[curr] = 1;
const he = halfEdges[curr];
cycleNodeIds.push(he.from);
const outList = outgoing.get(he.to);
if (!outList || outList.length === 0) break;
const twinIdx = posInOutgoing[he.twin];
const nextIdx = (twinIdx - 1 + outList.length) % outList.length;
curr = outList[nextIdx];
steps++;
}
if (!closed || cycleNodeIds.length < 3) continue;
const poly = cycleNodeIds.map((idx) => ({ x: nodes[idx].x, y: nodes[idx].y }));
const signedArea = polygonSignedArea(poly);
// Bounded interior rooms have positive signed area;
// the outer building silhouette has negative signed area and is skipped.
if (signedArea <= MIN_ROOM_AREA_SQM) continue;
// ...
}
The shoelace signed area automatically separates enclosed rooms (positive area) from the unbounded exterior perimeter face (negative area) in $O(E \log E)$ time — fast enough to run continuously at 60 FPS while dragging walls in the browser.
3. Concave Room Label Placement (polygonVisualCenter)
Standard polygon centroids fail badly on L-shaped hallways and U-shaped kitchens: the geometric centroid frequently lands outside the room, floating on top of an adjacent bathroom or exterior wall.
Instead, polygonVisualCenter(poly) samples an adaptive interior grid inside the room's bounding box, filters candidate points with pointInPolygon, and maximizes the minimum distance to all polygon edges (minEdgeDist), then runs a local refinement pass. The result guarantees every room label ("Living Room · 312 sq ft") stays centered cleanly inside the widest walkable area of the room — both on screen and in exported blueprint-to-3D & vector PDF sheets.
4. Bounded Wall Miter Joins (computeWallPolygons)
Centerline walls look crude in 2D architectural drawings and leave triangular gaps at corners in 3D extrusions. computeWallPolygons(walls) groups walls meeting at shared endpoints, intersects their offset left/right face lines with adjacent walls, and clamps acute angles to maxMiter = Math.max(selfHalfThick, adj.halfThick) * 2.5 so sharp bay-window or angled-wall joins never shoot spikes across the drawing:
const maxMiter = Math.max(selfHalfThick, adj.halfThick) * 2.5;
if (dist(hit, endpoint) > maxMiter) {
return fallback;
}
return hit;
5. Live Framing, Drywall & Paint Takeoffs with Opening Deductions
Because doors and windows are stored parametrically along their host wall (wallId, normalized position t, width, height, sillHeight), computeTakeoff(plan, rooms) recalculates real construction quantities in milliseconds:
-
Exterior walls count 1 interior drywall face (
sides = 1); interior partitions count both faces (sides = 2). - Every door and window opening on a wall is subtracted from
len * w.heightbefore multiplying bysides. - Drywall adds a standard 10% cut-waste factor and divides by 4×8 ft sheet area (
2.9729 m²). - Two-coat interior paint computes
Math.ceil((rawDrywallSqM * 10.7639 * 2) / 350)gallons. - Door (
D1, D2...) and Window (W1, W2...) schedules sort deterministically and stay synchronized across the live Studio sidebar, Sheet A2.0 PDF schedules, and CSV takeoff exports.
const sides = w.exterior ? 1 : 2;
const grossFaceSqM = len * w.height;
const wallOpenings = openingsByWall.get(w.id) ?? [];
const openingSqM = wallOpenings.reduce((s, o) => s + o.width * o.height, 0);
rawDrywallSqM += Math.max(0, grossFaceSqM - openingSqM) * sides;
Try It Live or Inspect the Source
You can test the half-edge room detector, wall miter engine, sketch-to-CAD tracing, and real-time material takeoffs immediately in the browser with zero signup:
- Interactive 2D/3D Studio: https://www.truedraftcad.com/studio
- No-Subscription Floor Plan Software Comparison: https://www.truedraftcad.com/floor-plan-software-no-subscription
-
AGPL-3.0 Source Code (
src/lib/cad/geometry.ts): https://github.com/truedraftcad/truedraft-cad
(Watch a 38-second walkthrough of TrueDraft CAD exporting multi-story & barndominium plans to DXF, PDF, and 3D-print STL: https://youtu.be/XpJcYWnkOZw)
Top comments (0)