| 1 | // VibeCodeViewer — metrópolis de cristal nítida. |
| 2 | import * as THREE from 'three'; |
| 3 | import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; |
| 4 | import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; |
| 5 | import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; |
| 6 | import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; |
| 7 | import { REPO_TREE, REPO_META } from './data.js'; |
| 8 | import { buildModel, applyCodeMeta } from './model.js'; |
| 9 | import { computeMode } from './colorModes.js'; |
| 10 | import { buildCity } from './builder.js'; |
| 11 | import { createNavigation } from './controls.js'; |
| 12 | import { createUI } from './ui.js'; |
| 13 | import { canPickFolder, pickAndScanFolder, reopenLastFolder, savedFolderName } from './fsScan.js'; |
| 14 | import { detectGPU } from './gpu.js'; |
| 15 | import { THEMES } from './themes.js'; |
| 16 | import { t } from './i18n.js'; |
| 17 | |
| 18 | const VISUAL_STORAGE_KEY = 'vcc.visualSettings.v1'; |
| 19 | const DEFAULT_VISUAL_SETTINGS = { |
| 20 | exposure: 1.05, |
| 21 | brightness: 1, |
| 22 | contrast: 1, |
| 23 | saturate: 1, |
| 24 | lines: 1, |
| 25 | files: 1, |
| 26 | glass: 1, |
| 27 | facades: 1, |
| 28 | labels: 1, |
| 29 | ground: 1, |
| 30 | fog: 1, |
| 31 | }; |
| 32 | const VISUAL_SETTING_LIMITS = { |
| 33 | exposure: [0.65, 1.8], |
| 34 | brightness: [0.75, 1.45], |
| 35 | contrast: [0.8, 1.8], |
| 36 | saturate: [0.6, 2.4], |
| 37 | lines: [0.45, 2.2], |
| 38 | files: [0.45, 2.4], |
| 39 | glass: [0.35, 2.2], |
| 40 | facades: [0.2, 1.8], |
| 41 | labels: [0.2, 2.4], |
| 42 | ground: [0.25, 1.5], |
| 43 | fog: [0.35, 1.8], |
| 44 | }; |
| 45 | |
| 46 | function sanitizeVisualSettings(values = {}) { |
| 47 | const out = { ...DEFAULT_VISUAL_SETTINGS }; |
| 48 | for (const key of Object.keys(DEFAULT_VISUAL_SETTINGS)) { |
| 49 | const n = Number(values[key]); |
| 50 | const [min, max] = VISUAL_SETTING_LIMITS[key]; |
| 51 | out[key] = Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : DEFAULT_VISUAL_SETTINGS[key]; |
| 52 | } |
| 53 | return out; |
| 54 | } |
| 55 | |
| 56 | function loadVisualSettings() { |
| 57 | try { |
| 58 | return sanitizeVisualSettings(JSON.parse(localStorage.getItem(VISUAL_STORAGE_KEY) || '{}')); |
| 59 | } catch { |
| 60 | return { ...DEFAULT_VISUAL_SETTINGS }; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | let visualSettings = loadVisualSettings(); |
| 65 | |
| 66 | // ── base persistente (renderer, cámara, composer) ───────────────────────── |
| 67 | // powerPreference fuerza la GPU discreta en portátiles con doble gráfica |
| 68 | const canvas = document.getElementById('view'); |
| 69 | const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); |
| 70 | const gpu = detectGPU(renderer.getContext()); |
| 71 | console.info(`[gpu] ${gpu.brand} · nivel ${gpu.tier} · renderer "${gpu.name}" · vendor "${gpu.vendor}" · bloom ${gpu.bloom ? 'on' : 'off'} · MSAA RT ×${gpu.msaaSamples} · pixelRatio ≤${gpu.pixelRatioCap}${gpu.override ? ` · override ${gpu.override}` : ''}${gpu.webgpu ? ' · WebGPU disponible' : ''}`); |
| 72 | renderer.setPixelRatio(Math.min(window.devicePixelRatio, gpu.pixelRatioCap)); |
| 73 | renderer.toneMapping = THREE.ACESFilmicToneMapping; |
| 74 | renderer.toneMappingExposure = visualSettings.exposure; |
| 75 | renderer.setClearColor(0x020309, 1); |
| 76 | |
| 77 | const scene = new THREE.Scene(); |
| 78 | scene.background = new THREE.Color(0x020309); |
| 79 | const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 1000); |
| 80 | |
| 81 | function createRenderPipeline() { |
| 82 | if (!gpu.bloom) { |
| 83 | return { |
| 84 | bloom: { strength: 0, threshold: 1, resolution: new THREE.Vector2(1, 1) }, |
| 85 | resize: () => {}, |
| 86 | render: () => renderer.render(scene, camera), |
| 87 | }; |
| 88 | } |
| 89 | |
| 90 | const target = new THREE.WebGLRenderTarget(1, 1, { |
| 91 | type: THREE.HalfFloatType, |
| 92 | samples: gpu.msaaSamples, |
| 93 | }); |
| 94 | target.texture.name = 'VCC.composer'; |
| 95 | const composer = new EffectComposer(renderer, target); |
| 96 | composer.addPass(new RenderPass(scene, camera)); |
| 97 | const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.65, 0.25, 0.85); |
| 98 | composer.addPass(bloom); |
| 99 | composer.addPass(new OutputPass()); |
| 100 | return { |
| 101 | bloom, |
| 102 | resize: (w, h) => { |
| 103 | composer.setSize(w, h); |
| 104 | bloom.resolution.set(w, h); |
| 105 | }, |
| 106 | render: () => composer.render(), |
| 107 | }; |
| 108 | } |
| 109 | const pipeline = createRenderPipeline(); |
| 110 | const bloom = pipeline.bloom; |
| 111 | |
| 112 | function resize() { |
| 113 | const w = window.innerWidth, h = window.innerHeight; |
| 114 | renderer.setSize(w, h, false); |
| 115 | pipeline.resize(w, h); |
| 116 | camera.aspect = w / h; |
| 117 | camera.updateProjectionMatrix(); |
| 118 | } |
| 119 | window.addEventListener('resize', resize); |
| 120 | |
| 121 | // ── estado reconstruible (modelo + ciudad + navegación) ─────────────────── |
| 122 | let model = null, city = null, nav = null; |
| 123 | let legendOn = true; |
| 124 | let groundSolid = false; |
| 125 | let colorMode = 'basic'; |
| 126 | let themeName = 'hacker'; |
| 127 | let fogBaseDensity = 0; |
| 128 | |
| 129 | function applyVisualSettings(next, { persist = true } = {}) { |
| 130 | visualSettings = next === null |
| 131 | ? { ...DEFAULT_VISUAL_SETTINGS } |
| 132 | : sanitizeVisualSettings({ ...visualSettings, ...next }); |
| 133 | renderer.toneMappingExposure = visualSettings.exposure; |
| 134 | canvas.style.filter = [ |
| 135 | `brightness(${visualSettings.brightness})`, |
| 136 | `contrast(${visualSettings.contrast})`, |
| 137 | `saturate(${visualSettings.saturate})`, |
| 138 | ].join(' '); |
| 139 | if (scene.fog && fogBaseDensity) scene.fog.density = fogBaseDensity * visualSettings.fog; |
| 140 | city?.setVisuals?.(visualSettings); |
| 141 | if (persist) localStorage.setItem(VISUAL_STORAGE_KEY, JSON.stringify(visualSettings)); |
| 142 | return { ...visualSettings }; |
| 143 | } |
| 144 | |
| 145 | function setBloomMode(enabled) { |
| 146 | const url = new URL(location.href); |
| 147 | if (enabled) url.searchParams.set('bloom', '1'); |
| 148 | else url.searchParams.delete('bloom'); |
| 149 | location.assign(url); |
| 150 | } |
| 151 | |
| 152 | // aplica la parte "barata" del tema: escena, bloom y variables CSS de la UI |
| 153 | function setSceneTheme(t) { |
| 154 | scene.background = new THREE.Color(t.background); |
| 155 | scene.fog?.color.set(t.fog); |
| 156 | bloom.strength = t.bloom.strength; |
| 157 | bloom.threshold = t.bloom.threshold; |
| 158 | for (const [k, v] of Object.entries(t.css)) { |
| 159 | document.documentElement.style.setProperty('--' + k, v); |
| 160 | } |
| 161 | // la clase `light` gobierna la UI; el blending de la escena usa t.light |
| 162 | document.body.classList.toggle('light', !!(t.uiLight ?? t.light)); |
| 163 | } |
| 164 | |
| 165 | function buildCityThemed() { |
| 166 | const t = THEMES[themeName]; |
| 167 | setSceneTheme(t); |
| 168 | city = buildCity(scene, model, t); |
| 169 | city.setLegend(legendOn); |
| 170 | city.setGroundOpaque(groundSolid); |
| 171 | city.setVisuals(visualSettings); |
| 172 | } |
| 173 | |
| 174 | function boot(packedTree, meta) { |
| 175 | selectedFile = null; |
| 176 | hoveredBuilding = null; |
| 177 | litFacade = null; |
| 178 | pulsers = []; |
| 179 | suggestions = []; |
| 180 | sugFacades.clear(); |
| 181 | |
| 182 | city?.dispose(); |
| 183 | nav?.dispose(); |
| 184 | |
| 185 | model = buildModel(packedTree, meta); |
| 186 | const extent = Math.max(model.city.box.sx, model.city.box.sz); |
| 187 | fogBaseDensity = 0.62 / extent; |
| 188 | scene.fog = new THREE.FogExp2(THEMES[themeName].fog, fogBaseDensity * visualSettings.fog); |
| 189 | camera.far = extent * 14; |
| 190 | camera.updateProjectionMatrix(); |
| 191 | |
| 192 | buildCityThemed(); |
| 193 | nav = createNavigation(camera, canvas, model.city.box); |
| 194 | nav.VIEWS.reset(); |
| 195 | ui.setModel(model); |
| 196 | ui.setModeAvailable('git', model.hasGit); |
| 197 | ui.setModeAvailable('ownership', model.owners.length > 0); |
| 198 | ui.setModeAvailable('blast', |
| 199 | Object.keys(model.linksOut).length > 0 || Object.keys(model.symOut).length > 0); |
| 200 | applyColorMode('basic'); |
| 201 | window.VCC = { model, city, nav, camera, selectFile, selectNode, clearSelection, applyColorMode, applyTheme, applyVisualSettings }; |
| 202 | } |
| 203 | |
| 204 | // cambia de tema reconstruyendo solo la ciudad (modelo y cámara intactos) |
| 205 | function applyTheme(name) { |
| 206 | if (!THEMES[name]) return; |
| 207 | themeName = name; |
| 208 | const sel = selectedFile; |
| 209 | city?.dispose(); |
| 210 | hoveredBuilding = null; |
| 211 | litFacade = null; |
| 212 | pulsers = []; |
| 213 | sugFacades.clear(); |
| 214 | suggestions = []; |
| 215 | buildCityThemed(); |
| 216 | applyColorMode(colorMode); |
| 217 | if (sel) selectFile(sel); |
| 218 | window.VCC.city = city; |
| 219 | } |
| 220 | |
| 221 | // ── modos de coloreado (básico / git / ownership) ───────────────────────── |
| 222 | function applyColorMode(mode) { |
| 223 | colorMode = mode; |
| 224 | document.body.classList.toggle('mode-git', mode === 'git'); |
| 225 | const theme = THEMES[themeName]; |
| 226 | const m = computeMode(model, mode, theme); |
| 227 | city.setModeColors(m.fileColor, m.nodeColor); |
| 228 | ui.setColorLegend(mode === 'blast' |
| 229 | ? [ |
| 230 | { label: t('legend.impact'), color: theme.beamIn ?? theme.beam }, |
| 231 | { label: t('legend.dependencies'), color: theme.beam }, |
| 232 | ] |
| 233 | : m.legend); |
| 234 | ui.setActiveMode(mode); |
| 235 | city.setBlastBeams(null); |
| 236 | // reaplica la selección activa sobre los nuevos colores base |
| 237 | if (selectedFile) selectFile(selectedFile); |
| 238 | } |
| 239 | |
| 240 | // ── modo Blast: relaciones de código del fichero seleccionado ───────────── |
| 241 | // dependencias (lo que este fichero usa) en theme.beam; dependientes —el |
| 242 | // impacto de cambiarlo: imports + usos de sus símbolos— en theme.beamIn. |
| 243 | |
| 244 | function blastEdges(file) { |
| 245 | // rel destino → { impact, syms:Set } (impact gana si hay ambas direcciones) |
| 246 | const edges = new Map(); |
| 247 | const dirs = new Set(); |
| 248 | const touch = (rel, impact, sym) => { |
| 249 | if (rel === file.rel) return; |
| 250 | const e = edges.get(rel) ?? { impact: false, syms: new Set() }; |
| 251 | e.impact ||= impact; |
| 252 | if (sym) e.syms.add(sym); |
| 253 | edges.set(rel, e); |
| 254 | }; |
| 255 | for (const tok of model.linksOut[file.rel] ?? []) { |
| 256 | if (tok.startsWith('F:')) touch(tok.slice(2), false); |
| 257 | else dirs.add(tok.slice(2)); |
| 258 | } |
| 259 | for (const [target, sym] of model.symOut[file.rel] ?? []) touch(target, false, sym); |
| 260 | for (const src of model.linksIn[file.rel] ?? []) touch(src, true); |
| 261 | for (const [src, sym] of model.symIn[file.rel] ?? []) touch(src, true, sym); |
| 262 | return { edges, dirs }; |
| 263 | } |
| 264 | |
| 265 | function applyBlast(file) { |
| 266 | const theme = THEMES[themeName]; |
| 267 | const BLAST_DEP = theme.beam.map(c => c * 1.2); |
| 268 | const BLAST_IMP = (theme.beamIn ?? theme.beam).map(c => c * 1.2); |
| 269 | const NODE_DEP = theme.beam.map(c => c * 0.75); |
| 270 | const NODE_IMP = (theme.beamIn ?? theme.beam).map(c => c * 0.75); |
| 271 | const from = [file.box.cx, file.box.cy, file.box.cz]; |
| 272 | const { edges, dirs } = blastEdges(file); |
| 273 | const pairs = []; |
| 274 | let nImp = 0, nDep = 0; |
| 275 | for (const [rel, e] of edges) { |
| 276 | const t = model.fileByRel.get(rel); |
| 277 | if (!t) continue; |
| 278 | e.impact ? nImp++ : nDep++; |
| 279 | city.paintFile(t.id, e.impact ? 0.95 : 0.8, e.impact ? BLAST_IMP : BLAST_DEP); |
| 280 | city.paintNode(t.node, 0.3, e.impact ? NODE_IMP : NODE_DEP); |
| 281 | pairs.push({ a: from, b: [t.box.cx, t.box.cy, t.box.cz], impact: e.impact }); |
| 282 | } |
| 283 | for (const rel of dirs) { |
| 284 | const n = model.dirByRel.get(rel); |
| 285 | if (!n?.box) continue; |
| 286 | nDep++; |
| 287 | city.paintNode(n, 0.55, NODE_DEP); |
| 288 | pairs.push({ a: from, b: [n.box.cx, n.box.cy, n.box.cz], impact: false }); |
| 289 | } |
| 290 | city.setBlastBeams(pairs); |
| 291 | ui.setColorLegend([ |
| 292 | { label: `${t('legend.impact')} · ${nImp}`, color: theme.beamIn ?? theme.beam }, |
| 293 | { label: `${t('legend.dependencies')} · ${nDep}`, color: theme.beam }, |
| 294 | ]); |
| 295 | } |
| 296 | |
| 297 | // ── selección jerárquica ────────────────────────────────────────────────── |
| 298 | const DECAY = 0.56; // caída de intensidad por nivel: cajón → … → distrito |
| 299 | let selectedFile = null; |
| 300 | let hoveredBuilding = null; |
| 301 | let litFacade = null; |
| 302 | let pulsers = []; // distritos encendidos que laten |
| 303 | let suggestions = []; // resultados de búsqueda que parpadean |
| 304 | const sugFacades = new Set(); |
| 305 | |
| 306 | function setFacade(building, keys) { |
| 307 | if (litFacade && litFacade !== building) city.redrawFacade(litFacade, null); |
| 308 | litFacade = building; |
| 309 | if (building) city.redrawFacade(building, keys); |
| 310 | } |
| 311 | |
| 312 | function glowChain(startNode, startGlow) { |
| 313 | const fills = []; |
| 314 | pulsers = []; |
| 315 | let glow = startGlow; |
| 316 | for (let n = startNode; n && n.role !== 'ciudad'; n = n.parent) { |
| 317 | if (n.role === 'distrito') { |
| 318 | // el barrio se ilumina algo más y late (pulse en el bucle de render) |
| 319 | const g = Math.min(1, glow * 2.4); |
| 320 | city.paintNode(n, g); |
| 321 | pulsers.push({ node: n, glow: g }); |
| 322 | } else { |
| 323 | city.paintNode(n, glow); |
| 324 | // relleno volumétrico solo en niveles interiores: el edificio se marca |
| 325 | // con aristas y fresnel para no velar el interior |
| 326 | if (fills.length < 10 && n.role !== 'edificio') fills.push({ box: n.box, glow }); |
| 327 | } |
| 328 | glow *= DECAY; |
| 329 | } |
| 330 | city.fillBoxes(fills); |
| 331 | } |
| 332 | |
| 333 | function selectFile(file, { fly = false } = {}) { |
| 334 | city.clearGlows(); |
| 335 | city.setBlastBeams(null); |
| 336 | selectedFile = file; |
| 337 | hoveredBuilding = null; |
| 338 | ui.markNode(null); |
| 339 | // celda a tope, hermanas del mismo contenedor a media luz |
| 340 | for (const fid of file.node.fileIds) city.paintFile(fid, fid === file.id ? 1 : 0.18); |
| 341 | glowChain(file.node, 1); |
| 342 | // fachada: resalta la ruta dentro del edificio |
| 343 | const building = file.node.building; |
| 344 | if (building) { |
| 345 | const keys = new Set(['f' + file.id]); |
| 346 | for (let n = file.node; n && n.building === building; n = n.parent) keys.add('n' + n.id); |
| 347 | setFacade(building, keys); |
| 348 | } |
| 349 | if (colorMode === 'blast') applyBlast(file); |
| 350 | const chainNames = [...file.chain].reverse().filter(n => !n.virtual).map(n => n.name); |
| 351 | ui.setPath(file, chainNames); |
| 352 | ui.markFile(file); |
| 353 | if (fly) nav.VIEWS.focus(file.node.box, 3.2); |
| 354 | } |
| 355 | |
| 356 | function selectNode(node) { |
| 357 | if (!node.box) return; |
| 358 | city.clearGlows(); |
| 359 | city.setBlastBeams(null); |
| 360 | selectedFile = null; |
| 361 | setFacade(null, null); |
| 362 | glowChain(node, 0.85); |
| 363 | // selección sincronizada ciudad ↔ árbol, con la ruta del nivel |
| 364 | const names = []; |
| 365 | for (let n = node; n && n.role !== 'ciudad'; n = n.parent) if (!n.virtual) names.unshift(n.name); |
| 366 | ui.setPathParts(names.length ? names : null); |
| 367 | ui.markFile(null); |
| 368 | ui.markNode(node); |
| 369 | const wide = node.role === 'edificio' || node.role === 'distrito' || node.role === 'urbanizacion'; |
| 370 | nav.VIEWS.focus(node.box, wide ? 1.6 : 2.6); |
| 371 | } |
| 372 | |
| 373 | function clearSelection() { |
| 374 | city.clearGlows(); |
| 375 | city.setBlastBeams(null); |
| 376 | setFacade(null, null); |
| 377 | pulsers = []; |
| 378 | selectedFile = null; |
| 379 | ui.setPath(null); |
| 380 | ui.markFile(null); |
| 381 | ui.markNode(null); |
| 382 | } |
| 383 | |
| 384 | // ── sugerencias de búsqueda: parpadeo en ciudad y fachadas ──────────────── |
| 385 | function setSuggestions(files) { |
| 386 | for (const f of suggestions) if (f !== selectedFile) city.paintFile(f.id, 0); |
| 387 | for (const b of sugFacades) if (b !== litFacade) city.redrawFacade(b, null); |
| 388 | sugFacades.clear(); |
| 389 | suggestions = files; |
| 390 | const byBuilding = new Map(); |
| 391 | for (const f of files) { |
| 392 | const b = f.node.building; |
| 393 | if (!b || b === litFacade) continue; |
| 394 | if (!byBuilding.has(b)) byBuilding.set(b, new Set()); |
| 395 | byBuilding.get(b).add('f' + f.id); |
| 396 | } |
| 397 | for (const [b, keys] of byBuilding) { |
| 398 | city.redrawFacade(b, keys); |
| 399 | sugFacades.add(b); |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | // ── interacción de ratón ────────────────────────────────────────────────── |
| 404 | const raycaster = new THREE.Raycaster(); |
| 405 | const pointer = new THREE.Vector2(); |
| 406 | |
| 407 | canvas.addEventListener('pointermove', (e) => { |
| 408 | pointer.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1); |
| 409 | hoverDirty = true; |
| 410 | }); |
| 411 | |
| 412 | function pick() { |
| 413 | if (nav.fly.active) raycaster.setFromCamera(new THREE.Vector2(0, 0), camera); |
| 414 | else raycaster.setFromCamera(pointer, camera); |
| 415 | const fileHit = raycaster.intersectObject(city.filesMesh)[0]; |
| 416 | const shellHit = raycaster.intersectObjects(city.shells)[0]; |
| 417 | return { fileHit, shellHit }; |
| 418 | } |
| 419 | |
| 420 | let hoverDirty = true; |
| 421 | let lastHoverAt = 0; |
| 422 | function updateHover(now) { |
| 423 | if (selectedFile) return; |
| 424 | if (!nav.fly.active && !hoverDirty && now - lastHoverAt < 50) return; |
| 425 | hoverDirty = false; |
| 426 | lastHoverAt = now; |
| 427 | // solo carcasas: raycast contra cientos de miles de celdas por frame no escala |
| 428 | if (nav.fly.active) raycaster.setFromCamera(new THREE.Vector2(0, 0), camera); |
| 429 | else raycaster.setFromCamera(pointer, camera); |
| 430 | const shellHit = raycaster.intersectObjects(city.shells)[0]; |
| 431 | const b = shellHit?.object.userData.building ?? null; |
| 432 | if (b !== hoveredBuilding) { |
| 433 | if (hoveredBuilding) city.paintNode(hoveredBuilding, 0); |
| 434 | hoveredBuilding = b; |
| 435 | if (b) city.paintNode(b, 0.16); |
| 436 | canvas.style.cursor = b ? 'pointer' : 'default'; |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | let downAt = null; |
| 441 | canvas.addEventListener('pointerdown', (e) => { downAt = [e.clientX, e.clientY]; }); |
| 442 | canvas.addEventListener('pointerup', (e) => { |
| 443 | if (!downAt) return; |
| 444 | const moved = Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]); |
| 445 | downAt = null; |
| 446 | if (moved > 5) return; // era un arrastre de cámara |
| 447 | const { fileHit, shellHit } = pick(); |
| 448 | if (fileHit && (!shellHit || fileHit.distance < shellHit.distance + 2)) { |
| 449 | selectFile(model.files[fileHit.instanceId]); |
| 450 | } else if (shellHit) { |
| 451 | selectNode(shellHit.object.userData.building); |
| 452 | } else { |
| 453 | clearSelection(); |
| 454 | } |
| 455 | }); |
| 456 | |
| 457 | document.addEventListener('keydown', (e) => { |
| 458 | if (document.activeElement?.tagName === 'INPUT') return; |
| 459 | if (e.code === 'Digit1') nav.VIEWS.reset(); |
| 460 | if (e.code === 'Digit2') nav.VIEWS.aerial(); |
| 461 | if (e.code === 'Digit3') nav.VIEWS.skyline(); |
| 462 | if (e.code === 'KeyX') clearSelection(); |
| 463 | if (e.code === 'KeyL') document.getElementById('btn-legend').click(); |
| 464 | if (e.code === 'KeyG') document.getElementById('btn-ground').click(); |
| 465 | if (e.code === 'Slash' || (e.code === 'KeyB' && e.ctrlKey)) { |
| 466 | e.preventDefault(); |
| 467 | document.getElementById('search-input').focus(); |
| 468 | } |
| 469 | }); |
| 470 | |
| 471 | // ── carga de carpetas: escaneo + análisis perezoso del modo Blast ───────── |
| 472 | // `scanGen` invalida un análisis en curso si se carga otra carpeta encima |
| 473 | let scanGen = 0; |
| 474 | async function loadScan(scanFn) { |
| 475 | let scan; |
| 476 | try { |
| 477 | ui.setLoading(t('analysis.loading')); |
| 478 | scan = await scanFn((msg) => ui.setLoading(t('analysis.loadingDetail', { msg }))); |
| 479 | } catch (err) { |
| 480 | if (err?.name !== 'AbortError') console.error(err); |
| 481 | } finally { |
| 482 | ui.setLoading(null); |
| 483 | } |
| 484 | if (!scan) return; |
| 485 | const gen = ++scanGen; |
| 486 | boot(scan.tree, scan.meta); |
| 487 | ui.setReopen(await savedFolderName()); |
| 488 | // el análisis de contenidos corre por lotes con la ciudad ya cargada: |
| 489 | // cada lote persiste su caché y refresca los enlaces del modo Blast |
| 490 | await scan.runAnalysis?.({ |
| 491 | isCancelled: () => gen !== scanGen, |
| 492 | onProgress: (msg) => { if (gen === scanGen) ui.setAnalysis(msg); }, |
| 493 | onBatch: (m) => { |
| 494 | if (gen !== scanGen) return; |
| 495 | applyCodeMeta(model, m.links, m.codeIndex); |
| 496 | ui.setModeAvailable('blast', |
| 497 | Object.keys(model.linksOut).length > 0 || Object.keys(model.symOut).length > 0); |
| 498 | if (colorMode === 'blast' && selectedFile) applyBlast(selectedFile); |
| 499 | }, |
| 500 | }); |
| 501 | if (gen === scanGen) ui.setAnalysis(null); |
| 502 | } |
| 503 | |
| 504 | // ── UI ──────────────────────────────────────────────────────────────────── |
| 505 | const ui = createUI({ |
| 506 | onSelectFile: (f, opts) => selectFile(f, opts ?? { fly: true }), |
| 507 | onSelectNode: (n) => { if (n.box) selectNode(n); }, |
| 508 | onView: (v) => nav.VIEWS[v](), |
| 509 | onSuggest: (files) => setSuggestions(files), |
| 510 | onToggleLegend: (on) => { legendOn = on; city.setLegend(on); }, |
| 511 | onToggleGround: (solid) => { groundSolid = solid; city.setGroundOpaque(solid); }, |
| 512 | onTheme: (name) => applyTheme(name), |
| 513 | getVisualSettings: () => ({ ...visualSettings }), |
| 514 | onVisualSettings: (settings) => applyVisualSettings(settings), |
| 515 | onVisualPreset: (settings) => applyVisualSettings(settings), |
| 516 | onBloomMode: (enabled) => setBloomMode(enabled), |
| 517 | isBloomEnabled: () => gpu.bloom, |
| 518 | onMode: (mode) => applyColorMode(mode), |
| 519 | onPickFolder: () => loadScan(pickAndScanFolder), |
| 520 | onReopenFolder: () => loadScan(reopenLastFolder), |
| 521 | onLanguageChanged: () => { |
| 522 | if (!model || !city) return; |
| 523 | applyColorMode(colorMode); |
| 524 | if (selectedFile) selectFile(selectedFile); |
| 525 | }, |
| 526 | }); |
| 527 | ui.setFolderSupported(canPickFolder()); |
| 528 | ui.setGpu(gpu); |
| 529 | if (canPickFolder()) savedFolderName().then((name) => ui.setReopen(name)); |
| 530 | canvas.addEventListener('flymode', (e) => ui.setFlyMode(e.detail)); |
| 531 | |
| 532 | // ── arranque + bucle ────────────────────────────────────────────────────── |
| 533 | boot(REPO_TREE, REPO_META); |
| 534 | resize(); |
| 535 | applyVisualSettings(visualSettings, { persist: false }); |
| 536 | |
| 537 | let last = performance.now(); |
| 538 | let fpsAcc = 0, fpsN = 0; |
| 539 | function frame(now) { |
| 540 | if (document.hidden) { |
| 541 | last = now; |
| 542 | requestAnimationFrame(frame); |
| 543 | return; |
| 544 | } |
| 545 | const dt = Math.min(0.05, (now - last) / 1000); |
| 546 | last = now; |
| 547 | nav.update(dt); |
| 548 | updateHover(now); |
| 549 | |
| 550 | // pulse de los barrios encendidos |
| 551 | for (const p of pulsers) { |
| 552 | city.paintNode(p.node, Math.min(1, p.glow * (0.78 + 0.3 * Math.sin(now * 0.004)))); |
| 553 | } |
| 554 | // parpadeo suave de las sugerencias de búsqueda |
| 555 | suggestions.forEach((f, i) => { |
| 556 | if (f === selectedFile) return; |
| 557 | city.paintFile(f.id, 0.1 + 0.2 * (0.5 + 0.5 * Math.sin(now * 0.006 + i * 0.8))); |
| 558 | }); |
| 559 | // pulsos de datos por los haces del modo Blast |
| 560 | city.tickBeams(now); |
| 561 | |
| 562 | pipeline.render(); |
| 563 | fpsAcc += dt; fpsN++; |
| 564 | if (fpsAcc >= 0.5) { |
| 565 | ui.setStats(Math.round(fpsN / fpsAcc)); |
| 566 | fpsAcc = 0; fpsN = 0; |
| 567 | } |
| 568 | requestAnimationFrame(frame); |
| 569 | } |
| 570 | requestAnimationFrame(frame); |