first push

This commit is contained in:
jhartworks committed 2026-11-09 10:37:41 +01:00
commit 2a81b4a502
845 files changed
+356635

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { emptyBuilding, newFloor, type RoofSection } from "../model.ts";
import { sectionProfile, sectionUV } from "../roof/frame.ts";
import { GROUND, fieldFace, groundFace, groundFloor, roofFaces, topFloor, wallFaces } from "./faces.ts";
import { cottage, field, near } from "./fixtures.ts";
const section = (patch: Partial<RoofSection> = {}): RoofSection => ({ id: "s", x0: 0, z0: 0, x1: 12, z1: 8, shape: "gable", axis: "x", eave_a: 3, eave_b: 3, pitch_a: 40, pitch_b: 40, base: 3, overhang: 0, ...patch });
test("no roof, no faces", () => {
assert.deepEqual(roofFaces(cottage({ type: "none", pitch: 35, overhang: 0.4 })), []);
assert.deepEqual(roofFaces(emptyBuilding()), []);
});
test("a gable roof has two slopes with the roof's pitch that face away from each other", () => {
const faces = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5 }));
assert.deepEqual(faces.map((f) => f.key), ["main:a", "main:b"]);
for (const f of faces) {
near(f.pitch, 30);
assert.ok(f.n[1] > 0, "normals point up");
assert.equal(f.flat, false);
}
assert.ok(faces[0].facing[1] * faces[1].facing[1] < 0, "opposite directions across the ridge");
// each slope reaches the ridge: half of 7 + 2 × 0.8 m of depth, along the slope
near(faces[0].ls, (7 + 2 * 0.8) / 2 / Math.cos((30 * Math.PI) / 180));
});
test("the ridge of the single roof can run along the short side", () => {
const long = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5 }))[0];
const short = roofFaces(cottage({ type: "gable", pitch: 30, overhang: 0.5, ridge: "short" }))[0];
assert.ok(long.lu > short.lu);
});
test("a flat roof is one level face sitting on the slab", () => {
const [face] = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }));
assert.equal(face.key, "main:top");
assert.equal(face.flat, true);
near(face.o[1], 2.6 + 0.25);
near(face.lu, 12 + 2 * 0.8);
});
test("a mansard has a lower and an upper face per side, and both lie on the roof as it is drawn", () => {
for (const patch of [{ shape: "mansard" as const, pitch_a: 70, pitch_b: 70 }, { shape: "mansard" as const, pitch_a: 75, pitch_b: 60, eave_b: 2.5, flip: true, overhang: 0.4 }]) {
const s = section(patch);
const faces = roofFaces(cottage({ type: "custom", pitch: 35, overhang: 0, sections: [s] }));
assert.deepEqual(faces.map((f) => f.key), ["s:a", "s:au", "s:b", "s:bu"]);
near(faces[0].pitch, s.pitch_a);
near(faces[1].pitch, 30, 1e-3);
const profile = sectionProfile(s);
for (const f of faces) {
assert.ok(f.n[1] > 0, "normals point up");
for (const [ku, ks] of [[0.1, 0], [0.5, 0.5], [0.9, 1]]) {
const p = [0, 1, 2].map((i) => f.o[i] + f.eu[i] * f.lu * ku + f.es[i] * f.ls * ks);
const [, v] = sectionUV(s, p[0], p[2]);
near(p[1], profile.y(v), 1e-6);
}
}
}
});
test("sections of a custom roof give their own faces: a hip adds two end triangles, a pyramid has four faces in all", () => {
const roof = (s: RoofSection) => {
const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [s] });
return roofFaces(b);
};
assert.deepEqual(roof(section()).map((f) => f.key), ["s:a", "s:b"]);
assert.deepEqual(roof(section({ shape: "hip" })).map((f) => f.key), ["s:a", "s:b", "s:c", "s:d"]);
assert.equal(roof(section({ shape: "pyramid", x1: 8 })).length, 4);
assert.deepEqual(roof(section({ shape: "pent" })).map((f) => f.key), ["s:a"]);
assert.deepEqual(roof(section({ shape: "flat" })).map((f) => f.key), ["s:top"]);
});
test("a hip slope narrows towards the ridge", () => {
const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [section({ shape: "hip", x1: 14 })] });
const slope = roofFaces(b)[0];
const [low0, low1] = slope.span(0);
const [high0, high1] = slope.span(slope.ls * 0.9);
assert.ok(high1 - high0 < low1 - low0);
});
test("walls: outer faces of an outer wall, both faces of a free wall, nothing for short walls", () => {
const b = cottage({ type: "none", pitch: 0, overhang: 0 });
const faces = wallFaces(b);
assert.equal(faces.length, 4);
assert.ok(faces.every((f) => f.wall?.floorId === "g" && f.pitch === 90 && f.n[1] === 0));
assert.equal(wallFaces(b, "nothing").length, 0);
// the outer face looks away from the house centre
for (const f of faces) {
const centre: [number, number] = [6, 3.5];
const middle: [number, number] = [f.o[0] + f.eu[0] * f.lu / 2, f.o[2] + f.eu[2] * f.lu / 2];
const away = (middle[0] - centre[0]) * f.n[0] + (middle[1] - centre[1]) * f.n[2];
assert.ok(away > 0, f.key);
}
});
test("the top floor is the highest with rooms; the ground floor skips a cellar", () => {
const b = emptyBuilding();
const cellar = newFloor("c", "Cellar", -2.6);
const ground = newFloor("g", "Ground", 0);
const upper = newFloor("u", "Upper", 2.7);
const empty = newFloor("e", "Empty", 5.4);
const room = { id: "r", name: "R", area_id: null, points: [[0, 0], [4, 0], [4, 4], [0, 4]] as [number, number][], floor_material: "wood" as const };
[cellar, ground, upper].forEach((f) => (f.rooms = [room]));
b.floors = [cellar, ground, upper, empty];
assert.equal(topFloor(b)?.id, "u");
assert.equal(groundFloor(b)?.id, "g");
assert.equal(topFloor(emptyBuilding()), null);
});
test("the ground face is level, unbounded and turns with the field", () => {
const b = cottage({ type: "none", pitch: 0, overhang: 0 });
const face = groundFace(b, { u: 3, v: 2, rotation: 90, base: null });
assert.equal(face.unbounded, true);
assert.equal(face.key, GROUND);
near(face.eu[2], 1);
near(face.es[0], -1);
assert.deepEqual(face.n, [0, 1, 0]);
// a field on its own surface height sits there
assert.equal(groundFace(b, { u: 0, v: 0, rotation: null, base: 2.6 }).o[1], 2.6);
});
test("a field's face is found by its key; a vanished roof face gives null", () => {
const b = cottage({ type: "gable", pitch: 30, overhang: 0.5 });
assert.equal(fieldFace(b, field("main:b"))?.key, "main:b");
assert.equal(fieldFace(b, field("gone:a")), null);
assert.equal(fieldFace(b, field(GROUND))?.unbounded, true);
const wall = wallFaces(b)[0];
assert.equal(fieldFace(b, field(wall.key))?.key, wall.key);
});
+268
View File
@@ -0,0 +1,268 @@
// The surfaces solar fields can lie on: the faces of roof sections, a single roof, house walls, and the garden ground.
//
// A face has a local frame. u runs along the eave (0 to lu), s up the slope from the eave (0 to ls, true length); on a
// flat roof s runs across, level. A field's u and v place its lower left corner on the face.
import { generateWalls } from "../geometry/walls.ts";
import { outdoorGround, type Building, type Floor, type RoofSection, type SolarField } from "../model.ts";
import { sectionFrame, sectionOverhang, sectionProfile } from "../roof-sections.ts";
import { gradient, mansardParts } from "../roof/frame.ts";
import { cross, DEG, length, normalize, sub, type V3 } from "./vec.ts";
/** Thickness of a flat roof slab as the roof draws it. */
export const FLAT_SLAB = 0.25;
export interface RoofFace {
/**
* "main:a", "main:b", "main:top" for the single roof; "<section id>:a", ":b", ":top" for sections; hip ends are ":c"
* (start) and ":d" (end). A mansard's ":a"/":b" are the steep lower slopes, ":au"/":bu" the upper ones above the break.
*/
key: string;
/** The section the face belongs to (null: the single roof). */
section: string | null;
side: "a" | "b" | "c" | "d" | "top";
flat: boolean;
/** The eave corner (heights above the ground), unit vectors along the eave and up the slope, and the normal. */
o: V3;
eu: V3;
es: V3;
n: V3;
lu: number;
ls: number;
/** Slope in degrees (0 on a flat roof). */
pitch: number;
/** The usable range along the eave at a distance up the slope (hip roofs narrow towards the ridge). */
span(s: number): [number, number];
/** The plan direction the face looks to (down the slope); for a flat roof the direction of +s. */
facing: [number, number];
/** The garden ground: no edges, a field goes where it is put. */
unbounded?: boolean;
/** A house wall: upright, on this floor. Modules hang flat on the facade. */
wall?: { floorId: string };
}
/** A face made of a flat slab, as seen from above. */
function flatFace(id: string, section: string | null, x0: number, z0: number, x1: number, z1: number, y: number): RoofFace {
// u along the longer side, s across
const alongX = x1 - x0 >= z1 - z0;
const lu = alongX ? x1 - x0 : z1 - z0;
return {
key: `${id}:top`,
section,
side: "top",
flat: true,
o: [x0, y, z0],
eu: alongX ? [1, 0, 0] : [0, 0, 1],
es: alongX ? [0, 0, 1] : [1, 0, 0],
n: [0, 1, 0],
lu,
ls: alongX ? z1 - z0 : x1 - x0,
pitch: 0,
span: () => [0, lu],
facing: alongX ? [0, 1] : [1, 0],
};
}
/** The upward normal of the plane spanned by two edge directions. */
function upwardNormal(eu: V3, es: V3): V3 {
const n = normalize(cross(eu, es));
return n[1] < 0 ? [-n[0], -n[1], -n[2]] : n;
}
/** The plan direction a slope looks to, from its up-the-slope direction. */
const lookingDown = (es: V3): [number, number] => {
const down = normalize([-es[0], 0, -es[2]]);
return [down[0], down[2]];
};
function slopeFace(key: string, section: string | null, side: "a" | "b", o: V3, eaveEnd: V3, ridge: V3, pitch: number, span: (s: number) => [number, number]): RoofFace {
const eu = normalize(sub(eaveEnd, o));
const es = normalize(sub(ridge, o));
return { key, section, side, flat: false, o, eu, es, n: upwardNormal(eu, es), lu: length(sub(eaveEnd, o)), ls: length(sub(ridge, o)), pitch, span, facing: lookingDown(es) };
}
/**
* A triangular face (a hip end): the eave from `o` to `eaveEnd`, rising to `apex`. The slope frame is the plane's own,
* with s at a right angle to the eave, and the usable span narrows linearly towards the apex.
*/
function triangleFace(key: string, section: string, side: "c" | "d", o: V3, eaveEnd: V3, apex: V3): RoofFace | null {
const lu = length(sub(eaveEnd, o));
if (lu < 0.3) return null;
const eu = normalize(sub(eaveEnd, o));
const toApex = sub(apex, o);
const along = toApex[0] * eu[0] + toApex[1] * eu[1] + toApex[2] * eu[2];
const rise: V3 = [toApex[0] - eu[0] * along, toApex[1] - eu[1] * along, toApex[2] - eu[2] * along];
const ls = length(rise);
if (ls < 0.3) return null;
const es = normalize(rise);
const span = (s: number): [number, number] => {
const k = Math.min(1, Math.max(0, s / ls));
return [along * k, lu - (lu - along) * k];
};
return { key, section, side, flat: false, o, eu, es, n: upwardNormal(eu, es), lu, ls, pitch: Math.atan2(es[1], Math.hypot(es[0], es[2])) / DEG, span, facing: lookingDown(es) };
}
type Overhang = { u0: number; u1: number; a: number; b: number };
/** The faces of one section as the roof draws them, with overhang at the eaves and gable ends (none where a taller part of the house stands). */
function sectionFaces(s: RoofSection, overhang: Overhang): RoofFace[] {
const frame = sectionFrame(s);
const profile = sectionProfile(s);
const at = (u: number, v: number, y: number): V3 => {
const [x, z] = frame.at(u, v);
return [x, y, z];
};
const [ovA, ovB] = [Math.max(0, overhang.a), Math.max(0, overhang.b)];
const U0 = frame.u0 - Math.max(0, overhang.u0);
const U1 = frame.u1 + Math.max(0, overhang.u1);
const width = U1 - U0;
const yA = profile.y(-ovA);
const yB = profile.y(frame.w + ovB);
if (s.shape === "flat" || s.shape === "parapet") {
const [p, q] = [frame.at(U0, -ovA), frame.at(U1, frame.w + ovB)];
return [flatFace(s.id, s.id, Math.min(p[0], q[0]), Math.min(p[1], q[1]), Math.max(p[0], q[0]), Math.max(p[1], q[1]), s.eave_a + FLAT_SLAB)];
}
if (s.shape === "pent") return [slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA, yA), at(U1, -ovA, yA), at(U0, frame.w + ovB, yB), s.pitch_a, () => [0, width])];
if (s.shape === "mansard") return mansardFaces(s, frame, U0, U1, ovA, ovB);
// a pyramid is a hip whose ridge has no length; a half-hip places its modules like a gable
const isHip = s.shape === "hip" || s.shape === "pyramid";
const half = (frame.u1 - frame.u0) / 2;
const run = s.shape === "pyramid" ? half : isHip ? Math.min(half, Math.min(profile.vr, frame.w - profile.vr) || frame.w / 2) : 0;
// a hip slope narrows from the full eave (overhang included) to the ridge, which starts `run` in from the walls
const inset0 = isHip ? frame.u0 + run - U0 : 0;
const inset1 = isHip ? U1 - (frame.u1 - run) : 0;
const faces: RoofFace[] = [];
if (profile.vr > 0.3) {
const slope = Math.hypot(profile.vr + ovA, profile.rh - yA);
faces.push(slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA, yA), at(U1, -ovA, yA), at(U0, profile.vr, profile.rh), s.pitch_a, (t) => [inset0 * (t / slope), width - inset1 * (t / slope)]));
}
if (frame.w - profile.vr > 0.3) {
const slope = Math.hypot(frame.w + ovB - profile.vr, profile.rh - yB);
// side b: the eave at v = w + overhang, running the other way so the face looks outwards
faces.push(slopeFace(`${s.id}:b`, s.id, "b", at(U1, frame.w + ovB, yB), at(U0, frame.w + ovB, yB), at(U1, profile.vr, profile.rh), s.pitch_b, (t) => [inset1 * (t / slope), width - inset0 * (t / slope)]));
}
if (isHip) {
const startEnd = triangleFace(`${s.id}:c`, s.id, "c", at(U0, frame.w + ovB, yB), at(U0, -ovA, yA), at(frame.u0 + run, profile.vr, profile.rh));
const finishEnd = triangleFace(`${s.id}:d`, s.id, "d", at(U1, -ovA, yA), at(U1, frame.w + ovB, yB), at(frame.u1 - run, profile.vr, profile.rh));
faces.push(...[startEnd, finishEnd].filter((f): f is RoofFace => f !== null));
}
return faces;
}
/**
* A mansard breaks each side at a kink: the steep lower slope from the eave to the break, then the flatter upper slope
* to the ridge. One plane from eave to ridge would cut under the break, so each part is a face of its own.
*/
function mansardFaces(s: RoofSection, frame: ReturnType<typeof sectionFrame>, U0: number, U1: number, ovA: number, ovB: number): RoofFace[] {
const m = mansardParts(frame.w, s.eave_a, s.eave_b, gradient(s.pitch_a), gradient(s.pitch_b));
const at = (u: number, v: number): V3 => {
const [x, z] = frame.at(u, v);
return [x, m.y(v), z];
};
const width = U1 - U0;
const span = (): [number, number] => [0, width];
const upperPitch = (rise: number, run: number) => Math.atan2(rise, run) / DEG;
const faces: RoofFace[] = [];
const [wb, bb] = [frame.w + ovB, frame.w - m.vlb];
if (m.vla + ovA > 0.3) faces.push(slopeFace(`${s.id}:a`, s.id, "a", at(U0, -ovA), at(U1, -ovA), at(U0, m.vla), s.pitch_a, span));
if (m.vr - m.vla > 0.3) faces.push(slopeFace(`${s.id}:au`, s.id, "a", at(U0, m.vla), at(U1, m.vla), at(U0, m.vr), upperPitch(m.rh - m.yla, m.vr - m.vla), span));
// side b: eaves at v = w + overhang, running the other way so the faces look outwards
if (m.vlb + ovB > 0.3) faces.push(slopeFace(`${s.id}:b`, s.id, "b", at(U1, wb), at(U0, wb), at(U1, bb), s.pitch_b, span));
if (bb - m.vr > 0.3) faces.push(slopeFace(`${s.id}:bu`, s.id, "b", at(U1, bb), at(U0, bb), at(U1, m.vr), upperPitch(m.rh - m.ylb, bb - m.vr), span));
return faces;
}
/** The floor the single roof sits on: the highest with rooms. */
export function topFloor(b: Building): Floor | null {
const withRooms = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3));
return withRooms.sort((p, q) => q.elevation - p.elevation)[0] ?? null;
}
/** Every roof face modules can lie on. */
export function roofFaces(b: Building): RoofFace[] {
const roof = b.settings.roof;
if (!roof || roof.type === "none") return [];
if (roof.type === "custom") return (roof.sections ?? []).flatMap((s) => sectionFaces(s, sectionOverhang(b, s, s.overhang ?? roof.overhang)));
const floor = topFloor(b);
if (!floor) return [];
const xs = floor.rooms.flatMap((r) => r.points.map((p) => p[0]));
const zs = floor.rooms.flatMap((r) => r.points.map((p) => p[1]));
const margin = b.settings.wall_exterior + roof.overhang;
const [x0, x1] = [Math.min(...xs) - margin, Math.max(...xs) + margin];
const [z0, z1] = [Math.min(...zs) - margin, Math.max(...zs) + margin];
const top = floor.elevation + floor.height;
if (roof.type === "flat") return [flatFace("main", null, x0, z0, x1, z1, top + FLAT_SLAB)];
// a gable, as the roof builds it: the ridge along the longer side (or the shorter one)
const longerAlongX = x1 - x0 >= z1 - z0;
const alongX = roof.ridge === "short" ? !longerAlongX : longerAlongX;
const halfWidth = (alongX ? z1 - z0 : x1 - x0) / 2;
const rise = halfWidth * Math.tan(roof.pitch * DEG);
const point = (u: number, v: number, y: number): V3 => (alongX ? [u, top + y, (z0 + z1) / 2 + v] : [(x0 + x1) / 2 + v, top + y, u]);
const [u0, u1] = alongX ? [x0, x1] : [z0, z1];
const span = () => [0, u1 - u0] as [number, number];
return [
slopeFace("main:a", null, "a", point(u0, -halfWidth, 0), point(u1, -halfWidth, 0), point(u0, 0, rise), roof.pitch, span),
slopeFace("main:b", null, "b", point(u0, halfWidth, 0), point(u1, halfWidth, 0), point(u0, 0, rise), roof.pitch, span),
];
}
/** The outer faces of the house walls per floor: modules can hang on a facade or balcony. */
export function wallFaces(b: Building, floorId?: string): RoofFace[] {
const faces: RoofFace[] = [];
for (const floor of b.floors.filter((f) => !floorId || f.id === floorId)) {
const { walls } = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }, floor.walls ?? []);
for (const wall of walls) {
// outer walls: the outer face; free-standing walls (garden wall, fence wall): both faces
if (!wall.exterior && !wall.free) continue;
const [dx, dz] = [wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]];
const l = Math.hypot(dx, dz);
if (l < 1.2) continue;
// outer walls have their room on the left, so the outer face is on the right
const [nx, nz] = [dz / l, -dx / l];
// a sloping wall offers its lower end
const height = Math.min(floor.height, wall.height ?? floor.height, wall.heightEnd ?? Infinity);
const addFace = (key: string, o: V3, eu: V3, n: V3) =>
faces.push({ key, section: null, side: "top", flat: false, o, eu, es: [0, 1, 0], n, lu: l, ls: height, pitch: 90, span: () => [0, l], facing: [n[0], n[2]], wall: { floorId: floor.id } });
addFace(`wall:${floor.id}:${wall.id}`, [wall.a[0] + nx * wall.right, floor.elevation, wall.a[1] + nz * wall.right], [dx / l, 0, dz / l], [nx, 0, nz]);
// the back of a free wall runs the other way, so its modules face outwards too
if (wall.free) addFace(`wall:${floor.id}:${wall.id}:back`, [wall.b[0] - nx * wall.left, floor.elevation, wall.b[1] - nz * wall.left], [-dx / l, 0, -dz / l], [-nx, 0, -nz]);
}
}
return faces;
}
/** The face key of fields standing in the garden. */
export const GROUND = "ground";
/** The floor whose garden ground-mounted fields stand in: the lowest with rooms at ground level (a cellar is passed over), else the lowest with rooms. */
export function groundFloor(b: Building): Floor | null {
const withRooms = b.floors.filter((f) => f.rooms.some((r) => r.points.length >= 3)).sort((p, q) => p.elevation - q.elevation);
return withRooms.find((f) => f.elevation > -0.5) ?? withRooms[0] ?? b.floors[0] ?? null;
}
/**
* The ground under a garden field: level, turned by the field's rotation. u and v are plan coordinates along the turned
* axes, so the corner of a field lies at u * (cos r, sin r) + v * (-sin r, cos r).
*/
export function groundFace(b: Building, f: Pick<SolarField, "u" | "v" | "rotation" | "base">): RoofFace {
const r = (f.rotation ?? 0) * DEG;
const eu: V3 = [Math.cos(r), 0, Math.sin(r)];
const es: V3 = [-Math.sin(r), 0, Math.cos(r)];
const floor = groundFloor(b);
const x = eu[0] * f.u + es[0] * f.v;
const z = eu[2] * f.u + es[2] * f.v;
// on a surface of its own height (a flat garage roof), else on the ground (a terrace raises it)
const y = floor ? floor.elevation + (f.base != null ? f.base : outdoorGround(floor, x, z)) : (f.base ?? 0);
return { key: GROUND, section: null, side: "top", flat: true, o: [0, y, 0], eu, es, n: [0, 1, 0], lu: 1e4, ls: 1e4, pitch: 0, span: () => [-1e4, 1e4], facing: [es[0], es[2]], unbounded: true };
}
/** The face a field lies on: a roof face, a wall, or the ground in the garden. Null when its roof face is gone. */
export function fieldFace(b: Building, f: SolarField, faces: readonly RoofFace[] = roofFaces(b)): RoofFace | null {
if (f.face === GROUND) return groundFace(b, f);
if (f.face.startsWith("wall:")) return wallFaces(b, f.face.split(":")[1]).find((x) => x.key === f.face) ?? null;
return faces.find((x) => x.key === f.face) ?? null;
}
+165
View File
@@ -0,0 +1,165 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { roofFaces, wallFaces, type RoofFace } from "./faces.ts";
import { MODULE_GAP, MODULE_H, MODULE_W, LIFT, clampField, fieldCenter, fieldModules, fieldPlan, fieldSize, moduleSize, rowCounts, rowPitch, windowAsField, windowCorners } from "./fields.ts";
import { cottage, field, near } from "./fixtures.ts";
import { GROUND, groundFace } from "./faces.ts";
const slope = (): RoofFace => roofFaces(cottage({ type: "gable", pitch: 35, overhang: 0.5 }))[1];
const flat = (): RoofFace => roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0];
test("modules are portrait by default and turn when landscape, own sizes win", () => {
assert.deepEqual(moduleSize({ portrait: true }), [MODULE_W, MODULE_H]);
assert.deepEqual(moduleSize({ portrait: false }), [MODULE_H, MODULE_W]);
assert.deepEqual(moduleSize({ portrait: true, module_w: 1, module_h: 2 }), [1, 2]);
});
test("rows: the same count in each, or the layout's own lengths, kept within limits", () => {
assert.deepEqual(rowCounts({ rows: 3, cols: 2 }), [2, 2, 2]);
assert.deepEqual(rowCounts({ rows: 0, cols: 0 }), [1]);
assert.deepEqual(rowCounts({ rows: 9, cols: 9, layout: [4, 4, 3, 99, -2] }), [4, 4, 3, 60, 0]);
});
test("on a slope the rows follow each other module by module; on flat ground they leave space against shading", () => {
near(rowPitch(slope(), field("x")), MODULE_H + MODULE_GAP);
assert.ok(rowPitch(flat(), field("x", { tilt: 20 })) > rowPitch(slope(), field("x")) * 0.9);
assert.ok(rowPitch(flat(), field("x", { tilt: 30 })) > rowPitch(flat(), field("x", { tilt: 10 })));
});
test("a field's size grows with its longest row and its row count", () => {
const f = slope();
const [w1, d1] = fieldSize(f, field("x", { rows: 1, cols: 2 }));
near(w1, 2 * MODULE_W + MODULE_GAP);
near(d1, MODULE_H);
const [w2, d2] = fieldSize(f, field("x", { rows: 3, cols: 2, layout: [2, 4, 3] }));
near(w2, 4 * MODULE_W + 3 * MODULE_GAP);
assert.ok(d2 > d1 * 2.5);
});
test("modules lie 7 cm above the slope", () => {
const face = slope();
const [first] = fieldModules(face, field(face.key));
for (const corner of first.corners) {
const q = [corner[0] - face.o[0], corner[1] - face.o[1], corner[2] - face.o[2]];
const above = q[0] * face.n[0] + q[1] * face.n[1] + q[2] * face.n[2];
near(above, LIFT, 1e-9);
}
assert.deepEqual(first.posts, []);
});
test("a module that would leave the face is left out; switched-off cells only show when asked for", () => {
const face = slope();
assert.equal(fieldModules(face, field(face.key, { u: face.lu - MODULE_W, cols: 2 })).length, 1);
const switched = field(face.key, { cols: 3, skip: ["0:1"] });
assert.equal(fieldModules(face, switched).length, 2);
const all = fieldModules(face, switched, true);
assert.equal(all.length, 3);
assert.deepEqual(all.filter((m) => m.skipped).map((m) => m.cell), ["0:1"]);
});
test("shorter rows sit left, centred or right under the longest one", () => {
const face = slope();
const first = (align: "left" | "center" | "right") => fieldModules(face, field(face.key, { layout: [4, 2], align, u: 0 }))
.filter((m) => m.cell.startsWith("1:"))[0].corners[0];
const [left, centre, right] = [first("left"), first("center"), first("right")];
const delta = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
near(delta(left, centre), MODULE_W + MODULE_GAP, 1e-6);
near(delta(centre, right), MODULE_W + MODULE_GAP, 1e-6);
});
test("on flat ground the modules lean up on a frame with posts", () => {
const face = groundFace(cottage({ type: "none", pitch: 0, overhang: 0 }), { u: 20, v: 0, rotation: null, base: null });
const [m] = fieldModules(face, field(GROUND, { tilt: 30, u: 20, v: 0 }));
assert.ok(m.corners[2][1] > m.corners[0][1] + 0.5, "the upper edge is higher");
assert.ok(m.corners[2][2] > m.corners[0][2], "and lies towards +z");
assert.equal(m.posts.length, 4);
const [flipped] = fieldModules(face, field(GROUND, { tilt: 30, u: 20, v: 0, flip: true }));
assert.ok(flipped.corners[2][1] > flipped.corners[0][1] + 0.5, "flipped: still the upper edge is higher");
assert.ok(flipped.corners[2][2] < flipped.corners[0][2], "but it lies towards -z");
});
test("on a wall the modules hang flat, or stand off when tilted", () => {
const wall = wallFaces(cottage({ type: "none", pitch: 0, overhang: 0 }))[0];
const [flatOne] = fieldModules(wall, field(wall.key, { tilt: 0 }));
assert.equal(flatOne.posts.length, 0);
const [tilted] = fieldModules(wall, field(wall.key, { tilt: 30 }));
assert.equal(tilted.posts.length, 2);
});
test("a field is kept on the face, rounded down to centimetres, and the ground has no limits", () => {
const face = slope();
const [w, d] = fieldSize(face, field(face.key));
const kept = clampField(face, field(face.key, { u: 999, v: 999 }));
near(kept.u, Math.floor((face.lu - w) * 100) / 100, 1e-9);
near(kept.v, Math.floor((face.ls - d) * 100) / 100, 1e-9);
assert.deepEqual(clampField(face, field(face.key, { u: -5, v: -5 })), { u: 0, v: 0 });
const ground = groundFace(cottage({ type: "none", pitch: 0, overhang: 0 }), { u: 0, v: 0, rotation: null, base: null });
assert.deepEqual(clampField(ground, field(GROUND, { u: 500, v: -500 })), { u: 500, v: -500 });
});
test("the plan shows each module's corners as plan points; the centre is the middle of the field", () => {
const face = slope();
const f = field(face.key, { cols: 2 });
const plan = fieldPlan(face, f);
assert.equal(plan.length, 2);
assert.ok(plan.every((corners) => corners.length === 4 && corners.every((p) => p.length === 2)));
const centre = fieldCenter(face, f);
const xs = plan.flat().map((p) => p[0]);
const zs = plan.flat().map((p) => p[1]);
assert.ok(centre[0] >= Math.min(...xs) - 0.01 && centre[0] <= Math.max(...xs) + 0.01);
assert.ok(centre[1] >= Math.min(...zs) - 0.01 && centre[1] <= Math.max(...zs) + 0.01);
});
test("a roof window is a field of one module of its size, sunk into the roof", () => {
const face = slope();
const win = { id: "w", face: face.key, u: 1, v: 1, w: null, h: null, cover: null, contact: null, tilt: null };
assert.deepEqual(moduleSize(windowAsField(win)), [0.78, 1.18]);
assert.deepEqual(moduleSize(windowAsField({ ...win, w: 1, h: 2 })), [1, 2]);
const corners = windowCorners(face, win)!;
const above = (c: number[]) => (c[0] - face.o[0]) * face.n[0] + (c[1] - face.o[1]) * face.n[1] + (c[2] - face.o[2]) * face.n[2];
near(above(corners[0]), LIFT - 0.05, 1e-9);
assert.equal(windowCorners(face, { ...win, u: 999 }), null);
});
test("a field on a flat roof turns about its middle, the modules swing with it", () => {
const face = flat();
const sized = field("x", { rows: 1, cols: 4 });
const [w, d] = fieldSize(face, sized);
const base = { ...sized, u: face.lu / 2 - w / 2, v: face.ls / 2 - d / 2 };
const centre = fieldCenter(face, base);
const plan = (f: typeof base) => fieldPlan(face, f).flat();
const spread = (points: number[][], axis: 0 | 1) => Math.max(...points.map((p) => p[axis])) - Math.min(...points.map((p) => p[axis]));
const straight = plan(base);
const turned = plan({ ...base, rotation: 90 });
assert.equal(turned.length, straight.length);
// a row that ran along the eave now runs across it: the extents swap
near(spread(turned, 0), spread(straight, 1), 1e-6);
near(spread(turned, 1), spread(straight, 0), 1e-6);
const middle = (points: number[][]) => [0, 1].map((i) => (Math.max(...points.map((p) => p[i])) + Math.min(...points.map((p) => p[i]))) / 2);
near(middle(turned)[0], centre[0], 1e-6);
near(middle(turned)[1], centre[1], 1e-6);
});
test("a turned field is kept on its face by its middle, and a full turn changes nothing", () => {
const face = flat();
const base = field("x", { rows: 1, cols: 3, u: 0, v: 0 });
const full = field("x", { rows: 1, cols: 3, u: 0, v: 0, rotation: 360 });
fieldPlan(face, full).flat(2).forEach((v, i) => near(v, fieldPlan(face, base).flat(2)[i], 1e-9));
const turned = field("x", { rows: 1, cols: 3, u: 0, v: 0, rotation: 90 });
const moved = { ...turned, ...clampField(face, turned) };
assert.equal(fieldModules(face, moved).length, 3, "all modules are on the roof after the clamp");
// garden fields and wall fields do not use the field turn
const wall = wallFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0];
assert.deepEqual(fieldPlan(wall, field("x", { rotation: 90 })), fieldPlan(wall, field("x")));
});
test("east-west racks turn every second row and stand the pairs close; a rack on a slope lifts the upper edge", () => {
const face = flat();
const ew = fieldModules(face, field("x", { rows: 2, cols: 1, tilt: 10, rack: "ew" }));
// which way a module leans: from its low edge to its high edge, along the face
const lean = (m: (typeof ew)[number]) => [0, 1, 2].reduce((s, i) => s + (m.corners[2][i] - m.corners[0][i]) * face.es[i], 0);
assert.ok(lean(ew[0]) > 0 && lean(ew[1]) < 0, "the second row leans the other way");
assert.ok(rowPitch(flat(), field("x", { tilt: 10, rack: "ew" })) < rowPitch(flat(), field("x", { tilt: 10 })));
const racked = fieldModules(slope(), field("x", { rows: 1, cols: 1, tilt: 20 }))[0];
assert.equal(racked.posts.length, 2, "brackets under the raised edge");
});
+231
View File
@@ -0,0 +1,231 @@
// The modules of a solar field on its face: size, layout, tilt, and the 3D corners of every module.
import type { ChimneyShape, RoofChimney, RoofWindow, SolarField, Vec2 } from "../model.ts";
import type { RoofFace } from "./faces.ts";
import { DEG, type V3 } from "./vec.ts";
/** A common 400 W module: width and height in portrait (m), and the gap between modules. */
export const MODULE_W = 1.13;
export const MODULE_H = 1.72;
export const MODULE_GAP = 0.025;
/** The modules ride this high above the roof surface on mounting rails. */
export const LIFT = 0.07;
/** One module: its four corners (lower left, lower right, upper right, upper left) and, on a flat roof, its stand. */
export interface SolarModule {
corners: [V3, V3, V3, V3];
/** Flat roofs: the feet of the raised upper edge (posts from the roof up to the module). */
posts: [V3, V3][];
/** The cell in the field ("row:column") and whether it is switched off (only listed when asked for). */
cell: string;
skipped: boolean;
}
/** The size of a module along the eave and up the slope. */
export function moduleSize(f: Pick<SolarField, "portrait" | "module_w" | "module_h">): [number, number] {
const w = f.module_w || MODULE_W;
const h = f.module_h || MODULE_H;
return f.portrait === false ? [h, w] : [w, h];
}
/** How many modules each row has: the layout (rows of their own length) or `cols` in every row. */
export function rowCounts(f: Pick<SolarField, "rows" | "cols" | "layout">): number[] {
if (f.layout?.length) return f.layout.map((n) => Math.max(0, Math.min(60, Math.round(n))));
return Array.from({ length: Math.max(1, f.rows) }, () => Math.max(1, f.cols));
}
/** The tilt of a field's modules in radians: frames on flat ground (15° by default), standing off a wall (0 by default). */
function tiltOf(face: RoofFace, f: Pick<SolarField, "tilt">): number {
if (face.flat) return Math.min(45, Math.max(0, f.tilt ?? 15)) * DEG;
if (face.wall) return Math.min(90, Math.max(0, f.tilt ?? 0)) * DEG;
// a pitched roof: modules lie on it, or stand on a rack that tilts them further (a roof too flat for the sun)
return Math.min(45, Math.max(0, f.tilt ?? 0)) * DEG;
}
/** The distance from one row to the next: on a flat roof the module's depth plus a gap against shading. */
export function rowPitch(face: RoofFace, f: Pick<SolarField, "portrait" | "tilt" | "module_w" | "module_h"> & { rack?: SolarField["rack"] }): number {
const [, height] = moduleSize(f);
const tilt = tiltOf(face, f);
// a wall: rows one above the other, as high as a tilted module reaches
if (face.wall) return height * Math.cos(tilt) + MODULE_GAP;
if (!face.flat && tilt < 0.001) return height + MODULE_GAP;
// east-west: the rows stand back to back in pairs, no gap against shading needed
if (face.flat && (f as Pick<SolarField, "rack">).rack === "ew") return height * Math.cos(tilt) + 0.08;
return height * Math.cos(tilt) + Math.max(0.3, 2 * height * Math.sin(tilt));
}
/** Width (the longest row) and depth (all rows) of a field on its face. */
export function fieldSize(face: RoofFace, f: SolarField): [number, number] {
const [width, height] = moduleSize(f);
const counts = rowCounts(f);
const longest = Math.max(1, ...counts);
return [longest * width + (longest - 1) * MODULE_GAP, (counts.length - 1) * rowPitch(face, f) + height * Math.cos(tiltOf(face, f))];
}
/** Whether a field on this face may be turned about its middle: flat roofs only (garden fields turn their whole face instead). */
const turnable = (face: RoofFace): boolean => face.flat && !face.unbounded && !face.wall;
/** A field's turn in radians (clockwise in the plan, like the garden fields) and the point it turns about, in face coordinates; null when it stands straight. */
function turnOf(face: RoofFace, f: SolarField): { cos: number; sin: number; u: number; s: number } | null {
if (!turnable(face) || !f.rotation) return null;
const r = f.rotation * DEG;
const [width, depth] = fieldSize(face, f);
return { cos: Math.cos(r), sin: Math.sin(r), u: f.u + width / 2, s: f.v + depth / 2 };
}
/**
* The modules of a field on its face. Modules that would leave the face (a hip, the ridge) are left out, and so are the
* ones switched off, unless `withSkipped` asks for them (the editor shows them).
*/
export function fieldModules(face: RoofFace, f: SolarField, withSkipped = false): SolarModule[] {
const [width, height] = moduleSize(f);
const tilt = tiltOf(face, f);
const depth = height * Math.cos(tilt);
const pitch = rowPitch(face, f);
const counts = rowCounts(f);
const longest = Math.max(1, ...counts);
const switchedOff = new Set(f.skip ?? []);
const turn = turnOf(face, f);
// a turned field: every point of it swings about the field's middle
const turned = (u: number, s: number): [number, number] => (turn ? [turn.u + (u - turn.u) * turn.cos - (s - turn.s) * turn.sin, turn.s + (u - turn.u) * turn.sin + (s - turn.s) * turn.cos] : [u, s]);
const at = (u0: number, s0: number, up: number): V3 => {
const [u, s] = turned(u0, s0);
return [0, 1, 2].map((i) => face.o[i] + face.eu[i] * u + face.es[i] * s + face.n[i] * up) as V3;
};
const onFace = (u0: number, s0: number) => {
const [u, s] = turned(u0, s0);
if (face.unbounded) return true;
if (s < -1e-6 || s > face.ls + 1e-6) return false;
const [from, to] = face.span(s);
return u >= from - 1e-6 && u <= to + 1e-6;
};
const modules: SolarModule[] = [];
counts.forEach((count, row) => {
// a shorter row sits left, centred or right under the longest one
const shift = f.align === "right" ? longest - count : f.align === "center" ? (longest - count) / 2 : 0;
for (let col = 0; col < count; col++) {
const cell = `${row}:${col}`;
const skipped = switchedOff.has(cell);
if (skipped && !withSkipped) continue;
const u0 = f.u + (col + shift) * (width + MODULE_GAP);
const u1 = u0 + width;
const s0 = f.v + row * pitch;
const s1 = s0 + (face.flat || face.wall || tilt > 0.001 ? depth : height);
if (![[u0, s0], [u1, s0], [u1, s1], [u0, s1]].every(([u, s]) => onFace(u, s))) continue;
if (face.wall && tilt > 0.001) {
// tilted on a wall: the upper edge stands off the wall (the lower edge when flipped), on brackets
const away = LIFT + height * Math.sin(tilt);
const [lowLift, highLift] = f.flip ? [away, LIFT] : [LIFT, away];
const corners: [V3, V3, V3, V3] = [at(u0, s0, lowLift), at(u1, s0, lowLift), at(u1, s1, highLift), at(u0, s1, highLift)];
const edge = f.flip ? s0 : s1;
modules.push({ corners, posts: [u0 + 0.05, u1 - 0.05].map((u) => [at(u, edge, 0), at(u, edge, away)] as [V3, V3]), cell, skipped });
} else if (!face.flat && tilt > 0.001) {
// a rack on a pitched roof: the upper edge stands off the roof, on brackets
const away = LIFT + height * Math.sin(tilt);
const corners: [V3, V3, V3, V3] = [at(u0, s0, LIFT), at(u1, s0, LIFT), at(u1, s1, away), at(u0, s1, away)];
modules.push({ corners, posts: [u0 + 0.05, u1 - 0.05].map((u) => [at(u, s1, 0), at(u, s1, away)] as [V3, V3]), cell, skipped });
} else if (!face.flat) {
modules.push({ corners: [at(u0, s0, LIFT), at(u1, s0, LIFT), at(u1, s1, LIFT), at(u0, s1, LIFT)], posts: [], cell, skipped });
} else {
// flat roof or ground: the module leans up towards +s (towards -s when flipped), on a low frame; east-west racks turn every
// second row the other way, so each pair stands back to back
const low = 0.15;
const high = low + height * Math.sin(tilt);
const flipped = f.rack === "ew" && row % 2 === 1 ? !f.flip : !!f.flip;
const [sLow, sHigh] = flipped ? [s1, s0] : [s0, s1];
const corners: [V3, V3, V3, V3] = [at(u0, sLow, low), at(u1, sLow, low), at(u1, sHigh, high), at(u0, sHigh, high)];
const posts = [u0 + 0.05, u1 - 0.05].flatMap((u) => [[at(u, sLow, 0), at(u, sLow, low)], [at(u, sHigh, 0), at(u, sHigh, high)]] as [V3, V3][]);
modules.push({ corners, posts, cell, skipped });
}
}
});
return modules;
}
/** The corners of every module of a field in the plan, for the editor. */
export const fieldPlan = (face: RoofFace, f: SolarField): Vec2[][] => fieldModules(face, f).map((m) => m.corners.map((p) => [p[0], p[2]] as Vec2));
/** Keeps a field on its face: its corner moves so the whole field stays on the face where it can. */
export function clampField(face: RoofFace, f: SolarField): { u: number; v: number } {
if (face.unbounded) return { u: f.u, v: f.v };
const [width, depth] = fieldSize(face, f);
const turn = turnOf(face, f);
if (turn) {
// a turned field: its middle stays where the turned outline still fits on the face
const [halfU, halfS] = [(width * Math.abs(turn.cos) + depth * Math.abs(turn.sin)) / 2, (width * Math.abs(turn.sin) + depth * Math.abs(turn.cos)) / 2];
const inside = (centre: number, half: number, size: number) => Math.floor(Math.max(half, Math.min(centre, size - half)) * 100 + 1e-6) / 100;
const [cu, cs] = [f.u + width / 2, f.v + depth / 2];
return { u: Math.round((inside(cu, halfU, face.lu) - width / 2) * 100) / 100, v: Math.round((inside(cs, halfS, face.ls) - depth / 2) * 100) / 100 };
}
// rounded down to centimetres, so a field pushed to the far edge still fits completely
const down = (x: number) => Math.floor(x * 100 + 1e-6) / 100;
return { u: down(Math.min(Math.max(0, f.u), Math.max(0, face.lu - width))), v: down(Math.min(Math.max(0, f.v), Math.max(0, face.ls - depth))) };
}
/** The middle of a field in the plan. */
export function fieldCenter(face: RoofFace, f: SolarField): Vec2 {
const [width, depth] = fieldSize(face, f);
const [u, s] = [f.u + width / 2, f.v + depth / 2];
return [face.o[0] + face.eu[0] * u + face.es[0] * s, face.o[2] + face.eu[2] * u + face.es[2] * s];
}
// ---------------------------------------------------------------- roof windows
/** The usual roof window size, 78 × 118 cm. */
export const ROOF_WINDOW_W = 0.78;
export const ROOF_WINDOW_H = 1.18;
/** A roof window as a field of one module of its own size, so that placing, moving and keeping it on the face work alike. */
export const windowAsField = (w: RoofWindow): SolarField => ({ id: w.id, face: w.face, u: w.u, v: w.v, rows: 1, cols: 1, portrait: true, module_w: w.w || ROOF_WINDOW_W, module_h: w.h || ROOF_WINDOW_H });
/** The four corners of a roof window, sunk 5 cm into the roof (lower left, lower right, upper right, upper left). Null off the face. */
export function windowCorners(face: RoofFace, w: RoofWindow): [V3, V3, V3, V3] | null {
const module = fieldModules(face, windowAsField(w))[0];
if (!module) return null;
// modules ride 7 cm above the roof on rails; a roof window sits nearly flush
const sink = (p: V3): V3 => [p[0] - face.n[0] * 0.05, p[1] - face.n[1] * 0.05, p[2] - face.n[2] * 0.05];
return module.corners.map(sink) as [V3, V3, V3, V3];
}
// ---------------------------------------------------------------- chimneys
/** The usual size of each chimney shape: width along the eave, depth in the plan, height above the roof (m). */
export const CHIMNEY_SIZE: Record<ChimneyShape, { w: number; d: number; h: number }> = {
brick: { w: 0.5, d: 0.5, h: 1 },
round: { w: 0.4, d: 0.4, h: 1 },
wide: { w: 1, d: 0.5, h: 1 },
steel: { w: 0.2, d: 0.2, h: 1.2 },
};
/** A chimney's shape and size, the shape's usual size where none is set. */
export function chimneySize(c: RoofChimney): { shape: ChimneyShape; w: number; d: number; h: number } {
const shape = c.shape ?? "brick";
const usual = CHIMNEY_SIZE[shape] ?? CHIMNEY_SIZE.brick;
return { shape, w: c.w || usual.w, d: c.d || usual.d, h: c.h || usual.h };
}
/** A chimney as a field of one module the size of its footprint on the slope, so placing and moving work like a roof window's. */
export function chimneyAsField(c: RoofChimney, face: RoofFace | null | undefined): SolarField {
const { w, d } = chimneySize(c);
const slope = face && !face.flat ? Math.cos(face.pitch * DEG) : 1;
return { id: c.id, face: c.face, u: c.u, v: c.v, rows: 1, cols: 1, portrait: true, module_w: w, module_h: d / Math.max(0.2, slope), tilt: 0 };
}
/**
* Where a chimney stands: the middle of its footprint in the plan, the plan directions along the eave and across it,
* and the roof's lowest and highest point under it (heights above the ground).
*/
export function chimneyPlace(face: RoofFace, c: RoofChimney): { center: Vec2; along: Vec2; across: Vec2; low: number; high: number } {
const f = chimneyAsField(c, face);
const [w, slope] = [f.module_w!, f.module_h!];
const at = (u: number, s: number): V3 => [face.o[0] + face.eu[0] * u + face.es[0] * s, face.o[1] + face.eu[1] * u + face.es[1] * s, face.o[2] + face.eu[2] * u + face.es[2] * s];
const [p0, p1] = [at(c.u + w / 2, c.v), at(c.u + w / 2, c.v + slope)];
const mid = at(c.u + w / 2, c.v + slope / 2);
const flat = (v: readonly number[]): Vec2 => {
const n = Math.hypot(v[0], v[2]) || 1;
return [v[0] / n, v[2] / n];
};
return { center: [mid[0], mid[2]], along: flat(face.eu), across: flat(face.es), low: Math.min(p0[1], p1[1]), high: Math.max(p0[1], p1[1]) };
}
+17
View File
@@ -0,0 +1,17 @@
// Builders for the solar tests.
import { emptyBuilding, newFloor, type Building, type SolarField } from "../model.ts";
export const near = (a: number, b: number, eps = 1e-6) => {
if (Math.abs(a - b) >= eps) throw new Error(`${a} is not close to ${b}`);
};
/** A one-floor house of 12 × 7 m with 2.6 m high walls and the given roof. */
export function cottage(roof: Building["settings"]["roof"], elevation = 0): Building {
const b = emptyBuilding();
b.floors = [{ ...newFloor("g", "G", elevation), height: 2.6, rooms: [{ id: "r", name: "R", area_id: null, points: [[0, 0], [12, 0], [12, 7], [0, 7]], floor_material: "wood" }] }];
b.settings = { ...b.settings, wall_exterior: 0.3, roof };
return b;
}
export const field = (face: string, extra: Partial<SolarField> = {}): SolarField => ({ id: "f", face, u: 0.5, v: 0.5, rows: 1, cols: 2, portrait: true, ...extra });
+88
View File
@@ -0,0 +1,88 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { roofFaces, wallFaces } from "./faces.ts";
import { cottage, field, near } from "./fixtures.ts";
import { fieldModules } from "./fields.ts";
import { bestFace, faceAt, faceCompass, onField, onFace, pointOnFace, rayOnFace } from "./picking.ts";
const house = () => cottage({ type: "gable", pitch: 35, overhang: 0.5 });
test("a plan point is found on the slope it lies under, with face coordinates that map back", () => {
const faces = roofFaces(house());
const hit = faceAt(faces, [6, 1])!;
assert.equal(hit.face.key, "main:a");
const back = [hit.face.o[0] + hit.face.eu[0] * hit.u + hit.face.es[0] * hit.s, hit.face.o[2] + hit.face.eu[2] * hit.u + hit.face.es[2] * hit.s];
near(back[0], 6, 1e-9);
near(back[1], 1, 1e-9);
assert.equal(faceAt(faces, [6, 6])!.face.key, "main:b");
assert.equal(faceAt(faces, [50, 50]), null);
assert.equal(pointOnFace(faces[0], [50, 50]), null);
});
test("where roofs overlap the highest one is picked", () => {
const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [
{ id: "low", x0: 0, z0: 0, x1: 12, z1: 7, shape: "pent", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 5, pitch_b: 5, base: 2.6, overhang: 0 },
{ id: "high", x0: 0, z0: 0, x1: 12, z1: 7, shape: "pent", axis: "x", eave_a: 5, eave_b: 5, pitch_a: 5, pitch_b: 5, base: 5, overhang: 0 },
] });
assert.equal(faceAt(roofFaces(b), [6, 3])!.face.section, "high");
});
test("right in front of a wall the wall wins, a little further out only where there is no roof", () => {
const b = house();
const faces = [...roofFaces(b), ...wallFaces(b)];
const wall = wallFaces(b)[0];
const mid = [wall.o[0] + wall.eu[0] * wall.lu / 2, wall.o[2] + wall.eu[2] * wall.lu / 2];
const near1 = faceAt(faces, [mid[0] + wall.n[0] * 0.2, mid[1] + wall.n[2] * 0.2])!;
assert.equal(near1.face.key, wall.key);
assert.ok(Number.isNaN(near1.s));
const far = faceAt(wallFaces(b), [mid[0] + wall.n[0] * 0.6, mid[1] + wall.n[2] * 0.6])!;
assert.equal(far.face.key, wall.key);
assert.equal(faceAt(wallFaces(b), [mid[0] + wall.n[0] * 2, mid[1] + wall.n[2] * 2]), null);
});
test("a ray from above meets a face at the right distance and coordinates", () => {
const face = roofFaces(house())[0];
const target = [face.o[0] + face.eu[0] * 3 + face.es[0] * 2, face.o[1] + face.eu[1] * 3 + face.es[1] * 2, face.o[2] + face.eu[2] * 3 + face.es[2] * 2] as [number, number, number];
const origin: [number, number, number] = [target[0], target[1] + 10, target[2]];
const hit = rayOnFace(face, origin, [0, -1, 0])!;
near(hit.u, 3, 1e-9);
near(hit.s, 2, 1e-9);
assert.ok(hit.t > 9 && hit.t < 11);
assert.equal(rayOnFace(face, origin, [0, 1, 0]), null, "away from the face");
assert.equal(rayOnFace(face, origin, [face.eu[0], face.eu[1], face.eu[2]]), null, "parallel to the face");
});
test("points are on a face inside its edges; the ground has no edges", () => {
const face = roofFaces(house())[0];
assert.equal(onFace(face, 1, 1), true);
assert.equal(onFace(face, -1, 1), false);
assert.equal(onFace(face, 1, face.ls + 1), false);
assert.equal(onFace({ ...face, unbounded: true }, 1e6, 1e6), true);
});
test("a point is on a field when it lies over one of its modules, with a little slack", () => {
const face = roofFaces(house())[0];
const f = field(face.key, { u: 1, v: 1, cols: 2 });
assert.equal(onField(face, f, 1.5, 1.5), true);
assert.equal(onField(face, f, 0.97, 1.5), true, "5 cm slack");
assert.equal(onField(face, f, 0.5, 1.5), false);
assert.equal(onField(face, f, 6, 6), false);
assert.equal(fieldModules(face, f).length, 2);
});
test("a face's compass direction follows the plan's north", () => {
const [a, b] = roofFaces(house());
assert.equal(faceCompass(a, 0), "n");
assert.equal(faceCompass(b, 0), "s");
assert.equal(faceCompass(b, 90), "e", "north turned 90° clockwise: a south-looking face reads as east");
assert.equal(faceCompass(a, 180), "s");
});
test("the best face looks south and is big; flat roofs score a bit lower than a south slope", () => {
const faces = roofFaces(house());
assert.equal(bestFace(faces, 0)?.key, "main:b");
assert.equal(bestFace(faces, 180)?.key, "main:a");
assert.equal(bestFace([], 0), null);
const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }));
assert.equal(bestFace(flat, 0)?.key, "main:top");
});
+94
View File
@@ -0,0 +1,94 @@
// Finding where a pointer or a ray meets a face and its fields, and which way a face looks.
import type { SolarField, Vec2 } from "../model.ts";
import type { RoofFace } from "./faces.ts";
import { fieldModules } from "./fields.ts";
import { bearingOf, dot, sub, type V3 } from "./vec.ts";
/** Where a plan point lies on a face (u along the eave, s up the slope), or null when it is not on it. */
export function pointOnFace(face: RoofFace, p: Vec2): { u: number; s: number } | null {
// solve p = o + eu * u + es * s in the plan; eu and es are not parallel there
const [d0, d1] = [p[0] - face.o[0], p[1] - face.o[2]];
const [a0, a1, b0, b1] = [face.eu[0], face.eu[2], face.es[0], face.es[2]];
const det = a0 * b1 - a1 * b0;
if (Math.abs(det) < 1e-9) return null;
const u = (d0 * b1 - d1 * b0) / det;
const s = (a0 * d1 - a1 * d0) / det;
if (s < 0 || s > face.ls) return null;
const [from, to] = face.span(s);
return u >= from && u <= to ? { u, s } : null;
}
type Hit = { face: RoofFace; u: number; s: number };
/**
* The face under a plan point: the highest one there (an upper roof hides a lower one). A wall is hit by a pointer just
* outside it; the height stays open then (s is NaN).
*/
export function faceAt(faces: readonly RoofFace[], p: Vec2): Hit | null {
let best: (Hit & { y: number }) | null = null;
for (const face of faces) {
if (face.wall) {
const [dx, dz] = [p[0] - face.o[0], p[1] - face.o[2]];
const u = dx * face.eu[0] + dz * face.eu[2];
const outward = dx * face.n[0] + dz * face.n[2];
const alongWall = u >= 0 && u <= face.lu;
// right in front of the wall it wins over a roof overhang above it; further out only where there is no roof
if (alongWall && outward >= -0.05 && outward <= 0.35) return { face, u, s: Number.NaN };
if (alongWall && outward > 0.35 && outward <= 0.8 && !best) best = { face, u, s: Number.NaN, y: -Infinity };
continue;
}
const hit = pointOnFace(face, p);
if (!hit) continue;
const y = face.o[1] + face.es[1] * hit.s;
if (!best || y > best.y) best = { face, ...hit, y };
}
return best && { face: best.face, u: best.u, s: best.s };
}
/** Where a ray (origin, direction, building coordinates) meets a face: the distance t and the face coordinates. */
export function rayOnFace(face: RoofFace, origin: V3, direction: V3): { t: number; u: number; s: number } | null {
const facing = dot(direction, face.n);
if (Math.abs(facing) < 1e-6) return null;
const t = dot(sub(face.o, origin), face.n) / facing;
if (t <= 0) return null;
const local = sub([origin[0] + direction[0] * t, origin[1] + direction[1] * t, origin[2] + direction[2] * t], face.o);
return { t, u: dot(local, face.eu), s: dot(local, face.es) };
}
/** Whether a point (u, s) lies on the face itself: inside its edges. The ground has none. */
export function onFace(face: RoofFace, u: number, s: number): boolean {
if (face.unbounded) return true;
if (s < 0 || s > face.ls) return false;
const [from, to] = face.span(s);
return u >= from && u <= to;
}
/** Whether a point (u, s) lies on one of the field's modules (their outlines on the face, with 5 cm to spare). */
export function onField(face: RoofFace, f: SolarField, u: number, s: number): boolean {
const slack = 0.05;
return fieldModules(face, f).some((module) => {
const local = module.corners.map((corner) => {
const q = sub(corner, face.o);
return [dot(q, face.eu), dot(q, face.es)];
});
const us = local.map((c) => c[0]);
const ss = local.map((c) => c[1]);
return u >= Math.min(...us) - slack && u <= Math.max(...us) + slack && s >= Math.min(...ss) - slack && s <= Math.max(...ss) + slack;
});
}
const COMPASS = ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const;
/** The compass direction a face looks to (n, ne, e ...), given the plan's north in degrees clockwise from up. */
export const faceCompass = (face: RoofFace, north: number): (typeof COMPASS)[number] => COMPASS[Math.round(bearingOf(face.facing, north) / 45) % 8];
/** The face that suits a new field best: towards the south, and the bigger the better. */
export function bestFace(faces: readonly RoofFace[], north: number): RoofFace | null {
const score = (face: RoofFace) => {
if (face.flat) return face.lu * face.ls * 0.8;
const southness = Math.cos(((bearingOf(face.facing, north) - 180) * Math.PI) / 180);
return face.lu * face.ls * (1.2 + southness);
};
return [...faces].sort((p, q) => score(q) - score(p))[0] ?? null;
}
+101
View File
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { GROUND, fieldFace, roofFaces, wallFaces } from "./faces.ts";
import { fieldModules, ROOF_WINDOW_H, ROOF_WINDOW_W } from "./fields.ts";
import { cottage, near } from "./fixtures.ts";
import { moveField, proposeField, proposeGroundField, proposeWallField, proposeWindow, turnGroundField } from "./placing.ts";
const gable = () => cottage({ type: "gable", pitch: 35, overhang: 0.5 });
test("a proposed field fits its face completely, with every module on it", () => {
for (const face of roofFaces(gable())) {
const f = proposeField(face, "p");
assert.equal(f.face, face.key);
assert.equal(fieldModules(face, f).length, f.rows * f.cols, face.key);
assert.ok(f.cols >= 1 && f.rows >= 1 && f.rows <= 4);
}
});
test("on a flat roof the proposal is tilted on frames, on a slope it lies flat", () => {
const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0];
assert.equal(proposeField(flat, "p").tilt, 15);
assert.equal(proposeField(roofFaces(gable())[0], "p").tilt, null);
});
test("a hip face narrows towards the ridge, so the proposal has fewer columns until all modules fit", () => {
const b = cottage({ type: "custom", pitch: 35, overhang: 0, sections: [{ id: "h", x0: 0, z0: 0, x1: 9, z1: 8, shape: "hip", axis: "x", eave_a: 2.6, eave_b: 2.6, pitch_a: 35, pitch_b: 35, base: 2.6, overhang: 0 }] });
for (const face of roofFaces(b)) {
const f = proposeField(face, "p");
assert.equal(fieldModules(face, f).length, f.rows * f.cols, face.key);
}
});
test("a field moved to another face keeps its modules and is centred inside the new face", () => {
const [a, b] = roofFaces(gable());
const original = { ...proposeField(a, "m"), rows: 2, cols: 3, portrait: false };
const moved = moveField(b, original);
assert.equal(moved.face, b.key);
assert.deepEqual([moved.rows, moved.cols, moved.portrait], [2, 3, false]);
assert.equal(moved.rotation, null);
assert.equal(fieldModules(b, moved).length, 6);
const flat = roofFaces(cottage({ type: "flat", pitch: 0, overhang: 0.5 }))[0];
assert.equal(moveField(flat, { ...original, tilt: null }).tilt, 15, "a flat roof brings a tilt");
});
test("the wall field goes on the wall that gets the most sun; none without walls", () => {
const b = gable();
b.settings.north = 0;
const f = proposeWallField(b, "w", "g")!;
const face = fieldFace(b, f)!;
assert.ok(face.wall);
assert.equal(f.portrait, false);
assert.equal(f.rows, 1);
assert.ok(f.cols >= 1);
// the sunny side looks south: +z in the plan with north up
assert.ok(face.facing[1] > 0.5, `faces ${face.facing}`);
assert.equal(proposeWallField(b, "w", "nowhere"), null);
assert.ok(wallFaces(b, "g").length > 1);
});
test("a garden field stands east of the house on frames, tilted 25°, as two rows of four, looking south", () => {
const b = gable();
const f = proposeGroundField(b, "g");
assert.equal(f.face, GROUND);
assert.equal(f.rows * f.cols, 8);
assert.equal(f.tilt, 25);
assert.ok(f.u >= 12 + 2.9, "beside the house");
assert.equal(f.rotation, 0);
const north = cottage({ type: "none", pitch: 0, overhang: 0 });
north.settings.north = 40;
assert.equal(proposeGroundField(north, "g").rotation, 40);
assert.equal(proposeGroundField({ ...north, floors: [] }, "g").u, 0);
});
test("turning a garden field about its middle keeps the middle where it was", () => {
const b = gable();
const f = { ...proposeGroundField(b, "g"), rotation: 0 };
const middle = (g: typeof f) => {
const mods = fieldModules(fieldFace(b, g)!, g);
const xs = mods.flatMap((m) => m.corners.map((c) => c[0]));
const zs = mods.flatMap((m) => m.corners.map((c) => c[2]));
return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2];
};
const before = middle(f);
const turned = { ...f, ...turnGroundField(b, f, 90) };
assert.equal(turned.rotation, 90);
const after = middle(turned);
// the box of modules turns too, but its centre stays within a field's depth of where it was
assert.ok(Math.hypot(after[0] - before[0], after[1] - before[1]) < 1.5);
assert.equal(turnGroundField(b, f, -90).rotation, 270);
assert.equal(turnGroundField(b, f, 450).rotation, 90);
});
test("a roof window is proposed in the middle of a face, fully on it", () => {
const face = roofFaces(gable())[0];
const w = proposeWindow(face, "win");
assert.equal(w.face, face.key);
assert.deepEqual([w.w, w.h], [null, null]);
assert.ok(w.u > 0 && w.u + ROOF_WINDOW_W < face.lu);
assert.ok(w.v >= 0 && w.v + ROOF_WINDOW_H <= face.ls + 1e-9);
near(w.u, Math.round(w.u * 100) / 100, 1e-9);
});
+99
View File
@@ -0,0 +1,99 @@
// Proposals for new fields and windows, moving a field to another face, and turning a garden field.
import type { Building, RoofChimney, RoofWindow, SolarField } from "../model.ts";
import { GROUND, groundFace, wallFaces, type RoofFace } from "./faces.ts";
import { CHIMNEY_SIZE, chimneyAsField, clampField, fieldModules, fieldSize, MODULE_GAP, MODULE_H, MODULE_W, moduleSize, ROOF_WINDOW_H, ROOF_WINDOW_W, rowPitch } from "./fields.ts";
import { bearingOf, cm, DEG } from "./vec.ts";
/** The u that centres a field of its column count along the eave of a face. */
function centredU(face: RoofFace, f: SolarField): number {
const [width] = moduleSize(f);
return cm((face.lu - (f.cols * width + (f.cols - 1) * MODULE_GAP)) / 2);
}
const FIRST_ROW_OFFSET = 0.4;
/** A field that fits: as many modules as the face holds, centred along the eave, starting a little above it. */
export function proposeField(face: RoofFace, id: string): SolarField {
const field: SolarField = { id, face: face.key, u: 0, v: 0, rows: 1, cols: 1, portrait: true, tilt: face.flat ? 15 : null, flip: false, entity: null, look: "black" };
const [width] = moduleSize(field);
const [from, to] = face.span(face.ls / 2);
field.cols = Math.max(1, Math.floor((to - from - 2 * FIRST_ROW_OFFSET + MODULE_GAP) / (width + MODULE_GAP)));
field.rows = Math.max(1, Math.min(4, Math.floor((face.ls - 2 * FIRST_ROW_OFFSET) / rowPitch(face, field))));
// hip faces narrow towards the ridge: fewer columns until every module fits
while (field.cols > 1 && fieldModules(face, { ...field, u: centredU(face, field), v: FIRST_ROW_OFFSET }).length < field.rows * field.cols) field.cols--;
field.u = centredU(face, field);
field.v = FIRST_ROW_OFFSET;
return field;
}
/** A field moved to another face: it keeps its modules (rows, columns, format, and tilt where the face allows one), centred along the new eave and inside its edges. */
export function moveField(face: RoofFace, f: SolarField): SolarField {
const moved: SolarField = { ...f, face: face.key, tilt: face.flat ? (f.tilt ?? 15) : null, rotation: null, flip: false };
moved.u = centredU(face, moved);
moved.v = FIRST_ROW_OFFSET;
return { ...moved, ...clampField(face, moved) };
}
/** A new wall field: on the wall that gets the most sun for its length, one row of landscape modules at head height. */
export function proposeWallField(b: Building, id: string, floorId: string): SolarField | null {
const north = b.settings.north ?? 0;
// long walls facing south score best
const score = (face: RoofFace) => face.lu * (1.3 + Math.cos(((bearingOf(face.facing, north) - 180) * Math.PI) / 180));
const face = wallFaces(b, floorId).sort((p, q) => score(q) - score(p))[0];
if (!face) return null;
const field = { ...proposeField(face, id), portrait: false, rows: 1 };
field.cols = Math.max(1, Math.floor((face.lu - 0.8 + MODULE_GAP) / (MODULE_H + MODULE_GAP)));
field.u = cm((face.lu - (field.cols * MODULE_H + (field.cols - 1) * MODULE_GAP)) / 2);
field.v = cm(Math.max(0, face.ls - MODULE_W - 0.3));
return field;
}
/** A new garden field beside the house: two rows of four, tilted 25°, looking south. */
export function proposeGroundField(b: Building, id: string): SolarField {
const corners = b.floors.flatMap((floor) => floor.rooms.flatMap((r) => r.points));
const x = corners.length ? Math.max(...corners.map((p) => p[0])) + 3 : 0;
const z = corners.length ? Math.min(...corners.map((p) => p[1])) : 0;
// rows run along x and the modules lean up towards -z: with north up in the plan they look south
return { id, face: GROUND, u: cm(x), v: cm(z), rows: 2, cols: 4, portrait: true, tilt: 25, flip: true, rotation: (b.settings.north ?? 0) || 0, look: "black", entity: null };
}
/**
* A garden field turned about its middle: u and v are measured along the turned axes, so they are worked out again from
* the field's centre in the plan (otherwise the field would jump away).
*/
export function turnGroundField(b: Building, f: SolarField, rotation: number): { u: number; v: number; rotation: number } {
const face = groundFace(b, f);
const [width, depth] = fieldSize(face, f);
const [halfU, halfV] = [f.u + width / 2, f.v + depth / 2];
const centre = [face.eu[0] * halfU + face.es[0] * halfV, face.eu[2] * halfU + face.es[2] * halfV];
const r = rotation * DEG;
// the centre stays put: the corner is half the size back along the new axes
const u = centre[0] * Math.cos(r) + centre[1] * Math.sin(r) - width / 2;
const v = centre[0] * -Math.sin(r) + centre[1] * Math.cos(r) - depth / 2;
return { u: cm(u), v: cm(v), rotation: ((Math.round(rotation) % 360) + 360) % 360 };
}
/** A new roof window in the middle of a face, around head height above the floor below. */
export function proposeWindow(face: RoofFace, id: string): RoofWindow {
const [from, to] = face.span(face.ls / 2);
return {
id,
face: face.key,
u: cm((from + to - ROOF_WINDOW_W) / 2),
v: cm(Math.max(0, Math.min(face.ls - ROOF_WINDOW_H, face.ls * 0.45 - ROOF_WINDOW_H / 2))),
w: null,
h: null,
cover: null,
contact: null,
tilt: null,
};
}
/** A new chimney: a brick one near the ridge, in the middle of the face. */
export function proposeChimney(face: RoofFace, id: string): RoofChimney {
const size = CHIMNEY_SIZE.brick;
const [from, to] = face.span(face.ls * 0.8);
const depth = chimneyAsField({ id, face: face.key, u: 0, v: 0 }, face).module_h!;
return { id, face: face.key, u: cm((from + to - size.w) / 2), v: cm(Math.max(0, Math.min(face.ls - depth, face.ls * 0.8 - depth / 2))), shape: "brick", w: null, d: null, h: null };
}
+20
View File
@@ -0,0 +1,20 @@
// Three-component vector helpers for the solar geometry.
export type V3 = [number, number, number];
export const DEG = Math.PI / 180;
export const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
export const dot = (a: V3, b: V3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
export const length = (a: V3): number => Math.hypot(a[0], a[1], a[2]);
export const normalize = (a: V3): V3 => {
const l = length(a) || 1;
return [a[0] / l, a[1] / l, a[2] / l];
};
export const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
/** Rounded to centimetres. */
export const cm = (v: number): number => Math.round(v * 100) / 100;
/** Bearing of a plan direction in degrees clockwise from up (-z), turned by the plan's north, in 0..360. */
export const bearingOf = ([dx, dz]: [number, number], north: number): number => (Math.atan2(dx, -dz) / DEG - north + 720) % 360;