Skip to content

Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.

Homes on several floors, and a better floor plan editor (1.3.0, build 12)

0xProbability85a440be6cc9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 17c26d4..50e2a3c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,7 +3,40 @@
What changed in each release of House Control. The Mac app is on
[Releases](https://github.com/0xProbabillity/house-control/releases); the iPhone app is on the App Store and TestFlight.
-## 1.2.0 — in TestFlight
+## 1.3.0 — in TestFlight
+
+### Homes on several floors
+
+- **Floors.** A house can have as many floors as it needs, each with its own name and ceiling height (a basement
+ too). The 3D model shows one floor at a time, standing on the floors under it; buttons under the model switch
+ floors, and picking a room, a lamp or an AC goes to its floor by itself. The panel lists devices floor by floor,
+ starting with the one on show, and remembers which floor you last looked at.
+- **Stairs**, as a piece of furniture that climbs to the floor above.
+- A new demo, **House**, on two floors, in the plan menu, the iPhone's Settings and **New home**.
+- Widgets draw the floor with the most lamps on. The phone's Devices screen names each room's floor.
+- AI Access can read and build homes on several floors (`add_floor`, `"level"` on rooms, furniture and openings).
+- A home on one floor looks and works as before; its plan file does not change.
+
+### The floor plan editor
+
+- **Floor tabs over the plan**, with **+ Floor**. A new floor copies the rooms of the one below (its windows and
+ inner doors too), or starts as one room as big as it; the floor below shows faintly under the one being edited,
+ with its stairs, so walls and landings line up. A floor's settings: name, ceiling height, order, remove.
+- **Resize a room from any corner or side**, not only the bottom-right corner. Edges snap to the walls of the
+ rooms around them (and of the floor below), with a guide line; hold ⌥ not to.
+- **Doors and windows slide along the walls** and jump to the nearest one; drag the dots at their ends to make
+ them wider. A new window goes on a far wall, where the 3D model shows it.
+- **Split in two** divides a room, moves its lamps and ACs to the half they stand in and puts a door between.
+- **Duplicate** (⌘D) and **turn** (R, ⇧R) on the Mac; buttons for both on the phone.
+- **Zoom and move around on the Mac:** scroll, pinch or ⌘-scroll, drag the empty plan or hold Space; zoom
+ buttons and ⌘0 to see the whole floor.
+- **An add bar under the plan** (Mac): room, lamp, AC, door, window, stairs, furniture. On the phone, **Add** has
+ windows, stairs and floors too.
+- A list of shortcuts under Home settings.
+- **Fixed:** in Chrome-based web views (Android) the editor did not fill its window.
+- **Fixed (phone):** a sheet sliding away could still catch a tap.
+
+## 1.2.0 — 2026-10-28
### iPhone
diff --git a/README.md b/README.md
index 37b5d7a..aed2dcb 100644
--- a/README.md
+++ b/README.md
@@ -323,11 +323,23 @@ Right-click the icon and choose **Edit Home…**
<img src="docs/editor.png" width="820" alt="The floor plan editor">
</p>
-- Drag rooms to move them and drag a corner to resize; everything snaps to 5 cm.
+- Drag rooms to move them; drag the dots on a selected room's corners and sides to resize it. Edges snap to
+ the rooms around them (hold ⌥ not to), everything else to 5 cm.
- Where two rooms touch, the wall between them appears by itself. Walls facing the camera are cut away.
-- Add doors, windows, furniture, lamps and air conditioners from the list on the left.
+ **Split in two** divides a room and puts a door between the halves.
+- Add rooms, lamps, air conditioners, doors, windows, stairs and furniture from the bar under the plan.
+ Doors and windows slide along the walls and jump to the nearest one; drag their ends to make them wider.
+- Scroll to move around, pinch or ⌘-scroll to zoom. ⌘D duplicates, R turns, ⌘Z undoes.
- **Save & apply** writes the plan and reloads the panel.
+### Floors
+
+A house on more than one floor: **+ Floor** over the plan adds one. A new floor can copy the rooms of the one
+below it, or start as one room as big as it to divide up; the floor below shows faintly underneath, with its
+stairs, so walls line up. Each floor has its own name and ceiling height. In the panel, buttons under the 3D model
+switch floors, and picking a room or a lamp goes to its floor by itself. The **House** demo is on two floors.
+A home on one floor looks and works exactly as before.
+
The plan is a single JSON file, `~/Library/Application Support/HouseControl/plan.json`. You can write it by hand,
export it, or import someone else's: see [docs/floor-plan.md](docs/floor-plan.md) for every field.
The demo plans in [`web/public/plans`](web/public/plans) are good starting points.
diff --git a/core/Sources/HouseCore/HomeSnapshot.swift b/core/Sources/HouseCore/HomeSnapshot.swift
index bc53f5f..bf8af82 100644
--- a/core/Sources/HouseCore/HomeSnapshot.swift
+++ b/core/Sources/HouseCore/HomeSnapshot.swift
@@ -11,6 +11,14 @@ public struct HomeSnapshot: Codable, Equatable, Sendable {
/// The room's rectangle on the floor plan, in metres.
public var x: Double, z: Double, w: Double, d: Double
public var floor: String?
+ /// The floor (storey) it is on, on a home with several; nil on a home with one.
+ public var level: String?
+ }
+
+ /// A floor of a home on several, lowest first.
+ public struct Level: Codable, Equatable, Sendable, Identifiable {
+ public var id: String
+ public var name: String
}
public struct Light: Codable, Equatable, Sendable, Identifiable {
@@ -69,13 +77,18 @@ public struct HomeSnapshot: Codable, Equatable, Sendable {
public var x: Double, z: Double, w: Double, d: Double
public var rot: Double
public var color: String?
+ public var level: String?
}
public var version = 1
public var name: String
- /// "home" / "studio" for the bundled demos, "custom" for the user's own plan.
+ /// "home" / "studio" / "house" for the bundled demos, "custom" for the user's own plan.
public var plan: String
public var outdoorTemp: Double?
+ /// The floors of a home on several; nil on a home with one.
+ public var levels: [Level]?
+ /// The floor the widgets draw: the one with the most lamps on (the panel picks it).
+ public var shownLevel: String?
public var rooms: [Room]
public var lights: [Light]
public var acs: [AC]
@@ -107,6 +120,20 @@ public struct HomeSnapshot: Codable, Equatable, Sendable {
public var isSimulated: Bool { lights.allSatisfy { $0.service == nil } && acs.allSatisfy { $0.service == nil } }
public func room(_ id: String) -> Room? { rooms.first { $0.id == id } }
+
+ /// On a home with several floors, the one the widgets draw (`shownLevel`): its rooms, their
+ /// lamps and ACs and its furniture. A home on one floor comes back as it is.
+ public var shownFloor: HomeSnapshot {
+ guard let level = shownLevel, let first = levels?.first?.id, (levels?.count ?? 0) > 1 else { return self }
+ var copy = self
+ copy.rooms = rooms.filter { ($0.level ?? first) == level }
+ let ids = Set(copy.rooms.map(\.id))
+ copy.lights = lights.filter { ids.contains($0.room) }
+ copy.acs = acs.filter { ids.contains($0.room) }
+ copy.furniture = furniture?.filter { ($0.level ?? first) == level }
+ copy.shownLevel = nil
+ return copy
+ }
public func light(_ id: String) -> Light? { lights.first { $0.id == id } }
public func ac(_ id: String) -> AC? { acs.first { $0.id == id } }
public func lights(in room: String) -> [Light] { lights.filter { $0.room == room } }
diff --git a/core/Sources/HouseCore/PlanEditor.swift b/core/Sources/HouseCore/PlanEditor.swift
index 1503b7f..46a26f7 100644
--- a/core/Sources/HouseCore/PlanEditor.swift
+++ b/core/Sources/HouseCore/PlanEditor.swift
@@ -34,6 +34,20 @@ public struct PlanEditor {
public struct Room: Identifiable, Equatable {
public let id: String
public let name: String
+ /// The name of its floor, on a home with several.
+ public var floor: String? = nil
+
+ /// "Bedroom", or "Bedroom · First floor" where two floors could have one.
+ public var title: String { floor.map { "\(name) · \($0)" } ?? name }
+ }
+
+ /// The floors of a home on several, lowest first (id, name); empty for a home on one.
+ public var levels: [(id: String, name: String)] {
+ let list = (plan["levels"] as? [[String: Any]] ?? []).compactMap { level -> (id: String, name: String)? in
+ guard let id = level["id"] as? String, !id.isEmpty else { return nil }
+ return (id, (level["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? id)
+ }
+ return list.count > 1 ? list : []
}
// MARK: - Reading
@@ -41,14 +55,17 @@ public struct PlanEditor {
public var name: String { plan["name"] as? String ?? "Home" }
public var rooms: [Room] {
- (plan["rooms"] as? [[String: Any]] ?? []).compactMap { room in
+ let levels = self.levels
+ let names = Dictionary(levels.map { ($0.id, $0.name) }, uniquingKeysWith: { a, _ in a })
+ return (plan["rooms"] as? [[String: Any]] ?? []).compactMap { room in
guard let id = room["id"] as? String else { return nil }
- return Room(id: id, name: (room["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? id)
+ let floor = levels.isEmpty ? nil : names[room["level"] as? String ?? levels[0].id]
+ return Room(id: id, name: (room["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? id, floor: floor)
}
}
public var items: [Item] {
- let names = Dictionary(rooms.map { ($0.id, $0.name) }, uniquingKeysWith: { a, _ in a })
+ let names = Dictionary(rooms.map { ($0.id, $0.title) }, uniquingKeysWith: { a, _ in a })
var out: [Item] = []
for (kind, key) in [(DeviceKind.light, "lights"), (.ac, "acs")] {
for device in plan[key] as? [[String: Any]] ?? [] {
@@ -276,16 +293,20 @@ public struct PlanEditor {
plan["scenes"] = scenes
}
- /// Adds a room east of the others; returns its id.
+ /// Adds a room east of the others (on the first floor of a home with several); returns its id.
@discardableResult
public mutating func addRoom(named name: String, width: Double = 4, depth: Double = 3.5) -> String {
var rooms = plan["rooms"] as? [[String: Any]] ?? []
- let rects = rooms.compactMap { ($0["rect"] as? [NSNumber])?.map(\.doubleValue) }.filter { $0.count == 4 }
+ let ground = levels.first?.id
+ let rects = rooms.filter { ground == nil || ($0["level"] as? String ?? ground) == ground }
+ .compactMap { ($0["rect"] as? [NSNumber])?.map(\.doubleValue) }.filter { $0.count == 4 }
let maxX = rects.map { $0[0] + $0[2] }.max() ?? 0
let minZ = rects.map { $0[1] }.min() ?? 0
let base = Self.slug(name)
let id = uniqueId(base, taken: allIds)
- rooms.append(["id": id, "name": name, "rect": [Self.fix(maxX), Self.fix(minZ), width, depth], "floor": "oak"])
+ var room: [String: Any] = ["id": id, "name": name, "rect": [Self.fix(maxX), Self.fix(minZ), width, depth], "floor": "oak"]
+ if let ground { room["level"] = ground }
+ rooms.append(room)
plan["rooms"] = rooms
return id
}
diff --git a/core/Sources/HouseCore/PlanStore.swift b/core/Sources/HouseCore/PlanStore.swift
index f9703d2..3f6442f 100644
--- a/core/Sources/HouseCore/PlanStore.swift
+++ b/core/Sources/HouseCore/PlanStore.swift
@@ -4,13 +4,13 @@ import CryptoKit
/// Persists which floor plan is active and the user's own plan file.
/// Everything lives in ~/Library/Application Support/HouseControl (or HOUSE_DATA_DIR).
public final class PlanStore {
- public static let bundled = ["home", "studio"]
+ public static let bundled = ["home", "studio", "house"]
public let directory: URL
public var customPlanURL: URL { directory.appendingPathComponent("plan.json") }
private var settingsURL: URL { directory.appendingPathComponent("settings.json") }
- /// "home" / "studio" for the bundled demos, or "custom" for plan.json.
+ /// "home" / "studio" / "house" for the bundled demos, or "custom" for plan.json.
public private(set) var activePlan = "home"
public init() {
diff --git a/core/Tests/HouseCoreTests/PlanEditorTests.swift b/core/Tests/HouseCoreTests/PlanEditorTests.swift
index 8cf071f..67e28a5 100644
--- a/core/Tests/HouseCoreTests/PlanEditorTests.swift
+++ b/core/Tests/HouseCoreTests/PlanEditorTests.swift
@@ -97,6 +97,24 @@ final class PlanEditorTests: XCTestCase {
XCTAssertEqual(Array(rules.keys), ["*"])
}
+ func testRoomsOnSeveralFloors() {
+ var plan = sample()
+ XCTAssertTrue(PlanEditor(plan: plan).levels.isEmpty)
+ XCTAssertEqual(PlanEditor(plan: plan).rooms.map(\.title), ["Living room"])
+ plan["levels"] = [["id": "ground", "name": "Ground floor"], ["id": "up", "name": "First floor"]]
+ var rooms = plan["rooms"] as! [[String: Any]]
+ rooms.append(["id": "loft", "name": "Loft", "rect": [0, 0, 9, 6], "floor": "oak", "level": "up"])
+ plan["rooms"] = rooms
+ var editor = PlanEditor(plan: plan)
+ XCTAssertEqual(editor.rooms.map(\.title), ["Living room · Ground floor", "Loft · First floor"])
+ XCTAssertEqual(editor.items.first?.roomName, "Living room · Ground floor")
+ // A new room goes on the ground floor, east of the rooms there (not of the wider loft above).
+ let id = editor.addRoom(named: "Study")
+ let study = (editor.plan["rooms"] as! [[String: Any]]).first { $0["id"] as? String == id }!
+ XCTAssertEqual(study["level"] as? String, "ground")
+ XCTAssertEqual((study["rect"] as! [NSNumber])[0].doubleValue, 5)
+ }
+
func testFixtureGuess() {
XCTAssertEqual(PlanEditor.fixture(for: "Bedside Lamp"), "table")
XCTAssertEqual(PlanEditor.fixture(for: "Hue color lamp"), "ceiling")
diff --git a/core/Tests/HouseCoreTests/WidgetTests.swift b/core/Tests/HouseCoreTests/WidgetTests.swift
index c710b96..461ed8a 100644
--- a/core/Tests/HouseCoreTests/WidgetTests.swift
+++ b/core/Tests/HouseCoreTests/WidgetTests.swift
@@ -22,6 +22,27 @@ final class WidgetTests: XCTestCase {
acs: [ac], scenes: [cozy])
}
+ func testWidgetsDrawTheShownFloorOfAHomeOnSeveral() {
+ var h = home()
+ XCTAssertEqual(h.shownFloor, h, "a home on one floor is drawn whole")
+ h.levels = [.init(id: "ground", name: "Ground floor"), .init(id: "up", name: "First floor")]
+ h.rooms[0].level = "ground"
+ h.rooms.append(.init(id: "bed", name: "Bedroom", x: 0, z: 0, w: 4, d: 3, floor: "walnut", level: "up"))
+ h.lights.append(.init(id: "bedside", name: "Bedside", room: "bed", type: "table", x: 1, z: 1, capabilities: [],
+ on: true, brightness: 1, temp: 2700, color: nil, service: nil, links: nil))
+ h.furniture = [.init(type: "bed", x: 2, z: 1.5, w: 1.7, d: 2.1, rot: 0, color: nil, level: "up"),
+ .init(type: "sofa", x: 2, z: 1.5, w: 2.2, d: 0.9, rot: 0, color: nil, level: "ground")]
+ h.shownLevel = "up"
+ let up = h.shownFloor
+ XCTAssertEqual(up.rooms.map(\.id), ["bed"])
+ XCTAssertEqual(up.lights.map(\.id), ["bedside"])
+ XCTAssertTrue(up.acs.isEmpty)
+ XCTAssertEqual(up.furniture?.map(\.type), ["bed"])
+ h.shownLevel = "ground"
+ XCTAssertEqual(h.shownFloor.rooms.map(\.id), ["living"])
+ XCTAssertEqual(h.shownFloor.lights.count, 3)
+ }
+
func testToggleIsResolved() {
var h = home()
let (resolved, changes) = h.apply(.light("main"))
diff --git a/docs/floor-plan.md b/docs/floor-plan.md
index baa9581..b08d485 100644
--- a/docs/floor-plan.md
+++ b/docs/floor-plan.md
@@ -4,8 +4,8 @@ A home is one JSON document. The 3D scene, the panel and the editor are all buil
file swaps the home.
- Your plan: `~/Library/Application Support/HouseControl/plan.json`
-- Bundled demos: [`web/public/plans/home.json`](../web/public/plans/home.json) and
- [`studio.json`](../web/public/plans/studio.json)
+- Bundled demos: [`web/public/plans/home.json`](../web/public/plans/home.json),
+ [`studio.json`](../web/public/plans/studio.json) and, on two floors, [`house.json`](../web/public/plans/house.json)
You rarely need to write it by hand — **Edit Home…** does it for you — but it is plain, stable and easy to
generate or version. Load a file with **Load Floor Plan…** in the menu bar icon's right-click menu, or with
@@ -74,6 +74,31 @@ Heights (`y`, `sill`, `head`) are metres above the floor. Angles are degrees.
| `interiorWallHeight` | `1.25` | How much of the inner walls is drawn, so they do not hide the rooms |
| `outdoorTemp` | `27` | Used to estimate the room temperature of an AC that has no sensor |
| `camera.azimuth`, `camera.elevation` | `34`, `47` | Default view. Walls facing the camera are cut away, so the azimuth decides which side is open |
+| `levels` | one floor | The floors of a home on several, lowest first. See [Floors](#levels-floors) |
+
+## `levels`: floors
+
+A home on one floor needs nothing here. A house on several lists its floors, lowest first:
+
+```jsonc
+"levels": [
+ { "id": "ground", "name": "Ground floor" },
+ { "id": "upper", "name": "First floor", "wallHeight": 2.5 }
+]
+```
+
+| Field | Meaning |
+| --- | --- |
+| `id` | Unique. Rooms, furniture and openings refer to it with `"level"` |
+| `name` | Shown on the floor buttons of the panel and the editor |
+| `wallHeight` | Optional: this floor's own wall height (the home's `wallHeight` otherwise) |
+
+Every room, piece of furniture and opening then says which floor it is on with `"level": "<id>"`; without it, it
+is on the first. Lamps and ACs are on their room's floor. All floors share one grid, so a room upstairs at
+`[0, 0, 4, 3]` sits right above the room at `[0, 0, 4, 3]` downstairs. Each floor stands on the one under it
+(its walls plus a 30 cm slab); the 3D view shows one floor at a time, with the floors under it, and the editor
+draws the floor below faintly so walls and stairs line up. Stairs are furniture on the lower floor
+(`"type": "stairs"`).
## `rooms`
@@ -83,6 +108,7 @@ Heights (`y`, `sill`, `head`) are metres above the floor. Angles are degrees.
| `name` | Shown in the room filter |
| `rect` | `[x, z, width, depth]` |
| `floor` | `oak`, `walnut`, `tile` or `stone` |
+| `level` | The floor (storey) it is on, on a home with [several](#levels-floors) |
Rooms are rectangles. Where two of them touch, an inner wall appears on its own; make an L-shaped room out of two.
@@ -95,10 +121,12 @@ A gap in a wall, given by its two end points on that wall. It must be horizontal
| `type` | `door`, `window`, or `open` (a doorway without a door, or a missing piece of wall) |
| `from`, `to` | `[x, z]` end points |
| `sill`, `head` | Bottom and top of a window. Defaults `0.85` and `2.1` |
+| `level` | Its floor, on a home with [several](#levels-floors) |
## `furniture`
-Decoration only. Every piece has `type`, `pos` (`[x, z]` of its centre) and an optional `rot`.
+Decoration only. Every piece has `type`, `pos` (`[x, z]` of its centre), an optional `rot` and, on a home with
+[several floors](#levels-floors), its `level`.
| `type` | Extra options |
| --- | --- |
@@ -113,6 +141,7 @@ Decoration only. Every piece has `type`, `pos` (`[x, z]` of its centre) and an o
| `bed` | `width`, `color` |
| `wardrobe`, `bookshelf` | `width`, `height` |
| `plant` | `height` |
+| `stairs` | `width`, `depth` (its length), `height` (up to the floor above by default). They climb away from the front |
| `fridge`, `nightstand`, `bathtub`, `toilet` | — |
## `lights`
diff --git a/ios/Config/Base.xcconfig b/ios/Config/Base.xcconfig
index b4c0e9e..6d5843e 100644
--- a/ios/Config/Base.xcconfig
+++ b/ios/Config/Base.xcconfig
@@ -1,6 +1,6 @@
// Version of the iPhone app. CURRENT_PROJECT_VERSION is the build number TestFlight sees.
-MARKETING_VERSION = 1.2.0
-CURRENT_PROJECT_VERSION = 11
+MARKETING_VERSION = 1.3.0
+CURRENT_PROJECT_VERSION = 12
CODE_SIGN_STYLE = Automatic
diff --git a/ios/Sources/DevicesView.swift b/ios/Sources/DevicesView.swift
index 6fe791f..0af23ef 100644
--- a/ios/Sources/DevicesView.swift
+++ b/ios/Sources/DevicesView.swift
@@ -140,7 +140,7 @@ struct DevicesView: View {
private func roomSection(_ room: PlanEditor.Room, _ items: [PlanEditor.Item]) -> some View {
VStack(spacing: 10) {
- SectionTitle(room.name)
+ SectionTitle(room.title)
Card {
ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
if index > 0 { RowDivider() }
@@ -314,7 +314,7 @@ struct AddDevicesView: View {
List {
Section {
Picker("Room", selection: $room) {
- ForEach(rooms) { Text($0.name).tag($0.id) }
+ ForEach(rooms) { Text($0.title).tag($0.id) }
Text("New room…").tag(Self.newRoomTag)
}
.tint(Theme.accent)
diff --git a/ios/Sources/NewHomeView.swift b/ios/Sources/NewHomeView.swift
index dbd8baa..ff1e77c 100644
--- a/ios/Sources/NewHomeView.swift
+++ b/ios/Sources/NewHomeView.swift
@@ -13,6 +13,7 @@ struct NewHomeView: View {
(nil, "One room", "Draw the rest yourself, or add your devices to it", "square.dashed"),
("studio", "Studio layout", "3 rooms with furniture, to adapt", "square.split.bottomrightquarter.fill"),
("home", "Apartment layout", "5 rooms with furniture, to adapt", "building.2.fill"),
+ ("house", "House on two floors", "10 rooms and stairs, to adapt", "stairs"),
]
var body: some View {
diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swift
index ee70448..ad56536 100644
--- a/ios/Sources/SettingsView.swift
+++ b/ios/Sources/SettingsView.swift
@@ -81,6 +81,8 @@ struct SettingsView: View {
planRow("home", name: "Apartment", detail: "Demo · 5 rooms, simulated devices", symbol: "building.2.fill", tint: Theme.accent)
RowDivider()
planRow("studio", name: "Studio", detail: "Demo · 3 rooms, simulated devices", symbol: "square.split.bottomrightquarter.fill", tint: Theme.accent)
+ RowDivider()
+ planRow("house", name: "House", detail: "Demo · 2 floors, 10 rooms, simulated devices", symbol: "stairs", tint: Theme.accent)
}
Card {
Button { model.openEditor() } label: {
diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swift
index bcda4a4..9dedce5 100644
--- a/macos/Sources/HouseControl/AppDelegate.swift
+++ b/macos/Sources/HouseControl/AppDelegate.swift
@@ -788,7 +788,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
model.openAtLogin = LoginItem.state
model.islandShown = island?.isShown == true
var choices = PlanStore.bundled.map { id in
- SettingsModel.Plan(id: id, name: "Demo · \(id == "home" ? "Apartment" : id.capitalized)")
+ SettingsModel.Plan(id: id, name: "Demo · \(["home": "Apartment", "house": "House on two floors"][id] ?? id.capitalized)")
}
if plans.hasCustomPlan { choices.insert(.init(id: "custom", name: plans.customPlanName ?? "My home"), at: 0) }
model.plans = choices
diff --git a/web/public/plans/house.json b/web/public/plans/house.json
new file mode 100644
index 0000000..982db9c
--- /dev/null
+++ b/web/public/plans/house.json
@@ -0,0 +1,108 @@
+{
+ "version": 1,
+ "name": "House",
+ "wallHeight": 2.7,
+ "interiorWallHeight": 1.25,
+ "camera": { "azimuth": 34, "elevation": 50 },
+ "outdoorTemp": 24,
+
+ "levels": [
+ { "id": "ground", "name": "Ground floor" },
+ { "id": "upper", "name": "First floor" }
+ ],
+
+ "rooms": [
+ { "id": "living", "name": "Living", "rect": [0, 3.4, 6.0, 4.6], "floor": "oak", "level": "ground" },
+ { "id": "kitchen", "name": "Kitchen", "rect": [6.0, 3.4, 4.0, 4.6], "floor": "stone", "level": "ground" },
+ { "id": "hall", "name": "Hall", "rect": [3.6, 0, 2.6, 3.4], "floor": "tile", "level": "ground" },
+ { "id": "study", "name": "Study", "rect": [0, 0, 3.6, 3.4], "floor": "walnut", "level": "ground" },
+ { "id": "wc", "name": "Guest bath", "rect": [6.2, 0, 3.8, 3.4], "floor": "tile", "level": "ground" },
+ { "id": "bedroom", "name": "Bedroom", "rect": [0, 3.4, 5.0, 4.6], "floor": "walnut", "level": "upper" },
+ { "id": "kids", "name": "Kids room", "rect": [5.0, 3.4, 5.0, 4.6], "floor": "oak", "level": "upper" },
+ { "id": "office", "name": "Office", "rect": [0, 0, 3.6, 3.4], "floor": "oak", "level": "upper" },
+ { "id": "landing", "name": "Landing", "rect": [3.6, 0, 2.6, 3.4], "floor": "oak", "level": "upper" },
+ { "id": "bath", "name": "Bathroom", "rect": [6.2, 0, 3.8, 3.4], "floor": "tile", "level": "upper" }
+ ],
+
+ "openings": [
+ { "type": "door", "from": [4.0, 0], "to": [4.9, 0], "level": "ground" },
+ { "type": "door", "from": [3.6, 1.2], "to": [3.6, 2.1], "level": "ground" },
+ { "type": "open", "from": [3.8, 3.4], "to": [5.0, 3.4], "level": "ground" },
+ { "type": "door", "from": [6.2, 1.6], "to": [6.2, 2.4], "level": "ground" },
+ { "type": "open", "from": [6.0, 4.0], "to": [6.0, 7.6], "level": "ground" },
+ { "type": "window", "from": [0, 4.4], "to": [0, 6.6], "level": "ground" },
+ { "type": "window", "from": [0.8, 0], "to": [2.6, 0], "level": "ground" },
+ { "type": "window", "from": [7.6, 0], "to": [8.6, 0], "sill": 1.5, "head": 2.2, "level": "ground" },
+ { "type": "door", "from": [3.6, 1.2], "to": [3.6, 2.1], "level": "upper" },
+ { "type": "door", "from": [3.8, 3.4], "to": [4.6, 3.4], "level": "upper" },
+ { "type": "door", "from": [5.2, 3.4], "to": [6.0, 3.4], "level": "upper" },
+ { "type": "door", "from": [6.2, 1.6], "to": [6.2, 2.4], "level": "upper" },
+ { "type": "window", "from": [0, 4.6], "to": [0, 6.4], "level": "upper" },
+ { "type": "window", "from": [0.8, 0], "to": [2.6, 0], "level": "upper" },
+ { "type": "window", "from": [7.4, 0], "to": [8.4, 0], "sill": 1.5, "head": 2.2, "level": "upper" },
+ { "type": "window", "from": [4.3, 0], "to": [5.5, 0], "level": "upper" }
+ ],
+
+ "furniture": [
+ { "type": "rug", "pos": [2.6, 5.7], "size": [2.6, 3.0], "color": "#3b4a66", "level": "ground" },
+ { "type": "tv", "pos": [0.32, 5.7], "rot": 90, "width": 1.7, "level": "ground" },
+ { "type": "sofa", "pos": [4.1, 5.7], "rot": -90, "width": 2.5, "color": "#8b93a7", "level": "ground" },
+ { "type": "coffeeTable", "pos": [2.6, 5.7], "rot": 90, "level": "ground" },
+ { "type": "armchair", "pos": [2.2, 4.0], "rot": 12, "color": "#c28a5a", "level": "ground" },
+ { "type": "plant", "pos": [0.45, 7.5], "level": "ground" },
+ { "type": "diningSet", "pos": [7.6, 6.0], "level": "ground" },
+ { "type": "kitchen", "pos": [9.69, 5.7], "rot": -90, "width": 3, "level": "ground" },
+ { "type": "fridge", "pos": [9.66, 7.6], "rot": -90, "level": "ground" },
+ { "type": "stairs", "pos": [5.6, 1.75], "width": 1, "depth": 2.8, "level": "ground" },
+ { "type": "desk", "pos": [1.8, 0.35], "level": "ground" },
+ { "type": "bookshelf", "pos": [0.18, 2.2], "rot": 90, "width": 1.2, "level": "ground" },
+ { "type": "plant", "pos": [3.2, 3.0], "level": "ground" },
+ { "type": "vanity", "pos": [7.0, 0.25], "level": "ground" },
+ { "type": "toilet", "pos": [9.5, 0.35], "level": "ground" },
+ { "type": "bed", "pos": [1.15, 5.7], "rot": 90, "width": 1.6, "color": "#d8d2c8", "level": "upper" },
+ { "type": "nightstand", "pos": [0.2, 4.55], "rot": 90, "level": "upper" },
+ { "type": "nightstand", "pos": [0.2, 6.85], "rot": 90, "level": "upper" },
+ { "type": "wardrobe", "pos": [4.68, 5.7], "rot": -90, "width": 1.8, "level": "upper" },
+ { "type": "rug", "pos": [2.9, 5.7], "size": [1.8, 2.6], "color": "#5a4a3c", "level": "upper" },
+ { "type": "bed", "pos": [8.93, 4.6], "rot": -90, "width": 0.9, "color": "#7fa7d9", "level": "upper" },
+ { "type": "desk", "pos": [7.0, 7.675], "rot": 180, "level": "upper" },
+ { "type": "rug", "pos": [7.3, 5.8], "size": [1.8, 1.4], "color": "#6b4a8c", "level": "upper" },
+ { "type": "plant", "pos": [5.45, 7.55], "level": "upper" },
+ { "type": "desk", "pos": [1.8, 0.35], "level": "upper" },
+ { "type": "bookshelf", "pos": [0.18, 2.0], "rot": 90, "width": 1.2, "level": "upper" },
+ { "type": "armchair", "pos": [2.7, 2.5], "rot": -150, "color": "#5d6b84", "level": "upper" },
+ { "type": "plant", "pos": [4.0, 3.0], "level": "upper" },
+ { "type": "bathtub", "pos": [9.61, 1.7], "rot": 90, "level": "upper" },
+ { "type": "vanity", "pos": [7.2, 0.25], "level": "upper" },
+ { "type": "toilet", "pos": [6.53, 3.0], "rot": 90, "level": "upper" }
+ ],
+
+ "lights": [
+ { "id": "living.main", "name": "Ceiling", "room": "living", "type": "ceiling", "pos": [2.6, 5.7], "capabilities": ["brightness", "temp"] },
+ { "id": "living.floor", "name": "Floor lamp", "room": "living", "type": "floor", "pos": [0.5, 3.9] },
+ { "id": "kitchen.pendant", "name": "Pendant", "room": "kitchen", "type": "pendant", "pos": [7.6, 6.0], "capabilities": ["brightness", "temp"] },
+ { "id": "kitchen.strip", "name": "Counter", "room": "kitchen", "type": "strip", "pos": [9.55, 5.7], "rot": 90, "length": 2.4, "y": 1.4, "capabilities": ["brightness"] },
+ { "id": "hall.main", "name": "Ceiling", "room": "hall", "type": "ceiling", "pos": [4.3, 1.7], "capabilities": ["brightness"] },
+ { "id": "study.desk", "name": "Desk lamp", "room": "study", "type": "table", "pos": [1.2, 0.3], "y": 1.0 },
+ { "id": "wc.main", "name": "Ceiling", "room": "wc", "type": "ceiling", "pos": [8.1, 1.7] },
+ { "id": "bedroom.main", "name": "Ceiling", "room": "bedroom", "type": "ceiling", "pos": [2.6, 5.7], "capabilities": ["brightness", "temp"] },
+ { "id": "bedroom.left", "name": "Bedside left", "room": "bedroom", "type": "table", "pos": [0.2, 4.55] },
+ { "id": "bedroom.right", "name": "Bedside right", "room": "bedroom", "type": "table", "pos": [0.2, 6.85] },
+ { "id": "kids.main", "name": "Ceiling", "room": "kids", "type": "ceiling", "pos": [7.5, 5.7], "capabilities": ["brightness", "temp", "color"] },
+ { "id": "office.main", "name": "Ceiling", "room": "office", "type": "ceiling", "pos": [1.8, 1.7], "capabilities": ["brightness", "temp"] },
+ { "id": "landing.spots", "name": "Spots", "room": "landing", "type": "spots", "pos": [4.4, 1.7], "capabilities": ["brightness"] },
+ { "id": "bath.main", "name": "Ceiling", "room": "bath", "type": "ceiling", "pos": [8.1, 1.7], "capabilities": ["brightness", "temp"] }
+ ],
+
+ "acs": [
+ { "id": "living.ac", "name": "Living AC", "room": "living", "wall": "west", "pos": [0, 7.3], "y": 2.25 },
+ { "id": "bedroom.ac", "name": "Bedroom AC", "room": "bedroom", "wall": "north", "pos": [2.2, 3.4], "y": 2.25 }
+ ],
+
+ "scenes": [
+ { "id": "bright", "name": "Bright", "icon": "sun", "lights": { "*": { "on": true, "brightness": 1, "temp": 4200 } } },
+ { "id": "cozy", "name": "Cozy", "icon": "sofa", "lights": { "*": { "on": false }, "living.floor": { "on": true }, "kitchen.pendant": { "on": true, "brightness": 0.45, "temp": 2400 }, "kitchen.strip": { "on": true, "brightness": 0.6 }, "hall.main": { "on": true, "brightness": 0.3 }, "bedroom.left": { "on": true }, "kids.main": { "on": true, "brightness": 0.5, "color": "#7b5cff" }, "landing.spots": { "on": true, "brightness": 0.4 } } },
+ { "id": "night", "name": "Night", "icon": "moon", "lights": { "*": { "on": false }, "landing.spots": { "on": true, "brightness": 0.12 }, "bedroom.right": { "on": true } }, "acs": { "bedroom.ac": { "on": true, "target": 24, "sleep": true } } },
+ { "id": "away", "name": "Away", "icon": "door", "lights": { "*": { "on": false } }, "acs": { "*": { "on": false } } }
+ ]
+}
diff --git a/web/src/agent/plan-edit.js b/web/src/agent/plan-edit.js
index 283f661..ee5a40e 100644
--- a/web/src/agent/plan-edit.js
+++ b/web/src/agent/plan-edit.js
@@ -1,11 +1,11 @@
// Edits to the floor plan an AI asks for: small, checked operations on the plan as it is
// written on disk. Nothing here touches the page, so it runs (and is tested) under Node too.
-import { normalize, LIGHT_KINDS, FLOOR_KINDS, LINK_FIELDS, isLinked } from '../config.js';
+import { normalize, LIGHT_KINDS, FLOOR_KINDS, LINK_FIELDS, isLinked, levelsOf } from '../config.js';
import { FURNITURE_TYPES, footprint } from '../three/furniture.js';
export const SCENE_ICONS = ['sun', 'sofa', 'film', 'moon', 'door', 'bed', 'tv', 'sparkles'];
export const WALLS = ['north', 'south', 'east', 'west'];
-const FURNITURE_KEYS = ['type', 'pos', 'rot', 'width', 'height', 'size', 'color', 'chairs', 'stools', 'upper'];
+const FURNITURE_KEYS = ['type', 'pos', 'rot', 'width', 'height', 'depth', 'size', 'color', 'chairs', 'stools', 'upper', 'level'];
const LIGHT_KEYS = ['id', 'name', 'room', 'type', 'pos', 'y', 'rot', 'length', 'capabilities', 'color'];
const AC_KEYS = ['id', 'name', 'room', 'wall', 'pos', 'y', 'min', 'max'];
@@ -51,7 +51,7 @@ function cleanFurniture(item, where) {
const out = pick(item, FURNITURE_KEYS);
out.pos = out.pos.map(round);
if (out.rot != null) { if (!isNum(out.rot)) fail(`${where}: "rot" must be a number of degrees`); out.rot = Math.round(out.rot); }
- for (const k of ['width', 'height']) {
+ for (const k of ['width', 'height', 'depth']) {
if (out[k] != null && !(isNum(out[k]) && out[k] > 0.1 && out[k] < 12)) fail(`${where}: "${k}" must be metres between 0.1 and 12`);
}
if (out.size != null && !(isPoint(out.size) && out.size.every((v) => v > 0.1 && v < 15))) fail(`${where}: "size" must be [width, depth] in metres`);
@@ -64,11 +64,18 @@ function cleanFurniture(item, where) {
return out;
}
-function roomAt(plan, [x, z]) {
- return (plan.rooms || []).find((r) => x >= r.rect[0] - 0.01 && x <= r.rect[0] + r.rect[2] + 0.01
+// The room at a point; on a home with floors, only a room on `level` (when given) counts.
+function roomAt(plan, [x, z], level) {
+ const first = levelsOf(plan)[0].id;
+ return (plan.rooms || []).find((r) => (level == null || (r.level ?? first) === level)
+ && x >= r.rect[0] - 0.01 && x <= r.rect[0] + r.rect[2] + 0.01
&& z >= r.rect[1] - 0.01 && z <= r.rect[1] + r.rect[3] + 0.01);
}
+// The floor something is on: its own "level", else the first floor.
+const levelOf = (plan, item) => item?.level ?? levelsOf(plan)[0].id;
+const sameLevel = (plan, a, b) => levelOf(plan, a) === levelOf(plan, b);
+
function findById(list, id, what) {
const i = list.findIndex((d) => d.id === id);
if (i < 0) fail(`There is no ${what} with id "${id}". Ids: ${list.map((d) => d.id).join(', ') || 'none'}`);
@@ -124,10 +131,36 @@ export function applyOperations(raw, operations) {
if (typeof op.id !== 'string' || !/^[a-z0-9_.-]+$/i.test(op.id)) fail(`${where}: "id" must be a short word like "office"`);
if (plan.rooms.some((r) => r.id === op.id)) fail(`${where}: a room "${op.id}" already exists`);
if (op.floor != null && !FLOOR_KINDS.includes(op.floor)) fail(`${where}: "floor" must be one of ${FLOOR_KINDS.join(', ')}`);
- plan.rooms.push({ id: op.id, name: String(op.name || op.id), rect: checkRect(op.rect, where), floor: op.floor || 'oak' });
+ const room = { id: op.id, name: String(op.name || op.id), rect: checkRect(op.rect, where), floor: op.floor || 'oak' };
+ if (op.level != null) room.level = String(op.level);
+ plan.rooms.push(room);
changes.push(`added room ${op.name || op.id}`);
break;
}
+ case 'add_floor':
+ case 'update_floor': {
+ // A home on several floors: "levels", lowest first. Everything without "level" is on the first.
+ const adding = op.op === 'add_floor';
+ if (typeof op.id !== 'string' || !/^[a-z0-9_.-]+$/i.test(op.id)) fail(`${where}: "id" must be a short word like "upstairs"`);
+ if (!Array.isArray(plan.levels) || !plan.levels.length) {
+ plan.levels = [{ id: 'ground', name: 'Ground floor' }];
+ for (const key of ['rooms', 'furniture', 'openings']) for (const item of plan[key]) item.level ??= 'ground';
+ }
+ let floor = plan.levels.find((l) => l.id === op.id);
+ if (adding && floor) fail(`${where}: a floor "${op.id}" already exists`);
+ if (!adding && !floor) fail(`${where}: there is no floor "${op.id}". Floors: ${plan.levels.map((l) => l.id).join(', ')}`);
+ if (adding) {
+ floor = { id: op.id, name: String(op.name || op.id) };
+ if (op.below) plan.levels.unshift(floor); else plan.levels.push(floor);
+ }
+ if (op.name != null) floor.name = String(op.name).slice(0, 40);
+ if (op.wallHeight != null) {
+ if (!(isNum(op.wallHeight) && op.wallHeight > 1.8 && op.wallHeight < 6)) fail(`${where}: wallHeight must be 1.8–6 m`);
+ floor.wallHeight = op.wallHeight;
+ }
+ changes.push(`${adding ? 'added' : 'changed'} floor ${floor.name}`);
+ break;
+ }
case 'update_room': {
const room = plan.rooms[findById(plan.rooms, op.id, 'room')];
if (op.name != null) room.name = String(op.name);
@@ -137,7 +170,7 @@ export function applyOperations(raw, operations) {
const [dx, dz] = [rect[0] - room.rect[0], rect[1] - room.rect[1]];
if (op.moveContents !== false && (dx || dz)) {
const inside = (p) => roomAt({ rooms: [room] }, p);
- for (const f of plan.furniture) if (inside(f.pos)) f.pos = [round(f.pos[0] + dx), round(f.pos[1] + dz)];
+ for (const f of plan.furniture) if (sameLevel(plan, f, room) && inside(f.pos)) f.pos = [round(f.pos[0] + dx), round(f.pos[1] + dz)];
for (const d of [...plan.lights, ...plan.acs]) if (d.room === room.id) d.pos = [round(d.pos[0] + dx), round(d.pos[1] + dz)];
}
room.rect = rect;
@@ -154,7 +187,7 @@ export function applyOperations(raw, operations) {
const devices = [...plan.lights, ...plan.acs].filter((d) => d.room === op.id);
if (devices.some(isLinked)) fail(`${where}: this room has devices linked to real hardware; unlink them in the editor first`);
const room = plan.rooms[i];
- plan.furniture.forEach((f, k) => { if (k < originalFurniture && roomAt({ rooms: [room] }, f.pos)) dropFurniture.add(k); });
+ plan.furniture.forEach((f, k) => { if (k < originalFurniture && sameLevel(plan, f, room) && roomAt({ rooms: [room] }, f.pos)) dropFurniture.add(k); });
plan.lights = plan.lights.filter((d) => d.room !== op.id);
plan.acs = plan.acs.filter((d) => d.room !== op.id);
plan.rooms.splice(i, 1);
@@ -166,9 +199,10 @@ export function applyOperations(raw, operations) {
const room = plan.rooms[findById(plan.rooms, op.room, 'room')];
if (!Array.isArray(op.items)) fail(`${where}: "items" must be a list of furniture`);
plan.furniture.forEach((f, k) => {
- if (k < originalFurniture && Array.isArray(f.pos) && roomAt({ rooms: [room] }, f.pos)?.id === room.id) dropFurniture.add(k);
+ if (k < originalFurniture && Array.isArray(f.pos) && sameLevel(plan, f, room) && roomAt({ rooms: [room] }, f.pos)?.id === room.id) dropFurniture.add(k);
});
- op.items.forEach((item, k) => addFurniture.push(cleanFurniture(item, `${where}, item ${k + 1}`)));
+ // The new pieces stand on the room's floor.
+ op.items.forEach((item, k) => addFurniture.push(cleanFurniture(room.level && !item?.level ? { ...item, level: room.level } : item, `${where}, item ${k + 1}`)));
changes.push(`refurnished ${room.name} (${op.items.length} pieces)`);
break;
}
@@ -196,6 +230,7 @@ export function applyOperations(raw, operations) {
if (!isPoint(op.from) || !isPoint(op.to)) fail(`${where}: "from" and "to" must be [x, z] points on a wall`);
if (op.from[0] !== op.to[0] && op.from[1] !== op.to[1]) fail(`${where}: an opening must be horizontal or vertical`);
const o = { type, from: op.from.map(round), to: op.to.map(round) };
+ if (op.level != null) o.level = String(op.level);
if (type === 'window') { if (isNum(op.sill)) o.sill = op.sill; if (isNum(op.head)) o.head = op.head; }
plan.openings.push(o);
changes.push(`added a ${type}`);
@@ -268,7 +303,7 @@ export function applyOperations(raw, operations) {
break;
}
default:
- fail(`${where}: unknown operation. Use one of: set_home, add_room, update_room, remove_room, furnish_room, `
+ fail(`${where}: unknown operation. Use one of: set_home, add_floor, update_floor, add_room, update_room, remove_room, furnish_room, `
+ 'add_furniture, update_furniture, remove_furniture, add_opening, remove_opening, add_light, update_light, '
+ 'remove_light, add_ac, update_ac, remove_ac, add_scene, update_scene, remove_scene');
}
@@ -289,7 +324,7 @@ export function check(plan) {
const warnings = [];
plan.furniture.forEach((f, i) => {
if (!FURNITURE_TYPES.includes(f.type)) fail(`Furniture #${i} has unknown type "${f.type}"`);
- if (!roomAt(plan, f.pos)) warnings.push(`furniture #${i} (${f.type}) stands outside every room`);
+ if (!roomAt(plan, f.pos, levelOf(plan, f))) warnings.push(`furniture #${i} (${f.type}) stands outside every room of its floor`);
});
for (const d of [...plan.lights, ...plan.acs]) {
const room = plan.rooms.find((r) => r.id === d.room);
@@ -334,6 +369,7 @@ export const FURNITURE_GUIDE = {
desk: 'desk; option width',
wardrobe: 'wardrobe; options width, height',
bookshelf: 'open bookshelf with books; options width, height',
+ stairs: 'straight stairs up to the floor above, climbing towards the back (north at rot 0); options width, depth (its length)',
};
export function furnitureCatalog() {
diff --git a/web/src/agent/tools.js b/web/src/agent/tools.js
index bb7b728..c62c78a 100644
--- a/web/src/agent/tools.js
+++ b/web/src/agent/tools.js
@@ -248,6 +248,8 @@ export function createAgent({ store, config, raw, render, onAction }) {
size: { type: 'array', items: { type: 'number' }, description: 'rug only: [width, depth]' },
color: { type: 'string', description: '#rrggbb (sofa, armchair, rug, bed)' },
chairs: { type: 'integer' }, stools: { type: 'integer' }, upper: { type: 'boolean' },
+ depth: { type: 'number', description: 'stairs only: their length, metres' },
+ level: { type: 'string', description: 'on a home with floors: the id of the floor it stands on' },
},
};
@@ -343,9 +345,10 @@ export function createAgent({ store, config, raw, render, onAction }) {
title: 'Change the 3D floor plan',
description: 'Change the home\'s 3D model with a list of operations, applied together (all or nothing). The model on the user\'s screen updates at once, '
+ 'and the change can be undone with undo_floor_plan_edit. To rebuild a room from photos use one "furnish_room" operation with every piece you see. '
- + 'Operations: set_home{name,outdoorTemp,wallHeight}, add_room{id,name,rect,floor}, update_room{id,name,rect,floor}, remove_room{id}, '
+ + 'Operations: set_home{name,outdoorTemp,wallHeight}, add_floor{id,name,wallHeight,below}, update_floor{id,name,wallHeight}, '
+ + 'add_room{id,name,rect,floor,level}, update_room{id,name,rect,floor}, remove_room{id}, '
+ 'furnish_room{room,items[]}, add_furniture{item|items[]}, update_furniture{index,set{}}, remove_furniture{index}, '
- + 'add_opening{type,from,to,sill,head}, remove_opening{index}, add_light{id,name,room,type,pos,capabilities,y,rot,length,color}, '
+ + 'add_opening{type,from,to,sill,head,level}, remove_opening{index}, add_light{id,name,room,type,pos,capabilities,y,rot,length,color}, '
+ 'update_light{id,set{}}, remove_light{id}, add_ac{id,name,room,wall,pos,y,min,max}, update_ac{id,set{}}, remove_ac{id}, '
+ 'add_scene{id,name,icon,lights{},acs{}}, update_scene{id,set{}}, remove_scene{id}. '
+ 'Indexes are those from get_floor_plan, before this edit.',
@@ -357,12 +360,14 @@ export function createAgent({ store, config, raw, render, onAction }) {
items: {
type: 'object', required: ['op'],
properties: {
- op: { type: 'string', enum: ['set_home', 'add_room', 'update_room', 'remove_room', 'furnish_room', 'add_furniture',
+ op: { type: 'string', enum: ['set_home', 'add_floor', 'update_floor', 'add_room', 'update_room', 'remove_room', 'furnish_room', 'add_furniture',
'update_furniture', 'remove_furniture', 'add_opening', 'remove_opening', 'add_light', 'update_light', 'remove_light',
'add_ac', 'update_ac', 'remove_ac', 'add_scene', 'update_scene', 'remove_scene'] },
id: { type: 'string' }, name: { type: 'string' }, room: { type: 'string' },
rect: { type: 'array', items: { type: 'number' }, description: '[x, z, width, depth] in metres' },
- floor: { type: 'string', enum: FLOOR_KINDS },
+ floor: { type: 'string', enum: FLOOR_KINDS, description: 'flooring of a room' },
+ level: { type: 'string', description: 'id of the floor (storey) a room or opening is on, from "levels"' },
+ wallHeight: { type: 'number' }, below: { type: 'boolean', description: 'add_floor: under the others (a basement)' },
items: { type: 'array', items: FURNITURE_ITEM },
item: FURNITURE_ITEM,
index: { type: 'integer' },
@@ -674,4 +679,7 @@ const PLAN_RULES = `Floor plan rules:
- Openings: doors, windows and open gaps sit on walls, given by two end points "from"/"to" on that wall line.
- Lights: "type" ceiling, pendant, spots, floor, table or strip; "capabilities" any of brightness, temp, color (none = plain switch).
- Air conditioners hang on a wall: "wall" north/south/east/west and "pos" on that wall line.
-- Devices marked "linked": true are real hardware: keep their ids, do not remove them.`;
+- Devices marked "linked": true are real hardware: keep their ids, do not remove them.
+- A home on several floors lists them in "levels", lowest first; rooms, furniture and openings carry "level" (the floor's id),
+ lamps and ACs are on their room's floor. Every floor uses the same x/z grid, so an upper room sits right above the one under it.
+ Without "levels" everything is on one floor. Stairs are furniture ("type": "stairs") on the lower floor.`;
diff --git a/web/src/config.js b/web/src/config.js
index 377a9e0..ab19ccc 100644
--- a/web/src/config.js
+++ b/web/src/config.js
@@ -30,6 +30,16 @@ export const SERVICES = {
};
export const FLOOR_KINDS = ['oak', 'walnut', 'tile', 'stone'];
+// A home on several floors lists them in "levels", lowest first: [{ id, name, wallHeight? }].
+// Rooms, furniture and openings say which one they are on with "level"; lamps and ACs are on
+// their room's. Without "levels" (or without "level" on an item) everything is on the first.
+export const SLAB = 0.3; // thickness of the floor between two levels, metres
+
+export function levelsOf(raw) {
+ const list = Array.isArray(raw?.levels) ? raw.levels.filter((l) => l && typeof l.id === 'string' && l.id) : [];
+ return list.length ? list : [{ id: 'main', name: 'Ground floor' }];
+}
+
// The plan exactly as written on disk (the editor works on this form).
export async function loadRawConfig() {
const boot = window.__HOUSE_BOOT__;
@@ -65,20 +75,39 @@ export function normalize(raw) {
ids.add(id);
};
+ const wallHeight = raw.wallHeight ?? 2.6;
+ const levelIds = new Set();
+ let elevation = 0;
+ const levels = levelsOf(raw).map((l) => {
+ need(!levelIds.has(l.id), `Duplicate floor id "${l.id}"`);
+ levelIds.add(l.id);
+ const H = Number.isFinite(l.wallHeight) && l.wallHeight > 0 ? l.wallHeight : wallHeight;
+ const level = { id: l.id, name: l.name || l.id, wallHeight: H, elevation };
+ elevation += H + SLAB;
+ return level;
+ });
+ const ground = levels[0].id;
+ const levelOf = (item, what) => {
+ if (item.level == null) return ground;
+ need(levelIds.has(item.level), `${what} is on unknown floor "${item.level}"`);
+ return item.level;
+ };
+
const rooms = raw.rooms.map((r) => {
unique(r.id, 'A room');
need(Array.isArray(r.rect) && r.rect.length === 4 && r.rect.every(Number.isFinite),
`Room "${r.id}" needs "rect": [x, z, width, depth]`);
const [x, z, w, d] = r.rect;
need(w > 0 && d > 0, `Room "${r.id}" has an empty rect`);
- return { id: r.id, name: r.name || r.id, x, z, w, d, floor: r.floor || 'oak' };
+ return { id: r.id, name: r.name || r.id, x, z, w, d, floor: r.floor || 'oak', level: levelOf(r, `Room "${r.id}"`) };
});
const roomIds = new Set(rooms.map((r) => r.id));
+ const roomLevel = new Map(rooms.map((r) => [r.id, r.level]));
const openings = (raw.openings || []).map((o, i) => {
need(isPoint(o.from) && isPoint(o.to), `Opening #${i + 1} needs "from" and "to" points`);
need(o.from[0] === o.to[0] || o.from[1] === o.to[1], `Opening #${i + 1} must be axis-aligned`);
- return { type: o.type || 'door', from: o.from, to: o.to, sill: o.sill ?? 0.85, head: o.head ?? 2.1 };
+ return { type: o.type || 'door', from: o.from, to: o.to, sill: o.sill ?? 0.85, head: o.head ?? 2.1, level: levelOf(o, `Opening #${i + 1}`) };
});
const lights = (raw.lights || []).map((l) => {
@@ -91,6 +120,7 @@ export function normalize(raw) {
name: l.name || l.id,
rot: l.rot || 0,
capabilities: l.capabilities || [], // plain smart plugs: on/off only
+ level: roomLevel.get(l.room),
};
});
@@ -99,7 +129,7 @@ export function normalize(raw) {
need(roomIds.has(a.room), `AC "${a.id}" refers to unknown room "${a.room}"`);
need(isPoint(a.pos), `AC "${a.id}" needs "pos": [x, z]`);
need(WALLS.includes(a.wall), `AC "${a.id}" needs "wall": one of ${WALLS.join(', ')}`);
- return { ...a, name: a.name || a.id, y: a.y ?? 2.2, min: a.min ?? 16, max: a.max ?? 30 };
+ return { ...a, name: a.name || a.id, y: a.y ?? 2.2, min: a.min ?? 16, max: a.max ?? 30, level: roomLevel.get(a.room) };
});
const scenes = (raw.scenes || []).map((s) => {
@@ -107,23 +137,39 @@ export function normalize(raw) {
return { id: s.id, name: s.name || s.id, icon: s.icon || 'sun', lights: s.lights || {}, acs: s.acs || {} };
});
- const minX = Math.min(...rooms.map((r) => r.x));
- const minZ = Math.min(...rooms.map((r) => r.z));
- const maxX = Math.max(...rooms.map((r) => r.x + r.w));
- const maxZ = Math.max(...rooms.map((r) => r.z + r.d));
+ const furniture = (raw.furniture || []).map((f, i) => {
+ const level = levelOf(f, `Furniture #${i + 1}`);
+ // Stairs climb to the floor above unless told otherwise.
+ const H = levels.find((l) => l.id === level).wallHeight;
+ return f.type === 'stairs' && f.height == null ? { ...f, level, height: H + SLAB } : { ...f, level };
+ });
+
+ const box = (rs) => ({
+ minX: Math.min(...rs.map((r) => r.x)),
+ minZ: Math.min(...rs.map((r) => r.z)),
+ maxX: Math.max(...rs.map((r) => r.x + r.w)),
+ maxZ: Math.max(...rs.map((r) => r.z + r.d)),
+ });
+ // A floor with no rooms yet borrows the outline of the whole home.
+ const all = box(rooms);
+ for (const l of levels) {
+ const own = rooms.filter((r) => r.level === l.id);
+ l.bounds = own.length ? box(own) : all;
+ }
return {
name: raw.name || 'Home',
- wallHeight: raw.wallHeight ?? 2.6,
+ wallHeight,
interiorWallHeight: raw.interiorWallHeight ?? 1.25,
camera: { azimuth: raw.camera?.azimuth ?? 34, elevation: raw.camera?.elevation ?? 47 },
outdoorTemp: raw.outdoorTemp ?? 27,
+ levels,
rooms,
openings,
- furniture: raw.furniture || [],
+ furniture,
lights,
acs,
scenes,
- bounds: { minX, minZ, maxX, maxZ },
+ bounds: all,
};
}
diff --git a/web/src/editor/editor.css b/web/src/editor/editor.css
index 6e29e62..1097e27 100644
--- a/web/src/editor/editor.css
+++ b/web/src/editor/editor.css
@@ -1,8 +1,10 @@
html.mode-editor body { background: var(--bg); overflow: hidden; }
-html.mode-editor #app { padding: 0; display: block; }
+/* place-items from the panel's #app would shrink the editor where block layout honours it (Chrome, Android). */
+html.mode-editor #app { padding: 0; display: block; place-items: normal; }
html.mode-editor, html.mode-editor body { user-select: none; }
.editor {
+ width: 100%;
height: 100%;
display: grid;
grid-template-columns: 268px minmax(0, 1fr) 340px;
@@ -120,7 +122,95 @@ html.mode-editor, html.mode-editor body { user-select: none; }
.p-light.sel circle:not(.halo), .p-light.sel rect { stroke: #fff; stroke-width: 0.08; }
.p-light.sel .halo { fill: rgba(255, 255, 255, 0.2); }
-.p-handle { fill: #6aa6ff; stroke: #fff; stroke-width: 0.05; cursor: nwse-resize; }
+.p-handle { fill: #6aa6ff; stroke: #fff; vector-effect: non-scaling-stroke; stroke-width: 1.5px; }
+.p-handle.nw, .p-handle.se, .grab.nw, .grab.se { cursor: nwse-resize; }
+.p-handle.ne, .p-handle.sw, .grab.ne, .grab.sw { cursor: nesw-resize; }
+.p-handle.n, .p-handle.s, .grab.n, .grab.s { cursor: ns-resize; }
+.p-handle.e, .p-handle.w, .grab.e, .grab.w { cursor: ew-resize; }
+.hit.grab { fill: transparent; stroke: none; }
+.p-guide { stroke: #ff6ad5; stroke-width: 1px; vector-effect: non-scaling-stroke; stroke-dasharray: 5 4; pointer-events: none; }
+
+/* the floor under the one being edited */
+.p-ghost { pointer-events: none; }
+.p-ghost rect { fill: rgba(255, 255, 255, 0.025); stroke: rgba(160, 190, 255, 0.4); stroke-width: 1px; vector-effect: non-scaling-stroke; stroke-dasharray: 6 5; }
+.p-ghost-label { text-anchor: middle; font: 600 0.22px -apple-system, system-ui, sans-serif; fill: rgba(160, 190, 255, 0.38); }
+.p-ghost .p-ghost-stairs { fill: rgba(160, 190, 255, 0.12); stroke-dasharray: none; }
+.p-ghost-step, .p-ghost-arrow { stroke: rgba(160, 190, 255, 0.5); stroke-width: 1px; vector-effect: non-scaling-stroke; fill: none; }
+
+.p-furn.stairs rect { fill: rgba(217, 212, 203, 0.16); stroke: rgba(255, 255, 255, 0.5); }
+.p-stairs-step { stroke: rgba(255, 255, 255, 0.35); stroke-width: 0.02; pointer-events: none; }
+.p-stairs-arrow { stroke: #ffd38a; stroke-width: 0.05; stroke-linecap: round; stroke-linejoin: round; fill: none; pointer-events: none; }
+.p-furn.stairs.sel rect { fill: rgba(90, 150, 255, 0.28); }
+
+.plan.can-pan, .plan.can-pan * { cursor: grab !important; }
+.plan.panning, .plan.panning * { cursor: grabbing !important; }
+
+/* ---------- floors, zoom and the add bar, over the plan ---------- */
+
+.levels {
+ position: absolute; left: 12px; top: 12px; z-index: 3; max-width: calc(100% - 24px);
+ display: flex; gap: 3px; padding: 3px; border-radius: 13px; overflow-x: auto; scrollbar-width: none;
+ background: rgba(16, 21, 36, 0.82); border: 1px solid var(--line);
+ -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px);
+}
+.levels::-webkit-scrollbar { display: none; }
+.level-tab, .level-add {
+ flex: none; height: 30px; padding: 0 11px; border-radius: 10px; display: inline-flex; align-items: center; gap: 7px;
+ font-size: 12.5px; font-weight: 600; color: var(--muted); white-space: nowrap;
+ transition: background 160ms, color 160ms, transform 200ms var(--spring);
+}
+.level-tab:hover, .level-add:hover { background: var(--glass-hi); color: var(--text); }
+.level-tab:active, .level-add:active { transform: scale(0.95); }
+.level-tab .n { font-size: 10.5px; font-weight: 700; color: var(--faint); }
+.level-tab.active { color: #fff; background: rgba(70, 130, 255, 0.5); }
+.level-tab.active .n { color: rgba(255, 255, 255, 0.7); }
+.level-add { color: #8fbaff; padding: 0 10px; }
+
+.zoom {
+ position: absolute; right: 12px; bottom: 12px; z-index: 3; display: flex; flex-direction: column; gap: 2px; padding: 3px;
+ border-radius: 12px; background: rgba(16, 21, 36, 0.82); border: 1px solid var(--line);
+ -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px);
+}
+.zoom button { width: 30px; height: 30px; border-radius: 9px; display: grid; place-items: center; color: var(--muted); }
+.zoom button:hover { background: var(--glass-hi); color: var(--text); }
+
+.add-bar {
+ position: absolute; left: 50%; bottom: 12px; z-index: 3; transform: translateX(-50%); max-width: calc(100% - 124px);
+ display: flex; gap: 2px; padding: 4px; border-radius: 15px; overflow-x: auto; scrollbar-width: none;
+ background: rgba(16, 21, 36, 0.86); border: 1px solid var(--line); box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.6);
+ -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px);
+}
+.add-bar::-webkit-scrollbar { display: none; }
+.add-bar button {
+ flex: none; min-width: 56px; height: 50px; padding: 0 8px; border-radius: 11px;
+ display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
+ font-size: 10.5px; font-weight: 600; color: var(--muted);
+ transition: background 140ms, color 140ms, transform 200ms var(--spring);
+}
+.add-bar button:hover { background: rgba(70, 130, 255, 0.25); color: #fff; }
+.add-bar button:active { transform: scale(0.94); }
+
+.empty-card {
+ position: absolute; left: 50%; top: 50%; z-index: 3; transform: translate(-50%, -50%); width: min(340px, calc(100% - 32px));
+ padding: 18px; border-radius: 18px; text-align: center;
+ background: rgba(16, 21, 36, 0.9); border: 1px solid var(--line); box-shadow: 0 16px 40px -14px rgba(0, 0, 0, 0.7);
+ -webkit-backdrop-filter: blur(14px); backdrop-filter: blur(14px);
+}
+.empty-card[hidden] { display: none; }
+.empty-card b { font-size: 14px; }
+.empty-card p { margin: 6px 0 14px; color: var(--muted); line-height: 1.45; }
+.empty-actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
+
+.level-row .icon { flex: none; color: var(--faint); }
+.level-row.current .icon { color: #8fbaff; }
+.level-row.current .row-name { color: var(--text); }
+
+dl.keys { margin: 0; font-size: 12px; line-height: 1.4; }
+dl.keys dt { color: var(--text); font-weight: 600; margin-top: 7px; }
+dl.keys dt:first-child { margin-top: 0; }
+dl.keys dd { margin: 0; color: var(--muted); }
+.btn.danger { color: #ff9a90; }
+.btn.danger[data-armed] { color: #fff; background: rgba(220, 60, 50, 0.7); border-color: rgba(255, 120, 110, 0.6); }
/* ---------- right column ---------- */
@@ -319,8 +409,14 @@ html.ios.mode-editor body { background: var(--bg); }
-webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
}
.p-float:active { color: var(--text); transform: scale(0.94); }
+.editor.phone .levels { right: auto; max-width: calc(100% - 76px); padding: 3px; border-radius: 14px; }
+.editor.phone .level-tab, .editor.phone .level-add { height: 34px; font-size: 13.5px; border-radius: 11px; }
+.editor.phone .empty-card { font-size: 14px; }
+.editor.phone .empty-actions .btn { height: 40px; font-size: 14px; }
+.canvas.show-3d .empty-card { visibility: hidden; }
+.canvas.show-3d .levels { z-index: 4; }
.p-issue {
- position: absolute; left: 12px; right: 60px; top: 12px; display: none; padding: 9px 12px; border-radius: 12px;
+ position: absolute; left: 12px; right: 60px; top: 60px; display: none; padding: 9px 12px; border-radius: 12px;
font-size: 13px; line-height: 1.35; color: #ffd2cc; background: rgba(80, 22, 22, 0.88); border: 1px solid rgba(255, 120, 110, 0.5);
}
.p-issue.show { display: block; }
@@ -395,9 +491,9 @@ html.ios.mode-editor body { background: var(--bg); }
position: absolute; left: 0; right: 0; bottom: 0; z-index: 8; max-height: calc(100% - var(--safe-top) - 40px);
display: flex; flex-direction: column; padding: 0 0 var(--safe-bottom);
background: #141a2b; border-radius: 22px 22px 0 0; border-top: 1px solid rgba(255, 255, 255, 0.12);
- transform: translateY(105%); transition: transform 340ms var(--ease);
+ transform: translateY(105%); transition: transform 340ms var(--ease); pointer-events: none;
}
-.p-modal.open { transform: none; }
+.p-modal.open { transform: none; pointer-events: auto; }
.p-modal-head { flex: none; display: flex; align-items: center; justify-content: space-between; padding: 16px 18px 8px; }
.p-modal-head b { font-size: 17px; font-weight: 650; }
.p-text { font-size: 16px; font-weight: 600; color: #7fb2ff; padding: 6px 2px; }
diff --git a/web/src/editor/editor.js b/web/src/editor/editor.js
index dc52514..45f1378 100644
--- a/web/src/editor/editor.js
+++ b/web/src/editor/editor.js
@@ -3,7 +3,7 @@
// real devices. On a phone the same pieces are laid out for a finger: the plan fills the
// screen, the inspector is a sheet from the bottom, pinch zooms and drag pans.
import './editor.css';
-import { normalize, loadRawConfig, LIGHT_KINDS, FLOOR_KINDS, isLinked } from '../config.js';
+import { normalize, loadRawConfig, LIGHT_KINDS, FLOOR_KINDS, isLinked, levelsOf } from '../config.js';
import { createWorld } from '../three/world.js';
import { FURNITURE_TYPES, footprint } from '../three/furniture.js';
import { h, clamp } from '../ui/dom.js';
@@ -23,6 +23,9 @@ const KEYS = { room: 'rooms', light: 'lights', ac: 'acs', furniture: 'furniture'
const TITLES = { room: 'Rooms', light: 'Lights', ac: 'Air conditioners', furniture: 'Furniture', opening: 'Doors & windows', scene: 'Scenes' };
const FLOOR_FILL = { oak: '#4a3d2e', walnut: '#3c2f28', tile: '#39424b', stone: '#30353c' };
const WALLS = ['north', 'east', 'south', 'west'];
+const LEVEL_NAMES = ['Ground floor', 'First floor', 'Second floor', 'Third floor', 'Fourth floor', 'Fifth floor'];
+const HANDLES = { nw: [0, 0], n: [0.5, 0], ne: [1, 0], e: [1, 0.5], se: [1, 1], s: [0.5, 1], sw: [0, 1], w: [0, 0.5] };
+const MIN_ROOM = 0.6; // metres, either way
const SCENE_ICONS = ['sun', 'sofa', 'film', 'moon', 'door', 'table', 'bed', 'tv', 'sparkles'];
const REGIONS = [
['eu', 'Central Europe'], ['eu-w', 'Western Europe'], ['us', 'Western America'], ['us-e', 'Eastern America'],
@@ -47,6 +50,8 @@ export async function bootEditor(root) {
let world = null;
let phone = null; // the iPhone's layout and gestures, set up by buildPhoneLayout()
let previewLights = true;
+ let level = levelsOf(doc)[0].id; // the floor being edited
+ let view = null; // the part of the plan on show, a box in metres, or null to fit the floor
const undo = [];
const redo = [];
const tuya = {
@@ -75,8 +80,10 @@ export async function bootEditor(root) {
nameInput.addEventListener('input', () => { snapshot('name'); doc.name = nameInput.value; touch({ inspector: sel.kind === 'home' }); });
const status = h('div.status');
const saveBtn = h('button.btn.primary', { onclick: save }, icon('check', 15, 2.4), 'Save & apply');
- const hint = h('div.hint', isPhone ? 'Tap to select · drag what is selected · pinch to zoom'
- : 'Drag rooms, lamps and furniture · drag a room’s corner to resize · everything snaps to 5 cm');
+ const hint = h('div.hint', 'Tap to select · drag what is selected · pinch to zoom');
+ const levelBar = h('div.levels', { role: 'tablist', 'aria-label': 'Floors' });
+ // An empty floor says how to start it.
+ const emptyCard = h('div.empty-card');
const toastEl = h('div.toast');
const sidebar = h('aside.side');
@@ -96,7 +103,7 @@ export async function bootEditor(root) {
h('button.btn', { onclick: exportPlan }, 'Export…'),
saveBtn)),
sidebar,
- h('main.canvas', plan, hint),
+ h('main.canvas', plan, levelBar, emptyCard, addBar(), zoomBar()),
h('aside.right', h('div.preview-wrap', previewHost, previewToggle), inspector),
h('footer.foot', status),
toastEl));
@@ -117,7 +124,9 @@ export async function bootEditor(root) {
to.push(JSON.stringify(doc));
doc = JSON.parse(from.pop());
lastSnapshotKey = null;
+ checkLevel();
if (sel.index != null && !doc[KEYS[sel.kind]]?.[sel.index]) sel = { kind: 'home' };
+ if (sel.kind === 'level' && !levelList().some((l) => l.id === sel.id)) sel = { kind: 'home' };
nameInput.value = doc.name || '';
touch();
}
@@ -132,6 +141,10 @@ export async function bootEditor(root) {
}
function select(next) {
+ // Something on another floor (picked in the list or a scene's rules): that floor comes up.
+ const item = next.index != null ? doc[KEYS[next.kind]]?.[next.index] : null;
+ const on = item && levelOf(next.kind, item);
+ if (on && on !== level) { level = on; view = null; world?.setLevel(level); }
sel = next;
lastSnapshotKey = null;
renderSidebar();
@@ -147,6 +160,271 @@ export async function bootEditor(root) {
toast.timer = setTimeout(() => { toastEl.className = 'toast'; }, 2600);
}
+ /* ---------- floors ---------- */
+
+ const levelList = () => levelsOf(doc);
+ const firstLevel = () => levelList()[0].id;
+ const levelName = (id) => levelList().find((l) => l.id === id)?.name || id;
+ const roomLevel = (id) => doc.rooms.find((r) => r.id === id)?.level ?? firstLevel();
+ const levelRooms = (id = level) => doc.rooms.filter((r) => (r.level ?? firstLevel()) === id);
+ // The floor an item is on; null for a scene, which is for the whole home.
+ function levelOf(kind, item) {
+ if (kind === 'light' || kind === 'ac') return roomLevel(item.room);
+ if (kind === 'room' || kind === 'furniture' || kind === 'opening') return item.level ?? firstLevel();
+ return null;
+ }
+ const here = (kind, item) => { const l = levelOf(kind, item); return l == null || l === level; };
+ // New things on a home with floors say which one they are on.
+ const stamp = (item) => (Array.isArray(doc.levels) && doc.levels.length ? { ...item, level } : item);
+ // The floor right under the one being edited, drawn faintly to line things up with.
+ function below(id = level) {
+ const list = levelList();
+ const i = list.findIndex((l) => l.id === id);
+ return i > 0 ? list[i - 1] : null;
+ }
+ const outline = (rooms) => rooms.length && {
+ minX: Math.min(...rooms.map((r) => r.rect[0])), minZ: Math.min(...rooms.map((r) => r.rect[1])),
+ maxX: Math.max(...rooms.map((r) => r.rect[0] + r.rect[2])), maxZ: Math.max(...rooms.map((r) => r.rect[1] + r.rect[3])),
+ };
+
+ function checkLevel() {
+ if (!levelList().some((l) => l.id === level)) level = firstLevel();
+ }
+
+ function setLevel(id) {
+ if (id === level || !levelList().some((l) => l.id === id)) return;
+ level = id;
+ view = null;
+ const item = sel.index != null ? doc[KEYS[sel.kind]]?.[sel.index] : null;
+ if (item && !here(sel.kind, item)) sel = { kind: 'home' };
+ if (sel.kind === 'level') sel = { kind: 'level', id };
+ lastSnapshotKey = null;
+ renderSidebar();
+ renderPlan();
+ renderInspector();
+ world?.setLevel(level);
+ haptic('tick');
+ }
+
+ // Before the floors change, everything says which one it is on (without "levels" in the
+ // plan, or "level" on an item, it is on the first floor, and the first may be about to change).
+ function pinLevels() {
+ const first = firstLevel();
+ for (const key of ['rooms', 'furniture', 'openings']) for (const item of doc[key]) item.level ??= first;
+ }
+
+ // Back to a home on one floor: the plan looks as if it never had floors.
+ function unpinLevels() {
+ delete doc.levels;
+ for (const key of ['rooms', 'furniture', 'openings']) for (const item of doc[key]) delete item.level;
+ level = firstLevel();
+ }
+
+ function addLevel(where = 'above') {
+ snapshot();
+ if (!Array.isArray(doc.levels) || !doc.levels.length) {
+ const name = levelList()[0].name;
+ doc.levels = [{ id: 'ground', name }];
+ level = 'ground';
+ }
+ pinLevels();
+ const ids = new Set(doc.levels.map((l) => l.id));
+ let n = doc.levels.length + 1;
+ while (ids.has(`floor${n}`)) n++;
+ const id = `floor${n}`;
+ const name = where === 'below' ? 'Basement' : LEVEL_NAMES[doc.levels.length] || `Floor ${doc.levels.length + 1}`;
+ doc.levels.splice(where === 'below' ? 0 : doc.levels.length, 0, { id, name });
+ level = id;
+ view = null;
+ sel = { kind: 'level', id };
+ world?.dispose();
+ world = null;
+ touch();
+ toast(`${name} added`);
+ }
+
+ function removeLevel(id) {
+ if (levelList().length < 2) return;
+ snapshot();
+ pinLevels();
+ const gone = new Set(levelRooms(id).map((r) => r.id));
+ dropRooms(gone);
+ doc.furniture = doc.furniture.filter((f) => f.level !== id);
+ doc.openings = doc.openings.filter((o) => o.level !== id);
+ const name = levelName(id);
+ doc.levels = doc.levels.filter((l) => l.id !== id);
+ if (doc.levels.length === 1) unpinLevels();
+ checkLevel();
+ sel = { kind: 'home' };
+ view = null;
+ touch();
+ toast(`${name} removed · ${isPhone ? 'Undo' : '⌘Z'} brings it back`);
+ }
+
+ function moveLevel(id, step) {
+ pinLevels();
+ const list = doc.levels;
+ const i = list.findIndex((l) => l.id === id);
+ const j = i + step;
+ if (i < 0 || j < 0 || j >= list.length) return;
+ snapshot();
+ [list[i], list[j]] = [list[j], list[i]];
+ touch();
+ }
+
+ // An opening on a wall only one room of the floor has (an outside wall).
+ function outside(o, rooms) {
+ const mid = [(o.from[0] + o.to[0]) / 2, (o.from[1] + o.to[1]) / 2];
+ const on = (r) => {
+ const [x, z, w, d] = r.rect;
+ const inX = mid[0] >= x - 1e-3 && mid[0] <= x + w + 1e-3;
+ const inZ = mid[1] >= z - 1e-3 && mid[1] <= z + d + 1e-3;
+ return inX && inZ && (Math.abs(mid[0] - x) < 1e-3 || Math.abs(mid[0] - x - w) < 1e-3
+ || Math.abs(mid[1] - z) < 1e-3 || Math.abs(mid[1] - z - d) < 1e-3);
+ };
+ return rooms.filter(on).length < 2;
+ }
+
+ // The rooms of the floor below, copied up: the same walls, windows and inner doors.
+ function copyRoomsFromBelow(id = level) {
+ const from = below(id);
+ if (!from) return;
+ snapshot();
+ pinLevels();
+ const rooms = levelRooms(from.id);
+ for (const r of rooms) {
+ doc.rooms.push({ id: uniqueId(`${r.id}.${id}`.replace(/[^a-z0-9.]+/gi, '')), name: r.name, rect: [...r.rect], floor: r.floor, level: id });
+ }
+ for (const o of doc.openings.filter((x) => x.level === from.id)) {
+ if (o.type === 'door' && outside(o, rooms)) continue; // the front door stays downstairs
+ doc.openings.push({ ...structuredClone(o), level: id });
+ }
+ view = null;
+ touch();
+ toast(`${rooms.length} rooms copied from ${from.name}`);
+ }
+
+ // One room as big as the floor below (or the whole home), to divide up.
+ function fillLevel(id = level) {
+ snapshot();
+ pinLevels();
+ const b = outline(below(id) ? levelRooms(below(id).id) : doc.rooms) || { minX: 0, minZ: 0, maxX: 6, maxZ: 4 };
+ doc.rooms.push({
+ id: uniqueId('room'), name: 'New room', rect: [b.minX, b.minZ, fix(b.maxX - b.minX), fix(b.maxZ - b.minZ)], floor: 'oak',
+ ...(Array.isArray(doc.levels) ? { level: id } : {}),
+ });
+ sel = { kind: 'room', index: doc.rooms.length - 1 };
+ view = null;
+ touch();
+ }
+
+ function renderLevels() {
+ const list = levelList();
+ levelBar.replaceChildren(
+ ...list.map((l) => h(`button.level-tab${l.id === level ? '.active' : ''}`, {
+ role: 'tab', 'aria-selected': String(l.id === level),
+ title: l.id === level ? `${l.name} · click for its settings` : `Edit ${l.name}`,
+ onclick: () => { if (l.id === level) select({ kind: 'level', id: l.id }); else setLevel(l.id); },
+ }, l.name, h('span.n', levelRooms(l.id).length))),
+ h('button.level-add', { title: 'Add a floor', 'aria-label': 'Add a floor', onclick: () => addLevel() }, icon('plus', 14, 2.4), isPhone ? null : 'Floor'));
+ levelBar.querySelector('.active')?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
+
+ const empty = !levelRooms().length;
+ emptyCard.hidden = !empty;
+ if (empty) {
+ const under = below();
+ emptyCard.replaceChildren(h('b', `${levelName(level)} is empty`),
+ h('p', under ? `Copy the rooms of ${under.name}, or start with one room as big as it and divide it up.` : 'Add a room to start.'),
+ h('div.empty-actions',
+ under ? h('button.btn.primary', { onclick: () => copyRoomsFromBelow() }, icon('copy', 14, 2.2), `Copy ${under.name}`) : null,
+ h('button.btn', { onclick: () => fillLevel() }, icon('room', 14, 2.2), under ? 'One big room' : 'Add a room')));
+ }
+ }
+
+ /* ---------- view: what part of the plan is on show ---------- */
+
+ function bounds() {
+ const b = outline(levelRooms()) || outline(below() ? levelRooms(below().id) : []) || outline(doc.rooms);
+ return b || { minX: 0, minZ: 0, maxX: 6, maxZ: 4 };
+ }
+
+ // The floor fitted into the plan's box, clear of the bars over it.
+ function fitBox() {
+ const b = bounds();
+ const rect = plan.getBoundingClientRect();
+ const W = rect.width || 390;
+ const H = rect.height || 600;
+ // On a phone the sides stay clear of the system's back gesture, so the handles there can be grabbed.
+ const pad = isPhone ? { top: 64, side: 34, bottom: 24 } : { top: 64, side: 56, bottom: 84 };
+ const scale = Math.max(1, Math.min((W - pad.side * 2) / (b.maxX - b.minX), (H - pad.top - pad.bottom) / (b.maxZ - b.minZ)));
+ const w = W / scale;
+ const hh = H / scale;
+ const midY = pad.top + (H - pad.top - pad.bottom) / 2;
+ return { x: (b.minX + b.maxX) / 2 - w / 2, y: (b.minZ + b.maxZ) / 2 - midY / scale, w, h: hh };
+ }
+
+ const box = () => view || fitBox();
+
+ function applyView() {
+ if (view) {
+ // The plan's box changed shape (a sheet came up, the window was resized): keep the middle and the zoom.
+ const rect = plan.getBoundingClientRect();
+ const hh = rect.width ? view.w * rect.height / rect.width : view.h;
+ view = { ...view, y: view.y + (view.h - hh) / 2, h: hh };
+ }
+ const v = box();
+ plan.setAttribute('viewBox', `${v.x} ${v.y} ${v.w} ${v.h}`);
+ }
+ new ResizeObserver(() => applyView()).observe(plan);
+
+ // Zooms by `factor` (above 1 is closer) keeping the plan point under (cx, cy) where it is.
+ function zoomAt(factor, cx, cy) {
+ const rect = plan.getBoundingClientRect();
+ const v = box();
+ const fit = fitBox();
+ const w = clamp(v.w / factor, 1.6, Math.max(fit.w * 3, 30));
+ const hh = w * rect.height / rect.width;
+ const fx = (cx - rect.left) / rect.width;
+ const fy = (cy - rect.top) / rect.height;
+ view = { x: v.x + fx * v.w - fx * w, y: v.y + fy * v.h - fy * hh, w, h: hh };
+ applyView();
+ }
+ function zoomBy(factor) {
+ const rect = plan.getBoundingClientRect();
+ zoomAt(factor, rect.left + rect.width / 2, rect.top + rect.height / 2);
+ }
+ // Shows the whole floor again.
+ function reveal() { view = null; applyView(); }
+
+ // How many metres a few screen pixels are: snapping reaches as far.
+ const pixels = (px) => px / (plan.getScreenCTM()?.a || 60);
+
+ function zoomBar() {
+ return h('div.zoom',
+ h('button', { title: 'Zoom in (⌘+ or pinch)', 'aria-label': 'Zoom in', onclick: () => zoomBy(1.35) }, icon('zoomIn', 16, 2)),
+ h('button', { title: 'Zoom out', 'aria-label': 'Zoom out', onclick: () => zoomBy(1 / 1.35) }, icon('zoomOut', 16, 2)),
+ h('button', { title: 'Show the whole floor (⌘0)', 'aria-label': 'Show the whole floor', onclick: reveal }, icon('fit', 16, 2)));
+ }
+
+ // What can be added, for the bar under the plan (Mac) and the Add sheet (phone).
+ function addable() {
+ return [
+ ['room', 'room', 'Room', () => add('room')],
+ ['light', 'bulb', 'Lamp', () => add('light')],
+ ['ac', 'ac', 'Air conditioner', () => add('ac')],
+ ['door', 'opening', 'Door', () => add('opening', { type: 'door' })],
+ ['window', 'window', 'Window', () => add('opening', { type: 'window' })],
+ ['stairs', 'stairs', 'Stairs', () => add('furniture', { type: 'stairs' })],
+ ['furniture', 'furniture', 'Furniture', () => add('furniture')],
+ ];
+ }
+
+ function addBar() {
+ return h('div.add-bar', addable().map(([key, name, label, run]) => h('button', {
+ title: `Add ${label.toLowerCase()}`, 'data-add': key, onclick: () => { run(); },
+ }, icon(name, 18, 1.9), h('span', key === 'ac' ? 'AC' : label))));
+ }
+
/* ---------- validation + preview ---------- */
let valid = null;
@@ -155,7 +433,8 @@ export async function bootEditor(root) {
valid = normalize(structuredClone(doc));
const linked = [...doc.lights, ...doc.acs].filter(isLinked).length;
status.className = 'status';
- status.replaceChildren(h('span.ok', '●'), ` ${doc.rooms.length} rooms · ${doc.lights.length} lights · ${doc.acs.length} ACs · `,
+ const floors = levelList().length > 1 ? `${levelList().length} floors · ` : '';
+ status.replaceChildren(h('span.ok', '●'), ` ${floors}${doc.rooms.length} rooms · ${doc.lights.length} lights · ${doc.acs.length} ACs · `,
`${linked} linked to real devices`, dirty ? h('span.dirty', ' · unsaved changes') : '');
} catch (e) {
valid = null;
@@ -189,6 +468,7 @@ export async function bootEditor(root) {
previewHost.replaceChildren(canvas);
try {
world = createWorld(canvas, valid, previewStore(valid), {
+ level,
onHover() {},
onPick(t) {
if (!t) return;
@@ -212,23 +492,36 @@ export async function bootEditor(root) {
if (kind === 'light') return [item.name || item.id, `${roomName(item.room)} · ${item.type}`];
if (kind === 'ac') return [item.name || item.id, `${roomName(item.room)} · ${item.wall} wall`];
if (kind === 'furniture') return [item.type, roomName(roomAt(item.pos)?.id) || '—'];
+ if (kind === 'opening' && !item.to) return [item.type || 'door', ''];
if (kind === 'opening') return [item.type || 'door', `${fix(Math.hypot(item.to[0] - item.from[0], item.to[1] - item.from[1]))} m`];
return [item.name || item.id, `${Object.keys(item.lights || {}).length} rules`];
}
const roomName = (id) => doc.rooms.find((r) => r.id === id)?.name || id || '';
- const roomAt = ([x, z]) => doc.rooms.find((r) => x >= r.rect[0] && x <= r.rect[0] + r.rect[2] && z >= r.rect[1] && z <= r.rect[1] + r.rect[3]);
+ const roomAt = ([x, z]) => levelRooms().find((r) => x >= r.rect[0] && x <= r.rect[0] + r.rect[2] && z >= r.rect[1] && z <= r.rect[1] + r.rect[3]);
function renderSidebar() {
const nodes = [h(`button.row.home-row${sel.kind === 'home' ? '.active' : ''}`, { onclick: () => select({ kind: 'home' }) },
icon('home', 15), h('span.row-name', 'Home settings')),
links.sidebarRow(sel.kind === 'connections' || sel.kind === 'service', () => select({ kind: 'connections' }))];
+ const list = levelList();
+ nodes.push(h('div.group', h('span', 'Floors'), h('span.n', list.length),
+ h('button.add', { title: 'Add a floor', 'aria-label': 'Add a floor', onclick: () => addLevel() }, icon('plus', 14, 2.4))));
+ for (const l of [...list].reverse()) {
+ const active = sel.kind === 'level' && sel.id === l.id;
+ nodes.push(h(`div.row.level-row${active ? '.active' : ''}${l.id === level ? '.current' : ''}`, {
+ role: 'button', tabindex: 0, onclick: () => { setLevel(l.id); select({ kind: 'level', id: l.id }); },
+ }, icon('layers', 14, 2), h('span.row-name', l.name), h('span.row-sub', `${levelRooms(l.id).length} rooms`),
+ list.length > 1 ? h('button.del', { title: 'Remove this floor', 'aria-label': `Remove ${l.name}`, onclick: (e) => { e.stopPropagation(); removeLevel(l.id); } }, icon('close', 13, 2.4)) : null));
+ }
for (const kind of Object.keys(KEYS)) {
const items = doc[KEYS[kind]];
+ const shown = items.filter((item) => here(kind, item)).length;
nodes.push(h('div.group',
- h('span', `${TITLES[kind]}`), h('span.n', items.length),
+ h('span', `${TITLES[kind]}`), h('span.n', shown),
h('button.add', { title: `Add to ${TITLES[kind].toLowerCase()}`, 'aria-label': `Add ${kind}`, onclick: () => add(kind) }, icon('plus', 14, 2.4))));
items.forEach((item, index) => {
+ if (!here(kind, item)) return;
const [name, sub] = rowLabel(kind, item);
const active = sel.kind === kind && sel.index === index;
nodes.push(h(`div.row${active ? '.active' : ''}`, { role: 'button', tabindex: 0, onclick: () => select({ kind, index }) },
@@ -249,15 +542,19 @@ export async function bootEditor(root) {
for (let i = 2; ; i++) if (!ids.has(`${base}${i}`)) return `${base}${i}`;
}
- function add(kind) {
+ function add(kind, { type } = {}) {
+ // On an empty floor the first room is as big as the floor below, ready to be divided.
+ if (kind === 'room' && !levelRooms().length && below()) { fillLevel(); return; }
snapshot();
- const room = (sel.kind === 'room' && doc.rooms[sel.index]) || doc.rooms.find((r) => r.id === doc[KEYS[sel.kind]]?.[sel.index]?.room) || doc.rooms[0];
+ const rooms = levelRooms();
+ const picked = sel.index != null ? doc[KEYS[sel.kind]]?.[sel.index] : null;
+ const room = (sel.kind === 'room' && picked) || (picked?.room && rooms.find((r) => r.id === picked.room)) || rooms[0];
const center = room ? [fix(room.rect[0] + room.rect[2] / 2), fix(room.rect[1] + room.rect[3] / 2)] : [1, 1];
const list = doc[KEYS[kind]];
if (kind === 'room') {
- const maxX = Math.max(0, ...doc.rooms.map((r) => r.rect[0] + r.rect[2]));
- const minZ = Math.min(...doc.rooms.map((r) => r.rect[1]), 0);
- list.push({ id: uniqueId('room'), name: 'New room', rect: [fix(maxX), fix(doc.rooms.length ? minZ : 0), 3, 3], floor: 'oak' });
+ const maxX = Math.max(0, ...rooms.map((r) => r.rect[0] + r.rect[2]));
+ const minZ = Math.min(...rooms.map((r) => r.rect[1]), 0);
+ list.push(stamp({ id: uniqueId('room'), name: 'New room', rect: [fix(maxX), fix(rooms.length ? minZ : 0), 3, 3], floor: 'oak' }));
} else if (kind === 'light') {
if (!room) return toast('Add a room first', true);
list.push({ id: uniqueId(`${room.id}.light`), name: 'New light', room: room.id, type: 'ceiling', pos: freeSpot(room, center), capabilities: [] });
@@ -265,22 +562,123 @@ export async function bootEditor(root) {
if (!room) return toast('Add a room first', true);
list.push({ id: uniqueId(`${room.id}.ac`), name: `${room.name} AC`, room: room.id, wall: 'north', pos: [center[0], room.rect[1]], y: 2.2 });
} else if (kind === 'furniture') {
- list.push({ type: 'sofa', pos: center, rot: 0 });
+ list.push(stamp(type === 'stairs' ? { type, pos: center, rot: 0, width: 1, depth: 2.8 } : { type: type || 'sofa', pos: center, rot: 0 }));
} else if (kind === 'opening') {
if (!room) return toast('Add a room first', true);
- const z = room.rect[1] + room.rect[3];
- list.push({ type: 'door', from: [fix(center[0] - 0.45), fix(z)], to: [fix(center[0] + 0.45), fix(z)] });
+ // A door on the near (south) wall; a window on the far (north) one, where the 3D model shows it.
+ const half = type === 'window' ? 0.6 : 0.45;
+ const z = type === 'window' ? room.rect[1] : room.rect[1] + room.rect[3];
+ list.push(stamp({ type: type || 'door', from: [fix(center[0] - half), fix(z)], to: [fix(center[0] + half), fix(z)] }));
} else if (kind === 'scene') {
list.push({ id: uniqueId('scene'), name: 'New scene', icon: 'sparkles', lights: { '*': { on: false } } });
}
sel = { kind, index: list.length - 1 };
+ if (view && !inView(list[list.length - 1])) view = null;
+ touch();
+ if (isPhone) phone.selected(sel);
+ }
+
+ // Whether an item's middle is in the part of the plan on show.
+ function inView(item) {
+ const p = item.pos || item.from || (item.rect && [item.rect[0] + item.rect[2] / 2, item.rect[1] + item.rect[3] / 2]);
+ if (!p || !view) return true;
+ return p[0] > view.x && p[0] < view.x + view.w && p[1] > view.y && p[1] < view.y + view.h;
+ }
+
+ // A copy of what is selected, beside it. A copied lamp or AC is not linked to the same device.
+ function duplicate() {
+ const kind = sel.kind;
+ const item = sel.index != null ? doc[KEYS[kind]]?.[sel.index] : null;
+ if (!item) return;
+ snapshot();
+ const copy = structuredClone(item);
+ if (kind === 'room') {
+ copy.id = uniqueId(item.id);
+ copy.name = `${item.name || item.id} 2`;
+ copy.rect[0] = fix(item.rect[0] + item.rect[2]);
+ } else if (kind === 'light' || kind === 'ac') {
+ copy.id = uniqueId(item.id);
+ for (const key of ['tuya', 'link', 'sensor']) delete copy[key];
+ if (kind === 'ac') {
+ const along = item.wall === 'north' || item.wall === 'south' ? 0 : 1;
+ copy.pos[along] = fix(copy.pos[along] + 1.1);
+ } else copy.pos = [fix(item.pos[0] + 0.5), fix(item.pos[1])];
+ } else if (kind === 'furniture') {
+ copy.pos = [fix(item.pos[0] + 0.4), fix(item.pos[1] + 0.4)];
+ } else if (kind === 'opening') {
+ const alongX = item.from[1] === item.to[1];
+ const len = Math.abs(alongX ? item.to[0] - item.from[0] : item.to[1] - item.from[1]) + 0.3;
+ const k = alongX ? 0 : 1;
+ copy.from[k] = fix(copy.from[k] + len);
+ copy.to[k] = fix(copy.to[k] + len);
+ } else if (kind === 'scene') {
+ copy.id = uniqueId(item.id);
+ copy.name = `${item.name || item.id} copy`;
+ }
+ doc[KEYS[kind]].push(copy);
+ sel = { kind, index: doc[KEYS[kind]].length - 1 };
+ touch();
+ toast('Duplicated');
+ }
+
+ // Turns furniture or a lamp a quarter (or, with `step`, a little).
+ function rotate(step = 90) {
+ const item = sel.index != null ? doc[KEYS[sel.kind]]?.[sel.index] : null;
+ if (!item || !['furniture', 'light'].includes(sel.kind)) return;
+ snapshot(`rotate${sel.kind}${sel.index}`);
+ item.rot = (((item.rot || 0) + step) % 360 + 540) % 360 - 180;
touch();
}
+ // Splits a room across its longer side, with a door between the two halves.
+ function splitRoom(index) {
+ const room = doc.rooms[index];
+ if (!room) return;
+ const [x, z, w, d] = room.rect;
+ if (Math.max(w, d) < MIN_ROOM * 2) { toast('Too small to split', true); return; }
+ snapshot();
+ const across = w >= d;
+ const cut = round((across ? w : d) / 2, 0.05);
+ const next = structuredClone(room);
+ next.id = uniqueId(room.id);
+ next.name = `${room.name || room.id} 2`;
+ if (across) {
+ room.rect = [x, z, fix(cut), d];
+ next.rect = [fix(x + cut), z, fix(w - cut), d];
+ } else {
+ room.rect = [x, z, w, fix(cut)];
+ next.rect = [x, fix(z + cut), w, fix(d - cut)];
+ }
+ doc.rooms.push(next);
+ const inNext = ([px, pz]) => px >= next.rect[0] && px <= next.rect[0] + next.rect[2] && pz >= next.rect[1] && pz <= next.rect[1] + next.rect[3];
+ for (const dev of [...doc.lights, ...doc.acs]) if (dev.room === room.id && inNext(dev.pos)) dev.room = next.id;
+ const mid = across ? [fix(x + cut), fix(z + d / 2)] : [fix(x + w / 2), fix(z + cut)];
+ const door = across ? { from: [mid[0], fix(mid[1] - 0.45)], to: [mid[0], fix(mid[1] + 0.45)] } : { from: [fix(mid[0] - 0.45), mid[1]], to: [fix(mid[0] + 0.45), mid[1]] };
+ doc.openings.push(stamp({ type: 'door', ...door, ...(room.level ? { level: room.level } : {}) }));
+ sel = { kind: 'room', index: doc.rooms.length - 1 };
+ touch();
+ toast('Split in two, with a door between');
+ }
+
+ // Moves a room, and what stands in it, to another floor.
+ function moveRoomToLevel(index, id) {
+ const room = doc.rooms[index];
+ if (!room || id === (room.level ?? firstLevel())) return;
+ pinLevels();
+ const [x, z, w, d] = room.rect;
+ const inside = ([px, pz]) => px >= x - 1e-6 && px <= x + w + 1e-6 && pz >= z - 1e-6 && pz <= z + d + 1e-6;
+ for (const f of doc.furniture) if (f.level === room.level && Array.isArray(f.pos) && inside(f.pos)) f.level = id;
+ for (const o of doc.openings) if (o.level === room.level && inside(o.from) && inside(o.to)) o.level = id;
+ room.level = id;
+ level = id;
+ view = null;
+ world?.setLevel(id);
+ }
+
// The middle of the room, or the nearest place around it no other lamp stands on.
function freeSpot(room, center) {
const [x, z, w, d] = room.rect;
- const taken = (p) => doc.lights.some((l) => Math.hypot(l.pos[0] - p[0], l.pos[1] - p[1]) < 0.45);
+ const taken = (p) => doc.lights.some((l) => here('light', l) && Math.hypot(l.pos[0] - p[0], l.pos[1] - p[1]) < 0.45);
for (let ring = 0; ring < 4; ring++) {
for (let k = 0; k < Math.max(1, ring * 6); k++) {
const a = (k / Math.max(1, ring * 6)) * Math.PI * 2;
@@ -294,70 +692,103 @@ export async function bootEditor(root) {
function remove(kind, index) {
snapshot();
const [gone] = doc[KEYS[kind]].splice(index, 1);
- if (kind === 'room') {
- // Devices cannot outlive their room.
- doc.lights = doc.lights.filter((l) => l.room !== gone.id);
- doc.acs = doc.acs.filter((a) => a.room !== gone.id);
- }
- if (kind === 'light' || kind === 'ac' || kind === 'room') {
- const ids = new Set([...doc.lights, ...doc.acs].map((d) => d.id));
- for (const sc of doc.scenes) {
- for (const map of [sc.lights, sc.acs]) for (const id of Object.keys(map || {})) if (id !== '*' && !ids.has(id)) delete map[id];
- }
- }
+ if (kind === 'room') dropRooms(new Set([gone.id]));
+ else if (kind === 'light' || kind === 'ac') forgetDevices();
sel = { kind: 'home' };
touch();
}
- /* ---------- plan (SVG) ---------- */
+ // Devices cannot outlive their room.
+ function dropRooms(ids) {
+ doc.rooms = doc.rooms.filter((r) => !ids.has(r.id));
+ doc.lights = doc.lights.filter((l) => !ids.has(l.room));
+ doc.acs = doc.acs.filter((a) => !ids.has(a.room));
+ forgetDevices();
+ }
- function bounds() {
- const rs = doc.rooms.length ? doc.rooms : [{ rect: [0, 0, 6, 4] }];
- const minX = Math.min(...rs.map((r) => r.rect[0]));
- const minZ = Math.min(...rs.map((r) => r.rect[1]));
- const maxX = Math.max(...rs.map((r) => r.rect[0] + r.rect[2]));
- const maxZ = Math.max(...rs.map((r) => r.rect[1] + r.rect[3]));
- return { minX, minZ, maxX, maxZ };
+ // Scenes let go of devices that are gone.
+ function forgetDevices() {
+ const ids = new Set([...doc.lights, ...doc.acs].map((d) => d.id));
+ for (const sc of doc.scenes) {
+ for (const map of [sc.lights, sc.acs]) for (const id of Object.keys(map || {})) if (id !== '*' && !ids.has(id)) delete map[id];
+ }
}
+ /* ---------- plan (SVG) ---------- */
+
const isSel = (kind, index) => sel.kind === kind && sel.index === index;
+ const svText = (attrs, value) => sv('text', attrs, document.createTextNode(value));
+
+ // A flight of stairs on the plan: its treads, and an arrow up from where you step on.
+ function stairsMarks(w, d, cls) {
+ const steps = Math.max(3, Math.round(d / 0.28));
+ const marks = [];
+ for (let i = 1; i < steps; i++) {
+ const y = -d / 2 + (d * i) / steps;
+ marks.push(sv('line', { x1: -w / 2, x2: w / 2, y1: y, y2: y, class: `${cls}-step` }));
+ }
+ marks.push(sv('path', { d: `M0 ${d / 2 - 0.25}V${-d / 2 + 0.3}M-0.16 ${-d / 2 + 0.5}L0 ${-d / 2 + 0.3}L0.16 ${-d / 2 + 0.5}`, class: `${cls}-arrow` }));
+ return marks;
+ }
function renderPlan() {
- const b = bounds();
- const m = 1.4;
- if (isPhone) phone.applyView();
- else plan.setAttribute('viewBox', `${b.minX - m} ${b.minZ - m} ${b.maxX - b.minX + m * 2} ${b.maxZ - b.minZ + m * 2}`);
+ applyView();
+ renderLevels();
// Fingers are bigger than a mouse pointer: on a phone small things get a wider target.
const big = isPhone;
const kids = [
sv('defs', {}, sv('pattern', { id: 'grid', width: 1, height: 1, patternUnits: 'userSpaceOnUse' },
sv('path', { d: 'M1 0H0V1', fill: 'none', stroke: 'rgba(255,255,255,0.07)', 'stroke-width': 0.015 }),
sv('path', { d: 'M0.5 0V1M0 0.5H1', fill: 'none', stroke: 'rgba(255,255,255,0.03)', 'stroke-width': 0.01 }))),
- sv('rect', { x: b.minX - 20, y: b.minZ - 20, width: 60, height: 60, fill: 'url(#grid)', 'data-kind': 'none' }),
+ sv('rect', { x: -500, y: -500, width: 1000, height: 1000, fill: 'url(#grid)', 'data-kind': 'none' }),
];
+ // The floor below, faintly, to line the walls (and the stairs coming up) up with.
+ const under = below();
+ const ghostStairs = sv('g', { class: 'p-ghost' });
+ if (under) {
+ const ghost = sv('g', { class: 'p-ghost' });
+ for (const r of levelRooms(under.id)) {
+ const [x, z, w, d] = r.rect;
+ ghost.append(sv('rect', { x, y: z, width: w, height: d }), svText({ x: x + w / 2, y: z + d / 2, class: 'p-ghost-label' }, r.name || r.id));
+ }
+ kids.push(ghost);
+ // The stairs coming up from below show over this floor's rooms: that is where the landing goes.
+ for (const f of doc.furniture) {
+ if (f.type !== 'stairs' || (f.level ?? firstLevel()) !== under.id || !Array.isArray(f.pos)) continue;
+ const [w, d] = footprint(f);
+ ghostStairs.append(sv('g', { transform: `translate(${f.pos[0]} ${f.pos[1]}) rotate(${-(f.rot || 0)})` },
+ sv('rect', { x: -w / 2, y: -d / 2, width: w, height: d, class: 'p-ghost-stairs' }), ...stairsMarks(w, d, 'p-ghost')));
+ }
+ }
+
doc.rooms.forEach((r, i) => {
+ if (!here('room', r)) return;
const [x, z, w, d] = r.rect;
- const g = sv('g', { class: `p-room${isSel('room', i) ? ' sel' : ''}`, 'data-kind': 'room', 'data-index': i },
+ kids.push(sv('g', { class: `p-room${isSel('room', i) ? ' sel' : ''}`, 'data-kind': 'room', 'data-index': i },
sv('rect', { x, y: z, width: w, height: d, fill: FLOOR_FILL[r.floor] || FLOOR_FILL.oak }),
- sv('text', { x: x + w / 2, y: z + d / 2 - 0.02, class: 'p-label' }, document.createTextNode(r.name || r.id)),
- sv('text', { x: x + w / 2, y: z + d / 2 + 0.3, class: 'p-dim' }, document.createTextNode(`${fix(w)} × ${fix(d)}`)));
- kids.push(g);
+ svText({ x: x + w / 2, y: z + d / 2 - 0.02, class: 'p-label' }, r.name || r.id),
+ svText({ x: x + w / 2, y: z + d / 2 + 0.3, class: 'p-dim' }, `${fix(w)} × ${fix(d)}`)));
});
+ kids.push(ghostStairs);
+
doc.furniture.forEach((f, i) => {
- if (!Array.isArray(f.pos)) return;
+ if (!Array.isArray(f.pos) || !here('furniture', f)) return;
const [w, d] = footprint(f);
+ const stairs = f.type === 'stairs';
kids.push(sv('g', {
- class: `p-furn${isSel('furniture', i) ? ' sel' : ''}`, 'data-kind': 'furniture', 'data-index': i,
+ class: `p-furn${stairs ? ' stairs' : ''}${isSel('furniture', i) ? ' sel' : ''}`, 'data-kind': 'furniture', 'data-index': i,
transform: `translate(${f.pos[0]} ${f.pos[1]}) rotate(${-(f.rot || 0)})`,
},
- sv('rect', { x: -w / 2, y: -d / 2, width: w, height: d, rx: 0.06 }),
- // a tick marks the front of the piece
- sv('path', { d: `M${-w / 4} ${d / 2}H${w / 4}`, class: 'front' })));
+ sv('rect', { x: -w / 2, y: -d / 2, width: w, height: d, rx: stairs ? 0.02 : 0.06 }),
+ ...(stairs ? stairsMarks(w, d, 'p-stairs')
+ // a tick marks the front of the piece
+ : [sv('path', { d: `M${-w / 4} ${d / 2}H${w / 4}`, class: 'front' })])));
});
doc.openings.forEach((o, i) => {
+ if (!here('opening', o)) return;
if (big) kids.push(sv('line', { class: 'p-hit', 'data-kind': 'opening', 'data-index': i, x1: o.from[0], y1: o.from[1], x2: o.to[0], y2: o.to[1] }));
kids.push(sv('line', {
class: `p-open ${o.type || 'door'}${isSel('opening', i) ? ' sel' : ''}`, 'data-kind': 'opening', 'data-index': i,
@@ -366,6 +797,7 @@ export async function bootEditor(root) {
});
doc.acs.forEach((a, i) => {
+ if (!here('ac', a)) return;
const rot = { north: 0, east: 90, south: 180, west: 270 }[a.wall] || 0;
kids.push(sv('g', {
class: `p-ac${isSel('ac', i) ? ' sel' : ''}`, 'data-kind': 'ac', 'data-index': i,
@@ -376,6 +808,7 @@ export async function bootEditor(root) {
});
doc.lights.forEach((l, i) => {
+ if (!here('light', l)) return;
const g = sv('g', {
class: `p-light ${l.type}${isSel('light', i) ? ' sel' : ''}${isLinked(l) ? ' linked' : ''}`, 'data-kind': 'light', 'data-index': i,
transform: `translate(${l.pos[0]} ${l.pos[1]}) rotate(${-(l.rot || 0)})`,
@@ -390,10 +823,36 @@ export async function bootEditor(root) {
kids.push(g);
});
- if (sel.kind === 'room' && doc.rooms[sel.index]) {
- const [x, z, w, d] = doc.rooms[sel.index].rect;
- if (big) kids.push(sv('circle', { cx: x + w, cy: z + d, r: 0.55, class: 'hit', 'data-kind': 'resize', 'data-index': sel.index }));
- kids.push(sv('circle', { cx: x + w, cy: z + d, r: big ? 0.24 : 0.16, class: 'p-handle', 'data-kind': 'resize', 'data-index': sel.index }));
+ // Handles of what is selected, sized in screen pixels so they stay easy to grab at any zoom.
+ const r = pixels(big ? 9 : 5.5);
+ const reach = pixels(big ? 22 : 9);
+ const room = sel.kind === 'room' && doc.rooms[sel.index];
+ if (room && here('room', room)) {
+ const [x, z, w, d] = room.rect;
+ for (const [name, [fx, fz]] of Object.entries(HANDLES)) {
+ const cx = x + w * fx;
+ const cz = z + d * fz;
+ const attrs = { 'data-kind': 'resize', 'data-index': sel.index, 'data-handle': name };
+ kids.push(sv('circle', { cx, cy: cz, r: reach, class: `hit grab ${name}`, ...attrs }),
+ sv('circle', { cx, cy: cz, r: name.length === 2 ? r : r * 0.8, class: `p-handle ${name}`, ...attrs }));
+ }
+ }
+ const open = sel.kind === 'opening' && doc.openings[sel.index];
+ if (open && here('opening', open)) {
+ const alongX = open.from[1] === open.to[1];
+ for (const end of ['from', 'to']) {
+ const [cx, cz] = open[end];
+ const attrs = { 'data-kind': 'oend', 'data-index': sel.index, 'data-handle': end };
+ kids.push(sv('circle', { cx, cy: cz, r: reach, class: `hit grab ${alongX ? 'e' : 's'}`, ...attrs }),
+ sv('circle', { cx, cy: cz, r: r * 0.85, class: `p-handle ${alongX ? 'e' : 's'}`, ...attrs }));
+ }
+ }
+
+ // Lines something being dragged has snapped to.
+ for (const g of drag?.guides || []) {
+ kids.push(g.axis === 'x'
+ ? sv('line', { x1: g.c, x2: g.c, y1: -500, y2: 500, class: 'p-guide' })
+ : sv('line', { x1: -500, x2: 500, y1: g.c, y2: g.c, class: 'p-guide' }));
}
plan.replaceChildren(...kids);
}
@@ -423,21 +882,87 @@ export async function bootEditor(root) {
ac.pos = wall === 'north' ? [cx, rz] : wall === 'south' ? [cx, fix(rz + rd)] : wall === 'west' ? [rx, cz] : [fix(rx + rw), cz];
}
+ // Every room edge on this floor: a wall running along `axis` at `c`, from `a` to `b`.
+ function walls() {
+ const out = [];
+ for (const r of levelRooms()) {
+ const [x, z, w, d] = r.rect;
+ out.push({ axis: 'x', c: z, a: x, b: x + w }, { axis: 'x', c: z + d, a: x, b: x + w },
+ { axis: 'z', c: x, a: z, b: z + d }, { axis: 'z', c: x + w, a: z, b: z + d });
+ }
+ return out;
+ }
+
+ // Lays a door or a window of length `len` on the wall nearest to the point, centred there.
+ function placeOpening(o, [px, pz], len) {
+ let best = null;
+ for (const wall of walls()) {
+ if (wall.b - wall.a < len - 1e-6) continue;
+ const along = wall.axis === 'x' ? px : pz;
+ const across = wall.axis === 'x' ? pz : px;
+ const t = clamp(along, wall.a + len / 2, wall.b - len / 2);
+ const dist = Math.hypot(along - t, across - wall.c);
+ if (!best || dist < best.dist) best = { wall, t, dist };
+ }
+ if (!best) return;
+ const { wall } = best;
+ const t = clamp(round(best.t), wall.a + len / 2, wall.b - len / 2);
+ const [a, b] = [fix(t - len / 2), fix(t + len / 2)];
+ const c = fix(wall.c);
+ if (wall.axis === 'x') { o.from = [a, c]; o.to = [b, c]; } else { o.from = [c, a]; o.to = [c, b]; }
+ }
+
+ // The room edges (on this floor, and the one under it) a moving edge can snap to.
+ function edgeLines(skip) {
+ const xs = [];
+ const zs = [];
+ const rooms = [...levelRooms(), ...(below() ? levelRooms(below().id) : [])];
+ for (const r of rooms) {
+ if (r === skip) continue;
+ xs.push(r.rect[0], r.rect[0] + r.rect[2]);
+ zs.push(r.rect[1], r.rect[1] + r.rect[3]);
+ }
+ return { xs, zs };
+ }
+
+ // The nearest line to any of `values` within reach: how far to move to sit on it, and where it is.
+ function snapTo(values, lines) {
+ let best = null;
+ const reach = pixels(9);
+ for (const v of values) for (const c of lines) {
+ const d = c - v;
+ if (Math.abs(d) <= reach && (!best || Math.abs(d) < Math.abs(best.d))) best = { d, c };
+ }
+ return best;
+ }
+
let drag = null;
+ let pan = null; // dragging the plan itself around (Mac)
plan.addEventListener('pointerdown', (ev) => {
if (isPhone) return;
+ plan.focus({ preventScroll: true });
const el = ev.target.closest('[data-kind]');
const kind = el?.dataset.kind;
- if (!kind || kind === 'none') { select({ kind: 'home' }); return; }
plan.setPointerCapture(ev.pointerId);
- startDrag(kind, Number(el.dataset.index), ev);
+ // The empty plan, the middle button or the space bar held: the plan moves.
+ if (!kind || kind === 'none' || ev.button === 1 || spaceHeld) {
+ pan = { x: ev.clientX, y: ev.clientY, v0: box(), moved: false, empty: !kind || kind === 'none' };
+ plan.classList.add('panning');
+ return;
+ }
+ startDrag(kind, Number(el.dataset.index), ev, el.dataset.handle);
});
- // Picks up an item (or a room's resize handle) under the pointer.
- function startDrag(kind, index, ev) {
+ // Picks up an item (or a handle of one) under the pointer.
+ function startDrag(kind, index, ev, handle) {
const start = planPoint(ev);
if (kind === 'resize') {
- drag = { kind, index, start, rect: [...doc.rooms[index].rect] };
+ drag = { kind, index, start, handle, rect: [...doc.rooms[index].rect] };
+ return;
+ }
+ if (kind === 'oend') {
+ const o = doc.openings[index];
+ drag = { kind, index, start, handle, from: [...o.from], to: [...o.to] };
return;
}
if (!isSel(kind, index)) select({ kind, index });
@@ -451,9 +976,10 @@ export async function bootEditor(root) {
drag.riders = [
...doc.lights.filter((l) => l.room === item.id).map((o) => ({ o, pos: [...o.pos] })),
...doc.acs.filter((a) => a.room === item.id).map((o) => ({ o, pos: [...o.pos] })),
- ...doc.furniture.filter((f) => Array.isArray(f.pos) && inside(f.pos)).map((o) => ({ o, pos: [...o.pos] })),
+ ...doc.furniture.filter((f) => Array.isArray(f.pos) && here('furniture', f) && inside(f.pos)).map((o) => ({ o, pos: [...o.pos] })),
];
- drag.openings = doc.openings.filter((o) => inside(o.from) && inside(o.to)).map((o) => ({ o, from: [...o.from], to: [...o.to] }));
+ drag.openings = doc.openings.filter((o) => here('opening', o) && inside(o.from) && inside(o.to)).map((o) => ({ o, from: [...o.from], to: [...o.to] }));
+ drag.lines = edgeLines(item);
} else if (kind === 'opening') {
drag.from = [...item.from];
drag.to = [...item.to];
@@ -462,7 +988,20 @@ export async function bootEditor(root) {
}
}
- plan.addEventListener('pointermove', (ev) => { if (!isPhone) moveDrag(ev); });
+ plan.addEventListener('pointermove', (ev) => {
+ if (isPhone) return;
+ if (pan) {
+ const dx = ev.clientX - pan.x;
+ const dy = ev.clientY - pan.y;
+ if (!pan.moved && Math.hypot(dx, dy) < 4) return;
+ pan.moved = true;
+ const rect = plan.getBoundingClientRect();
+ view = { ...pan.v0, x: pan.v0.x - dx * pan.v0.w / rect.width, y: pan.v0.y - dy * pan.v0.h / rect.height };
+ applyView();
+ return;
+ }
+ moveDrag(ev);
+ });
function moveDrag(ev) {
if (!drag) return;
@@ -471,27 +1010,65 @@ export async function bootEditor(root) {
const dz = round(pz - drag.start[1]);
if (!drag.moved && !dx && !dz) return;
if (!drag.moved) { drag.moved = true; snapshot(); haptic('tick'); }
- const item = drag.kind === 'resize' ? doc.rooms[drag.index] : doc[KEYS[drag.kind]][drag.index];
+ const free = ev.altKey; // ⌥ held: no snapping to other rooms
+ drag.guides = [];
if (drag.kind === 'resize') {
- item.rect[2] = fix(Math.max(1, round(drag.rect[2] + px - drag.start[0], 0.1)));
- item.rect[3] = fix(Math.max(1, round(drag.rect[3] + pz - drag.start[1], 0.1)));
+ const item = doc.rooms[drag.index];
+ const [x, z, w, d] = drag.rect;
+ const lines = edgeLines(item);
+ let [x0, z0, x1, z1] = [x, z, x + w, z + d];
+ const hd = drag.handle;
+ const edge = (v, list, axis) => {
+ const s = !free && snapTo([v], list);
+ if (s) { drag.guides.push({ axis, c: s.c }); return s.c; }
+ return round(v);
+ };
+ if (hd.includes('w')) x0 = Math.min(edge(x + px - drag.start[0], lines.xs, 'x'), x1 - MIN_ROOM);
+ if (hd.includes('e')) x1 = Math.max(edge(x + w + px - drag.start[0], lines.xs, 'x'), x0 + MIN_ROOM);
+ if (hd.includes('n')) z0 = Math.min(edge(z + pz - drag.start[1], lines.zs, 'z'), z1 - MIN_ROOM);
+ if (hd.includes('s')) z1 = Math.max(edge(z + d + pz - drag.start[1], lines.zs, 'z'), z0 + MIN_ROOM);
+ item.rect = [fix(x0), fix(z0), fix(x1 - x0), fix(z1 - z0)];
+ } else if (drag.kind === 'oend') {
+ const o = doc.openings[drag.index];
+ const alongX = drag.from[1] === drag.to[1];
+ const k = alongX ? 0 : 1;
+ const other = drag.handle === 'from' ? drag.to : drag.from;
+ const moved = round(drag[drag.handle][k] + (k ? pz - drag.start[1] : px - drag.start[0]));
+ const sign = Math.sign(drag[drag.handle][k] - other[k]) || 1;
+ const end = [...drag[drag.handle]];
+ end[k] = fix(sign > 0 ? Math.max(moved, other[k] + 0.4) : Math.min(moved, other[k] - 0.4));
+ o[drag.handle] = end;
} else if (drag.kind === 'room') {
- const mx = round(px - drag.start[0], 0.1);
- const mz = round(pz - drag.start[1], 0.1);
- item.rect[0] = fix(drag.rect[0] + mx);
- item.rect[1] = fix(drag.rect[1] + mz);
+ const item = doc.rooms[drag.index];
+ let mx = round(px - drag.start[0]);
+ let mz = round(pz - drag.start[1]);
+ const [x, z, w, d] = drag.rect;
+ if (!free) {
+ const sx = snapTo([x + mx, x + w + mx], drag.lines.xs);
+ const sz = snapTo([z + mz, z + d + mz], drag.lines.zs);
+ if (sx) { mx = fix(mx + sx.d); drag.guides.push({ axis: 'x', c: sx.c }); }
+ if (sz) { mz = fix(mz + sz.d); drag.guides.push({ axis: 'z', c: sz.c }); }
+ }
+ item.rect[0] = fix(x + mx);
+ item.rect[1] = fix(z + mz);
for (const r of drag.riders) r.o.pos = [fix(r.pos[0] + mx), fix(r.pos[1] + mz)];
for (const r of drag.openings) {
r.o.from = [fix(r.from[0] + mx), fix(r.from[1] + mz)];
r.o.to = [fix(r.to[0] + mx), fix(r.to[1] + mz)];
}
} else if (drag.kind === 'opening') {
- item.from = [fix(drag.from[0] + dx), fix(drag.from[1] + dz)];
- item.to = [fix(drag.to[0] + dx), fix(drag.to[1] + dz)];
+ const item = doc.openings[drag.index];
+ const len = Math.hypot(drag.to[0] - drag.from[0], drag.to[1] - drag.from[1]);
+ const mid = [(drag.from[0] + drag.to[0]) / 2 + px - drag.start[0], (drag.from[1] + drag.to[1]) / 2 + pz - drag.start[1]];
+ if (free) {
+ item.from = [fix(drag.from[0] + dx), fix(drag.from[1] + dz)];
+ item.to = [fix(drag.to[0] + dx), fix(drag.to[1] + dz)];
+ } else placeOpening(item, mid, len); // doors and windows slide along the walls, and jump to the nearest one
} else if (drag.kind === 'ac') {
- snapAC(item, [px, pz]);
+ snapAC(doc.acs[drag.index], [px, pz]);
} else {
+ const item = doc[KEYS[drag.kind]][drag.index];
item.pos = [fix(drag.pos[0] + dx), fix(drag.pos[1] + dz)];
if (drag.kind === 'light') {
const room = roomAt(item.pos);
@@ -501,9 +1078,39 @@ export async function bootEditor(root) {
touch();
}
- const endDrag = () => { drag = null; lastSnapshotKey = null; };
- plan.addEventListener('pointerup', () => { if (!isPhone) endDrag(); });
- plan.addEventListener('pointercancel', () => { if (!isPhone) endDrag(); });
+ const endDrag = () => {
+ const guides = drag?.guides?.length;
+ drag = null;
+ lastSnapshotKey = null;
+ if (guides) renderPlan();
+ };
+ const endPointer = (ev) => {
+ if (isPhone) return;
+ if (pan) {
+ if (!pan.moved && pan.empty && ev.type === 'pointerup') select({ kind: 'home' });
+ pan = null;
+ plan.classList.remove('panning');
+ }
+ endDrag();
+ };
+ plan.addEventListener('pointerup', endPointer);
+ plan.addEventListener('pointercancel', endPointer);
+
+ // Two fingers on a trackpad scroll the plan; a pinch (or ⌘ / Ctrl and the wheel) zooms.
+ plan.addEventListener('wheel', (ev) => {
+ ev.preventDefault();
+ if (ev.ctrlKey || ev.metaKey) {
+ zoomAt(Math.exp(-ev.deltaY * (ev.deltaMode === 1 ? 0.05 : 0.0075)), ev.clientX, ev.clientY);
+ return;
+ }
+ const rect = plan.getBoundingClientRect();
+ const v = box();
+ const k = ev.deltaMode === 1 ? 16 : 1;
+ view = { ...v, x: v.x + ev.deltaX * k * v.w / rect.width, y: v.y + ev.deltaY * k * v.h / rect.height };
+ applyView();
+ }, { passive: false });
+ let spaceHeld = false;
+ window.addEventListener('keyup', (ev) => { if (ev.code === 'Space') { spaceHeld = false; plan.classList.remove('can-pan'); } });
/* ---------- inspector ---------- */
@@ -539,6 +1146,19 @@ export async function bootEditor(root) {
const row = (...fields) => h('div.fields', fields);
const section = (title, ...nodes) => h('section.block', h('h3', title), nodes);
+ // A button that asks once more before it does something big.
+ function confirmButton(label, run) {
+ const b = h('button.btn.wide.danger', {
+ onclick: () => {
+ if (b.dataset.armed) { run(); return; }
+ b.dataset.armed = '1';
+ b.textContent = 'Tap again to remove';
+ haptic('medium');
+ setTimeout(() => { delete b.dataset.armed; b.textContent = label; }, 3000);
+ },
+ }, label);
+ return b;
+ }
// Linking to a real device: links.deviceSection / links.sensorSection (connections.js).
const linkHooks = { snapshot: () => snapshot(), changed: (note) => { touch(); if (note) toast(note); } };
@@ -563,10 +1183,56 @@ export async function bootEditor(root) {
row(bind('Azimuth, °', number(1), { ...prop(doc.camera, 'azimuth', 34), parse: parseNum }),
bind('Elevation, °', number(1), { ...prop(doc.camera, 'elevation', 47), parse: parseNum })),
h('p.note', 'Walls facing the camera are cut away, so the azimuth decides which side of the home is open.')),
+ isPhone ? null : section('Shortcuts',
+ h('dl.keys',
+ h('dt', 'Scroll · ⌘ scroll or pinch'), h('dd', 'Move around · zoom'),
+ h('dt', 'Drag the empty plan · Space-drag'), h('dd', 'Move around'),
+ h('dt', '⌘D · R · ⇧R'), h('dd', 'Duplicate · turn 90° · turn 15°'),
+ h('dt', 'Arrows · ⇧ arrows'), h('dd', 'Nudge 5 cm · 50 cm'),
+ h('dt', '⌥ while dragging'), h('dd', 'No snapping'),
+ h('dt', 'Page Up · Page Down'), h('dd', 'Floor above · below'),
+ h('dt', '⌘0 · Esc · ⌫'), h('dd', 'Whole floor · deselect · remove'))),
section('How it works',
h('p.note', isPhone
? 'Tap anything on the plan, or find it under Items, to edit it. “Save” keeps the plan on this iPhone and sends it to your paired computer. Coordinates are metres: x grows to the right (east), z grows downwards (south).'
: 'Pick anything on the plan or in the list to edit it. “Save & apply” writes the plan to disk and reloads the menu bar panel. Coordinates are metres: x grows to the right (east), z grows downwards (south).')));
+ } else if (kind === 'level') {
+ const l = levelList().find((x) => x.id === sel.id) || levelList().find((x) => x.id === level);
+ const list = levelList();
+ const i = list.indexOf(l);
+ const rooms = levelRooms(l.id);
+ const under = below(l.id);
+ head(l.name, `${rooms.length} rooms · floor ${i + 1} of ${list.length}`);
+ const own = Array.isArray(doc.levels) ? doc.levels.find((x) => x.id === l.id) : null;
+ // A home without "levels" gets them as soon as its one floor is named or given a height.
+ const editable = () => {
+ if (!Array.isArray(doc.levels) || !doc.levels.length) {
+ doc.levels = [{ id: 'ground', name: l.name }];
+ level = 'ground';
+ sel = { kind: 'level', id: 'ground' };
+ }
+ return doc.levels.find((x) => x.id === sel.id);
+ };
+ nodes.push(section('Floor',
+ bind('Name', text(), { get: () => l.name, set: (v) => { editable().name = v; } }),
+ bind('Ceiling height, m', number(0.1), {
+ get: () => own?.wallHeight ?? '',
+ set: (v) => { const x = editable(); if (v === '') delete x.wallHeight; else x.wallHeight = v; },
+ parse: optNum,
+ }),
+ h('p.note', `Empty: the home’s wall height (${doc.wallHeight ?? 2.6} m). Floors stack in this order; the 3D view shows one floor at a time, with the floors under it.`)),
+ section('Arrange',
+ h('div.fields',
+ h('button.btn', { disabled: i === list.length - 1, onclick: () => moveLevel(l.id, 1) }, icon('stairs', 14, 2.2), 'Move up'),
+ h('button.btn', { disabled: i === 0, onclick: () => moveLevel(l.id, -1) }, icon('down', 14, 2.2), 'Move down')),
+ h('div.fields',
+ h('button.btn', { onclick: () => addLevel('above') }, icon('plus', 14, 2.2), 'Floor above'),
+ i === 0 ? h('button.btn', { onclick: () => addLevel('below') }, icon('plus', 14, 2.2), 'Basement') : null),
+ under && !rooms.length ? h('button.btn.primary.wide', { onclick: () => copyRoomsFromBelow(l.id) }, icon('copy', 14, 2.2), `Copy the rooms of ${under.name}`) : null,
+ under ? h('p.note', `${under.name} shows faintly under this floor, with its stairs, so walls and stairs line up.`) : null),
+ list.length > 1 ? section('Remove',
+ confirmButton(`Remove ${l.name}`, () => removeLevel(l.id)),
+ h('p.note', `Takes its ${rooms.length} rooms with their lamps, ACs, furniture, doors and windows.`)) : null);
} else if (kind === 'connections') {
head('Connections', 'Where your real lamps and air conditioners live');
if (isPhone) nodes.push(h('button.back-link', { onclick: () => select({ kind: 'home' }) }, icon('back', 14, 2.2), 'Home'));
@@ -581,13 +1247,21 @@ export async function bootEditor(root) {
if (isPhone) nodes.push(h('p.note', 'Tap a room, a lamp or anything else on the plan.'));
} else if (kind === 'room') {
head(item.name || item.id, `id: ${item.id}`);
+ const list = levelList();
nodes.push(section('Room',
bind('Name', text(), prop(item, 'name', '')),
- bind('Floor', choice(FLOOR_KINDS), { ...prop(item, 'floor', 'oak'), event: 'change' })),
+ row(bind('Flooring', choice(FLOOR_KINDS), { ...prop(item, 'floor', 'oak'), event: 'change' }),
+ list.length > 1 ? bind('On floor', choice(list.map((l) => [l.id, l.name])), {
+ get: () => item.level ?? firstLevel(), set: (v) => moveRoomToLevel(sel.index, v), event: 'change',
+ }) : null),
+ h('div.fields',
+ h('button.btn', { onclick: () => splitRoom(sel.index) }, icon('split', 14, 2.2), 'Split in two'),
+ h('button.btn', { onclick: duplicate }, icon('duplicate', 14, 2.2), 'Duplicate'))),
section('Position & size, m',
row(bind('X', number(0.1), { ...at(item, 'rect', 0), parse: parseNum }), bind('Z', number(0.1), { ...at(item, 'rect', 1), parse: parseNum })),
row(bind('Width', number(0.1), { ...at(item, 'rect', 2), parse: parseNum }), bind('Depth', number(0.1), { ...at(item, 'rect', 3), parse: parseNum })),
- h('p.note', 'Rooms that share an edge get an interior wall there. Add a door or an “open” gap to connect them.')));
+ h('p.note', isPhone ? 'Drag the dots on its corners and sides to resize it. Rooms that share an edge get an interior wall there; add a door or an “open” gap to connect them.'
+ : 'Drag the dots on its corners and sides to resize it; edges snap to other rooms (hold ⌥ not to). Rooms that share an edge get an interior wall there; add a door or an “open” gap to connect them.')));
} else if (kind === 'light') {
head(item.name || item.id, `id: ${item.id}`);
item.capabilities ||= [];
@@ -629,14 +1303,19 @@ export async function bootEditor(root) {
links.deviceSection(item, 'ac', linkHooks),
links.sensorSection(item, linkHooks));
} else if (kind === 'furniture') {
- head(item.type, 'Decoration only');
+ const stairs = item.type === 'stairs';
+ head(stairs ? 'Stairs' : item.type, stairs ? 'Up to the floor above' : 'Decoration only');
nodes.push(section('Furniture',
bind('Type', choice(FURNITURE_TYPES), { ...prop(item, 'type'), event: 'change' }),
row(bind('X', number(), { ...at(item, 'pos', 0), parse: parseNum }), bind('Z', number(), { ...at(item, 'pos', 1), parse: parseNum })),
row(bind('Rotation, °', number(15), { ...prop(item, 'rot', 0), parse: parseNum }),
bind('Width, m', number(0.1), { ...optional(item, 'width'), parse: optNum })),
- bind('Colour (hex, optional)', text(), optional(item, 'color')),
- h('p.note', 'The short line on the plan marks the front. Rotation 0° faces south (towards the bottom of the plan).')));
+ stairs ? bind('Length, m', number(0.1), { ...optional(item, 'depth'), parse: optNum }) : bind('Colour (hex, optional)', text(), optional(item, 'color')),
+ h('div.fields',
+ h('button.btn', { onclick: () => rotate(90) }, icon('rotateCw', 14, 2.2), 'Turn 90°'),
+ h('button.btn', { onclick: duplicate }, icon('duplicate', 14, 2.2), 'Duplicate')),
+ h('p.note', stairs ? 'Stairs climb in the direction of the arrow and reach the floor above; the floor above shows them faintly, to line its landing up.'
+ : 'The short line on the plan marks the front. Rotation 0° faces south (towards the bottom of the plan).')));
} else if (kind === 'opening') {
head(item.type || 'door', 'A gap or a window in a wall');
nodes.push(section('Opening',
@@ -645,7 +1324,7 @@ export async function bootEditor(root) {
row(bind('To X', number(), { ...at(item, 'to', 0), parse: parseNum }), bind('To Z', number(), { ...at(item, 'to', 1), parse: parseNum })),
item.type === 'window' ? row(bind('Sill, m', number(), { ...prop(item, 'sill', 0.85), parse: parseNum }),
bind('Head, m', number(), { ...prop(item, 'head', 2.1), parse: parseNum })) : null,
- h('p.note', 'Both points must lie on the same wall line (same X or same Z). Windows only show on the far walls; the walls facing the camera are cut away.')));
+ h('p.note', 'Drag it along a wall, or onto another one: it snaps to the walls (hold ⌥ not to). Drag the dots at its ends to make it wider. Windows only show on the far walls; the walls facing the camera are cut away.')));
} else if (kind === 'scene') {
head(item.name || item.id, `id: ${item.id}`);
item.lights ||= {};
@@ -670,7 +1349,7 @@ export async function bootEditor(root) {
event: 'change',
})));
}
- const key = `${sel.kind}:${sel.index ?? sel.service ?? ''}`;
+ const key = `${sel.kind}:${sel.index ?? sel.service ?? sel.id ?? ''}`;
const same = key === inspector.dataset.key;
const top = same ? inspector.scrollTop : 0;
// A refresh of the same screen (devices arriving) keeps the field being typed in.
@@ -853,6 +1532,8 @@ export async function bootEditor(root) {
for (const key of Object.values(KEYS)) doc[key] ||= [];
nameInput.value = doc.name || 'Home';
sel = { kind: 'home' };
+ checkLevel();
+ view = null;
touch();
toast('Plan imported — review it and press “Save & apply”');
};
@@ -874,26 +1555,51 @@ export async function bootEditor(root) {
window.addEventListener('keydown', (ev) => {
const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement?.tagName || '');
- if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'z' && !typing) {
+ const cmd = ev.metaKey || ev.ctrlKey;
+ const key = ev.key.toLowerCase();
+ if (cmd && key === 'z' && !typing) {
ev.preventDefault();
if (ev.shiftKey) stepHistory(redo, undo); else stepHistory(undo, redo);
- } else if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 's') {
+ } else if (cmd && key === 's') {
ev.preventDefault();
save();
- } else if ((ev.key === 'Backspace' || ev.key === 'Delete') && !typing && sel.index != null) {
+ } else if (typing) {
+ // the field gets the key
+ } else if (cmd && key === 'd') {
+ ev.preventDefault();
+ duplicate();
+ } else if (cmd && (key === '0' || key === '=' || key === '+' || key === '-')) {
+ ev.preventDefault();
+ if (key === '0') reveal(); else zoomBy(key === '-' ? 1 / 1.35 : 1.35);
+ } else if (ev.code === 'Space' && !isPhone) {
+ ev.preventDefault();
+ spaceHeld = true;
+ plan.classList.add('can-pan');
+ } else if (ev.key === 'Escape') {
+ if (sel.kind !== 'home') select({ kind: 'home' });
+ } else if (key === 'r' && !cmd) {
+ rotate(ev.shiftKey ? 15 : 90);
+ } else if (ev.key === 'PageUp' || ev.key === 'PageDown') {
+ ev.preventDefault();
+ const list = levelList();
+ const next = list[list.findIndex((l) => l.id === level) + (ev.key === 'PageUp' ? 1 : -1)];
+ if (next) setLevel(next.id);
+ } else if ((ev.key === 'Backspace' || ev.key === 'Delete') && sel.index != null) {
ev.preventDefault();
remove(sel.kind, sel.index);
- } else if (ev.key.startsWith('Arrow') && !typing && sel.index != null) {
+ } else if (ev.key.startsWith('Arrow') && sel.index != null) {
const item = doc[KEYS[sel.kind]][sel.index];
- const target = item.pos || item.rect;
- if (!target) return;
+ const targets = item.from ? [item.from, item.to] : [item.pos || item.rect].filter(Boolean);
+ if (!targets.length) return;
ev.preventDefault();
const stepSize = ev.shiftKey ? 0.5 : 0.05;
snapshot(`nudge${sel.kind}${sel.index}`);
- if (ev.key === 'ArrowLeft') target[0] = fix(target[0] - stepSize);
- if (ev.key === 'ArrowRight') target[0] = fix(target[0] + stepSize);
- if (ev.key === 'ArrowUp') target[1] = fix(target[1] - stepSize);
- if (ev.key === 'ArrowDown') target[1] = fix(target[1] + stepSize);
+ for (const target of targets) {
+ if (ev.key === 'ArrowLeft') target[0] = fix(target[0] - stepSize);
+ if (ev.key === 'ArrowRight') target[0] = fix(target[0] + stepSize);
+ if (ev.key === 'ArrowUp') target[1] = fix(target[1] - stepSize);
+ if (ev.key === 'ArrowDown') target[1] = fix(target[1] + stepSize);
+ }
touch();
}
});
@@ -914,7 +1620,7 @@ export async function bootEditor(root) {
const redoBtn = h('button.p-icon', { 'aria-label': 'Redo', onclick: () => { stepHistory(redo, undo); haptic('light'); } }, icon('redo', 19, 2.1));
const doneBtn = h('button.p-save', { onclick: () => (dirty ? save() : close()) });
const issue = h('div.p-issue');
- const fitBtn = h('button.p-float', { 'aria-label': 'Show the whole plan', onclick: () => { ui.view = null; ui.applyView(); haptic('light'); } }, icon('fit', 18, 2));
+ const fitBtn = h('button.p-float', { 'aria-label': 'Show the whole floor', onclick: () => { reveal(); haptic('light'); } }, icon('fit', 18, 2));
const tool = (name, label, onclick) => h('button.p-tool', { onclick }, icon(name, 22, 1.9), h('span', label));
const view3d = tool('box', '3D', () => setShow3D(!ui.show3D));
const tools = h('nav.p-tools',
@@ -928,12 +1634,13 @@ export async function bootEditor(root) {
sidebar.classList.add('p-list');
listSheet.append(h('div.p-modal-head', h('b', 'Items'), h('button.p-text', { onclick: closeModals }, 'Done')), sidebar);
const addables = [
- ['room', 'home', 'Room'], ['light', 'bulb', 'Lamp'], ['ac', 'ac', 'Air conditioner'],
- ['opening', 'opening', 'Door or window'], ['furniture', 'furniture', 'Furniture'], ['scene', 'sparkles', 'Scene'],
+ ...addable(),
+ ['level', 'layers', 'Floor', () => addLevel()],
+ ['scene', 'sparkles', 'Scene', () => add('scene')],
];
addSheet.append(h('div.p-modal-head', h('b', 'Add to the plan'), h('button.p-text', { onclick: closeModals }, 'Cancel')),
- h('div.p-add-grid', addables.map(([kind, name, label]) => h('button.p-add-item', {
- onclick: () => { closeModals(); add(kind); haptic('light'); ui.reveal(); },
+ h('div.p-add-grid', addables.map(([, name, label, run]) => h('button.p-add-item', {
+ onclick: () => { closeModals(); run(); haptic('light'); if (sel.kind !== 'level') setSheet('peek'); else setSheet('full'); },
}, icon(name, 24, 1.8), h('span', label)))));
confirmSheet.append(h('div.p-modal-head', h('b', 'Unsaved changes')),
h('p.note', 'Save them before closing? Saved plans reach your paired computer too.'),
@@ -943,7 +1650,7 @@ export async function bootEditor(root) {
h('button.btn.wide', { onclick: closeModals }, 'Keep editing')));
sheet.append(grip, inspector);
- canvas.append(plan, h('div.p-preview', previewHost, previewToggle), issue, fitBtn, hint);
+ canvas.append(plan, levelBar, emptyCard, h('div.p-preview', previewHost, previewToggle), issue, fitBtn, hint);
const shell = h('div.editor.phone',
h('header.p-bar', h('button.p-icon', { 'aria-label': 'Close', onclick: requestClose }, icon('close', 20, 2.2)),
nameInput, undoBtn, redoBtn, doneBtn),
@@ -1020,31 +1727,20 @@ export async function bootEditor(root) {
haptic('light');
}
- /* the plan's view: a box in plan metres with the element's aspect, or null to fit */
- function fitBox() {
- const b = bounds();
- const rect = plan.getBoundingClientRect();
- const W = rect.width || 390;
- const H = rect.height || 600;
- // Clear of the fit button on top, a little air on the other sides.
- const pad = { top: 64, side: 18, bottom: 18 };
- const scale = Math.min((W - pad.side * 2) / (b.maxX - b.minX), (H - pad.top - pad.bottom) / (b.maxZ - b.minZ));
- const w = W / scale;
- const hh = H / scale;
- const midY = pad.top + (H - pad.top - pad.bottom) / 2;
- return { x: (b.minX + b.maxX) / 2 - w / 2, y: (b.minZ + b.maxZ) / 2 - midY / scale, w, h: hh };
- }
- new ResizeObserver(() => ui.applyView()).observe(plan);
-
// One finger on what is selected drags it; anywhere else it pans, and a tap picks.
// Two fingers pinch to zoom.
const fingers = new Map();
let gesture = null;
- const box = () => ui.view || fitBox();
const spread = () => { const [a, b] = [...fingers.values()]; return Math.hypot(a.x - b.x, a.y - b.y); };
const middle = () => { const [a, b] = [...fingers.values()]; return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; };
plan.addEventListener('pointerdown', (ev) => {
+ // A first finger starts afresh: a gesture the system took over (a back swipe) never ended here.
+ if (ev.isPrimary && (fingers.size || gesture)) {
+ fingers.clear();
+ gesture = null;
+ if (drag) endDrag();
+ }
plan.setPointerCapture(ev.pointerId);
fingers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
if (fingers.size === 2) {
@@ -1063,11 +1759,12 @@ export async function bootEditor(root) {
const room = sel.kind === 'room' && doc.rooms[sel.index];
const [px, pz] = planPoint(ev);
const inRoom = room && px >= room.rect[0] && px <= room.rect[0] + room.rect[2] && pz >= room.rect[1] && pz <= room.rect[1] + room.rect[3];
- if (kind === 'resize' || (kind && kind !== 'none' && isSel(kind, index)) || (inRoom && kind !== 'light' && kind !== 'ac')) {
- const what = kind === 'resize' || isSel(kind, index) ? [kind, index] : ['room', sel.index];
+ const handle = kind === 'resize' || kind === 'oend';
+ if (handle || (kind && kind !== 'none' && isSel(kind, index)) || (inRoom && kind !== 'light' && kind !== 'ac')) {
+ const what = handle || isSel(kind, index) ? [kind, index] : ['room', sel.index];
// The view holds still while something is dragged past the plan's edge.
- if (!ui.view) ui.view = fitBox();
- startDrag(what[0], what[1], ev);
+ if (!view) view = fitBox();
+ startDrag(what[0], what[1], ev, el?.dataset.handle);
gesture = { type: 'drag' };
return;
}
@@ -1085,16 +1782,16 @@ export async function bootEditor(root) {
const w = clamp(gesture.v0.w * gesture.d0 / Math.max(1, spread()), 1.6, Math.max(fit.w * 2.5, 24));
const hh = w * rect.height / rect.width;
const mid = middle();
- ui.view = { x: gesture.at.x - (mid.x - rect.left) * w / rect.width, y: gesture.at.y - (mid.y - rect.top) * hh / rect.height, w, h: hh };
- ui.applyView();
+ view = { x: gesture.at.x - (mid.x - rect.left) * w / rect.width, y: gesture.at.y - (mid.y - rect.top) * hh / rect.height, w, h: hh };
+ applyView();
} else if (gesture.type === 'pan') {
const dx = ev.clientX - gesture.x;
const dy = ev.clientY - gesture.y;
if (!gesture.moved && Math.hypot(dx, dy) < 8) return;
gesture.moved = true;
const v = gesture.v0;
- ui.view = { ...v, x: v.x - dx * v.w / rect.width, y: v.y - dy * v.h / rect.height };
- ui.applyView();
+ view = { ...v, x: v.x - dx * v.w / rect.width, y: v.y - dy * v.h / rect.height };
+ applyView();
}
});
@@ -1103,7 +1800,7 @@ export async function bootEditor(root) {
if (!gesture) return;
if (gesture.type === 'drag') {
// A tap on what is already selected (just added, say) brings up its details.
- const tapped = ev.type === 'pointerup' && drag && !drag.moved && drag.kind !== 'resize';
+ const tapped = ev.type === 'pointerup' && drag && !drag.moved && drag.kind !== 'resize' && drag.kind !== 'oend';
endDrag();
gesture = null;
if (tapped && ui.sheet === 'closed') { haptic('light'); setSheet('peek'); }
@@ -1117,7 +1814,7 @@ export async function bootEditor(root) {
}
if (gesture.type === 'pan' && !gesture.moved && ev.type === 'pointerup') {
const { kind, index } = gesture;
- if (kind && kind !== 'none' && kind !== 'resize') { haptic('light'); select({ kind, index }); }
+ if (kind && kind !== 'none' && kind !== 'resize' && kind !== 'oend') { haptic('light'); select({ kind, index }); }
else if (ui.sheet !== 'closed') closeSheet();
}
gesture = null;
@@ -1126,30 +1823,21 @@ export async function bootEditor(root) {
plan.addEventListener('pointercancel', lift);
const ui = {
- view: null,
sheet: 'closed',
show3D: false,
- applyView() {
- if (ui.view) {
- // The plan's box changed shape (the sheet came up): keep the middle and the zoom.
- const rect = plan.getBoundingClientRect();
- const hh = rect.width ? ui.view.w * rect.height / rect.width : ui.view.h;
- ui.view = { ...ui.view, y: ui.view.y + (ui.view.h - hh) / 2, h: hh };
- }
- const v = ui.view || fitBox();
- plan.setAttribute('viewBox', `${v.x} ${v.y} ${v.w} ${v.h}`);
- },
// Something was picked (on the plan, in the list, in 3D): its details come up.
selected(next) {
closeModals();
- if (next.kind === 'connections' || next.kind === 'service') setSheet('full');
+ if (next.kind === 'connections' || next.kind === 'service' || next.kind === 'level') setSheet('full');
else if (next.kind !== 'home' && ui.sheet === 'closed') setSheet('peek');
},
- // The item just added may lie outside what is shown: show everything again.
- reveal() { ui.view = null; ui.applyView(); },
headActions() {
const nodes = [];
+ if (sel.kind === 'furniture' || (sel.kind === 'light' && doc.lights[sel.index]?.type === 'strip')) {
+ nodes.push(h('button.p-icon', { 'aria-label': 'Turn 90°', onclick: () => { haptic('light'); rotate(90); } }, icon('rotateCw', 18, 2)));
+ }
if (sel.index != null) {
+ nodes.push(h('button.p-icon', { 'aria-label': 'Duplicate', onclick: () => { haptic('light'); duplicate(); } }, icon('duplicate', 18, 2)));
nodes.push(h('button.p-icon.danger', {
'aria-label': 'Remove', onclick: () => { haptic('medium'); remove(sel.kind, sel.index); setSheet('closed'); },
}, icon('trash', 18, 2)));
@@ -1188,7 +1876,9 @@ export async function bootEditor(root) {
doc = structuredClone(config);
for (const key of Object.values(KEYS)) doc[key] ||= [];
nameInput.value = doc.name || 'Home';
+ checkLevel();
if (sel.index != null && !doc[KEYS[sel.kind]]?.[sel.index]) sel = { kind: 'home' };
+ if (sel.kind === 'level' && !levelList().some((l) => l.id === sel.id)) sel = { kind: 'home' };
touch();
dirty = false;
validate();
diff --git a/web/src/main.js b/web/src/main.js
index 2767279..564e0b5 100644
--- a/web/src/main.js
+++ b/web/src/main.js
@@ -12,6 +12,7 @@ import { publishWidgets, runWidgetAction } from './widgets.js';
const DEMO_PLANS = [
{ id: 'home', name: 'Demo · Apartment' },
{ id: 'studio', name: 'Demo · Studio' },
+ { id: 'house', name: 'Demo · House on two floors' },
];
const STAGE_INSETS = [62, 50]; // header above, panel overlap below
@@ -75,6 +76,11 @@ async function boot() {
try {
world = createWorld(panel.canvas, config, store, {
+ level: savedLevel(config),
+ onLevel(id) {
+ panel.levelShown(id);
+ try { localStorage.setItem(levelKey(config), id); } catch { /* private mode */ }
+ },
onHover: panel.showTooltip,
onPick(target) {
if (!target) return;
@@ -123,9 +129,11 @@ async function boot() {
// On a phone the header sits lower (status bar) but is closer to the model; with the
// stage to itself (beside the controls, or above the fold) nothing covers its foot.
+ // The floor buttons of a home on several floors sit under the model: it moves up clear of them.
+ const floorsInset = config.levels.length > 1 ? 44 : 0;
function applyInsets() {
- if (isPhone) world.setInsets(50 + safeAreaTop(), layout?.kind === 'stack' ? 36 : 0);
- else world.setInsets(...STAGE_INSETS);
+ if (isPhone) world.setInsets(50 + safeAreaTop(), (layout?.kind === 'stack' ? 36 : 0) + floorsInset);
+ else world.setInsets(STAGE_INSETS[0], STAGE_INSETS[1] + floorsInset);
}
applyInsets();
new ResizeObserver(() => (isPhone ? applyInsets() : world.resize())).observe(panel.canvas);
@@ -252,6 +260,12 @@ async function boot() {
window.__house = { store, world, panel, config }; // handy in the dev console
}
+// The floor a home on several floors was last looked at, kept per home.
+const levelKey = (config) => `house.level:${config.name}`;
+function savedLevel(config) {
+ try { return localStorage.getItem(levelKey(config)); } catch { return null; }
+}
+
// A still of the 3D model for an AI checking its own edit: a second, off-screen world
// rendered once and thrown away, so the panel's own view is left as it is.
async function renderShot(config, store, room) {
diff --git a/web/src/style.css b/web/src/style.css
index cd24596..722b395 100644
--- a/web/src/style.css
+++ b/web/src/style.css
@@ -307,6 +307,60 @@ html.native .card { width: auto; height: auto; box-shadow:
}
.room .count.zero { transform: scale(0); opacity: 0; min-width: 0; width: 0; padding: 0; margin-left: -7px; }
+/* Floors of a home on several: a row of buttons under the model, the panel just below it. */
+.floors {
+ position: absolute;
+ bottom: 44px;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 4;
+ max-width: calc(100% - 28px);
+ display: flex;
+ gap: 3px;
+ padding: 4px;
+ border-radius: 18px;
+ background: rgba(16, 21, 36, 0.55);
+ border: 1px solid var(--line);
+ backdrop-filter: blur(14px) saturate(1.4);
+ -webkit-backdrop-filter: blur(14px) saturate(1.4);
+}
+.floors[hidden] { display: none; }
+.floor {
+ height: 30px;
+ min-width: 0;
+ max-width: 160px;
+ padding: 0 11px;
+ border-radius: 999px;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--muted);
+ border: 1px solid transparent;
+ transition: background 220ms, color 220ms, border-color 220ms, transform 260ms var(--spring);
+}
+.floor span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+@media (hover: hover) { .floor:hover { color: var(--text); background: var(--glass); } }
+.floor:active { transform: scale(0.95); }
+.floor.active { color: var(--text); background: var(--accent); box-shadow: 0 4px 14px -4px var(--accent); }
+.floor .count {
+ min-width: 17px; height: 17px; padding: 0 5px; border-radius: 9px;
+ display: grid; place-items: center;
+ font-size: 10.5px; font-weight: 700;
+ color: #2a1a05; background: var(--warm);
+ transition: transform 260ms var(--spring), opacity 200ms;
+}
+.floor .count.zero { transform: scale(0); opacity: 0; min-width: 0; width: 0; padding: 0; margin-left: -7px; }
+.level-label {
+ grid-column: 1 / -1;
+ margin: 14px 2px 0;
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--text);
+}
+.level-label:first-child { margin-top: 0; }
+
.list-head {
display: flex;
align-items: center;
@@ -773,6 +827,9 @@ html.ios .menu button { height: 46px; font-size: 15px; border-radius: 14px; }
html.ios .menu button:active { background: rgba(255, 255, 255, 0.1); color: var(--text); }
html.ios .panel-toast { bottom: calc(var(--safe-bottom) + 14px); font-size: 13.5px; }
html.ios .tooltip { display: none; }
+html.ios .floor { height: 34px; font-size: 13px; padding: 0 13px; }
+html.ios.split .floors { bottom: calc(var(--safe-bottom) + 16px); }
+html.ios.table .floors { bottom: 12px; }
html.ios .fatal { margin: calc(env(safe-area-inset-top, 0px) + 20px) 16px 0; width: auto; }
/* ---------- iPhone Duo and other wide screens ---------- */
diff --git a/web/src/three/furniture.js b/web/src/three/furniture.js
index efdb613..51f73db 100644
--- a/web/src/three/furniture.js
+++ b/web/src/three/furniture.js
@@ -320,6 +320,32 @@ const builders = {
}
return g;
},
+
+ // A straight flight up to the floor above: you step on at the front (+z) and climb towards the back.
+ stairs({ width = 1, depth = 2.8, height = 2.9 }) {
+ const steps = Math.max(3, Math.round(height / 0.18));
+ const rise = height / steps;
+ const run = depth / steps;
+ const body = mat('#d9d4cb', { rough: 0.9 });
+ const tread = mat(WOOD, { rough: 0.6 });
+ const g = new THREE.Group();
+ for (let i = 0; i < steps; i++) {
+ const z = depth / 2 - run * (i + 0.5);
+ g.add(at(box(width, rise * i + rise - 0.03, run, body, { r: 0 }), 0, 0, z));
+ g.add(at(box(width + 0.02, 0.03, run + 0.02, tread, { r: 0.008 }), 0, rise * (i + 1) - 0.03, z));
+ }
+ // A handrail along the open side.
+ const rail = mat(BLACK, { rough: 0.5 });
+ const slope = Math.atan2(height, depth);
+ const length = Math.hypot(height, depth);
+ const bar = at(box(0.04, 0.04, length, rail, { r: 0.015 }), width / 2 - 0.03, height / 2 + 0.9, 0);
+ bar.rotation.x = slope;
+ g.add(bar);
+ for (const t of [0.1, 0.5, 0.9]) {
+ g.add(at(box(0.025, 0.9, 0.025, rail, { r: 0 }), width / 2 - 0.03, height * t, depth / 2 - depth * t));
+ }
+ return g;
+ },
};
export const FURNITURE_TYPES = Object.keys(builders);
@@ -348,6 +374,7 @@ export function footprint(item) {
case 'desk': return [w || 1.4, 0.65];
case 'wardrobe': return [w || 1.6, 0.6];
case 'bookshelf': return [w || 1, 0.32];
+ case 'stairs': return [w || 1, item.depth || 2.8];
default: return [0.6, 0.6];
}
}
diff --git a/web/src/three/house.js b/web/src/three/house.js
index 912ed44..7ac51ac 100644
--- a/web/src/three/house.js
+++ b/web/src/three/house.js
@@ -1,6 +1,7 @@
// Turns the rooms + openings of a plan into floors, walls and windows.
import * as THREE from 'three';
import { box, mat, at, floorMesh } from './kit.js';
+import { SLAB } from '../config.js';
const EXT_T = 0.2; // exterior wall thickness
const INT_T = 0.1; // interior wall thickness
@@ -64,20 +65,34 @@ function wallSegments(config) {
return segments;
}
-export function buildHouse(config, camDir) {
+// One floor of the home, standing on y = 0: `level` is one of config.levels. The lowest
+// stands on a plinth; a floor above it rests on a slab under each of its rooms.
+export function buildHouse(config, camDir, level = config.levels[0]) {
const group = new THREE.Group();
const floors = [];
- const H = config.wallHeight;
+ const H = level.wallHeight;
const Hi = Math.min(config.interiorWallHeight, H);
- const { minX, minZ, maxX, maxZ } = config.bounds;
+ const rooms = config.rooms.filter((r) => r.level === level.id);
+ const openings = config.openings.filter((o) => o.level === level.id);
+ const { minX, minZ, maxX, maxZ } = level.bounds;
- // Plinth the model stands on.
- const plinth = box(maxX - minX + 0.7, 0.3, maxZ - minZ + 0.7, mat('#141927', { rough: 0.9 }), { r: 0.12 });
- at(plinth, (minX + maxX) / 2, -0.305, (minZ + maxZ) / 2);
- plinth.receiveShadow = true;
- group.add(plinth);
+ if (level.elevation === 0) {
+ // Plinth the model stands on.
+ const plinth = box(maxX - minX + 0.7, 0.3, maxZ - minZ + 0.7, mat('#141927', { rough: 0.9 }), { r: 0.12 });
+ at(plinth, (minX + maxX) / 2, -0.305, (minZ + maxZ) / 2);
+ plinth.receiveShadow = true;
+ group.add(plinth);
+ } else {
+ const slab = mat('#1d2232', { rough: 0.9 });
+ for (const r of rooms) {
+ const s = box(r.w + EXT_T, SLAB - 0.01, r.d + EXT_T, slab, { r: 0 });
+ at(s, r.x + r.w / 2, -SLAB, r.z + r.d / 2);
+ s.receiveShadow = true;
+ group.add(s);
+ }
+ }
- for (const room of config.rooms) {
+ for (const room of rooms) {
const floor = floorMesh(room, room.floor);
floor.userData = { kind: 'room', id: room.id };
floors.push(floor);
@@ -106,7 +121,7 @@ export function buildHouse(config, camDir) {
return m;
};
- for (const s of wallSegments(config)) {
+ for (const s of wallSegments({ rooms, openings })) {
const exterior = s.kind === 'exterior';
const t = exterior ? EXT_T : INT_T;
// Outward normal of an exterior wall points away from its room.
diff --git a/web/src/three/world.js b/web/src/three/world.js
index 84485cd..270c33a 100644
--- a/web/src/three/world.js
+++ b/web/src/three/world.js
@@ -19,7 +19,7 @@ const EL_MAX = 70;
const ZOOM_MIN = 0.55; // closest
const ZOOM_MAX = 1.2;
-export function createWorld(canvas, config, store, { onHover, onPick, background = STAGE_BG }) {
+export function createWorld(canvas, config, store, { onHover, onPick, onLevel = () => {}, level: firstLevel, background = STAGE_BG }) {
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
@@ -34,24 +34,33 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
const camera = new THREE.PerspectiveCamera(24, 1, 0.5, 120);
const { minX, minZ, maxX, maxZ } = config.bounds;
- const H = config.wallHeight;
const center = new THREE.Vector3((minX + maxX) / 2, 0, (minZ + maxZ) / 2);
const span = Math.max(maxX - minX, maxZ - minZ);
+ // A home on several floors shows one at a time, with the floors under it: `level` is it.
+ const levelById = new Map(config.levels.map((l) => [l.id, l]));
+ let level = levelById.get(firstLevel) || config.levels[0];
const baseAz = config.camera.azimuth;
const camDir = new THREE.Vector3(Math.sin(rad(baseAz)), 0, Math.cos(rad(baseAz)));
/* ---------- content ---------- */
- const house = buildHouse(config, camDir);
- scene.add(house.group);
- scene.add(buildFurniture(config.furniture));
+ let shadowFrames = 3; // shadow maps are rendered again for this many frames
+ const floors = new Map(); // level id -> { group, house }
+ for (const l of config.levels) {
+ const group = new THREE.Group();
+ group.position.y = l.elevation;
+ const house = buildHouse(config, camDir, l);
+ group.add(house.group, buildFurniture(config.furniture.filter((f) => f.level === l.id)));
+ scene.add(group);
+ floors.set(l.id, { group, house });
+ }
const lights = new Map();
for (const cfg of config.lights) {
- const unit = new LightUnit(cfg, H);
+ const unit = new LightUnit(cfg, levelById.get(cfg.level).wallHeight);
lights.set(cfg.id, unit);
- scene.add(unit.group);
+ floors.get(cfg.level).group.add(unit.group);
}
// Every shadow-casting lamp costs the shader a texture sampler, and WebGL caps how many
@@ -63,38 +72,54 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
const SHADOW_PRIORITY = { ceiling: 0, pendant: 1, floor: 2, spots: 3, table: 4, strip: 9 };
const canShadow = (unit) => unit.lights.some((l) => l.userData.canShadow);
const shadowCap = Math.max(1, Math.min(8, renderer.capabilities.maxTextures - 6));
- const ranked = [...lights.values()].sort((a, b) =>
- (SHADOW_PRIORITY[a.cfg.type] ?? 9) - (SHADOW_PRIORITY[b.cfg.type] ?? 9));
- // One lamp per room first, so every room keeps some depth, then fill up to the cap.
- const shadowOrder = [];
- const seenRooms = new Set();
- for (const unit of ranked) {
- if (shadowOrder.length >= shadowCap) break;
- if (canShadow(unit) && !seenRooms.has(unit.cfg.room)) { shadowOrder.push(unit); seenRooms.add(unit.cfg.room); }
- }
- for (const unit of ranked) {
- if (shadowOrder.length >= shadowCap) break;
- if (canShadow(unit) && !shadowOrder.includes(unit)) shadowOrder.push(unit);
- }
- for (const unit of lights.values()) {
- const keep = shadowOrder.includes(unit);
- for (const l of unit.lights) if (l.userData.canShadow) l.castShadow = keep;
+ // Only the floor on show lights its rooms, so the slots go to its lamps.
+ function assignShadows() {
+ const ranked = [...lights.values()].filter((u) => u.cfg.level === level.id).sort((a, b) =>
+ (SHADOW_PRIORITY[a.cfg.type] ?? 9) - (SHADOW_PRIORITY[b.cfg.type] ?? 9));
+ // One lamp per room first, so every room keeps some depth, then fill up to the cap.
+ const shadowOrder = [];
+ const seenRooms = new Set();
+ for (const unit of ranked) {
+ if (shadowOrder.length >= shadowCap) break;
+ if (canShadow(unit) && !seenRooms.has(unit.cfg.room)) { shadowOrder.push(unit); seenRooms.add(unit.cfg.room); }
+ }
+ for (const unit of ranked) {
+ if (shadowOrder.length >= shadowCap) break;
+ if (canShadow(unit) && !shadowOrder.includes(unit)) shadowOrder.push(unit);
+ }
+ for (const unit of lights.values()) {
+ const keep = shadowOrder.includes(unit);
+ for (const l of unit.lights) if (l.userData.canShadow) l.castShadow = keep;
+ }
}
const acs = new Map();
for (const cfg of config.acs) {
const unit = new ACUnit(cfg);
acs.set(cfg.id, unit);
- scene.add(unit.group);
+ floors.get(cfg.level).group.add(unit.group);
+ }
+ let hitTargets = [];
+
+ // The floors above the one on show are lifted off; the ones under it stay, unlit, as its base.
+ function showLevel() {
+ for (const [id, { group }] of floors) group.visible = levelById.get(id).elevation <= level.elevation;
+ for (const unit of [...lights.values(), ...acs.values()]) unit.group.visible = unit.cfg.level === level.id;
+ hitTargets = [
+ ...[...lights.values()].filter((u) => u.group.visible).map((u) => u.hit),
+ ...[...acs.values()].filter((u) => u.group.visible).map((u) => u.hit),
+ ...floors.get(level.id).house.floors,
+ ];
+ assignShadows();
+ moon.position.set(center.x + camDir.x * 3.2 + 1.5, level.elevation + 10, center.z + camDir.z * 3.2 - 1.5);
+ moon.target.position.set(center.x, level.elevation, center.z);
+ shadowFrames = 3;
}
- const hitTargets = [...[...lights.values()].map((u) => u.hit), ...[...acs.values()].map((u) => u.hit), ...house.floors];
// Night-time ambience: enough to read the model with every lamp off.
scene.add(new THREE.HemisphereLight(0x8ea6ff, 0x0b0e17, 0.42));
const moon = new THREE.DirectionalLight(0xa9c0ff, 0.6);
// Steep and coming from the viewer's side, so the faces we look at stay readable.
- moon.position.copy(center).add(new THREE.Vector3(camDir.x * 3.2 + 1.5, 10, camDir.z * 3.2 - 1.5));
- moon.target.position.copy(center);
moon.castShadow = true;
moon.shadow.mapSize.set(2048, 2048);
const sc = moon.shadow.camera;
@@ -102,6 +127,7 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
sc.right = sc.top = span * 0.85;
sc.near = 1;
sc.far = 30;
+ showLevel();
moon.shadow.bias = -0.0008;
moon.shadow.normalBias = 0.04;
moon.shadow.radius = 4;
@@ -161,19 +187,22 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
const f = rig.focus;
let box;
let fill = 0.96;
+ const y = level.elevation;
+ const H = level.wallHeight;
if (f?.kind === 'room') {
const r = config.rooms.find((x) => x.id === f.id);
- box = new THREE.Box3(new THREE.Vector3(r.x, 0, r.z), new THREE.Vector3(r.x + r.w, H * 0.75, r.z + r.d));
+ box = new THREE.Box3(new THREE.Vector3(r.x, y, r.z), new THREE.Vector3(r.x + r.w, y + H * 0.75, r.z + r.d));
fill = 0.84;
} else if (f?.kind === 'ac') {
const unit = acs.get(f.id);
- const p = unit.group.position;
+ const p = unit.group.getWorldPosition(new THREE.Vector3());
const out = new THREE.Vector3(0, 0, 1).applyQuaternion(unit.group.quaternion);
box = new THREE.Box3().setFromCenterAndSize(
- new THREE.Vector3(p.x + out.x * 1.3, 1.25, p.z + out.z * 1.3), new THREE.Vector3(3.6, 2.6, 3.6));
+ new THREE.Vector3(p.x + out.x * 1.3, y + 1.25, p.z + out.z * 1.3), new THREE.Vector3(3.6, 2.6, 3.6));
fill = 0.92;
} else {
- box = new THREE.Box3(new THREE.Vector3(minX, 0, minZ), new THREE.Vector3(maxX, H * 0.8, maxZ));
+ const b = level.bounds;
+ box = new THREE.Box3(new THREE.Vector3(b.minX, y, b.minZ), new THREE.Vector3(b.maxX, y + H * 0.8, b.maxZ));
}
const { dist, center: c } = fitDistance(box, rig.goal.az, rig.goal.el, fill);
rig.goal.dist = dist * rig.zoom;
@@ -336,7 +365,6 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
let last = 0;
let awake = 0; // frames still owed after the last change
let running = false;
- let shadowFrames = 3;
function wake(frames = 2) {
awake = Math.max(awake, frames);
@@ -384,7 +412,23 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
setInsets(top, bottom) { topInset = top; bottomInset = bottom; resize(); },
resize,
+ get level() { return level.id; },
+
+ // Shows another floor of the home (and the ones under it).
+ setLevel(id) {
+ const next = levelById.get(id);
+ if (!next || next === level) return;
+ level = next;
+ showLevel();
+ if (rig.focus && levelOf(rig.focus) !== level.id) rig.focus = null;
+ frameGoal();
+ wake(4);
+ onLevel(level.id);
+ },
+
focus(next) {
+ const on = next && levelOf(next);
+ if (on && on !== level.id) world.setLevel(on);
rig.focus = next;
rig.zoom = 1;
rig.goal.az = baseAz + (next?.kind === 'ac' ? (WALL_SIDE[acs.get(next.id).cfg.wall] ?? 0) : 0);
@@ -436,6 +480,12 @@ export function createWorld(canvas, config, store, { onHover, onPick, background
},
};
+ // The floor a room, a lamp or an AC is on.
+ function levelOf(t) {
+ if (t.kind === 'room') return config.rooms.find((r) => r.id === t.id)?.level;
+ return (t.kind === 'ac' ? acs : lights).get(t.id)?.cfg.level;
+ }
+
syncAll({ instant: true });
resize();
updateRig(0, true);
diff --git a/web/src/ui/icons.js b/web/src/ui/icons.js
index 6fa2817..3be08e6 100644
--- a/web/src/ui/icons.js
+++ b/web/src/ui/icons.js
@@ -7,6 +7,7 @@ import {
Undo2, Activity, KeyRound, ArrowUpRight, Camera, Square,
HouseWifi, Smartphone, Radar, CircleCheck, CircleAlert, ChevronRight, Unlink, LoaderCircle, Router,
List, Trash2, Scan, Redo2, Map as MapIcon, DoorClosed, Armchair,
+ Layers, ChevronsUp, RotateCw, ZoomIn, ZoomOut, SquareSplitHorizontal, CopyPlus, AppWindow, SquareDashed,
} from 'lucide';
const ICONS = {
@@ -23,6 +24,8 @@ const ICONS = {
homeassistant: HouseWifi, phone: Smartphone, radar: Radar, ok: CircleCheck, alert: CircleAlert,
next: ChevronRight, unlink: Unlink, spinner: LoaderCircle, bridge: Router, bulb: Lightbulb,
list: List, trash: Trash2, fit: Scan, redo: Redo2, map: MapIcon, opening: DoorClosed, furniture: Armchair,
+ layers: Layers, stairs: ChevronsUp, rotateCw: RotateCw, zoomIn: ZoomIn, zoomOut: ZoomOut,
+ split: SquareSplitHorizontal, duplicate: CopyPlus, window: AppWindow, room: SquareDashed,
};
export function icon(name, size = 18, stroke = 1.8) {
diff --git a/web/src/ui/panel.js b/web/src/ui/panel.js
index 7211e8b..3f443ed 100644
--- a/web/src/ui/panel.js
+++ b/web/src/ui/panel.js
@@ -33,9 +33,11 @@ function acTemperatureColor(target, cfg) {
export function createPanel(root, config, store, { onFocus, onMenu }) {
const { state } = store;
- const ui = { room: 'all', sheet: null };
+ const ui = { room: 'all', sheet: null, level: config.levels[0].id };
let world = null;
const roomName = new Map(config.rooms.map((r) => [r.id, r.name]));
+ const roomLevel = new Map(config.rooms.map((r) => [r.id, r.level]));
+ const multiLevel = config.levels.length > 1;
/* ---------- skeleton ---------- */
@@ -62,8 +64,18 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {
sheet.inert = true;
const toastEl = h('div.panel-toast');
+ // A home on several floors: one button per floor under the 3D model, lowest first.
+ const floorButtons = new Map();
+ const floors = h('div.floors', { role: 'group', 'aria-label': 'Floors', hidden: !multiLevel },
+ config.levels.map((l) => {
+ const count = h('span.count.zero', '0');
+ const b = h('button.floor', { 'aria-label': l.name, onclick: () => { haptic('tick'); showLevel(l.id); } }, h('span', l.name), count);
+ floorButtons.set(l.id, { b, count });
+ return b;
+ }));
+
const clip = h('div.card-clip',
- h('div.stage', canvas),
+ h('div.stage', canvas, floors),
h('div.tint'),
h('header.top',
h('div.home', h('div.home-badge', icon('home', 17)),
@@ -102,6 +114,20 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {
onFocus(id === 'all' ? null : { kind: 'room', id });
}
+ // The model shows another floor; a room on a different one is let go.
+ function showLevel(id) {
+ if (ui.room !== 'all' && roomLevel.get(ui.room) !== id) { ui.room = 'all'; layoutTiles(); }
+ world?.setLevel(id);
+ levelShown(id);
+ }
+
+ function levelShown(id) {
+ if (ui.level === id) return;
+ ui.level = id;
+ if (multiLevel && ui.room === 'all') layoutTiles();
+ update();
+ }
+
function inScope(cfg) {
return ui.room === 'all' || cfg.room === ui.room;
}
@@ -249,13 +275,19 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {
const nodes = [];
let i = 0;
const add = (t) => { t.el.style.setProperty('--i', i++); nodes.push(t.el); };
- for (const room of config.rooms) {
- if (ui.room !== 'all' && room.id !== ui.room) continue;
- const devices = [...tiles.values()].filter((t) => t.cfg.room === room.id);
- if (!devices.length) continue;
- if (ui.room === 'all') nodes.push(h('div.group-label', room.name));
- devices.filter((t) => t.kind === 'ac').forEach(add);
- devices.filter((t) => t.kind === 'light').forEach(add);
+ // On several floors the one on show comes first, each under its own heading.
+ const levels = [...config.levels].sort((a, b) => (b.id === ui.level) - (a.id === ui.level));
+ for (const level of levels) {
+ const before = nodes.length;
+ for (const room of config.rooms) {
+ if (room.level !== level.id || (ui.room !== 'all' && room.id !== ui.room)) continue;
+ const devices = [...tiles.values()].filter((t) => t.cfg.room === room.id);
+ if (!devices.length) continue;
+ if (ui.room === 'all') nodes.push(h('div.group-label', room.name));
+ devices.filter((t) => t.kind === 'ac').forEach(add);
+ devices.filter((t) => t.kind === 'light').forEach(add);
+ }
+ if (multiLevel && ui.room === 'all' && nodes.length > before) nodes.splice(before, 0, h('div.level-label', level.name));
}
if (!nodes.length) nodes.push(h('div.group-label', 'No devices in this room yet'));
else if (isPhone && config.lights.some((l) => l.capabilities.length && inScope(l))) {
@@ -535,6 +567,13 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {
count.textContent = n;
count.classList.toggle('zero', n === 0 || id === 'all');
}
+ for (const [id, { b, count }] of floorButtons) {
+ b.classList.toggle('active', ui.level === id);
+ b.setAttribute('aria-pressed', String(ui.level === id));
+ const n = config.lights.filter((l) => l.level === id && state.lights[l.id].on).length;
+ count.textContent = n;
+ count.classList.toggle('zero', n === 0);
+ }
const scoped = config.lights.filter(inScope);
const scopedOn = scoped.filter((l) => state.lights[l.id].on).length;
@@ -557,7 +596,9 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {
return {
canvas,
card,
- attach(w) { world = w; card.classList.remove('booting'); },
+ attach(w) { world = w; card.classList.remove('booting'); levelShown(w.level); },
+ /** The model went to another floor by itself (a room or a device on it was picked). */
+ levelShown,
showTooltip,
openSheet,
closeSheet,
diff --git a/web/src/widgets.js b/web/src/widgets.js
index 117433f..14c2ead 100644
--- a/web/src/widgets.js
+++ b/web/src/widgets.js
@@ -13,8 +13,16 @@ function links(device) {
return Object.keys(out).length ? out : null;
}
+// On a home with several floors the widgets draw one: the one with the most lamps on, or the first.
+function shownLevel(config, state) {
+ if (config.levels.length < 2) return null;
+ const on = (id) => config.lights.filter((l) => l.level === id && state.lights[l.id].on).length;
+ return config.levels.reduce((best, l) => (on(l.id) > on(best.id) ? l : best), config.levels[0]).id;
+}
+
export function widgetSnapshot(config, store, plan) {
const { state } = store;
+ const multi = config.levels.length > 1;
return {
version: 1,
name: config.name,
@@ -22,7 +30,9 @@ export function widgetSnapshot(config, store, plan) {
outdoorTemp: config.outdoorTemp,
updated: Date.now() / 1000,
scene: state.scene || null,
- rooms: config.rooms.map((r) => ({ id: r.id, name: r.name, x: r.x, z: r.z, w: r.w, d: r.d, floor: r.floor })),
+ levels: multi ? config.levels.map((l) => ({ id: l.id, name: l.name })) : undefined,
+ shownLevel: shownLevel(config, state) ?? undefined,
+ rooms: config.rooms.map((r) => ({ id: r.id, name: r.name, x: r.x, z: r.z, w: r.w, d: r.d, floor: r.floor, level: multi ? r.level : undefined })),
lights: config.lights.map((l) => {
const s = state.lights[l.id];
return {
@@ -41,7 +51,7 @@ export function widgetSnapshot(config, store, plan) {
}),
furniture: config.furniture.filter((f) => Array.isArray(f.pos)).map((f) => {
const [w, d] = footprint(f);
- return { type: f.type, x: f.pos[0], z: f.pos[1], w, d, rot: f.rot || 0, color: f.color || null };
+ return { type: f.type, x: f.pos[0], z: f.pos[1], w, d, rot: f.rot || 0, color: f.color || null, level: multi ? f.level : undefined };
}),
scenes: config.scenes.map((s) => ({ id: s.id, name: s.name, icon: s.icon, lights: s.lights, acs: s.acs })),
};
diff --git a/widgets/Sources/HouseModel.swift b/widgets/Sources/HouseModel.swift
index 3427d91..f3412df 100644
--- a/widgets/Sources/HouseModel.swift
+++ b/widgets/Sources/HouseModel.swift
@@ -85,12 +85,22 @@ private struct Wall: Identifiable {
/// The home as a small 3D model: floors, walls, every lamp glowing in its colour on the
/// floor of its room, the ACs on their walls. With `interactive`, each lamp is a button.
struct HouseModel: View {
+ /// The floor drawn: on a home with several, the one with the most lamps on.
let home: HomeSnapshot
var padding: CGFloat = 8
var interactive = false
/// Larger dots and glows for a small widget, where the model is tiny.
var boost: Double = 1
private let look = WidgetLook()
+ private let summary: String
+
+ init(home: HomeSnapshot, padding: CGFloat = 8, interactive: Bool = false, boost: Double = 1) {
+ self.home = home.shownFloor
+ self.padding = padding
+ self.interactive = interactive
+ self.boost = boost
+ summary = "\(home.name): \(home.lightsLine)"
+ }
var body: some View {
GeometryReader { geo in
@@ -106,7 +116,7 @@ struct HouseModel: View {
.frame(width: geo.size.width, height: geo.size.height, alignment: .topLeading)
}
.accessibilityElement(children: interactive ? .contain : .ignore)
- .accessibilityLabel("\(home.name): \(home.lightsLine)")
+ .accessibilityLabel(summary)
}
private func roomCorners(_ r: HomeSnapshot.Room, _ iso: IsoProjection, inset: Double = 0) -> [CGPoint] {
diff --git a/widgets/Sources/Style.swift b/widgets/Sources/Style.swift
index e267f15..e9c4061 100644
--- a/widgets/Sources/Style.swift
+++ b/widgets/Sources/Style.swift
@@ -115,7 +115,10 @@ extension HomeSnapshot {
copy.rooms = [room]
copy.lights = lights.filter { $0.room == id }
copy.acs = acs.filter { $0.room == id }
- copy.furniture = furniture?.filter { $0.x >= room.x && $0.x <= room.x + room.w && $0.z >= room.z && $0.z <= room.z + room.d }
+ copy.furniture = furniture?.filter {
+ $0.level == room.level && $0.x >= room.x && $0.x <= room.x + room.w && $0.z >= room.z && $0.z <= room.z + room.d
+ }
+ copy.shownLevel = nil
return copy
}
}