Building a Real-Time 3D Architectural Cutaway & Wavefront .OBJ Exporter from a 2D Floor Plan Graph in TypeScript

2026-11-27来源 dev.to TypeScriptEnglish

Most browser floor-plan tools treat 2D drafting and 3D visualization as two completely separate codebases — or worse, bake a flat image into a 3D box and hope nobody zooms in. When we built PlanCaliber, we wanted the 2D drafting canvas, the real-time Three.js 3D dollhouse view, and the downloadable 3D .OBJ / .MTL model to compile deterministically from the exact same planar wall graph in pure TypeScript — with zero server round-trips and zero heavy native CAD kernels.

Here are the four geometric techniques that made live 3D cutaway viewing and clean Blender/SketchUp .OBJ export work reliably at 60 FPS on ordinary laptops.

1. Analytic Wall Slicing Beats 3D Boolean CSG Every Time

The first instinct when extruding walls with doors and windows is to extrude a solid wall box and subtract door/window cubes with a 3D CSG (Constructive Solid Geometry) library. In a browser CAD app, CSG booleans create three painful bugs:

  • T-junction cracks and z-fighting whenever two windows sit near a corner miter.
  • Degenerate coplanar triangles that fail manifold checks when a builder opens the exported .OBJ in Blender or SketchUp.
  • 50–300 ms rebuild stalls during live wall dragging.

Instead, our planar solver slices every wall analytically along its 1D axis s in [0, wallLengthIn] before a single 3D vertex is generated. Each wall emits clean, non-overlapping 3D box intervals (WallPiece[]):

  • Solid pier intervals between openings: full height [0, ceilingHeightIn]
  • Door transoms: [opening.headHeightIn, ceilingHeightIn] (typically 80" to 108")
  • Window sills & headers: [0, opening.sillHeightIn] and [opening.headHeightIn, ceilingHeightIn]
  • Separate glazing prisms: 0.70" thick centered along the wall centerline between sillHeightIn and headHeightIn

Because every piece is already a convex quadrilateral prism in 2D (corners2D: [Point2D, Point2D, Point2D, Point2D]) plus a vertical span [bottomIn, topIn], both our Three.js dollhouse renderer and our Wavefront .OBJ serializer consume the exact same array of analytic pieces. Wall dragging stays smooth at 60 FPS, and exported meshes contain zero coplanar slivers.

2. Camera-Facing Auto-Cutaway in 15 Lines of Dot-Product Math

A common usability complaint in 3D floor-plan viewers is that exterior walls block your view of the kitchen island and bathroom fixtures whenever you orbit around the house. Rebuilding Three.js geometry every time the camera moves is wasteful; hiding all exterior walls makes the space lose all architectural depth.

In Viewer3D.svelte, each exterior wall registers two prebuilt THREE.Group meshes at compile time — fullGroup (full 9'-0" ceiling height) and cutGroup (low cutaway curb height) — paired with the wall's precomputed outward unit normal (outwardX, outwardZ). On every camera orbit update, syncCutawayVisibility() flips visibility in O(walls) with a single 2D dot product:

interface ExteriorCutawayEntry { outwardX: number; outwardZ: number; fullGroup: THREE.Group; cutGroup: THREE.Group; } function syncCutawayVisibility() { const useCut = cameraPreset === 'dollhouse' && autoCutaway; const camHorizX = camera.position.x - orbitTarget.x; const camHorizZ = camera.position.z - orbitTarget.z; const len = Math.hypot(camHorizX, camHorizZ) || 1; const dirToCamX = camHorizX / len; const dirToCamZ = camHorizZ / len; for (const entry of cutawayEntries) { if (!useCut) { entry.fullGroup.visible = true; entry.cutGroup.visible = false; } else { const dot = entry.outwardX * dirToCamX + entry.outwardZ * dirToCamZ; const shouldCut = dot > 0.16; entry.fullGroup.visible = !shouldCut; entry.cutGroup.visible = shouldCut; } } } 

The 0.16 threshold (~80.8 degrees) keeps side walls tall while dropping only the walls facing toward the camera. Orbiting 360 degrees around a remodel feels instantaneous because zero buffers are reallocated — Three.js simply toggles .visible booleans. You can test that live auto-cutaway on any of our 20 editable US floor plan templates or compile one from text or a sketch in our AI Floor Plan Generator.

3. Concave Room Slabs Require Real Ear-Clipping Triangulation

Real residential rooms are rarely rectangles. L-shaped kitchens, T-shaped hallways, wrap-around great rooms, and notched primary suites are concave polygons. If you try to render or export floor slabs with naive triangle-fan triangulation from vertex 0, triangles spill outside the room perimeter across concave corners.

To keep our Cloudflare Worker bundle tiny and dependency-free, src/lib/cad/export-3d-csv.ts implements a deterministic 70-line ear-clipping triangulator directly on each room's solved interiorPolygon:

function triangulatePolygon2D(poly: Point2D[]): [Point2D, Point2D, Point2D][] { if (poly.length < 3) return []; if (poly.length === 3) return [[poly[0], poly[1], poly[2]]]; const pts = poly.map((p) => ({ x: p.x, y: p.y })); let area = 0; for (let i = 0; i < pts.length; i++) { const a = pts[i]; const b = pts[(i + 1) % pts.length]; area += a.x * b.y - b.x * a.y; } if (area < 0) pts.reverse(); const tris: [Point2D, Point2D, Point2D][] = []; const indices = pts.map((_, idx) => idx); let guard = 0; while (indices.length > 3 && guard++ < 500) { let earFound = false; const len = indices.length; for (let i = 0; i < len; i++) { const a = pts[indices[(i - 1 + len) % len]]; const b = pts[indices[i]]; const c = pts[indices[(i + 1) % len]]; // Convex corner test in screen-Y-down coordinates const cross = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); if (cross <= 1e-4) continue; let containsOther = false; for (let j = 0; j < len; j++) { const idx = indices[j]; if (idx === indices[(i - 1 + len) % len] || idx === indices[i] || idx === indices[(i + 1) % len]) continue; if (pointInTri(pts[idx], a, b, c)) { containsOther = true; break; } } if (!containsOther) { tris.push([a, b, c]); indices.splice(i, 1); earFound = true; break; } } if (!earFound) break; } if (indices.length === 3) { tris.push([pts[indices[0]], pts[indices[1]], pts[indices[2]]]); } return tris; } 

Each triangle emits a top finish surface at y = 0 and a subfloor underside at y = -4" grouped under o Floor_<roomId> with room-specific material assignments (floor_oak_hardwood, floor_porcelain_tile, floor_polished_concrete, floor_carpet, or floor_luxury_vinyl).

4. Emitting Clean, Right-Handed Wavefront .OBJ + .MTL in Inches

When exporting .OBJ files for Blender, SketchUp, or Rhino, two silent gotchas ruin otherwise valid meshes:

  1. Inconsistent face winding (inside-out dark walls under backface culling).
  2. Untyped blobs where every wall, cabinet, floor finish, and pane of glass gets merged into one giant mesh.

Our generateWavefrontObj() serializer normalizes every 2D quad's signed area before emitting vertices in architectural inches (+X East, +Y Elevation Up, +Z South) and pairs the .OBJ with a physical .MTL library (mtllib plan.mtl) spanning 12 distinct materials including translucent window glass (d 0.38):

const emitQuadPrism = ( quad: [Point2D, Point2D, Point2D, Point2D], yBottom: number, yTop: number ): void => { const pts = [...quad]; let area2 = 0; for (let i = 0; i < 4; i++) { const a = pts[i]; const b = pts[(i + 1) % 4]; area2 += a.x * b.y - b.x * a.y; } if (area2 < 0) pts.reverse(); const base = vIndex; for (const p of pts) objLines.push(`v ${n3(p.x)} ${n3(yBottom)} ${n3(p.y)}`); for (const p of pts) objLines.push(`v ${n3(p.x)} ${n3(yTop)} ${n3(p.y)}`); vIndex += 8; const [b0, b1, b2, b3] = [base, base + 1, base + 2, base + 3]; const [t0, t1, t2, t3] = [base + 4, base + 5, base + 6, base + 7]; objLines.push(`f ${t0} ${t3} ${t2} ${t1}`); // Top (+Y) objLines.push(`f ${b0} ${b1} ${b2} ${b3}`); // Bottom (-Y) objLines.push(`f ${b0} ${t0} ${t1} ${b1}`); objLines.push(`f ${b1} ${t1} ${t2} ${b2}`); objLines.push(`f ${b2} ${t2} ${t3} ${b3}`); objLines.push(`f ${b3} ${t3} ${t0} ${b0}`); }; 

Walls split cleanly into o Walls_Exterior, o Walls_Interior, o Glazing, per-room o Floor_<id>, and o Fixtures_And_Cabinetry (mapping ranges/fridges to appliance_steel, tubs/toilets to fixture_porcelain, beds/sofas to furniture_upholstery, and base/island millwork to cabinet_wood). Because everything lives in plain inches alongside our framing quantities, the exact same geometry also drives our free Wall Stud & Drywall Takeoff Calculator.

Try the 2D/3D Engine Live

You can test the 2D drafting canvas, real-time 3D auto-cutaway dollhouse view, and walkthrough camera free in your browser — no account or install required:

Drafting in 2D and live 3D is completely free (including 2 AI sketch/PDF scans per day). When you need clean unwatermarked exports, one-time passes start at $9 for scaled 1/4"=1'-0" PDF (A-101 + M-101), 2400px PNG, and vector SVG, or $19 for the full 5-sheet CAD package with 8-layer AutoCAD R12 .DXF, 3D .OBJ/.MTL, and takeoff .CSV — no subscription and a 14-day instant refund.

(Note: PlanCaliber is preliminary space-planning and CAD drafting software. Always verify dimensions, structural framing, and local building codes on site.)

原文:https://www.a8q9.cn/en/article/building-a-real-time-3d-architectural-cutaway-wavefront-obj-exporter-from-a-2d-f-5bf4d4.html

相关文章