Elffuss BraidHub

kikocis/VibeCodeViewer public

26f65a4fb4c5 · 24.2 KiBRawPermalink
1// Construcción de la escena: ciudad de cristal nítida.
2// Receta anti-difuminado: aristas finas con colores HDR (el bloom solo se
3// dispara en lo resaltado), cristal con fresnel de opacidad mínima y nada
4// de volúmenes aditivos permanentes.
5// Toda la paleta viene del tema activo (src/themes.js); los temas claros
6// usan blending normal en lugar de aditivo.
7import * as THREE from 'three';
8
9function lerp3(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; }
10
11// 12 aristas de una caja → 24 vértices
12const EDGE_PAIRS = [
13 [0, 1], [1, 3], [3, 2], [2, 0],
14 [4, 5], [5, 7], [7, 6], [6, 4],
15 [0, 4], [1, 5], [2, 6], [3, 7],
16];
17function corners(b) {
18 const x0 = b.cx - b.sx / 2, x1 = b.cx + b.sx / 2;
19 const y0 = b.cy - b.sy / 2, y1 = b.cy + b.sy / 2;
20 const z0 = b.cz - b.sz / 2, z1 = b.cz + b.sz / 2;
21 return [
22 [x0, y0, z0], [x1, y0, z0], [x0, y0, z1], [x1, y0, z1],
23 [x0, y1, z0], [x1, y1, z0], [x0, y1, z1], [x1, y1, z1],
24 ];
25}
26
27// ── suelo: placa de circuito impreso ──────────────────────────────────────
28function circuitTexture(theme) {
29 const T = theme.ground;
30 const S = 1024;
31 const cv = document.createElement('canvas');
32 cv.width = cv.height = S;
33 const g = cv.getContext('2d');
34 g.fillStyle = T.bg;
35 g.fillRect(0, 0, S, S);
36 g.strokeStyle = T.grid;
37 g.lineWidth = 1;
38 for (let i = 0; i <= S; i += 64) {
39 g.beginPath(); g.moveTo(i, 0); g.lineTo(i, S); g.stroke();
40 g.beginPath(); g.moveTo(0, i); g.lineTo(S, i); g.stroke();
41 }
42 const rnd = (() => { let s = 1234567; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
43 for (let i = 0; i < 260; i++) {
44 const isA = rnd() < 0.58;
45 const a = 0.18 + rnd() * 0.5;
46 const [tr, tg, tb] = isA ? T.traceA : T.traceB;
47 g.strokeStyle = `rgba(${tr}, ${tg}, ${tb}, ${isA ? a : a * 0.9})`;
48 g.lineWidth = rnd() < 0.12 ? 3 : 1.4;
49 let x = rnd() * S, y = rnd() * S;
50 g.beginPath(); g.moveTo(x, y);
51 const segs = 2 + Math.floor(rnd() * 4);
52 for (let sg = 0; sg < segs; sg++) {
53 const len = 24 + rnd() * 150;
54 if (rnd() < 0.5) x += rnd() < 0.5 ? len : -len; else y += rnd() < 0.5 ? len : -len;
55 g.lineTo(x, y);
56 }
57 g.stroke();
58 const [pr, pg, pb] = isA ? T.padA : T.padB;
59 g.fillStyle = `rgba(${pr}, ${pg}, ${pb}, ${a + 0.2})`;
60 const ps = 2 + rnd() * 3;
61 g.fillRect(x - ps / 2, y - ps / 2, ps, ps);
62 }
63 const tx = new THREE.CanvasTexture(cv);
64 tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
65 tx.colorSpace = THREE.SRGBColorSpace;
66 tx.anisotropy = 8;
67 return tx;
68}
69
70// ── cristal con fresnel (bordes algo más vivos, centro casi invisible) ────
71function glassMaterial(theme, dim = 1, solid = 0) {
72 return new THREE.ShaderMaterial({
73 uniforms: {
74 uColor: { value: new THREE.Color(...theme.glass) },
75 uHi: { value: new THREE.Color(...theme.glassHi) },
76 uGlow: { value: 0 },
77 uDim: { value: dim },
78 uSolid: { value: solid },
79 },
80 vertexShader: /* glsl */`
81 varying vec3 vN, vV;
82 void main() {
83 vec4 mv = modelViewMatrix * vec4(position, 1.0);
84 vN = normalMatrix * normal;
85 vV = -mv.xyz;
86 gl_Position = projectionMatrix * mv;
87 }`,
88 fragmentShader: /* glsl */`
89 uniform vec3 uColor;
90 uniform vec3 uHi;
91 uniform float uGlow;
92 uniform float uDim;
93 uniform float uSolid;
94 varying vec3 vN, vV;
95 void main() {
96 float fr = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.6);
97 vec3 col = mix(uColor, uHi, uGlow);
98 float alpha = (0.022 + fr * 0.12 + uSolid * 0.12) * uDim + uGlow * 0.05;
99 gl_FragColor = vec4(col * ((0.5 + fr * 1.9) * uDim + uGlow), alpha);
100 }`,
101 transparent: true,
102 depthWrite: false,
103 side: THREE.DoubleSide,
104 });
105}
106
107// ── fachada: árbol de ficheros impreso sobre el cristal ───────────────────
108const FACADE_MAX_LINES = 150;
109
110function facadeLines(building) {
111 const lines = [];
112 let overflow = false;
113 (function walk(node, depth) {
114 if (lines.length > FACADE_MAX_LINES) { overflow = true; return; }
115 lines.push({ text: node.name + '/', depth, key: 'n' + node.id });
116 for (const c of node.children) walk(c, depth + 1);
117 for (const fid of node.fileIds) {
118 if (lines.length > FACADE_MAX_LINES) { overflow = true; return; }
119 const f = building.modelFiles[fid];
120 lines.push({ text: f.name, depth: depth + 1, key: 'f' + f.id });
121 }
122 })(building, 0);
123 if (overflow) lines.push({ text: '· · ·', depth: 1, key: '' });
124 return lines;
125}
126
127function drawFacade(building, highlight, theme) {
128 const cv = building.facadeCanvas;
129 if (!cv) return; // edificio sin fachada (recorte en ciudades enormes)
130 const g = cv.getContext('2d');
131 const W = cv.width, H = cv.height;
132 g.clearRect(0, 0, W, H);
133 const lines = building.facadeLineCache;
134 const fs = Math.max(9, Math.min(30, (H - 60) / (lines.length + 1)));
135 g.font = `${fs}px "JetBrains Mono", "Cascadia Code", monospace`;
136 g.textBaseline = 'top';
137 let y = 26;
138 for (const ln of lines) {
139 const x = 22 + ln.depth * fs * 1.1;
140 const hot = highlight && highlight.has(ln.key);
141 if (hot) {
142 g.shadowColor = theme.facade.hotGlow;
143 g.shadowBlur = 14;
144 g.fillStyle = theme.facade.hotBg;
145 g.fillRect(x - 6, y - 3, g.measureText(ln.text).width + 12, fs + 6);
146 g.fillStyle = theme.facade.hot;
147 } else {
148 g.shadowBlur = 0;
149 g.fillStyle = theme.facade.text;
150 }
151 g.fillText(ln.text, x, y);
152 y += fs * 1.18;
153 if (y > H - fs) break;
154 }
155 g.shadowBlur = 0;
156 building.facadeTexture.needsUpdate = true;
157}
158
159function buildFacade(building, model, group, theme) {
160 building.modelFiles = model.files;
161 building.facadeLineCache = facadeLines(building);
162 const b = building.box;
163 const H = 1024;
164 const W = Math.round(Math.min(2048, Math.max(256, H * (b.sx / b.sy))));
165 const cv = document.createElement('canvas');
166 cv.width = W; cv.height = H;
167 building.facadeCanvas = cv;
168 const tx = new THREE.CanvasTexture(cv);
169 tx.colorSpace = THREE.SRGBColorSpace;
170 tx.anisotropy = 8;
171 building.facadeTexture = tx;
172 drawFacade(building, null, theme);
173 const mat = new THREE.MeshBasicMaterial({
174 map: tx, transparent: true, depthWrite: false, side: THREE.FrontSide,
175 });
176 const E = 0.14;
177 const faces = [
178 { w: b.sx, pos: [b.cx, b.cy, b.cz + b.sz / 2 + E], rot: 0 },
179 { w: b.sx, pos: [b.cx, b.cy, b.cz - b.sz / 2 - E], rot: Math.PI },
180 { w: b.sz, pos: [b.cx + b.sx / 2 + E, b.cy, b.cz], rot: Math.PI / 2 },
181 { w: b.sz, pos: [b.cx - b.sx / 2 - E, b.cy, b.cz], rot: -Math.PI / 2 },
182 ];
183 for (const f of faces) {
184 const plane = new THREE.Mesh(new THREE.PlaneGeometry(f.w, b.sy), mat);
185 plane.position.set(...f.pos);
186 plane.rotation.y = f.rot;
187 plane.renderOrder = 3;
188 group.add(plane);
189 }
190}
191
192// ── leyenda: nombres serigrafiados (suelo de distrito y tejado) ───────────
193function labelTexture(text, color) {
194 const fs = 96, pad = 40;
195 const probe = document.createElement('canvas').getContext('2d');
196 probe.font = `bold ${fs}px "JetBrains Mono", monospace`;
197 const tw = probe.measureText(text).width;
198 const cv = document.createElement('canvas');
199 cv.width = Math.ceil(tw + pad * 2 + 220);
200 cv.height = 190;
201 const g = cv.getContext('2d');
202 g.font = `bold ${fs}px "JetBrains Mono", monospace`;
203 g.textBaseline = 'middle';
204 // pista de circuito: línea con pads a ambos lados del texto
205 g.strokeStyle = color; g.globalAlpha = 0.65; g.lineWidth = 5;
206 const y = cv.height / 2;
207 g.beginPath(); g.moveTo(14, y); g.lineTo(pad + 60, y); g.stroke();
208 g.beginPath(); g.moveTo(pad + 100 + tw, y); g.lineTo(cv.width - 14, y); g.stroke();
209 g.fillStyle = color;
210 for (const px of [14, pad + 60, pad + 100 + tw, cv.width - 26]) g.fillRect(px - 7, y - 7, 14, 14);
211 g.globalAlpha = 0.92;
212 g.shadowColor = color; g.shadowBlur = 16;
213 g.fillText(text, pad + 80, y);
214 const tx = new THREE.CanvasTexture(cv);
215 tx.colorSpace = THREE.SRGBColorSpace;
216 tx.anisotropy = 8;
217 return { tx, aspect: cv.width / cv.height };
218}
219
220const LEGEND_MAX_BUILDINGS = 400;
221
222function buildLegend(model, labeled, theme) {
223 const legend = new THREE.Group();
224 const add = (text, color, width, pos, flat) => {
225 const { tx, aspect } = labelTexture(text, color);
226 const w = Math.min(width, aspect * 8);
227 const mesh = new THREE.Mesh(
228 new THREE.PlaneGeometry(w, w / aspect),
229 new THREE.MeshBasicMaterial({
230 map: tx, transparent: true, depthWrite: false,
231 blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending,
232 }),
233 );
234 if (flat) mesh.rotation.x = -Math.PI / 2;
235 mesh.position.set(...pos);
236 mesh.renderOrder = 4;
237 legend.add(mesh);
238 };
239 for (const di of model.districts) {
240 add(di.name, theme.labels.district, di.box.sx * 0.85,
241 [di.box.cx, 0.3, di.box.cz + di.box.sz / 2 - 2], true);
242 }
243 // urbanizaciones: mismo serigrafiado de suelo que los distritos, en tono
244 // intermedio; en monorepos se etiquetan las de mayor superficie
245 const urbs = [...model.urbs].sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz);
246 for (const u of urbs.slice(0, LEGEND_MAX_BUILDINGS)) {
247 add(u.name, theme.labels.urb, u.box.sx * 0.8,
248 [u.box.cx, 0.32, u.box.cz + u.box.sz / 2 - 1.4], true);
249 }
250 for (const b of labeled.slice(0, LEGEND_MAX_BUILDINGS)) {
251 if (b.isBasement) continue; // su tejado es la calle: sin etiqueta
252 add(b.name, theme.labels.building, b.box.sx * 0.95,
253 [b.box.cx, b.box.cy + b.box.sy / 2 + 0.12, b.box.cz], true);
254 }
255 return legend;
256}
257
258// ── ciudad completa ───────────────────────────────────────────────────────
259export function buildCity(scene, model, theme) {
260 const group = new THREE.Group();
261 scene.add(group);
262 // paleta del tema; en temas claros el blending aditivo no funciona
263 const ROLE_COLOR = theme.roleColor;
264 const HI = theme.hi;
265 const FILE_BASE = theme.fileBase;
266 const FILE_HI = theme.fileHi;
267 const BLEND = theme.light ? THREE.NormalBlending : THREE.AdditiveBlending;
268
269 // suelo
270 const extent = Math.max(model.city.box.sx, model.city.box.sz);
271 const ground = new THREE.Mesh(
272 new THREE.PlaneGeometry(extent * 7, extent * 7),
273 // semitransparente y a doble cara: los sótanos (ficheros ignorados)
274 // se intuyen a través del plano de circuitos. depthWrite: false — era el
275 // único material que escribía profundidad y, con el rango near/far de la
276 // ciudad, las plotas y serigrafías a ras de suelo hacían z-fighting
277 // (parpadeo en franjas) al mover la cámara
278 new THREE.MeshBasicMaterial({
279 map: circuitTexture(theme), transparent: true, opacity: 0.8, side: THREE.DoubleSide,
280 depthWrite: false,
281 // separa el suelo en el z-buffer de plotas y serigrafías a ras de
282 // suelo (evita el z-fighting cuando el modo opaco activa depthWrite)
283 polygonOffset: true, polygonOffsetFactor: 2, polygonOffsetUnits: 2,
284 }),
285 );
286 ground.material.map.repeat.set(7, 7);
287 ground.rotation.x = -Math.PI / 2;
288 ground.position.y = -0.05;
289 group.add(ground);
290
291 // aristas de las cajas en un único buffer con rangos por nodo.
292 // LOD por presupuesto para monorepos: decenas de miles de wireframes
293 // aditivos se acumulan en blanco. Distritos y edificios siempre dibujan;
294 // del interior se conservan las cajas más grandes y menos profundas.
295 const LINE_BUDGET = 12000;
296 const ROLE_DEPTH = { distrito: 0, urbanizacion: 0, edificio: 0, planta: 1, apartamento: 2, habitacion: 3, archivador: 4, cajon: 5 };
297 const candidates = model.nodes.filter(n => n.role !== 'ciudad' && n.box);
298 let boxNodes = candidates;
299 if (candidates.length > LINE_BUDGET) {
300 const score = (n) => (n.role === 'distrito' || n.role === 'urbanizacion' || n.role === 'edificio')
301 ? Infinity
302 : Math.max(n.box.sx, n.box.sy, n.box.sz) - ROLE_DEPTH[n.role] * 3;
303 boxNodes = candidates.sort((a, b) => score(b) - score(a)).slice(0, LINE_BUDGET);
304 }
305 const positions = new Float32Array(boxNodes.length * 24 * 3);
306 const colors = new Float32Array(boxNodes.length * 24 * 3);
307 // brillo de arista normalizado por edificio: el interior de un edificio
308 // reparte un presupuesto de luz constante (mismo principio que las celdas)
309 const boxesPerBuilding = new Map();
310 for (const n of boxNodes) {
311 if (n.building && n.building !== n) {
312 boxesPerBuilding.set(n.building.id, (boxesPerBuilding.get(n.building.id) ?? 0) + 1);
313 }
314 }
315 // …y una atenuación global suave en ciudades con miles de edificios:
316 // uniforme (todos los edificios conservan el mismo aspecto entre sí),
317 // solo evita que la acumulación aditiva a vista de pájaro se queme
318 const cityDim = Math.min(1, Math.max(0.45, Math.sqrt(900 / Math.max(model.buildings.length, 1))));
319 for (const n of boxNodes) {
320 const local = (!n.building || n.building === n)
321 ? 1
322 : Math.min(1, Math.max(0.12, 30 / (boxesPerBuilding.get(n.building.id) ?? 1)));
323 // las plotas (distrito y urbanización) son solo perímetro: siempre nítidas
324 n.lineDim = (n.role === 'distrito' || n.role === 'urbanizacion') ? 1 : local * cityDim;
325 }
326
327 let v = 0;
328 for (const node of boxNodes) {
329 node.lineStart = v;
330 const cs = corners(node.box);
331 const base = (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon).map(c => c * node.lineDim);
332 node.baseColor = base;
333 for (const [a, b] of EDGE_PAIRS) {
334 for (const p of [cs[a], cs[b]]) {
335 positions[v * 3] = p[0]; positions[v * 3 + 1] = p[1]; positions[v * 3 + 2] = p[2];
336 colors[v * 3] = base[0]; colors[v * 3 + 1] = base[1]; colors[v * 3 + 2] = base[2];
337 v++;
338 }
339 }
340 }
341 const lineGeo = new THREE.BufferGeometry();
342 lineGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
343 lineGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
344 // opacidad adaptativa: cuantas más cajas, más tenue cada arista
345 const lineOpacity = Math.min(0.95, Math.max(0.4, Math.sqrt(4000 / Math.max(boxNodes.length, 1))));
346 const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({
347 vertexColors: true, transparent: true, opacity: lineOpacity,
348 blending: BLEND, depthWrite: false,
349 }));
350 lines.renderOrder = 2;
351 group.add(lines);
352
353 // carcasas de cristal por edificio (también sirven para el raycast).
354 // En ciudades enormes las fachadas con texto se reservan a los edificios
355 // más grandes (una textura canvas por edificio no escala a miles).
356 const byArea = [...model.buildings].sort(
357 (a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz);
358 const facadeSet = new Set(byArea.slice(0, 250));
359 const shells = [];
360 for (const b of model.buildings) {
361 const mat = glassMaterial(theme, cityDim, b.onlyBasement ? 1 : 0);
362 const mesh = new THREE.Mesh(new THREE.BoxGeometry(b.box.sx, b.box.sy, b.box.sz), mat);
363 mesh.position.set(b.box.cx, b.box.cy, b.box.cz);
364 mesh.renderOrder = 1;
365 mesh.userData.building = b;
366 b.shell = mesh;
367 shells.push(mesh);
368 group.add(mesh);
369 if (facadeSet.has(b)) buildFacade(b, model, group, theme);
370 }
371
372 // forjados de las plantas (losa fina, casi invisible); con tope en
373 // monorepos, priorizando las plantas de mayor superficie
374 let slabNodes = model.nodes.filter(n => n.role === 'planta');
375 if (slabNodes.length > 4000) {
376 slabNodes = slabNodes
377 .sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz)
378 .slice(0, 4000);
379 }
380 if (slabNodes.length) {
381 const slabGeo = new THREE.BoxGeometry(1, 1, 1);
382 const slabMat = new THREE.MeshBasicMaterial({
383 color: new THREE.Color(...theme.slab), transparent: true,
384 opacity: Math.min(0.045, 0.045 * Math.sqrt(1500 / slabNodes.length)),
385 depthWrite: false, blending: BLEND,
386 });
387 const slabs = new THREE.InstancedMesh(slabGeo, slabMat, slabNodes.length);
388 const m = new THREE.Matrix4();
389 slabNodes.forEach((n, i) => {
390 m.makeScale(n.box.sx, 0.12, n.box.sz);
391 m.setPosition(n.box.cx, n.box.cy - n.box.sy / 2, n.box.cz);
392 slabs.setMatrixAt(i, m);
393 });
394 slabs.renderOrder = 1;
395 group.add(slabs);
396 }
397
398 // celdas de fichero (instanciadas)
399 const fileGeo = new THREE.BoxGeometry(1, 1, 1);
400 const fileMat = new THREE.MeshBasicMaterial({
401 transparent: true, opacity: 0.9, depthWrite: false, blending: BLEND,
402 });
403 const filesMesh = new THREE.InstancedMesh(fileGeo, fileMat, model.files.length);
404 {
405 const m = new THREE.Matrix4();
406 const c = new THREE.Color();
407 for (const f of model.files) {
408 m.makeScale(f.box.sx, f.box.sy, f.box.sz);
409 m.setPosition(f.box.cx, f.box.cy, f.box.cz);
410 filesMesh.setMatrixAt(f.id, m);
411 filesMesh.setColorAt(f.id, c.setRGB(...FILE_BASE));
412 }
413 filesMesh.instanceColor.needsUpdate = true;
414 }
415 filesMesh.renderOrder = 2;
416 group.add(filesMesh);
417
418 // cajas de relleno para los niveles encendidos (pool reutilizable)
419 const fillPool = [];
420 for (let i = 0; i < 10; i++) {
421 const mesh = new THREE.Mesh(
422 new THREE.BoxGeometry(1, 1, 1),
423 new THREE.MeshBasicMaterial({
424 color: new THREE.Color(...theme.fill), transparent: true, opacity: 0,
425 depthWrite: false, blending: BLEND,
426 }),
427 );
428 mesh.visible = false;
429 mesh.renderOrder = 2;
430 group.add(mesh);
431 fillPool.push(mesh);
432 }
433
434 // ── API de iluminación ──────────────────────────────────────────────
435 const touchedNodes = new Set();
436 const touchedFiles = new Set();
437 const colorAttr = lineGeo.getAttribute('color');
438 const tmpColor = new THREE.Color();
439 // atenuación normalizada por edificio: cada edificio reparte un presupuesto
440 // de luz constante entre sus celdas — así un rascacielos con 50k ficheros
441 // no se quema y uno con 20 sigue viéndose igual que antes
442 const filesPerBuilding = new Map();
443 for (const f of model.files) {
444 const b = f.node.building;
445 if (b) filesPerBuilding.set(b.id, (filesPerBuilding.get(b.id) ?? 0) + 1);
446 }
447 const dimOf = (f) => {
448 const n = filesPerBuilding.get(f.node.building?.id) ?? 1;
449 return Math.min(1, Math.max(0.05, 350 / n)) * cityDim;
450 };
451 // color base por fichero, reescribible por los modos de coloreado
452 const fileBase = model.files.map(f => FILE_BASE.map(c => c * dimOf(f)));
453
454 function paintNode(node, glow, hi = HI) {
455 // los nodos diminutos no tienen aristas (LOD): solo carcasa/relleno
456 if (node.lineStart !== undefined) {
457 const col = lerp3(node.baseColor, hi, Math.pow(glow, 1.35));
458 for (let i = node.lineStart; i < node.lineStart + 24; i++) {
459 colorAttr.array[i * 3] = col[0];
460 colorAttr.array[i * 3 + 1] = col[1];
461 colorAttr.array[i * 3 + 2] = col[2];
462 }
463 // subida parcial: en monorepos el buffer completo pesa decenas de MB
464 colorAttr.addUpdateRange(node.lineStart * 3, 72);
465 colorAttr.needsUpdate = true;
466 }
467 if (node.shell) node.shell.material.uniforms.uGlow.value = glow * 0.3;
468 if (glow > 0.01) touchedNodes.add(node); else touchedNodes.delete(node);
469 }
470
471 function paintFile(fileId, glow, hi = FILE_HI) {
472 const col = lerp3(fileBase[fileId], hi, glow);
473 filesMesh.setColorAt(fileId, tmpColor.setRGB(...col));
474 filesMesh.instanceColor.addUpdateRange(fileId * 3, 3);
475 filesMesh.instanceColor.needsUpdate = true;
476 if (glow > 0.01) touchedFiles.add(fileId); else touchedFiles.delete(fileId);
477 }
478
479 function clearGlows() {
480 for (const n of [...touchedNodes]) paintNode(n, 0);
481 for (const f of [...touchedFiles]) paintFile(f, 0);
482 for (const mesh of fillPool) mesh.visible = false;
483 }
484
485 // haces del modo Blast: del fichero seleccionado a sus relacionados,
486 // con pulsos viajando por la línea como paquetes de datos
487 let blastBeams = null;
488 function setBlastBeams(pairs) {
489 if (blastBeams) {
490 group.remove(blastBeams);
491 blastBeams.geometry.dispose();
492 blastBeams.material.dispose();
493 blastBeams = null;
494 }
495 if (!pairs?.length) return;
496 // pairs: { a, b, impact } — impact=true: b depende del seleccionado
497 // (consecuencias de un cambio); el pulso siempre viaja en el sentido de
498 // la propagación: hacia fuera en impactos, hacia dentro en dependencias
499 const pos = new Float32Array(pairs.length * 6);
500 const dist = new Float32Array(pairs.length * 2);
501 const dir = new Float32Array(pairs.length * 2);
502 pairs.forEach(({ a, b, impact }, i) => {
503 pos.set(a, i * 6);
504 pos.set(b, i * 6 + 3);
505 const len = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
506 dist[i * 2] = impact ? 0 : len;
507 dist[i * 2 + 1] = impact ? len : 0;
508 dir[i * 2] = dir[i * 2 + 1] = impact ? 1 : 0;
509 });
510 const geo = new THREE.BufferGeometry();
511 geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
512 geo.setAttribute('aDist', new THREE.BufferAttribute(dist, 1));
513 geo.setAttribute('aDir', new THREE.BufferAttribute(dir, 1));
514 blastBeams = new THREE.LineSegments(geo, new THREE.ShaderMaterial({
515 uniforms: {
516 uTime: { value: 0 },
517 uColor: { value: new THREE.Color(...theme.beam) },
518 uColorIn: { value: new THREE.Color(...(theme.beamIn ?? theme.beam)) },
519 },
520 vertexShader: /* glsl */`
521 attribute float aDist;
522 attribute float aDir;
523 varying float vD;
524 varying float vDir;
525 void main() {
526 vD = aDist;
527 vDir = aDir;
528 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
529 }`,
530 fragmentShader: /* glsl */`
531 uniform float uTime;
532 uniform vec3 uColor;
533 uniform vec3 uColorIn;
534 varying float vD;
535 varying float vDir;
536 void main() {
537 // tren de pulsos avanzando por la línea (cada ~8 unidades); la
538 // línea base se mantiene bien visible entre pulsos
539 float w = fract(vD * 0.125 - uTime * 1.4);
540 float pulse = exp(-pow((w - 0.2) * 6.0, 2.0));
541 vec3 col = mix(uColor, uColorIn, vDir);
542 gl_FragColor = vec4(col * (0.6 + pulse * 2.4), 0.5 + pulse * 0.5);
543 }`,
544 transparent: true,
545 blending: BLEND,
546 depthWrite: false,
547 }));
548 blastBeams.renderOrder = 3;
549 group.add(blastBeams);
550 }
551
552 function tickBeams(timeMs) {
553 if (blastBeams) blastBeams.material.uniforms.uTime.value = timeMs / 1000;
554 }
555
556 // modos de coloreado: reescribe los colores base de nodos y ficheros
557 // (fileColorFn/nodeColorFn → [r,g,b] o null para el color por defecto)
558 function setModeColors(fileColorFn, nodeColorFn) {
559 for (const node of boxNodes) {
560 const col = nodeColorFn?.(node) ?? (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon);
561 node.baseColor = col.map(c => c * (node.lineDim ?? 1));
562 paintNode(node, 0);
563 }
564 for (const f of model.files) {
565 const dim = dimOf(f);
566 const col = fileColorFn?.(f) ?? FILE_BASE;
567 fileBase[f.id] = col.map(c => c * dim);
568 paintFile(f.id, 0);
569 }
570 // se ha tocado todo: mejor una única subida completa que miles de rangos
571 colorAttr.clearUpdateRanges();
572 filesMesh.instanceColor.clearUpdateRanges();
573 }
574
575 function fillBoxes(boxesWithGlow) {
576 fillPool.forEach((mesh, i) => {
577 const entry = boxesWithGlow[i];
578 if (!entry) { mesh.visible = false; return; }
579 const { box, glow } = entry;
580 mesh.scale.set(box.sx, box.sy, box.sz);
581 mesh.position.set(box.cx, box.cy, box.cz);
582 mesh.material.opacity = 0.008 + glow * 0.045;
583 mesh.visible = true;
584 });
585 }
586
587 // leyenda serigrafiada (conmutable)
588 const legend = buildLegend(model, byArea, theme);
589 group.add(legend);
590
591 function dispose() {
592 scene.remove(group);
593 group.traverse((o) => {
594 o.geometry?.dispose?.();
595 for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
596 m?.map?.dispose?.();
597 m?.dispose?.();
598 }
599 });
600 }
601
602 return {
603 group, lines, shells, filesMesh, ground, legend,
604 paintNode, paintFile, clearGlows, fillBoxes, dispose, setModeColors, setBlastBeams, tickBeams,
605 setLegend: (v) => { legend.visible = v; },
606 // suelo opaco/translúcido. Opaco = escribe profundidad y se dibuja en la
607 // pasada de opacos: oculta de verdad los sótanos (ficheros ignorados)
608 setGroundOpaque: (v) => {
609 const m = ground.material;
610 m.opacity = v ? 1 : 0.8;
611 m.transparent = !v;
612 m.depthWrite = v;
613 m.needsUpdate = true;
614 },
615 redrawFacade: (building, highlightKeys) => drawFacade(building, highlightKeys, theme),
616 };
617}