first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Background, Vec2 } from "../../../model.ts";
|
||||
import { dragRotation, pictureCentre, pictureLocal, scaledToLength, straightened, wrapHalfTurn } from "./background.ts";
|
||||
|
||||
const bg = (extra: Partial<Background> = {}): Background => ({ image_id: "i", x: 0, z: 0, width: 4, opacity: 1, ...extra });
|
||||
const near = (a: number, b: number, eps = 1e-3) => assert.ok(Math.abs(a - b) < eps, `${a} is not ${b}`);
|
||||
|
||||
test("the picture's middle follows from its position, width and aspect", () => {
|
||||
assert.deepEqual(pictureCentre(bg({ x: 1, z: 2 }), 0.5), [3, 3]);
|
||||
});
|
||||
|
||||
test("a line that is nearly along x is straightened by turning the picture about the first point", () => {
|
||||
const picture = bg();
|
||||
const p: Vec2 = [0, 0];
|
||||
const q: Vec2 = [10, 1];
|
||||
const result = straightened(picture, 0.5, p, q)!;
|
||||
near(result.rotation!, -5.71, 0.01);
|
||||
// the middle keeps its distance from the turning point
|
||||
const before = Math.hypot(...pictureCentre(picture, 0.5));
|
||||
const after = Math.hypot(...pictureCentre(result, 0.5));
|
||||
near(before, after, 0.01);
|
||||
assert.equal(result.width, 4);
|
||||
});
|
||||
|
||||
test("a line that is already straight, or too short, changes nothing", () => {
|
||||
assert.equal(straightened(bg(), 0.5, [0, 0], [5, 0]), null);
|
||||
assert.equal(straightened(bg(), 0.5, [0, 0], [0, 0.01]), null);
|
||||
});
|
||||
|
||||
test("a line nearly along z is turned to run along z, in the right direction", () => {
|
||||
const result = straightened(bg(), 0.5, [0, 0], [1, 10])!;
|
||||
// the line points a little east of south: the picture turns anticlockwise to bring it straight
|
||||
assert.ok(result.rotation! > 0 && result.rotation! < 10);
|
||||
});
|
||||
|
||||
test("scaling to a measured length keeps the point fixed and the turn", () => {
|
||||
const picture = bg({ rotation: 30 });
|
||||
const a: Vec2 = [1, 1];
|
||||
const result = scaledToLength(picture, 0.5, a, [3, 1], 8)!;
|
||||
assert.equal(result.width, 16);
|
||||
assert.equal(result.rotation, 30);
|
||||
// a point of the picture that was at `a` is still at `a`: its distance from the middle scaled by the same factor
|
||||
const [c1, c2] = [pictureCentre(picture, 0.5), pictureCentre(result, 0.5)];
|
||||
near(c2[0] - a[0], 4 * (c1[0] - a[0]));
|
||||
near(c2[1] - a[1], 4 * (c1[1] - a[1]));
|
||||
});
|
||||
|
||||
test("scaling needs a positive length and a stretch that can be measured", () => {
|
||||
assert.equal(scaledToLength(bg(), 0.5, [0, 0], [1, 0], 0), null);
|
||||
assert.equal(scaledToLength(bg(), 0.5, [0, 0], [1, 0], -3), null);
|
||||
assert.equal(scaledToLength(bg(), 0.5, [2, 2], [2, 2], 5), null);
|
||||
});
|
||||
|
||||
test("a plan point in the picture's own frame, with and without a turn", () => {
|
||||
assert.deepEqual(pictureLocal(bg({ x: 1, z: 1 }), 0.5, [2, 3]), [1, 2]);
|
||||
// the picture's middle is (2, 1); a point 2 east of it lies 2 up the picture when that is turned a quarter clockwise
|
||||
const turned = pictureLocal(bg({ rotation: 90 }), 0.5, [4, 1]);
|
||||
near(turned[0], 2, 1e-9);
|
||||
near(turned[1], -1, 1e-9);
|
||||
});
|
||||
|
||||
test("angles wrap into a half turn each way, and dragging the handle snaps with Shift", () => {
|
||||
assert.equal(wrapHalfTurn(190), -170);
|
||||
assert.equal(wrapHalfTurn(-190), 170);
|
||||
assert.equal(wrapHalfTurn(180), -180);
|
||||
assert.equal(dragRotation(10, 0, Math.PI / 6, true), 45);
|
||||
assert.equal(dragRotation(0, 0, (7 * Math.PI) / 180, true), 15 * Math.round(7 / 15));
|
||||
assert.equal(dragRotation(0, 0, (7.04 * Math.PI) / 180, false), 7);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The picture behind a floor plan (a scan of the architect's drawing, say): its size follows from the picture's aspect, and the
|
||||
// helpers here straighten it, scale it to a measured length, and map plan points into it.
|
||||
|
||||
import type { Background, Vec2 } from "../../../model.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** The picture's own height in metres. */
|
||||
export const pictureHeight = (bg: Background, aspect: number): number => bg.width * aspect;
|
||||
|
||||
/** The middle of the picture in the plan. */
|
||||
export const pictureCentre = (bg: Background, aspect: number): Vec2 => [bg.x + bg.width / 2, bg.z + pictureHeight(bg, aspect) / 2];
|
||||
|
||||
/** A point turned about another by an angle in radians (clockwise in the plan, where z points down). */
|
||||
function turnAbout(point: Vec2, about: Vec2, angle: number): Vec2 {
|
||||
const [dx, dz] = [point[0] - about[0], point[1] - about[1]];
|
||||
return [about[0] + dx * Math.cos(angle) - dz * Math.sin(angle), about[1] + dx * Math.sin(angle) + dz * Math.cos(angle)];
|
||||
}
|
||||
|
||||
/** An angle in degrees brought into -180 up to 180. */
|
||||
export const wrapHalfTurn = (degrees: number): number => (((((degrees + 180) % 360) + 360) % 360) - 180);
|
||||
|
||||
/** The picture placed so that its middle is at `centre`. */
|
||||
function centredAt(centre: Vec2, width: number, height: number): Pick<Background, "x" | "z"> {
|
||||
return { x: thousandths(centre[0] - width / 2), z: thousandths(centre[1] - height / 2) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the picture about the first of two tapped points so that the line between them runs exactly along x or z, whichever is
|
||||
* nearer. Null when the points are too close together or the line already is straight.
|
||||
*/
|
||||
export function straightened(bg: Background, aspect: number, p: Vec2, q: Vec2): Background | null {
|
||||
if (Math.hypot(q[0] - p[0], q[1] - p[1]) < 0.05) return null;
|
||||
const angle = Math.atan2(q[1] - p[1], q[0] - p[0]);
|
||||
const correction = Math.round(angle / (Math.PI / 2)) * (Math.PI / 2) - angle;
|
||||
if (Math.abs(correction) < 1e-4) return null;
|
||||
// turning about p carries the picture's middle along
|
||||
const centre = turnAbout(pictureCentre(bg, aspect), p, correction);
|
||||
const rotation = Math.round(wrapHalfTurn((bg.rotation ?? 0) + (correction * 180) / Math.PI) * 100) / 100;
|
||||
return { ...bg, rotation, ...centredAt(centre, bg.width, pictureHeight(bg, aspect)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales the picture about the first of two points so that the stretch between them measures `real` metres. The turn is kept.
|
||||
* Null when the stretch is too short to measure or the real length is no positive number.
|
||||
*/
|
||||
export function scaledToLength(bg: Background, aspect: number, a: Vec2, b: Vec2, real: number): Background | null {
|
||||
const measured = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
if (!(real > 0) || measured < 1e-4) return null;
|
||||
const k = real / measured;
|
||||
const [cx, cz] = pictureCentre(bg, aspect);
|
||||
const centre: Vec2 = [a[0] + k * (cx - a[0]), a[1] + k * (cz - a[1])];
|
||||
const width = bg.width * k;
|
||||
return { ...bg, width: thousandths(width), ...centredAt(centre, width, pictureHeight(bg, aspect) * k) };
|
||||
}
|
||||
|
||||
/** A plan point measured in the picture's own frame: from its top left corner, along its (turned) sides, in metres. */
|
||||
export function pictureLocal(bg: Background, aspect: number, world: Vec2): Vec2 {
|
||||
const turned = turnAbout(world, pictureCentre(bg, aspect), (-(bg.rotation ?? 0) * Math.PI) / 180);
|
||||
return [turned[0] - bg.x, turned[1] - bg.z];
|
||||
}
|
||||
|
||||
/** The rotation the picture gets while its turn handle is dragged: whole 15° steps with Shift, tenths of a degree otherwise. */
|
||||
export function dragRotation(startRotation: number, startAngle: number, nowAngle: number, snap: boolean): number {
|
||||
const raw = startRotation + ((nowAngle - startAngle) * 180) / Math.PI;
|
||||
return wrapHalfTurn(snap ? Math.round(raw / 15) * 15 : Math.round(raw * 10) / 10);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { distance, fingerprintsOf, locate, medianReading, replaceRoom, signalLevel } from "./ble.ts";
|
||||
|
||||
const prints = [
|
||||
{ room: "kitchen", rssi: { a: -50, b: -80, c: -90 } },
|
||||
{ room: "kitchen", rssi: { a: -55, b: -78, c: -92 } },
|
||||
{ room: "bath", rssi: { a: -85, b: -45, c: -70 } },
|
||||
{ room: "hall", rssi: { a: -75, b: -75, c: -50 } },
|
||||
];
|
||||
|
||||
test("the distance is zero for the same pattern, a missing scanner counts as far, and differences are capped", () => {
|
||||
assert.equal(distance({ a: -60 }, { a: -60 }), 0);
|
||||
assert.ok(Math.abs(distance({ a: -60, b: -50 }, { a: -60 }) - Math.sqrt((40 * 40) / 2)) < 1e-9);
|
||||
assert.equal(distance({}, {}), Infinity);
|
||||
});
|
||||
|
||||
test("the nearest room wins, also when a room has several spots", () => {
|
||||
const k = locate(prints, { a: -53, b: -79, c: -91 });
|
||||
assert.equal(k.room, "kitchen");
|
||||
assert.ok(k.distance < 5 && k.margin > 20);
|
||||
assert.equal(locate(prints, { a: -84, b: -47, c: -71 }).room, "bath");
|
||||
assert.equal(locate(prints, { a: -76, b: -74, c: -52 }).room, "hall");
|
||||
});
|
||||
|
||||
test("nothing heard, no fingerprints or nothing close gives no room", () => {
|
||||
assert.equal(locate(prints, {}).room, null);
|
||||
assert.equal(locate([], { a: -60 }).room, null);
|
||||
assert.equal(locate(prints, { a: -30, b: -30, c: -30 }).room, null);
|
||||
});
|
||||
|
||||
test("the median drops a scanner that missed most samples", () => {
|
||||
assert.deepEqual(medianReading([{ a: -60, b: -70 }, { a: -64, b: -72 }, { a: -62 }, { a: -61 }]), { a: -61.5 });
|
||||
assert.deepEqual(medianReading([]), {});
|
||||
});
|
||||
|
||||
test("a walk through a room becomes up to three fingerprints of its own stretches", () => {
|
||||
const walk = Array.from({ length: 20 }, (_, i) => ({ a: -50 - i, b: -80 + i }));
|
||||
const fps = fingerprintsOf("kitchen", walk);
|
||||
assert.equal(fps.length, 3);
|
||||
assert.ok(fps[0].rssi.a > fps[2].rssi.a);
|
||||
assert.deepEqual(fingerprintsOf("kitchen", [{ a: -60 }, { a: -61 }]).length, 1);
|
||||
assert.deepEqual(fingerprintsOf("kitchen", [{}, {}, {}]), []);
|
||||
});
|
||||
|
||||
test("recording a room again replaces its fingerprints and keeps the others", () => {
|
||||
const out = replaceRoom(prints, "kitchen", [{ room: "kitchen", rssi: { a: -40 } }]);
|
||||
assert.equal(out.filter((p) => p.room === "kitchen").length, 1);
|
||||
assert.equal(out.length, 3);
|
||||
});
|
||||
|
||||
test("signal bars run from nothing at −95 dBm to full at −45", () => {
|
||||
assert.equal(signalLevel(-100), 0);
|
||||
assert.equal(signalLevel(-70), 0.5);
|
||||
assert.equal(signalLevel(-40), 1);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
// Locating a Bluetooth tag by room, the editor's side: the same comparison the backend sensor makes (custom_components/nextfloor/ble.py),
|
||||
// so the editor can show "now: kitchen" while you walk, and the recording of a room into fingerprints.
|
||||
|
||||
import type { BleFingerprint } from "../../../model.ts";
|
||||
|
||||
export type Reading = Record<string, number>;
|
||||
|
||||
/** A scanner that does not hear the tag counts as this (dBm); differences are capped at MAX_DIFF. */
|
||||
export const MISSING = -100;
|
||||
export const MAX_DIFF = 40;
|
||||
/** Above this distance (RMS in dB) no room is a good match. */
|
||||
export const UNKNOWN_DISTANCE = 18;
|
||||
|
||||
/** How long a room is recorded, how often it is sampled, and into how many spots the samples are split. */
|
||||
export const RECORD_SECONDS = 30;
|
||||
export const SAMPLE_EVERY_MS = 1500;
|
||||
export const SPOTS_PER_ROOM = 3;
|
||||
|
||||
export function distance(a: Reading, b: Reading): number {
|
||||
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
||||
if (keys.size === 0) return Infinity;
|
||||
let total = 0;
|
||||
for (const k of keys) total += Math.min(Math.abs((a[k] ?? MISSING) - (b[k] ?? MISSING)), MAX_DIFF) ** 2;
|
||||
return Math.sqrt(total / keys.size);
|
||||
}
|
||||
|
||||
export interface Located {
|
||||
room: string | null;
|
||||
distance: number;
|
||||
/** How far the runner-up room is behind the winner (dB). */
|
||||
margin: number;
|
||||
}
|
||||
|
||||
export function locate(prints: readonly BleFingerprint[], reading: Reading): Located {
|
||||
if (Object.keys(reading).length === 0) return { room: null, distance: Infinity, margin: 0 };
|
||||
const best = new Map<string, number>();
|
||||
for (const fp of prints) {
|
||||
const d = distance(fp.rssi, reading);
|
||||
if (d < (best.get(fp.room) ?? Infinity)) best.set(fp.room, d);
|
||||
}
|
||||
const ranked = [...best].sort((p, q) => p[1] - q[1]);
|
||||
if (ranked.length === 0) return { room: null, distance: Infinity, margin: 0 };
|
||||
const [room, dist] = ranked[0];
|
||||
if (dist > UNKNOWN_DISTANCE) return { room: null, distance: dist, margin: 0 };
|
||||
return { room, distance: dist, margin: ranked.length > 1 ? ranked[1][1] - dist : UNKNOWN_DISTANCE };
|
||||
}
|
||||
|
||||
const median = (values: number[]): number => {
|
||||
const s = [...values].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
|
||||
/** The median signal per scanner over some samples; a scanner that missed the tag in most of them is left out. */
|
||||
export function medianReading(samples: readonly Reading[]): Reading {
|
||||
const out: Reading = {};
|
||||
const keys = new Set(samples.flatMap((s) => Object.keys(s)));
|
||||
for (const k of keys) {
|
||||
const values = samples.filter((s) => k in s).map((s) => s[k]);
|
||||
if (values.length * 2 > samples.length) out[k] = Math.round(median(values) * 10) / 10;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Turns the samples taken while walking through a room into up to `spots` fingerprints (one per stretch of the walk). */
|
||||
export function fingerprintsOf(room: string, samples: readonly Reading[], spots = SPOTS_PER_ROOM): BleFingerprint[] {
|
||||
const heard = samples.filter((s) => Object.keys(s).length > 0);
|
||||
if (heard.length === 0) return [];
|
||||
const n = Math.max(1, Math.min(spots, Math.floor(heard.length / 3)));
|
||||
const out: BleFingerprint[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const chunk = heard.slice(Math.floor((i * heard.length) / n), Math.floor(((i + 1) * heard.length) / n));
|
||||
const rssi = medianReading(chunk);
|
||||
if (Object.keys(rssi).length > 0) out.push({ room, rssi });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The prints of a tag with the ones of `room` replaced by new ones. */
|
||||
export const replaceRoom = (prints: readonly BleFingerprint[], room: string, fresh: readonly BleFingerprint[]): BleFingerprint[] => [
|
||||
...prints.filter((p) => p.room !== room),
|
||||
...fresh,
|
||||
];
|
||||
|
||||
/** The signal bar for a dBm value: 0 … 1 (−95 and below nothing, −45 and above full). */
|
||||
export const signalLevel = (dbm: number): number => Math.max(0, Math.min(1, (dbm + 95) / 50));
|
||||
@@ -0,0 +1,101 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
import { CATEGORIES, cardsOf, categoryOf, mainCategory, roomCategories, sizeLabel, withRecent, type CatalogEntry } from "./catalog.ts";
|
||||
|
||||
const pack = (id: string, extra: Partial<CatalogEntry> = {}, source = "nextfloor.demo"): CatalogEntry => ({ type: `pack:${source}:${id}`, source, id, size: [1, 0.6, 0.8], ...extra });
|
||||
|
||||
/** Every item of the packs that ship with NextFloor. */
|
||||
function builtinPackEntries(): CatalogEntry[] {
|
||||
const dir = new URL("../../../../../custom_components/nextfloor/packs/", import.meta.url);
|
||||
return readdirSync(dir).flatMap((file) => {
|
||||
const p = JSON.parse(readFileSync(new URL(file, dir), "utf8")) as { id: string; items: { id: string; size: [number, number, number]; light?: string; electric?: boolean; vehicle?: boolean; climate?: boolean }[] };
|
||||
return p.items.map((it) => pack(it.id, { size: it.size, lamp: !!it.light, electric: !!it.electric, vehicle: !!it.vehicle, climate: !!it.climate }, p.id));
|
||||
});
|
||||
}
|
||||
|
||||
test("items are sorted by what they are, not by the pack they come from", () => {
|
||||
assert.equal(categoryOf({ type: "sofa", source: "living", id: "sofa", size: [2, 0.9, 0.8] }), "seating");
|
||||
assert.equal(categoryOf({ type: "lamp_floor", source: "lights", id: "lamp_floor", size: [0.4, 0.4, 1.6], lamp: true }), "lights");
|
||||
assert.equal(categoryOf(pack("vanity_80")), "bath");
|
||||
assert.equal(categoryOf(pack("base_60")), "kitchen");
|
||||
assert.equal(categoryOf(pack("tesla_model_3", { vehicle: true })), "vehicles");
|
||||
assert.equal(categoryOf(pack("thermostat_wall", { climate: true })), "climate");
|
||||
});
|
||||
|
||||
test("a glowing item is filed by what it is, a lamp among the lights", () => {
|
||||
assert.equal(categoryOf(pack("aquarium_240", { lamp: true })), "pets");
|
||||
assert.equal(categoryOf(pack("fireplace_wall", { lamp: true })), "climate");
|
||||
assert.equal(categoryOf(pack("inverter", { lamp: true })), "energy");
|
||||
assert.equal(categoryOf(pack("floor_lamp_arc", { lamp: true })), "lights");
|
||||
assert.equal(categoryOf(pack("orb_lamp", { lamp: true })), "lights");
|
||||
assert.equal(categoryOf(pack("unknown_glow", { lamp: true })), "lights");
|
||||
});
|
||||
|
||||
test("words inside other words do not mislead the sorting", () => {
|
||||
assert.equal(categoryOf(pack("display_8")), "media", "display_ is not play_");
|
||||
assert.equal(categoryOf(pack("cat_steps")), "pets", "cat steps are not stairs");
|
||||
assert.equal(categoryOf(pack("whirlpool_indoor")), "bath", "a whirlpool is not a garden pool");
|
||||
assert.equal(categoryOf(pack("console")), "tables");
|
||||
assert.equal(categoryOf(pack("game_console")), "media");
|
||||
});
|
||||
|
||||
test("every built-in pack item lands in a category, and few are left as decoration", () => {
|
||||
const entries = builtinPackEntries();
|
||||
assert.ok(entries.length > 500);
|
||||
const decor = entries.filter((e) => categoryOf(e) === "decor");
|
||||
assert.ok(decor.length <= 15, `too many unsorted items: ${decor.map((e) => e.id).join(", ")}`);
|
||||
const used = new Set(entries.map(categoryOf));
|
||||
for (const c of CATEGORIES) assert.ok(used.has(c) || c === "decor", `no item in ${c}`);
|
||||
});
|
||||
|
||||
test("a room's name picks the categories that fit it, lights always among them", () => {
|
||||
const kitchen = roomCategories("Küche")!;
|
||||
assert.ok(kitchen.has("kitchen") && kitchen.has("lights") && !kitchen.has("beds"));
|
||||
assert.ok(roomCategories("Master Bedroom")!.has("beds"));
|
||||
assert.ok(roomCategories("Gäste-WC")!.has("bath"));
|
||||
assert.ok(roomCategories("Terrasse")!.has("garden"));
|
||||
assert.equal(roomCategories("Raum 3"), null);
|
||||
assert.equal(roomCategories(undefined), null);
|
||||
});
|
||||
|
||||
test("one model in several sizes becomes one card, smallest first", () => {
|
||||
const cards = cardsOf([pack("bed_160", { size: [1.6, 2, 0.4] }), pack("bed_90", { size: [0.9, 2, 0.4] }), pack("bed_140", { size: [1.4, 2, 0.4] }), pack("bed_canopy")]);
|
||||
assert.equal(cards.length, 2);
|
||||
assert.deepEqual(cards[0].entries.map((e) => e.id), ["bed_90", "bed_140", "bed_160"]);
|
||||
assert.deepEqual(cards[0].entries.map((e) => sizeLabel(e, cards[0].entries)), ["90", "140", "160"]);
|
||||
});
|
||||
|
||||
test("vehicles, built-in types and items of other packs keep their own cards", () => {
|
||||
const cards = cardsOf([
|
||||
pack("tesla_model_y", { vehicle: true }),
|
||||
pack("tesla_model_y_2025", { vehicle: true }),
|
||||
pack("sofa_3", {}, "nextfloor.a"),
|
||||
pack("sofa_2", {}, "nextfloor.b"),
|
||||
{ type: "sofa", source: "living", id: "sofa", size: [2, 0.9, 0.8] },
|
||||
]);
|
||||
assert.equal(cards.length, 5);
|
||||
});
|
||||
|
||||
test("sizes sharing a width are told apart by the size in their id", () => {
|
||||
const all = [pack("cube_2x2", { size: [0.77, 0.39, 0.77] }), pack("cube_4x2", { size: [0.77, 0.39, 1.47] })];
|
||||
assert.deepEqual(all.map((e) => sizeLabel(e, all)), ["2x2", "4x2"]);
|
||||
});
|
||||
|
||||
test("the recently used list keeps the newest first, once each", () => {
|
||||
assert.deepEqual(withRecent(["a", "b", "c"], "b"), ["b", "a", "c"]);
|
||||
assert.deepEqual(withRecent(["a", "b"], "c", 2), ["c", "a"]);
|
||||
});
|
||||
|
||||
test("a room opens with its main kind of furniture", () => {
|
||||
assert.equal(mainCategory("Küche"), "kitchen");
|
||||
assert.equal(mainCategory("Kinderzimmer"), "kids");
|
||||
assert.equal(mainCategory("Schlafzimmer"), "beds");
|
||||
assert.equal(mainCategory("Raum 3"), null);
|
||||
});
|
||||
|
||||
test("a word inside a room name does not pick the wrong room", () => {
|
||||
assert.equal(mainCategory("Fitnessraum"), "fitness", "fitness is not a dining room");
|
||||
assert.equal(mainCategory("Wohn-/Esszimmer"), "seating");
|
||||
assert.equal(mainCategory("Esszimmer"), "tables");
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
// The furniture library sorted by what an item is (sofas, beds, kitchen …) instead of where it comes from, the categories that fit a
|
||||
// room by its name, and items of one model in several sizes folded into one card. Pure functions over ids, names and sizes.
|
||||
|
||||
export const CATEGORIES = [
|
||||
"lights",
|
||||
"seating",
|
||||
"tables",
|
||||
"storage",
|
||||
"beds",
|
||||
"kitchen",
|
||||
"appliances",
|
||||
"bath",
|
||||
"media",
|
||||
"office",
|
||||
"tech",
|
||||
"climate",
|
||||
"energy",
|
||||
"garden",
|
||||
"plants",
|
||||
"kids",
|
||||
"fitness",
|
||||
"pets",
|
||||
"workshop",
|
||||
"music",
|
||||
"season",
|
||||
"pictures",
|
||||
"vehicles",
|
||||
"building",
|
||||
"decor",
|
||||
] as const;
|
||||
|
||||
export type Category = (typeof CATEGORIES)[number];
|
||||
|
||||
/** What the catalogue needs to know about an item. */
|
||||
export interface CatalogEntry {
|
||||
type: string;
|
||||
/** The built-in group ("living", "kitchen" …) or the pack id ("nextfloor.a_kueche"). */
|
||||
source: string;
|
||||
/** Item id inside its pack, or the built-in type. */
|
||||
id: string;
|
||||
/** Size in metres [w, d, h]. */
|
||||
size: readonly [number, number, number];
|
||||
lamp?: boolean;
|
||||
electric?: boolean;
|
||||
vehicle?: boolean;
|
||||
climate?: boolean;
|
||||
}
|
||||
|
||||
// built-in types first: their group says little ("living" holds sofas and plants), so each type is named
|
||||
const BUILT_IN: Record<string, Category> = {
|
||||
sofa: "seating",
|
||||
armchair: "seating",
|
||||
stool: "seating",
|
||||
chair: "seating",
|
||||
bench: "seating",
|
||||
corner_bench: "seating",
|
||||
bar_stool: "seating",
|
||||
office_chair: "office",
|
||||
coffee_table: "tables",
|
||||
table: "tables",
|
||||
table_round: "tables",
|
||||
desk: "office",
|
||||
worktop: "kitchen",
|
||||
tv_board: "media",
|
||||
tv_wall: "media",
|
||||
sideboard: "storage",
|
||||
shelf: "storage",
|
||||
tall_cabinet: "storage",
|
||||
wardrobe: "storage",
|
||||
dresser: "storage",
|
||||
nightstand: "beds",
|
||||
coat_rack: "storage",
|
||||
plant: "plants",
|
||||
rug: "decor",
|
||||
kitchen: "kitchen",
|
||||
kitchen_wall: "kitchen",
|
||||
kitchen_tall: "kitchen",
|
||||
island: "kitchen",
|
||||
sink: "kitchen",
|
||||
stove: "kitchen",
|
||||
dishwasher: "appliances",
|
||||
fridge: "appliances",
|
||||
washer: "appliances",
|
||||
dryer: "appliances",
|
||||
robot_vacuum: "appliances",
|
||||
bed: "beds",
|
||||
bunk_bed: "beds",
|
||||
bathtub: "bath",
|
||||
shower: "bath",
|
||||
wc: "bath",
|
||||
washbasin: "bath",
|
||||
radiator: "climate",
|
||||
stairs: "building",
|
||||
parking: "vehicles",
|
||||
ceiling_fan: "lights",
|
||||
};
|
||||
|
||||
// pack items by words in their id, checked in this order (the first hit wins)
|
||||
const RULES: [RegExp, Category][] = [
|
||||
[/xmas|advent|window_star|candle_arch|reindeer|pumpkin|easter|snowman|gift_pile|lights_outdoor/, "season"],
|
||||
[/^frame_|^canvas$|^poster$|picture_ledge/, "pictures"],
|
||||
[/piano|drum_kit|guitar|synth|mic_stand|vinyl|easel|studio_monitor|mixing_desk/, "music"],
|
||||
[/lamp|pendant|light_pillar|light_bars|mood_spot|ceiling_panel|garden_spots|wall_light|light_cove|niche_led|shelf_led|monitor_light|workshop_light|painting_light|cabinet_light|moon_light|torch|lantern|ceiling_fan_light/, "lights"],
|
||||
[/cat_|dog_|pet_|litter|scratch|hamster|rabbit|bird_cage|small_animal|aquarium|terrarium/, "pets"],
|
||||
[/stairs|steps|landing|rail_|column|pilaster|beam|chimney|glass_wall|sliding_wall|half_wall|platform|niche_shelf|window_seat|divider_slats|gallery/, "building"],
|
||||
[/tree|shrub|conifer|hedge|brush|monstera|plant|herb_garden|herb_planter|flower|raised_bed|greenhouse|ficus|cactus|bonsai|living_wall|vertical_garden/, "plants"],
|
||||
[/kids|toy|teepee|(^|_)play_|rocking_horse|ball_pit|house_bed|cot\b|^cot|crib|changing_table|baby|loft_bed|star_projector|moon_light/, "kids"],
|
||||
[/treadmill|fitness|power_rack|rowing|rower|spin_bike|dumbbell|punching|yoga|elliptical|gym|exercise|wall_bars|bike_trainer|kettlebell|weight_bench|massage_chair/, "fitness"],
|
||||
[/heat_pump|boiler|buffer_tank|manifold|ventilation|radiator|towel_heater|thermostat|air_purifier|humidifier|dehumidifier|tower_fan|ceiling_fan|hot_water|water_softener|water_pump|fireplace|wood_stove|patio_heater|sauna|oil_|expansion_vessel|water_tank|infrared|cold_bath/, "climate"],
|
||||
[/wallbox|inverter|battery|solar|meter|fuse_box|grid/, "energy"],
|
||||
[/workbench|tool_|compressor|drill|tyre|paint_cabinet|heavy_shelf|shelf_rack|garage_opener|workshop|bike_stand|bike_holder|bike_rack|lawn_mower|mower|welder|ev_bike_charger|tool_chest|parts_cabinet/, "workshop"],
|
||||
[/speaker|subwoofer|soundbar|receiver|turntable|record|game_console|multiroom|hifi|cinema|acoustic|bass_trap|popcorn|projector|projection|screen|display_|smart_display|media|tv|arcade|star_ceiling|av_/, "media"],
|
||||
[/desk|office|filing|whiteboard|monitor|bookcase|phone_booth|sim_cockpit|chair_gaming|gaming/, "office"],
|
||||
[/server|nas|router|wifi|access_point|network|printer|filament|tower_pc|smoke_detector|siren|baby_monitor|sunrise_clock|light_switch|socket|co_detector|presence_|water_leak|air_quality|doorbell/, "tech"],
|
||||
[/grill|lounge|lounger|parasol|pergola|hot_tub|fire_bowl|torch|lantern|play_tower|garden|trampoline|sprinkler|valve|rain_barrel|outdoor|hammock|(^|_)pool|swing|bin_box|^bin_|mailbox|rotary_line|kamado|pizza_oven|fire_pit|sandbox|wood_pile|bird_house|cistern|pond|water_feature|beach_chair/, "garden"],
|
||||
[/vanity_\d|vanity_double|double_vanity|basin|bath|shower|toilet|bidet|towel|mirror_cabinet|mirror_round|mirror_80|mirror_led|whirlpool|washer_under|laundry|urinal|wt_\d|handtuch|seife|wc/, "bath"],
|
||||
[/fridge|freezer|dishwasher|washer|dryer|microwave|coffee_machine|kettle|toaster|mixer|oven|steam|vacuum|ironing|drying_rack|trash|water_cooler|drip_tray|espresso|air_fryer|water_bar|thermo_cooker/, "appliances"],
|
||||
[/base_|drawer_|sink|hob|cooker|hood|pantry|kitchen|island|breakfast_bar|wall_\d|wall_glass|wall_corner|row_|spice|cabinet_light|trolley|bar_cart|utility_sink/, "kitchen"],
|
||||
[/bed|boxspring|futon|nightstand|canopy|mattress/, "beds"],
|
||||
[/sofa|chair|armchair|stool|bench|pouf|bean_bag|recliner|wingback|chaise|seat|ektorp|poang|cosy_corner|swing_bench|hanging_chair|nook|floor_cushion|tatami/, "seating"],
|
||||
[/table|dining|coffee_|side_round|lack_|^console$|bekant|alex/, "tables"],
|
||||
[/wardrobe|closet|clothes_rail|chest|dresser|shelf|cabinet|sideboard|lowboard|highboard|kallax|billy|ivar|pax|besta|cube_|coat_stand|shoe_bench|divider|display_cabinet|wall_unit|malm_chest|locker/, "storage"],
|
||||
];
|
||||
|
||||
/** The category of an item. */
|
||||
export function categoryOf(entry: CatalogEntry): Category {
|
||||
if (entry.vehicle) return "vehicles";
|
||||
if (entry.climate) return "climate";
|
||||
if (!entry.type.startsWith("pack:")) return entry.lamp ? "lights" : (BUILT_IN[entry.type] ?? "decor");
|
||||
// a glowing item (an aquarium, a fireplace) has a light too, so what it is decides before that it glows
|
||||
const hit = RULES.find(([pattern]) => pattern.test(entry.id));
|
||||
return hit ? hit[1] : entry.lamp ? "lights" : "decor";
|
||||
}
|
||||
|
||||
// room names in German and English, and what belongs there besides lights (always offered)
|
||||
const ROOMS: [RegExp, Category[]][] = [
|
||||
[/k(u|ü)che|kitchen|kochen/, ["kitchen", "appliances", "tables", "seating", "storage", "plants", "decor"]],
|
||||
[/wohn|living|lounge|salon/, ["seating", "tables", "storage", "media", "plants", "decor", "climate", "tech"]],
|
||||
[/\bess|dining/, ["tables", "seating", "storage", "plants", "decor", "media"]],
|
||||
[/schlaf|bed|gast|guest/, ["beds", "storage", "seating", "tables", "decor", "plants", "climate", "media"]],
|
||||
[/kind|kids|child|baby|spiel|play|nursery/, ["kids", "beds", "storage", "seating", "tables", "decor"]],
|
||||
[/bad|bath|wc|toilet|dusch|shower|sauna/, ["bath", "appliances", "storage", "climate", "plants"]],
|
||||
[/b(u|ü)ro|office|arbeit|study|work/, ["office", "tech", "storage", "seating", "tables", "plants"]],
|
||||
[/kino|cinema|media|game|gaming|hifi/, ["media", "seating", "tables", "storage", "office"]],
|
||||
[/fitness|gym|sport|training/, ["fitness", "media", "storage", "climate"]],
|
||||
[/garage|carport|stellplatz|parking/, ["vehicles", "workshop", "energy", "storage", "garden"]],
|
||||
[/werkstatt|workshop|hobby|keller|cellar|basement|lager|storage/, ["workshop", "storage", "appliances", "energy", "climate", "fitness", "tech"]],
|
||||
[/hauswirtschaft|hwr|utility|laundry|wasch|technik|heiz|boiler/, ["appliances", "climate", "energy", "storage", "tech", "bath"]],
|
||||
[/flur|diele|hall|entr|eingang|corridor|treppe|stair/, ["storage", "seating", "decor", "plants", "building"]],
|
||||
[/garten|garden|terrass|terrace|balkon|balcony|patio|hof|yard|pool/, ["garden", "plants", "seating", "tables", "pets", "kids"]],
|
||||
];
|
||||
|
||||
/** The categories that fit a room by its name; null when the name says nothing (then the whole library shows). */
|
||||
export function roomCategories(roomName: string | null | undefined): Set<Category> | null {
|
||||
const name = (roomName ?? "").toLowerCase();
|
||||
const hit = ROOMS.find(([pattern]) => pattern.test(name));
|
||||
return hit ? new Set<Category>(["lights", ...hit[1]]) : null;
|
||||
}
|
||||
|
||||
/** The category a room is mostly furnished from (a kitchen's kitchen units, a bedroom's beds); null when the name says nothing. */
|
||||
export function mainCategory(roomName: string | null | undefined): Category | null {
|
||||
const name = (roomName ?? "").toLowerCase();
|
||||
return ROOMS.find(([pattern]) => pattern.test(name))?.[1][0] ?? null;
|
||||
}
|
||||
|
||||
/** Items that stand outside: garden, plants, vehicles. */
|
||||
export const isOutdoorCategory = (category: Category): boolean => category === "garden" || category === "plants" || category === "vehicles";
|
||||
|
||||
/** One card of the library: an item, or one model in several sizes (the first is the one placed unless a size is picked). */
|
||||
export interface CatalogCard {
|
||||
key: string;
|
||||
category: Category;
|
||||
entries: CatalogEntry[];
|
||||
}
|
||||
|
||||
const sizeSuffix = /_(\d+(?:x\d+)?)$/;
|
||||
|
||||
/** Folds items of one model in several sizes (vanity_60, vanity_80 …) into one card; built-in types and vehicles stay on their own. */
|
||||
export function cardsOf(entries: readonly CatalogEntry[]): CatalogCard[] {
|
||||
const cards = new Map<string, CatalogCard>();
|
||||
for (const entry of entries) {
|
||||
const category = categoryOf(entry);
|
||||
const base = entry.type.startsWith("pack:") && !entry.vehicle ? entry.id.replace(sizeSuffix, "") : entry.id;
|
||||
const key = `${entry.source}:${base}`;
|
||||
const card = cards.get(key);
|
||||
if (card && card.category === category) card.entries.push(entry);
|
||||
else cards.set(card ? `${key}:${entry.id}` : key, { key: card ? `${key}:${entry.id}` : key, category, entries: [entry] });
|
||||
}
|
||||
for (const card of cards.values()) card.entries.sort((a, b) => a.size[0] - b.size[0] || a.size[1] - b.size[1]);
|
||||
return [...cards.values()];
|
||||
}
|
||||
|
||||
/** The label of a size chip: the width in cm, or the size in the item's id (2x2, 4x4) when several share a width. */
|
||||
export function sizeLabel(entry: CatalogEntry, all: readonly CatalogEntry[]): string {
|
||||
const cm = (m: number) => Math.round(m * 100);
|
||||
const sameWidth = all.some((e) => e !== entry && cm(e.size[0]) === cm(entry.size[0]));
|
||||
return sameWidth ? (sizeSuffix.exec(entry.id)?.[1] ?? `${cm(entry.size[0])}×${cm(entry.size[2])}`) : `${cm(entry.size[0])}`;
|
||||
}
|
||||
|
||||
/** The list a type was used in, with the newest first and at most `max` long. */
|
||||
export function withRecent(recent: readonly string[], type: string, max = 12): string[] {
|
||||
return [type, ...recent.filter((t) => t !== type)].slice(0, max);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture, Placement } from "../../../model.ts";
|
||||
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "./device-list.ts";
|
||||
|
||||
const pin = (id: string, x: number, z: number): Placement => ({ entity_id: id, x, z, y: null });
|
||||
const lamp = (id: string, entity: string, x: number, z: number): Furniture => ({ id, type: "lamp_ceiling", x, z, rotation: 0, w: 0.3, d: 0.3, h: 0.1, variant: null, entity });
|
||||
|
||||
test("pins and ceiling lamps inside the room count as placed in it", () => {
|
||||
const room = box("a", 0, 0, 4, 4);
|
||||
const floor = floorWith([room, box("b", 4, 0, 8, 4)], { placements: [pin("sensor.in", 1, 1), pin("sensor.out", 6, 1)], furniture: [lamp("l1", "light.in", 2, 2), lamp("l2", "light.out", 6, 2), { ...lamp("l3", "", 1, 1), entity: null }] });
|
||||
assert.deepEqual([...placedInRoom(floor, room)].sort(), ["light.in", "sensor.in"]);
|
||||
assert.deepEqual([...placedInRoom(undefined, room)], []);
|
||||
});
|
||||
|
||||
test("entities in other rooms, on any floor, are listed with that room's name", () => {
|
||||
const a = box("a", 0, 0, 4, 4);
|
||||
const upper = floorWith([{ ...box("c", 0, 0, 4, 4), name: "Attic" }], { id: "u", placements: [pin("sensor.up", 1, 1)] } as never);
|
||||
const ground = floorWith([a, { ...box("b", 4, 0, 8, 4), name: "Kitchen" }], { placements: [pin("sensor.here", 1, 1), pin("sensor.k", 6, 1)], furniture: [lamp("l", "light.k", 7, 2)] });
|
||||
const doc = { floors: [ground, upper] } as unknown as Building;
|
||||
const elsewhere = placedElsewhere(doc, a);
|
||||
assert.deepEqual([...elsewhere.entries()].sort(), [["light.k", "Kitchen"], ["sensor.k", "Kitchen"], ["sensor.up", "Attic"]]);
|
||||
assert.equal(elsewhere.has("sensor.here"), false);
|
||||
});
|
||||
|
||||
test("toggling adds an id or takes it out", () => {
|
||||
assert.deepEqual(withToggled(undefined, "a"), ["a"]);
|
||||
assert.deepEqual(withToggled(["a", "b"], "a"), ["b"]);
|
||||
assert.deepEqual(withToggled(["a"], "b"), ["a", "b"]);
|
||||
});
|
||||
|
||||
test("the search matches any of the texts, ignoring case, and an empty search matches all", () => {
|
||||
assert.equal(matchesQuery("", "x"), true);
|
||||
assert.equal(matchesQuery(" ", undefined), true);
|
||||
assert.equal(matchesQuery("lamp", "Floor Lamp", "light.x"), true);
|
||||
assert.equal(matchesQuery("LIGHT.X", "Floor Lamp", "light.x"), true);
|
||||
assert.equal(matchesQuery("fan", "Floor Lamp", "light.x"), false);
|
||||
});
|
||||
|
||||
test("options are ordered by rank and keep their order within a rank", () => {
|
||||
const options = [{ id: "c" }, { id: "a" }, { id: "b" }, { id: "d" }];
|
||||
assert.deepEqual(rankedBy(options, (id) => (id === "b" || id === "d" ? 0 : 1)).map((o) => o.id), ["b", "d", "c", "a"]);
|
||||
});
|
||||
|
||||
test("taking the first entries of several groups reports what did not fit", () => {
|
||||
const { taken, left } = takeFirst([{ ids: [1, 2, 3] }, { ids: [4, 5] }, { ids: [6] }], 4);
|
||||
assert.deepEqual(taken, [[1, 2, 3], [4], []]);
|
||||
assert.equal(left, 2);
|
||||
assert.deepEqual(takeFirst([{ ids: [1] }], 10), { taken: [[1]], left: 0 });
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
// What the device list of a room needs to know: which entities are placed in it, which in another room, and how options are ranked.
|
||||
|
||||
import { isLamp, pointInPolygon, type Building, type Floor, type Room } from "../../../model.ts";
|
||||
|
||||
/** An entity placed in the room: as a device pin, or as the light of a lamp. */
|
||||
export function placedInRoom(floor: Floor | undefined, room: Room): Set<string> {
|
||||
const placed = new Set<string>();
|
||||
for (const p of floor?.placements ?? []) if (pointInPolygon([p.x, p.z], room.points)) placed.add(p.entity_id);
|
||||
for (const m of floor?.furniture ?? []) if (isLamp(m.type) && m.entity && pointInPolygon([m.x, m.z], room.points)) placed.add(m.entity);
|
||||
return placed;
|
||||
}
|
||||
|
||||
/** Entities that are placed in a room other than this one, with the name of that room: placing them here moves them. */
|
||||
export function placedElsewhere(doc: Building, room: Room): Map<string, string> {
|
||||
const elsewhere = new Map<string, string>();
|
||||
for (const floor of doc.floors) {
|
||||
const spots: [string, number, number][] = [
|
||||
...floor.placements.map((p): [string, number, number] => [p.entity_id, p.x, p.z]),
|
||||
...floor.furniture.filter((m) => isLamp(m.type) && m.entity).map((m): [string, number, number] => [m.entity!, m.x, m.z]),
|
||||
];
|
||||
for (const [id, x, z] of spots) {
|
||||
const home = floor.rooms.find((r) => pointInPolygon([x, z], r.points));
|
||||
if (home && home.id !== room.id) elsewhere.set(id, home.name);
|
||||
}
|
||||
}
|
||||
return elsewhere;
|
||||
}
|
||||
|
||||
/** A list with an id added, or removed when it is there. Empty lists give undefined in the saved plan, so callers decide. */
|
||||
export const withToggled = (list: readonly string[] | undefined, id: string): string[] => ((list ?? []).includes(id) ? (list ?? []).filter((x) => x !== id) : [...(list ?? []), id]);
|
||||
|
||||
/** Whether an entity matches what was typed in the search box: its name (without the room's name), its id or its area. Empty matches all. */
|
||||
export function matchesQuery(query: string, ...texts: (string | undefined)[]): boolean {
|
||||
const q = query.trim().toLowerCase();
|
||||
return !q || texts.some((t) => (t ?? "").toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
/** Options for a climate sensor ordered by how likely they are the room's own: its area first, then the dedicated sensors of a room. */
|
||||
export function rankedBy<T extends { id: string }>(options: readonly T[], rank: (id: string) => number): T[] {
|
||||
return options.map((o) => ({ o, r: rank(o.id) })).sort((a, b) => a.r - b.r).map(({ o }) => o);
|
||||
}
|
||||
|
||||
/** Takes the first `limit` entries of areas' entity lists in order, and reports how many did not fit. */
|
||||
export function takeFirst<T>(groups: readonly { ids: readonly T[] }[], limit: number): { taken: T[][]; left: number } {
|
||||
let room = limit;
|
||||
let left = 0;
|
||||
const taken = groups.map((g) => {
|
||||
const part = g.ids.slice(0, Math.max(0, room));
|
||||
room -= part.length;
|
||||
left += g.ids.length - part.length;
|
||||
return [...part];
|
||||
});
|
||||
return { taken, left };
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { aimReach, dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./drags.ts";
|
||||
|
||||
test("the pointer's distance is counted in whole grid steps", () => {
|
||||
assert.deepEqual(steppedDelta([0, 0], [0.26, -0.24], 0.1), [0.30000000000000004, -0.2]);
|
||||
assert.equal(dragStep(0.1, false), 0.1);
|
||||
assert.equal(dragStep(0.1, true), 0.01);
|
||||
});
|
||||
|
||||
test("a drag starts once the pointer has left the circle around its start", () => {
|
||||
assert.equal(hasLeftStart([0, 0], [3, 3]), false);
|
||||
assert.equal(hasLeftStart([0, 0], [4, 4]), true);
|
||||
assert.equal(hasLeftStart([0, 0], [3, 3], 4), true);
|
||||
});
|
||||
|
||||
test("with Shift a wall is held straight along the axis the pointer is nearer to", () => {
|
||||
assert.deepEqual(straightEnd([0, 0], [5, 1], true), [5, 0]);
|
||||
assert.deepEqual(straightEnd([0, 0], [1, 5], true), [0, 5]);
|
||||
assert.deepEqual(straightEnd([0, 0], [5, 1], false), [5, 1]);
|
||||
});
|
||||
|
||||
test("a piece lands on the grid after the pointer moved it", () => {
|
||||
assert.deepEqual(gridPositionAfter([1.04, 2], [0, 0], [0.52, 0.3], 0.1), [1.6, 2.3]);
|
||||
assert.deepEqual(shifted([1, 1], [0.0004, 2]), [1, 3]);
|
||||
});
|
||||
|
||||
test("facing: 0° looks towards +z, and the angle turns with the pointer in steps", () => {
|
||||
assert.equal(facingAngle([0, 0], [0, 5], 15), 0);
|
||||
assert.equal(facingAngle([0, 0], [-5, 0], 15), 90);
|
||||
assert.equal(facingAngle([0, 0], [0, -5], 15), 180);
|
||||
assert.equal(facingAngle([0, 0], [5, 0], 15), 270);
|
||||
assert.equal(facingAngle([0, 0], [-5, 0.3], 1), 87);
|
||||
});
|
||||
|
||||
test("the ground field's heading counts from up in the plan", () => {
|
||||
assert.equal(headingAngle([0, 0], [0, -5], 15), 0);
|
||||
assert.equal(headingAngle([0, 0], [5, 0], 15), 90);
|
||||
assert.equal(headingAngle([0, 0], [-5, 0], 15), -90);
|
||||
});
|
||||
|
||||
test("a camera's reach follows the pointer's distance within its limits", () => {
|
||||
assert.equal(aimReach([0, 0], [3, 4]), 5);
|
||||
assert.equal(aimReach([0, 0], [0.1, 0]), 0.5);
|
||||
assert.equal(aimReach([0, 0], [100, 0]), 50);
|
||||
});
|
||||
|
||||
test("dragging a corner of a rectangular area drags its neighbours along one axis each", () => {
|
||||
const rect: [number, number][] = [[0, 0], [4, 0], [4, 2], [0, 2]];
|
||||
assert.deepEqual(outlineWithCornerAt(rect, 2, [5.0004, 3]), [[0, 0], [5, 0], [5, 3], [0, 3]]);
|
||||
const triangle: [number, number][] = [[0, 0], [4, 0], [0, 3]];
|
||||
assert.deepEqual(outlineWithCornerAt(triangle, 1, [6, 1]), [[0, 0], [6, 1], [0, 3]]);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The arithmetic behind dragging in the plan: given where the drag started and where the pointer is now, what the thing dragged
|
||||
// becomes. All of these are pure, so the gesture code only has to pick the right one.
|
||||
|
||||
import { isAxisRect, type Vec2 } from "../../../model.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** How far the pointer moved from the start, in whole steps of the grid (a finer step with Alt). */
|
||||
export function steppedDelta(start: Vec2, now: Vec2, step: number): Vec2 {
|
||||
return [Math.round((now[0] - start[0]) / step) * step, Math.round((now[1] - start[1]) / step) * step];
|
||||
}
|
||||
|
||||
/** The grid step of a drag: the plan's grid, or 1 cm while Alt is held. */
|
||||
export const dragStep = (grid: number, fine: boolean): number => (fine ? 0.01 : grid);
|
||||
|
||||
/** A drag counts as a drag once the pointer has left a small circle around where it went down. */
|
||||
export const hasLeftStart = (a: readonly [number, number], b: readonly [number, number], pixels = 5): boolean => Math.hypot(a[0] - b[0], a[1] - b[1]) >= pixels;
|
||||
|
||||
/** The end of a wall being drawn. With Shift it is held straight: horizontal or vertical, whichever the pointer is nearer to. */
|
||||
export function straightEnd(start: Vec2, end: Vec2, straight: boolean): Vec2 {
|
||||
if (!straight) return end;
|
||||
return Math.abs(end[0] - start[0]) > Math.abs(end[1] - start[1]) ? [end[0], start[1]] : [start[0], end[1]];
|
||||
}
|
||||
|
||||
/** A point moved by a distance, rounded to a millimetre. */
|
||||
export const shifted = (p: Vec2, by: Vec2): Vec2 => [thousandths(p[0] + by[0]), thousandths(p[1] + by[1])];
|
||||
|
||||
/**
|
||||
* Where a piece that was at `from` ends up when the pointer moved from `start` to `now`: its own position moved by that distance and
|
||||
* then put on the grid.
|
||||
*/
|
||||
export function gridPositionAfter(from: Vec2, start: Vec2, now: Vec2, step: number): Vec2 {
|
||||
return [thousandths(Math.round((from[0] + now[0] - start[0]) / step) * step), thousandths(Math.round((from[1] + now[1] - start[1]) / step) * step)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The angle (degrees, 0 to 360) that turns the front of a piece at `centre` towards the pointer, in steps (15° normally, 1° with Alt).
|
||||
* Pieces face +z at 0°, so the angle is measured from there.
|
||||
*/
|
||||
export function facingAngle(centre: Vec2, pointer: Vec2, step: number): number {
|
||||
const raw = (Math.atan2(-(pointer[0] - centre[0]), pointer[1] - centre[1]) * 180) / Math.PI;
|
||||
return (((Math.round(raw / step) * step) % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
/** The same for the handle of a ground solar field, which points the other way round (up in the plan is 0°). */
|
||||
export function headingAngle(centre: Vec2, pointer: Vec2, step: number): number {
|
||||
const raw = (Math.atan2(pointer[0] - centre[0], -(pointer[1] - centre[1])) * 180) / Math.PI;
|
||||
return Math.round(raw / step) * step;
|
||||
}
|
||||
|
||||
/** How far a camera's view reaches while its handle is dragged: the distance to the pointer in tenths of a metre, between 0.5 and 50. */
|
||||
export const aimReach = (centre: Vec2, pointer: Vec2): number => Math.min(50, Math.max(0.5, Math.round(Math.hypot(pointer[0] - centre[0], pointer[1] - centre[1]) * 10) / 10));
|
||||
|
||||
/**
|
||||
* The outline of an outdoor area after one corner was dragged to `to`. A rectangle stays a rectangle: the corners that share an x or a
|
||||
* z with the dragged one follow along that axis.
|
||||
*/
|
||||
export function outlineWithCornerAt(points: readonly Vec2[], index: number, to: Vec2): Vec2[] {
|
||||
const keepsRectangle = isAxisRect([...points]);
|
||||
const was = points[index];
|
||||
const target: Vec2 = [thousandths(to[0]), thousandths(to[1])];
|
||||
return points.map((p, j): Vec2 => {
|
||||
if (j === index) return target;
|
||||
if (!keepsRectangle) return [p[0], p[1]];
|
||||
return [Math.abs(p[0] - was[0]) < 1e-6 ? target[0] : p[0], Math.abs(p[1] - was[1]) < 1e-6 ? target[1] : p[1]];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box } from "../../../entities/fixtures.ts";
|
||||
import type { Room } from "../../../model.ts";
|
||||
import { clearWallSlope, cutEdge, edgeLength, setWallSlope, joinAtCut, moveCut, setPartHeight, setWallHeight, setWallThickness, thicknessFromTyped } from "./edges.ts";
|
||||
|
||||
const room = (extra: Partial<Room> = {}): Room => ({ ...box("r", 0, 0, 6, 4), ...extra });
|
||||
|
||||
test("edge lengths follow the corners round the room", () => {
|
||||
const r = room();
|
||||
assert.deepEqual([0, 1, 2, 3].map((i) => edgeLength(r, i)), [6, 4, 6, 4]);
|
||||
});
|
||||
|
||||
test("a wall height is set per edge, and a list with nothing in it disappears", () => {
|
||||
const r = room();
|
||||
setWallHeight(r, 1, 1.2);
|
||||
assert.deepEqual(r.wall_heights, [null, 1.2, null, null]);
|
||||
setWallHeight(r, 1, null);
|
||||
assert.equal(r.wall_heights, undefined);
|
||||
});
|
||||
|
||||
test("a wall of several parts keeps a height per part, and equal parts collapse to one height", () => {
|
||||
const r = room();
|
||||
setPartHeight(r, 0, 1, 1, 2);
|
||||
assert.deepEqual(r.wall_heights![0], [null, 1]);
|
||||
setPartHeight(r, 0, 0, 1, 2);
|
||||
assert.equal(r.wall_heights![0], 1);
|
||||
setPartHeight(r, 0, 0, null, 2);
|
||||
setPartHeight(r, 0, 1, null, 2);
|
||||
assert.equal(r.wall_heights, undefined);
|
||||
// a single height spreads over the parts when one of them changes
|
||||
const s = room({ wall_heights: [2, null, null, null] });
|
||||
setPartHeight(s, 0, 1, 0.5, 3);
|
||||
assert.deepEqual(s.wall_heights![0], [2, 0.5, 2]);
|
||||
});
|
||||
|
||||
test("cutting an edge puts the cut in the middle of the piece, and short pieces are left alone", () => {
|
||||
const r = room();
|
||||
assert.equal(cutEdge(r, 0, undefined, [0]), true);
|
||||
assert.deepEqual(r.wall_splits![0], [3]);
|
||||
assert.equal(cutEdge(r, 0, 1, [0, 3]), true, "the part after the cut is 3 m long");
|
||||
assert.deepEqual(r.wall_splits![0], [3, 4.5]);
|
||||
const short = room({ points: [[0, 0], [0.3, 0], [0.3, 4], [0, 4]] });
|
||||
assert.equal(cutEdge(short, 0, undefined, [0]), false);
|
||||
assert.equal(short.wall_splits, undefined);
|
||||
});
|
||||
|
||||
test("a new part starts with the height of the part it was cut from", () => {
|
||||
const r = room({ wall_heights: [[1, 2], null, null, null] });
|
||||
cutEdge(r, 0, 1, [0, 2]);
|
||||
assert.deepEqual(r.wall_heights![0], [1, 2, 2]);
|
||||
});
|
||||
|
||||
test("a cut moves along the edge but keeps clear of the ends and of other cuts", () => {
|
||||
const r = room({ wall_splits: [[2, 4], null, null, null] });
|
||||
moveCut(r, 0, 2, 2.504, [0, 2, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [2.5, 4]);
|
||||
moveCut(r, 0, 2.5, 3.95, [0, 2.5, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [2.5, 4], "too close to the other cut: stays");
|
||||
moveCut(r, 0, 2.5, -3, [0, 2.5, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [0.1, 4]);
|
||||
moveCut(r, 0, 4, 99, [0, 0.1, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [0.1, 5.9]);
|
||||
});
|
||||
|
||||
test("joining at a cut drops it, merges the part's height into the one before, and cleans up", () => {
|
||||
const r = room({ wall_splits: [[3], null, null, null], wall_heights: [[1, 2], null, null, null] });
|
||||
joinAtCut(r, 0, 3, 1);
|
||||
assert.equal(r.wall_splits, undefined);
|
||||
assert.equal(r.wall_heights![0], 1);
|
||||
const two = room({ wall_splits: [[2, 4], null, null, null], wall_heights: [[1, 2, 3], null, null, null] });
|
||||
joinAtCut(two, 0, 2, 1);
|
||||
assert.deepEqual(two.wall_splits![0], [4]);
|
||||
assert.deepEqual(two.wall_heights![0], [1, 3]);
|
||||
});
|
||||
|
||||
test("a wall thickness is stored per edge and reset with null", () => {
|
||||
const r = room();
|
||||
setWallThickness(r, 2, 0.4);
|
||||
assert.deepEqual(r.wall_thickness, [null, null, 0.4, null]);
|
||||
setWallThickness(r, 2, null);
|
||||
assert.equal(r.wall_thickness, undefined);
|
||||
assert.equal(thicknessFromTyped(0.2449, 0.245), null);
|
||||
assert.equal(thicknessFromTyped(0.3, 0.12), 0.3);
|
||||
assert.equal(thicknessFromTyped(9, 0.12), 1.5);
|
||||
assert.equal(thicknessFromTyped(0, 0.12), 0.02);
|
||||
});
|
||||
|
||||
test("a wall slopes from its start to its end height; a level height, parts or clearing end the slope", () => {
|
||||
const r = room();
|
||||
setWallSlope(r, 1, 2.5, 4.7);
|
||||
assert.deepEqual([r.wall_heights, r.wall_slopes], [[null, 2.5, null, null], [null, 4.7, null, null]]);
|
||||
// heights are kept in sane limits
|
||||
setWallSlope(r, 1, 0, 99);
|
||||
assert.deepEqual([r.wall_heights?.[1], r.wall_slopes?.[1]], [0.05, 30]);
|
||||
// a level height ends the slope, and with nothing else set the lists disappear
|
||||
setWallHeight(r, 1, null);
|
||||
assert.deepEqual([r.wall_heights, r.wall_slopes], [undefined, undefined]);
|
||||
// heights per part and a slope exclude each other
|
||||
setWallSlope(r, 0, 2, 3);
|
||||
setPartHeight(r, 0, 1, 1.5, 2);
|
||||
assert.equal(r.wall_slopes, undefined);
|
||||
assert.deepEqual(r.wall_heights?.[0], [2, 1.5]);
|
||||
});
|
||||
|
||||
test("levelling a slope keeps its start height, and the full floor height when that is not lower", () => {
|
||||
const r = room();
|
||||
setWallSlope(r, 2, 1.2, 3);
|
||||
clearWallSlope(r, 2, 2.5);
|
||||
assert.deepEqual([r.wall_heights?.[2], r.wall_slopes], [1.2, undefined]);
|
||||
setWallSlope(r, 2, 4.7, 2.5);
|
||||
clearWallSlope(r, 2, 2.5);
|
||||
assert.equal(r.wall_heights, undefined, "from the floor height up it is a full wall again");
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
// Per-wall settings of a room: the height of each wall (or of each part of a wall that another room splits), the points where a wall
|
||||
// is cut by hand, and the thickness of one wall. All functions change the room they are given, which is a copy made by the editor.
|
||||
|
||||
import type { Room } from "../../../model.ts";
|
||||
|
||||
type Height = number | null | (number | null)[];
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const hundredths = (v: number) => Math.round(v * 100) / 100;
|
||||
|
||||
/** A per-edge list brought to exactly one entry per edge. */
|
||||
function perEdge<T>(list: readonly (T | null)[] | undefined, count: number): (T | null)[] {
|
||||
const out = [...(list ?? [])].slice(0, count);
|
||||
while (out.length < count) out.push(null);
|
||||
return out;
|
||||
}
|
||||
|
||||
const allNull = (list: readonly unknown[]) => list.every((x) => x === null);
|
||||
|
||||
/** The length of an edge of a room. */
|
||||
export function edgeLength(room: Room, edge: number): number {
|
||||
const [a, b] = [room.points[edge], room.points[(edge + 1) % room.points.length]];
|
||||
return Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
}
|
||||
|
||||
/** Sets the height of a whole edge; null is "as high as the floor", and a list with nothing set is dropped. */
|
||||
export function setWallHeight(room: Room, edge: number, height: number | null): void {
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
list[edge] = height;
|
||||
room.wall_heights = allNull(list) ? undefined : (list as Room["wall_heights"]);
|
||||
// a level height ends a slope
|
||||
setSlopeEnd(room, edge, null);
|
||||
}
|
||||
|
||||
function setSlopeEnd(room: Room, edge: number, end: number | null): void {
|
||||
if (end === null && !room.wall_slopes) return;
|
||||
const slopes = perEdge<number>(room.wall_slopes, room.points.length);
|
||||
slopes[edge] = end;
|
||||
room.wall_slopes = allNull(slopes) ? undefined : (slopes as number[]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a wall slope: `start` is its height at the first corner of the edge, `end` at the next one. The top runs straight between them
|
||||
* (a lean-to, clerestory windows); both may be above the floor height. Heights are kept between 5 cm and 30 m.
|
||||
*/
|
||||
export function setWallSlope(room: Room, edge: number, start: number, end: number): void {
|
||||
const [from, to] = [start, end].map((h) => Math.min(30, Math.max(0.05, thousandths(h))));
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
list[edge] = from;
|
||||
room.wall_heights = list as Room["wall_heights"];
|
||||
setSlopeEnd(room, edge, to);
|
||||
}
|
||||
|
||||
/** Levels a sloping wall again: it keeps its start height, and the full floor height when that is not lower. */
|
||||
export function clearWallSlope(room: Room, edge: number, floorHeight: number): void {
|
||||
const start = room.wall_heights?.[edge];
|
||||
setSlopeEnd(room, edge, null);
|
||||
if (typeof start === "number" && start >= floorHeight - 0.005) setWallHeight(room, edge, null);
|
||||
}
|
||||
|
||||
/** Sets the height of one part of an edge that has several parts. Parts that all end up the same collapse to one height. */
|
||||
export function setPartHeight(room: Room, edge: number, part: number, height: number | null, partCount: number): void {
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
const current = list[edge];
|
||||
const parts: (number | null)[] = Array.isArray(current) ? [...current] : new Array<number | null>(partCount).fill(typeof current === "number" ? current : null);
|
||||
while (parts.length < partCount) parts.push(null);
|
||||
parts[part] = height;
|
||||
list[edge] = parts.every((h) => h === parts[0]) ? parts[0] : parts;
|
||||
room.wall_heights = allNull(list) ? undefined : (list as Room["wall_heights"]);
|
||||
// heights per part and a slope over the whole wall exclude each other
|
||||
setSlopeEnd(room, edge, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts an edge (or one part of it) in the middle. The new part keeps the height of the one it was cut from. Nothing happens when the
|
||||
* piece is shorter than 40 cm. Returns whether it was cut.
|
||||
*/
|
||||
export function cutEdge(room: Room, edge: number, part: number | undefined, starts: readonly number[]): boolean {
|
||||
const length = edgeLength(room, edge);
|
||||
const from = part === undefined ? 0 : starts[part];
|
||||
const to = part === undefined ? length : (starts[part + 1] ?? length);
|
||||
if (to - from < 0.4) return false;
|
||||
const at = hundredths((from + to) / 2);
|
||||
const splits = perEdge<number[]>(room.wall_splits, room.points.length);
|
||||
splits[edge] = [...(splits[edge] ?? []), at].sort((a, b) => a - b);
|
||||
room.wall_splits = splits as Room["wall_splits"];
|
||||
const heights = room.wall_heights?.[edge];
|
||||
if (Array.isArray(heights)) heights.splice((part ?? 0) + 1, 0, heights[part ?? 0] ?? null);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Moves a cut along its edge, kept 10 cm from the ends and from other cuts (it stays where it was if it would come closer). */
|
||||
export function moveCut(room: Room, edge: number, from: number, to: number, otherStarts: readonly number[]): void {
|
||||
const length = edgeLength(room, edge);
|
||||
const others = otherStarts.filter((s) => Math.abs(s - from) > 1e-3 && s > 0);
|
||||
let at = Math.max(0.1, Math.min(length - 0.1, hundredths(to)));
|
||||
if (others.some((s) => Math.abs(s - at) < 0.1)) at = from;
|
||||
const list = room.wall_splits?.[edge];
|
||||
if (!list) return;
|
||||
const index = list.findIndex((d) => Math.abs(d - from) < 1e-3);
|
||||
if (index >= 0) list[index] = at;
|
||||
list.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/** Takes a cut away: the part behind it joins the one before, whose height stays. */
|
||||
export function joinAtCut(room: Room, edge: number, at: number, part: number): void {
|
||||
const splits = room.wall_splits;
|
||||
if (!splits?.[edge]) return;
|
||||
const left = splits[edge]!.filter((d) => Math.abs(d - at) > 1e-3);
|
||||
splits[edge] = left.length > 0 ? left : null;
|
||||
if (splits.every((l) => !l)) room.wall_splits = undefined;
|
||||
const heights = room.wall_heights?.[edge];
|
||||
if (Array.isArray(heights)) {
|
||||
heights.splice(part, 1);
|
||||
if (heights.every((h) => h === heights[0])) room.wall_heights![edge] = heights[0] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The thickness of one wall; null brings back the thickness of the house for walls of that kind. */
|
||||
export function setWallThickness(room: Room, edge: number, thickness: number | null, part?: number, partCount = 1): void {
|
||||
const list = perEdge<number | (number | null)[]>(room.wall_thickness, room.points.length);
|
||||
if (part === undefined || partCount < 2) list[edge] = thickness;
|
||||
else {
|
||||
// one part of a split edge: the others keep what the edge had
|
||||
const current = list[edge];
|
||||
const parts: (number | null)[] = Array.isArray(current) ? [...current] : new Array<number | null>(partCount).fill(typeof current === "number" ? current : null);
|
||||
while (parts.length < partCount) parts.push(null);
|
||||
parts[part] = thickness;
|
||||
list[edge] = parts.every((v) => v === parts[0]) ? parts[0] : parts;
|
||||
}
|
||||
room.wall_thickness = allNull(list) ? undefined : (list as Room["wall_thickness"]);
|
||||
}
|
||||
|
||||
/** A thickness typed for a wall: kept between 2 cm and 1.5 m, and null when it equals the default. */
|
||||
export function thicknessFromTyped(typed: number, standard: number): number | null {
|
||||
const value = Math.min(1.5, Math.max(0.02, thousandths(typed)));
|
||||
return Math.abs(value - standard) < 0.0005 ? null : value;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, floorWith, hassOf } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import { energyChecklist } from "./energy-checklist.ts";
|
||||
import { importEnergyPrefs } from "./energy-import.ts";
|
||||
|
||||
const device = (id: string, type: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type, x: 0, z: 0, rotation: 0, w: 1, d: 1, h: 1, variant: null, ...extra });
|
||||
const plan = (furniture: Furniture[], energy = {}, solar: unknown[] = []): Building =>
|
||||
({ version: 1, floors: [floorWith([], { furniture })], settings: { roof: { type: "none", solar } }, energy, presence: [] }) as unknown as Building;
|
||||
const none = new Map<string, { power: string | null }>();
|
||||
|
||||
test("an empty plan lists everything to do, with the battery and grid point optional", () => {
|
||||
const rows = energyChecklist(plan([]), none);
|
||||
assert.deepEqual(rows.map((r) => [r.label, r.state]), [["chk_solar_add", "todo"], ["chk_meter_add", "todo"], ["chk_inverter_add", "todo"], ["chk_battery_opt", "opt"], ["chk_grid_opt", "opt"]]);
|
||||
assert.deepEqual(rows[1].target, { kind: "add-device", type: "meter" });
|
||||
});
|
||||
|
||||
test("devices without a sensor ask for one, with a sensor (own or found) they are done", () => {
|
||||
const furniture = [device("m", "meter"), device("i", "inverter"), device("b", "home_battery")];
|
||||
const open = energyChecklist(plan(furniture, {}, [{ id: "f1" }]), none);
|
||||
assert.deepEqual(open.map((r) => r.state), ["ok", "todo", "todo", "todo", "opt"]);
|
||||
assert.equal(open[1].label, "chk_meter_sensor");
|
||||
const done = energyChecklist(plan([device("m", "meter", { power: "sensor.m" }), device("i", "inverter"), device("b", "home_battery", { power: "sensor.b", soc: "sensor.soc" })], {}, [{ id: "f1" }]), new Map([["i", { power: "sensor.found" }]]));
|
||||
assert.deepEqual(done.map((r) => r.state), ["ok", "ok", "ok", "ok", "opt"]);
|
||||
});
|
||||
|
||||
test("sensors chosen in the balance settings count for the devices", () => {
|
||||
const rows = energyChecklist(plan([device("m", "meter"), device("i", "inverter"), device("b", "home_battery")], { grid: "sensor.g", solar: "sensor.s", battery: "sensor.b" }), none);
|
||||
assert.deepEqual(rows.slice(1, 4).map((r) => r.state), ["ok", "ok", "ok"]);
|
||||
});
|
||||
|
||||
test("the inverter row points at the first inverter that still lacks a sensor", () => {
|
||||
const furniture = [device("i1", "inverter", { power: "sensor.a" }), device("i2", "inverter")];
|
||||
const row = energyChecklist(plan(furniture), none)[2];
|
||||
assert.equal(row.state, "todo");
|
||||
assert.ok(row.target.kind === "device" && row.target.item.id === "i2");
|
||||
});
|
||||
|
||||
function importSetup(furniture: Furniture[], statesOk = true) {
|
||||
const hass = Object.assign(
|
||||
hassOf(
|
||||
[entity("sensor.grid_power", "10", { device_class: "power" }), entity("sensor.pv_power", "5", { device_class: "power" })],
|
||||
{ "sensor.grid_power": { device_id: "dg" }, "sensor.pv_power": { device_id: "dp" }, "sensor.grid_energy": { device_id: "dg" }, "sensor.pv_energy": { device_id: "dp" } },
|
||||
),
|
||||
{
|
||||
callWS: async () => {
|
||||
if (!statesOk) throw new Error("no");
|
||||
return { energy_sources: [{ type: "grid", flow_from: [{ stat_energy_from: "sensor.grid_energy" }] }, { type: "solar", stat_energy_from: "sensor.pv_energy" }] };
|
||||
},
|
||||
},
|
||||
);
|
||||
const doc = plan(furniture);
|
||||
const set: string[] = [];
|
||||
const added: string[] = [];
|
||||
const deps = {
|
||||
hass,
|
||||
doc: () => doc,
|
||||
canAdd: () => true,
|
||||
addDevice: (type: string) => {
|
||||
added.push(type);
|
||||
doc.floors[0].furniture.push(device(`new-${type}`, type));
|
||||
},
|
||||
setField: (id: string, key: string, sensor: string) => {
|
||||
set.push(`${id}.${key}=${sensor}`);
|
||||
const item = doc.floors[0].furniture.find((m) => m.id === id)!;
|
||||
(item as unknown as Record<string, string>)[key] = sensor;
|
||||
},
|
||||
};
|
||||
return { deps, set, added };
|
||||
}
|
||||
|
||||
test("the import fills the sensors found in the energy dashboard and creates the missing devices", async () => {
|
||||
const s = importSetup([device("m", "meter")]);
|
||||
const result = await importEnergyPrefs(s.deps);
|
||||
assert.deepEqual(result.kind === "done" && result.filled, 2);
|
||||
assert.deepEqual(s.added, ["inverter"]);
|
||||
assert.deepEqual(s.set, ["m.power=sensor.grid_power", "new-inverter.power=sensor.pv_power"]);
|
||||
});
|
||||
|
||||
test("what is already set stays, and a failing dashboard call is reported", async () => {
|
||||
const kept = importSetup([device("m", "meter", { power: "sensor.mine" }), device("i", "inverter", { power: "sensor.mine2" })]);
|
||||
const result = await importEnergyPrefs(kept.deps);
|
||||
assert.deepEqual(result, { kind: "done", filled: 0 });
|
||||
assert.deepEqual(kept.set, []);
|
||||
const broken = importSetup([], false);
|
||||
assert.deepEqual(await importEnergyPrefs(broken.deps), { kind: "failed" });
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// What the energy tool still needs, as a list that gets ticked off while the plan fills in. Pure: the form turns each row into a
|
||||
// button that jumps to the thing to do.
|
||||
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import type { Building, Floor, Furniture } from "../../../model.ts";
|
||||
import { powerSensorOf } from "../entities.ts";
|
||||
|
||||
export type ChecklistTarget =
|
||||
| { kind: "solar-field"; id: string }
|
||||
| { kind: "add-solar-field" }
|
||||
| { kind: "device"; floor: Floor; item: Furniture }
|
||||
| { kind: "add-device"; type: string };
|
||||
|
||||
export interface ChecklistRow {
|
||||
/** Done, still to do, or optional. */
|
||||
state: "ok" | "todo" | "opt";
|
||||
label: I18nKey;
|
||||
target: ChecklistTarget;
|
||||
}
|
||||
|
||||
type Found = Map<string, { power: string | null }>;
|
||||
|
||||
export function energyChecklist(doc: Building, found: Found): ChecklistRow[] {
|
||||
const items = doc.floors.flatMap((floor) => floor.furniture.map((item) => ({ floor, item })));
|
||||
const ofType = (type: string) => items.filter((entry) => entry.item.type === type);
|
||||
const hasPower = (entry: (typeof items)[number]) => !!powerSensorOf(entry.item, found);
|
||||
const device = (entry: (typeof items)[number]): ChecklistTarget => ({ kind: "device", ...entry });
|
||||
const [fields, meters, inverters, batteries, grid] = [doc.settings.roof.solar ?? [], ofType("meter"), ofType("inverter"), ofType("home_battery"), ofType("grid_point")];
|
||||
|
||||
const meterOk = !!doc.energy.grid || meters.some(hasPower);
|
||||
const inverterOk = !!doc.energy.solar || (inverters.length > 0 && inverters.every(hasPower));
|
||||
const batteryOk = !!doc.energy.battery || batteries.every((b) => hasPower(b) && b.item.soc && b.item.soc !== "none");
|
||||
|
||||
return [
|
||||
fields.length > 0
|
||||
? { state: "ok", label: "chk_solar", target: { kind: "solar-field", id: fields[0].id } }
|
||||
: { state: "todo", label: "chk_solar_add", target: { kind: "add-solar-field" } },
|
||||
meters.length > 0
|
||||
? { state: meterOk ? "ok" : "todo", label: meterOk ? "chk_meter" : "chk_meter_sensor", target: device(meters[0]) }
|
||||
: { state: "todo", label: "chk_meter_add", target: { kind: "add-device", type: "meter" } },
|
||||
inverters.length > 0
|
||||
? { state: inverterOk ? "ok" : "todo", label: inverterOk ? "chk_inverter" : "chk_inverter_sensor", target: device(inverters.find((i) => !hasPower(i)) ?? inverters[0]) }
|
||||
: { state: "todo", label: "chk_inverter_add", target: { kind: "add-device", type: "inverter" } },
|
||||
batteries.length > 0
|
||||
? { state: batteryOk ? "ok" : "todo", label: batteryOk ? "chk_battery" : "chk_battery_sensor", target: device(batteries[0]) }
|
||||
: { state: "opt", label: "chk_battery_opt", target: { kind: "add-device", type: "home_battery" } },
|
||||
grid.length > 0 ? { state: "ok", label: "chk_grid", target: device(grid[0]) } : { state: "opt", label: "chk_grid_opt", target: { kind: "add-device", type: "grid_point" } },
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import { longestFreeWall, newEnergyDevice, roomForEnergyDevice } from "./energy-devices.ts";
|
||||
|
||||
const plan = (floor: ReturnType<typeof floorWith>): Building => ({ version: 1, floors: [floor], settings: { wall_interior: 0.12, wall_exterior: 0.3 }, energy: {}, presence: [] }) as unknown as Building;
|
||||
const ctx = (selected?: ReturnType<typeof box>) => ({ roomLabel: (r: { name: string }) => r.name, selected, fallback: [9, 9] as [number, number] });
|
||||
|
||||
function house() {
|
||||
const living = box("Living", 0, 0, 5, 4);
|
||||
const garage = box("Garage", 5, 0, 8, 4);
|
||||
const utility = box("Technik", 0, 4, 3, 7);
|
||||
const hall = box("Flur", 3, 4, 8, 7);
|
||||
return floorWith([living, garage, utility, hall]);
|
||||
}
|
||||
|
||||
test("each kind of device goes to the room it belongs to", () => {
|
||||
const floor = house();
|
||||
assert.equal(roomForEnergyDevice("wallbox", floor, ctx())?.id, "Garage");
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx())?.id, "Technik");
|
||||
assert.equal(roomForEnergyDevice("home_battery", floor, ctx())?.id, "Technik");
|
||||
assert.equal(roomForEnergyDevice("meter", floor, ctx())?.id, "Technik");
|
||||
});
|
||||
|
||||
test("a meter takes the hall when there is no utility room, and a garage is found by the parking spot in it", () => {
|
||||
const floor = floorWith([box("Wohnen", 0, 0, 5, 4), box("Flur", 5, 0, 8, 4), box("Halle", 0, 4, 6, 8)]);
|
||||
assert.equal(roomForEnergyDevice("meter", floor, ctx())?.id, "Flur");
|
||||
const withCar = { ...floor, furniture: [{ id: "p", type: "parking", x: 3, z: 6 } as Furniture] };
|
||||
assert.equal(roomForEnergyDevice("wallbox", withCar, ctx())?.id, "Halle");
|
||||
});
|
||||
|
||||
test("without any hint the selected room is used, and without one the largest", () => {
|
||||
const floor = floorWith([box("A", 0, 0, 2, 2), box("B", 2, 0, 8, 6)]);
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx(floor.rooms[0]))?.id, "A");
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx())?.id, "B");
|
||||
assert.equal(roomForEnergyDevice("inverter", floorWith([]), ctx()), undefined);
|
||||
});
|
||||
|
||||
test("the longest wall is chosen, walls with openings only when nothing else is left, and the direction points inward", () => {
|
||||
const room = box("R", 0, 0, 6, 2);
|
||||
const wall = longestFreeWall(room, new Set())!;
|
||||
assert.deepEqual(wall.mid, [3, 0]);
|
||||
assert.deepEqual(wall.inward, [0, 1]);
|
||||
assert.deepEqual(longestFreeWall(room, new Set([0]))!.mid, [3, 2], "the top wall has an opening, so the bottom one is taken");
|
||||
assert.ok(longestFreeWall(room, new Set([0, 1, 2, 3])), "all walls are open: any will do");
|
||||
});
|
||||
|
||||
test("a wallbox ends up flush against a wall of the garage", () => {
|
||||
const floor = house();
|
||||
const device = newEnergyDevice("wallbox", plan(floor), floor, ctx());
|
||||
assert.equal(device.type, "wallbox");
|
||||
assert.ok(device.x > 5 && device.x < 8 && device.z >= 0 && device.z <= 4, `${device.x},${device.z}`);
|
||||
const atWall = [device.x - 5, 8 - device.x, device.z, 4 - device.z].some((gap) => gap < 0.5);
|
||||
assert.ok(atWall);
|
||||
assert.ok(device.id.startsWith("furniture"));
|
||||
});
|
||||
|
||||
test("without a room the device goes where the caller says; the grid point falls back too when there is no meter", () => {
|
||||
const empty = floorWith([]);
|
||||
const loose = newEnergyDevice("inverter", plan(empty), empty, ctx());
|
||||
assert.deepEqual([loose.x, loose.z], [9, 9]);
|
||||
const grid = newEnergyDevice("grid_point", plan(empty), empty, ctx());
|
||||
assert.deepEqual([grid.x, grid.z], [9, 9]);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// Where a new energy device goes. A wallbox belongs in the garage, an inverter or battery in the utility room, a meter in the
|
||||
// utility room or the hall; the device stands against the room's longest free wall, and the grid connection outside the house.
|
||||
|
||||
import { snapToWall } from "../../../geometry/snap.ts";
|
||||
import { centroid, pointInPolygon, signedArea, uid, type Building, type Floor, type Furniture, type Room, type Vec2 } from "../../../model.ts";
|
||||
import { furnitureSize } from "../../../packs.ts";
|
||||
import { suggestGridSpot } from "../../../energy.ts";
|
||||
|
||||
const GARAGE = /garage|carport/;
|
||||
const UTILITY = /hwr|hauswirt|technik|keller|abstell|utility|basement|boiler|heiz/;
|
||||
const HALL = /flur|diele|eingang|hall|entr|lobby/;
|
||||
|
||||
/** How far in front of the wall the device is dropped before it snaps flush against it. */
|
||||
const WALL_GAP = 0.25;
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
export interface EnergySpotContext {
|
||||
/** The text a room is recognised by: its name and the name of its Home Assistant area. */
|
||||
roomLabel(room: Room): string;
|
||||
/** The room selected in the editor, tried when no better room is found. */
|
||||
selected?: Room;
|
||||
/** Where to put things when the plan gives no hint (the middle of what is on screen). */
|
||||
fallback: Vec2;
|
||||
}
|
||||
|
||||
/** The room a device of this type belongs in, or the selected room, or the largest one. */
|
||||
export function roomForEnergyDevice(type: string, floor: Floor, ctx: EnergySpotContext): Room | undefined {
|
||||
const rooms = floor.rooms.filter((r) => r.points.length >= 3);
|
||||
const named = (pattern: RegExp) => rooms.find((r) => pattern.test(ctx.roomLabel(r).toLowerCase()));
|
||||
const parkedIn = rooms.find((r) => floor.furniture.some((m) => m.type === "parking" && pointInPolygon([m.x, m.z], r.points)));
|
||||
const garage = named(GARAGE) ?? parkedIn;
|
||||
const utility = named(UTILITY);
|
||||
const fitting = type === "wallbox" ? garage : type === "meter" ? (utility ?? named(HALL) ?? garage) : (utility ?? garage);
|
||||
const largest = [...rooms].sort((a, b) => Math.abs(signedArea(b.points)) - Math.abs(signedArea(a.points)))[0];
|
||||
return fitting ?? ctx.selected ?? largest;
|
||||
}
|
||||
|
||||
/** The middle of the longest wall of the room and the direction into the room. Walls with an opening are avoided when others exist. */
|
||||
export function longestFreeWall(room: Room, openedEdges: ReadonlySet<number>): { mid: Vec2; inward: Vec2 } | null {
|
||||
const [cx, cz] = centroid(room.points);
|
||||
const anyFree = room.points.some((_, i) => !openedEdges.has(i));
|
||||
let best: { mid: Vec2; inward: Vec2; length: number } | null = null;
|
||||
room.points.forEach((p, i) => {
|
||||
if (anyFree && openedEdges.has(i)) return;
|
||||
const q = room.points[(i + 1) % room.points.length];
|
||||
const length = Math.hypot(q[0] - p[0], q[1] - p[1]);
|
||||
if (best && length <= best.length) return;
|
||||
const mid: Vec2 = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
|
||||
// `+ 0` turns a negative zero into a plain zero
|
||||
let inward: Vec2 = [-(q[1] - p[1]) / length + 0, (q[0] - p[0]) / length + 0];
|
||||
if ((cx - mid[0]) * inward[0] + (cz - mid[1]) * inward[1] < 0) inward = [0 - inward[0], 0 - inward[1]];
|
||||
best = { mid, inward, length };
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A new energy device of this type on the floor, placed where it belongs and snapped to the wall. */
|
||||
export function newEnergyDevice(type: string, building: Building, floor: Floor, ctx: EnergySpotContext): Furniture {
|
||||
const [w, d, h] = furnitureSize(type);
|
||||
const base = { id: uid("furniture"), type, rotation: 0, w, d, h, variant: null };
|
||||
if (type === "grid_point") {
|
||||
// the grid connection starts just outside the wall nearest to the meter, and can be dragged from there
|
||||
const spot = suggestGridSpot(building);
|
||||
const [x, z] = spot ? [spot.x, spot.z] : ctx.fallback;
|
||||
return { ...base, x: thousandths(x), z: thousandths(z) };
|
||||
}
|
||||
const room = roomForEnergyDevice(type, floor, ctx);
|
||||
let [x, z] = room ? centroid(room.points) : ctx.fallback;
|
||||
if (room) {
|
||||
// in front of the longest wall, so that it snaps to that wall: from the middle of the room no wall is near enough
|
||||
const opened = new Set(floor.openings.filter((o) => o.room_id === room.id).map((o) => o.edge));
|
||||
const wall = longestFreeWall(room, opened);
|
||||
if (wall) [x, z] = [wall.mid[0] + wall.inward[0] * (d / 2 + WALL_GAP), wall.mid[1] + wall.inward[1] * (d / 2 + WALL_GAP)];
|
||||
}
|
||||
const item: Furniture = { ...base, x: thousandths(x), z: thousandths(z) };
|
||||
const snapped = room ? snapToWall({ ...floor, furniture: [...floor.furniture, item] }, item, building.settings.wall_interior) : null;
|
||||
return snapped ? { ...item, x: thousandths(snapped.x), z: thousandths(snapped.z), rotation: snapped.rotation } : item;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Filling the energy balance from Home Assistant's energy dashboard: its statistics lead to power sensors of the same devices, and
|
||||
// those go onto the devices of the plan (meter, inverter, battery). Only empty fields are filled, so what the user chose stays.
|
||||
|
||||
import { proposeEnergySensors, type EnergyPrefs } from "../../../energy.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import type { HomeAssistant } from "../../../types.ts";
|
||||
|
||||
export interface EnergyImportDeps {
|
||||
hass: HomeAssistant;
|
||||
/** The current plan; read again after a device was added. */
|
||||
doc(): Building;
|
||||
/** Whether a floor is selected, which is where missing devices are created. */
|
||||
canAdd(): boolean;
|
||||
addDevice(type: string): void;
|
||||
setField(furnitureId: string, key: "power" | "soc", sensor: string): void;
|
||||
}
|
||||
|
||||
export type EnergyImportResult = { kind: "failed" } | { kind: "done"; filled: number };
|
||||
|
||||
/** The device of this type anywhere in the plan. */
|
||||
const deviceOfType = (doc: Building, type: string): Furniture | undefined => doc.floors.flatMap((f) => f.furniture).find((m) => m.type === type);
|
||||
|
||||
const isEmpty = (value: string | null | undefined) => !value || value === "none";
|
||||
|
||||
export async function importEnergyPrefs(deps: EnergyImportDeps): Promise<EnergyImportResult> {
|
||||
let prefs: EnergyPrefs;
|
||||
try {
|
||||
prefs = await deps.hass.callWS<EnergyPrefs>({ type: "energy/get_prefs" });
|
||||
} catch {
|
||||
return { kind: "failed" };
|
||||
}
|
||||
const found = proposeEnergySensors(deps.hass, prefs);
|
||||
let filled = 0;
|
||||
const fill = (type: string, key: "power" | "soc", sensor: string | null | undefined) => {
|
||||
if (!sensor) return;
|
||||
let device = deviceOfType(deps.doc(), type);
|
||||
if (!device && deps.canAdd()) {
|
||||
deps.addDevice(type);
|
||||
device = deviceOfType(deps.doc(), type);
|
||||
}
|
||||
if (!device || !isEmpty(device[key])) return;
|
||||
deps.setField(device.id, key, sensor);
|
||||
filled++;
|
||||
};
|
||||
fill("meter", "power", found.grid);
|
||||
fill("inverter", "power", found.solar);
|
||||
fill("home_battery", "power", found.battery);
|
||||
fill("home_battery", "soc", found.battery_soc);
|
||||
return { kind: "done", filled };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import type { Building } from "../../../model.ts";
|
||||
import { copyOfFloor, floorsSwapped, floorsWith, freeHaFloors, linkableHaFloors, moveFurnitureToFloor, newFloorFor, unlinked, unplacedAreas } from "./floors.ts";
|
||||
|
||||
const names = { first: "Ground floor", next: (n: number) => `Floor ${n}` };
|
||||
const level = (id: string, elevation: number, extra = {}) => floorWith([], { id, elevation, ...extra } as never);
|
||||
const house = (...floors: ReturnType<typeof level>[]) => ({ floors }) as unknown as Building;
|
||||
|
||||
test("the first floor gets its own name, later ones are numbered, and a Home Assistant floor lends its name and level", () => {
|
||||
assert.equal(newFloorFor(house(), null, names).name, "Ground floor");
|
||||
assert.equal(newFloorFor(house(level("g", 0)), null, names).name, "Floor 1");
|
||||
const fromHa = newFloorFor(house(level("g", 0)), { floor_id: "upstairs", name: "Upstairs", level: 1 }, names);
|
||||
assert.deepEqual([fromHa.name, fromHa.ha_floor, fromHa.elevation], ["Upstairs", "upstairs", 2.75]);
|
||||
assert.notEqual(newFloorFor(house(), null, names).id, newFloorFor(house(), null, names).id);
|
||||
});
|
||||
|
||||
test("a new floor without a level goes on top of the house", () => {
|
||||
const added = newFloorFor(house(level("g", 0)), null, names);
|
||||
assert.equal(added.elevation, 2.75);
|
||||
});
|
||||
|
||||
test("floors stay ordered from bottom to top when one is added", () => {
|
||||
const floors = [level("a", 0), level("b", 3), level("c", 6)];
|
||||
assert.deepEqual(floorsWith(floors, level("x", 1)).map((f) => f.id), ["a", "x", "b", "c"]);
|
||||
assert.deepEqual(floorsWith(floors, level("x", 9)).map((f) => f.id), ["a", "b", "c", "x"]);
|
||||
assert.deepEqual(floorsWith(floors, level("x", -3)).map((f) => f.id), ["x", "a", "b", "c"]);
|
||||
assert.deepEqual(floorsWith([], level("x", 0)).map((f) => f.id), ["x"]);
|
||||
});
|
||||
|
||||
test("floors swap with the neighbour in the direction, and stay put at the ends", () => {
|
||||
const floors = [level("a", 0), level("b", 3), level("c", 6)];
|
||||
assert.deepEqual(floorsSwapped(floors, "b", 1).map((f) => f.id), ["a", "c", "b"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "b", -1).map((f) => f.id), ["b", "a", "c"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "c", 1).map((f) => f.id), ["a", "b", "c"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "nope", 1).map((f) => f.id), ["a", "b", "c"]);
|
||||
});
|
||||
|
||||
test("Home Assistant floors that are not used yet come lowest first, unnumbered ones last", () => {
|
||||
const registry = { a: { floor_id: "a", name: "Attic", level: 2 }, g: { floor_id: "g", name: "Ground", level: 0 }, z: { floor_id: "z", name: "Zeta" }, b: { floor_id: "b", name: "Basement", level: -1 } };
|
||||
const doc = house(level("x", 0, { ha_floor: "g" }));
|
||||
assert.deepEqual(freeHaFloors(doc, registry).map((f) => f.floor_id), ["b", "a", "z"]);
|
||||
assert.deepEqual(freeHaFloors(doc, undefined), []);
|
||||
assert.deepEqual(linkableHaFloors(doc, doc.floors[0], registry).map((f) => f.floor_id).sort(), ["a", "b", "g", "z"]);
|
||||
assert.deepEqual(linkableHaFloors(house(level("x", 0, { ha_floor: "g" }), level("y", 3)), doc.floors[0], registry).map((f) => f.floor_id).sort(), ["a", "b", "g", "z"]);
|
||||
assert.deepEqual(linkableHaFloors(house(level("x", 0, { ha_floor: "g" }), level("y", 3, { ha_floor: "a" })), doc.floors[0], registry).map((f) => f.floor_id).sort(), ["b", "g", "z"]);
|
||||
});
|
||||
|
||||
test("areas without a room: only those of the floor's Home Assistant floor, by name", () => {
|
||||
const areas = {
|
||||
k: { area_id: "k", name: "Kitchen", floor_id: "g" },
|
||||
b: { area_id: "b", name: "Bath", floor_id: "g" },
|
||||
a: { area_id: "a", name: "Attic room", floor_id: "up" },
|
||||
h: { area_id: "h", name: "Hall", floor_id: "g" },
|
||||
};
|
||||
const ground = floorWith([box("room", 0, 0, 1, 1, "h")], { id: "x", ha_floor: "g" } as never);
|
||||
const doc = { floors: [ground] } as unknown as Building;
|
||||
assert.deepEqual(unplacedAreas(doc, ground, areas).map((a) => a.area_id), ["b", "k"]);
|
||||
assert.deepEqual(unplacedAreas(doc, { ...ground, ha_floor: null }, areas), []);
|
||||
assert.deepEqual(unplacedAreas(doc, ground, undefined), []);
|
||||
});
|
||||
|
||||
test("a floor copy gets new ids, goes on top of the house and keeps its doors on the copied rooms", () => {
|
||||
let n = 0;
|
||||
const id = (prefix: string) => `${prefix}_${++n}`;
|
||||
const room = { ...box("r1", 0, 0, 4, 3), area_id: "living" };
|
||||
const ground = floorWith([room], {
|
||||
id: "g",
|
||||
ha_floor: "eg",
|
||||
walls: [{ id: "w1", a: [0, 1], b: [2, 1] }],
|
||||
openings: [opening("o1", "r1", "door"), opening("o2", "r1", "window", { wall: "w1" })],
|
||||
furniture: [
|
||||
{ id: "f1", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 1, h: 0.8, variant: null, entity: "media_player.tv", state_entity: "binary_sensor.seat" },
|
||||
{ id: "f2", type: "meter", x: 0, z: 0, rotation: 0, w: 0.5, d: 0.2, h: 1, variant: null },
|
||||
],
|
||||
placements: [{ entity_id: "light.a", x: 1, z: 1 } as never],
|
||||
});
|
||||
const upper = floorWith([], { id: "u", elevation: 2.75, height: 2.5 });
|
||||
const doc = house(ground, upper);
|
||||
const copy = copyOfFloor(doc, ground, "Ground (copy)", { furniture: true, devices: false, outdoor: false }, id);
|
||||
assert.equal(copy.elevation, 5.25, "above the highest floor");
|
||||
assert.equal(copy.ha_floor, null);
|
||||
assert.equal(copy.rooms[0].area_id, null);
|
||||
assert.notEqual(copy.rooms[0].id, "r1");
|
||||
assert.deepEqual(copy.openings.map((o) => o.room_id), [copy.rooms[0].id, copy.rooms[0].id]);
|
||||
assert.equal(copy.openings[1].wall, copy.walls![0].id);
|
||||
assert.deepEqual(copy.furniture.map((f) => f.type), ["sofa"], "the meter stays behind");
|
||||
assert.equal(copy.furniture[0].entity, "none");
|
||||
assert.equal(copy.furniture[0].state_entity, null);
|
||||
assert.deepEqual(copy.placements, []);
|
||||
assert.equal(ground.rooms[0].area_id, "living", "the original is untouched");
|
||||
});
|
||||
|
||||
test("furniture moves to another floor at the same spot", () => {
|
||||
const sofa = { id: "f1", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 1, h: 0.8, variant: null };
|
||||
const doc = house(floorWith([], { id: "g", furniture: [sofa] }), floorWith([], { id: "u", elevation: 2.75 }));
|
||||
assert.equal(moveFurnitureToFloor(doc, "g", "f1", "u"), true);
|
||||
assert.deepEqual([doc.floors[0].furniture.length, doc.floors[1].furniture[0].x], [0, 1]);
|
||||
assert.equal(moveFurnitureToFloor(doc, "g", "f1", "u"), false);
|
||||
});
|
||||
|
||||
test("a copied piece of furniture keeps no link to Home Assistant", () => {
|
||||
const linked = {
|
||||
id: "f1",
|
||||
type: "fridge_smart",
|
||||
x: 1,
|
||||
z: 1,
|
||||
rotation: 0,
|
||||
w: 0.9,
|
||||
d: 0.7,
|
||||
h: 1.8,
|
||||
variant: null,
|
||||
entity: "switch.fridge",
|
||||
power: "sensor.fridge_power",
|
||||
temp_entity: "sensor.fridge_temp",
|
||||
door_left: "binary_sensor.freezer_door",
|
||||
door_right: "binary_sensor.fridge_door",
|
||||
state_entity: "binary_sensor.seat",
|
||||
color_entity: "light.bulb",
|
||||
care_entity: "sensor.bin",
|
||||
cover_entity: "cover.curtain",
|
||||
fan_entity: "fan.ceiling",
|
||||
room_sensor: "sensor.vacuum_room",
|
||||
type_entity: "sensor.car_kind",
|
||||
gang_entities: ["light.a", "light.b"],
|
||||
pictures: [{ entity: "media_player.tv", state: "*", image: "x" }],
|
||||
car: { device: "sensor.car_soc", soc: "sensor.car_soc" },
|
||||
tap: { action: "more-info", target: "light.a" },
|
||||
} as never;
|
||||
const copy = unlinked(linked);
|
||||
const text = JSON.stringify(copy);
|
||||
assert.doesNotMatch(text, /[a-z_]+\.[a-z0-9_]+/, "no entity id survives");
|
||||
assert.deepEqual([copy.entity, copy.power, copy.fan_entity, copy.room_sensor], ["none", "none", "none", "none"]);
|
||||
assert.deepEqual([copy.w, copy.d, copy.h, copy.x], [0.9, 0.7, 1.8, 1]);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
// The floors of the house: adding one (also from a floor of Home Assistant's registry), ordering them, and finding what is still to be
|
||||
// connected to Home Assistant.
|
||||
|
||||
import { floorElevation, newFloor, uid, type Building, type Floor, type Furniture } from "../../../model.ts";
|
||||
import type { HassArea, HassFloor } from "../../../types.ts";
|
||||
|
||||
/** A new floor, named after a Home Assistant floor when it comes from one, and placed at that floor's level or on top of the house. */
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }): Floor {
|
||||
const count = doc.floors.length;
|
||||
const name = from?.name ?? (count === 0 ? names.first : names.next(count));
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(doc.floors, from?.level)), ha_floor: from?.floor_id ?? null };
|
||||
}
|
||||
|
||||
/** The floors with a new one slotted in below the first floor that lies higher: floors are kept from bottom to top. */
|
||||
export function floorsWith(floors: readonly Floor[], added: Floor): Floor[] {
|
||||
const above = floors.findIndex((f) => f.elevation > added.elevation);
|
||||
const at = above < 0 ? floors.length : above;
|
||||
return [...floors.slice(0, at), added, ...floors.slice(at)];
|
||||
}
|
||||
|
||||
/** The floors with the one of this id swapped with its neighbour above (1) or below (-1). Unchanged at the ends. */
|
||||
export function floorsSwapped(floors: readonly Floor[], id: string, direction: -1 | 1): Floor[] {
|
||||
const from = floors.findIndex((f) => f.id === id);
|
||||
const to = from + direction;
|
||||
if (from < 0 || to < 0 || to >= floors.length) return [...floors];
|
||||
const next = [...floors];
|
||||
[next[from], next[to]] = [next[to], next[from]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Floors of Home Assistant that no floor of the plan stands for yet, lowest first. */
|
||||
export function freeHaFloors(doc: Building, registry: Readonly<Record<string, HassFloor>> | undefined): HassFloor[] {
|
||||
const used = new Set(doc.floors.map((f) => f.ha_floor));
|
||||
return Object.values(registry ?? {})
|
||||
.filter((f) => !used.has(f.floor_id))
|
||||
.sort((a, b) => (a.level ?? 99) - (b.level ?? 99) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Areas on the Home Assistant floor of this floor that have no room in the plan yet, by name. */
|
||||
export function unplacedAreas(doc: Building, floor: Floor, areas: Readonly<Record<string, HassArea>> | undefined): HassArea[] {
|
||||
if (!floor.ha_floor) return [];
|
||||
const placed = new Set(doc.floors.flatMap((f) => f.rooms.map((r) => r.area_id)));
|
||||
return Object.values(areas ?? {})
|
||||
.filter((a) => a.floor_id === floor.ha_floor && !placed.has(a.area_id))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** The Home Assistant floors a floor may be linked to: its own and the ones no other floor uses. */
|
||||
export function linkableHaFloors(doc: Building, floor: Floor, registry: Readonly<Record<string, HassFloor>> | undefined): HassFloor[] {
|
||||
return Object.values(registry ?? {}).filter((f) => f.floor_id === floor.ha_floor || !doc.floors.some((other) => other.ha_floor === f.floor_id));
|
||||
}
|
||||
|
||||
/** What a floor copy takes along besides its rooms, walls, doors and windows. */
|
||||
export interface FloorCopyOptions {
|
||||
furniture: boolean;
|
||||
/** Device pins: off by default, since the same entity would then show twice. */
|
||||
devices: boolean;
|
||||
outdoor: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A copy of a floor with new ids for everything on it, put on top of the house (above the highest floor). Rooms lose
|
||||
* their Home Assistant area and the floor its Home Assistant floor, since each can stand for one room or floor only;
|
||||
* doors and windows keep pointing at the copied rooms and walls.
|
||||
*/
|
||||
export function copyOfFloor(doc: Building, floor: Floor, name: string, options: FloorCopyOptions, id: (prefix: string) => string = uid): Floor {
|
||||
const copy = structuredClone(floor);
|
||||
const top = doc.floors.reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const rooms = new Map<string, string>();
|
||||
const walls = new Map<string, string>();
|
||||
copy.id = id("floor");
|
||||
copy.name = name;
|
||||
copy.elevation = Math.round(top * 1000) / 1000;
|
||||
copy.ha_floor = null;
|
||||
copy.start_view = null;
|
||||
copy.rooms = copy.rooms.map((r) => {
|
||||
const fresh = id("room");
|
||||
rooms.set(r.id, fresh);
|
||||
return { ...r, id: fresh, area_id: null };
|
||||
});
|
||||
copy.walls = (copy.walls ?? []).map((w) => {
|
||||
const fresh = id("wall");
|
||||
walls.set(w.id, fresh);
|
||||
return { ...w, id: fresh };
|
||||
});
|
||||
copy.openings = copy.openings.filter((o) => rooms.has(o.room_id)).map((o) => ({ ...o, id: id("opening"), room_id: rooms.get(o.room_id)!, wall: o.wall ? (walls.get(o.wall) ?? null) : o.wall }));
|
||||
// energy devices (meters, inverters …) belong to the real house once, so they stay behind
|
||||
const energy = new Set(["meter", "inverter", "home_battery", "wallbox", "grid_point"]);
|
||||
copy.furniture = options.furniture ? copy.furniture.filter((f) => !energy.has(f.type)).map((f) => unlinked({ ...f, id: id("furniture") })) : [];
|
||||
copy.placements = options.devices ? copy.placements : [];
|
||||
copy.outdoor = options.outdoor ? copy.outdoor.map((a) => ({ ...a, id: id("outdoor") })) : [];
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Links that are found automatically while they are null: a copy sets them to "none", or it would find the original's entities again. */
|
||||
const AUTO_LINKS = ["entity", "power", "fan_entity", "room_sensor"] as const;
|
||||
/** Links that are simply empty while null. */
|
||||
const PLAIN_LINKS = [
|
||||
"door_left",
|
||||
"door_right",
|
||||
"soc",
|
||||
"charge",
|
||||
"export",
|
||||
"status",
|
||||
"temp_entity",
|
||||
"temp_entity2",
|
||||
"state_entity",
|
||||
"state_entity2",
|
||||
"color_entity",
|
||||
"care_entity",
|
||||
"cover_entity",
|
||||
"type_entity",
|
||||
"parent_meter",
|
||||
"car",
|
||||
"tap",
|
||||
] as const;
|
||||
/** Lists of links, dropped as a whole. */
|
||||
const LINK_LISTS = ["gang_entities", "pictures", "types", "meter_floors", "show_when", "extra_lights"] as const;
|
||||
|
||||
/** A piece of furniture with every link to Home Assistant removed, its size, place and look kept. */
|
||||
export function unlinked(item: Furniture): Furniture {
|
||||
const out = { ...item } as Record<string, unknown>;
|
||||
// the fan and the vacuum's room sensor are looked up in the item's room, which a copy no longer links to an area
|
||||
for (const key of AUTO_LINKS) if (key === "entity" || key === "power" || out[key] != null) out[key] = "none";
|
||||
for (const key of PLAIN_LINKS) if (out[key] != null) out[key] = null;
|
||||
for (const key of LINK_LISTS) delete out[key];
|
||||
return out as unknown as Furniture;
|
||||
}
|
||||
|
||||
/** Moves a piece of furniture to another floor, at the same spot in the plan. Returns false when it or the floor is missing. */
|
||||
export function moveFurnitureToFloor(doc: Building, fromFloorId: string, itemId: string, toFloorId: string): boolean {
|
||||
const from = doc.floors.find((f) => f.id === fromFloorId);
|
||||
const to = doc.floors.find((f) => f.id === toFloorId);
|
||||
if (!from || !to || from === to) return false;
|
||||
const index = from.furniture.findIndex((f) => f.id === itemId);
|
||||
if (index < 0) return false;
|
||||
const [item] = from.furniture.splice(index, 1);
|
||||
to.furniture.push(item);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { likelyRoomSensors, parseButtonData, patchPresence, startViewYaml } from "./house.ts";
|
||||
import { moveWithin, orUndefined, patchAt, removeAt } from "./lists.ts";
|
||||
|
||||
test("moving within a list keeps every item and stops at the ends", () => {
|
||||
assert.deepEqual(moveWithin([1, 2, 3, 4], 1, 1), [1, 3, 2, 4]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3, 4], 2, -1), [1, 3, 2, 4]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 0, -1), [1, 2, 3]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 2, 1), [1, 2, 3]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 0, 9), [2, 3, 1]);
|
||||
});
|
||||
|
||||
test("removing and patching leave the original alone", () => {
|
||||
const list = [{ a: 1 }, { a: 2 }];
|
||||
assert.deepEqual(removeAt(list, 0), [{ a: 2 }]);
|
||||
assert.deepEqual(patchAt(list, 1, { a: 9 }), [{ a: 1 }, { a: 9 }]);
|
||||
assert.deepEqual(list, [{ a: 1 }, { a: 2 }]);
|
||||
assert.equal(orUndefined([]), undefined);
|
||||
assert.deepEqual(orUndefined([1]), [1]);
|
||||
});
|
||||
|
||||
test("a presence link is replaced, added or removed; its room keeps it alive without a sensor", () => {
|
||||
const links = [{ person: "person.a", sensor: "sensor.a" }];
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: "sensor.b" }), [{ person: "person.a", sensor: "sensor.b" }]);
|
||||
assert.deepEqual(patchPresence(links, "person.b", { sensor: "sensor.c" }), [...links, { person: "person.b", sensor: "sensor.c" }]);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: null }), []);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: "none" }), []);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { room: "kitchen" }), [{ person: "person.a", sensor: "sensor.a", room: "kitchen" }]);
|
||||
assert.deepEqual(patchPresence([{ person: "person.a", sensor: "sensor.a", room: "k" }], "person.a", { sensor: null }), [{ person: "person.a", sensor: null, room: "k" }], "the room alone is enough");
|
||||
assert.deepEqual(patchPresence([{ person: "person.a", sensor: null, room: "k" }], "person.a", { room: null }), []);
|
||||
assert.equal(links.length, 1);
|
||||
});
|
||||
|
||||
test("sensors named after the person and a room come first", () => {
|
||||
const options = [
|
||||
{ id: "sensor.other_room", label: "" },
|
||||
{ id: "sensor.anna_phone_area", label: "" },
|
||||
{ id: "sensor.anna_battery", label: "" },
|
||||
{ id: "sensor.bermuda_anna_room", label: "" },
|
||||
];
|
||||
assert.deepEqual(likelyRoomSensors(options, "person.anna").map((o) => o.id), ["sensor.anna_phone_area", "sensor.bermuda_anna_room", "sensor.other_room", "sensor.anna_battery"]);
|
||||
});
|
||||
|
||||
test("the start view becomes one line of card YAML", () => {
|
||||
assert.equal(startViewYaml({ theta: 1, phi: 2, radius: 3 }), "start_view: { theta: 1, phi: 2, radius: 3 }");
|
||||
assert.equal(startViewYaml({ theta: 1, phi: 2, radius: 3, target: { x: 4, y: 5, z: 6 } }), "start_view: { theta: 1, phi: 2, radius: 3, target: { x: 4, y: 5, z: 6 } }");
|
||||
});
|
||||
|
||||
test("button data: empty is none, objects pass, everything else is refused", () => {
|
||||
assert.deepEqual(parseButtonData(" "), { ok: true, value: null });
|
||||
assert.deepEqual(parseButtonData('{"entity_id": "script.party"}'), { ok: true, value: { entity_id: "script.party" } });
|
||||
for (const bad of ["[1]", "5", "null", "{oops", '"text"']) assert.deepEqual(parseButtonData(bad), { ok: false }, bad);
|
||||
});
|
||||
|
||||
import { clamp, turnedNorth, withEffect, wrapDegrees } from "./settings.ts";
|
||||
|
||||
test("settings are kept within their limits", () => {
|
||||
assert.equal(clamp(5, 0, 1), 1);
|
||||
assert.equal(clamp(-5, 0, 1), 0);
|
||||
assert.equal(clamp(0.5, 0, 1), 0.5);
|
||||
assert.equal(wrapDegrees(370), 10);
|
||||
assert.equal(wrapDegrees(-10), 350);
|
||||
assert.equal(turnedNorth(0, 180), 180, "north and south swapped");
|
||||
assert.equal(turnedNorth(200, 180), 20);
|
||||
assert.equal(turnedNorth(10, -90), 280);
|
||||
assert.equal(wrapDegrees(359.6), 0);
|
||||
});
|
||||
|
||||
test("weather effects can be added once and removed", () => {
|
||||
assert.deepEqual(withEffect(["rain"], "snow", true), ["rain", "snow"]);
|
||||
assert.deepEqual(withEffect(["rain", "snow"], "rain", true), ["rain", "snow"]);
|
||||
assert.deepEqual(withEffect(["rain", "snow"], "rain", false), ["snow"]);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Settings of the house as a whole: who is tracked by which sensor, the start camera, the data of an own button.
|
||||
|
||||
import type { PresenceLink, StartView } from "../../../model.ts";
|
||||
import type { EntityOption } from "../entities.ts";
|
||||
|
||||
/**
|
||||
* The presence links with `person` changed by `patch` (sensor: null or "none" clears it, room: null clears it). A link that has
|
||||
* neither a sensor nor a room left is removed.
|
||||
*/
|
||||
export function patchPresence(links: readonly PresenceLink[], person: string, patch: { sensor?: string | null; room?: string | null }): PresenceLink[] {
|
||||
const old = links.find((l) => l.person === person);
|
||||
const sensor = "sensor" in patch ? (patch.sensor && patch.sensor !== "none" ? patch.sensor : null) : (old?.sensor ?? null);
|
||||
const room = "room" in patch ? patch.room || null : (old?.room ?? null);
|
||||
const others = links.filter((l) => l.person !== person);
|
||||
if (!sensor && !room) return others;
|
||||
const next: PresenceLink = room ? { person, sensor, room } : { person, sensor };
|
||||
return old ? links.map((l) => (l.person === person ? next : l)) : [...others, next];
|
||||
}
|
||||
|
||||
/** Room sensors that look like they belong to this person (named after them, ESPresense and Bermuda style) come first. */
|
||||
export function likelyRoomSensors(options: readonly EntityOption[], person: string): EntityOption[] {
|
||||
const slug = person.slice(person.indexOf(".") + 1);
|
||||
const likely = (o: EntityOption) => o.id.includes(slug) && /(area|room|raum|bermuda|espresense)/.test(o.id);
|
||||
return [...options.filter(likely), ...options.filter((o) => !likely(o))];
|
||||
}
|
||||
|
||||
/** The start view as the line to put into a card's YAML. */
|
||||
export function startViewYaml(view: StartView): string {
|
||||
const target = view.target ? `, target: { x: ${view.target.x}, y: ${view.target.y}, z: ${view.target.z} }` : "";
|
||||
return `start_view: { theta: ${view.theta}, phi: ${view.phi}, radius: ${view.radius}${target} }`;
|
||||
}
|
||||
|
||||
export type ParsedData = { ok: true; value: Record<string, unknown> | null } | { ok: false };
|
||||
|
||||
/** The extra data of a button, typed as JSON: empty means none, and anything but an object is refused. */
|
||||
export function parseButtonData(text: string): ParsedData {
|
||||
const raw = text.trim();
|
||||
if (!raw) return { ok: true, value: null };
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? { ok: true, value: value as Record<string, unknown> } : { ok: false };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture, Placement } from "../../../model.ts";
|
||||
import { drawOrder, copyOfFurniture, copyOfOutdoorArea, deviceForFurniture, insertOutdoorCorner, removeOutdoorCorner, edgeOf, furnitureForDevice, newFloorOpening, newFreeWall, newFurniture, newOpening, newOutdoorArea, offsetOnEdge, openingKindPatch, parkingSpotFor, placeInRoom, removeDevice, roomCentre, wallEndForLength, wallHeightPatch } from "./items.ts";
|
||||
import { NO_CHANGE, NOTHING_TO_MOVE, nudge, type Nudge } from "./nudge.ts";
|
||||
|
||||
const sofa = (extra: Partial<Furniture> = {}): Furniture => ({ id: "s", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null, ...extra });
|
||||
const pin = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra });
|
||||
const applied = (n: Nudge, floor: ReturnType<typeof floorWith>) => {
|
||||
assert.ok(typeof n === "object", `expected a change, got ${String(n)}`);
|
||||
const copy = structuredClone(floor);
|
||||
n.apply(copy);
|
||||
return copy;
|
||||
};
|
||||
|
||||
test("free walls: rounding, a typed length that keeps the direction, and the height that means 'as high as the floor'", () => {
|
||||
const wall = newFreeWall([0, 0.1234], [3, 4.0004]);
|
||||
assert.deepEqual([wall.a, wall.b], [[0, 0.123], [3, 4]]);
|
||||
assert.deepEqual(wallEndForLength({ ...wall, a: [0, 0], b: [3, 4] }, 10), [6, 8]);
|
||||
assert.deepEqual(wallEndForLength({ ...wall, a: [0, 0], b: [3, 4] }, 0), [0.06, 0.08], "never shorter than 10 cm");
|
||||
assert.deepEqual(wallHeightPatch(2.5, 2.5), { height: null });
|
||||
assert.deepEqual(wallHeightPatch(1, 2.5), { height: 1 });
|
||||
assert.deepEqual(wallHeightPatch(0, 2.5), { height: 0.05 });
|
||||
});
|
||||
|
||||
test("a floor opening is the drawn rectangle, and an outdoor area its outline; copies move half a metre", () => {
|
||||
const hole = newFloorOpening([1, 1], [3, 4]);
|
||||
assert.deepEqual([hole.type, hole.x, hole.z, hole.w, hole.d], ["stairwell", 2, 2.5, 2, 3]);
|
||||
const area = newOutdoorArea([[0, 0], [1, 0], [1, 1.23456]]);
|
||||
assert.equal(area.type, "lawn");
|
||||
assert.equal(area.points[2][1], 1.235);
|
||||
assert.deepEqual(copyOfOutdoorArea(area).points[0], [0.5, 0.5]);
|
||||
});
|
||||
|
||||
test("new furniture has its type's size, and stairs reach to the floor above", () => {
|
||||
const ground = floorWith([box("r", 0, 0, 4, 4)], { elevation: 0, height: 2.5 });
|
||||
const upper = floorWith([], { id: "u", elevation: 2.8 } as never);
|
||||
const doc = { floors: [ground, upper] } as unknown as Building;
|
||||
const chair = newFurniture("sofa", doc, ground, [1.23456, 2]);
|
||||
assert.deepEqual([chair.type, chair.x, chair.z, chair.rotation], ["sofa", 1.235, 2, 0]);
|
||||
assert.equal(newFurniture("stairs", doc, ground, [0, 0]).h, 2.8);
|
||||
assert.equal(newFurniture("stairs", doc, upper, [0, 0]).h, 2.75, "no floor above: a little over the ceiling");
|
||||
});
|
||||
|
||||
test("a copy of furniture is moved by 30 cm and independent; a vehicle becomes a parking spot that holds it", () => {
|
||||
const original = sofa({ name: "Ledersofa" });
|
||||
const copy = copyOfFurniture(original);
|
||||
assert.deepEqual([copy.x, copy.z], [1.3, 1.3]);
|
||||
assert.notEqual(copy.id, original.id);
|
||||
const spot = parkingSpotFor({ ...sofa({ type: "tesla", w: 2, d: 5, name: "Model Y" }) });
|
||||
assert.equal(spot.type, "parking");
|
||||
assert.equal(spot.vehicle, "tesla");
|
||||
assert.equal(spot.name, "Model Y");
|
||||
assert.ok(spot.w >= 2.5 && spot.d >= 5.4);
|
||||
});
|
||||
|
||||
test("device and furniture can stand in for each other and keep place, turn, name and lock", () => {
|
||||
const furniture = furnitureForDevice(pin("media_player.tv", 2, 3, { rotation: 90, name: "TV", locked: true }), "tv");
|
||||
assert.deepEqual([furniture.x, furniture.z, furniture.rotation, furniture.entity, furniture.name, furniture.locked], [2, 3, 90, "media_player.tv", "TV", true]);
|
||||
const back = deviceForFurniture(sofa({ rotation: 180, name: "Lamp" }), "light.x");
|
||||
assert.deepEqual([back.entity_id, back.rotation, back.name, back.y], ["light.x", 180, "Lamp", null]);
|
||||
assert.equal("name" in deviceForFurniture(sofa(), "light.x"), false);
|
||||
});
|
||||
|
||||
test("removing a device takes its ceiling lamp too, on every floor", () => {
|
||||
const doc = {
|
||||
floors: [floorWith([], { placements: [pin("light.a", 1, 1), pin("sensor.b", 1, 1)], furniture: [sofa({ id: "l", type: "lamp_ceiling", entity: "light.a" }), sofa({ id: "keep" })] }), floorWith([], { id: "u", placements: [pin("light.a", 2, 2)] } as never)],
|
||||
} as unknown as Building;
|
||||
removeDevice(doc, "light.a");
|
||||
assert.deepEqual(doc.floors[0].placements.map((p) => p.entity_id), ["sensor.b"]);
|
||||
assert.deepEqual(doc.floors[0].furniture.map((f) => f.id), ["keep"]);
|
||||
assert.equal(doc.floors[1].placements.length, 0);
|
||||
});
|
||||
|
||||
test("placing entities in a room: lights become ceiling lamps, others pins, and ones placed elsewhere move over", () => {
|
||||
const room = box("r", 0, 0, 5, 4);
|
||||
const floor = floorWith([room, box("q", 5, 0, 9, 4)], { placements: [pin("sensor.moves", 7, 2)] });
|
||||
const doc = { floors: [floor] } as unknown as Building;
|
||||
placeInRoom(doc, floor, room, ["light.new", "sensor.moves", "switch.s"]);
|
||||
const lamps = floor.furniture.filter((f) => f.type === "lamp_ceiling");
|
||||
assert.deepEqual(lamps.map((l) => l.entity), ["light.new"]);
|
||||
assert.deepEqual(floor.placements.map((p) => p.entity_id).sort(), ["sensor.moves", "switch.s"]);
|
||||
assert.ok(floor.placements.every((p) => p.x > 0 && p.x < 5), "inside the room");
|
||||
assert.deepEqual(roomCentre(room), [2.5, 2]);
|
||||
});
|
||||
|
||||
test("an opening dropped on an edge snaps to the grid and stays inside the edge", () => {
|
||||
assert.equal(offsetOnEdge(4, 1.23, 0.9, 0.1), 1.2);
|
||||
assert.equal(offsetOnEdge(4, 0, 0.9, 0.1), 0.45);
|
||||
assert.equal(offsetOnEdge(4, 9, 0.9, 0.1), 3.55);
|
||||
assert.equal(offsetOnEdge(4, 1.234, 0.9, 0), 1.234);
|
||||
assert.equal(offsetOnEdge(0.5, 3, 0.9, 0.1), 0.25, "narrower than the opening: its middle");
|
||||
});
|
||||
|
||||
test("a new door or window follows its preset, narrowed to fit short edges", () => {
|
||||
const host = { roomId: "r", edge: 2, length: 4, offset: (width: number) => width / 2 };
|
||||
const door = newOpening("door", host);
|
||||
assert.deepEqual([door.type, door.width, door.height, door.leaves, door.offset, door.edge], ["door", 0.9, 2.05, 1, 0.45, 2]);
|
||||
const narrow = newOpening("window_double", { ...host, length: 1, wall: "w" });
|
||||
assert.equal(narrow.width, 0.9);
|
||||
assert.equal(narrow.wall, "w");
|
||||
assert.equal(newOpening("garage", { ...host, length: 0.2 }).width, 0.3);
|
||||
});
|
||||
|
||||
test("changing the kind of an opening keeps its width only when its shape stays the same", () => {
|
||||
const door = newOpening("door", { roomId: "r", edge: 0, length: 5, offset: () => 1 });
|
||||
assert.equal("width" in openingKindPatch({ ...door, width: 1.1 }, "door"), false);
|
||||
const patch = openingKindPatch({ ...door, width: 1.1 }, "window");
|
||||
assert.deepEqual([patch.type, patch.width, patch.sill, patch.style], ["window", 1.2, 0.9, null]);
|
||||
assert.equal(openingKindPatch(door, "front").style, "front");
|
||||
// a lift-and-slide door slides; changing it back into a terrace door turns again
|
||||
const slide = openingKindPatch(door, "lift_slide");
|
||||
assert.deepEqual([slide.type, slide.opens, slide.sill], ["window", "slide", 0]);
|
||||
assert.equal(openingKindPatch({ ...door, ...slide } as typeof door, "terrace").opens, null);
|
||||
});
|
||||
|
||||
test("a new glass wall or lift-and-slide door keeps its preset's look and way of opening; doors stay automatic", () => {
|
||||
const host = { roomId: "r", edge: 0, length: 5, offset: () => 1 };
|
||||
assert.equal(newOpening("glass_wall", host).style, "glass_wall");
|
||||
assert.equal(newOpening("lift_slide", host).opens, "slide");
|
||||
assert.equal(newOpening("door", host).style, undefined);
|
||||
assert.equal(newOpening("front", host).style, undefined);
|
||||
});
|
||||
|
||||
test("the edge an opening sits on, for rooms and free walls", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 3)], { walls: [{ id: "w1", a: [0, 5], b: [3, 5], thickness: null }] } as never);
|
||||
assert.deepEqual(edgeOf({ ...opening("o", "r", "door"), edge: 1 }, floor), [[4, 0], [4, 3]]);
|
||||
assert.deepEqual(edgeOf({ ...opening("o", "x", "door"), wall: "w1" }, floor), [[0, 5], [3, 5]]);
|
||||
assert.equal(edgeOf({ ...opening("o", "nope", "door"), edge: 0 }, floor), null);
|
||||
});
|
||||
|
||||
test("arrow keys move furniture, devices, walls and outdoor areas by the step", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)], {
|
||||
furniture: [sofa()],
|
||||
placements: [pin("light.a", 2, 2)],
|
||||
walls: [{ id: "w", a: [0, 0], b: [1, 0], thickness: null }],
|
||||
outdoor: [{ id: "o", type: "lawn", points: [[0, 0], [1, 0], [1, 1]] }],
|
||||
} as never);
|
||||
assert.deepEqual(applied(nudge(floor, { kind: "furniture", id: "s" }, 0.1, -0.05), floor).furniture[0].x, 1.1);
|
||||
assert.equal(applied(nudge(floor, { kind: "device", id: "light.a" }, 0.1, -0.05), floor).placements[0].z, 1.95);
|
||||
const wall = applied(nudge(floor, { kind: "wall", id: "w" }, 1, 0), floor).walls![0];
|
||||
assert.deepEqual([wall.a, wall.b], [[1, 0], [2, 0]]);
|
||||
assert.deepEqual(applied(nudge(floor, { kind: "outdoor", id: "o" }, 0, 1), floor).outdoor[0].points[2], [1, 2]);
|
||||
assert.equal(nudge(floor, { kind: "device", id: "light.missing" }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
test("a room moves with the devices inside it, a selected corner moves alone", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)], { placements: [pin("light.in", 1, 1), pin("light.out", 9, 9)] });
|
||||
const room = applied(nudge(floor, { kind: "room", id: "r", corner: null }, 1, 0), floor);
|
||||
assert.deepEqual(room.rooms[0].points[0], [1, 0]);
|
||||
assert.deepEqual(room.placements.map((p) => p.x), [2, 9]);
|
||||
const corner = applied(nudge(floor, { kind: "room", id: "r", corner: 2 }, 0, 0.5), floor);
|
||||
assert.deepEqual(corner.rooms[0].points.map((p) => p[1]), [0, 0, 4.5, 4]);
|
||||
assert.deepEqual(corner.placements.map((p) => p.x), [1, 9]);
|
||||
assert.equal(nudge(floor, { kind: "room", id: "nope", corner: null }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
test("an opening slides along its wall only: across it nothing changes, and it stays within the edge", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 3)], { openings: [{ ...opening("o", "r", "door"), edge: 0, offset: 1, width: 1 }] });
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, 0.5, 0), floor).openings[0].offset, 1.5);
|
||||
assert.equal(nudge(floor, { kind: "opening", id: "o" }, 0, 1), NO_CHANGE, "edge 0 runs along x");
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, 10, 0), floor).openings[0].offset, 3.5);
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, -10, 0), floor).openings[0].offset, 0.5);
|
||||
assert.equal(nudge(floor, { kind: "opening", id: "gone" }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
import { outdoorRectangleAfter } from "./items.ts";
|
||||
|
||||
test("an outdoor area's rectangle follows typed values and never gets thinner than 10 cm", () => {
|
||||
const area = newOutdoorArea([[0, 0], [4, 0], [4, 2], [0, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "x", 1), [[1, 0], [5, 0], [5, 2], [1, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "w", 6), [[0, 0], [6, 0], [6, 2], [0, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "d", 0), [[0, 0], [4, 0], [4, 0.1], [0, 0.1]]);
|
||||
});
|
||||
|
||||
test("an outdoor area gets a corner in the middle of an edge and gives one back, but never drops below three", () => {
|
||||
const pool = newOutdoorArea([[0, 0], [4, 0], [4, 3], [0, 3]]);
|
||||
insertOutdoorCorner(pool, 1, [4.0004, 1.5]);
|
||||
assert.deepEqual(pool.points, [[0, 0], [4, 0], [4, 1.5], [4, 3], [0, 3]]);
|
||||
insertOutdoorCorner(pool, 4, [0, 1.5]);
|
||||
assert.equal(pool.points.length, 6, "the closing edge (last corner back to the first) can be split too");
|
||||
assert.deepEqual(pool.points[5], [0, 1.5]);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(pool.points.length, 3);
|
||||
assert.equal(removeOutdoorCorner(pool, 0), false);
|
||||
});
|
||||
|
||||
test("what stands higher is drawn on top, so a click hits the speaker on the desk (#105)", () => {
|
||||
const desk = { ...sofa({ id: "desk", type: "desk", w: 1.6, d: 0.8, h: 0.75 }), x: 2, z: 2 };
|
||||
const speaker = { ...sofa({ id: "speaker", type: "sofa", w: 0.1, d: 0.1, h: 0.2, mount_y: 0.75 }), x: 2, z: 2 };
|
||||
const floor = floorWith([], { furniture: [speaker, desk] });
|
||||
assert.deepEqual(drawOrder(floor).map((f) => f.id), ["desk", "speaker"]);
|
||||
const same = floorWith([], { furniture: [sofa({ id: "a", x: 1 }), sofa({ id: "b", x: 3 })] });
|
||||
assert.deepEqual(drawOrder(same).map((f) => f.id), ["a", "b"], "equal heights keep their order");
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
// Making and changing the things on a floor: furniture, devices, outdoor areas, free walls, floor openings and doors and windows.
|
||||
|
||||
import { autoPlace } from "../../../devices.ts";
|
||||
import { mountBase } from "../../../packs.ts";
|
||||
import { DEFAULT_STAIR } from "../../../geometry/stairs.ts";
|
||||
import { openingHost } from "../../../geometry/walls.ts";
|
||||
import {
|
||||
bounds,
|
||||
centroid,
|
||||
FURNITURE_SIZE,
|
||||
isLamp,
|
||||
AUTO_STYLES,
|
||||
OPENING_PRESETS,
|
||||
openingPreset,
|
||||
uid,
|
||||
type Building,
|
||||
type Floor,
|
||||
type FreeWall,
|
||||
type Furniture,
|
||||
type Opening,
|
||||
type OpeningPreset,
|
||||
type OutdoorArea,
|
||||
type Placement,
|
||||
type Room,
|
||||
type Vec2,
|
||||
} from "../../../model.ts";
|
||||
import { furnitureSize } from "../../../packs.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const quarterTurns = (degrees: number, by: number) => (((degrees + by) % 360) + 360) % 360;
|
||||
|
||||
// free walls, outdoor areas and floor openings
|
||||
|
||||
export function newFreeWall(a: Vec2, b: Vec2): FreeWall {
|
||||
return { id: uid("wall"), a: [thousandths(a[0]), thousandths(a[1])], b: [thousandths(b[0]), thousandths(b[1])], thickness: null };
|
||||
}
|
||||
|
||||
/** The far end of a free wall after its length was typed: the wall keeps its start and its direction. */
|
||||
export function wallEndForLength(wall: FreeWall, length: number): Vec2 {
|
||||
const current = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]) || 1;
|
||||
const k = Math.max(0.1, length) / current;
|
||||
return [thousandths(wall.a[0] + (wall.b[0] - wall.a[0]) * k), thousandths(wall.a[1] + (wall.b[1] - wall.a[1]) * k)];
|
||||
}
|
||||
|
||||
/** A wall as high as the floor is stored as "no height of its own". */
|
||||
export const wallHeightPatch = (height: number, floorHeight: number): { height: number | null } => ({ height: height >= floorHeight - 0.005 ? null : Math.max(0.05, height) });
|
||||
|
||||
/** A floor opening (stairwell, gallery) drawn as a rectangle: a hole in the floor of this level. */
|
||||
export function newFloorOpening(lo: Vec2, hi: Vec2): Furniture {
|
||||
return { id: uid("hole"), type: "stairwell", x: thousandths((lo[0] + hi[0]) / 2), z: thousandths((lo[1] + hi[1]) / 2), w: thousandths(hi[0] - lo[0]), d: thousandths(hi[1] - lo[1]), h: 0.02, rotation: 0, variant: null };
|
||||
}
|
||||
|
||||
export const newOutdoorArea = (points: readonly Vec2[]): OutdoorArea => ({ id: uid("outdoor"), type: "lawn", points: points.map(([x, z]) => [thousandths(x), thousandths(z)]) });
|
||||
|
||||
/** A new corner in the middle of an outdoor area's edge (edge i runs from corner i to the next), so that a rectangle can become any shape. */
|
||||
export function insertOutdoorCorner(area: OutdoorArea, edge: number, at: Vec2): void {
|
||||
area.points.splice(edge + 1, 0, [thousandths(at[0]), thousandths(at[1])]);
|
||||
}
|
||||
|
||||
/** Takes a corner away; an area keeps at least three. */
|
||||
export function removeOutdoorCorner(area: OutdoorArea, index: number): boolean {
|
||||
if (area.points.length <= 3 || index < 0 || index >= area.points.length) return false;
|
||||
area.points.splice(index, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
export const copyOfOutdoorArea = (area: OutdoorArea): OutdoorArea => ({ ...area, id: uid("outdoor"), points: area.points.map(([x, z]) => [thousandths(x + 0.5), thousandths(z + 0.5)]) });
|
||||
|
||||
// furniture
|
||||
|
||||
/** A new piece of furniture of this type at `at`. Stairs reach up to the next floor above, or a little above the ceiling of the top one. */
|
||||
export function newFurniture(type: string, doc: Building, floor: Floor, at: Vec2): Furniture {
|
||||
const [w, d, height] = furnitureSize(type);
|
||||
const above = doc.floors.filter((f) => f.elevation > floor.elevation).sort((p, q) => p.elevation - q.elevation)[0];
|
||||
const h = type === "stairs" ? thousandths(above ? above.elevation - floor.elevation : floor.height + 0.25) : height;
|
||||
const item: Furniture = { id: uid("furniture"), type, x: thousandths(at[0]), z: thousandths(at[1]), rotation: 0, w, d, h, variant: null };
|
||||
// new stairs are shaped stairs: shape, turn and steps are set in the form, and they open only the floor they need
|
||||
if (type === "stairs") item.stair = { ...DEFAULT_STAIR };
|
||||
return item;
|
||||
}
|
||||
|
||||
/** A copy of a piece of furniture 30 cm to the south east. */
|
||||
export const copyOfFurniture = (item: Furniture): Furniture => ({ ...structuredClone(item), id: uid("furniture"), x: thousandths(item.x + 0.3), z: thousandths(item.z + 0.3) });
|
||||
|
||||
export const turnedBy = (degrees: number, delta: number): number => quarterTurns(degrees, delta);
|
||||
|
||||
/** A vehicle that was placed as plain furniture becomes a parking spot holding it: presence and the car's live data live there. */
|
||||
export function parkingSpotFor(vehicle: Furniture): Furniture {
|
||||
const [w, d, h] = furnitureSize("parking");
|
||||
return {
|
||||
id: uid("furniture"),
|
||||
type: "parking",
|
||||
x: vehicle.x,
|
||||
z: vehicle.z,
|
||||
rotation: vehicle.rotation,
|
||||
w: Math.max(w, thousandths(vehicle.w + 0.5)),
|
||||
d: Math.max(d, thousandths(vehicle.d + 0.4)),
|
||||
h,
|
||||
variant: null,
|
||||
vehicle: vehicle.type,
|
||||
...(vehicle.name ? { name: vehicle.name } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// devices
|
||||
|
||||
/** A piece of furniture of this type standing for a placed device, where its pin was. */
|
||||
export function furnitureForDevice(placed: Placement, type: string): Furniture {
|
||||
const [w, d, h] = furnitureSize(type);
|
||||
return { id: uid("furniture"), type, x: placed.x, z: placed.z, rotation: placed.rotation ?? 0, w, d, h, variant: null, entity: placed.entity_id, name: placed.name ?? null, animations_enabled: placed.animations_enabled, effect_animations: structuredClone(placed.effect_animations), ...(placed.locked ? { locked: true } : {}) };
|
||||
}
|
||||
|
||||
/** A plain device pin where a piece of furniture linked by hand stood. */
|
||||
export const deviceForFurniture = (item: Furniture, entityId: string): Placement => ({ entity_id: entityId, x: item.x, z: item.z, y: null, rotation: item.rotation, animations_enabled: item.animations_enabled, effect_animations: structuredClone(item.effect_animations), ...(item.name ? { name: item.name } : {}) });
|
||||
|
||||
/** Takes a device off every floor, with the ceiling lamp that stands for it. */
|
||||
export function removeDevice(doc: Building, entityId: string): void {
|
||||
for (const floor of doc.floors) {
|
||||
floor.placements = floor.placements.filter((p) => p.entity_id !== entityId);
|
||||
floor.furniture = floor.furniture.filter((m) => !(isLamp(m.type) && m.entity === entityId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts entities into a room. One that was placed elsewhere moves here. Lights become ceiling lamps, which can be tapped directly in
|
||||
* 3D; everything else becomes a pin.
|
||||
*/
|
||||
export function placeInRoom(doc: Building, floor: Floor, room: Room, entityIds: readonly string[]): void {
|
||||
const moving = new Set(entityIds);
|
||||
for (const f of doc.floors) {
|
||||
f.placements = f.placements.filter((p) => !moving.has(p.entity_id));
|
||||
f.furniture = f.furniture.filter((m) => !(isLamp(m.type) && m.entity && moving.has(m.entity)));
|
||||
}
|
||||
const taken: Vec2[] = [...floor.placements.map((p): Vec2 => [p.x, p.z]), ...floor.furniture.filter((m) => isLamp(m.type)).map((m): Vec2 => [m.x, m.z])];
|
||||
for (const spot of autoPlace(room, entityIds, taken)) {
|
||||
if (!spot.entity_id.startsWith("light.")) {
|
||||
floor.placements.push(spot);
|
||||
continue;
|
||||
}
|
||||
const [w, d, h] = FURNITURE_SIZE.lamp_ceiling;
|
||||
floor.furniture.push({ id: uid("furniture"), type: "lamp_ceiling", x: spot.x, z: spot.z, rotation: 0, w, d, h, variant: null, entity: spot.entity_id, power: null });
|
||||
}
|
||||
}
|
||||
|
||||
/** The middle of the room a point lies in, as a place for a device. */
|
||||
export function roomCentre(room: Room): Vec2 {
|
||||
const [x, z] = centroid(room.points);
|
||||
return [thousandths(x), thousandths(z)];
|
||||
}
|
||||
|
||||
// doors and windows
|
||||
|
||||
/** Where along an edge (from its start, in metres) an opening of this width sits when dropped at `along`, kept inside the edge. */
|
||||
export function offsetOnEdge(edgeLength: number, along: number, width: number, grid: number): number {
|
||||
const half = Math.min(width, edgeLength) / 2;
|
||||
const snapped = grid > 0 ? Math.round(along / grid) * grid : along;
|
||||
return thousandths(Math.min(edgeLength - half, Math.max(half, snapped)));
|
||||
}
|
||||
|
||||
/** A new opening of this kind on an edge: as wide as the preset, but never wider than the edge allows. */
|
||||
export function newOpening(preset: OpeningPreset, host: { roomId: string; edge: number; wall?: string; length: number; offset(width: number): number }): Opening {
|
||||
const kind = OPENING_PRESETS[preset] as { type: Opening["type"]; leaves: 1 | 2; sill: number; height: number; width: number; style?: Opening["style"]; opens?: Opening["opens"] };
|
||||
const width = thousandths(Math.min(kind.width, Math.max(0.3, host.length - 0.1)));
|
||||
return {
|
||||
id: uid("opening"),
|
||||
room_id: host.roomId,
|
||||
edge: host.edge,
|
||||
...(host.wall ? { wall: host.wall } : {}),
|
||||
offset: host.offset(width),
|
||||
width,
|
||||
type: kind.type,
|
||||
sill: kind.sill,
|
||||
height: kind.height,
|
||||
hinge: "left",
|
||||
leaves: kind.leaves,
|
||||
swing: "in",
|
||||
// the preset's own look (a glass wall; room and front doors stay automatic by their wall) and way of opening
|
||||
...(kind.style && !AUTO_STYLES.has(kind.style) ? { style: kind.style } : {}),
|
||||
...(kind.opens ? { opens: kind.opens } : {}),
|
||||
cover: null,
|
||||
contact: null,
|
||||
contact2: null,
|
||||
tilt: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What changing an opening into another kind sets. It keeps its own width unless it already was of that kind's shape. */
|
||||
export function openingKindPatch(opening: Opening, preset: OpeningPreset): Partial<Opening> {
|
||||
const kind = OPENING_PRESETS[preset] as { type: Opening["type"]; leaves: 1 | 2; sill: number; height: number; width: number; style?: Opening["style"]; opens?: Opening["opens"] };
|
||||
const widthChange = openingPreset(opening) === preset ? {} : { width: kind.width };
|
||||
return { type: kind.type, leaves: kind.leaves, sill: kind.sill, height: kind.height, style: kind.style ?? null, opens: kind.opens ?? null, ...widthChange };
|
||||
}
|
||||
|
||||
/** The wall edge an opening sits on, as its two end points. */
|
||||
export function edgeOf(opening: Opening, floor: Floor): [Vec2, Vec2] | null {
|
||||
const host = openingHost(opening, floor.rooms, floor.walls ?? []);
|
||||
if (!host) return null;
|
||||
return [host.room.points[host.edge], host.room.points[(host.edge + 1) % host.room.points.length]];
|
||||
}
|
||||
|
||||
/** The outline of an outdoor area as a rectangle after its left, top, width or depth was typed. Sizes never get below 10 cm. */
|
||||
export function outdoorRectangleAfter(area: OutdoorArea, field: "x" | "z" | "w" | "d", value: number): Vec2[] {
|
||||
const box = bounds(area.points);
|
||||
let { x0, z0, x1, z1 } = box;
|
||||
if (field === "x") [x0, x1] = [value, value + (x1 - x0)];
|
||||
else if (field === "z") [z0, z1] = [value, value + (z1 - z0)];
|
||||
else if (field === "w") x1 = x0 + Math.max(0.1, value);
|
||||
else z1 = z0 + Math.max(0.1, value);
|
||||
return [[x0, z0], [x1, z0], [x1, z1], [x0, z1]].map(([x, z]) => [thousandths(x), thousandths(z)] as Vec2);
|
||||
}
|
||||
|
||||
/**
|
||||
* The furniture of a floor in the order the plan draws it: what stands higher is drawn later, so it lies on top and is the one a click
|
||||
* hits (a speaker on a desk, a lamp on a shelf – #105). Pieces at the same height keep their order.
|
||||
*/
|
||||
export function drawOrder(floor: Floor): Furniture[] {
|
||||
return floor.furniture
|
||||
.map((item, index) => ({ item, index, base: mountBase(floor, item) }))
|
||||
.sort((a, b) => a.base - b.base || a.index - b.index)
|
||||
.map((e) => e.item);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { fold, hasAllWords, wordsOf } from "./library.ts";
|
||||
|
||||
test("accents and case do not matter", () => {
|
||||
assert.equal(fold("Küche ÉCLAIR"), "kuche eclair");
|
||||
assert.ok(hasAllWords(wordsOf("kuhlschrank"), "Kühlschrank refrigerator"));
|
||||
assert.ok(hasAllWords(wordsOf("REFRIGERATOR"), "Kühlschrank refrigerator"));
|
||||
});
|
||||
|
||||
test("every word must be found somewhere, in any order", () => {
|
||||
assert.ok(hasAllWords(wordsOf("sink kuche"), "Doppelspüle sink_double Küche"));
|
||||
assert.ok(!hasAllWords(wordsOf("fridge nothing"), "Kühlschrank fridge"));
|
||||
assert.ok(hasAllWords(wordsOf(" "), "anything"));
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
// The search of the furniture library: every word of the query must appear somewhere in an item's names, its id or its kind;
|
||||
// accents and case do not matter ("kuche" finds "Küche").
|
||||
|
||||
/** Lower case without accents. */
|
||||
export const fold = (text: string): string => text.toLowerCase().normalize("NFD").replace(/\p{M}/gu, "");
|
||||
|
||||
/** The words of a query, folded. */
|
||||
export const wordsOf = (query: string): string[] => fold(query).split(/\s+/).filter(Boolean);
|
||||
|
||||
/** Whether every word is found in the text (an empty query finds everything). */
|
||||
export const hasAllWords = (words: readonly string[], haystack: string): boolean => {
|
||||
const text = fold(haystack);
|
||||
return words.every((w) => text.includes(w));
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
// Small operations on the lists a form edits (favourites, buttons, presets). All return new arrays.
|
||||
|
||||
/** The list with the item at `from` moved by `by` places, stopping at either end. */
|
||||
export function moveWithin<T>(list: readonly T[], from: number, by: number): T[] {
|
||||
const next = [...list];
|
||||
const [item] = next.splice(from, 1);
|
||||
next.splice(Math.max(0, Math.min(next.length, from + by)), 0, item);
|
||||
return next;
|
||||
}
|
||||
|
||||
export const removeAt = <T>(list: readonly T[], index: number): T[] => list.filter((_, i) => i !== index);
|
||||
|
||||
export const patchAt = <T>(list: readonly T[], index: number, patch: Partial<T>): T[] => list.map((item, i) => (i === index ? { ...item, ...patch } : item));
|
||||
|
||||
/** Empty lists are stored as missing, which keeps the saved plan small. */
|
||||
export const orUndefined = <T>(list: T[]): T[] | undefined => (list.length > 0 ? list : undefined);
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Building, Floor } from "../../../model.ts";
|
||||
import { movedMap, newMap, planCentre, tileTemplateFrom } from "./map.ts";
|
||||
|
||||
const house = (floors: Partial<Floor>[]) => ({ floors }) as unknown as Building;
|
||||
|
||||
test("the plan's middle is the middle of every room and outdoor area on all floors", () => {
|
||||
const b = house([{ rooms: [{ points: [[0, 0], [10, 0], [10, 6], [0, 6]] }], outdoor: [{ points: [[-4, -2], [0, -2], [0, 8]] }] } as never]);
|
||||
assert.deepEqual(planCentre(b), [3, 3]);
|
||||
assert.deepEqual(planCentre(house([{ rooms: [], outdoor: [] }])), [0, 0], "an empty plan: the origin");
|
||||
});
|
||||
|
||||
test("a new map starts at Home Assistant's place with the defaults, anchored in the plan's middle", () => {
|
||||
const b = house([{ rooms: [{ points: [[0, 0], [4, 0], [4, 2]] }], outdoor: [] } as never]);
|
||||
const map = newMap(b, { lat: 50.11, lon: 8.68 });
|
||||
assert.deepEqual([map.on, map.lat, map.lon, map.x, map.z, map.opacity, map.zoom, map.url], [true, 50.11, 8.68, 2, 1, 0.5, 18, null]);
|
||||
assert.equal(newMap(b, undefined).lat, 0, "without a place the user types one");
|
||||
});
|
||||
|
||||
test("moving the map shifts its anchor and nothing else", () => {
|
||||
const map = { on: true, lat: 1, lon: 2, x: 1, z: 1, opacity: 0.4 };
|
||||
assert.deepEqual(movedMap(map, 2.5, -1), { ...map, x: 3.5, z: 0 });
|
||||
assert.equal(movedMap({ on: true, lat: 1, lon: 2 }, 1, 1).x, 1, "an anchor that was never set starts at 0");
|
||||
});
|
||||
|
||||
test("a tile address needs https and the three placeholders; empty means OpenStreetMap", () => {
|
||||
assert.equal(tileTemplateFrom(""), null);
|
||||
assert.equal(tileTemplateFrom(" https://t.example/{z}/{x}/{y}.png "), "https://t.example/{z}/{x}/{y}.png");
|
||||
assert.equal(tileTemplateFrom("http://t.example/{z}/{x}/{y}.png"), undefined);
|
||||
assert.equal(tileTemplateFrom("https://t.example/{z}/{x}.png"), undefined);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// Edits of the real map under the plan: switching it on at a sensible place and moving it under the drawing.
|
||||
|
||||
import { DEFAULT_MAP_OPACITY, DEFAULT_MAP_ZOOM } from "../../../map-geo.ts";
|
||||
import type { Building, MapSettings } from "../../../model.ts";
|
||||
|
||||
/** The middle of everything drawn on any floor (rooms and outdoor areas), or the plan's origin for an empty plan. */
|
||||
export function planCentre(b: Building): [number, number] {
|
||||
const xs: number[] = [];
|
||||
const zs: number[] = [];
|
||||
for (const floor of b.floors) {
|
||||
for (const room of floor.rooms) for (const [x, z] of room.points) (xs.push(x), zs.push(z));
|
||||
for (const area of floor.outdoor ?? []) for (const [x, z] of area.points) (xs.push(x), zs.push(z));
|
||||
}
|
||||
if (!xs.length) return [0, 0];
|
||||
const mid = (v: number[]) => Math.round(((Math.min(...v) + Math.max(...v)) / 2) * 100) / 100;
|
||||
return [mid(xs), mid(zs)];
|
||||
}
|
||||
|
||||
/** A map switched on for the first time: at Home Assistant's location (when it knows one), anchored in the middle of the plan. */
|
||||
export function newMap(b: Building, place: { lat?: number; lon?: number } | undefined): MapSettings {
|
||||
const [x, z] = planCentre(b);
|
||||
return { on: true, lat: place?.lat ?? 0, lon: place?.lon ?? 0, x, z, opacity: DEFAULT_MAP_OPACITY, zoom: DEFAULT_MAP_ZOOM, url: null };
|
||||
}
|
||||
|
||||
/** The map moved under the drawing by `dx` metres to the right and `dz` metres down in the plan. */
|
||||
export function movedMap(map: MapSettings, dx: number, dz: number): MapSettings {
|
||||
const round = (v: number) => Math.round(v * 100) / 100;
|
||||
return { ...map, x: round((map.x ?? 0) + dx), z: round((map.z ?? 0) + dz) };
|
||||
}
|
||||
|
||||
/** An address typed for the tile server: https with the three placeholders, or nothing for OpenStreetMap. */
|
||||
export function tileTemplateFrom(text: string): string | null | undefined {
|
||||
const t = text.trim();
|
||||
if (t === "") return null;
|
||||
return /^https:\/\/\S+$/.test(t) && ["{z}", "{x}", "{y}"].every((p) => t.includes(p)) ? t : undefined;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Moving the selection with the arrow keys: one step in a direction. What can move depends on what is selected.
|
||||
|
||||
import { pointInPolygon, type Floor, type Vec2 } from "../../../model.ts";
|
||||
import { openingHost } from "../../../geometry/walls.ts";
|
||||
import { frontExtent, frontOf, outlineLength, withFront } from "../../../geometry/glass-front.ts";
|
||||
|
||||
export type NudgeTarget =
|
||||
| { kind: "device"; id: string }
|
||||
| { kind: "furniture"; id: string }
|
||||
| { kind: "opening"; id: string }
|
||||
| { kind: "wall"; id: string }
|
||||
| { kind: "outdoor"; id: string }
|
||||
| { kind: "room"; id: string; corner: number | null };
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** Nothing of that kind is there to move. */
|
||||
export const NOTHING_TO_MOVE = "unmovable";
|
||||
/** The key was understood but changes nothing, such as an arrow across a wall for an opening that slides along it. */
|
||||
export const NO_CHANGE = "no change";
|
||||
|
||||
export type Nudge = typeof NOTHING_TO_MOVE | typeof NO_CHANGE | { apply(floor: Floor): void };
|
||||
|
||||
/**
|
||||
* What moving the target by (dx, dz) metres would do. A selected corner moves alone. A room moves with the devices inside it. An
|
||||
* opening only slides along its wall by the arrow's share in the wall's direction, and stays within its edge.
|
||||
*/
|
||||
export function nudge(floor: Floor, target: NudgeTarget, dx: number, dz: number): Nudge {
|
||||
const step = (p: Vec2): Vec2 => [thousandths(p[0] + dx), thousandths(p[1] + dz)];
|
||||
switch (target.kind) {
|
||||
case "device": {
|
||||
if (!floor.placements.some((p) => p.entity_id === target.id)) return NOTHING_TO_MOVE;
|
||||
return {
|
||||
apply(f) {
|
||||
const placed = f.placements.find((p) => p.entity_id === target.id);
|
||||
if (placed) [placed.x, placed.z] = step([placed.x, placed.z]);
|
||||
},
|
||||
};
|
||||
}
|
||||
case "furniture":
|
||||
return {
|
||||
apply(f) {
|
||||
const item = f.furniture.find((m) => m.id === target.id);
|
||||
if (item) [item.x, item.z] = step([item.x, item.z]);
|
||||
},
|
||||
};
|
||||
case "wall":
|
||||
return {
|
||||
apply(f) {
|
||||
const wall = (f.walls ?? []).find((w) => w.id === target.id);
|
||||
if (wall) [wall.a, wall.b] = [step(wall.a), step(wall.b)];
|
||||
},
|
||||
};
|
||||
case "outdoor":
|
||||
return {
|
||||
apply(f) {
|
||||
const area = f.outdoor.find((a) => a.id === target.id);
|
||||
if (area) area.points = area.points.map(step);
|
||||
},
|
||||
};
|
||||
case "opening": {
|
||||
const opening = floor.openings.find((o) => o.id === target.id);
|
||||
const host = opening ? openingHost(opening, floor.rooms, floor.walls ?? []) : null;
|
||||
if (!opening || !host) return NOTHING_TO_MOVE;
|
||||
const a = host.room.points[host.edge];
|
||||
const b = host.room.points[(host.edge + 1) % host.room.points.length];
|
||||
const length = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
|
||||
const along = (dx * (b[0] - a[0]) + dz * (b[1] - a[1])) / length;
|
||||
if (Math.abs(along) < 1e-9) return NO_CHANGE;
|
||||
// a pane over several edges slides as a whole, and keeps the length of all of its pieces
|
||||
const group = frontOf(floor.openings, opening);
|
||||
const extent = !opening.wall && group.length > 1 ? frontExtent(host.room, group) : null;
|
||||
if (extent) {
|
||||
const from = Math.max(0, Math.min(outlineLength(host.room) - extent.width, extent.from + along));
|
||||
if (Math.abs(from - extent.from) < 1e-9) return NO_CHANGE;
|
||||
return {
|
||||
apply(f) {
|
||||
const o = f.openings.find((x) => x.id === target.id);
|
||||
const next = o ? withFront(f.openings, host.room, o, from, extent.width) : null;
|
||||
if (next) f.openings = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
const half = Math.min(opening.width, length) / 2;
|
||||
const offset = thousandths(Math.min(length - half, Math.max(half, opening.offset + along)));
|
||||
return {
|
||||
apply(f) {
|
||||
const o = f.openings.find((x) => x.id === target.id);
|
||||
if (o) o.offset = offset;
|
||||
},
|
||||
};
|
||||
}
|
||||
case "room": {
|
||||
const room = floor.rooms.find((r) => r.id === target.id);
|
||||
if (!room) return NOTHING_TO_MOVE;
|
||||
const inside = new Set(floor.placements.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id));
|
||||
return {
|
||||
apply(f) {
|
||||
const r = f.rooms.find((x) => x.id === target.id);
|
||||
if (!r) return;
|
||||
if (target.corner !== null && target.corner < r.points.length) {
|
||||
r.points[target.corner] = step(r.points[target.corner]);
|
||||
return;
|
||||
}
|
||||
r.points = r.points.map(step);
|
||||
for (const placed of f.placements) if (inside.has(placed.entity_id)) [placed.x, placed.z] = step([placed.x, placed.z]);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf, opening } from "../../../entities/fixtures.ts";
|
||||
import { emptyBuilding } from "../../../model.ts";
|
||||
import { checkPlan, roomsOverlap } from "./plan-check.ts";
|
||||
|
||||
test("rooms that only share a wall do not overlap, rooms on top of each other do", () => {
|
||||
assert.equal(roomsOverlap(box("a", 0, 0, 4, 3), box("b", 4, 0, 8, 3)), false);
|
||||
assert.equal(roomsOverlap(box("a", 0, 0, 4, 3), box("b", 3, 0, 8, 3)), true);
|
||||
assert.equal(roomsOverlap(box("a", 0, 0, 4, 3), box("b", 1, 1, 2, 2)), true);
|
||||
});
|
||||
|
||||
test("the plan check finds rooms without an area, overlapping rooms, unplaced devices and gone entities", () => {
|
||||
const hass = hassOf([entity("light.wohnen", "on"), entity("switch.wohnen_tv", "off")], { "light.wohnen": { area_id: "wohnen" }, "switch.wohnen_tv": { area_id: "wohnen" } }, {
|
||||
areas: { wohnen: { area_id: "wohnen", name: "Wohnen" }, kueche: { area_id: "kueche", name: "Küche" } },
|
||||
});
|
||||
const living = { ...box("w", 0, 0, 5, 4), name: "Wohnen", area_id: "wohnen" };
|
||||
const kitchen = { ...box("k", 5, 0, 8, 4), name: "Küche", area_id: null };
|
||||
const store = { ...box("s", 7, 1, 9, 3), name: "Abstell", area_id: null };
|
||||
const floor = { ...floorWith([living, kitchen, store]), placements: [{ entity_id: "light.gone", x: 1, z: 1, y: null, mount: null }] };
|
||||
const doc = { ...emptyBuilding(), floors: [floor] };
|
||||
const kinds = checkPlan(doc, hass).map((f) => f.kind);
|
||||
assert.ok(kinds.includes("room_no_area"));
|
||||
assert.ok(kinds.includes("rooms_overlap"));
|
||||
assert.ok(kinds.includes("devices_unplaced"));
|
||||
assert.ok(kinds.includes("entity_missing"));
|
||||
// the kitchen has a free area of its own name: the fix links it
|
||||
const named = checkPlan(doc, hass).find((f) => f.kind === "room_no_area" && f.vars.room === "Küche");
|
||||
assert.deepEqual(named?.fix, { do: "set_area", roomId: "k", areaId: "kueche" });
|
||||
const store2 = checkPlan(doc, hass).find((f) => f.kind === "room_no_area" && f.vars.room === "Abstell");
|
||||
assert.deepEqual(store2?.fix, { do: "show_room", roomId: "s" });
|
||||
});
|
||||
|
||||
test("a door on a wall is fine, one past the end of its wall is found", () => {
|
||||
const room = box("r", 0, 0, 4, 3);
|
||||
const ok = { ...floorWith([room]), openings: [opening("d1", "r", "door", { edge: 0, offset: 1, width: 0.9 })] };
|
||||
assert.equal(checkPlan({ ...emptyBuilding(), floors: [ok] }, undefined).filter((f) => f.kind === "opening_off_wall").length, 0);
|
||||
const off = { ...floorWith([room]), openings: [opening("d1", "r", "door", { edge: 9, offset: 1, width: 0.9 })] };
|
||||
assert.equal(checkPlan({ ...emptyBuilding(), floors: [off] }, undefined).filter((f) => f.kind === "opening_off_wall").length, 1);
|
||||
});
|
||||
|
||||
test("a device that is off but still draws power is a standby eater, with its cost a year", () => {
|
||||
const hass = hassOf(
|
||||
[entity("switch.tv", "off"), entity("sensor.tv_power", "12", { device_class: "power", unit_of_measurement: "W" }), entity("sensor.tariff", "0.30", { unit_of_measurement: "EUR/kWh" })],
|
||||
{ "switch.tv": { device_id: "d1" }, "sensor.tv_power": { device_id: "d1" } },
|
||||
);
|
||||
const room = box("w", 0, 0, 5, 4);
|
||||
const floor = { ...floorWith([room]), placements: [{ entity_id: "switch.tv", x: 1, z: 1, y: null, mount: null }] };
|
||||
const doc = { ...emptyBuilding(), floors: [floor] };
|
||||
doc.energy = { ...doc.energy, tariff: "sensor.tariff" };
|
||||
const found = checkPlan(doc, hass).find((f) => f.kind === "standby");
|
||||
assert.ok(found, JSON.stringify(checkPlan(doc, hass).map((f) => f.kind)));
|
||||
assert.equal(found.vars.w, 12);
|
||||
// 12 W all year: 105 kWh, 32 €
|
||||
assert.equal(found.vars.cost, "32 €");
|
||||
});
|
||||
|
||||
test("a cover that a window picks up automatically through its area is not reported as unplaced (#81)", () => {
|
||||
const hass = hassOf([entity("cover.wohnen_rollo", "open")], { "cover.wohnen_rollo": { area_id: "wohnen" } }, { areas: { wohnen: { area_id: "wohnen", name: "Wohnen" } } });
|
||||
const living = { ...box("w", 0, 0, 5, 4), name: "Wohnen", area_id: "wohnen" };
|
||||
const floor = { ...floorWith([living]), openings: [opening("o1", "w", "window")] };
|
||||
const found = checkPlan({ ...emptyBuilding(), floors: [floor] }, hass).filter((f) => f.kind === "devices_unplaced");
|
||||
assert.equal(found.length, 0);
|
||||
const without = checkPlan({ ...emptyBuilding(), floors: [{ ...floor, openings: [] }] }, hass).filter((f) => f.kind === "devices_unplaced");
|
||||
assert.equal(without.length, 1, "without the window the cover is still missing");
|
||||
});
|
||||
|
||||
test("devices on the ignore list are not reported as missing from the plan (#103)", () => {
|
||||
const hass = hassOf([entity("light.wohnen", "on"), entity("switch.knx_intern", "off")], { "light.wohnen": { area_id: "wohnen" }, "switch.knx_intern": { area_id: "wohnen" } }, { areas: { wohnen: { area_id: "wohnen", name: "Wohnen" } } });
|
||||
const living = { ...box("w", 0, 0, 5, 4), name: "Wohnen", area_id: "wohnen" };
|
||||
const doc = { ...emptyBuilding(), floors: [floorWith([living])] };
|
||||
const first = checkPlan(doc, hass).find((f) => f.kind === "devices_unplaced");
|
||||
assert.deepEqual([...(first?.entityIds ?? [])].sort(), ["light.wohnen", "switch.knx_intern"]);
|
||||
doc.settings.check_ignore = ["switch.knx_intern"];
|
||||
assert.deepEqual(checkPlan(doc, hass).find((f) => f.kind === "devices_unplaced")?.entityIds, ["light.wohnen"]);
|
||||
doc.settings.check_ignore = ["switch.knx_intern", "light.wohnen"];
|
||||
assert.equal(checkPlan(doc, hass).filter((f) => f.kind === "devices_unplaced").length, 0);
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
// The plan check: what is missing or off in the plan, found in one pass over the building. Each finding names where it is and, where
|
||||
// one is clear, the fix the editor can make in one tap.
|
||||
|
||||
import { entityKind, entityName, groupByDevice, isPlaceable, roomEntities } from "../../../devices.ts";
|
||||
import { furnitureEntities } from "../../../entities/furniture-links.ts";
|
||||
import { openingEntities } from "../../../entities/openings.ts";
|
||||
import { powerSensorFor, readPower } from "../../../energy.ts";
|
||||
import { energyCost } from "../../../live/room-energy.ts";
|
||||
import { LOW_BATTERY, planBatteries } from "../../../live/batteries.ts";
|
||||
import { locateOpening, openingHost, generateWalls } from "../../../geometry/walls.ts";
|
||||
import { isLamp, pointInPolygon, type Building, type Floor, type Room, type Vec2 } from "../../../model.ts";
|
||||
import type { HomeAssistant } from "../../../types.ts";
|
||||
import { placedInRoom } from "./device-list.ts";
|
||||
import { unplacedAreas } from "./floors.ts";
|
||||
|
||||
export type CheckKind = "room_no_area" | "areas_unplaced" | "devices_unplaced" | "rooms_overlap" | "opening_off_wall" | "entity_missing" | "furniture_entity_missing" | "standby" | "battery_low";
|
||||
|
||||
/** What a tap on a finding does: show it, or fix it right away. */
|
||||
export type CheckFix =
|
||||
| { do: "show_room"; roomId: string }
|
||||
| { do: "show_floor" }
|
||||
| { do: "set_area"; roomId: string; areaId: string }
|
||||
| { do: "add_area_rooms" }
|
||||
| { do: "place_devices"; roomId: string; entityIds: string[] }
|
||||
| { do: "ignore_devices"; entityIds: string[] }
|
||||
| { do: "show_opening"; openingId: string }
|
||||
| { do: "remove_placements"; entityIds: string[] }
|
||||
| { do: "show_furniture"; furnitureId: string };
|
||||
|
||||
export interface CheckFinding {
|
||||
kind: CheckKind;
|
||||
floorId: string;
|
||||
/** Values for the text: a room name, a count, an entity. */
|
||||
vars: Record<string, string | number>;
|
||||
fix: CheckFix;
|
||||
/** The entities a finding is about, when it is about a list of them (the devices not in the plan yet, #103). */
|
||||
entityIds?: string[];
|
||||
/** Fixes that change the plan (all others only show the place). */
|
||||
changes: boolean;
|
||||
}
|
||||
|
||||
const MARGIN = 0.08;
|
||||
|
||||
function distanceToEdges(p: Vec2, points: readonly Vec2[]): number {
|
||||
let best = Infinity;
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const a = points[i];
|
||||
const b = points[(i + 1) % points.length];
|
||||
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
|
||||
const len2 = dx * dx + dz * dz;
|
||||
const t = len2 > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / len2)) : 0;
|
||||
best = Math.min(best, Math.hypot(p[0] - (a[0] + dx * t), p[1] - (a[1] + dz * t)));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const boxOf = (points: readonly Vec2[]) => ({
|
||||
x0: Math.min(...points.map((p) => p[0])),
|
||||
x1: Math.max(...points.map((p) => p[0])),
|
||||
z0: Math.min(...points.map((p) => p[1])),
|
||||
z1: Math.max(...points.map((p) => p[1])),
|
||||
});
|
||||
|
||||
/** Whether two rooms really share floor space (not only a wall): some point lies well inside both. */
|
||||
export function roomsOverlap(a: Room, b: Room, step = 0.2): boolean {
|
||||
if (a.points.length < 3 || b.points.length < 3) return false;
|
||||
const [p, q] = [boxOf(a.points), boxOf(b.points)];
|
||||
const x0 = Math.max(p.x0, q.x0) + MARGIN;
|
||||
const x1 = Math.min(p.x1, q.x1) - MARGIN;
|
||||
const z0 = Math.max(p.z0, q.z0) + MARGIN;
|
||||
const z1 = Math.min(p.z1, q.z1) - MARGIN;
|
||||
if (x1 <= x0 || z1 <= z0) return false;
|
||||
for (let x = x0; x <= x1 + 1e-9; x += Math.min(step, x1 - x0 || step)) {
|
||||
for (let z = z0; z <= z1 + 1e-9; z += Math.min(step, z1 - z0 || step)) {
|
||||
const pt: Vec2 = [x, z];
|
||||
if (pointInPolygon(pt, a.points) && pointInPolygon(pt, b.points) && distanceToEdges(pt, a.points) > MARGIN && distanceToEdges(pt, b.points) > MARGIN) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Every field of an item that holds an entity id (a light, a power sensor, a contact …), lists of them included. */
|
||||
function entityValues(item: object): string[] {
|
||||
const skip = new Set(["id", "type", "variant", "name", "icon", "picture", "vehicle", "room_id", "wall"]);
|
||||
const looks = (v: unknown): v is string => typeof v === "string" && /^[a-z_]+\.[a-z0-9_]+$/.test(v);
|
||||
return Object.entries(item).flatMap(([key, value]) => (skip.has(key) ? [] : Array.isArray(value) ? value.filter(looks) : looks(value) ? [value] : []));
|
||||
}
|
||||
|
||||
/** The entities a piece of furniture links: the light, power sensor, doors, state, extra lights … */
|
||||
const furnitureEntityFields = (m: Floor["furniture"][number]): string[] => entityValues(m);
|
||||
|
||||
/** A device that is off but still draws more than this (W) is listed as a standby eater. */
|
||||
const STANDBY_W = 3;
|
||||
const OFF = new Set(["off", "standby", "idle"]);
|
||||
|
||||
/** Devices of the plan that are off but draw power: their entity says off, the power sensor on their device still reads watts. */
|
||||
function standbyFindings(hass: HomeAssistant, doc: Building, floor: Floor, out: CheckFinding[]): void {
|
||||
const id = doc.energy.tariff;
|
||||
const st = id ? hass.states[id] : undefined;
|
||||
const tariff = st ? { value: Number(st.state), unit: String(st.attributes.unit_of_measurement ?? "") } : null;
|
||||
const seen = new Set<string>();
|
||||
const check = (entity: string | null | undefined, show: CheckFix) => {
|
||||
if (!entity || entity === "none" || seen.has(entity)) return;
|
||||
seen.add(entity);
|
||||
const state = hass.states[entity]?.state;
|
||||
if (!state || !OFF.has(state) || entity.startsWith("light.")) return;
|
||||
const sensor = powerSensorFor(hass, entity);
|
||||
const w = sensor ? readPower(hass.states[sensor]) : null;
|
||||
if (w === null || w <= STANDBY_W) return;
|
||||
const cost = energyCost((w * 24 * 365) / 1000, tariff);
|
||||
out.push({ kind: "standby", floorId: floor.id, vars: { name: entityName(hass, entity), w: Math.round(w), cost: cost ? `${cost.value.toFixed(0)} ${cost.currency}` : `${Math.round((w * 24 * 365) / 1000)} kWh` }, fix: show, changes: false });
|
||||
};
|
||||
for (const m of floor.furniture) check(m.entity, { do: "show_furniture", furnitureId: m.id });
|
||||
for (const p of floor.placements) {
|
||||
const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([p.x, p.z], r.points));
|
||||
if (room) check(p.entity_id, { do: "show_room", roomId: room.id });
|
||||
}
|
||||
}
|
||||
|
||||
/** Every finding of the plan check, floor by floor. A finding needs Home Assistant's states only where it says so. */
|
||||
export function checkPlan(doc: Building, hass: HomeAssistant | undefined): CheckFinding[] {
|
||||
const out: CheckFinding[] = [];
|
||||
const areas = hass?.areas;
|
||||
// devices the user said they do not want in the plan (internal KNX devices, say)
|
||||
const ignored = new Set(doc.settings.check_ignore ?? []);
|
||||
const usedAreas = new Set(doc.floors.flatMap((f) => f.rooms.map((r) => r.area_id)).filter((a): a is string => !!a));
|
||||
for (const floor of doc.floors) {
|
||||
if (floor.layer) continue;
|
||||
// rooms without a Home Assistant area: an area of the same name is offered when it is free
|
||||
for (const room of floor.rooms) {
|
||||
if (room.area_id) continue;
|
||||
const same = Object.values(areas ?? {}).find((a) => a.name.trim().toLowerCase() === room.name.trim().toLowerCase() && !usedAreas.has(a.area_id));
|
||||
out.push(same ? { kind: "room_no_area", floorId: floor.id, vars: { room: room.name, area: same.name }, fix: { do: "set_area", roomId: room.id, areaId: same.area_id }, changes: true } : { kind: "room_no_area", floorId: floor.id, vars: { room: room.name, area: "" }, fix: { do: "show_room", roomId: room.id }, changes: false });
|
||||
}
|
||||
const lacking = unplacedAreas(doc, floor, areas);
|
||||
if (lacking.length) out.push({ kind: "areas_unplaced", floorId: floor.id, vars: { n: lacking.length, names: lacking.map((a) => a.name).join(", ") }, fix: { do: "add_area_rooms" }, changes: true });
|
||||
// devices of a room's area that are not in the plan yet (the main entity of each device, as the device list counts them)
|
||||
if (hass) {
|
||||
// what furniture, doors and windows are linked to, explicitly or found automatically through the area (a KNX blind, a lamp)
|
||||
const linkedFurniture = furnitureEntities(hass, [floor]);
|
||||
const linkedOpenings = openingEntities(hass, [floor]);
|
||||
for (const room of floor.rooms) {
|
||||
if (!room.area_id) continue;
|
||||
// placed: as a pin or lamp, or linked to a piece of furniture or a door or window of the room
|
||||
const here = placedInRoom(floor, room);
|
||||
for (const m of floor.furniture) if (pointInPolygon([m.x, m.z], room.points)) for (const id of furnitureEntityFields(m)) here.add(id);
|
||||
for (const o of floor.openings) {
|
||||
if (o.room_id !== room.id) continue;
|
||||
for (const id of entityValues(o)) here.add(id);
|
||||
for (const id of Object.values(linkedOpenings.get(o.id) ?? {})) if (typeof id === "string") here.add(id);
|
||||
}
|
||||
for (const m of floor.furniture) {
|
||||
const l = linkedFurniture.get(m.id);
|
||||
if (l && pointInPolygon([m.x, m.z], room.points)) for (const id of [l.entity, l.power]) if (typeof id === "string") here.add(id);
|
||||
}
|
||||
const ids = roomEntities(hass, room).filter((id) => isPlaceable(entityKind(hass, id)));
|
||||
const unplaced = groupByDevice(hass, ids)
|
||||
.map((g) => g.primary)
|
||||
.filter((id) => !here.has(id) && !ignored.has(id));
|
||||
if (unplaced.length) out.push({ kind: "devices_unplaced", floorId: floor.id, vars: { room: room.name, n: unplaced.length }, fix: { do: "place_devices", roomId: room.id, entityIds: unplaced }, entityIds: unplaced, changes: true });
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < floor.rooms.length; i++) {
|
||||
for (let j = i + 1; j < floor.rooms.length; j++) {
|
||||
const [a, b] = [floor.rooms[i], floor.rooms[j]];
|
||||
if (roomsOverlap(a, b)) out.push({ kind: "rooms_overlap", floorId: floor.id, vars: { a: a.name, b: b.name }, fix: { do: "show_room", roomId: b.id }, changes: false });
|
||||
}
|
||||
}
|
||||
if (floor.openings.length) {
|
||||
const walls = generateWalls(floor.rooms, { exterior: doc.settings.wall_exterior, interior: doc.settings.wall_interior }, floor.walls ?? []).walls;
|
||||
for (const o of floor.openings) {
|
||||
const host = openingHost(o, floor.rooms, floor.walls ?? []);
|
||||
if (!host || !locateOpening(walls, o, host)) out.push({ kind: "opening_off_wall", floorId: floor.id, vars: { room: floor.rooms.find((r) => r.id === o.room_id)?.name ?? "" }, fix: { do: "show_opening", openingId: o.id }, changes: false });
|
||||
}
|
||||
}
|
||||
if (hass) standbyFindings(hass, doc, floor, out);
|
||||
// links to entities Home Assistant no longer knows (renamed or removed)
|
||||
if (hass && Object.keys(hass.states).length) {
|
||||
const gone = floor.placements.map((p) => p.entity_id).filter((id) => !hass.states[id]);
|
||||
if (gone.length) out.push({ kind: "entity_missing", floorId: floor.id, vars: { n: gone.length, ids: gone.slice(0, 3).join(", ") }, fix: { do: "remove_placements", entityIds: gone }, changes: true });
|
||||
for (const m of floor.furniture) {
|
||||
const missing = furnitureEntityFields(m).filter((id) => id !== "none" && !hass.states[id]);
|
||||
if (missing.length && !(isLamp(m.type) && !m.entity)) out.push({ kind: "furniture_entity_missing", floorId: floor.id, vars: { id: missing[0] }, fix: { do: "show_furniture", furnitureId: m.id }, changes: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
// low batteries of the plan's devices, by floor
|
||||
if (hass) {
|
||||
for (const b of planBatteries(hass, doc)) {
|
||||
if (b.level >= LOW_BATTERY) break;
|
||||
out.push({ kind: "battery_low", floorId: b.floorId, vars: { name: entityName(hass, b.entity), level: Math.round(b.level) }, fix: b.roomId ? { do: "show_room", roomId: b.roomId } : { do: "show_floor" }, changes: false });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import { emptyBuilding } from "../../../model.ts";
|
||||
import { diffBuildings } from "./plan-diff.ts";
|
||||
|
||||
test("comparing two states lists what was added, removed, renamed, reshaped and moved", () => {
|
||||
const older = emptyBuilding();
|
||||
older.floors = [
|
||||
{
|
||||
...floorWith([box("a", 0, 0, 4, 3), box("b", 4, 0, 7, 3)]),
|
||||
name: "EG",
|
||||
openings: [opening("d1", "a", "door")],
|
||||
furniture: [{ id: "s1", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null }],
|
||||
placements: [{ entity_id: "light.a", x: 1, z: 1, y: null, mount: null }],
|
||||
},
|
||||
];
|
||||
const current = structuredClone(older);
|
||||
const eg = current.floors[0];
|
||||
eg.rooms[0].name = "Wohnen";
|
||||
eg.rooms[1].points = [[4, 0], [8, 0], [8, 3], [4, 3]];
|
||||
eg.rooms.push(box("c", 0, 3, 4, 6));
|
||||
eg.openings = [opening("w1", "c", "window")];
|
||||
eg.furniture[0].x = 2;
|
||||
eg.placements = [{ entity_id: "light.b", x: 2, z: 2, y: null, mount: null }];
|
||||
const kinds = diffBuildings(older, current).map((e) => e.kind).sort();
|
||||
assert.deepEqual(kinds, ["device_added", "device_removed", "furniture_moved", "opening_added", "opening_removed", "room_added", "room_renamed", "room_reshaped"].sort());
|
||||
const reshaped = diffBuildings(older, current).find((e) => e.kind === "room_reshaped");
|
||||
assert.equal(reshaped?.detail, 3);
|
||||
assert.deepEqual(diffBuildings(older, older), []);
|
||||
});
|
||||
|
||||
test("floors added and removed", () => {
|
||||
const older = emptyBuilding();
|
||||
older.floors = [{ ...floorWith([]), id: "a", name: "Keller" }];
|
||||
const current = emptyBuilding();
|
||||
current.floors = [{ ...floorWith([]), id: "b", name: "Dach" }];
|
||||
assert.deepEqual(diffBuildings(older, current).map((e) => [e.kind, e.name]), [["floor_added", "Dach"], ["floor_removed", "Keller"]]);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
// Two states of the plan compared: what was added, removed, moved or renamed, floor by floor. Items are matched by their id, so a
|
||||
// room drawn anew counts as removed and added, while a room dragged or reshaped counts as changed.
|
||||
|
||||
import { polygonArea, type Building, type Floor } from "../../../model.ts";
|
||||
|
||||
export type DiffKind = "floor_added" | "floor_removed" | "room_added" | "room_removed" | "room_renamed" | "room_reshaped" | "opening_added" | "opening_removed" | "furniture_added" | "furniture_removed" | "furniture_moved" | "device_added" | "device_removed" | "device_moved";
|
||||
|
||||
export interface DiffEntry {
|
||||
kind: DiffKind;
|
||||
/** The floor's name in the newer plan (in the older one for a removed floor). */
|
||||
floor: string;
|
||||
/** What it is about: a room's name, a piece's type, an entity. */
|
||||
name: string;
|
||||
/** A second name: the old name of a renamed room, the area change of a reshaped one (m²). */
|
||||
detail?: string | number;
|
||||
}
|
||||
|
||||
const MOVE = 0.05;
|
||||
const same = (a: readonly [number, number][], b: readonly [number, number][]) => a.length === b.length && a.every((p, i) => Math.abs(p[0] - b[i][0]) < 1e-3 && Math.abs(p[1] - b[i][1]) < 1e-3);
|
||||
const byId = <T extends { id: string }>(list: readonly T[]) => new Map(list.map((x) => [x.id, x]));
|
||||
|
||||
function floorDiff(was: Floor, now: Floor, out: DiffEntry[], roomName: (id: string) => string): void {
|
||||
const floor = now.name;
|
||||
const [oldRooms, newRooms] = [byId(was.rooms), byId(now.rooms)];
|
||||
for (const r of now.rooms) {
|
||||
const before = oldRooms.get(r.id);
|
||||
if (!before) out.push({ kind: "room_added", floor, name: r.name });
|
||||
else {
|
||||
if (before.name !== r.name) out.push({ kind: "room_renamed", floor, name: r.name, detail: before.name });
|
||||
if (!same(before.points, r.points)) out.push({ kind: "room_reshaped", floor, name: r.name, detail: Math.round((polygonArea(r.points) - polygonArea(before.points)) * 10) / 10 });
|
||||
}
|
||||
}
|
||||
for (const r of was.rooms) if (!newRooms.has(r.id)) out.push({ kind: "room_removed", floor, name: r.name });
|
||||
const [oldOpenings, newOpenings] = [byId(was.openings), byId(now.openings)];
|
||||
for (const o of now.openings) if (!oldOpenings.has(o.id)) out.push({ kind: "opening_added", floor, name: o.type, detail: roomName(o.room_id) });
|
||||
for (const o of was.openings) if (!newOpenings.has(o.id)) out.push({ kind: "opening_removed", floor, name: o.type, detail: roomName(o.room_id) });
|
||||
const [oldItems, newItems] = [byId(was.furniture), byId(now.furniture)];
|
||||
for (const m of now.furniture) {
|
||||
const before = oldItems.get(m.id);
|
||||
if (!before) out.push({ kind: "furniture_added", floor, name: m.name || m.type });
|
||||
else if (Math.hypot(m.x - before.x, m.z - before.z) > MOVE || Math.abs(m.rotation - before.rotation) > 1 || Math.abs(m.w - before.w) > MOVE || Math.abs(m.d - before.d) > MOVE)
|
||||
out.push({ kind: "furniture_moved", floor, name: m.name || m.type });
|
||||
}
|
||||
for (const m of was.furniture) if (!newItems.has(m.id)) out.push({ kind: "furniture_removed", floor, name: m.name || m.type });
|
||||
const [oldPins, newPins] = [new Map(was.placements.map((p) => [p.entity_id, p])), new Map(now.placements.map((p) => [p.entity_id, p]))];
|
||||
for (const p of now.placements) {
|
||||
const before = oldPins.get(p.entity_id);
|
||||
if (!before) out.push({ kind: "device_added", floor, name: p.entity_id });
|
||||
else if (Math.hypot(p.x - before.x, p.z - before.z) > MOVE) out.push({ kind: "device_moved", floor, name: p.entity_id });
|
||||
}
|
||||
for (const p of was.placements) if (!newPins.has(p.entity_id)) out.push({ kind: "device_removed", floor, name: p.entity_id });
|
||||
}
|
||||
|
||||
/** Everything that differs between an older plan and the current one. */
|
||||
export function diffBuildings(older: Building, current: Building): DiffEntry[] {
|
||||
const out: DiffEntry[] = [];
|
||||
const oldFloors = byId(older.floors);
|
||||
const rooms = new Map([...older.floors, ...current.floors].flatMap((f) => f.rooms.map((r) => [r.id, r.name] as const)));
|
||||
const roomName = (id: string) => rooms.get(id) ?? "";
|
||||
for (const f of current.floors) {
|
||||
const before = oldFloors.get(f.id);
|
||||
if (!before) out.push({ kind: "floor_added", floor: f.name, name: f.name });
|
||||
else floorDiff(before, f, out, roomName);
|
||||
}
|
||||
const now = new Set(current.floors.map((f) => f.id));
|
||||
for (const f of older.floors) if (!now.has(f.id)) out.push({ kind: "floor_removed", floor: f.name, name: f.name });
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building, RoofSection, RoofSettings, SolarField } from "../../../model.ts";
|
||||
import { copyOfSection, insertRoofCorner, removeRoofCorner, roofOutline, sectionFromRectangle, sectionNumber } from "./roof.ts";
|
||||
import { assignString, columnsPatch, columnsText, keptOnMove, pruneStrings, rowsPatch, toggledSkip } from "./solar.ts";
|
||||
|
||||
const field = (id: string, extra: Partial<SolarField> = {}): SolarField => ({ id, face: "main:a", u: 0, v: 0, rows: 2, cols: 3, portrait: true, ...extra });
|
||||
const roof = (extra: Partial<RoofSettings> = {}): RoofSettings => ({ type: "custom", pitch: 35, overhang: 0.4, ...extra });
|
||||
const house = (): Building => ({ version: 1, floors: [floorWith([box("r", 0, 0, 6, 4)], { elevation: 0, height: 2.5 })], settings: { roof: roof() }, energy: {}, presence: [] }) as unknown as Building;
|
||||
|
||||
test("a section drawn over a room sits on its walls, one drawn over nothing is an open canopy", () => {
|
||||
const over = sectionFromRectangle(house(), [0, 0], [6, 4]);
|
||||
assert.equal(over.shape, "gable");
|
||||
assert.equal(over.axis, "x");
|
||||
assert.equal(over.eave_a, 2.5);
|
||||
assert.equal(over.pitch_a, 35);
|
||||
assert.equal(over.overhang, null);
|
||||
assert.equal(over.open, undefined);
|
||||
const canopy = sectionFromRectangle(house(), [10, 10], [12, 16]);
|
||||
assert.equal(canopy.shape, "pent");
|
||||
assert.equal(canopy.axis, "z");
|
||||
assert.equal(canopy.eave_a, 2.4);
|
||||
assert.equal(canopy.pitch_a, 6);
|
||||
assert.equal(canopy.overhang, 0.15);
|
||||
assert.equal(canopy.open, true);
|
||||
});
|
||||
|
||||
test("a copy is shifted by a metre, has its own id, and shares nothing with the original", () => {
|
||||
const original: RoofSection = { ...sectionFromRectangle(house(), [0, 0], [6, 4]), points: [[0, 0], [1, 0], [1, 1]] };
|
||||
const copy = copyOfSection(original);
|
||||
assert.notEqual(copy.id, original.id);
|
||||
assert.deepEqual([copy.x0, copy.x1, copy.z0, copy.z1], [1, 7, 1, 5]);
|
||||
copy.points!.push([5, 5]);
|
||||
assert.equal(original.points!.length, 3);
|
||||
assert.equal(sectionNumber([original, copy], copy.id), 2);
|
||||
assert.equal(sectionNumber([original], "nope"), 0);
|
||||
});
|
||||
|
||||
test("a new string takes the field's sensor, and a string nobody uses any more goes away", () => {
|
||||
const settings = roof({ solar: [field("a", { entity: "sensor.pv" }), field("b")] });
|
||||
assignString(settings, "a", "new", { id: "s1", name: (n) => `String ${n}` });
|
||||
assert.deepEqual(settings.strings, [{ id: "s1", name: "String 1", entity: "sensor.pv", inverter: null }]);
|
||||
assert.equal(settings.solar![0].string, "s1");
|
||||
assignString(settings, "b", "s1", { id: "unused", name: () => "" });
|
||||
assert.equal(settings.solar![1].string, "s1");
|
||||
assignString(settings, "a", null, { id: "unused", name: () => "" });
|
||||
assert.equal(settings.strings!.length, 1, "b still uses it");
|
||||
assignString(settings, "b", null, { id: "unused", name: () => "" });
|
||||
assert.deepEqual(settings.strings, []);
|
||||
assignString(settings, "missing", "new", { id: "x", name: () => "" });
|
||||
assert.deepEqual(settings.strings, []);
|
||||
});
|
||||
|
||||
test("pruning keeps the strings that are used", () => {
|
||||
const settings = roof({ solar: [field("a", { string: "keep" })], strings: [{ id: "keep", name: "k" }, { id: "drop", name: "d" }] });
|
||||
pruneStrings(settings);
|
||||
assert.deepEqual(settings.strings!.map((s) => s.id), ["keep"]);
|
||||
});
|
||||
|
||||
test("clicking a module switches it off, and clicking it again on; no cell left out gives null", () => {
|
||||
assert.deepEqual(toggledSkip(null, "1:2"), ["1:2"]);
|
||||
assert.deepEqual(toggledSkip(["1:2"], "0:0"), ["0:0", "1:2"]);
|
||||
assert.equal(toggledSkip(["1:2"], "1:2"), null);
|
||||
});
|
||||
|
||||
test("the columns box: one number or a list, with limits, and nothing usable gives null", () => {
|
||||
assert.deepEqual(columnsPatch("5"), { cols: 5, layout: null, skip: null });
|
||||
assert.deepEqual(columnsPatch("0"), { cols: 1, layout: null, skip: null });
|
||||
assert.deepEqual(columnsPatch("500"), { cols: 60, layout: null, skip: null });
|
||||
assert.deepEqual(columnsPatch("4, 4;3"), { layout: [4, 4, 3], rows: 3, cols: 4, skip: null });
|
||||
assert.equal(columnsPatch("abc"), null);
|
||||
assert.equal(columnsPatch(""), null);
|
||||
assert.equal(columnsText(field("a", { layout: [4, 3] })), "4, 3");
|
||||
assert.equal(columnsText(field("a", { cols: 7 })), "7");
|
||||
});
|
||||
|
||||
test("more rows take the last row's length, fewer rows cut the list, and the count stays in range", () => {
|
||||
assert.deepEqual(rowsPatch(field("a"), 4), { rows: 4 });
|
||||
assert.deepEqual(rowsPatch(field("a", { layout: [4, 3] }), 4), { rows: 4, layout: [4, 3, 3, 3] });
|
||||
assert.deepEqual(rowsPatch(field("a", { layout: [4, 3, 2] }), 2), { rows: 2, layout: [4, 3] });
|
||||
assert.equal(rowsPatch(field("a"), 0).rows, 1);
|
||||
assert.equal(rowsPatch(field("a"), 99).rows, 40);
|
||||
});
|
||||
|
||||
test("moving to another face keeps the modules and links but not the place", () => {
|
||||
const kept = keptOnMove(field("a", { name: "Süd", wp: 410, look: "blue", u: 3, v: 4, rows: 9 }));
|
||||
assert.equal(kept.name, "Süd");
|
||||
assert.equal(kept.wp, 410);
|
||||
assert.equal(kept.look, "blue");
|
||||
assert.equal("u" in kept, false);
|
||||
assert.equal("rows" in kept, false);
|
||||
});
|
||||
|
||||
test("a flat roof becomes a free shape with the first corner, and its box follows the points", () => {
|
||||
const flat = { ...sectionFromRectangle(house(), [0, 0], [6, 4]), shape: "flat" as const };
|
||||
assert.deepEqual(roofOutline(flat), [[0, 0], [6, 0], [6, 4], [0, 4]]);
|
||||
insertRoofCorner(flat, 1, [6, 2]);
|
||||
assert.deepEqual(flat.points, [[0, 0], [6, 0], [6, 2], [6, 4], [0, 4]]);
|
||||
// pulling the new corner out widens the box
|
||||
flat.points![2] = [8, 2];
|
||||
insertRoofCorner(flat, 2, [7, 3]);
|
||||
assert.equal(flat.x1, 8);
|
||||
assert.equal(flat.z1, 4);
|
||||
assert.equal(removeRoofCorner(flat, 2), true);
|
||||
assert.equal(flat.points!.length, 5);
|
||||
});
|
||||
|
||||
test("a free flat roof keeps three corners; a plain rectangle has no points to take away", () => {
|
||||
const flat = { ...sectionFromRectangle(house(), [0, 0], [6, 4]), shape: "flat" as const };
|
||||
assert.equal(removeRoofCorner(flat, 0), false);
|
||||
flat.points = [[0, 0], [4, 0], [4, 3]];
|
||||
assert.equal(removeRoofCorner(flat, 1), false);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
// Roof sections as the editor makes them: a section drawn on the plan, a copy, and the sections' list helpers.
|
||||
|
||||
import { sectionCorners } from "../../../roof/frame.ts";
|
||||
import { uid, type Building, type RoofSection, type Vec2 } from "../../../model.ts";
|
||||
import { polygonBox, wallTopUnder } from "../../../roof-sections.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** The height of a canopy's eaves above the ground floor. */
|
||||
const CANOPY_EAVE = 2.4;
|
||||
|
||||
/**
|
||||
* A section drawn as a rectangle on the plan. Over rooms of a lower floor (a garage) its eaves sit on those walls, over no room
|
||||
* (a terrace, a carport) it becomes a canopy: a flat pent roof on posts 2.4 m above the ground floor.
|
||||
*/
|
||||
export function sectionFromRectangle(doc: Building, lo: Vec2, hi: Vec2): RoofSection {
|
||||
const wallTop = wallTopUnder(doc, lo[0], lo[1], hi[0], hi[1]);
|
||||
const canopy = wallTop === null;
|
||||
const ground = Math.min(...doc.floors.map((f) => f.elevation));
|
||||
const eave = thousandths(wallTop ?? ground + CANOPY_EAVE);
|
||||
const pitch = canopy ? 6 : doc.settings.roof.pitch || 35;
|
||||
return {
|
||||
id: uid("roof"),
|
||||
x0: thousandths(lo[0]),
|
||||
z0: thousandths(lo[1]),
|
||||
x1: thousandths(hi[0]),
|
||||
z1: thousandths(hi[1]),
|
||||
shape: canopy ? "pent" : "gable",
|
||||
axis: hi[0] - lo[0] >= hi[1] - lo[1] ? "x" : "z",
|
||||
eave_a: eave,
|
||||
eave_b: eave,
|
||||
pitch_a: pitch,
|
||||
pitch_b: pitch,
|
||||
base: eave,
|
||||
overhang: canopy ? 0.15 : null,
|
||||
...(canopy ? { open: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A copy of a section, a metre to the south east, so that it can be told from the original. */
|
||||
export function copyOfSection(section: RoofSection): RoofSection {
|
||||
const move = (v: number) => thousandths(v + 1);
|
||||
return { ...structuredClone(section), id: uid("roof"), x0: move(section.x0), x1: move(section.x1), z0: move(section.z0), z1: move(section.z1) };
|
||||
}
|
||||
|
||||
/** A section, or the list's 1-based number of it (0 when it is not in the list). */
|
||||
export const sectionNumber = (sections: readonly RoofSection[], id: string): number => sections.findIndex((s) => s.id === id) + 1;
|
||||
|
||||
/** The outline of a flat roof section: its own free shape, or the corners of its rectangle. */
|
||||
export function roofOutline(s: RoofSection): Vec2[] {
|
||||
if (s.points && s.points.length >= 3) return s.points.map(([x, z]): Vec2 => [x, z]);
|
||||
if (s.rotation) return sectionCorners(s);
|
||||
return [[s.x0, s.z0], [s.x1, s.z0], [s.x1, s.z1], [s.x0, s.z1]];
|
||||
}
|
||||
|
||||
/** A new corner in the middle of an edge of a flat roof: a rectangle becomes a free shape, and the section's box follows its points. */
|
||||
export function insertRoofCorner(s: RoofSection, edge: number, at: Vec2): void {
|
||||
const points = roofOutline(s);
|
||||
points.splice(edge + 1, 0, [thousandths(at[0]), thousandths(at[1])]);
|
||||
s.points = points;
|
||||
Object.assign(s, polygonBox(points));
|
||||
}
|
||||
|
||||
/** Takes a corner of a free flat roof away; a free shape keeps at least three. */
|
||||
export function removeRoofCorner(s: RoofSection, index: number): boolean {
|
||||
if (!s.points || s.points.length <= 3 || index < 0 || index >= s.points.length) return false;
|
||||
s.points.splice(index, 1);
|
||||
Object.assign(s, polygonBox(s.points));
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import type { Placement } from "../../../model.ts";
|
||||
import { setWallSlope } from "./edges.ts";
|
||||
import { insertCorner, areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom } from "./rooms.ts";
|
||||
|
||||
const lamp = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra });
|
||||
|
||||
test("a new room has a wooden floor and rounded corners; a copy is shifted and independent", () => {
|
||||
const room = newRoom([[0, 0.12345], [2, 0], [2, 2]], "Study");
|
||||
assert.equal(room.name, "Study");
|
||||
assert.equal(room.floor_material, "wood");
|
||||
assert.equal(room.points[0][1], 0.123);
|
||||
const copy = copyOfRoom(room);
|
||||
assert.notEqual(copy.id, room.id);
|
||||
assert.deepEqual(copy.points[1], [2.5, 0.5]);
|
||||
copy.points.push([9, 9]);
|
||||
assert.equal(room.points.length, 3);
|
||||
});
|
||||
|
||||
test("removing a room takes its devices and its openings, but not those of free walls", () => {
|
||||
const floor = floorWith([box("a", 0, 0, 4, 4), box("b", 4, 0, 8, 4)], {
|
||||
placements: [lamp("light.in_a", 1, 1), lamp("light.in_b", 6, 1)],
|
||||
openings: [opening("o1", "a", "door"), opening("o2", "b", "window"), { ...opening("o3", "a", "window"), wall: "w1" }],
|
||||
});
|
||||
removeRoom(floor, "a");
|
||||
assert.deepEqual(floor.rooms.map((r) => r.id), ["b"]);
|
||||
assert.deepEqual(floor.placements.map((p) => p.entity_id), ["light.in_b"]);
|
||||
assert.deepEqual(floor.openings.map((o) => o.id), ["o2", "o3"]);
|
||||
});
|
||||
|
||||
test("removing a corner drops the openings on its two edges and renumbers the edges after it", () => {
|
||||
const room = { ...box("r", 0, 0, 4, 4), points: [[0, 0], [4, 0], [4, 4], [2, 5], [0, 4]] as [number, number][], wall_heights: [1, 2, 3, 4, 5] };
|
||||
const floor = floorWith([room], { openings: [{ ...opening("on0", "r", "door"), edge: 0 }, { ...opening("on1", "r", "door"), edge: 1 }, { ...opening("on2", "r", "door"), edge: 2 }, { ...opening("on4", "r", "door"), edge: 4 }] });
|
||||
assert.equal(removeCorner(floor, "r", 2), true);
|
||||
assert.equal(floor.rooms[0].points.length, 4);
|
||||
assert.deepEqual(floor.rooms[0].wall_heights, [1, 2, 4, 5]);
|
||||
// edges 1 (before the corner) and 2 (at it) are gone, edge 4 became 3
|
||||
assert.deepEqual(floor.openings.map((o) => [o.id, o.edge]), [["on0", 0], ["on4", 3]]);
|
||||
});
|
||||
|
||||
test("a triangle keeps its three corners", () => {
|
||||
const floor = floorWith([{ ...box("t", 0, 0, 1, 1), points: [[0, 0], [1, 0], [0, 1]] }]);
|
||||
assert.equal(removeCorner(floor, "t", 0), false);
|
||||
assert.equal(floor.rooms[0].points.length, 3);
|
||||
});
|
||||
|
||||
test("typing the left, top, width or depth of a room gives its new rectangle", () => {
|
||||
const room = box("r", 1, 2, 5, 4);
|
||||
assert.deepEqual(rectangleAfter(room, "x", 3), [[3, 2], [7, 2], [7, 4], [3, 4]]);
|
||||
assert.deepEqual(rectangleAfter(room, "z", 0), [[1, 0], [5, 0], [5, 2], [1, 2]]);
|
||||
assert.deepEqual(rectangleAfter(room, "w", 6), [[1, 2], [7, 2], [7, 4], [1, 4]]);
|
||||
assert.deepEqual(rectangleAfter(room, "d", 1), [[1, 2], [5, 2], [5, 3], [1, 3]]);
|
||||
assert.deepEqual(rectangleAfter(room, "w", 0.01), [[1, 2], [5, 2], [5, 4], [1, 4]], "too narrow: the size stays");
|
||||
assert.equal(rectangleAfter(room, "x", Number.NaN), null);
|
||||
});
|
||||
|
||||
test("moving one coordinate of one corner", () => {
|
||||
const room = box("r", 0, 0, 2, 2);
|
||||
assert.deepEqual(cornerMoved(room, 1, 0, 3.14159), [[0, 0], [3.142, 0], [2, 2], [0, 2]]);
|
||||
assert.deepEqual(cornerMoved(room, 2, 1, 5)![2], [2, 5]);
|
||||
assert.equal(cornerMoved(room, 9, 0, 1), null);
|
||||
assert.equal(cornerMoved(room, 0, 0, Number.NaN), null);
|
||||
});
|
||||
|
||||
test("choosing an area names a room that only had a placeholder name", () => {
|
||||
const areas = { kitchen: { name: "Kitchen" }, study: { name: "Study" } };
|
||||
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Room 3" }, "kitchen", areas), { area_id: "kitchen", name: "Kitchen" });
|
||||
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Raum 12" }, "kitchen", areas), { area_id: "kitchen", name: "Kitchen" });
|
||||
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Study" }, "kitchen", areas), { area_id: "kitchen", name: "Kitchen" }, "a name of another area is a placeholder too");
|
||||
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Lounge" }, "kitchen", areas), { area_id: "kitchen" });
|
||||
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Lounge" }, "", areas), { area_id: null });
|
||||
});
|
||||
|
||||
test("ceiling lights spread over the room in a grid, a short last row over the full width", () => {
|
||||
const room = box("r", 0, 0, 6, 4);
|
||||
const lights = [lamp("light.a", 1, 1), lamp("light.b", 1.1, 1), lamp("light.c", 1.2, 1), lamp("light.d", 1.3, 1), lamp("light.e", 1.4, 1)];
|
||||
const spots = evenCeilingLights(room, lights);
|
||||
assert.equal(spots.length, 5);
|
||||
assert.deepEqual(spots.map((s) => s.entityId), ["light.a", "light.b", "light.c", "light.d", "light.e"]);
|
||||
assert.ok(spots.every((s) => s.x > 0 && s.x < 6 && s.z > 0 && s.z < 4));
|
||||
assert.equal(new Set(spots.map((s) => `${s.x},${s.z}`)).size, 5);
|
||||
// wall lamps, other rooms and single lights are not touched
|
||||
assert.deepEqual(evenCeilingLights(room, [lamp("light.a", 1, 1)]), []);
|
||||
assert.deepEqual(evenCeilingLights(room, [lamp("light.a", 1, 1), lamp("light.b", 2, 2, { mount: "wall" })]), []);
|
||||
assert.deepEqual(evenCeilingLights(room, [lamp("light.a", 1, 1), lamp("light.b", 20, 20)]), []);
|
||||
});
|
||||
|
||||
test("a corner inserted on an edge splits it: heights are kept, openings stay on their half", () => {
|
||||
const floor = floorWith([{ ...box("r", 0, 0, 4, 4), wall_heights: [1, null, null, null] }], { openings: [{ ...opening("a", "r", "door"), edge: 0, offset: 1 }, { ...opening("b", "r", "door"), edge: 0, offset: 3 }, { ...opening("c", "r", "door"), edge: 1, offset: 1 }] });
|
||||
insertCorner(floor, "r", 0, [2, 0]);
|
||||
assert.deepEqual(floor.rooms[0].points[1], [2, 0]);
|
||||
assert.deepEqual(floor.rooms[0].wall_heights, [1, 1, null, null, null]);
|
||||
assert.deepEqual(floor.openings.map((o) => [o.id, o.edge, o.offset]), [["a", 0, 1], ["b", 1, 1], ["c", 2, 1]]);
|
||||
insertCorner(floor, "missing", 0, [0, 0]);
|
||||
});
|
||||
|
||||
test("a corner on a sloping wall splits the slope: both halves meet at the height the slope has there", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)]);
|
||||
const room = floor.rooms[0];
|
||||
setWallSlope(room, 1, 2, 4);
|
||||
// edge 1 runs from (4,0) to (4,4): the new corner halfway stands at 3
|
||||
insertCorner(floor, "r", 1, [4, 2]);
|
||||
assert.deepEqual(room.wall_heights?.slice(1, 3), [2, 3]);
|
||||
assert.deepEqual(room.wall_slopes?.slice(1, 3), [3, 4]);
|
||||
// removing a corner drops the entry of the edge that began there, like the heights
|
||||
assert.equal(removeCorner(floor, "r", 2), true);
|
||||
assert.equal(room.points.length, 4);
|
||||
assert.equal(room.wall_slopes?.length, room.wall_heights?.length);
|
||||
});
|
||||
|
||||
test("a corner on an edge without slope leaves the slopes of the other walls in place", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)]);
|
||||
const room = floor.rooms[0];
|
||||
setWallSlope(room, 2, 1, 3);
|
||||
insertCorner(floor, "r", 0, [2, 0]);
|
||||
assert.deepEqual([room.wall_heights?.[3], room.wall_slopes?.[3]], [1, 3], "the sloping wall is now edge 3");
|
||||
});
|
||||
|
||||
test("bending a shared edge bends both rooms the same way and keeps the door on it", async () => {
|
||||
const { arcRoomEdge } = await import("./rooms.ts");
|
||||
const { box, floorWith, opening } = await import("../../../entities/fixtures.ts");
|
||||
const left = box("a", 0, 0, 4, 4);
|
||||
const right = box("b", 4, 0, 8, 4);
|
||||
const floor = floorWith([left, right], { openings: [opening("d", "a", "door", { edge: 1, offset: 2, width: 0.9 })] });
|
||||
const edge = left.points.findIndex((p, i) => p[0] === 4 && left.points[(i + 1) % 4][0] === 4);
|
||||
const before = left.points.length;
|
||||
assert.equal(arcRoomEdge(floor, "a", edge, 0.8), true);
|
||||
assert.ok(left.points.length > before);
|
||||
// a bulges into b: the corners lie right of x = 4, and b has the very same corners
|
||||
const added = left.points.filter((p) => p[0] > 4.001);
|
||||
assert.ok(added.length >= 2);
|
||||
for (const p of added) assert.ok(right.points.some((q) => q[0] === p[0] && q[1] === p[1]));
|
||||
const door = floor.openings[0];
|
||||
assert.ok(door.edge >= edge && door.edge < edge + added.length + 1);
|
||||
assert.equal((left.wall_heights ?? []).length <= left.points.length, true);
|
||||
});
|
||||
|
||||
test("a free wall bends into a chain of walls that keeps its openings", async () => {
|
||||
const { arcFreeWall } = await import("./rooms.ts");
|
||||
const { floorWith, opening } = await import("../../../entities/fixtures.ts");
|
||||
const floor = floorWith([], { walls: [{ id: "w", a: [0, 0], b: [5, 0], thickness: 0.2 }], openings: [opening("o", "r", "window", { wall: "w", offset: 4, width: 1 })] });
|
||||
const ids = arcFreeWall(floor, "w", 1);
|
||||
assert.ok(ids.length >= 2 && ids[0] === "w");
|
||||
assert.equal(floor.walls!.length, ids.length);
|
||||
assert.ok(floor.walls!.every((w) => w.thickness === 0.2));
|
||||
assert.ok(ids.includes(floor.openings[0].wall!));
|
||||
});
|
||||
|
||||
test("both rooms of a bent shared edge keep their openings whole on a piece of the arc, and its wall height and thickness", async () => {
|
||||
const { arcRoomEdge } = await import("./rooms.ts");
|
||||
const { box, floorWith, opening } = await import("../../../entities/fixtures.ts");
|
||||
const left = { ...box("a", 0, 0, 4, 5), wall_heights: [null, 2.2, null, null], wall_thickness: [null, 0.3, null, null] };
|
||||
const right = box("b", 4, 0, 8, 5);
|
||||
// edge 1 of a runs (4,0)→(4,5); b has the same edge the other way round as its edge 3
|
||||
const floor = floorWith([left, right], {
|
||||
openings: [opening("door", "a", "door", { edge: 1, offset: 1.2, width: 0.9 }), opening("window", "b", "window", { edge: 3, offset: 1.5, width: 1.2 })],
|
||||
});
|
||||
assert.equal(arcRoomEdge(floor, "a", 1, -0.6), true, "bulging into room a");
|
||||
// a box has four edges; bending one into n pieces leaves n + 3
|
||||
const pieces = (room: { points: unknown[] }) => room.points.length - 3;
|
||||
const len = (pts: [number, number][], i: number) => Math.hypot(pts[(i + 1) % pts.length][0] - pts[i][0], pts[(i + 1) % pts.length][1] - pts[i][1]);
|
||||
// the arc's corners are shared: every corner of a that lies off the old edge is also a corner of b
|
||||
const bent = left.points.filter((p) => p[0] < 3.999 && p[1] > 0.001 && p[1] < 4.999);
|
||||
assert.ok(bent.length >= 2, "corners on the arc");
|
||||
for (const p of bent) assert.ok(right.points.some((q) => q[0] === p[0] && q[1] === p[1]), `b has ${p}`);
|
||||
for (const [room, id, first] of [[left, "door", 1], [right, "window", 3]] as const) {
|
||||
const o = floor.openings.find((x) => x.id === id)!;
|
||||
const count = pieces(room);
|
||||
assert.ok(o.edge >= first && o.edge < first + count, `${id} on a piece of the arc (edge ${o.edge})`);
|
||||
const piece = len(room.points as [number, number][], o.edge);
|
||||
assert.ok(o.offset - o.width / 2 >= -1e-6 && o.offset + o.width / 2 <= piece + 1e-6, `${id} fits its piece (${o.offset} ± ${o.width / 2} on ${piece})`);
|
||||
}
|
||||
// the pieces of a's wall keep its height and thickness
|
||||
for (let e = 1; e < 1 + pieces(left); e++) {
|
||||
assert.equal(left.wall_heights![e], 2.2);
|
||||
assert.equal(left.wall_thickness![e], 0.3);
|
||||
}
|
||||
});
|
||||
|
||||
test("an arc too sharp for a wide opening on it leaves the wall straight", async () => {
|
||||
const { arcFreeWall, arcRoomEdge } = await import("./rooms.ts");
|
||||
const { box, floorWith, opening } = await import("../../../entities/fixtures.ts");
|
||||
// a 2 m window on a 3 m wall: a deep bulge would need pieces far shorter than the window
|
||||
const walls = floorWith([], { walls: [{ id: "w", a: [0, 0], b: [3, 0] }], openings: [opening("o", "r", "window", { wall: "w", offset: 1.5, width: 2 })] });
|
||||
assert.deepEqual(arcFreeWall(walls, "w", 1.2), []);
|
||||
assert.equal(walls.walls!.length, 1);
|
||||
const room = box("a", 0, 0, 3, 3);
|
||||
const rooms = floorWith([room], { openings: [opening("d", "a", "window", { edge: 0, offset: 1.5, width: 2 })] });
|
||||
assert.equal(arcRoomEdge(rooms, "a", 0, 1.2), false);
|
||||
assert.equal(room.points.length, 4);
|
||||
// a narrower window fits on a flat curve
|
||||
const flat = floorWith([], { walls: [{ id: "w", a: [0, 0], b: [3, 0] }], openings: [opening("o", "r", "window", { wall: "w", offset: 1.5, width: 1.2 })] });
|
||||
assert.deepEqual(arcFreeWall(structuredClone(flat), "w", 1.2), [], "but not on a deep one");
|
||||
assert.ok(arcFreeWall(flat, "w", 0.15).length >= 2);
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
// Rooms: making, copying and removing them, moving a corner or the whole rectangle, and the ceiling lights of a room.
|
||||
|
||||
import { bounds, pointInPolygon, uid, type Floor, type Opening, type Placement, type Room, type Vec2 } from "../../../model.ts";
|
||||
import { arcPoints, pieceAt, polylineLength } from "../../../geometry/arcs.ts";
|
||||
import { kindOf } from "../../../devices.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const rounded = (points: readonly Vec2[]): Vec2[] => points.map(([x, z]) => [thousandths(x), thousandths(z)]);
|
||||
|
||||
/** A new room on the given outline, with a wooden floor and no area. */
|
||||
export function newRoom(points: readonly Vec2[], name: string): Room {
|
||||
return { id: uid("room"), name, area_id: null, points: rounded(points), floor_material: "wood" };
|
||||
}
|
||||
|
||||
/** A copy of a room half a metre to the south east, so that it can be told from the original. */
|
||||
export function copyOfRoom(room: Room): Room {
|
||||
return { ...structuredClone(room), id: uid("room"), points: rounded(room.points.map(([x, z]) => [x + 0.5, z + 0.5])) };
|
||||
}
|
||||
|
||||
/** Takes a room off the floor with the devices standing in it and its door and window openings. Openings in free walls stay. */
|
||||
export function removeRoom(floor: Floor, roomId: string): void {
|
||||
const room = floor.rooms.find((r) => r.id === roomId);
|
||||
floor.rooms = floor.rooms.filter((r) => r.id !== roomId);
|
||||
floor.openings = floor.openings.filter((o) => o.room_id !== roomId || o.wall);
|
||||
if (room) floor.placements = floor.placements.filter((p) => !pointInPolygon([p.x, p.z], room.points));
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a corner out of a room. The two edges at the corner become one, so openings on them cannot keep their place and are removed,
|
||||
* and the edges after the corner move up one place. A room keeps at least three corners.
|
||||
*/
|
||||
export function removeCorner(floor: Floor, roomId: string, index: number): boolean {
|
||||
const room = floor.rooms.find((r) => r.id === roomId);
|
||||
if (!room || room.points.length <= 3) return false;
|
||||
const before = (index - 1 + room.points.length) % room.points.length;
|
||||
room.points.splice(index, 1);
|
||||
// per-edge lists lose the edge that started at the removed corner
|
||||
room.wall_heights?.splice(index, 1);
|
||||
room.wall_slopes?.splice(index, 1);
|
||||
room.wall_thickness?.splice(index, 1);
|
||||
const onRoom = (o: { room_id: string; wall?: string | null }) => o.room_id === roomId && !o.wall;
|
||||
floor.openings = floor.openings
|
||||
.filter((o) => !(onRoom(o) && (o.edge === index || o.edge === before)))
|
||||
.map((o) => (onRoom(o) && o.edge > index ? { ...o, edge: o.edge - 1 } : o));
|
||||
return true;
|
||||
}
|
||||
|
||||
export type RectField = "x" | "z" | "w" | "d";
|
||||
|
||||
/** The outline of a room as a rectangle after one of its box values (left, top, width, depth) was typed. Null when the value is no use. */
|
||||
export function rectangleAfter(room: Room, field: RectField, value: number): Vec2[] | null {
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const box = bounds(room.points);
|
||||
let { x0, z0, x1, z1 } = box;
|
||||
if (field === "x") [x0, x1] = [value, value + (x1 - x0)];
|
||||
else if (field === "z") [z0, z1] = [value, value + (z1 - z0)];
|
||||
else if (value > 0.05) {
|
||||
if (field === "w") x1 = x0 + value;
|
||||
else z1 = z0 + value;
|
||||
}
|
||||
return rounded([[x0, z0], [x1, z0], [x1, z1], [x0, z1]]);
|
||||
}
|
||||
|
||||
/** The outline of a room with one coordinate of one corner changed. */
|
||||
export function cornerMoved(room: Room, index: number, axis: 0 | 1, value: number): Vec2[] | null {
|
||||
if (!Number.isFinite(value) || index < 0 || index >= room.points.length) return null;
|
||||
return room.points.map((p, i): Vec2 => (i === index ? (axis === 0 ? [thousandths(value), p[1]] : [p[0], thousandths(value)]) : [p[0], p[1]]));
|
||||
}
|
||||
|
||||
const GENERIC_NAME = /^(Raum|Room) \d+$/;
|
||||
|
||||
/**
|
||||
* What choosing a Home Assistant area does to a room: it gets the area, and a name that was only a placeholder ("Room 3", or the
|
||||
* name of some area) takes the area's name.
|
||||
*/
|
||||
export function areaChoice(room: Room, areaId: string, areas: Readonly<Record<string, { name: string }>>): Partial<Room> {
|
||||
const area = areaId ? areas[areaId] : undefined;
|
||||
const placeholder = !room.name || GENERIC_NAME.test(room.name) || Object.values(areas).some((a) => a.name === room.name);
|
||||
return { area_id: areaId || null, ...(area && placeholder ? { name: area.name } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the ceiling lights of a room go to light it evenly: one per cell of a grid over the room's box. A last row that is not full
|
||||
* is spread over the whole width as well. Nothing for fewer than two lights.
|
||||
*/
|
||||
export function evenCeilingLights(room: Room, placements: readonly Placement[]): { entityId: string; x: number; z: number }[] {
|
||||
const lights = placements.filter((p) => kindOf(p.entity_id) === "light" && (p.mount ?? "ceiling") === "ceiling" && pointInPolygon([p.x, p.z], room.points));
|
||||
if (lights.length < 2) return [];
|
||||
const box = bounds(room.points);
|
||||
const [width, depth] = [box.x1 - box.x0, box.z1 - box.z0];
|
||||
const columns = Math.max(1, Math.round(Math.sqrt((lights.length * width) / Math.max(0.1, depth))));
|
||||
const rows = Math.ceil(lights.length / columns);
|
||||
return lights.map((light, i) => {
|
||||
const row = Math.floor(i / columns);
|
||||
const inRow = row === rows - 1 ? lights.length - columns * (rows - 1) : columns;
|
||||
const column = i - row * columns;
|
||||
return { entityId: light.entity_id, x: thousandths(box.x0 + (width / inRow) * (column + 0.5)), z: thousandths(box.z0 + (depth / rows) * (row + 0.5)) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a new corner on an edge. Both halves keep the edge's wall height and thickness, and openings on the edge stay where they were
|
||||
* on the half that now holds them.
|
||||
*/
|
||||
export function insertCorner(floor: Floor, roomId: string, edge: number, at: Vec2): void {
|
||||
const room = floor.rooms.find((r) => r.id === roomId);
|
||||
if (!room) return;
|
||||
const start = room.points[edge];
|
||||
const end = room.points[(edge + 1) % room.points.length];
|
||||
room.points.splice(edge + 1, 0, at);
|
||||
const [from, to] = [room.wall_heights?.[edge], room.wall_slopes?.[edge]];
|
||||
if (typeof from === "number" && typeof to === "number" && room.wall_slopes) {
|
||||
// a sloping wall stays one slope: the new corner stands at the height the slope has there
|
||||
const whole = Math.hypot(end[0] - start[0], end[1] - start[1]);
|
||||
const middle = thousandths(from + ((to - from) * Math.min(1, Math.hypot(at[0] - start[0], at[1] - start[1]) / (whole || 1))));
|
||||
room.wall_slopes.splice(edge, 1, middle, to);
|
||||
room.wall_heights!.splice(edge + 1, 0, middle);
|
||||
} else {
|
||||
room.wall_heights?.splice(edge + 1, 0, room.wall_heights[edge] ?? null);
|
||||
room.wall_slopes?.splice(edge + 1, 0, null);
|
||||
}
|
||||
room.wall_thickness?.splice(edge + 1, 0, room.wall_thickness[edge] ?? null);
|
||||
const firstHalf = Math.hypot(at[0] - start[0], at[1] - start[1]);
|
||||
for (const o of floor.openings) {
|
||||
if (o.room_id !== roomId || o.wall) continue;
|
||||
if (o.edge > edge) o.edge += 1;
|
||||
else if (o.edge === edge && o.offset > firstHalf) {
|
||||
o.edge = edge + 1;
|
||||
o.offset = thousandths(o.offset - firstHalf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The most an arc may turn from one piece to the next (degrees): coarser than that it reads as a kink, not a curve. */
|
||||
const MAX_PIECE_TURN = 22.5;
|
||||
|
||||
/**
|
||||
* The pieces an arc may have so that every opening on it still fits on one piece, or 0 when the widest opening would need
|
||||
* pieces so long that the arc turns into a kink.
|
||||
*/
|
||||
function piecesFor(chordLength: number, sagitta: number, widest: number): number {
|
||||
const s = Math.min(Math.abs(sagitta), chordLength * 2);
|
||||
const arcLength = chordLength * (1 + (8 / 3) * (s / Math.max(1e-6, chordLength)) ** 2);
|
||||
const turn = (4 * Math.atan((2 * s) / Math.max(1e-6, chordLength)) * 180) / Math.PI;
|
||||
const fewest = Math.max(2, Math.ceil(turn / MAX_PIECE_TURN));
|
||||
if (widest <= 0) return 24;
|
||||
const most = Math.floor(arcLength / (widest + 0.1));
|
||||
return most >= fewest ? most : 0;
|
||||
}
|
||||
|
||||
/** Where openings land on a bent edge: at the same share of its length, kept whole on their piece. */
|
||||
function rehost(openings: Opening[], fractions: number[], points: Vec2[], firstEdge: number): void {
|
||||
const total = polylineLength(points);
|
||||
openings.forEach((o, k) => {
|
||||
const { piece, offset } = pieceAt(points, fractions[k] * total);
|
||||
const length = Math.hypot(points[piece + 1][0] - points[piece][0], points[piece + 1][1] - points[piece][1]);
|
||||
o.edge = firstEdge + piece;
|
||||
o.offset = thousandths(length > o.width ? Math.min(length - o.width / 2, Math.max(o.width / 2, offset)) : length / 2);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Bends a room's edge into an arc that bulges by `sagitta` metres away from the room (negative: into it). A room sharing the
|
||||
* edge bends along. The arc is stored as short straight pieces; the pieces keep the wall's height and thickness, and the doors
|
||||
* and windows on it move to the piece at the same share of the length.
|
||||
*/
|
||||
export function arcRoomEdge(floor: Floor, roomId: string, edge: number, sagitta: number): boolean {
|
||||
const room = floor.rooms.find((r) => r.id === roomId);
|
||||
if (!room || edge < 0 || edge >= room.points.length || Math.abs(sagitta) < 0.01) return false;
|
||||
const a = room.points[edge];
|
||||
const b = room.points[(edge + 1) % room.points.length];
|
||||
const chord = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
if (chord < 0.2) return false;
|
||||
// which side of a→b is outside this room
|
||||
const [ux, uz] = [(b[0] - a[0]) / chord, (b[1] - a[1]) / chord];
|
||||
const probe: Vec2 = [(a[0] + b[0]) / 2 + uz * 0.02, (a[1] + b[1]) / 2 - ux * 0.02];
|
||||
const leftIsInside = pointInPolygon(probe, room.points);
|
||||
const bulgeLeft = leftIsInside ? -sagitta : sagitta;
|
||||
const onEdge = (r: Room, e: number) => floor.openings.filter((o) => o.room_id === r.id && !o.wall && o.edge === e);
|
||||
// the rooms bending along: this one, and every room with the same edge (usually the other way round)
|
||||
const sharing = floor.rooms.flatMap((r) =>
|
||||
r.points
|
||||
.map((p, i): [Room, number, boolean] | null => {
|
||||
const q = r.points[(i + 1) % r.points.length];
|
||||
const same = (m: Vec2, n: Vec2) => Math.abs(m[0] - n[0]) < 1e-3 && Math.abs(m[1] - n[1]) < 1e-3;
|
||||
if (same(p, a) && same(q, b)) return [r, i, false];
|
||||
if (same(p, b) && same(q, a)) return [r, i, true];
|
||||
return null;
|
||||
})
|
||||
.filter((x): x is [Room, number, boolean] => !!x),
|
||||
);
|
||||
const widest = Math.max(0, ...sharing.flatMap(([r, e]) => onEdge(r, e).map((o) => o.width)));
|
||||
const pieces = piecesFor(chord, sagitta, widest);
|
||||
if (!pieces) return false;
|
||||
const inner = arcPoints(a, b, bulgeLeft, pieces).map(([x, z]): Vec2 => [thousandths(x), thousandths(z)]);
|
||||
if (!inner.length) return false;
|
||||
for (const [r, e, reversed] of sharing) {
|
||||
const corners = reversed ? [...inner].reverse() : inner;
|
||||
const moving = onEdge(r, e);
|
||||
const start = r.points[e];
|
||||
const fractions = moving.map((o) => Math.min(1, Math.max(0, o.offset / chord)));
|
||||
// park the openings while the corners go in, then put them on their piece
|
||||
for (const o of moving) o.edge = -1;
|
||||
corners.forEach((p, k) => insertCorner(floor, r.id, e + k, p));
|
||||
r.wall_splits?.splice(e + 1, 0, ...corners.map(() => null));
|
||||
if (r.wall_splits?.[e]) r.wall_splits[e] = null;
|
||||
rehost(moving, fractions, [start, ...corners, r.points[(e + corners.length + 1) % r.points.length]], e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bends a free wall into an arc: it becomes a chain of free walls with the same thickness and height. Returns the ids of the
|
||||
* new walls (the first one keeps the old id, so openings and selection stay valid).
|
||||
*/
|
||||
export function arcFreeWall(floor: Floor, wallId: string, sagitta: number): string[] {
|
||||
const walls = floor.walls ?? [];
|
||||
const index = walls.findIndex((w) => w.id === wallId);
|
||||
if (index < 0 || Math.abs(sagitta) < 0.01) return [];
|
||||
const wall = walls[index];
|
||||
const chord = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
|
||||
const moving = floor.openings.filter((o) => o.wall === wallId);
|
||||
const widest = Math.max(0, ...moving.map((o) => o.width));
|
||||
const pieces = piecesFor(chord, sagitta, widest);
|
||||
if (!pieces) return [];
|
||||
const inner = arcPoints(wall.a, wall.b, sagitta, pieces).map(([x, z]): Vec2 => [thousandths(x), thousandths(z)]);
|
||||
if (!inner.length) return [];
|
||||
const points = [wall.a, ...inner, wall.b];
|
||||
const chain = points.slice(1).map((p, i) => ({ ...wall, id: i === 0 ? wall.id : uid("wall"), a: points[i], b: p }));
|
||||
walls.splice(index, 1, ...chain);
|
||||
floor.walls = walls;
|
||||
const total = polylineLength(points);
|
||||
for (const o of moving) {
|
||||
const { piece, offset } = pieceAt(points, (o.offset / chord) * total);
|
||||
const length = Math.hypot(points[piece + 1][0] - points[piece][0], points[piece + 1][1] - points[piece][1]);
|
||||
o.wall = chain[piece].id;
|
||||
o.offset = thousandths(length > o.width ? Math.min(length - o.width / 2, Math.max(o.width / 2, offset)) : length / 2);
|
||||
}
|
||||
return chain.map((w) => w.id);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Limits and conversions for the house settings.
|
||||
|
||||
export const clamp = (value: number, low: number, high: number): number => Math.min(high, Math.max(low, value));
|
||||
|
||||
/** Compass degrees as a whole number in 0 to 359. */
|
||||
export const wrapDegrees = (value: number): number => ((Math.round(value) % 360) + 360) % 360;
|
||||
|
||||
/** North turned by `by` degrees (180 swaps north and south), kept within 0 to 359. */
|
||||
export const turnedNorth = (north: number, by: number): number => wrapDegrees(north + by);
|
||||
|
||||
/** The weather effects with one switched on or off; no effect appears twice. */
|
||||
export function withEffect<T>(effects: readonly T[], effect: T, on: boolean): T[] {
|
||||
return on ? [...new Set([...effects, effect])] : effects.filter((e) => e !== effect);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box } from "../../../entities/fixtures.ts";
|
||||
import { snapToPlan } from "./snapping.ts";
|
||||
|
||||
const options = (extra = {}) => ({ rooms: [box("a", 0, 0, 4, 3)], grid: 0.1, reach: 0.2, ...extra });
|
||||
|
||||
test("a point near a corner of a room lands on it and shows the guide", () => {
|
||||
const snapped = snapToPlan([4.05, 0.08], options());
|
||||
assert.deepEqual(snapped.point, [4, 0]);
|
||||
assert.deepEqual(snapped.guides, { point: [4, 0] });
|
||||
});
|
||||
|
||||
test("a point near a wall lands on it, so walls can meet in a T", () => {
|
||||
const snapped = snapToPlan([2.04, 3.1], options());
|
||||
assert.deepEqual(snapped.point, [2, 3]);
|
||||
assert.deepEqual(snapped.guides.point, [2, 3]);
|
||||
});
|
||||
|
||||
test("far from everything the point lands on the grid", () => {
|
||||
const snapped = snapToPlan([7.04, 8.97], options());
|
||||
assert.deepEqual(snapped.point, [7, 9]);
|
||||
assert.deepEqual(snapped.guides, {});
|
||||
});
|
||||
|
||||
test("a point is lined up with the x or z of a corner along that axis only", () => {
|
||||
const snapped = snapToPlan([4.12, 8.07], options({ rooms: [box("a", 0, 0, 4, 3)] }));
|
||||
assert.equal(snapped.point[0], 4);
|
||||
assert.equal(snapped.point[1], 8.1);
|
||||
assert.deepEqual(snapped.guides, { x: 4 });
|
||||
});
|
||||
|
||||
test("the room being moved is not something to snap to, and free placement is up to the caller", () => {
|
||||
const moving = snapToPlan([4.05, 0.08], options({ skip: { roomId: "a" } }));
|
||||
assert.deepEqual(moving.point, [4, 0.1]);
|
||||
const oneCorner = snapToPlan([4.05, 0.08], options({ skip: { roomId: "a", index: 1 } }));
|
||||
assert.deepEqual(oneCorner.guides.point ?? null, null, "the corner skipped; the wall next to it is still near");
|
||||
});
|
||||
|
||||
test("walls along an axis are held to the grid when snapped to", () => {
|
||||
const snapped = snapToPlan([2.37, 3.12], options({ grid: 0.5, reach: 0.3 }));
|
||||
assert.deepEqual(snapped.point, [2.5, 3]);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
// Where a point drawn in the plan lands: on a corner of another room, on another room's wall (so walls can meet in a T), or on the
|
||||
// grid, lined up with other corners along each axis.
|
||||
|
||||
import type { Room, Vec2 } from "../../../model.ts";
|
||||
import type { Guides } from "../canvas/draft.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
export interface SnapOptions {
|
||||
rooms: readonly Room[];
|
||||
/** The grid step in metres. */
|
||||
grid: number;
|
||||
/** How close a point must be to something to snap to it, in metres. */
|
||||
reach: number;
|
||||
/** A room (or one corner of it) that is being moved and so is not something to snap to. */
|
||||
skip?: { roomId: string; index?: number };
|
||||
}
|
||||
|
||||
export interface Snapped {
|
||||
point: Vec2;
|
||||
guides: Guides;
|
||||
}
|
||||
|
||||
const distance = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]);
|
||||
|
||||
/** The nearest corner of the other rooms within reach, if any. */
|
||||
function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 | null {
|
||||
let best: Vec2 | null = null;
|
||||
let bestDistance = reach;
|
||||
for (const corner of corners) {
|
||||
const d = distance(corner, p);
|
||||
if (d < bestDistance) [best, bestDistance] = [corner, d];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The point on a wall of another room that is nearest to p, within reach. Walls along an axis are held to the grid. */
|
||||
function nearestOnWall(rooms: readonly Room[], p: Vec2, o: SnapOptions): Vec2 | null {
|
||||
let best: Vec2 | null = null;
|
||||
let bestDistance = o.reach;
|
||||
for (const room of rooms) {
|
||||
if (o.skip && room.id === o.skip.roomId) continue;
|
||||
room.points.forEach((a, i) => {
|
||||
const b = room.points[(i + 1) % room.points.length];
|
||||
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
|
||||
const squared = dx * dx + dz * dz;
|
||||
if (squared < 1e-9) return;
|
||||
const along = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / squared;
|
||||
if (along <= 0 || along >= 1) return;
|
||||
const foot: Vec2 = [a[0] + along * dx, a[1] + along * dz];
|
||||
const d = distance(foot, p);
|
||||
const within = (v: number, lo: number, hi: number) => Math.min(Math.max(v, Math.min(lo, hi)), Math.max(lo, hi));
|
||||
if (Math.abs(dz) < 1e-9) foot[0] = within(Math.round(foot[0] / o.grid) * o.grid, a[0], b[0]);
|
||||
if (Math.abs(dx) < 1e-9) foot[1] = within(Math.round(foot[1] / o.grid) * o.grid, a[1], b[1]);
|
||||
if (d < bestDistance) [best, bestDistance] = [foot, d];
|
||||
});
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The grid point nearest to p, pulled onto the x or z of any corner that is within reach along that axis. */
|
||||
function gridOrAligned(corners: readonly Vec2[], p: Vec2, o: SnapOptions): Snapped {
|
||||
const point: Vec2 = [thousandths(Math.round(p[0] / o.grid) * o.grid), thousandths(Math.round(p[1] / o.grid) * o.grid)];
|
||||
const guides: Guides = {};
|
||||
let [nearX, nearZ] = [o.reach, o.reach];
|
||||
for (const corner of corners) {
|
||||
if (Math.abs(corner[0] - p[0]) < nearX) {
|
||||
nearX = Math.abs(corner[0] - p[0]);
|
||||
point[0] = corner[0];
|
||||
guides.x = corner[0];
|
||||
}
|
||||
if (Math.abs(corner[1] - p[1]) < nearZ) {
|
||||
nearZ = Math.abs(corner[1] - p[1]);
|
||||
point[1] = corner[1];
|
||||
guides.z = corner[1];
|
||||
}
|
||||
}
|
||||
return { point, guides };
|
||||
}
|
||||
|
||||
export function snapToPlan(p: Vec2, o: SnapOptions): Snapped {
|
||||
const corners = o.rooms.flatMap((room) => room.points.filter((_, i) => !(o.skip && room.id === o.skip.roomId && (o.skip.index === undefined || o.skip.index === i))));
|
||||
const corner = nearestCorner(corners, p, o.reach);
|
||||
if (corner) return { point: [corner[0], corner[1]], guides: { point: corner } };
|
||||
const wall = nearestOnWall(o.rooms, p, o);
|
||||
if (wall) return { point: [thousandths(wall[0]), thousandths(wall[1])], guides: { point: wall } };
|
||||
return gridOrAligned(corners, p, o);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Solar fields and their strings: the small calculations behind the solar form.
|
||||
|
||||
import type { Building, RoofSettings, SolarField, SolarString } from "../../../model.ts";
|
||||
import { GROUND, moveField, proposeGroundField, roofFaces, wallFaces } from "../../../solar.ts";
|
||||
|
||||
const MAX_ROWS = 40;
|
||||
const MAX_PER_ROW = 60;
|
||||
|
||||
/** Strings that no field uses any more are dropped. */
|
||||
export function pruneStrings(roof: RoofSettings): void {
|
||||
const used = new Set((roof.solar ?? []).map((f) => f.string).filter(Boolean));
|
||||
roof.strings = (roof.strings ?? []).filter((s) => used.has(s.id));
|
||||
}
|
||||
|
||||
/** Puts a field into the string `value`, into a new string for "new", or out of its string for null. Empty strings disappear. */
|
||||
export function assignString(roof: RoofSettings, fieldId: string, value: string | null, create: { id: string; name(n: number): string }): void {
|
||||
const field = roof.solar?.find((f) => f.id === fieldId);
|
||||
if (!field) return;
|
||||
if (value === "new") {
|
||||
const strings = roof.strings ?? [];
|
||||
const made: SolarString = { id: create.id, name: create.name(strings.length + 1), entity: field.entity ?? null, inverter: null };
|
||||
roof.strings = [...strings, made];
|
||||
field.string = made.id;
|
||||
} else {
|
||||
field.string = value;
|
||||
}
|
||||
pruneStrings(roof);
|
||||
}
|
||||
|
||||
/** The modules left out of a field after one cell was clicked: switched off if it was on, on if it was off. */
|
||||
export function toggledSkip(skip: readonly string[] | null | undefined, cell: string): string[] | null {
|
||||
const left = new Set(skip ?? []);
|
||||
if (!left.delete(cell)) left.add(cell);
|
||||
return left.size > 0 ? [...left].sort() : null;
|
||||
}
|
||||
|
||||
/** What typing into the "modules per row" box means: one number for every row, or a list with a number per row. Null for no usable number. */
|
||||
export function columnsPatch(text: string): Partial<SolarField> | null {
|
||||
const numbers = text
|
||||
.split(/[,;\s]+/)
|
||||
.map((part) => Number.parseInt(part, 10))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0);
|
||||
if (numbers.length === 0) return null;
|
||||
if (numbers.length === 1) return { cols: Math.max(1, Math.min(MAX_PER_ROW, numbers[0])), layout: null, skip: null };
|
||||
const layout = numbers.slice(0, MAX_ROWS).map((n) => Math.min(MAX_PER_ROW, n));
|
||||
return { layout, rows: Math.min(MAX_ROWS, numbers.length), cols: Math.max(1, ...numbers), skip: null };
|
||||
}
|
||||
|
||||
/** A new number of rows. Fields with rows of their own length keep those lengths, and new rows take the length of the last one. */
|
||||
export function rowsPatch(field: SolarField, wanted: number): Partial<SolarField> {
|
||||
const rows = Math.max(1, Math.min(MAX_ROWS, Math.round(wanted)));
|
||||
const layout = field.layout;
|
||||
if (!layout?.length) return { rows };
|
||||
return { rows, layout: Array.from({ length: rows }, (_, i) => layout[i] ?? layout[layout.length - 1]) };
|
||||
}
|
||||
|
||||
/** The text of the "modules per row" box. */
|
||||
export const columnsText = (field: SolarField): string => (field.layout?.length ? field.layout.join(", ") : String(field.cols));
|
||||
|
||||
/** What a field keeps when it moves to another face: its modules and its links, not its position. */
|
||||
export const KEPT_ON_MOVE = ["portrait", "look", "name", "string", "entity", "module_w", "module_h", "wp"] as const;
|
||||
|
||||
export function keptOnMove(field: SolarField): Partial<SolarField> {
|
||||
const kept: Record<string, unknown> = {};
|
||||
for (const key of KEPT_ON_MOVE) kept[key] = field[key];
|
||||
return kept as Partial<SolarField>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a field becomes when it is moved to the face with this key: the free-standing ground, a roof face or a house wall. It keeps
|
||||
* its modules and is laid out anew there; on a wall it is a single row. Null when no such face exists.
|
||||
*/
|
||||
export function fieldOnFace(doc: Building, field: SolarField, key: string): Partial<SolarField> | null {
|
||||
const kept = keptOnMove(field);
|
||||
if (key === GROUND) return { ...proposeGroundField(doc, field.id), ...kept, rows: field.rows, cols: field.cols };
|
||||
const roofFace = roofFaces(doc).find((f) => f.key === key);
|
||||
if (roofFace) return moveField(roofFace, { ...field, ...kept });
|
||||
const wallFace = wallFaces(doc).find((f) => f.key === key);
|
||||
return wallFace ? moveField(wallFace, { ...field, ...kept, rows: 1 }) : null;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box } from "../../../entities/fixtures.ts";
|
||||
import { spotCount, spotItems, suggestedSpots } from "./spots.ts";
|
||||
|
||||
test("about one spot per 1.2 metres, at least one, and the first light of the room is followed", () => {
|
||||
assert.deepEqual(suggestedSpots(box("r", 0, 0, 6, 3), ["light.a", "light.b"]), { type: "lamp_downlight", rows: 3, cols: 5, entity: "light.a" });
|
||||
assert.deepEqual(suggestedSpots(box("r", 0, 0, 0.5, 0.5), []), { type: "lamp_downlight", rows: 1, cols: 1, entity: null });
|
||||
});
|
||||
|
||||
test("the spots sit at the cell centres and all follow the chosen light", () => {
|
||||
const items = spotItems(box("r", 0, 0, 4, 2), { type: "lamp_spot", rows: 1, cols: 2, entity: "light.a" });
|
||||
assert.deepEqual(items.map((i) => [i.x, i.z]), [[1, 1], [3, 1]]);
|
||||
assert.ok(items.every((i) => i.type === "lamp_spot" && i.entity === "light.a"));
|
||||
assert.equal(new Set(items.map((i) => i.id)).size, 2);
|
||||
assert.equal(spotItems(box("r", 0, 0, 4, 2), { type: "lamp_spot", rows: 1, cols: 1, entity: null })[0].entity, "none");
|
||||
});
|
||||
|
||||
test("an L-shaped room leaves out the cells in its missing corner", () => {
|
||||
const l = { ...box("l", 0, 0, 4, 4), points: [[0, 0], [4, 0], [4, 2], [2, 2], [2, 4], [0, 4]] as [number, number][] };
|
||||
assert.equal(spotItems(l, { type: "lamp_spot", rows: 2, cols: 2, entity: null }).length, 3);
|
||||
});
|
||||
|
||||
test("counts stay within 1 to 12", () => {
|
||||
assert.deepEqual([spotCount(0), spotCount(3.4), spotCount(99)], [1, 3, 12]);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// A grid of ceiling spots in a room, planned in the side panel and placed in one go.
|
||||
|
||||
import { FURNITURE_SIZE, spotGrid, uid, bounds, type Furniture, type FurnitureType, type Room } from "../../../model.ts";
|
||||
import type { SpotDraft } from "../side-state.ts";
|
||||
|
||||
/** The spot types the form offers. */
|
||||
export const SPOT_TYPES = ["lamp_downlight", "lamp_spot", "lamp_panel", "lamp_ceiling"] as const satisfies readonly FurnitureType[];
|
||||
|
||||
/** Roughly one spot every 1.2 m in each direction, following the first light of the room's area. */
|
||||
export function suggestedSpots(room: Room, lightsOfRoom: readonly string[]): SpotDraft {
|
||||
const box = bounds(room.points);
|
||||
return {
|
||||
type: "lamp_downlight",
|
||||
rows: Math.max(1, Math.round((box.z1 - box.z0) / 1.2)),
|
||||
cols: Math.max(1, Math.round((box.x1 - box.x0) / 1.2)),
|
||||
entity: lightsOfRoom[0] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The spots as furniture. Every spot follows the same light, as spots on one dimmer do; "none" means not linked. */
|
||||
export function spotItems(room: Room, draft: SpotDraft): Furniture[] {
|
||||
const [w, d, h] = FURNITURE_SIZE[draft.type];
|
||||
return spotGrid(room, draft.rows, draft.cols).map(([x, z]) => ({ id: uid("furniture"), type: draft.type, x, z, rotation: 0, w, d, h, variant: null, entity: draft.entity ?? "none", power: null }));
|
||||
}
|
||||
|
||||
/** A count typed for rows or columns, kept within 1 to 12. */
|
||||
export const spotCount = (value: number): number => Math.max(1, Math.min(12, Math.round(value)));
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building } from "../../../model.ts";
|
||||
import { pivotOf, translate, turnQuarterClockwise } from "./transform.ts";
|
||||
|
||||
function house(): Building {
|
||||
const ground = floorWith([box("a", 0, 0, 4, 2)], {
|
||||
furniture: [{ id: "s", type: "sofa", x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null }],
|
||||
placements: [{ entity_id: "light.a", x: 2, z: 1, y: null }],
|
||||
walls: [{ id: "w", a: [0, 3], b: [4, 3], thickness: null }],
|
||||
outdoor: [{ id: "o", type: "lawn", points: [[5, 0], [6, 0], [6, 1]] }],
|
||||
background: { image_id: "i", x: 0, z: 0, width: 4, opacity: 1 },
|
||||
} as never);
|
||||
const upper = floorWith([box("b", 0, 0, 4, 2)], { id: "u", elevation: 3 } as never);
|
||||
return {
|
||||
version: 1,
|
||||
floors: [ground, upper],
|
||||
settings: { roof: { type: "custom", pitch: 35, overhang: 0, sections: [{ id: "r", x0: 0, z0: 0, x1: 4, z1: 2, points: [[0, 0], [4, 0], [4, 2]] }] } },
|
||||
energy: { meter: { floor_id: "g", x: 1, z: 1 } },
|
||||
presence: [],
|
||||
} as unknown as Building;
|
||||
}
|
||||
|
||||
test("moving a floor moves everything on it and leaves the other floors and the roof alone", () => {
|
||||
const doc = house();
|
||||
translate(doc, { floorId: "g", allFloors: false }, 1.5, -0.5);
|
||||
const ground = doc.floors[0];
|
||||
assert.deepEqual(ground.rooms[0].points[0], [1.5, -0.5]);
|
||||
assert.deepEqual([ground.furniture[0].x, ground.furniture[0].z], [2.5, 0.5]);
|
||||
assert.deepEqual([ground.placements[0].x, ground.placements[0].z], [3.5, 0.5]);
|
||||
assert.deepEqual(ground.walls![0].a, [1.5, 2.5]);
|
||||
assert.deepEqual(ground.outdoor[0].points[0], [6.5, -0.5]);
|
||||
assert.deepEqual([ground.background!.x, ground.background!.z], [1.5, -0.5]);
|
||||
assert.deepEqual(doc.floors[1].rooms[0].points[0], [0, 0]);
|
||||
assert.equal(doc.settings.roof.sections![0].x0, 0);
|
||||
});
|
||||
|
||||
test("moving all floors takes the roof sections and the meter along", () => {
|
||||
const doc = house();
|
||||
translate(doc, { floorId: "g", allFloors: true }, 1, 2);
|
||||
assert.deepEqual(doc.floors[1].rooms[0].points[0], [1, 2]);
|
||||
const section = doc.settings.roof.sections![0];
|
||||
assert.deepEqual([section.x0, section.x1, section.z0, section.z1], [1, 5, 2, 4]);
|
||||
assert.deepEqual(section.points![0], [1, 2]);
|
||||
assert.deepEqual([doc.energy.meter!.x, doc.energy.meter!.z], [2, 3]);
|
||||
});
|
||||
|
||||
test("the pivot is the middle of the rooms' box, of one floor or of all", () => {
|
||||
const doc = house();
|
||||
assert.deepEqual(pivotOf(doc, { floorId: "g", allFloors: false }), [2, 1]);
|
||||
assert.equal(pivotOf(doc, { floorId: "nope", allFloors: false }), null);
|
||||
doc.floors[1].rooms[0].points = [[10, 10], [12, 10], [12, 12], [10, 12]];
|
||||
assert.deepEqual(pivotOf(doc, { floorId: "g", allFloors: true }), [6, 6]);
|
||||
});
|
||||
|
||||
test("a quarter turn turns positions and what faces somewhere; four turns are the way it was", () => {
|
||||
const doc = house();
|
||||
const before = structuredClone(doc);
|
||||
assert.equal(turnQuarterClockwise(doc, { floorId: "g", allFloors: false }), true);
|
||||
const ground = doc.floors[0];
|
||||
// about (2, 1): the corner (0, 0) goes to (3, -1)
|
||||
assert.deepEqual(ground.rooms[0].points[0], [3, -1]);
|
||||
assert.equal(ground.furniture[0].rotation, 90);
|
||||
assert.equal(ground.placements[0].rotation, 90);
|
||||
assert.equal(ground.background!.rotation, 90);
|
||||
for (let i = 0; i < 3; i++) turnQuarterClockwise(doc, { floorId: "g", allFloors: false });
|
||||
assert.deepEqual(doc.floors[0].rooms, before.floors[0].rooms);
|
||||
assert.equal(doc.floors[0].furniture[0].rotation, 0);
|
||||
assert.deepEqual(doc.floors[0].furniture[0].x, 1);
|
||||
});
|
||||
|
||||
test("turning a floor without rooms does nothing", () => {
|
||||
const doc = house();
|
||||
doc.floors[0].rooms = [];
|
||||
assert.equal(turnQuarterClockwise(doc, { floorId: "g", allFloors: false }), false);
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
// Moving and turning a whole floor, or the whole house, as one piece: rooms, furniture, devices, outdoor areas, free walls and the
|
||||
// background picture. Roof sections and the meter belong to the house and follow when all floors move.
|
||||
|
||||
import type { Building, Floor, Vec2 } from "../../../model.ts";
|
||||
|
||||
type PointMap = (p: Vec2) => Vec2;
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const quarter = (degrees: number) => (degrees + 90) % 360;
|
||||
|
||||
/** Applies a map of plan points to everything on a floor. With `turns`, the things that face somewhere turn a quarter as well. */
|
||||
function mapFloor(floor: Floor, at: PointMap, turns: boolean): void {
|
||||
const place = <T extends { x: number; z: number }>(thing: T) => ([thing.x, thing.z] = at([thing.x, thing.z]));
|
||||
for (const room of floor.rooms) room.points = room.points.map(at);
|
||||
for (const item of floor.furniture) {
|
||||
place(item);
|
||||
if (turns) item.rotation = quarter(item.rotation);
|
||||
}
|
||||
for (const placed of floor.placements) {
|
||||
place(placed);
|
||||
if (turns) placed.rotation = quarter(placed.rotation ?? 0);
|
||||
}
|
||||
for (const area of floor.outdoor) area.points = area.points.map(at);
|
||||
for (const wall of floor.walls ?? []) [wall.a, wall.b] = [at(wall.a), at(wall.b)];
|
||||
if (floor.background) {
|
||||
place(floor.background);
|
||||
if (turns) floor.background.rotation = quarter(floor.background.rotation ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Roof sections (as the box around their moved corners) and the meter, which belong to the house and not to a floor. */
|
||||
function mapHouseExtras(doc: Building, at: PointMap): void {
|
||||
for (const section of doc.settings.roof.sections ?? []) {
|
||||
const corners = [at([section.x0, section.z0]), at([section.x1, section.z0]), at([section.x1, section.z1]), at([section.x0, section.z1])];
|
||||
const [xs, zs] = [corners.map((c) => c[0]), corners.map((c) => c[1])];
|
||||
[section.x0, section.x1, section.z0, section.z1] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)];
|
||||
if (section.points) section.points = section.points.map(at);
|
||||
}
|
||||
const meter = doc.energy.meter;
|
||||
if (meter) [meter.x, meter.z] = at([meter.x, meter.z]);
|
||||
}
|
||||
|
||||
/** What a move or turn covers: one floor, or every floor with the roof and meter. */
|
||||
export interface Scope {
|
||||
floorId: string | null;
|
||||
allFloors: boolean;
|
||||
}
|
||||
|
||||
function apply(doc: Building, scope: Scope, at: PointMap, turns: boolean): void {
|
||||
if (scope.allFloors) {
|
||||
for (const floor of doc.floors) mapFloor(floor, at, turns);
|
||||
mapHouseExtras(doc, at);
|
||||
} else {
|
||||
const floor = doc.floors.find((f) => f.id === scope.floorId);
|
||||
if (floor) mapFloor(floor, at, turns);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves everything in the scope by (dx, dz) metres. */
|
||||
export function translate(doc: Building, scope: Scope, dx: number, dz: number): void {
|
||||
apply(doc, scope, ([x, z]) => [thousandths(x + dx), thousandths(z + dz)], false);
|
||||
}
|
||||
|
||||
/** The middle of the box around the rooms of the scope, or null when there are none. */
|
||||
export function pivotOf(doc: Building, scope: Scope): Vec2 | null {
|
||||
const floors = scope.allFloors ? doc.floors : doc.floors.filter((f) => f.id === scope.floorId);
|
||||
const points = floors.flatMap((f) => f.rooms.flatMap((r) => r.points));
|
||||
if (points.length === 0) return null;
|
||||
const [xs, zs] = [points.map((p) => p[0]), points.map((p) => p[1])];
|
||||
return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2];
|
||||
}
|
||||
|
||||
/** Turns everything in the scope a quarter clockwise about the middle of its rooms, for a floor that was drawn the wrong way round. */
|
||||
export function turnQuarterClockwise(doc: Building, scope: Scope): boolean {
|
||||
const pivot = pivotOf(doc, scope);
|
||||
if (!pivot) return false;
|
||||
const [cx, cz] = pivot;
|
||||
apply(doc, scope, ([x, z]) => [thousandths(cx - (z - cz)), thousandths(cz + (x - cx))], true);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { newFloor, type Furniture, type Opening, type Room } from "../../../model.ts";
|
||||
import { furnitureAt, onWall, openingAt, wallElevation, wallFrame } from "./wall-view.ts";
|
||||
|
||||
const room = (id: string, points: [number, number][]): Room => ({ id, name: id, area_id: null, points, floor_material: "wood", panel: [] }) as Room;
|
||||
const piece = (id: string, type: string, x: number, z: number, w: number, d: number, h: number, rotation = 0, extra: Partial<Furniture> = {}): Furniture =>
|
||||
({ id, type, x, z, w, d, h, rotation, variant: null, entity: null, power: null, ...extra }) as Furniture;
|
||||
const hole = (id: string, room_id: string, edge: number, offset: number, type: Opening["type"], width: number, sill: number, height: number): Opening =>
|
||||
({ id, room_id, edge, offset, type, width, sill, height, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }) as Opening;
|
||||
|
||||
function flat() {
|
||||
const floor = newFloor("f", "Ground", 0);
|
||||
const living = room("living", [[0, 0], [5, 0], [5, 4], [0, 4]]);
|
||||
floor.rooms = [living];
|
||||
return { floor, living };
|
||||
}
|
||||
|
||||
test("seen from inside, the back wall runs from its left end to the right, and the room lies in front of it", () => {
|
||||
const { floor, living } = flat();
|
||||
const back = wallFrame(floor, living, 0, 0.12);
|
||||
assert.deepEqual(back.origin, [0, 0]);
|
||||
assert.deepEqual(back.normal, [0, 1]);
|
||||
assert.equal(back.length, 5);
|
||||
// the front wall (edge 2 runs from [5,4] to [0,4]): its left end, seen from inside, is [5,4]
|
||||
const front = wallFrame(floor, living, 2, 0.12);
|
||||
assert.deepEqual(front.origin, [5, 4]);
|
||||
assert.deepEqual(onWall(front, [4, 3.5]), { u: 1, depth: 0.5 });
|
||||
assert.equal(back.heightLeft, floor.height);
|
||||
});
|
||||
|
||||
test("the wall shows its doors and windows and the furniture with its back to it", () => {
|
||||
const { floor, living } = flat();
|
||||
floor.openings = [hole("w", "living", 0, 1.5, "window", 1.2, 0.9, 1.3)];
|
||||
floor.furniture = [
|
||||
piece("shelf", "shelf", 3.5, 0.2, 0.9, 0.35, 1.9, 0),
|
||||
piece("sofa", "sofa", 2.5, 2.0, 2.0, 0.9, 0.8, 0), // in the middle of the room
|
||||
piece("turned", "shelf", 4.7, 2.0, 0.9, 0.35, 1.9, 90), // its back is to the right wall
|
||||
];
|
||||
const boxes = wallElevation(floor, living, wallFrame(floor, living, 0, 0.12));
|
||||
assert.deepEqual(boxes.map((b) => b.id), ["w", "shelf"]);
|
||||
const [window, shelf] = boxes;
|
||||
assert.deepEqual([window.x0, window.x1, window.y0, window.y1], [0.9, 2.1, 0.9, 2.2]);
|
||||
assert.ok(window.lifts, "a window's sill can be moved");
|
||||
assert.equal(Math.round(shelf.x0 * 100) / 100, 3.05);
|
||||
assert.equal(shelf.lifts, false, "a shelf stands on the floor");
|
||||
});
|
||||
|
||||
test("moving along the wall keeps the distance from it; a wall item also takes its height", () => {
|
||||
const { floor, living } = flat();
|
||||
const frame = wallFrame(floor, living, 0, 0.12);
|
||||
const shelf = piece("shelf", "shelf", 3.5, 0.2, 0.9, 0.35, 1.9);
|
||||
assert.deepEqual(furnitureAt(frame, shelf, 1.0, 0.5), { x: 1.45, z: 0.2 });
|
||||
const lamp = piece("lamp", "lamp_wall", 2, 0.05, 0.2, 0.1, 0.2);
|
||||
assert.deepEqual(furnitureAt(frame, lamp, 2.4, 1.85), { x: 2.5, z: 0.05, mount_y: 1.85 });
|
||||
// never past the end of the wall
|
||||
assert.equal(furnitureAt(frame, shelf, 9, null).x, 4.55);
|
||||
});
|
||||
|
||||
test("a door or window moves by its offset from the edge's first corner, also when that is the right end", () => {
|
||||
const { floor, living } = flat();
|
||||
const back = wallFrame(floor, living, 0, 0.12);
|
||||
const front = wallFrame(floor, living, 2, 0.12);
|
||||
const w = hole("w", "living", 0, 1.5, "window", 1.2, 0.9, 1.3);
|
||||
assert.deepEqual(openingAt(back, living, w, 2, 1.1), { offset: 2.6, sill: 1.1 });
|
||||
const d = hole("d", "living", 2, 1, "door", 0.9, 0, 2.05);
|
||||
// the front wall's left end (seen from inside) is its first corner [5,4]
|
||||
assert.deepEqual(openingAt(front, living, d, 0.5, 0.4), { offset: 0.95 });
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
// The wall view: one wall of a room seen from the front, with its doors and windows and the furniture standing or hanging against it,
|
||||
// in wall coordinates (u along the wall from its left end as seen from the room, y up from the floor). Moving something in the view
|
||||
// turns back into plan positions here.
|
||||
|
||||
import { dot, norm, sub } from "../../../geometry/vec2.ts";
|
||||
import { pointInPolygon, signedArea, type Floor, type Furniture, type Opening, type Room, type Vec2 } from "../../../model.ts";
|
||||
import { mountBase, packItem } from "../../../packs.ts";
|
||||
|
||||
/** One wall as the view sees it. */
|
||||
export interface WallFrame {
|
||||
/** The left end of the wall seen from inside the room, and the direction to its right end. */
|
||||
origin: Vec2;
|
||||
along: Vec2;
|
||||
/** Into the room. */
|
||||
normal: Vec2;
|
||||
length: number;
|
||||
/** How far the wall's face lies inside the room edge (half an interior wall; 0 for an outer wall). */
|
||||
face: number;
|
||||
/** The wall's height at its left and right end. */
|
||||
heightLeft: number;
|
||||
heightRight: number;
|
||||
}
|
||||
|
||||
export interface ElevationBox {
|
||||
id: string;
|
||||
kind: "opening" | "furniture";
|
||||
type: string;
|
||||
/** Left and right along the wall, bottom and top above the floor (metres). */
|
||||
x0: number;
|
||||
x1: number;
|
||||
y0: number;
|
||||
y1: number;
|
||||
/** It can be moved up and down (wall-mounted items, windows), not only along. */
|
||||
lifts: boolean;
|
||||
}
|
||||
|
||||
/** Furniture counts as standing against the wall when its back is at most this far from the wall face (metres). */
|
||||
const NEAR = 0.15;
|
||||
const angleBetween = (a: number, b: number) => Math.abs(((a - b + 540) % 360) - 180);
|
||||
|
||||
function edgeIsShared(floor: Floor, room: Room, a: Vec2, normal: Vec2): boolean {
|
||||
return floor.rooms.some(
|
||||
(other) =>
|
||||
other.id !== room.id &&
|
||||
other.points.some((p, k) => {
|
||||
const q = other.points[(k + 1) % other.points.length];
|
||||
return Math.abs(dot(sub(p, a), normal)) < 0.02 && Math.abs(dot(sub(q, a), normal)) < 0.02;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The frame of a room's wall (edge points[edge] -> points[edge + 1]), turned so that its left end is on the left seen from inside. */
|
||||
export function wallFrame(floor: Floor, room: Room, edge: number, wallInterior: number): WallFrame {
|
||||
const pts = room.points;
|
||||
const [a, b] = [pts[edge], pts[(edge + 1) % pts.length]];
|
||||
const length = norm(sub(b, a));
|
||||
const winding = signedArea(pts) >= 0 ? 1 : -1;
|
||||
const dir: Vec2 = [(b[0] - a[0]) / length, (b[1] - a[1]) / length];
|
||||
const normal: Vec2 = [-dir[1] * winding || 0, dir[0] * winding || 0];
|
||||
// standing in the room and looking at the wall, the left end is the one to the left of the normal
|
||||
const leftIsA = dir[0] * normal[1] - dir[1] * normal[0] > 0;
|
||||
const entry = room.wall_heights?.[edge];
|
||||
const full = room.ceiling ?? floor.height;
|
||||
const start = typeof entry === "number" ? entry : Array.isArray(entry) ? Math.max(...entry.map((h) => h ?? full)) : full;
|
||||
const slope = room.wall_slopes?.[edge];
|
||||
const end = typeof slope === "number" && typeof entry === "number" ? slope : start;
|
||||
return {
|
||||
origin: leftIsA ? a : b,
|
||||
along: leftIsA ? dir : [-dir[0], -dir[1]],
|
||||
normal,
|
||||
length,
|
||||
face: edgeIsShared(floor, room, a, normal) ? wallInterior / 2 : 0,
|
||||
heightLeft: leftIsA ? start : end,
|
||||
heightRight: leftIsA ? end : start,
|
||||
};
|
||||
}
|
||||
|
||||
/** Where a point of the plan lies on the wall: along it from the left end, and its distance from the wall face into the room. */
|
||||
export function onWall(frame: WallFrame, p: Vec2): { u: number; depth: number } {
|
||||
const rel = sub(p, frame.origin);
|
||||
return { u: dot(rel, frame.along), depth: dot(rel, frame.normal) - frame.face };
|
||||
}
|
||||
|
||||
/** The middle of an opening in the plan. */
|
||||
function openingCentre(floor: Floor, o: Opening): Vec2 | null {
|
||||
const room = floor.rooms.find((r) => r.id === o.room_id);
|
||||
if (!room || o.wall) return null;
|
||||
const [a, b] = [room.points[o.edge], room.points[(o.edge + 1) % room.points.length]];
|
||||
if (!a || !b) return null;
|
||||
const length = norm(sub(b, a)) || 1;
|
||||
return [a[0] + ((b[0] - a[0]) * o.offset) / length, a[1] + ((b[1] - a[1]) * o.offset) / length];
|
||||
}
|
||||
|
||||
const isWallMounted = (f: Furniture): boolean => packItem(f.type)?.mount === "wall" || f.type === "lamp_wall" || f.mount_y != null;
|
||||
|
||||
/** The doors, windows and furniture of a wall, in wall coordinates. Furniture must stand in the room with its back to this wall. */
|
||||
export function wallElevation(floor: Floor, room: Room, frame: WallFrame): ElevationBox[] {
|
||||
const boxes: ElevationBox[] = [];
|
||||
for (const o of floor.openings) {
|
||||
const centre = openingCentre(floor, o);
|
||||
if (!centre) continue;
|
||||
const { u, depth } = onWall(frame, centre);
|
||||
// the doors of this wall, also when the room on the other side owns them
|
||||
if (Math.abs(depth + frame.face) > 0.3 || u < -0.01 || u > frame.length + 0.01) continue;
|
||||
boxes.push({ id: o.id, kind: "opening", type: o.type, x0: u - o.width / 2, x1: u + o.width / 2, y0: o.sill, y1: o.sill + o.height, lifts: o.type === "window" });
|
||||
}
|
||||
const back = (Math.atan2(-frame.normal[0], frame.normal[1]) * 180) / Math.PI;
|
||||
for (const f of floor.furniture) {
|
||||
if (!pointInPolygon([f.x, f.z], room.points) || angleBetween(f.rotation, back) > 20) continue;
|
||||
const { u, depth } = onWall(frame, [f.x, f.z]);
|
||||
if (depth - f.d / 2 > NEAR || u < 0 || u > frame.length) continue;
|
||||
const y0 = mountBase(floor, f);
|
||||
boxes.push({ id: f.id, kind: "furniture", type: f.type, x0: u - f.w / 2, x1: u + f.w / 2, y0, y1: y0 + f.h, lifts: isWallMounted(f) });
|
||||
}
|
||||
return boxes.sort((p, q) => Number(p.kind === "furniture") - Number(q.kind === "furniture") || p.x0 - q.x0);
|
||||
}
|
||||
|
||||
const mm = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** A piece of furniture moved to `left` along the wall (its left side) and, when it hangs on the wall, to `bottom` above the floor. */
|
||||
export function furnitureAt(frame: WallFrame, f: Furniture, left: number, bottom: number | null): Partial<Furniture> {
|
||||
const depth = onWall(frame, [f.x, f.z]).depth;
|
||||
const u = Math.min(frame.length - f.w / 2, Math.max(f.w / 2, left + f.w / 2));
|
||||
const at: Vec2 = [frame.origin[0] + frame.along[0] * u + frame.normal[0] * (depth + frame.face), frame.origin[1] + frame.along[1] * u + frame.normal[1] * (depth + frame.face)];
|
||||
return { x: mm(at[0]), z: mm(at[1]), ...(bottom !== null && isWallMounted(f) ? { mount_y: mm(Math.max(0, bottom)) } : {}) };
|
||||
}
|
||||
|
||||
/** A door or window moved to `left` along the wall and, for a window, to a sill height of `bottom`. */
|
||||
export function openingAt(frame: WallFrame, room: Room, o: Opening, left: number, bottom: number | null): Partial<Opening> {
|
||||
const [a] = [room.points[o.edge]];
|
||||
const middle = Math.min(frame.length - o.width / 2, Math.max(o.width / 2, left + o.width / 2));
|
||||
// the offset counts from points[edge], which may be the right end seen from the room
|
||||
const fromA = norm(sub(a, frame.origin)) < 1e-6 ? middle : frame.length - middle;
|
||||
return { offset: mm(fromA), ...(bottom !== null && o.type === "window" ? { sill: mm(Math.max(0, bottom)) } : {}) };
|
||||
}
|
||||
Reference in new issue
Block a user