Files
buryan-infra/ops/home/house3d-card.js
T

309 lines
13 KiB
JavaScript

/* house3d-card v7 — 3D-модель дома (GLB) в Home Assistant.
* Загружает three.js r140 + GLTFLoader (UMD) + /local/house3d/house.glb.
* Клик по модели переключает сущность; оптимистичный отклик; фоновая сверка.
*
* Конфиг: type: custom:house3d-card, entity, domain, service, title, room
*/
class House3dCard extends HTMLElement {
setConfig(config) {
this._config = Object.assign(
{ entity: "", title: "Дом", room: "", domain: "switch", service: "toggle", model: "/local/house3d/house.glb" },
config || {},
);
this._root = this.attachShadow({ mode: "open" });
this._root.innerHTML = `
<style>
:host { display:block; }
.wrap { position:relative; width:100%; height:520px; border-radius:20px; overflow:hidden;
background: radial-gradient(ellipse at 50% 15%, #101a24 0%, #070a0e 60%, #05070a 100%);
box-shadow: inset 0 0 90px rgba(0,0,0,.9), 0 10px 40px rgba(0,0,0,.45); }
canvas { display:block; }
.hud { position:absolute; left:18px; top:16px; font:600 15px/1.35 'Segoe UI',sans-serif;
color:#e6eef7; letter-spacing:.05em; text-transform:uppercase; pointer-events:none;
text-shadow:0 1px 10px rgba(0,0,0,.9); }
.room { display:block; font-weight:400; font-size:12px; color:#7f93a8; margin-top:3px;
letter-spacing:.12em; text-transform:none; }
.chip { position:absolute; right:16px; top:14px; display:flex; align-items:center; gap:8px;
padding:7px 12px; border-radius:999px; font:500 13px/1 'Segoe UI',sans-serif;
color:#cfe1f2; background:rgba(18,28,38,.75); border:1px solid rgba(90,160,200,.25);
backdrop-filter: blur(8px); pointer-events:none; transition:.2s; }
.chip.pending { border-color:rgba(255,190,90,.55); color:#ffe0a8; }
.chip.ok { border-color:rgba(90,220,160,.55); color:#a9f0cf; }
.chip.err { border-color:rgba(255,120,120,.55); color:#ffb3b3; }
.dot { width:8px; height:8px; border-radius:50%; background:#4a5560; transition:.25s; }
.dot.on { background:#54d1ff; box-shadow:0 0 12px 2px rgba(84,209,255,.65); }
.chip.pending .dot { background:#ffbe5a; }
.hint { position:absolute; left:18px; bottom:12px; font:400 12px/1.4 'Segoe UI',sans-serif;
color:#5d7186; pointer-events:none; }
.load { position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
color:#7f93a8; font:500 13px 'Segoe UI',sans-serif; }
</style>
<div class="wrap">
<div class="hud">${this._config.title}<span class="room">${this._config.room}</span></div>
<div class="chip"><span class="dot"></span><span class="txt">—</span></div>
<div class="hint">клик по дому — вкл/выкл · тянуть — поворот · колесо — зум</div>
<div class="load">загрузка модели…</div>
</div>`;
this._wrap = this._root.querySelector(".wrap");
this._dot = this._root.querySelector(".dot");
this._txt = this._root.querySelector(".txt");
this._chip = this._root.querySelector(".chip");
this._load = this._root.querySelector(".load");
}
set hass(hass) {
this._hass = hass;
if (!this._booted) this._boot();
this._syncState();
}
_script(src) {
return new Promise((res, rej) => {
const s = document.createElement("script");
s.src = src; s.onload = res; s.onerror = () => rej(new Error(src));
document.head.appendChild(s);
});
}
async _boot() {
this._booted = true;
try {
if (!window.THREE) await this._script("/local/house3d/three.min.js");
if (!window.THREE.GLTFLoader) await this._script("/local/house3d/GLTFLoader.js");
this._build();
} catch (e) {
this._load.textContent = "не удалось загрузить three.js";
}
}
_build() {
const T = window.THREE;
const W = this._wrap.clientWidth || 900;
const H = this._wrap.clientHeight || 520;
this._scene = new T.Scene();
this._scene.background = null;
this._scene.fog = new T.Fog(0x06090c, 40, 120);
this._cam = new T.PerspectiveCamera(42, W / H, 0.1, 500);
this._renderer = new T.WebGLRenderer({ antialias: true, alpha: true });
this._renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
this._renderer.setSize(W, H);
this._renderer.outputEncoding = T.sRGBEncoding;
this._renderer.toneMapping = T.ACESFilmicToneMapping;
this._renderer.toneMappingExposure = 1.05;
this._wrap.appendChild(this._renderer.domElement);
this._scene.add(new T.AmbientLight(0xffffff, 0.40));
this._scene.add(new T.HemisphereLight(0xbcd6ee, 0x1a2028, 0.9));
const dir = new T.DirectionalLight(0xfff4e2, 2.0);
dir.position.set(-24, 38, -18);
this._scene.add(dir);
const fill = new T.DirectionalLight(0x9cc4e8, 1.1);
fill.position.set(26, 16, 26);
this._scene.add(fill);
const fill2 = new T.DirectionalLight(0xcfe0f0, 0.7);
fill2.position.set(-10, 8, 30);
this._scene.add(fill2);
// земля + сетка
const ground = new T.Mesh(
new T.CircleGeometry(70, 64),
new T.MeshStandardMaterial({ color: 0x0d1216, roughness: 1, metalness: 0 }),
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.02;
this._scene.add(ground);
const grid = new T.GridHelper(140, 70, 0x1e4a60, 0x112833);
grid.position.y = 0.0;
this._scene.add(grid);
this._rot = { y: -0.6, x: 0 };
this._pivot = new T.Group();
this._scene.add(this._pivot);
const loader = new T.GLTFLoader();
loader.load(
this._config.model,
(gltf) => {
const model = gltf.scene;
// убираем землю и дорожку из GLB (в сцене свои)
const drop = [];
model.traverse((o) => {
if (!o.isMesh) return;
const n = (o.name || "").toLowerCase();
if (n === "plane" || n.includes("path") || n.includes("ground") || n === "plane_0") drop.push(o);
o.castShadow = false; o.receiveShadow = false;
});
drop.forEach((o) => o.parent && o.parent.remove(o));
model.traverse((o) => {
if (o.isMesh && o.material && o.material.name === "Glass") {
o.material.transparent = true;
o.material.opacity = 0.35;
o.material.roughness = 0.1;
o.material.metalness = 0.2;
}
});
model.traverse((o) => { if (o.isMesh && o.material) o.material.side = T.DoubleSide; });
this._pivot.add(model);
this._model = model;
// считаем габариты только по «домовым» мешам (без крупных плоскостей)
model.updateWorldMatrix(true, true);
const bb = new T.Box3();
model.traverse((o) => {
if (!o.isMesh) return;
const b = new T.Box3().setFromObject(o);
const sz = b.getSize(new T.Vector3());
if (sz.x * sz.z > 400) return;
bb.union(b);
});
if (bb.isEmpty()) bb.setFromObject(model);
const size = bb.getSize(new T.Vector3());
const center = bb.getCenter(new T.Vector3());
this._pivot.position.set(-center.x, -bb.min.y, -center.z);
const dist = Math.max(size.x, size.z) * 1.05;
this._cam.position.set(dist * 0.9, size.y * 0.85 + 3.5, dist * 1.0);
this._cam.lookAt(0, size.y * 0.33, 0);
this._radius = dist;
this._load.style.display = "none";
this._ready = true;
this._syncState(true);
this._dirty = true;
},
undefined,
(err) => { this._load.textContent = "модель не загрузилась: " + (err && err.message ? err.message : "ошибка"); },
);
const el = this._renderer.domElement;
el.style.touchAction = "none";
el.style.cursor = "grab";
this._drag = false; this._moved = 0;
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._drag = false; el.style.cursor = "grab";
if (this._moved < 14) this._click(e);
});
el.addEventListener("pointermove", (e) => {
if (!this._drag) return;
const dx = e.clientX - this._px, dy = e.clientY - this._py;
this._moved += Math.abs(dx) + Math.abs(dy);
this._rot.y += dx * 0.005;
this._rot.x = Math.max(-0.35, Math.min(0.35, this._rot.x + dy * 0.003));
this._px = e.clientX; this._py = e.clientY;
this._dirty = true;
});
el.addEventListener("wheel", (e) => {
e.preventDefault();
const s = e.deltaY > 0 ? 1.07 : 0.93;
this._cam.position.multiplyScalar(s);
this._cam.position.clampLength(this._radius * 0.5, this._radius * 2.5);
this._cam.lookAt(0, 1.5, 0);
this._dirty = true;
}, { passive: false });
new ResizeObserver(() => {
const w = this._wrap.clientWidth, h = this._wrap.clientHeight;
if (!w || !h) return;
this._cam.aspect = w / h;
this._cam.updateProjectionMatrix();
this._renderer.setSize(w, h);
this._dirty = true;
}).observe(this._wrap);
const loop = () => {
requestAnimationFrame(loop);
if (this._pivot) {
this._pivot.rotation.y = this._rot.y;
this._pivot.rotation.x = this._rot.x;
}
if (!this._dirty) return;
this._dirty = false;
this._renderer.render(this._scene, this._cam);
};
loop();
}
_click(ev) {
if (!this._hass || !this._ready || this._pending) return;
const T = window.THREE;
const r = this._renderer.domElement.getBoundingClientRect();
const p = new T.Vector2(
((ev.clientX - r.left) / r.width) * 2 - 1,
-((ev.clientY - r.top) / r.height) * 2 + 1,
);
const ray = new T.Raycaster();
ray.setFromCamera(p, this._cam);
if (!ray.intersectObject(this._model, true).length) return;
this._toggle();
}
async _toggle() {
const _c0 = performance.now();
this._pending = true;
this._optimistic = !this._visualOn;
this._paint();
this._setChip("pending", "применяется…");
if (navigator.vibrate) navigator.vibrate(10);
try {
await this._hass.callService(this._config.domain, this._config.service, { entity_id: this._config.entity });
this._pending = false;
this._lastClickMs = Math.round(performance.now() - _c0);
this._setChip("ok", "применено");
setTimeout(() => this._setChip("", this._visualOn ? "включено" : "выключено"), 700);
this._reconcile(this._config.entity, this._optimistic);
} catch (e) {
this._pending = false;
this._optimistic = null;
this._setChip("err", "не применено");
this._syncState(true);
}
}
_setChip(kind, text) {
this._chip.classList.toggle("pending", kind === "pending");
this._chip.classList.toggle("ok", kind === "ok");
this._chip.classList.toggle("err", kind === "err");
this._txt.textContent = text;
}
async _reconcile(entity, expected) {
const deadline = Date.now() + 8000;
while (Date.now() < deadline) {
const st = this._hass && this._hass.states[entity];
if (st && (st.state === "on") === expected) { this._optimistic = null; this._syncState(true); return; }
await new Promise((r) => setTimeout(r, 400));
}
this._optimistic = null;
this._syncState(true);
}
_paint() {
const on = this._optimistic !== null && this._optimistic !== undefined ? this._optimistic : this._visualOn;
this._visualOn = on;
this._dot.classList.toggle("on", !!on);
// подсветка модели при включении
if (this._model) {
this._model.traverse((o) => {
if (o.isMesh && o.material && o.material.emissive) {
o.material.emissive.setHex(0x000000);
}
});
}
this._dirty = true;
}
_syncState() {
if (!this._ready || !this._hass) return;
const st = this._hass.states[this._config.entity];
const on = !!st && st.state === "on";
if (this._optimistic !== null && this._optimistic !== undefined && this._optimistic === on) this._optimistic = null;
if (this._optimistic === null || this._optimistic === undefined) this._visualOn = on;
this._paint();
if (!this._pending) this._txt.textContent = st ? (this._visualOn ? "включено" : "выключено") : "нет сущности";
}
}
customElements.define("house3d-card", House3dCard);