Skip to content

Building Shell ​

Building Shell, rendered in the brepjs playground
BIM · 209 lines▶ Run it in the playground

A garden studio as a BIM model: a foundation slab, four walls that meet at the corners, a door and three windows, a gable roof on the wall heads and an IfcSpace for the room, in a project, site, building and storey structure. The brick, the wall layers, the door leaf, the lintel bearing, the step up from the ground and the least roof pitch are published figures, and the kernel measures the volume of the room. The plan, the windows and the trim are a display model.

Code ​

This is the full program. The playground runs it in your browser without a change.

ts
import { BimModel, placedSolids, toIfc } from 'brepjs-bim';
import { box, clone, compound, cutAll, cylinder, extrude, fuseAll, getSolids, measureVolume, polygon, rotate, translate, unwrap } from 'brepjs/quick';
import { color, present } from 'brepjs/playground';

// Garden studio as a BIM model: a foundation slab, four walls that meet at the corners, a door and three windows,
// a gable roof on the wall heads and an IfcSpace for the room, in a project, site, building and storey structure.
// The brick, the wall layers, the door leaf, the lintel bearing, the step up from the ground and the least roof
// pitch are published figures. The plan, the windows and the trim are a display model.
// Units are millimetres. The ridge is along X, and the door is in the gable wall that looks to +X.
interface StudioParams {
  roofLift?: number; // 0 to 1: lifts the roof off the walls in the view
  pitch?: number; // roof pitch in degrees, 35 or more
  length?: number; // length of the building along the ridge
}

// ---- published figures
const BRICK = { length: 215, height: 65, joint: 10 }; // with its joint a brick takes 225 x 75 of the face
// Cavity wall, from the outside: a brick leaf, a cavity with insulation, a block leaf.
const LAYERS = [{ name: 'Facing brick', thicknessMm: 102.5 }, { name: 'Cavity with insulation', thicknessMm: 100 }, { name: 'Concrete block', thicknessMm: 100 }];
const LEAF = { width: 926, height: 2040, thickness: 44 }; // a standard door leaf
const BEARING = 150; // a lintel bears this much on each side
const STEP = 150; // the floor and the damp proof course are this far over the ground
const MIN_PITCH = 35; // plain tiles

// ---- display model
const COURSE = BRICK.height + BRICK.joint, T = LAYERS.reduce((sum, layer) => sum + layer.thicknessMm, 0);
const W = 4200, H = 32 * COURSE; // width of the plan, and 2400 of wall
const DOOR = { width: 1010, height: 2110 }, WINDOW = { height: 16 * COURSE, sill: 12 * COURSE };
const ROOF = { eave: 300, verge: 200, depth: 150, gauge: 250 };
const FRAME = { face: 60, depth: 80, back: 55, glass: 24 };
const COLORS = { wall: '#d08a68', roof: '#6f7b8a', timber: '#d3a956', stone: '#d8d2c4', frame: '#f5f2ea', leaf: '#12b5b0', glass: '#9fc3d4', metal: '#48515c', base: '#9a948a', floor: '#b89263', ground: '#7f9a62' };
type Tone = keyof typeof COLORS;
type P3 = [number, number, number];
type Body = ReturnType<typeof box>;
type Id = Extract<ReturnType<BimModel['addWall']>, { ok: true }>['value']; // the id of an element in the model
const X: P3 = [1, 0, 0], Y: P3 = [0, 1, 0], Z: P3 = [0, 0, 1];
// A wall as the openings see it: u goes along the wall, d goes from the outer face into the wall.
type Side = { along: 'x' | 'y'; from: number; face: number; into: 1 | -1 };

function studio({ roofLift = 0, pitch = MIN_PITCH, length = 6000 }: StudioParams = {}) {
  const model = new BimModel(), owned: { delete(): void }[] = [];
  const own = <T extends { delete(): void }>(s: T): T => { owned.push(s); return s; };
  try {
    model.init({ name: 'Building shell' });
    const site = unwrap(model.addSite({ name: 'Site' }));
    const building = unwrap(model.addBuilding({ name: 'Garden studio' }));
    const storey = unwrap(model.addStorey({ name: 'Ground floor', elevation: 0 }));
    const project = model.getProject();
    if (project) model.aggregate(project.localId, site);
    model.aggregate(site, building);
    model.aggregate(building, storey);
    const tones = new Map<Id, Tone>(), lifted = new Set<Id>();
    const put = (tone: Tone, made: ReturnType<BimModel['addWall']>): Id => {
      const id = unwrap(made);
      model.placeIn(id, storey);
      tones.set(id, tone);
      return id;
    };
    const L = Math.max(length, 3600), slope = Math.max(pitch, MIN_PITCH);

    // The foundation slab is 100 mm proud of the walls. Its top is the floor level, z = 0.
    put('base', model.addSlab({ length: L + 200, width: W + 200, thickness: 300, origin: [-100, -100, -300], axisX: X, axisZ: Z, predefinedType: 'BASESLAB', materialName: 'Concrete' }));

    // Four walls. The thickness of a wall is on the left of its axisX. The two long walls have the full length,
    // and the two gable walls fit between them, so the corners meet and do not double up.
    const wall = (origin: P3, axisX: P3, run: number): Id => put('wall', model.addWall({ length: run, height: H, thickness: T, origin, axisX, axisZ: Z, materialName: 'Brick', materialLayers: LAYERS, layerSetName: 'Cavity wall', isExternal: true }));
    const south = wall([0, 0, 0], X, L), north = wall([0, W - T, 0], X, L);
    const east = wall([L, T, 0], Y, W - 2 * T);
    wall([T, T, 0], Y, W - 2 * T);
    // The door and the windows name their host wall. The model cuts a void for each.
    const sides: Record<'south' | 'north' | 'east', Side> = { south: { along: 'x', from: 0, face: 0, into: 1 }, north: { along: 'x', from: 0, face: W, into: -1 }, east: { along: 'y', from: T, face: L, into: -1 } };
    const hosts = { south, north, east };
    const openings = [
      { host: 'east', door: true, at: (W - 2 * T - DOOR.width) / 2, width: DOOR.width, height: DOOR.height, sill: 0 },
      { host: 'south', door: false, at: 900, width: 1210, height: WINDOW.height, sill: WINDOW.sill },
      { host: 'south', door: false, at: L - 900 - 1210, width: 1210, height: WINDOW.height, sill: WINDOW.sill },
      { host: 'north', door: false, at: (L - 2410) / 2, width: 2410, height: WINDOW.height, sill: WINDOW.sill },
    ] as const;
    for (const o of openings) {
      const spec = { wallLocalId: hosts[o.host], width: o.width, height: o.height, offsetAlongWall: o.at, offsetFromFloor: o.sill, isExternal: true };
      put('frame', o.door ? model.addDoor({ ...spec, materialName: 'Timber' }) : model.addWindow({ ...spec, materialName: 'Timber' }));
    }

    // A gable roof on the wall heads. Its base is at z = H, and it goes past the walls at the eaves and the verges.
    const roof = put('roof', model.addRoof({ length: L + 2 * ROOF.verge, width: W + 2 * ROOF.eave, thickness: ROOF.depth, origin: [-ROOF.verge, -ROOF.eave, H], axisX: X, axisZ: Z, predefinedType: 'GABLE_ROOF', pitch: slope, materialName: 'Plain tile' }));
    lifted.add(roof);

    // The room is an IfcSpace: a volume in the model and in the IFC tree, with no solid in the view.
    const room = unwrap(model.addSpace({ name: 'Studio', length: L - 2 * T, width: W - 2 * T, height: H, origin: [T, T, 0], axisX: X, axisZ: Z, materialName: 'Air' }));
    model.placeIn(room, storey);

    const kit = { model, put, own, lifted, L, slope };
    const seats = fillOpenings(kit, openings.map((o) => ({ ...o, side: sides[o.host] })));
    trim(kit);

    // The view. placedSolids() gives each element in its place. The view cuts the lintel seats into the
    // walls, marks the tile courses on the roof, and lifts the roof and its trim when roofLift is not 0.
    const groups = Object.fromEntries(Object.keys(COLORS).map((tone) => [tone, []])) as unknown as Record<Tone, Body[]>;
    const all = new Map(model.getAllElements().map((el) => [el.localId, el]));
    const lintels = seats.flatMap((id) => unwrap(placedSolids(all.get(id)!)).map((body) => own(body)));
    const rad = slope * Math.PI / 180, ridge: P3 = [L / 2, W / 2, H + ROOF.depth + (W / 2 + ROOF.eave) * Math.tan(rad)];
    const run = (W / 2 + ROOF.eave) / Math.cos(rad);
    const groove = own(box(L + 2 * ROOF.verge + 2, 8, 14, { at: [0, 0, 0] }));
    const courses = [-1, 1].flatMap((side) => Array.from({ length: Math.floor(run / ROOF.gauge) }, (_, i) => {
      const s = (i + 0.5) * ROOF.gauge;
      return own(translate(own(rotate(groove, -side * slope, { axis: X })), [ridge[0], ridge[1] + side * s * Math.cos(rad), ridge[2] - s * Math.sin(rad)]));
    }));
    const lift = Math.min(Math.max(roofLift, 0), 1) * 1800;
    let spaceM3 = 0;
    for (const [id, el] of all) {
      if (id === room) spaceM3 = unwrap(placedSolids(el)).map((body) => own(body)).reduce((sum, body) => sum + unwrap(measureVolume(body)), 0) / 1e9;
      const tone = tones.get(id);
      if (!tone) continue;
      let placed: Body[] = unwrap(placedSolids(el)).map((body) => own(body));
      if (tone === 'wall') placed = placed.map((body) => own(unwrap(cutAll(body, lintels))) as Body);
      if (id === roof) placed = placed.map((body) => own(unwrap(cutAll(body, courses))) as Body);
      if (lifted.has(id) && lift > 0) placed = placed.map((body) => own(translate(body, [0, 0, lift])));
      groups[tone].push(...placed);
    }
    const shown = (Object.keys(COLORS) as Tone[]).filter((tone) => groups[tone].length > 0).map((tone) => color(compound(groups[tone]), COLORS[tone]));
    return { model, shown, spaceM3, floorM2: spaceM3 * 1e3 / H, byHand: (L - 2 * T) * (W - 2 * T) * H / 1e9 };
  } catch (error) {
    model[Symbol.dispose]();
    throw error;
  } finally {
    owned.splice(0).forEach((body) => body.delete());
  }
}

type Kit = { model: BimModel; put: (tone: Tone, made: ReturnType<BimModel['addWall']>) => Id; own: <T extends { delete(): void }>(s: T) => T; lifted: Set<Id>; L: number; slope: number };
type Opening = { side: Side; door: boolean; at: number; width: number; height: number; sill: number };

// What fills each opening: a lintel over it, a frame, glass or a door leaf, and a sill or a step. The lintel is an
// IfcBeam and the other parts are proxies. It gives back the lintels.
function fillOpenings({ model, put, own }: Kit, openings: Opening[]): Id[] {
  const one = (shape: Parameters<typeof getSolids>[0]): Body => unwrap(clone(getSolids(own(shape))[0]!)) as Body;
  const part = (tone: Tone, name: string, solid: Body, materialName: string): Id => put(tone, model.addProxy({ name, solid, materialName }));
  const lintels: Id[] = [];
  for (const { side, door, at, width, height, sill } of openings) {
    // A block in the wall of this opening: u along the wall from the opening, d into the wall, z from the floor.
    const block = (u0: number, u1: number, d0: number, d1: number, z0: number, z1: number): Body => {
      const a = side.from + at + (u0 + u1) / 2, b = side.face + side.into * (d0 + d1) / 2;
      return side.along === 'x' ? box(u1 - u0, d1 - d0, z1 - z0, { at: [a, b, (z0 + z1) / 2] }) : box(d1 - d0, u1 - u0, z1 - z0, { at: [b, a, (z0 + z1) / 2] });
    };
    const top = sill + height, depth = 3 * COURSE, mid = side.face + side.into * T / 2, start = side.from + at - BEARING;
    lintels.push(put('stone', model.addBeam({
      length: width + 2 * BEARING, profile: { kind: 'RECTANGULAR', width: T, height: depth },
      origin: side.along === 'x' ? [start, mid, top + depth / 2] : [mid, start, top + depth / 2], axisX: side.along === 'x' ? X : Y, axisZ: Z, predefinedType: 'LINTEL', materialName: 'Precast concrete',
    })));
    const f = FRAME.face, d0 = FRAME.back, d1 = d0 + FRAME.depth, g0 = (d0 + d1 - FRAME.glass) / 2;
    if (door) {
      const jamb = (width - LEAF.width) / 2 - 2, head = height - 18 - LEAF.height - 6, z0 = 18, l0 = jamb + 2, l1 = l0 + LEAF.width;
      part('frame', 'Door frame', one(unwrap(fuseAll([own(block(0, jamb, d0, d1, 0, height)), own(block(width - jamb, width, d0, d1, 0, height)), own(block(jamb, width - jamb, d0, d1, height - head, height))]))), 'Timber');
      part('metal', 'Threshold', block(jamb, width - jamb, d0 - 20, d1, 0, 15), 'Aluminium');
      // The leaf has four sunk panels and a glazed light on its outer face.
      const panels = [0, 1].flatMap((j) => [0, 1].map((k) => own(block(l0 + 110 + j * (LEAF.width - 110) / 2, l0 + (j + 1) * (LEAF.width - 110) / 2, d0 + 9, d0 + 18, z0 + 180 + k * 760, z0 + 180 + k * 760 + (k === 0 ? 640 : 520)))));
      const light = [l0 + 190, l1 - 190, z0 + 1560, z0 + LEAF.height - 180] as const;
      part('leaf', 'Door leaf', one(unwrap(cutAll(own(block(l0, l1, d0 + 10, d0 + 10 + LEAF.thickness, z0, z0 + LEAF.height)), [...panels, own(block(light[0], light[1], d0 + 9, d0 + 11 + LEAF.thickness, light[2], light[3]))]))), 'Timber, painted');
      part('glass', 'Door glazing', block(light[0], light[1], d0 + 22, d0 + 42, light[2], light[3]), 'Glass');
      part('metal', 'Door handle', one(unwrap(fuseAll([own(block(l1 - 90, l1 - 40, d0 - 2, d0 + 10, 960, 1040)), own(block(l1 - 190, l1 - 50, d0 - 40, d0 - 2, 992, 1008))]))), 'Steel');
      part('stone', 'Door step', block(-150, width + 150, -600, -100, -STEP, -10), 'Cast stone');
      continue;
    }
    // A window: a stone sill, a frame with a light for each 600 mm, and the glass.
    const s = COURSE, count = Math.max(1, Math.round(width / 600)), clear = (width - (count + 1) * f) / count;
    part('stone', 'Window sill', block(0, width, -60, T, sill, sill + s), 'Cast stone');
    const lights = Array.from({ length: count }, (_, i) => [f + i * (clear + f), f + i * (clear + f) + clear] as const);
    part('frame', 'Window frame', one(unwrap(cutAll(own(block(0, width, d0, d1, sill + s, top)), lights.map(([u0, u1]) => own(block(u0, u1, d0 - 1, d1 + 1, sill + s + f, top - f)))))), 'Timber');
    for (const [u0, u1] of lights) part('glass', 'Glazing', block(u0, u1, g0, g0 + FRAME.glass, sill + s + f, top - f), 'Glass');
  }
  return lintels;
}

// The trim: boards on the two gables, a ridge cap and a gutter on each eave, a timber floor, and the ground with a
// path to the door. The parts on the roof go up with it.
function trim({ model, put, own, lifted, L, slope }: Kit): void {
  const one = (shape: Parameters<typeof getSolids>[0]): Body => unwrap(clone(getSolids(own(shape))[0]!)) as Body;
  const part = (tone: Tone, name: string, solid: Body, materialName: string): Id => put(tone, model.addProxy({ name, solid, materialName }));
  const rad = slope * Math.PI / 180, tan = Math.tan(rad), top = H + ROOF.depth, rise = (W / 2 + ROOF.eave) * tan;
  for (const x of [-ROOF.verge - 22, L + ROOF.verge]) {
    // The boards leave the edge of the roof free: 120 mm in from the eaves, and a constant drop under the slopes.
    const inset = 120, y0 = -ROOF.eave + inset, y1 = W + ROOF.eave - inset, drop = inset / Math.cos(rad) - inset * tan;
    const face = own(unwrap(polygon([[x, y0, H + 30], [x, y1, H + 30], [x, y1, top + inset * tan - drop], [x, W / 2, top + rise - drop], [x, y0, top + inset * tan - drop]])));
    lifted.add(part('timber', 'Gable boards', unwrap(extrude(face, [22, 0, 0])) as Body, 'Timber'));
  }
  // The ridge cap lies on the two slopes.
  const half = 170, t = 18, zr = top + rise;
  const cap = own(unwrap(polygon([[0, W / 2 - half, zr - half * tan], [0, W / 2, zr], [0, W / 2 + half, zr - half * tan], [0, W / 2 + half, zr - half * tan + t / Math.cos(rad)], [0, W / 2, zr + t / Math.cos(rad)], [0, W / 2 - half, zr - half * tan + t / Math.cos(rad)]])));
  lifted.add(part('metal', 'Ridge cap', translate(own(unwrap(extrude(cap, [L + 2 * ROOF.verge, 0, 0])) as Body), [-ROOF.verge, 0, 0]), 'Clay'));
  for (const side of [-1, 1]) {
    const y = W / 2 + side * (W / 2 + ROOF.eave + 60);
    const channel = one(unwrap(cutAll(own(box(L + 2 * ROOF.verge, 120, 75, { at: [L / 2, y, H + 60] })), [own(box(L + 2 * ROOF.verge - 12, 108, 75, { at: [L / 2, y, H + 66] }))])));
    lifted.add(part('metal', 'Gutter', channel, 'Aluminium'));
  }
  put('floor', model.addCovering({ length: L - 2 * T, width: W - 2 * T, thickness: 20, origin: [T, T, 0], axisX: X, axisZ: Z, predefinedType: 'FLOORING', materialName: 'Oak boards' }));
  // The ground is 150 mm under the floor. An opening in it takes the foundation slab.
  const ground = put('ground', model.addSlab({ length: L + 4200, width: W + 2600, thickness: 100, origin: [-1300, -1300, -STEP - 100], axisX: X, axisZ: Z, predefinedType: 'BASESLAB', materialName: 'Topsoil' }));
  unwrap(model.addSlabOpening({ slabLocalId: ground, offsetX: 1200, offsetY: 1200, sizeX: L + 200, sizeY: W + 200 }));
  for (let i = 0; i < 3; i++) part('stone', 'Paving slab', box(600, 900, 40, { at: [L + 950 + i * 640, W / 2, -STEP + 20] }), 'Cast stone');
}

// Try studio({ roofLift: 1 }), studio({ pitch: 45 }) or studio({ length: 8000 }).
const scene = studio();
console.log('Room: the kernel measures ' + scene.spaceM3.toFixed(2) + ' m3 in the IfcSpace, which is ' + scene.floorM2.toFixed(2) + ' m2 of floor. Length x width x height gives ' + scene.byHand.toFixed(2) + ' m3.');
// The tree panel shows the IFC structure. The IFC button saves the model as a file.
export default present(scene.shown, {
  bimTree: scene.model.toTreeSummary(),
  ifc: async () => unwrap(await toIfc(scene.model, { applicationName: 'brepjs playground', applicationVersion: '1.0' })),
});

Functions used ​

placedSolids toIfc box clone compound cutAll cylinder extrude fuseAll getSolids measureVolume polygon rotate translate unwrap color present

▶ Run Building Shell in the playground

Released under the Apache 2.0 License.