[HOME] 3D-модель дома в Blender (GLB 270 КБ) + карта v7 грузит её в HA
lint / hygiene (push) Successful in 18s

This commit is contained in:
root committed 2026-10-31 01:17:23 +03:00
1 parent 1727d6809e
commit 08284a23d5
8 files changed
+1059 -193

No files matched your search

+28
View File
@@ -56,3 +56,31 @@
| AdGuard switch | 0.00 с | ≈1 с |
| Zigbee-реле (план) | — | ожидается 0.3–1 с |
| Яндекс-устройства | команды не применяются | `supported_features=0` |
## v7 — реальная модель дома в карте (31.10.2026)
Сделано:
| Компонент | Файл / место |
|---|---|
| Blender-сцена (солидные стены + булевы проёмы) | `ops/home/plans/house_scene4.py` |
| Модель для веба (GLB, 270 КБ) | `/config/www/house3d/house.glb` |
| three.js r140 + GLTFLoader (UMD) | `/config/www/house3d/three.min.js`, `GLTFLoader.js` |
| Карта v7 (грузит GLB, клик по дому) | `/config/www/house3d/house3d-card.js?v=7` |
| Рендеры | `ops/home/plans/render-front.png`, `render-terrace.png` |
Ловушки:
* в Debian-сборке Blender **нет OpenImageDenoise** → денойз отключён, шум
гасится числом сэмплов;
* экспорт GLB требует **numpy** — поставили `python3-numpy` и запускаем
Blender с `PYTHONPATH=/usr/lib/python3/dist-packages`;
* UMD-сборка `GLTFLoader` есть только до three r0.147 — взяли r0.140
(`examples/js/loaders/GLTFLoader.js`), иначе 404;
* `Plane`/`path` из GLB в карте удаляются — земля и сетка создаются в сцене.
Геометрия: блок 12,1 × 8,5 м, терраса 2,4 м с запада, крыльцо с юга,
тех.пом. с севера, сваи, двускатная кровля с коньком вдоль длинной оси.
Что осталось отполировать: фактура металла «шумит» (bump слишком резкий),
крыльцо и ограждение террасы — черновые, окна без рам.
+139 -193
View File
@@ -1,51 +1,38 @@
/* house3d-card v3 — 3D-сцена в Home Assistant с оптимистичным откликом.
/* house3d-card v7 — 3D-модель дома (GLB) в Home Assistant.
* Загружает three.js r140 + GLTFLoader (UMD) + /local/house3d/house.glb.
* Клик по модели переключает сущность; оптимистичный отклик; фоновая сверка.
*
* v3:
* • мгновенная реакция интерфейса (оптимистичное переключение) — не ждём,
* пока интеграция обновит состояние;
* • индикатор «применяется…» (пульсирующий чип), затем сверка с hass.states;
* • откат и сообщение об ошибке, если сервис не сработал;
* • защита от двойного клика во время применения;
* • невидимый хитбокс, hover-подсветка, тактильный отклик.
*
* Конфиг: type: custom:house3d-card
* entity: switch.xxx, domain: switch, service: toggle, title, room
* Конфиг: type: custom:house3d-card, entity, domain, service, title, room
*/
class House3dCard extends HTMLElement {
setConfig(config) {
this._config = Object.assign(
{ entity: "", title: "3D", domain: "light", service: "toggle", room: "Комната", pending_ms: 6000 },
{ 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:440px; border-radius:20px; overflow:hidden;
background: radial-gradient(ellipse at 50% 20%, #12202b 0%, #070a0e 65%, #05070a 100%);
box-shadow: inset 0 0 90px rgba(0,0,0,.85), 0 10px 40px rgba(0,0,0,.45); }
.wrap::after { content:""; position:absolute; inset:0; pointer-events:none;
background: radial-gradient(ellipse at 50% 45%, transparent 45%, rgba(0,0,0,.55) 100%); }
.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:.04em; text-transform:uppercase; pointer-events:none;
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; }
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,.5); color:#ffe0a8; }
.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; animation:pulse 1s infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.25} }
.err { position:absolute; left:16px; bottom:38px; font:500 12px 'Segoe UI',sans-serif;
color:#ff9b9b; opacity:0; transition:.2s; }
.err.show { opacity:1; }
.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;
@@ -54,17 +41,14 @@ class House3dCard extends HTMLElement {
<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="err"></div>
<div class="hint">клик по светильнику — вкл/выкл · <span class="tm"></span></div>
<div class="load">загрузка сцены…</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._err = this._root.querySelector(".err");
this._load = this._root.querySelector(".load");
this._tm = this._root.querySelector(".tm");
}
set hass(hass) {
@@ -73,152 +57,133 @@ class House3dCard extends HTMLElement {
this._syncState();
}
_boot() {
this._booted = true;
if (window.THREE) return this._build();
const s = document.createElement("script");
s.src = "/local/house3d/three.min.js";
s.onload = () => this._build();
s.onerror = () => { this._load.textContent = "three.js не загрузился"; };
document.head.appendChild(s);
_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);
});
}
_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);
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;
if (!T) return;
const _t0 = performance.now();
this._load.style.display = "none";
const W = this._wrap.clientWidth || 800;
const H = this._wrap.clientHeight || 440;
const W = this._wrap.clientWidth || 900;
const H = this._wrap.clientHeight || 520;
this._scene = new T.Scene();
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._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._wrap.appendChild(this._renderer.domElement);
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);
this._scene.add(new T.HemisphereLight(0x8fb4d8, 0x0a0f14, 0.55));
const dir = new T.DirectionalLight(0xfff0d8, 1.5);
dir.position.set(-30, 45, -25);
this._scene.add(dir);
const fill = new T.DirectionalLight(0x6fa8d8, 0.5);
fill.position.set(30, 20, 30);
this._scene.add(fill);
const g = new T.Group();
this._group = g;
this._scene.add(g);
// земля + сетка
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);
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, 12, 0x2b5f7a, 0x16303d));
this._rot = { y: -0.6, x: 0 };
this._pivot = new T.Group();
this._scene.add(this._pivot);
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.7, 5.4), wallMat);
left.position.set(-3.2, 1.35, 0);
g.add(left);
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;
}
});
this._pivot.add(model);
this._model = model;
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 box = new T.Box3().setFromObject(model);
const size = box.getSize(new T.Vector3());
const center = box.getCenter(new T.Vector3());
this._pivot.position.set(-center.x, -box.min.y, -center.z);
const dist = Math.max(size.x, size.z) * 1.25;
this._cam.position.set(dist * 0.85, size.y * 0.95 + 4, dist * 0.95);
this._cam.lookAt(0, size.y * 0.35, 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 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);
this._lampMat = new T.MeshStandardMaterial({
color: 0xffe9c6, emissive: 0xffb968, emissiveIntensity: 0.06, roughness: 0.35,
});
const lamp = new T.Mesh(new T.SphereGeometry(0.24, 20, 14), this._lampMat);
lamp.position.set(-2.4, 1.75, -2.1);
g.add(lamp);
this._lamp = lamp;
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, 10, 8), 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 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);
this._rot = { x: 0, y: 0 };
this._drag = false;
this._moved = 0;
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 = this._hover ? "pointer" : "grab";
this._drag = false; el.style.cursor = "grab";
if (this._moved < 14) this._click(e);
});
el.addEventListener("pointermove", (e) => {
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;
this._dirty = true;
} else {
const now = performance.now();
if (now - (this._hoverTs || 0) > 80) {
this._hoverTs = now;
const hv = !!this._ray(e);
if (hv !== this._hover) { this._hover = hv; el.style.cursor = hv ? "pointer" : "grab"; this._paint(); }
}
}
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("pointerleave", () => { this._drag = false; el.style.cursor = "grab"; });
el.addEventListener("wheel", (e) => {
e.preventDefault();
this._cam.position.multiplyScalar(e.deltaY > 0 ? 1.05 : 0.95);
this._cam.position.clampLength(4, 13);
this._cam.lookAt(0, 1.0, 0);
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 });
@@ -228,62 +193,50 @@ class House3dCard extends HTMLElement {
this._cam.aspect = w / h;
this._cam.updateProjectionMatrix();
this._renderer.setSize(w, h);
this._dirty = true;
}).observe(this._wrap);
// рендер только когда есть изменения (экономит CPU и батарею)
this._dirty = true;
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._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(true);
this._initMs = Math.round(performance.now() - _t0);
if (this._tm) this._tm.textContent = "сцена " + this._initMs + " мс";
}
_ray(ev) {
if (!this._renderer) return null;
_click(ev) {
if (!this._hass || !this._ready || this._pending) return;
const T = window.THREE;
const r = this._renderer.domElement.getBoundingClientRect();
const p = new window.THREE.Vector2(
const p = new T.Vector2(
((ev.clientX - r.left) / r.width) * 2 - 1,
-((ev.clientY - r.top) / r.height) * 2 + 1,
);
const ray = new window.THREE.Raycaster();
const ray = new T.Raycaster();
ray.setFromCamera(p, this._cam);
const hits = ray.intersectObject(this._hit, true);
return hits.length ? hits[0] : null;
if (!ray.intersectObject(this._model, true).length) return;
this._toggle();
}
async _click(ev) {
if (!this._hass || !this._ready) return;
if (!this._ray(ev)) return;
if (this._pending) return;
async _toggle() {
const _c0 = performance.now();
this._pending = true;
this._optimistic = !this._visualOn;
this._paint(); // сцена меняется сразу
this._paint();
this._setChip("pending", "применяется…");
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 });
// команда принята — чип больше не ждёт устройство
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", "применено");
if (this._tm) this._tm.textContent =
"сцена " + (this._initMs || 0) + " мс · отклик " + this._lastClickMs + " мс";
setTimeout(() => this._setChip("", this._visualOn ? "включено" : "выключено"), 700);
this._reconcile(entity, this._optimistic); // фоновая сверка
this._reconcile(this._config.entity, this._optimistic);
} catch (e) {
this._pending = false;
this._optimistic = null;
@@ -300,46 +253,39 @@ class House3dCard extends HTMLElement {
}
async _reconcile(entity, expected) {
// ждём подтверждения устройства максимум 8 с, ничего не блокируя
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() {
if (!this._lampMat) return;
const on = this._optimistic !== null && this._optimistic !== undefined
? this._optimistic
: this._visualOn;
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);
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(force) {
_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; // HA подтвердил — дальше живём по состоянию
}
if (this._optimistic === null || this._optimistic === undefined) {
this._visualOn = 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 ? "включено" : "выключено") : "нет сущности";
}
void force;
if (!this._pending) this._txt.textContent = st ? (this._visualOn ? "включено" : "выключено") : "нет сущности";
}
}
customElements.define("house3d-card", House3dCard);
Binary file not shown.
+318
View File
@@ -0,0 +1,318 @@
# -*- coding: utf-8 -*-
"""Дом «Барнева 8,5 × 14,5» — Blender-сцена (v3, геометрия по паспорту).
Блок 8,50 × 12,10 м · терраса 8,50 × 2,40 (запад) · крыльцо (юг) ·
тех.пом. (север) · сваи · двускатная кровля, конёк вдоль длинной оси.
Палитра: металл RAL 7024, дерево «Олененок» Tikkurila, терраса «Графит»,
кровля графит.
Запуск: blender -b -P house_scene3.py
Результат: render-*.png + house.glb
"""
import math
import os
import bpy
from mathutils import Vector
OUT = os.path.dirname(os.path.abspath(__file__))
# --- габариты, м ---
LX, WY = 12.10, 8.50 # длинная ось X (запад→восток), ширина Y (юг→север)
TER_D = 2.40 # терраса с запада
Z0 = 0.75 # верх свай / низ стен
WALL_H = 2.78 # высота стены
Z1 = Z0 + WALL_H # 3.53
ROOF_H = 1.85
ZR = Z1 + ROOF_H
T = 0.16 # толщина стены
OVER = 0.45 # свес кровли
Y_RIDGE = WY / 2
C_METAL = "3B3F43"
C_WOOD = "C9A578"
C_DECK = "45474A"
C_ROOF = "2E3134"
C_TRIM = "24282C"
C_GLASS = "16242C"
C_PILE = "B9B3A5"
C_GROUND = "6E6F63"
def lin(c):
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def col(h, a=1.0):
h = h.lstrip("#")
r, g, b = (int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
return (lin(r), lin(g), lin(b), a)
def new_mat(name, hexv, rough=0.6, metal=0.0, glass=False, bump=None, bump_scale=1.0):
m = bpy.data.materials.new(name)
m.use_nodes = True
nt = m.node_tree
b = nt.nodes["Principled BSDF"]
b.inputs["Base Color"].default_value = col(hexv)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
if glass:
b.inputs["Transmission Weight"].default_value = 0.92
b.inputs["Roughness"].default_value = 0.035
b.inputs["IOR"].default_value = 1.45
b.inputs["Base Color"].default_value = col("0E1B22")
if bump:
tex = nt.nodes.new("ShaderNodeTexWave")
tex.wave_type = "BANDS"
tex.bands_direction = bump
tex.inputs["Scale"].default_value = bump_scale
tex.inputs["Distortion"].default_value = 1.5
bmp = nt.nodes.new("ShaderNodeBump")
bmp.inputs["Strength"].default_value = 0.28
nt.links.new(tex.outputs["Color"], bmp.inputs["Height"])
nt.links.new(bmp.outputs["Normal"], b.inputs["Normal"])
return m
def box(name, x0, x1, y0, y1, z0, z1, mat):
bpy.ops.mesh.primitive_cube_add(size=1)
o = bpy.context.object
o.name = name
o.scale = ((x1 - x0) / 2, (y1 - y0) / 2, (z1 - z0) / 2)
o.location = ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)
o.data.materials.append(mat)
return o
def wall(name, axis, fixed, u0, u1, z0, z1, thick, mat, openings=()):
"""Стена с проёмами. axis='x' — стена вдоль X при y=fixed; 'y' — вдоль Y при x=fixed.
openings: список (a0, a1, za0, za1) в координатах вдоль стены."""
ops = sorted(openings, key=lambda o: o[0])
segs = []
cur = u0
for (a0, a1, za0, za1) in ops:
if a0 > cur:
segs.append((cur, a0, z0, z1))
# под проёмом и над проёмом
if za0 > z0:
segs.append((a0, a1, z0, za0))
if za1 < z1:
segs.append((a0, a1, za1, z1))
cur = max(cur, a1)
if cur < u1:
segs.append((cur, u1, z0, z1))
for i, (a0, a1, b0, b1) in enumerate(segs):
if axis == "x":
box("%s_%d" % (name, i), a0, a1, fixed, fixed + thick, b0, b1, mat)
else:
box("%s_%d" % (name, i), fixed, fixed + thick, a0, a1, b0, b1, mat)
def gable(name, x, y0, y1, z_base, z_top, thick, mat, win=None):
v = [(x, y0, z_base), (x, y1, z_base), (x, (y0 + y1) / 2, z_top),
(x + thick, y0, z_base), (x + thick, y1, z_base), (x + thick, (y0 + y1) / 2, z_top)]
f = [(0, 1, 2), (5, 4, 3), (0, 3, 4, 1), (1, 4, 5, 2), (2, 5, 3, 0)]
me = bpy.data.meshes.new(name)
me.from_pydata(v, [], f)
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
if win:
a0, a1, za0, za1 = win
box(name + "_glass", x + 0.02, x + thick - 0.02, a0, a1, za0, za1, glass_mat)
return o
def slab(name, pts, mat, thick=0.1):
me = bpy.data.meshes.new(name)
me.from_pydata(pts, [], [(0, 1, 2, 3)])
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
s = o.modifiers.new("sol", "SOLIDIFY")
s.thickness = thick
s.offset = 0
return o
def main():
bpy.ops.wm.read_factory_settings(use_empty=True)
sc = bpy.context.scene
global glass_mat
metal = new_mat("RAL7024", C_METAL, 0.34, 0.55, bump="Z", bump_scale=42)
wood = new_mat("Olenenok", C_WOOD, 0.58, 0.0, bump="Z", bump_scale=30)
deck = new_mat("DeckGraphite", C_DECK, 0.5, 0.0, bump="X", bump_scale=40)
roof = new_mat("Roof", C_ROOF, 0.42, 0.3, bump="Y", bump_scale=18)
glass_mat = new_mat("Glass", C_GLASS, glass=True)
trim = new_mat("Trim", C_TRIM, 0.5, 0.2)
pile = new_mat("Pile", C_PILE, 0.88)
ground = new_mat("Ground", C_GROUND, 0.95, bump="Z", bump_scale=120)
# ---------- сваи ----------
xs = [0.55 + i * (LX - 1.1) / 6 for i in range(7)]
for x in xs:
for y in (0.32, WY - 0.32):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
for y in (1.6, 3.2, 4.8, 6.4):
for x in (0.32, LX - 0.32):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
# ---------- пол ----------
box("floor", 0, LX, 0, WY, Z0 - 0.22, Z0 - 0.01, trim)
# ---------- стены ----------
south_wins = [(1.15, 2.65), (3.55, 5.05), (8.35, 9.95), (10.35, 11.60)]
s_open = [(a, b, Z0 + 0.95, Z0 + 2.25) for a, b in south_wins]
s_open.append((6.30, 7.35, Z0, Z0 + 2.30)) # дверь
wall("wall_south", "x", 0.0, 0.0, LX, Z0, Z1, T, metal, s_open)
north_wins = [(1.8, 3.1), (5.4, 6.7), (9.2, 10.5)]
n_open = [(a, b, Z0 + 1.0, Z0 + 2.25) for a, b in north_wins]
wall("wall_north", "x", WY - T, 0.0, LX, Z0, Z1, T, metal, n_open)
west_open = [(1.3, 3.7, Z0 + 0.9, Z0 + 2.35), (4.4, 6.8, Z0 + 0.9, Z0 + 2.35)]
wall("wall_west", "y", 0.0, 0.0, WY, Z0, Z1, T, wood, west_open)
east_open = [(1.9, 3.5, Z0 + 1.0, Z0 + 2.25), (5.2, 6.8, Z0 + 1.0, Z0 + 2.25)]
wall("wall_east", "y", LX - T, 0.0, WY, Z0, Z1, T, wood, east_open)
# фронтоны
gable("gable_west", 0.0, 0.0, WY, Z1, ZR, T, wood, win=(2.4, 5.9, Z1 + 0.2, Z1 + 1.05))
gable("gable_east", LX - T, 0.0, WY, Z1, ZR, T, wood, win=(3.2, 5.2, Z1 + 0.25, Z1 + 0.95))
# ---------- окна: рамы и стекло ----------
for i, (a, b) in enumerate(south_wins):
box("sg_%d" % i, a, b, -0.05, 0.01, Z0 + 0.95, Z0 + 2.25, glass_mat)
box("sf_t_%d" % i, a - 0.06, b + 0.06, -0.07, 0.03, Z0 + 2.25, Z0 + 2.33, trim)
box("sf_b_%d" % i, a - 0.06, b + 0.06, -0.07, 0.03, Z0 + 0.87, Z0 + 0.95, trim)
box("sf_l_%d" % i, a - 0.06, a, -0.07, 0.03, Z0 + 0.95, Z0 + 2.25, trim)
box("sf_r_%d" % i, b, b + 0.06, -0.07, 0.03, Z0 + 0.95, Z0 + 2.25, trim)
for i, (a, b) in enumerate(north_wins):
box("ng_%d" % i, a, b, WY - 0.06, WY, Z0 + 1.0, Z0 + 2.25, glass_mat)
for i, (a0, a1, z0, z1) in enumerate(west_open):
box("wg_%d" % i, -0.05, 0.01, a0, a1, z0, z1, glass_mat)
box("wf_%d" % i, -0.07, 0.03, a0 - 0.05, a1 + 0.05, z1, z1 + 0.07, trim)
for i, (a0, a1, z0, z1) in enumerate(east_open):
box("eg_%d" % i, LX - 0.06, LX, a0, a1, z0, z1, glass_mat)
# дверь
box("door", 6.32, 7.33, -0.04, 0.02, Z0, Z0 + 2.28, trim)
box("door_frame", 6.24, 7.41, -0.06, 0.04, Z0, Z0 + 2.36, wood)
# ---------- кровля ----------
slab("roof_south", [(-OVER, -OVER, Z1), (LX + OVER, -OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roof, 0.11)
slab("roof_north", [(-OVER, WY + OVER, Z1), (LX + OVER, WY + OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roof, 0.11)
# торцевые доски свесов
box("fascia_w", -OVER - 0.02, -OVER + 0.06, -OVER, WY + OVER, Z1 - 0.16, Z1 + 0.02, trim)
box("fascia_e", LX + OVER - 0.06, LX + OVER + 0.02, -OVER, WY + OVER, Z1 - 0.16, Z1 + 0.02, trim)
# конёк
box("ridge", -OVER, LX + OVER, Y_RIDGE - 0.09, Y_RIDGE + 0.09, ZR - 0.03, ZR + 0.05, trim)
# труба
box("chimney", 2.30, 2.90, 3.05, 3.65, ZR - 0.35, ZR + 0.95, trim)
box("chimney_cap", 2.24, 2.96, 2.99, 3.71, ZR + 0.95, ZR + 1.02, trim)
# ---------- терраса (запад) ----------
box("deck_base", -TER_D, 0.0, 0.0, WY, Z0 - 0.30, Z0 - 0.02, deck)
# доски настила
n = int(WY / 0.14)
for i in range(n):
y0 = i * (WY / n)
box("plank_%02d" % i, -TER_D + 0.02, -0.02, y0 + 0.01, y0 + (WY / n) - 0.02, Z0 - 0.02, Z0 + 0.02, deck)
# столбы и ограждение
for y in (0.12, WY - 0.12):
box("tpost_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.06, y + 0.06, Z0 - 0.02, Z1, trim)
for y in (WY / 3, 2 * WY / 3):
box("tpostm_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.06, y + 0.06, Z0 - 0.02, Z1, trim)
box("rail_top", -TER_D, -TER_D + 0.12, 0.06, WY - 0.06, Z0 + 0.98, Z0 + 1.08, wood)
box("rail_mid", -TER_D + 0.02, -TER_D + 0.10, 0.06, WY - 0.06, Z0 + 0.48, Z0 + 0.54, trim)
# стеклянные вставки ограждения
box("rail_glass", -TER_D + 0.04, -TER_D + 0.08, 0.10, WY - 0.10, Z0 + 0.54, Z0 + 0.98, glass_mat)
# ---------- крыльцо (юг) ----------
box("porch_deck", 5.55, 6.95, -2.55, 0.0, Z0 - 0.30, Z0 - 0.02, deck)
for i in range(3):
y0 = -2.55 - 0.36 * (i + 1)
box("step_%d" % i, 5.75, 6.75, y0, y0 + 0.36, 0.02, 0.50 - 0.15 * i, deck)
# ---------- тех.пом. (север) ----------
box("tech_wall_s", 4.90, 7.00, WY, WY + 0.16, Z0, Z1 - 0.35, metal)
box("tech_wall_e", 6.84, 7.00, WY + 0.16, WY + 2.10, Z0, Z1 - 0.35, metal)
box("tech_wall_w", 4.90, 5.06, WY + 0.16, WY + 2.10, Z0, Z1 - 0.35, metal)
box("tech_wall_n", 4.90, 7.00, WY + 1.94, WY + 2.10, Z0, Z1 - 0.35, metal)
box("tech_roof", 4.80, 7.10, WY - 0.05, WY + 2.20, Z1 - 0.35, Z1 - 0.24, roof)
box("tech_door", 5.10, 5.95, WY + 1.90, WY + 1.96, Z0, Z0 + 2.0, trim)
# ---------- земля ----------
bpy.ops.mesh.primitive_plane_add(size=140, location=(LX / 2, WY / 2, 0))
bpy.context.object.data.materials.append(ground)
box("path", 5.65, 6.85, -13.0, -2.55, 0.004, 0.03, ground)
# ---------- свет и небо ----------
w = bpy.data.worlds.new("World")
sc.world = w
w.use_nodes = True
nt = w.node_tree
sky = nt.nodes.new("ShaderNodeTexSky")
sky.sky_type = "NISHITA"
sky.sun_elevation = math.radians(28)
sky.sun_rotation = math.radians(215)
bg = nt.nodes["Background"]
nt.links.new(sky.outputs["Color"], bg.inputs["Color"])
bg.inputs["Strength"].default_value = 0.32
bpy.ops.object.light_add(type="SUN", location=(-14, -20, 26))
sun = bpy.context.object
sun.data.energy = 3.0
sun.data.angle = math.radians(1.6)
sun.rotation_euler = (math.radians(52), 0, math.radians(38))
# ---------- камера ----------
cd = bpy.data.cameras.new("Cam")
cd.lens = 38
cam = bpy.data.objects.new("Cam", cd)
bpy.context.collection.objects.link(cam)
sc.camera = cam
sc.render.engine = "CYCLES"
sc.cycles.device = "CPU"
sc.cycles.samples = 110
sc.cycles.use_denoising = False
sc.cycles.max_bounces = 8
sc.render.resolution_x, sc.render.resolution_y = 1600, 900
sc.view_settings.view_transform = "AgX"
sc.view_settings.look = "AgX - Medium High Contrast"
sc.view_settings.exposure = -1.1
def shot(name, loc, target):
cam.location = loc
cam.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
sc.render.filepath = os.path.join(OUT, name)
bpy.ops.render.render(write_still=True)
print("render:", name, flush=True)
shot("render-front.png", (LX + 13.5, -15.0, 7.0), (LX / 2 - 1.0, WY / 2 - 1.0, 1.9))
shot("render-terrace.png", (-13.5, -11.5, 6.0), (LX / 2 - 3.0, WY / 2 + 0.5, 1.7))
# ---------- экспорт GLB ----------
bpy.ops.object.select_all(action="SELECT")
glb = os.path.join(OUT, "house.glb")
bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_apply=True,
use_selection=True, export_yup=True)
print("glb:", glb, os.path.getsize(glb), flush=True)
print("done")
if __name__ == "__main__":
main()
+287
View File
@@ -0,0 +1,287 @@
# -*- coding: utf-8 -*-
"""Дом «Барнева 8,5 × 14,5» — Blender v4: солидные стены + булевы проёмы.
Блок 8,50 × 12,10 · терраса 2,40 (запад) · крыльцо (юг) · тех.пом. (север).
Палитра: RAL 7024 / «Олененок» Tikkurila / масло «Графит» / кровля графит.
blender -b -P house_scene4.py → render-*.png + house.glb
"""
import math
import os
import bpy
from mathutils import Vector
OUT = os.path.dirname(os.path.abspath(__file__))
LX, WY = 12.10, 8.50
TER_D = 2.40
Z0 = 0.75
WALL_H = 2.78
Z1 = Z0 + WALL_H
ROOF_H = 1.85
ZR = Z1 + ROOF_H
T = 0.18
OVER = 0.45
Y_RIDGE = WY / 2
def lin(c):
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def col(h, a=1.0):
h = h.lstrip("#")
r, g, b = (int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
return (lin(r), lin(g), lin(b), a)
def new_mat(name, hexv, rough=0.6, metal=0.0, glass=False, bump_axis=None, bump_scale=1.0):
m = bpy.data.materials.new(name)
m.use_nodes = True
nt = m.node_tree
b = nt.nodes["Principled BSDF"]
b.inputs["Base Color"].default_value = col(hexv)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
if glass:
b.inputs["Transmission Weight"].default_value = 0.95
b.inputs["Roughness"].default_value = 0.03
b.inputs["IOR"].default_value = 1.45
b.inputs["Base Color"].default_value = col("0C161C")
if bump_axis:
tex = nt.nodes.new("ShaderNodeTexWave")
tex.wave_type = "BANDS"
tex.bands_direction = bump_axis
tex.inputs["Scale"].default_value = bump_scale
tex.inputs["Distortion"].default_value = 0.6
bmp = nt.nodes.new("ShaderNodeBump")
bmp.inputs["Strength"].default_value = 0.22
nt.links.new(tex.outputs["Color"], bmp.inputs["Height"])
nt.links.new(bmp.outputs["Normal"], b.inputs["Normal"])
return m
def cube(name, center, size, mat):
bpy.ops.mesh.primitive_cube_add(size=1)
o = bpy.context.object
o.name = name
o.scale = size
o.location = center
o.data.materials.append(mat)
return o
def box(name, x0, x1, y0, y1, z0, z1, mat):
return cube(name, ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2),
((x1 - x0) / 2, (y1 - y0) / 2, (z1 - z0) / 2), mat)
def cut(obj, box_args):
x0, x1, y0, y1, z0, z1 = box_args
c = box("cutter", x0, x1, y0, y1, z0, z1, obj.data.materials[0])
m = obj.modifiers.new("b", "BOOLEAN")
m.operation = "DIFFERENCE"
m.object = c
m.solver = "EXACT"
bpy.context.view_layer.objects.active = obj
bpy.ops.object.modifier_apply(modifier=m.name)
bpy.data.objects.remove(c, do_unlink=True)
def gable(name, x, y0, y1, z_base, z_top, thick, mat):
v = [(x, y0, z_base), (x, y1, z_base), (x, (y0 + y1) / 2, z_top),
(x + thick, y0, z_base), (x + thick, y1, z_base), (x + thick, (y0 + y1) / 2, z_top)]
f = [(0, 1, 2), (5, 4, 3), (0, 3, 4, 1), (1, 4, 5, 2), (2, 5, 3, 0)]
me = bpy.data.meshes.new(name)
me.from_pydata(v, [], f)
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
return o
def slab(name, pts, mat, thick=0.12):
me = bpy.data.meshes.new(name)
me.from_pydata(pts, [], [(0, 1, 2, 3)])
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
s = o.modifiers.new("sol", "SOLIDIFY")
s.thickness = thick
return o
def main():
bpy.ops.wm.read_factory_settings(use_empty=True)
sc = bpy.context.scene
metal = new_mat("RAL7024", "2E3236", 0.42, 0.45, bump_axis="Z", bump_scale=38)
wood = new_mat("Olenenok", "C2996E", 0.62, 0.0, bump_axis="Z", bump_scale=26)
deck = new_mat("DeckGraphite", "3A3D40", 0.6, 0.0, bump_axis="X", bump_scale=34)
roofm = new_mat("Roof", "212428", 0.5, 0.2, bump_axis="Y", bump_scale=16)
glass = new_mat("Glass", "0C161C", glass=True)
trim = new_mat("Trim", "24282C", 0.5, 0.2)
pile = new_mat("Pile", "B9B3A5", 0.9)
ground = new_mat("Ground", "6C6D60", 0.95, bump_axis="Z", bump_scale=90)
# сваи
for i in range(7):
x = 0.55 + i * (LX - 1.1) / 6
for y in (0.35, WY - 0.35):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
for y in (1.7, 3.3, 4.9, 6.5):
for x in (0.35, LX - 0.35):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
box("floor", -0.05, LX + 0.05, -0.05, WY + 0.05, Z0 - 0.24, Z0, trim)
# --- стены: солид + булевы проёмы ---
south = box("wall_south", 0, LX, 0, T, Z0, Z1, metal)
for (a, b) in [(1.15, 2.65), (3.55, 5.05), (8.35, 9.95), (10.35, 11.60)]:
cut(south, (a, b, -0.1, T + 0.1, Z0 + 0.95, Z0 + 2.25))
cut(south, (6.30, 7.35, -0.1, T + 0.1, Z0 - 0.05, Z0 + 2.30))
north = box("wall_north", 0, LX, WY - T, WY, Z0, Z1, metal)
for (a, b) in [(1.8, 3.1), (5.4, 6.7), (9.2, 10.5)]:
cut(north, (a, b, WY - T - 0.1, WY + 0.1, Z0 + 1.0, Z0 + 2.25))
west = box("wall_west", 0, T, T, WY - T, Z0, Z1, wood)
for (a, b) in [(1.3, 3.7), (4.4, 6.8)]:
cut(west, (-0.1, T + 0.1, a, b, Z0 + 0.9, Z0 + 2.35))
east = box("wall_east", LX - T, LX, T, WY - T, Z0, Z1, wood)
for (a, b) in [(1.9, 3.5), (5.2, 6.8)]:
cut(east, (LX - T - 0.1, LX + 0.1, a, b, Z0 + 1.0, Z0 + 2.25))
# фронтоны (солидные)
gw = gable("gable_west", 0.0, 0.0, WY, Z1, ZR, T, wood)
ge = gable("gable_east", LX - T, 0.0, WY, Z1, ZR, T, wood)
# окна во фронтонах
cut(gw, (-0.1, T + 0.1, 2.5, 5.8, Z1 + 0.25, Z1 + 1.05))
cut(ge, (LX - T - 0.1, LX + 0.1, 3.2, 5.2, Z1 + 0.3, Z1 + 0.95))
# стёкла и рамы в проёмах
for (a, b) in [(1.15, 2.65), (3.55, 5.05), (8.35, 9.95), (10.35, 11.60)]:
box("sg_%d" % int(a * 100), a + 0.03, b - 0.03, T * 0.35, T * 0.65,
Z0 + 0.98, Z0 + 2.22, glass)
for (a, b) in [(1.8, 3.1), (5.4, 6.7), (9.2, 10.5)]:
box("ng_%d" % int(a * 100), a + 0.03, b - 0.03, WY - T * 0.65, WY - T * 0.35,
Z0 + 1.03, Z0 + 2.22, glass)
for (a, b) in [(1.3, 3.7), (4.4, 6.8)]:
box("wg_%d" % int(a * 100), T * 0.35, T * 0.65, a + 0.03, b - 0.03,
Z0 + 0.93, Z0 + 2.32, glass)
for (a, b) in [(1.9, 3.5), (5.2, 6.8)]:
box("eg_%d" % int(a * 100), LX - T * 0.65, LX - T * 0.35, a + 0.03, b - 0.03,
Z0 + 1.03, Z0 + 2.22, glass)
box("gw_glass", T * 0.35, T * 0.65, 2.53, 5.77, Z1 + 0.28, Z1 + 1.02, glass)
box("ge_glass", LX - T * 0.65, LX - T * 0.35, 3.23, 5.17, Z1 + 0.33, Z1 + 0.92, glass)
# дверь
box("door", 6.33, 7.32, T * 0.3, T * 0.7, Z0 + 0.02, Z0 + 2.27, trim)
box("door_handle", 7.02, 7.06, T * 0.2, T * 0.3, Z0 + 1.02, Z0 + 1.10, wood)
# кровля
slab("roof_south", [(-OVER, -OVER, Z1), (LX + OVER, -OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roofm, 0.13)
slab("roof_north", [(-OVER, WY + OVER, Z1), (LX + OVER, WY + OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roofm, 0.13)
box("ridge", -OVER, LX + OVER, Y_RIDGE - 0.1, Y_RIDGE + 0.1, ZR - 0.06, ZR + 0.04, trim)
box("fascia_w", -OVER - 0.03, -OVER + 0.05, -OVER, WY + OVER, Z1 - 0.18, Z1 + 0.02, trim)
box("fascia_e", LX + OVER - 0.05, LX + OVER + 0.03, -OVER, WY + OVER, Z1 - 0.18, Z1 + 0.02, trim)
box("chimney", 2.30, 2.90, 3.05, 3.65, ZR - 0.4, ZR + 0.95, trim)
box("chimney_cap", 2.24, 2.96, 2.99, 3.71, ZR + 0.95, ZR + 1.03, trim)
# терраса
box("deck_base", -TER_D, 0.0, 0.0, WY, Z0 - 0.34, Z0 - 0.06, deck)
n = 24
for i in range(n):
y0 = i * (WY / n)
box("plank_%02d" % i, -TER_D + 0.02, -0.03, y0 + 0.012, y0 + (WY / n) - 0.024,
Z0 - 0.06, Z0 - 0.005, deck)
for y in (0.10, WY - 0.10):
box("tpost_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.06, y + 0.06, Z0 - 0.06, Z1, trim)
for y in (WY / 3, 2 * WY / 3):
box("tpostm_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.05, y + 0.05, Z0 - 0.06, Z1, trim)
box("rail_top", -TER_D, -TER_D + 0.14, 0.05, WY - 0.05, Z0 + 0.98, Z0 + 1.08, wood)
box("rail_glass", -TER_D + 0.05, -TER_D + 0.09, 0.08, WY - 0.08, Z0 + 0.10, Z0 + 0.96, glass)
# крыльцо
box("porch_deck", 5.55, 6.95, -2.55, 0.0, Z0 - 0.34, Z0 - 0.04, deck)
for i in range(3):
y0 = -2.55 - 0.36 * (i + 1)
box("step_%d" % i, 5.75, 6.75, y0, y0 + 0.36, 0.02, 0.50 - 0.15 * i, deck)
for y in (-2.5, -1.3, -0.1):
box("ppost_%d" % int(-y * 10), 5.6, 5.72, y - 0.05, y + 0.05, Z0 - 0.04, Z1 - 0.7, trim)
# тех.пом.
box("tech", 4.90, 7.00, WY, WY + 2.10, Z0, Z1 - 0.30, metal)
box("tech_roof", 4.80, 7.10, WY - 0.06, WY + 2.20, Z1 - 0.30, Z1 - 0.18, roofm)
box("tech_door", 5.15, 5.95, WY + 2.02, WY + 2.10, Z0 + 0.02, Z0 + 2.0, trim)
# земля и дорожка
bpy.ops.mesh.primitive_plane_add(size=160, location=(LX / 2, WY / 2, -0.01))
bpy.context.object.data.materials.append(ground)
box("path", 5.65, 6.85, -14.0, -2.55, 0.0, 0.03, ground)
# небо и свет
w = bpy.data.worlds.new("World")
sc.world = w
w.use_nodes = True
nt = w.node_tree
sky = nt.nodes.new("ShaderNodeTexSky")
sky.sky_type = "NISHITA"
sky.sun_elevation = math.radians(24)
sky.sun_rotation = math.radians(210)
bg = nt.nodes["Background"]
nt.links.new(sky.outputs["Color"], bg.inputs["Color"])
bg.inputs["Strength"].default_value = 0.28
bpy.ops.object.light_add(type="SUN", location=(-14, -20, 26))
sun = bpy.context.object
sun.data.energy = 3.2
sun.data.angle = math.radians(1.4)
sun.rotation_euler = (math.radians(54), 0, math.radians(36))
# камера и рендер
cd = bpy.data.cameras.new("Cam")
cd.lens = 42
cam = bpy.data.objects.new("Cam", cd)
bpy.context.collection.objects.link(cam)
sc.camera = cam
sc.render.engine = "CYCLES"
sc.cycles.device = "CPU"
sc.cycles.samples = 96
sc.cycles.use_denoising = False
sc.cycles.max_bounces = 6
sc.render.resolution_x, sc.render.resolution_y = 1600, 900
sc.view_settings.view_transform = "AgX"
sc.view_settings.exposure = -0.95
def shot(name, loc, target):
cam.location = loc
cam.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
sc.render.filepath = os.path.join(OUT, name)
bpy.ops.render.render(write_still=True)
print("render:", name, flush=True)
shot("render-front.png", (LX + 11.0, -13.0, 5.4), (LX / 2 - 0.5, WY / 2 - 0.5, 2.1))
shot("render-terrace.png", (-11.0, -10.0, 5.0), (LX / 2 - 2.5, WY / 2 + 0.5, 1.9))
# GLB
bpy.ops.object.select_all(action="SELECT")
glb = os.path.join(OUT, "house.glb")
bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_apply=True,
use_selection=True, export_yup=True)
print("glb:", os.path.getsize(glb), flush=True)
print("done")
if __name__ == "__main__":
main()
+287
View File
@@ -0,0 +1,287 @@
# -*- coding: utf-8 -*-
"""Дом «Барнева 8,5 × 14,5» — Blender v4: солидные стены + булевы проёмы.
Блок 8,50 × 12,10 · терраса 2,40 (запад) · крыльцо (юг) · тех.пом. (север).
Палитра: RAL 7024 / «Олененок» Tikkurila / масло «Графит» / кровля графит.
blender -b -P house_scene4.py → render-*.png + house.glb
"""
import math
import os
import bpy
from mathutils import Vector
OUT = os.path.dirname(os.path.abspath(__file__))
LX, WY = 12.10, 8.50
TER_D = 2.40
Z0 = 0.75
WALL_H = 2.78
Z1 = Z0 + WALL_H
ROOF_H = 1.85
ZR = Z1 + ROOF_H
T = 0.18
OVER = 0.45
Y_RIDGE = WY / 2
def lin(c):
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def col(h, a=1.0):
h = h.lstrip("#")
r, g, b = (int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))
return (lin(r), lin(g), lin(b), a)
def new_mat(name, hexv, rough=0.6, metal=0.0, glass=False, bump_axis=None, bump_scale=1.0):
m = bpy.data.materials.new(name)
m.use_nodes = True
nt = m.node_tree
b = nt.nodes["Principled BSDF"]
b.inputs["Base Color"].default_value = col(hexv)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
if glass:
b.inputs["Transmission Weight"].default_value = 0.95
b.inputs["Roughness"].default_value = 0.03
b.inputs["IOR"].default_value = 1.45
b.inputs["Base Color"].default_value = col("0C161C")
if bump_axis:
tex = nt.nodes.new("ShaderNodeTexWave")
tex.wave_type = "BANDS"
tex.bands_direction = bump_axis
tex.inputs["Scale"].default_value = bump_scale
tex.inputs["Distortion"].default_value = 0.6
bmp = nt.nodes.new("ShaderNodeBump")
bmp.inputs["Strength"].default_value = 0.22
nt.links.new(tex.outputs["Color"], bmp.inputs["Height"])
nt.links.new(bmp.outputs["Normal"], b.inputs["Normal"])
return m
def cube(name, center, size, mat):
bpy.ops.mesh.primitive_cube_add(size=1)
o = bpy.context.object
o.name = name
o.scale = size
o.location = center
o.data.materials.append(mat)
return o
def box(name, x0, x1, y0, y1, z0, z1, mat):
return cube(name, ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2),
((x1 - x0) / 2, (y1 - y0) / 2, (z1 - z0) / 2), mat)
def cut(obj, box_args):
x0, x1, y0, y1, z0, z1 = box_args
c = box("cutter", x0, x1, y0, y1, z0, z1, obj.data.materials[0])
m = obj.modifiers.new("b", "BOOLEAN")
m.operation = "DIFFERENCE"
m.object = c
m.solver = "EXACT"
bpy.context.view_layer.objects.active = obj
bpy.ops.object.modifier_apply(modifier=m.name)
bpy.data.objects.remove(c, do_unlink=True)
def gable(name, x, y0, y1, z_base, z_top, thick, mat):
v = [(x, y0, z_base), (x, y1, z_base), (x, (y0 + y1) / 2, z_top),
(x + thick, y0, z_base), (x + thick, y1, z_base), (x + thick, (y0 + y1) / 2, z_top)]
f = [(0, 1, 2), (5, 4, 3), (0, 3, 4, 1), (1, 4, 5, 2), (2, 5, 3, 0)]
me = bpy.data.meshes.new(name)
me.from_pydata(v, [], f)
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
return o
def slab(name, pts, mat, thick=0.12):
me = bpy.data.meshes.new(name)
me.from_pydata(pts, [], [(0, 1, 2, 3)])
me.update()
o = bpy.data.objects.new(name, me)
bpy.context.collection.objects.link(o)
o.data.materials.append(mat)
s = o.modifiers.new("sol", "SOLIDIFY")
s.thickness = thick
return o
def main():
bpy.ops.wm.read_factory_settings(use_empty=True)
sc = bpy.context.scene
metal = new_mat("RAL7024", "2E3236", 0.42, 0.45, bump_axis="Z", bump_scale=38)
wood = new_mat("Olenenok", "C2996E", 0.62, 0.0, bump_axis="Z", bump_scale=26)
deck = new_mat("DeckGraphite", "3A3D40", 0.6, 0.0, bump_axis="X", bump_scale=34)
roofm = new_mat("Roof", "212428", 0.5, 0.2, bump_axis="Y", bump_scale=16)
glass = new_mat("Glass", "0C161C", glass=True)
trim = new_mat("Trim", "24282C", 0.5, 0.2)
pile = new_mat("Pile", "B9B3A5", 0.9)
ground = new_mat("Ground", "6C6D60", 0.95, bump_axis="Z", bump_scale=90)
# сваи
for i in range(7):
x = 0.55 + i * (LX - 1.1) / 6
for y in (0.35, WY - 0.35):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
for y in (1.7, 3.3, 4.9, 6.5):
for x in (0.35, LX - 0.35):
bpy.ops.mesh.primitive_cylinder_add(radius=0.075, depth=Z0, location=(x, y, Z0 / 2))
bpy.context.object.data.materials.append(pile)
box("floor", -0.05, LX + 0.05, -0.05, WY + 0.05, Z0 - 0.24, Z0, trim)
# --- стены: солид + булевы проёмы ---
south = box("wall_south", 0, LX, 0, T, Z0, Z1, metal)
for (a, b) in [(1.15, 2.65), (3.55, 5.05), (8.35, 9.95), (10.35, 11.60)]:
cut(south, (a, b, -0.1, T + 0.1, Z0 + 0.95, Z0 + 2.25))
cut(south, (6.30, 7.35, -0.1, T + 0.1, Z0 - 0.05, Z0 + 2.30))
north = box("wall_north", 0, LX, WY - T, WY, Z0, Z1, metal)
for (a, b) in [(1.8, 3.1), (5.4, 6.7), (9.2, 10.5)]:
cut(north, (a, b, WY - T - 0.1, WY + 0.1, Z0 + 1.0, Z0 + 2.25))
west = box("wall_west", 0, T, T, WY - T, Z0, Z1, wood)
for (a, b) in [(1.3, 3.7), (4.4, 6.8)]:
cut(west, (-0.1, T + 0.1, a, b, Z0 + 0.9, Z0 + 2.35))
east = box("wall_east", LX - T, LX, T, WY - T, Z0, Z1, wood)
for (a, b) in [(1.9, 3.5), (5.2, 6.8)]:
cut(east, (LX - T - 0.1, LX + 0.1, a, b, Z0 + 1.0, Z0 + 2.25))
# фронтоны (солидные)
gw = gable("gable_west", 0.0, 0.0, WY, Z1, ZR, T, wood)
ge = gable("gable_east", LX - T, 0.0, WY, Z1, ZR, T, wood)
# окна во фронтонах
cut(gw, (-0.1, T + 0.1, 2.5, 5.8, Z1 + 0.25, Z1 + 1.05))
cut(ge, (LX - T - 0.1, LX + 0.1, 3.2, 5.2, Z1 + 0.3, Z1 + 0.95))
# стёкла и рамы в проёмах
for (a, b) in [(1.15, 2.65), (3.55, 5.05), (8.35, 9.95), (10.35, 11.60)]:
box("sg_%d" % int(a * 100), a + 0.03, b - 0.03, T * 0.35, T * 0.65,
Z0 + 0.98, Z0 + 2.22, glass)
for (a, b) in [(1.8, 3.1), (5.4, 6.7), (9.2, 10.5)]:
box("ng_%d" % int(a * 100), a + 0.03, b - 0.03, WY - T * 0.65, WY - T * 0.35,
Z0 + 1.03, Z0 + 2.22, glass)
for (a, b) in [(1.3, 3.7), (4.4, 6.8)]:
box("wg_%d" % int(a * 100), T * 0.35, T * 0.65, a + 0.03, b - 0.03,
Z0 + 0.93, Z0 + 2.32, glass)
for (a, b) in [(1.9, 3.5), (5.2, 6.8)]:
box("eg_%d" % int(a * 100), LX - T * 0.65, LX - T * 0.35, a + 0.03, b - 0.03,
Z0 + 1.03, Z0 + 2.22, glass)
box("gw_glass", T * 0.35, T * 0.65, 2.53, 5.77, Z1 + 0.28, Z1 + 1.02, glass)
box("ge_glass", LX - T * 0.65, LX - T * 0.35, 3.23, 5.17, Z1 + 0.33, Z1 + 0.92, glass)
# дверь
box("door", 6.33, 7.32, T * 0.3, T * 0.7, Z0 + 0.02, Z0 + 2.27, trim)
box("door_handle", 7.02, 7.06, T * 0.2, T * 0.3, Z0 + 1.02, Z0 + 1.10, wood)
# кровля
slab("roof_south", [(-OVER, -OVER, Z1), (LX + OVER, -OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roofm, 0.13)
slab("roof_north", [(-OVER, WY + OVER, Z1), (LX + OVER, WY + OVER, Z1),
(LX + OVER, Y_RIDGE, ZR), (-OVER, Y_RIDGE, ZR)], roofm, 0.13)
box("ridge", -OVER, LX + OVER, Y_RIDGE - 0.1, Y_RIDGE + 0.1, ZR - 0.06, ZR + 0.04, trim)
box("fascia_w", -OVER - 0.03, -OVER + 0.05, -OVER, WY + OVER, Z1 - 0.18, Z1 + 0.02, trim)
box("fascia_e", LX + OVER - 0.05, LX + OVER + 0.03, -OVER, WY + OVER, Z1 - 0.18, Z1 + 0.02, trim)
box("chimney", 2.30, 2.90, 3.05, 3.65, ZR - 0.4, ZR + 0.95, trim)
box("chimney_cap", 2.24, 2.96, 2.99, 3.71, ZR + 0.95, ZR + 1.03, trim)
# терраса
box("deck_base", -TER_D, 0.0, 0.0, WY, Z0 - 0.34, Z0 - 0.06, deck)
n = 24
for i in range(n):
y0 = i * (WY / n)
box("plank_%02d" % i, -TER_D + 0.02, -0.03, y0 + 0.012, y0 + (WY / n) - 0.024,
Z0 - 0.06, Z0 - 0.005, deck)
for y in (0.10, WY - 0.10):
box("tpost_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.06, y + 0.06, Z0 - 0.06, Z1, trim)
for y in (WY / 3, 2 * WY / 3):
box("tpostm_%d" % int(y * 100), -TER_D, -TER_D + 0.12, y - 0.05, y + 0.05, Z0 - 0.06, Z1, trim)
box("rail_top", -TER_D, -TER_D + 0.14, 0.05, WY - 0.05, Z0 + 0.98, Z0 + 1.08, wood)
box("rail_glass", -TER_D + 0.05, -TER_D + 0.09, 0.08, WY - 0.08, Z0 + 0.10, Z0 + 0.96, glass)
# крыльцо
box("porch_deck", 5.55, 6.95, -2.55, 0.0, Z0 - 0.34, Z0 - 0.04, deck)
for i in range(3):
y0 = -2.55 - 0.36 * (i + 1)
box("step_%d" % i, 5.75, 6.75, y0, y0 + 0.36, 0.02, 0.50 - 0.15 * i, deck)
for y in (-2.5, -1.3, -0.1):
box("ppost_%d" % int(-y * 10), 5.6, 5.72, y - 0.05, y + 0.05, Z0 - 0.04, Z1 - 0.7, trim)
# тех.пом.
box("tech", 4.90, 7.00, WY, WY + 2.10, Z0, Z1 - 0.30, metal)
box("tech_roof", 4.80, 7.10, WY - 0.06, WY + 2.20, Z1 - 0.30, Z1 - 0.18, roofm)
box("tech_door", 5.15, 5.95, WY + 2.02, WY + 2.10, Z0 + 0.02, Z0 + 2.0, trim)
# земля и дорожка
bpy.ops.mesh.primitive_plane_add(size=160, location=(LX / 2, WY / 2, -0.01))
bpy.context.object.data.materials.append(ground)
box("path", 5.65, 6.85, -14.0, -2.55, 0.0, 0.03, ground)
# небо и свет
w = bpy.data.worlds.new("World")
sc.world = w
w.use_nodes = True
nt = w.node_tree
sky = nt.nodes.new("ShaderNodeTexSky")
sky.sky_type = "NISHITA"
sky.sun_elevation = math.radians(24)
sky.sun_rotation = math.radians(210)
bg = nt.nodes["Background"]
nt.links.new(sky.outputs["Color"], bg.inputs["Color"])
bg.inputs["Strength"].default_value = 0.14
bpy.ops.object.light_add(type="SUN", location=(-14, -20, 26))
sun = bpy.context.object
sun.data.energy = 2.0
sun.data.angle = math.radians(1.4)
sun.rotation_euler = (math.radians(54), 0, math.radians(36))
# камера и рендер
cd = bpy.data.cameras.new("Cam")
cd.lens = 42
cam = bpy.data.objects.new("Cam", cd)
bpy.context.collection.objects.link(cam)
sc.camera = cam
sc.render.engine = "CYCLES"
sc.cycles.device = "CPU"
sc.cycles.samples = 48
sc.cycles.use_denoising = False
sc.cycles.max_bounces = 6
sc.render.resolution_x, sc.render.resolution_y = 900, 500
sc.view_settings.view_transform = "AgX"
sc.view_settings.exposure = -1.7
def shot(name, loc, target):
cam.location = loc
cam.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
sc.render.filepath = os.path.join(OUT, name)
bpy.ops.render.render(write_still=True)
print("render:", name, flush=True)
shot("render-front.png", (LX + 11.0, -13.0, 5.4), (LX / 2 - 0.5, WY / 2 - 0.5, 2.1))
pass # тест: только южный ракурс
# GLB
bpy.ops.object.select_all(action="SELECT")
glb = os.path.join(OUT, "house.glb")
bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_apply=True,
use_selection=True, export_yup=True)
print("glb:", os.path.getsize(glb), flush=True)
print("done")
if __name__ == "__main__":
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 683 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB