Flatmate

How it works · packages/domain · editor · render

The geometric core

Every part of a Flatmate house is a shape on the plan plus a height range. From that one model the app derives rooms, mitred walls, collisions, a 3D view and vertical sections. This page shows how, with the data structures and the algorithms.

Try it

One model, three pictures

The plan, the 3D view and the section below are drawn from the same list of boxes: a footprint in metres and a bottom and top height. Turn the camera and move the cut line.

Plan, cut at 1.20 m
3D, orthographic, tilt 35°
Section A–A, looking north
This demo is a small stand-in written for this page, using the app's rules and values: walls facing the camera are hidden, colours are chosen on the CPU from a fixed light, the 3D picture is a software depth buffer with 2 × 2 samples per pixel, the shelf at 1.45 m is dashed on the plan because it sits above the cut, and the section fills dark only what the plane passes through. The app's own code is described in the sections that follow.

packages/domain/src/model.ts

The model

The core is not a solid-modelling kernel. It has no boundary representation, no curved surfaces and no boolean operations on solids. It is a planar graph of walls, convex footprints for everything else, and one interval of height for each part. That boundary is deliberate: the plan edits, the 3D view only shows.

Seventeen flat tables

A document is a set of tables of rows keyed by ID. Rows link to each other by ID, never by reference, and nothing derivable is stored.

type Joint     = { id, x, y }                    // metres, y up
type Wall      = { id, a: JointId, b: JointId,
                   thickness,                    // 0.05 to 0.50, default 0.20
                   base: "floor" | DeckId,
                   top:  "ceiling" | number | DeckId,
                   column: boolean }
type Opening   = { id, wall, kind, offset, width,
                   side, hinge, sill, head }     // offset from joint a
type LayoutObject = { id, kind, w, d, h, z }     // sizes per configuration
type Placement = { id, object, state, at, rotation,
                   config, deck: DeckId | null } // one per layout
type Deck      = { id, at, w, d, rotation, top, solid }
type Section   = { id: "A".."Z", a, b, side: 1 | -1, depth: number | null }

Conventions

units
metres, y up; heights, sizes, decks and sections are stored to the millimetre
rotation
whole degrees, counter-clockwise
front
a piece at rotation 0 faces −y
anchor
a piece's position is the middle of its back edge
EPS
0.001 m. Touching is not overlapping.
ceiling
2.50 m by default; flat, shed or gable
deck slab
0.12 m under a hollow deck's top

Where the geometry lives

web · server · mcpshells: Canvas2D, WebGL2, WebGPU, PDF, the tools Claude calls
@fm/renderbuffer format, shaders, triangulation, the software 3D rasteriser
@fm/editorpictures as data: the plan's primitives, 3D faces, sections
@fm/domainthe document, its rules and every geometric query. Pure synchronous functions.
@fm/protocolwire types and parsers

Queries are cached by document identity: a document is an immutable value, so a result stays right for as long as that document object lives.

export function memo<T>(fn: (doc: Document) => T): (doc: Document) => T {
  const cache = new WeakMap<Document, T>();
  return (doc) => {
    const hit = cache.get(doc);
    if (hit !== undefined) return hit;
    const value = fn(doc);
    cache.set(doc, value);
    return value;
  };
}

packages/domain/src/commands

An edit

Every change, from a person, a collaborator or Claude, is a command. A command never modifies its input. It returns a new document and a patch, or a refusal with a reason.

CommandmoveJoints, placeObject, addOpening … 70 types
Copyshallow copy of the tables; rows are shared
Changethe command's own rule, with snapping and splitting
Validatethe whole result against the invariants
Diffputs, deletes, previous values, dependencies

Commands that change walls, openings, pieces, decks, heights or sections validate the whole document, not only the rows they changed. That is the simple proof behind the product's first rule, that the drawing is always true: a ghost that is green can be placed, and a placed thing never needs a fix. Commands that only change names or appearance (room labels, layouts, sheets, options, wall and deck finishes, project fields) check their own rows instead.

The 26 invariants
IDRule
I1–I3A wall has two distinct existing joints, is at least 0.01 m long, and every joint is used.
I4No two joints within 1 mm of each other.
I5Walls meet only at a shared joint.
I6No joint lies on a wall it does not end.
I7No collinear overlap; no two walls on the same pair of joints.
I8Row shapes: IDs, finite numbers, names, finishes.
I9At least one layout; each object placed at most once per layout, at least once overall.
I10A piece lies inside one room or on its deck, clear of walls and decks in height.
I11No two pieces in one layout overlap in plan and in height.
I12Openings fit their wall in length and height; stacked ones keep 0.10 m between them.
I13Wall thickness between 0.05 and 0.50 m.
I14–I16Project fields, dimension anchors and the underlay row are well formed.
I17Ceiling and roof limits; walls and pieces stay under the ceiling.
I18Decks: sizes, over the building, clear of walls, not overlapping, under the ceiling.
I19Stairs: one equal copy per layout; the height matches the deck reached.
I20–I21Columns, and what a wall row may stand on and stop at.
I22Deck holes: at least 0.30 m, inside the deck, not overlapping.
I23–I24Sheets and the logo.
I25A section is one letter, at least 0.50 m long, depth not negative.
I26Named areas are sized and do not overlap.

queries/faces.ts · queries/zones.ts · queries/area.ts

Rooms from walls

Nobody draws a room. Rooms are the bounded faces of the planar graph that joints and floor walls make, found again after each edit.

Computed on this page with the same walk. Solid arrows are counter-clockwise walks: rooms. Dashed arrows are the clockwise walk round the outside of each wall group. The island's outside walk becomes a hole of the room around it. The stub wall is a bridge and belongs to no face.
  1. Collect the walls that stand on the floor. Walls on a loft never make rooms.
  2. Remove bridges, the walls that close no cycle, with an iterative Tarjan search in O(V + E).
  3. Make two half-edges per wall and sort each joint's outgoing half-edges by angle.
  4. Walk. Arriving at v along u→v, leave by the edge just clockwise of v→u. The interior stays on the left.
  5. Classify by signed area. At least 0.01 m² counter-clockwise is a room. Negative is an outside walk.
  6. Attach holes. Each outside walk goes to the smallest room of another wall group that contains its leftmost joint. Free columns become holes of the smallest room around their centre.
The turning rule at a joint of three walls. The outgoing list is sorted by angle; the walk finds the reverse edge at index i and leaves by index i − 1.

Step 6 can use one point per group because walls cannot cross: a wall group lies wholly inside or wholly outside each face of another group. The candidate rooms come from a coarse grid of bounding boxes, so a point is tested against a few faces, not all of them. An index of the same kind answers faceAt(doc, p), which room is under the pointer.

Two readings of thickness

Topology uses centrelines. Area and the drawn floor use the inner faces: each edge of the room's ring is offset inward by half of its own wall's thickness, corners are the intersections of neighbouring offset lines, and the footprints of holes are subtracted. If the offset ring folds or stops being simple, the room's area is reported as unavailable instead of guessed.

type Face = { key: string;                 // sorted wall IDs: stable across edits
              jointIds: string[]; wallIds: string[];
              ring: Point[];               // centreline, counter-clockwise
              holes: Hole[] };
type Zone = { face: Face; floor: Point[] | null;   // inset to the inner faces
              area: number | null; labelIds: string[]; holes: ZoneHole[] };

queries/outlines.ts

Wall bodies and mitred joints

A wall is stored as a centreline and a thickness. Its drawn body is computed joint by joint. At each joint the walls are sorted by angle, and each side of each wall meets the facing side of its neighbour.

Computed with the app's corner rule. Left: walls of 0.20 and 0.10 m. Each edge line is offset by its own half thickness, so both walls compute the same tip from the same two lines. Middle: a T. The through wall's halves meet straight, and every outline passes through the joint, which closes the triangle under the stem. Right: at a sharp angle the outer tip would run past four half-thicknesses, so it is bevelled.

The rule for one side of one wall, in order:

  1. Lone end: a square end at the joint.
  2. Straight through: flat. Equal walls share one edge; unequal walls show a step.
  3. Folding tip: if the two edge lines meet ahead of one wall and behind the other, both end flat.
  4. Bevel: on the outer side, when the tip lies more than 4 × the larger half thickness from the joint.
  5. Otherwise: the mitre tip, the intersection of the two offset edge lines.

On a short wall the two inner corners can reach past each other. Their reaches are then scaled in proportion so they meet.

Collision tests do not use these outlines. They use each wall's plain rectangle with square ends, which is convex and cheap. The mitred outlines feed drawing, the 3D solids, the roof's footprint and the stretch of a wall an opening may use.

geometry.ts · wall-pairs.ts

Valid walls

Walls may meet only at joints. Checking every pair is quadratic, so candidates come from one sort-and-sweep over bounding boxes. Joints go in as point boxes beside the walls' segment boxes, so one sweep serves all four wall invariants.

export function overlappingPairs(boxes: readonly Box[], margin: number): [number, number][] {
  const gap = 2 * margin;
  const order = boxes.map((box, i) => ({ box, i })).sort((p, q) => p.box.minX - q.box.minX);
  const pairs: [number, number][] = [];
  order.forEach(({ box: a, i }, k) => {
    for (let l = k + 1; l < order.length; l++) {
      const other = order[l];
      if (!other || other.box.minX > a.maxX + gap) break;      // sorted: nothing further can reach a
      const b = other.box;
      if (b.minY > a.maxY + gap || a.minY > b.maxY + gap) continue;
      pairs.push(i < other.i ? [i, other.i] : [other.i, i]);
    }
  });
  return pairs.sort((p, q) => p[0] - q[0] || p[1] - q[1]);     // the order an all-pairs loop would give
}

Each candidate pair is then tested exactly, and only when the two things overlap in height: a wall on a loft may cross above a wall on the floor.

InvariantTest on a candidate pair
I4 joints apartdistance between two joints under 1 mm
I5 no crossingsegment intersection at a point that is not a shared joint
I6 no joint on a walla joint within 1 mm of a centreline it does not end
I7 no overlapcollinear segments sharing more than 1 mm, or the same two joints

The sweep costs O(n log n) plus the pairs that overlap in x. It has no active set, so many boxes sharing one x range push it back toward quadratic.

shapes.ts · queries/footprints.ts · queries/fit.ts

Furniture and fit

A piece is a footprint, a rotation and a height range. Its footprint is one of seven outlines inscribed in its width × depth box, and each outline is given as convex parts so that every overlap test stays convex.

Six of the seven outlines (the seventh, pan, is a superellipse for toilets). The dot is the stored position: the middle of the back edge. The front faces down. Only the L is not convex, so it is tested as two rectangles.

Convex overlap: separating axes

Two convex polygons are apart if some edge normal of either one separates their projections. The 1 mm tolerance makes touching legal, which is what lets a wardrobe stand flush against a wall.

function convexOverlap(a, b, tol = EPS): boolean {
  for (const poly of [a, b]) {
    for (let i = 0; i < poly.length; i++) {
      const p = poly[i];
      const q = poly[(i + 1) % poly.length];
      const axis = p && q
        ? normalize(perpLeft(sub(q, p))) : null;
      if (!axis) continue;
      const [minA, maxA] = project(a, axis);
      const [minB, maxB] = project(b, axis);
      if (maxA <= minB + tol || maxB <= minA + tol)
        return false;             // a separating axis
    }
  }
  return true;
}

The fit check

Every wall rectangle, deck slab cell and convex piece part becomes a solid: a ring, a box and a height range. One sweep gives the candidate pairs. Two solids collide only when both tests say so:

plan:   convexOverlap(a.ring, b.ring)
height: a.bottom < b.top − EPS &&
        b.bottom < a.top − EPS

Then each piece must be under the ceiling and inside one room: the room under its centre must contain every vertex of its outline. A piece on a deck must stand on the slab instead, with a small allowed overhang on low platforms.

A few rules bend the test, each read from the piece's kind. These are the three you meet most. A rug overlaps any other piece. A chair tucks under a table: against a piece you can sit at, the chair's solid shrinks to its backrest strip, 0.10 m deep. An open stair has an underside, and whatever stays below it clears the stair.

The same sweep and the same overlap test drive the warnings. A use zone is a rectangle on a chosen side of a piece, a door swing a rectangle in front of a door, and each warns when a piece or a wall reaches into it between the surface the piece stands on and 1.20 m above it. Free floor is plain arithmetic: the room's clear area minus the area of each piece that stands below 1.20 m, with each tuck overlap added back once. A piece standing on a loft takes no floor from the room under it.

queries/vertical.ts · roof.ts · queries/levels.ts

Heights and the cut

The half dimension is one interval per part. A desk under a high shelf is two footprints that overlap on the plan and two ranges that do not, so it fits. The same ranges decide how the plan draws each thing.

An elevation above, the plan symbol each part gets below. The plan is a horizontal cut at 1.20 m, or at half the ceiling under a low one. A part is crossing, below or above the cut (or, on an upper level, under it and hidden), and each layer builder classifies it once, so the canvas, paper and Claude's picture agree.
export function relationToCut(range: Range, cut: number, base = 0): CutRelation {
  if (base > 0 && toMm(range.top) <= toMm(base)) return "under";   // upper levels: beneath the level's floor
  if (range.bottom >= cut - EPS) return "above";                   // dashed outline, no fill
  if (range.top <= cut + EPS) return "below";                      // a wall: thin outline. A piece: drawn whole
  return "crossing";                                               // a wall: filled
}

A ceiling is a minimum of planes

A flat ceiling is one plane, a shed one sloping plane, a gable two. The height at a point is the lowest of them, which makes the ridge without storing it. Because a minimum of planes is concave, the lowest ceiling over a polygon is found at its vertices alone.

The word "ceiling" in a row resolves in two ways. A full wall rises to the highest ceiling along it and is clipped to the slope when drawn. A piece, a deck or a door head must clear the lowest ceiling over its footprint.

A gable in section. The thin lines are the two planes; the bold line is their minimum. The wardrobe must fit under the lowest corner above it.

Decks and levels

A deck is a rotated rectangle with a top. A solid one fills from the floor; a hollow one is a 0.12 m slab with room below. Holes cut the rectangle along a grid, and the kept cells merge back into convex rectangles, so a deck with a stairwell still tests as convex parts. A deck whose top is at or above the floor's cut becomes a level of its own, viewed with its own cut.

packages/editor/src/view · packages/render

The plan picture

The editor never draws. It builds a picture as data, in metres, from five kinds of primitive. Every output reads that same picture, which is why the screen and the paper cannot drift apart.

type Width = { px: number } | { m: number };       // px: screen pixels, or millimetres on paper
type Primitive =
  | { kind: "segment"; a; b; width: Width; color; cap: "butt" | "round"; dash?: [on, off] }
  | { kind: "polygon"; points; holes; color }
  | { kind: "arc";     center; radius; from; to; width: Width; color }
  | { kind: "disc";    center; radius: Width; color }
  | { kind: "text";    text; at; size; color; align; rotation; font };
planPicturedocument, layout, level and cut, style, zoom
ScreenCanvas2D by default; WebGL2 and WebGPU on request
PaperSVG and PDF writers; PNG through Canvas2D
ClaudeSVG, then a PNG the model looks at

The canvas scene has eighteen layers in a fixed order, from the grid through floors, decks, pieces, walls and openings up to dimensions, marks and other people's cursors. Each layer builder remembers its last arguments and returns the same array when nothing it reads has changed. Everything downstream keys on that identity: a pan re-uploads nothing but the grid and the overlays.

The buffer the GPU reads

For WebGL2 and WebGPU each changed layer is encoded into one little-endian buffer: a header, then one section per kind. Polygons are triangulated on the CPU by ear clipping. Segments, arcs and discs are one instance each on a shared unit quad.

headermagic FMR1, version, count and offset per kind · 56 bytes
polygons6 floats per vertex · x y r g b a
segments13 floats per instance · a b width unit cap dash rgba
arcs11 floats
discs8 floats

A segment's fragment shader computes the distance to the line in pixels, a capsule for round caps and a box for butt caps, and turns it into coverage. That gives antialiased lines of any width without derivatives. Dashes discard fragments by distance along the segment, so a dash keeps its length on screen at any zoom; dash ends are cut hard. Polygon edges get only the context's multisampling, which is why a cut wall is drawn as a fill plus outline segments in the same colour.

// segment fragment shader. v_p: x along the segment from a, y across it, in CSS px.
float along  = clamp(v_p.x, 0.0, v_length);
float roundD = length(v_p - vec2(along, 0.0)) - v_halfWidth;
vec2  q      = vec2(abs(v_p.x - 0.5 * v_length) - 0.5 * v_length, abs(v_p.y) - v_halfWidth);
float buttD  = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
float d      = v_round == 1.0 ? roundD : buttD;
// Dashes start at a, like Canvas2D; their ends are cut without antialiasing.
if (v_dash.x > 0.0 && mod(max(v_p.x, 0.0), v_dash.x + v_dash.y) > v_dash.x) discard;
shade(d, v_color);     // coverage from the distance d, premultiplied

Text never enters the buffers. The core measures it with width tables for its two fonts, and the GPU renderers draw it on a Canvas2D overlay above the geometry.

packages/editor/src/view3d · packages/render

The 3D view

The 3D view is read-only and orthographic. It is built in four steps, and only the last one touches a graphics API.

Itemsfloors, walls, decks, guards and pieces, each with its range
Facesflat polygons with holes, a colour and an owner
Trianglesear clipping; x y z r g b per vertex, plus edge lines
Depth bufferWebGL2 in the app, a software rasteriser for Claude

Extrusion

The basic solid is a prism: a plan ring, a bottom and a top. Each edge of the ring gives one side quad with its outward normal, and the ring itself gives the top. A prism never gets a bottom face; only the roof slab draws its underside. Furniture is a handful of prisms per kind (boxes, twelve-sided cylinders, the piece's own outline) in the piece's local frame, with thin panels raised half a millimetre for doors and drawer fronts.

type Face3d = { points: Point3[]; holes: Point3[][]; color: string; owner: string;
                lines?: Line3d[];        // pattern joints drawn on the face
                outline?: false };       // an internal or seam face draws no edge

A wall with openings is one solid

A wall is not split into boxes around its doors and windows: touching boxes show seams and internal faces. Instead each long side is cut into a grid at every opening edge, sill and head, the cells an opening covers are dropped, and the boundary of the rest is traced into rings. A door comes out as a notch in the outer ring and a window as a hole. Reveals, sills and thresholds are added where a solid cell meets a gap.

One side of a wall 4.00 m long with a door and a window. Boundary edges are taken with the wall on their left and chained into loops: the outer ring runs counter-clockwise, the hole clockwise. The section cut reuses this same tracer.

Where a long wall was split at a joint, a second pass removes the seam: a wall face lying against another wall's face is marked internal, and faces that continue each other in one plane drop the edge they share.

Hidden walls

To see inside, an outside wall is left out when its outward normal points toward the camera. Walls with rooms on both sides always stay. The set changes only when the yaw crosses a wall's direction, so turning the view rarely rebuilds anything.

Colour without lighting

The shaders do no lighting. Each face gets its colour on the CPU when it is built: tops take the top shade, and a side is lit or shaded by the sign of one dot product with a light fixed in the world, from the north-west. Turning the camera never changes a face's colour.

const LIGHT = { x: −Math.SQRT1_2, y: Math.SQRT1_2 };
const sideShade = (n, shades) =>
  n.x * LIGHT.x + n.y * LIGHT.y > 0 ? shades.lit : shades.shaded;

The camera

Yaw and tilt give three rows. Two scale and centre the picture; the third is depth in metres. The scale comes from the 3D diagonal of the walls' box, floor to ceiling, so the house keeps its size and place at every angle. When the surroundings are shown, the picture is pulled back to 0.88 of that.

d       = (cos yaw, sin yaw)          // toward the camera
forward = (−d.x·cos t, −d.y·cos t, −sin t)
right   = (−d.y, d.x, 0)
up      = right × forward
k       = 2·(1 − 0.06) / |box diagonal|

row0 = k·right     row1 = k·up     row2 = forward

The default view is yaw 225° and tilt 35°. Tilt runs from 10° to 90°, where the view is the plan seen from above.

Two depth buffers, one uniform

Faces are triangulated by ear clipping after dropping the axis of the largest normal component, and each triangle is re-wound to agree with its face's normal so back-face culling works. Both renderers then read the same packed camera.

WebGL2, in the app. Depth test, back faces culled. Fills are drawn first with a polygon offset that pushes them slightly back; edges follow as one-pixel lines, still depth-tested, so an edge wins on its own face and hides behind nearer ones. Buffers upload once per scene: turning the camera changes four uniforms.

A software rasteriser, for Claude. The same vertex maths in TypeScript. A float depth buffer at twice the output size, three edge functions per sample with a top-left fill rule, depth from each triangle's plane equation, the same offset on fills, lines by stepping along their longer axis, then a 2 × 2 average down to the final picture.

The second renderer exists because Claude edits through tools on a server with no GPU, and needs to see the same house a person sees. A test in the project compares the two pictures pixel by pixel, and asks for at least 97 % of the pixels to agree within a small tolerance.

packages/editor/src/view3d/section-*.ts

Section cuts

A section is a stored line, a side to look toward and an optional depth. It is drawn from the same items as the 3D view and comes out as the same primitives as the plan, so the screen, the PDF sheet and Claude's picture share it. In the picture, x is the distance along the line and y is the height.

The cut

  1. Intersect. For each wall outline and deck slab, find where the line crosses the ring's edges and keep the stretches that lie inside. A stretch is tested a hair (10⁻⁷ m) to each side of the line.
  2. Give each stretch its height range. The result is a rectangle in the picture, with the wall's openings as gaps.
  3. Fill where both sides agree. All rectangle edges make a grid. A cell is filled when a body covers it a hair ahead of the plane and a body covers it a hair behind.
  4. Trace the filled cells into polygons with the wall tracer above. Touching walls, the floor band and the ceiling band become one dark shape with no seams.
  wall │ wall         a hair ahead: the right-hand wall
═══════╪═══════ plane
  wall │ wall         a hair behind: the left-hand wall     both sides have wall: it is cut

The both-sides rule settles the edge cases. A plane lying exactly on a wall's free face cuts nothing. A plane on the seam where two walls meet cuts both. A door cut across leaves a hole from the floor to its head with the lintel dark above; a window leaves a hole between sill and head, with the pane drawn in it.

Furniture the plane passes through is cut part by part and drawn light grey with an outline, so it never reads as structure. Under a sloped roof the dark shapes are clipped under the ceiling's planes, expressed in the section's own frame as z = a + b·x + c·depth.

Beyond the plane

What lies past the plane is shown in elevation. Each solid is clipped to a strip on the plan (between the line's ends, on the seen side, up to the depth) and becomes white rectangles with a thin outline. Openings show as flat panels, wall finishes as colour and pattern.

This is the one place the app still sorts far to near, since a vector picture has no depth buffer. The sort has no single depth key. Solids are compared in pairs: two solids that overlap in x and in height are ordered by which one a ray from the viewer meets first, the pairs make a graph, and a topological sort gives the drawing order. Solids that interlock can still form a cycle; one solid is then drawn out of turn.

The beyond is drawn first and the cut over it, so a wall the plane passes through always reads dark.

type SectionFrame = { origin: Point; dir: Point; seen: Point; length: number };
type Body  = { lo, hi, bottom, top, gaps: Span[] };       // a cut rectangle with openings
type Solid = { key; rings; spans; bottom; top };          // a thing beyond, for ordering
type SectionPicture = { primitives: Primitive[]; title: TextPrimitive };

Measured, and what is left out

Numbers and limits

WhatTimeSource
Validate a 312-wall document1.5 msmeasured for this page, warm median of 20
Find the rooms of 312 walls1.6 msmeasured for this page, warm median of 20
Move one joint among 312 walls, validated2.5 msmeasured for this page, warm median of 20
Move one joint among 5,100 walls, 200 chairs, 3 layouts122 msmeasured for this page, median of 5 in one run
Build one section picture0.5–2.1 msmeasured earlier, not repeated for this page

The measurements ran on one laptop with other work going on, so read them as orders of magnitude. A flat or a tiny house has tens of walls, not hundreds. The 5,100-wall grid is a stress test, and it is where whole-document validation starts to cost: at that size an edit pays for checks on walls it never touched.

What the core does not do

  • No curved walls, no sloped floors, no solids that are not a plan shape with a height range. Roofs are the one sloped surface, as planes.
  • The 3D view has no perspective, no shadows and no lighting beyond two side shades. It is in no file export.
  • Validation is whole-document on every geometric edit. It is not incremental.
  • Wall crossing tests use centrelines; collisions use square-ended rectangles, not the mitred outlines.
  • A section shows no floor finishes, no open door leaves and no hatching, and stairs appear only in elevation.

Drawn from the code in packages/domain, packages/editor and packages/render. Every drawing on this page is computed in the browser from coordinates in metres.