diff --git a/ops/home/house3d-card.js b/ops/home/house3d-card.js
index a5d16f1..0e491b6 100644
--- a/ops/home/house3d-card.js
+++ b/ops/home/house3d-card.js
@@ -1,155 +1,216 @@
-/* house3d-card — прототип 3D-карты для Home Assistant.
- * Одна комната, кликабельный светильник, обновление цвета из состояния HA.
- * Конфиг:
- * type: custom:house3d-card
- * entity: light.svet_v_tambure_svet_v_tambure
- * title: Спальня (прототип)
+/* house3d-card v3 — 3D-сцена в Home Assistant с оптимистичным откликом.
+ *
+ * v3:
+ * • мгновенная реакция интерфейса (оптимистичное переключение) — не ждём,
+ * пока интеграция обновит состояние;
+ * • индикатор «применяется…» (пульсирующий чип), затем сверка с hass.states;
+ * • откат и сообщение об ошибке, если сервис не сработал;
+ * • защита от двойного клика во время применения;
+ * • невидимый хитбокс, hover-подсветка, тактильный отклик.
+ *
+ * Конфиг: type: custom:house3d-card
+ * entity: switch.xxx, domain: switch, service: toggle, title, room
*/
class House3dCard extends HTMLElement {
setConfig(config) {
- this._config = Object.assign({ entity: "", title: "3D", domain: "light", service: "toggle" }, config || {});
+ this._config = Object.assign(
+ { entity: "", title: "3D", domain: "light", service: "toggle", room: "Комната", pending_ms: 6000 },
+ config || {},
+ );
this._root = this.attachShadow({ mode: "open" });
this._root.innerHTML = `
-
-
клик по светильнику — вкл/выкл · тянуть — поворот · колесо — зум
`;
+
+
${this._config.title}${this._config.room}
+
—
+
+
клик по светильнику — вкл/выкл · тянуть — поворот · колесо — зум
+
загрузка сцены…
+
`;
this._wrap = this._root.querySelector(".wrap");
- this._hud = this._root.querySelector(".hud");
- this._stateEl = this._root.querySelector(".state");
- this._hud.textContent = this._config.title;
+ this._dot = this._root.querySelector(".dot");
+ this._txt = this._root.querySelector(".txt");
+ this._chip = this._root.querySelector(".chip");
+ this._err = this._root.querySelector(".err");
+ this._load = this._root.querySelector(".load");
}
set hass(hass) {
this._hass = hass;
- if (!this._ready) this._boot();
+ if (!this._booted) this._boot();
this._syncState();
}
_boot() {
- if (this._booted) return;
this._booted = true;
- const src = "/local/house3d/three.min.js";
- const start = () => this._build();
- if (window.THREE) return start();
+ if (window.THREE) return this._build();
const s = document.createElement("script");
- s.src = src;
- s.onload = start;
- s.onerror = () => { this._wrap.innerHTML = 'three.js не загрузился
'; };
+ s.src = "/local/house3d/three.min.js";
+ s.onload = () => this._build();
+ s.onerror = () => { this._load.textContent = "three.js не загрузился"; };
document.head.appendChild(s);
}
+ _glowTexture() {
+ const c = document.createElement("canvas");
+ c.width = c.height = 128;
+ const g = c.getContext("2d");
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ grd.addColorStop(0, "rgba(255,220,160,0.95)");
+ grd.addColorStop(0.35, "rgba(255,190,110,0.35)");
+ grd.addColorStop(1, "rgba(255,170,80,0)");
+ g.fillStyle = grd;
+ g.fillRect(0, 0, 128, 128);
+ return new window.THREE.CanvasTexture(c);
+ }
+
_build() {
- if (!window.THREE) return;
const T = window.THREE;
+ if (!T) return;
+ this._load.style.display = "none";
const W = this._wrap.clientWidth || 800;
- const H = this._wrap.clientHeight || 420;
+ const H = this._wrap.clientHeight || 440;
this._scene = new T.Scene();
- this._scene.fog = new T.Fog(0x0b0f14, 12, 30);
- this._cam = new T.PerspectiveCamera(42, W / H, 0.1, 100);
- this._cam.position.set(4.2, 3.4, 5.2);
- this._cam.lookAt(0, 0.9, 0);
-
+ this._scene.fog = new T.Fog(0x070b0f, 9, 26);
+ this._cam = new T.PerspectiveCamera(40, W / H, 0.1, 100);
+ this._cam.position.set(4.0, 3.0, 5.0);
+ this._cam.lookAt(0, 1.0, 0);
this._renderer = new T.WebGLRenderer({ antialias: true, alpha: true });
this._renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this._renderer.setSize(W, H);
this._wrap.appendChild(this._renderer.domElement);
- // свет
- this._scene.add(new T.HemisphereLight(0x6f8bb0, 0x141a22, 0.55));
- this._point = new T.PointLight(0xffd7a0, 0, 12, 2);
- this._point.position.set(0, 2.4, 0);
+ this._scene.add(new T.HemisphereLight(0x5878a0, 0x0a0f14, 0.42));
+ this._point = new T.PointLight(0xffcf98, 0, 14, 2);
+ this._point.position.set(-2.4, 1.9, -1.9);
this._scene.add(this._point);
- // комната
const g = new T.Group();
this._group = g;
this._scene.add(g);
- const floorMat = new T.MeshStandardMaterial({ color: 0x2a323c, roughness: 0.85, metalness: 0.1 });
- const floor = new T.Mesh(new T.BoxGeometry(6, 0.12, 5), floorMat);
- floor.position.set(0, -0.06, 0);
+ const floor = new T.Mesh(new T.BoxGeometry(6.4, 0.1, 5.4),
+ new T.MeshStandardMaterial({ color: 0x141b22, roughness: 0.75, metalness: 0.25 }));
+ floor.position.y = -0.05;
g.add(floor);
+ g.add(new T.GridHelper(6.4, 24, 0x2b5f7a, 0x16303d));
- const wallMat = new T.MeshStandardMaterial({ color: 0x1c232b, roughness: 0.9 });
- const back = new T.Mesh(new T.BoxGeometry(6, 2.6, 0.12), wallMat);
- back.position.set(0, 1.3, -2.5);
+ const wallMat = new T.MeshStandardMaterial({ color: 0x161d24, roughness: 0.85, metalness: 0.05 });
+ const back = new T.Mesh(new T.BoxGeometry(6.4, 2.7, 0.12), wallMat);
+ back.position.set(0, 1.35, -2.7);
g.add(back);
- const left = new T.Mesh(new T.BoxGeometry(0.12, 2.6, 5), wallMat);
- left.position.set(-3, 1.3, 0);
+ const left = new T.Mesh(new T.BoxGeometry(0.12, 2.7, 5.4), wallMat);
+ left.position.set(-3.2, 1.35, 0);
g.add(left);
- // «окно»-подсветка
- const win = new T.Mesh(new T.PlaneGeometry(2.2, 1.3),
- new T.MeshBasicMaterial({ color: 0x2b4a63, transparent: true, opacity: 0.55 }));
- win.position.set(0.6, 1.6, -2.43);
+ const ledMat = new T.MeshBasicMaterial({ color: 0x2f9dd2, transparent: true, opacity: 0.55 });
+ const ledBack = new T.Mesh(new T.BoxGeometry(6.2, 0.03, 0.03), ledMat);
+ ledBack.position.set(0, 0.06, -2.62);
+ g.add(ledBack);
+ const ledLeft = new T.Mesh(new T.BoxGeometry(0.03, 0.03, 5.2), ledMat);
+ ledLeft.position.set(-3.12, 0.06, 0);
+ g.add(ledLeft);
+
+ const win = new T.Mesh(new T.PlaneGeometry(2.3, 1.35),
+ new T.MeshBasicMaterial({ color: 0x2a5a78, transparent: true, opacity: 0.5 }));
+ win.position.set(0.7, 1.65, -2.63);
g.add(win);
- // светильник (бра) — кликабельный
- const lampMat = new T.MeshStandardMaterial({
- color: 0xffe6bf, emissive: 0xffbe73, emissiveIntensity: 0.1, roughness: 0.4,
+ this._lampMat = new T.MeshStandardMaterial({
+ color: 0xffe9c6, emissive: 0xffb968, emissiveIntensity: 0.06, roughness: 0.35,
});
- this._lampMat = lampMat;
- const lamp = new T.Mesh(new T.SphereGeometry(0.26, 32, 24), lampMat);
- lamp.position.set(-2.4, 1.7, -2.2);
+ const lamp = new T.Mesh(new T.SphereGeometry(0.24, 32, 24), this._lampMat);
+ lamp.position.set(-2.4, 1.75, -2.1);
g.add(lamp);
this._lamp = lamp;
- const lampBase = new T.Mesh(new T.BoxGeometry(0.1, 0.5, 0.1),
- new T.MeshStandardMaterial({ color: 0x0e1216, metalness: 0.6, roughness: 0.5 }));
- lampBase.position.set(-2.4, 1.35, -2.2);
- g.add(lampBase);
- // «мебель» для объёма
- const bedMat = new T.MeshStandardMaterial({ color: 0x33424f, roughness: 0.9 });
- const bed = new T.Mesh(new T.BoxGeometry(2.2, 0.45, 3.0), bedMat);
- bed.position.set(1.4, 0.22, 0.2);
+ this._glow = new T.Sprite(new T.SpriteMaterial({
+ map: this._glowTexture(), transparent: true, opacity: 0, depthWrite: false, blending: T.AdditiveBlending,
+ }));
+ this._glow.scale.set(2.2, 2.2, 1);
+ this._glow.position.copy(lamp.position);
+ g.add(this._glow);
+
+ this._hit = new T.Mesh(new T.SphereGeometry(0.9, 12, 10), new T.MeshBasicMaterial({ visible: false }));
+ this._hit.position.copy(lamp.position);
+ g.add(this._hit);
+
+ const bedMat = new T.MeshStandardMaterial({ color: 0x243240, roughness: 0.9 });
+ const bed = new T.Mesh(new T.BoxGeometry(2.3, 0.45, 3.0), bedMat);
+ bed.position.set(1.5, 0.225, 0.2);
g.add(bed);
- const bedHead = new T.Mesh(new T.BoxGeometry(2.2, 0.9, 0.16), bedMat);
- bedHead.position.set(1.4, 0.45, -1.28);
- g.add(bedHead);
+ const head = new T.Mesh(new T.BoxGeometry(2.3, 0.85, 0.16), bedMat);
+ head.position.set(1.5, 0.42, -1.3);
+ g.add(head);
+ const stand = new T.Mesh(new T.BoxGeometry(0.7, 0.5, 0.5),
+ new T.MeshStandardMaterial({ color: 0x2b3a48, roughness: 0.8 }));
+ stand.position.set(0.1, 0.25, -1.9);
+ g.add(stand);
- // рамка вокруг сцены (футуристичный контур)
- const ring = new T.Mesh(new T.RingGeometry(4.6, 4.66, 64),
- new T.MeshBasicMaterial({ color: 0x2f7fa8, transparent: true, opacity: 0.35, side: T.DoubleSide }));
- ring.rotation.x = -Math.PI / 2;
- ring.position.y = -0.02;
- this._scene.add(ring);
-
- // управление
this._rot = { x: 0, y: 0 };
- this._dragging = false;
+ this._drag = false;
+ this._moved = 0;
const el = this._renderer.domElement;
el.style.touchAction = "none";
- el.addEventListener("pointerdown", (e) => { this._dragging = true; this._px = e.clientX; this._py = e.clientY; });
+ el.style.cursor = "grab";
+ el.addEventListener("pointerdown", (e) => {
+ this._drag = true; this._moved = 0; this._px = e.clientX; this._py = e.clientY;
+ el.style.cursor = "grabbing";
+ });
el.addEventListener("pointerup", (e) => {
- this._dragging = false;
- const dx = Math.abs(e.clientX - this._px), dy = Math.abs(e.clientY - this._py);
- if (dx < 5 && dy < 5) this._click(e);
+ this._drag = false;
+ el.style.cursor = this._hover ? "pointer" : "grab";
+ if (this._moved < 14) this._click(e);
});
el.addEventListener("pointermove", (e) => {
- if (!this._dragging) return;
- this._rot.y += (e.clientX - this._px) * 0.006;
- this._rot.x = Math.max(-0.5, Math.min(0.5, this._rot.x + (e.clientY - this._py) * 0.004));
- this._px = e.clientX; this._py = e.clientY;
+ if (this._drag) {
+ const dx = e.clientX - this._px, dy = e.clientY - this._py;
+ this._moved += Math.abs(dx) + Math.abs(dy);
+ this._rot.y += dx * 0.006;
+ this._rot.x = Math.max(-0.45, Math.min(0.45, this._rot.x + dy * 0.004));
+ this._px = e.clientX; this._py = e.clientY;
+ } else {
+ this._hover = !!this._ray(e);
+ el.style.cursor = this._hover ? "pointer" : "grab";
+ this._paint();
+ }
});
+ el.addEventListener("pointerleave", () => { this._drag = false; el.style.cursor = "grab"; });
el.addEventListener("wheel", (e) => {
e.preventDefault();
- this._cam.position.multiplyScalar(e.deltaY > 0 ? 1.06 : 0.94);
- this._cam.position.clampLength(4, 14);
- this._cam.lookAt(0, 0.9, 0);
+ this._cam.position.multiplyScalar(e.deltaY > 0 ? 1.05 : 0.95);
+ this._cam.position.clampLength(4, 13);
+ this._cam.lookAt(0, 1.0, 0);
}, { passive: false });
new ResizeObserver(() => {
@@ -164,15 +225,16 @@ class House3dCard extends HTMLElement {
requestAnimationFrame(loop);
this._group.rotation.y = this._rot.y;
this._group.rotation.x = this._rot.x;
+ if (this._glow) this._glow.material.opacity = this._visualOn ? 0.85 : 0.0;
this._renderer.render(this._scene, this._cam);
};
loop();
this._ready = true;
- this._syncState();
+ this._syncState(true);
}
- _click(ev) {
- if (!this._hass || !this._ready) return;
+ _ray(ev) {
+ if (!this._renderer) return null;
const r = this._renderer.domElement.getBoundingClientRect();
const p = new window.THREE.Vector2(
((ev.clientX - r.left) / r.width) * 2 - 1,
@@ -180,21 +242,74 @@ class House3dCard extends HTMLElement {
);
const ray = new window.THREE.Raycaster();
ray.setFromCamera(p, this._cam);
- const hit = ray.intersectObject(this._lamp, true).length > 0;
- if (hit && this._config.entity) {
- this._hass.callService(this._config.domain, this._config.service, { entity_id: this._config.entity });
+ const hits = ray.intersectObject(this._hit, true);
+ return hits.length ? hits[0] : null;
+ }
+
+ async _click(ev) {
+ if (!this._hass || !this._ready) return;
+ if (!this._ray(ev)) return;
+ if (this._pending) return;
+
+ this._pending = true;
+ this._optimistic = !this._visualOn; // мгновенный отклик
+ this._paint();
+ this._chip.classList.add("pending");
+ this._txt.textContent = "применяется…";
+ if (navigator.vibrate) navigator.vibrate(10);
+
+ const entity = this._config.entity;
+ try {
+ await this._hass.callService(this._config.domain, this._config.service, { entity_id: entity });
+ // ждём подтверждения от HA не дольше pending_ms
+ const deadline = Date.now() + (this._config.pending_ms || 6000);
+ const wait = () => new Promise((res) => setTimeout(res, 250));
+ while (Date.now() < deadline) {
+ const st = this._hass.states[entity];
+ if (st && (st.state === "on") === this._optimistic) break;
+ await wait();
+ }
+ this._pending = false;
+ this._chip.classList.remove("pending");
+ this._syncState(true);
+ } catch (e) {
+ this._pending = false;
+ this._optimistic = null;
+ this._chip.classList.remove("pending");
+ this._err.textContent = "не удалось применить команду";
+ this._err.classList.add("show");
+ setTimeout(() => this._err.classList.remove("show"), 3500);
+ this._syncState(true);
}
}
- _syncState() {
+ _paint() {
+ if (!this._lampMat) return;
+ const on = this._optimistic !== null && this._optimistic !== undefined
+ ? this._optimistic
+ : this._visualOn;
+ this._visualOn = on;
+ this._lampMat.emissiveIntensity = on ? (this._hover ? 2.2 : 1.6) : (this._hover ? 0.35 : 0.06);
+ this._lampMat.color.set(on ? 0xffe9c6 : 0x5a646f);
+ this._point.intensity = on ? 11 : 0;
+ this._dot.classList.toggle("on", on);
+ }
+
+ _syncState(force) {
if (!this._ready || !this._hass) return;
const st = this._hass.states[this._config.entity];
- const on = st && st.state === "on";
- this._lampMat.emissiveIntensity = on ? 1.6 : 0.05;
- this._lampMat.color.set(on ? 0xffe6bf : 0x59636e);
- this._point.intensity = on ? 9 : 0;
- this._stateEl.textContent = st ? (on ? "включено" : "выключено") : "нет сущности";
+ const on = !!st && st.state === "on";
+ if (this._optimistic !== null && this._optimistic !== undefined && this._optimistic === on) {
+ this._optimistic = null; // HA подтвердил — дальше живём по состоянию
+ }
+ if (this._optimistic === null || this._optimistic === undefined) {
+ this._visualOn = on;
+ }
+ this._paint();
+ if (!this._pending) {
+ this._txt.textContent = st ? (this._visualOn ? "включено" : "выключено") : "нет сущности";
+ }
+ void force;
}
}
customElements.define("house3d-card", House3dCard);
-