neuronal / web /app.js
amogaddy's picture
amogaddyofficial
claude sonnet 4.6
Neuronal
d601f7c
Raw History Blame Contribute Delete
118 kB
import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { Particles } from './particles.js'; import { BlocksView, BLOCK_COLORS } from './blocks3d.js'; import { SentinelsView, ROLE_COLORS } from './sentinels3d.js'; import qrcode from './vendor/qrcode.mjs'; // Telefono o tablet: 3D alleggerito (un neurone ogni LITE_STRIDE) per restare fluido. const LITE = matchMedia('(max-width: 900px)').matches || /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent); const LITE_STRIDE = 8; const $ = (id) => document.getElementById(id); const fmt = (n) => n.toLocaleString('it-IT'); const REGION_COLORS = ['#5ce1e6', '#7b8cff', '#c77dff', '#ff6fb5', '#ffb347', '#9be15d', '#4dabf7', '#ff8c69', '#63e6be', '#e599f7', '#ffd43b', '#b2f2bb']; const GLOW_CAP = 40000; // neuroni accesi contemporaneamente al massimo const MARK_CAP = 20000; // neuroni modificati evidenziati const S = { nLayer: 0, nFF: 0, atlas: null, regionOfLayer: [], basePos: null, ws: null, generating: false, aiMsg: null, factors: new Map(), // chiave L*nFF+idx -> fattore eeg: new Float32Array(0), eegMax: new Float32Array(0), selected: null, // {L, idx} focusRegion: -1, tokCount: 0, tokStart: 0, blocks: [], // blocchi dal motore blockProgress: new Map(), // id -> messaggio di elaborazione in corso editing: new Set(), // blocchi di cui si sta cambiando la funzione focusBlock: -1, regions: [], // macroaree con le modifiche dell'utente regionBusy: new Map(), // id area -> id blocco in elaborazione (0 = in coda) ui: null, doctor: null, // stato dell'autodiagnosi e diario memory: null, // memoria a gruppi di neuroni memFocus: -1, // ricordo evidenziato nel 3D // modifica aperta: {kind: 'region'|'block', id, mode: 'rename'|'use'|'delete'|'function'} synapses: null, // ultime sinapsi calcolate per il neurone selezionato msgCount: 0, }; // ---------------------------------------------------------------- scena const canvas = $('scene'); const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); renderer.setPixelRatio(LITE ? 1 : Math.min(devicePixelRatio, 2)); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200); camera.position.set(0, 5, 16); const controls = new OrbitControls(camera, canvas); controls.enableDamping = true; controls.autoRotate = true; controls.autoRotateSpeed = 0.35; let idleTimer; controls.addEventListener('start', () => { controls.autoRotate = false; clearTimeout(idleTimer); }); controls.addEventListener('end', () => { idleTimer = setTimeout(() => (controls.autoRotate = true), 20000); }); function glowSprite() { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'); const grad = g.createRadialGradient(32, 32, 0, 32, 32, 32); grad.addColorStop(0, 'rgba(255,255,255,1)'); grad.addColorStop(0.25, 'rgba(255,255,255,0.55)'); grad.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = grad; g.fillRect(0, 0, 64, 64); return new THREE.CanvasTexture(c); } const sprite = glowSprite(); function pointsLayer(cap, material) { const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage)); geo.setAttribute('color', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage)); geo.setDrawRange(0, 0); const pts = new THREE.Points(geo, material); pts.frustumCulled = false; scene.add(pts); return pts; } let base = null; // tutti i neuroni const glow = pointsLayer(GLOW_CAP, new THREE.PointsMaterial({ size: 0.11, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false })); const marks = pointsLayer(MARK_CAP, new THREE.PointsMaterial({ size: 0.14, map: sprite, vertexColors: true, transparent: true, depthWrite: false, depthTest: false })); marks.renderOrder = 2; // sempre visibili, sopra l'attività const pick = pointsLayer(1, new THREE.PointsMaterial({ size: 0.45, map: sprite, color: 0xffffff, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending })); const posOf = (l, j) => { const k = (l * S.nFF + j) * 3; return [S.basePos[k], S.basePos[k + 1], S.basePos[k + 2]]; }; const particles = new Particles(scene, sprite); const blocksView = new BlocksView(scene, sprite, posOf); const sentinelsView = new SentinelsView(scene, sprite, posOf); let sentinelsKey = ''; function syncSentinels(force) { const d = S.doctor; const key = d ? JSON.stringify([d.network_on, d.groups.map((g) => [g.index, g.region, g.first, g.last, g.enabled])]) : ''; if (!force && key === sentinelsKey) return; sentinelsKey = key; sentinelsView.sync(d?.groups, S.nLayer, S.nFF, !!(d && d.network_on && S.basePos)); } const EXCITE = new THREE.Color('#bff6ff'), INHIBIT = new THREE.Color('#ff5c7a'); let synLines = null; // fili delle sinapsi del neurone selezionato // Esercitazione di infezione: neuroni infetti in verde tossico. const INFECT_GREEN = new THREE.Color('#7cff4f'), CURED_WHITE = new THREE.Color('#e8fbff'); const infGlow = pointsLayer(4000, new THREE.PointsMaterial({ size: 0.12, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); infGlow.renderOrder = 3; const BKEY = 16777216; // chiavi dei neuroni dei blocchi: BKEY + id * 1024 + indice function onInfection(ev) { if (!S.basePos) return; const nff = ev.neurons_per_layer; const at = (key) => { if (key < BKEY) return posOf(Math.floor(key / nff), key % nff); const v = blocksView.views.get(Math.floor((key - BKEY) / 1024)), k = (key - BKEY) % 1024; return v && k < v.block.neurons ? [v.pos[k * 3], v.pos[k * 3 + 1], v.pos[k * 3 + 2]] : null; }; const p = infGlow.geometry.attributes.position.array, c = infGlow.geometry.attributes.color.array; let n = 0; for (const key of ev.list) { const a = at(key); if (!a || n >= 4000) continue; p[n * 3] = a[0]; p[n * 3 + 1] = a[1]; p[n * 3 + 2] = a[2]; c[n * 3] = INFECT_GREEN.r; c[n * 3 + 1] = INFECT_GREEN.g; c[n * 3 + 2] = INFECT_GREEN.b; n++; } infGlow.geometry.attributes.position.needsUpdate = true; infGlow.geometry.attributes.color.needsUpdate = true; infGlow.geometry.setDrawRange(0, n); for (const [from, to] of ev.new) { const a = at(from), b = at(to); if (a && b) particles.spawn(a, b, INFECT_GREEN, 1, 0.7); } // contagio lungo la sinapsi for (const key of ev.cured) { const a = at(key); if (a) particles.spawn(a, [a[0], a[1] + 0.5, a[2]], CURED_WHITE, 1, 0.9); } // guarito const bar = $('infection-bar'); bar.hidden = !ev.on && !ev.healed; bar.classList.toggle('cured', !ev.on); $('inf-cure').hidden = !ev.on; $('inf-text').textContent = ev.on ? `Infezione: ${fmt(ev.infected)} neuroni infetti · ${fmt(ev.healed)} guariti · ${Math.round(ev.seconds)} s${ev.detected ? '' : ' · incubazione, i presidi non se ne sono ancora accorti'}` : `Infezione debellata: ${fmt(ev.healed)} neuroni guariti (massimo ${fmt(ev.peak)} infetti insieme)`; if (!ev.on) setTimeout(() => { if (!S.infOn) bar.hidden = true; }, 15000); S.infOn = ev.on; } $('inf-cure').onclick = () => send({ cmd: 'infect_cure' }); $('btn-infect').onclick = () => { if (S.selected) send({ cmd: 'infect', layer: S.selected.L, idx: S.selected.idx }); }; const MEM_GOLD = new THREE.Color('#ffd166'); const memGlow = pointsLayer(128 * 64, new THREE.PointsMaterial({ size: 0.07, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); memGlow.renderOrder = 3; let memGlowUntil = 0, memGlowPersist = false; // Accende tutti i neuroni dei gruppi indicati (128 per gruppo). function showMemoryGroups(groups, persist) { if (!S.basePos || !S.memory) return; const per = S.memory.per_layer, gs = S.memory.group_neurons; const p = memGlow.geometry.attributes.position.array, c = memGlow.geometry.attributes.color.array; let n = 0; for (const g of groups.slice(0, 64)) { const l = Math.floor(g / per), q = g % per; for (let j = q * gs; j < (q + 1) * gs && j < S.nFF; j++) { const k = (l * S.nFF + j) * 3; p[n * 3] = S.basePos[k]; p[n * 3 + 1] = S.basePos[k + 1]; p[n * 3 + 2] = S.basePos[k + 2]; c[n * 3] = MEM_GOLD.r; c[n * 3 + 1] = MEM_GOLD.g; c[n * 3 + 2] = MEM_GOLD.b; n++; } } memGlow.geometry.attributes.position.needsUpdate = true; memGlow.geometry.attributes.color.needsUpdate = true; memGlow.geometry.setDrawRange(0, n); memGlow.material.opacity = 1; memGlowPersist = persist; memGlowUntil = performance.now() + 4000; } const regionColor = (r) => new THREE.Color(REGION_COLORS[((r % REGION_COLORS.length) + REGION_COLORS.length) % REGION_COLORS.length]); // Disposizione: gli strati scorrono lungo x (dall'ingresso all'uscita), ogni strato è una sezione // ellittica del "cervello"; le macroaree sono separate da un piccolo solco, gli emisferi da una fessura. function buildBrain() { const { nLayer: L, nFF: F } = S; const total = L * F; const pos = new Float32Array(total * 3); const col = new Float32Array(total * 3); const span = 12, gap = 0.32; const nReg = S.atlas ? S.atlas.regions.length : 1; const golden = Math.PI * (3 - Math.sqrt(5)); const gray = new THREE.Color(0.24, 0.26, 0.29); const tmp = new THREE.Color(); let seed = 12345; const rand = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff); for (let l = 0; l < L; l++) { const r = S.regionOfLayer[l] ?? 0; const x = -span / 2 + (l / (L - 1)) * span + (r - (nReg - 1) / 2) * gap; const t = (l + 0.5) / L; const radius = 0.55 + 2.4 * Math.pow(Math.sin(Math.PI * (0.06 + 0.88 * t)), 0.55); const state = S.regions[r]?.state; tmp.copy(gray).lerp(regionColor(r), r === S.focusRegion ? 0.55 : state === 'modificata' ? 0.45 : 0.2); if (S.focusRegion >= 0 && r !== S.focusRegion) tmp.multiplyScalar(0.45); if (state === 'eliminata') tmp.multiplyScalar(0.35); // specializzazione spenta if (state === 'eliminata_tutta') tmp.setRGB(0.07, 0.07, 0.08); // area spenta del tutto for (let j = 0; j < F; j++) { const i = l * F + j; const rr = radius * Math.sqrt((j + 0.5) / F); const th = j * golden; let z = rr * Math.cos(th); z += Math.sign(z) * 0.18; // fessura tra gli emisferi pos[i * 3] = x + (rand() - 0.5) * (span / (L - 1)); pos[i * 3 + 1] = rr * Math.sin(th) * 0.8; pos[i * 3 + 2] = z; const shade = 0.75 + rand() * 0.5; col[i * 3] = tmp.r * shade; col[i * 3 + 1] = tmp.g * shade; col[i * 3 + 2] = tmp.b * shade; } } S.basePos = pos; if (base) { scene.remove(base); base.geometry.dispose(); } // sul telefono si disegna un neurone ogni LITE_STRIDE; le posizioni di tutti restano per attività e selezione let dpos = pos, dcol = col; S.displayKey = null; if (LITE) { const n = Math.ceil(total / LITE_STRIDE); dpos = new Float32Array(n * 3); dcol = new Float32Array(n * 3); S.displayKey = new Int32Array(n); for (let k = 0, i = 0; i < total; i += LITE_STRIDE, k++) { S.displayKey[k] = i; dpos.set(pos.subarray(i * 3, i * 3 + 3), k * 3); dcol.set(col.subarray(i * 3, i * 3 + 3), k * 3); } } const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(dpos, 3)); geo.setAttribute('color', new THREE.BufferAttribute(dcol, 3)); geo.computeBoundingSphere(); base = new THREE.Points(geo, new THREE.PointsMaterial({ size: LITE ? 0.022 : 0.011, vertexColors: true, transparent: true, opacity: 0.6, depthWrite: false })); scene.add(base); glowReset(); renderMarks(); renderPick(); particles.clear(); blocksView.sync(S.blocks, true); syncSentinels(true); drawSynapses(); $('st-neurons').textContent = fmt(total); } // ---------------------------------------------------------------- neuroni accesi const glowSlot = new Map(); // chiave -> slot const glowKey = new Int32Array(GLOW_CAP); const glowInt = new Float32Array(GLOW_CAP); let glowN = 0; function glowReset() { glowSlot.clear(); glowN = 0; glow.geometry.setDrawRange(0, 0); } function light(l, j, v) { const key = l * S.nFF + j; let s = glowSlot.get(key); if (s === undefined) { if (glowN >= GLOW_CAP) return; s = glowN++; glowSlot.set(key, s); glowKey[s] = key; glowInt[s] = 0; const p = glow.geometry.attributes.position.array; p[s * 3] = S.basePos[key * 3]; p[s * 3 + 1] = S.basePos[key * 3 + 1]; p[s * 3 + 2] = S.basePos[key * 3 + 2]; glow.geometry.attributes.position.needsUpdate = true; } glowInt[s] = Math.max(glowInt[s], v); } function glowUpdate(dt) { const decay = Math.pow(0.015, dt); // ~0.25 s di persistenza: si vede il flusso, non una nebbia const p = glow.geometry.attributes.position.array; const c = glow.geometry.attributes.color.array; let moved = false; for (let s = 0; s < glowN; s++) { glowInt[s] *= decay; if (glowInt[s] < 0.04) { // spento: sposta l'ultimo al suo posto glowSlot.delete(glowKey[s]); const last = --glowN; if (s !== last) { glowKey[s] = glowKey[last]; glowInt[s] = glowInt[last]; glowSlot.set(glowKey[s], s); p[s * 3] = p[last * 3]; p[s * 3 + 1] = p[last * 3 + 1]; p[s * 3 + 2] = p[last * 3 + 2]; moved = true; } s--; continue; } const v = glowInt[s]; const rc = regionColor(S.regionOfLayer[Math.floor(glowKey[s] / S.nFF)] ?? 0); const w = v * v * v * 0.7; // i più intensi virano al bianco c[s * 3] = rc.r * v + w; c[s * 3 + 1] = rc.g * v + w; c[s * 3 + 2] = rc.b * v + w; } if (moved) glow.geometry.attributes.position.needsUpdate = true; glow.geometry.attributes.color.needsUpdate = true; glow.geometry.setDrawRange(0, glowN); $('st-active').textContent = fmt(glowN); } // ---------------------------------------------------------------- neuroni modificati e selezione const markColor = (f) => (f === 0 ? new THREE.Color('#ff5c7a') : f > 1 ? new THREE.Color('#5ce1e6') : new THREE.Color('#ffb347')); function renderMarks() { if (!S.basePos) return; const p = marks.geometry.attributes.position.array; const c = marks.geometry.attributes.color.array; let n = 0; for (const [key, f] of S.factors) { if (n >= MARK_CAP) break; const col = markColor(f); p[n * 3] = S.basePos[key * 3]; p[n * 3 + 1] = S.basePos[key * 3 + 1]; p[n * 3 + 2] = S.basePos[key * 3 + 2]; c[n * 3] = col.r; c[n * 3 + 1] = col.g; c[n * 3 + 2] = col.b; n++; } marks.geometry.attributes.position.needsUpdate = true; marks.geometry.attributes.color.needsUpdate = true; marks.geometry.setDrawRange(0, n); } function renderPick() { const sel = S.selected; if (!sel || !S.basePos) { pick.geometry.setDrawRange(0, 0); return; } const key = sel.L * S.nFF + sel.idx; const p = pick.geometry.attributes.position.array; p[0] = S.basePos[key * 3]; p[1] = S.basePos[key * 3 + 1]; p[2] = S.basePos[key * 3 + 2]; pick.geometry.attributes.position.needsUpdate = true; pick.geometry.setDrawRange(0, 1); } const raycaster = new THREE.Raycaster(); raycaster.params.Points.threshold = 0.05; let downAt = null; canvas.addEventListener('pointerdown', (e) => (downAt = [e.clientX, e.clientY])); canvas.addEventListener('pointerup', (e) => { if (!downAt || !base || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 4) return; const r = canvas.getBoundingClientRect(); raycaster.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera); const shit = raycaster.intersectObjects(sentinelsView.pickables)[0]; if (shit) { showTab('blocks'); document.getElementById('diagnosis')?.scrollIntoView({ behavior: 'smooth' }); return; } const bhit = raycaster.intersectObjects(blocksView.pickables)[0]; const hit = raycaster.intersectObject(base)[0]; if (bhit && (!hit || bhit.distance <= hit.distance)) { S.blockNeuron = { id: bhit.object.userData.blockId, k: bhit.index }; openBlock(bhit.object.userData.blockId); return; } if (!hit) return; const key = S.displayKey ? S.displayKey[hit.index] : hit.index; select(Math.floor(key / S.nFF), key % S.nFF); }); function regionName(l) { const r = S.regionOfLayer[l]; return S.atlas && r !== undefined ? S.atlas.regions[r].name : '—'; } function describeFactor(f) { if (f === undefined || f === 1) return 'normale'; if (f === 0) return 'spento'; if (f < 0) return `invertito (×${f})`; return f > 1 ? `amplificato ×${f}` : `ridotto ×${f}`; } function select(l, j) { S.selected = { L: l, idx: j }; S.synapses = null; $('syn-list').replaceChildren(); $('btn-syn').textContent = 'Mostra le sinapsi'; drawSynapses(); $('inspector').hidden = false; $('insp-title').textContent = `Neurone ${fmt(j)}`; $('insp-sub').textContent = `strato ${l} · ${regionName(l)}`; refreshInspector(); renderPick(); } function refreshInspector() { const sel = S.selected; if (!sel) return; const key = sel.L * S.nFF + sel.idx; $('insp-state').textContent = describeFactor(S.factors.get(key)); const s = glowSlot.get(key); $('insp-act').textContent = s === undefined ? 'a riposo' : `${Math.round(glowInt[s] * 100)}% del massimo dello strato`; // ogni neurone ha un indirizzo e sa dove si trova il suo pezzo di memoria sul disco $('insp-addr').textContent = `n. ${fmt(key)}`; if (S.memory) { const per = S.memory.per_layer, gs = S.memory.group_neurons, q = Math.floor(sel.idx / gs), g = sel.L * per + q; const owner = S.memory.memories.find((m) => m.groups.includes(g)); $('insp-group').textContent = `n. ${fmt(g)} (${gs} neuroni, ${S.memory.slot_bits} bit)${owner ? ` · custodisce «${owner.title}»` : ' · libero'}`; $('insp-disk').textContent = `memoria/strato_${String(sel.L).padStart(2, '0')}.bin, byte ${q * (S.memory.slot_bits / 8)}–${(q + 1) * (S.memory.slot_bits / 8) - 1}`; } } $('insp-close').onclick = () => { S.selected = null; S.synapses = null; $('inspector').hidden = true; renderPick(); drawSynapses(); }; // ---------------------------------------------------------------- sinapsi del neurone selezionato $('btn-syn').onclick = () => { if (!S.selected) return; $('btn-syn').textContent = 'Calcolo dai pesi del modello…'; send({ cmd: 'synapses', layer: S.selected.L, idx: S.selected.idx }); }; function onSynapses(ev) { if (!S.selected || ev.layer !== S.selected.L || ev.idx !== S.selected.idx) return; S.synapses = ev; $('btn-syn').textContent = `Ricalcola (${ev.seconds.toFixed(2)} s)`; const list = $('syn-list'); list.replaceChildren(); const section = (title, items, dirIn) => { const box = document.createElement('div'); box.innerHTML = `<h4>${title}</h4>`; for (const [l, j, w] of items.slice(0, 6)) { const b = document.createElement('button'); b.innerHTML = `<span>strato ${l} · neurone ${fmt(j)}</span><span class="${w >= 0 ? 'syn-pos' : 'syn-neg'}">${w >= 0 ? '+' : ''}${w.toFixed(3)}</span>`; b.title = (w >= 0 ? 'eccitatoria' : 'inibitoria') + ' — clicca per andare a quel neurone'; b.onclick = () => select(l, j); box.append(b); } list.append(box); }; section('Riceve da (strato precedente)', ev.in, true); section('Invia a (strato successivo)', ev.out, false); drawSynapses(); // un'ondata di messaggi lungo le sinapsi appena scoperte const me = posOf(ev.layer, ev.idx); const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2]))); for (const [l, j, w] of ev.in) particles.spawn(posOf(l, j), me, w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1); for (const [l, j, w] of ev.out) particles.spawn(me, posOf(l, j), w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1); } function drawSynapses() { if (synLines) { scene.remove(synLines); synLines.geometry.dispose(); synLines.material.dispose(); synLines = null; } const ev = S.synapses; if (!ev || !S.basePos) return; const me = posOf(ev.layer, ev.idx); const pos = [], col = []; const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2]))); const add = (a, b, w) => { const c = (w >= 0 ? EXCITE : INHIBIT).clone().multiplyScalar(0.25 + 0.75 * Math.abs(w) / maxw); pos.push(...a, ...b); col.push(c.r, c.g, c.b, c.r, c.g, c.b); }; for (const [l, j, w] of ev.in) add(posOf(l, j), me, w); for (const [l, j, w] of ev.out) add(me, posOf(l, j), w); const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3)); synLines = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.85, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false })); synLines.renderOrder = 2; scene.add(synLines); } document.querySelectorAll('#inspector [data-factor]').forEach((b) => (b.onclick = () => { if (!S.selected) return; send({ cmd: 'neurons', layer: S.selected.L, idx: [S.selected.idx], factor: Number(b.dataset.factor) }); })); document.querySelectorAll('#inspector [data-top]').forEach((b) => (b.onclick = () => { if (!S.selected) return; send({ cmd: 'neurons', layer: S.selected.L, top: Number(b.dataset.top), factor: Number(b.dataset.topfactor) }); })); $('btn-undo').onclick = () => send({ cmd: 'undo' }); $('btn-reset').onclick = () => { if (confirm('Riportare tutti i neuroni allo stato originale? Non si può annullare.')) send({ cmd: 'reset' }); }; $('btn-remap').onclick = () => { showBoot('Rimappatura del cervello in corso…'); send({ cmd: 'remap' }); }; // ---------------------------------------------------------------- attività per strato (EEG) const eeg = $('eeg'); function drawEEG() { const dpr = Math.min(devicePixelRatio, 2); const w = eeg.clientWidth, h = eeg.clientHeight; if (eeg.width !== w * dpr) { eeg.width = w * dpr; eeg.height = h * dpr; } const g = eeg.getContext('2d'); g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, w, h); const L = S.nLayer; if (!L) return; const bw = w / L; for (let l = 0; l < L; l++) { const v = S.eegMax[l] > 0 ? S.eeg[l] / S.eegMax[l] : 0; const bh = Math.max(1, v * (h - 12)); g.fillStyle = REGION_COLORS[(S.regionOfLayer[l] ?? 0) % REGION_COLORS.length]; g.globalAlpha = 0.25 + 0.75 * v; g.fillRect(l * bw + 1, h - 12 - bh, Math.max(1, bw - 2), bh); } g.globalAlpha = 1; g.fillStyle = '#7d8a9c'; g.font = '10px Consolas, monospace'; g.fillText('strato 0', 0, h - 1); g.textAlign = 'right'; g.fillText(`strato ${L - 1}`, w, h - 1); } // ---------------------------------------------------------------- frame di attività // header: u8 'A', u8 versione, u16 strati, u16 k, u16 0, u32 seq; per strato: f32 media, u16 idx[k], f32 val[k] function onFrame(buf) { const dv = new DataView(buf); if (dv.getUint8(0) === 80) return playVoice(buf); // 'P': la voce di Neuronal nella chiamata if (!S.basePos || dv.getUint8(1) !== 1) return; const kind = dv.getUint8(0); if (kind === 83) return onMessages(dv); // 'S' if (kind === 67) return onBlockFrame(dv); // 'C' if (kind === 68) return sentinelsView.onFrame(dv); // 'D' if (kind !== 65) return; // 'A' const L = dv.getUint16(2, true), k = dv.getUint16(4, true); const per = 4 + 6 * k; for (let l = 0; l < L; l++) { const o = 12 + l * per; const mean = dv.getFloat32(o, true); S.eeg[l] = S.eeg[l] * 0.5 + mean * 0.5; S.eegMax[l] = Math.max(S.eegMax[l] * 0.999, S.eeg[l]); const top = Math.abs(dv.getFloat32(o + 4 + 2 * k, true)) || 1; for (let t = 0; t < k; t++) { const idx = dv.getUint16(o + 4 + 2 * t, true); const v = Math.abs(dv.getFloat32(o + 4 + 2 * k + 4 * t, true)) / top; if (v > 0.3) light(l, idx, v); // solo i neuroni davvero dominanti nello strato } } } // Messaggi tra neuroni lungo sinapsi reali: u16 n, u32 seq; per messaggio u16 strato, u16 da, u16 a, i16 forza function onMessages(dv) { const n = dv.getUint16(2, true); for (let k = 0; k < n; k++) { const o = 8 + k * 8; const l = dv.getUint16(o, true), i = dv.getUint16(o + 2, true), j = dv.getUint16(o + 4, true); const f = dv.getInt16(o + 6, true) / 32767; if (l + 1 >= S.nLayer) continue; particles.spawn(posOf(l, i), posOf(l + 1, j), f >= 0 ? EXCITE : INHIBIT, Math.abs(f), 0.55); S.msgCount++; } } // Attivazione dei neuroni dei blocchi: u16 blocchi, u32 seq; per blocco u16 id, u16 n, f32 att[n] function onBlockFrame(dv) { const nb = dv.getUint16(2, true); let o = 8; for (let b = 0; b < nb; b++) { const id = dv.getUint16(o, true), n = dv.getUint16(o + 2, true); o += 4; const vals = new Float32Array(n); for (let k = 0; k < n; k++) vals[k] = dv.getFloat32(o + 4 * k, true); o += 4 * n; blocksView.setActivations(id, vals); } } // ---------------------------------------------------------------- blocchi $('new-block').onsubmit = (e) => { e.preventDefault(); const n = Number($('nb-n').value); if (!(n >= 1 && n <= 512)) return; send({ cmd: 'block_create', neurons: n, name: $('nb-name').value.trim() }); $('nb-name').value = ''; }; function openBlock(id) { S.focusBlock = id; showTab('blocks'); renderBlocks(); const c = blocksView.focus(id); if (c) controls.target.set(c[0], c[1] * 0.5, 0); document.querySelector(`.block[data-id="${id}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } const STATE_LABEL = { normale: '<span class="status">originale</span>', modificata: '<span class="status live">nuovo utilizzo</span>', eliminata: '<span class="status danger">eliminata · specializzazione spenta</span>', eliminata_tutta: '<span class="status danger">eliminata completamente</span>', }; const isUi = (kind, id, mode) => S.ui && S.ui.kind === kind && S.ui.id === id && (!mode || S.ui.mode === mode); const openUi = (kind, id, mode) => { S.ui = isUi(kind, id, mode) ? null : { kind, id, mode }; renderBlocks(); }; // Controlli comuni di un blocco applicato: acceso, intensità, prova di Neuronal, esempi. function blockControls(b) { return `<div class="block-stats">Si attiva nel ${Math.round(b.pos_rate * 100)}% degli esempi della funzione e nel ${Math.round(b.neg_rate * 100)}% dei testi neutri · ${fmt(b.neurons)} neuroni negli strati ${b.first}–${b.last}</div> <div class="row"><label><input type="checkbox" data-act="enabled" ${b.enabled ? 'checked' : ''}> acceso</label> <label>intensità <input type="range" min="0" max="3" step="0.1" value="${b.gain}" data-act="gain"> <output>×${b.gain.toFixed(1)}</output></label></div> <details><summary>Come lo usa Neuronal</summary><p>${esc(b.effect)}</p></details> <details><summary>Esempi elaborati da Neuronal (${b.examples.length})</summary><ul>${b.examples.map((x) => `<li>${esc(x)}</li>`).join('')}</ul></details> <div class="btn-row"><button class="ghost danger" data-act="infect" title="Esercitazione: il contagio passa alla rete lungo le sinapsi del blocco e la Rete della Diagnosi lo cura">☣ Infetta ${S.blockNeuron?.id === b.id ? `il neurone n. ${S.blockNeuron.k}` : 'un neurone'}</button></div>`; } function renameForm(name) { return `<div class="row"><input type="text" data-act="name" value="${esc(name)}" maxlength="63"> <button class="primary" data-act="save-name">Salva</button><button class="ghost" data-act="cancel">Annulla</button></div>`; } function examplesField() { return `<details><summary>Aggiungi esempi tuoi (facoltativo, uno per riga)</summary><textarea data-act="examples"></textarea></details>`; } const readExamples = (li) => (li.querySelector('[data-act="examples"]')?.value || '').split('\n').map((x) => x.trim()).filter(Boolean); function wireBlockControls(li, b) { li.querySelector('[data-act="enabled"]')?.addEventListener('change', (e) => send({ cmd: 'block_set', id: b.id, enabled: e.target.checked })); const g = li.querySelector('[data-act="gain"]'); if (g) { g.oninput = () => (g.nextElementSibling.textContent = '×' + Number(g.value).toFixed(1)); g.onchange = () => send({ cmd: 'block_set', id: b.id, gain: Number(g.value) }); } li.querySelector('[data-act="infect"]')?.addEventListener('click', () => { const k = S.blockNeuron?.id === b.id ? S.blockNeuron.k : Math.floor(Math.random() * b.neurons); send({ cmd: 'infect', block: b.id, k }); }); } const HEALTH = { ok: ['live', 'in salute'], controllo: ['busy', 'si sta controllando…'], riparato: ['live', 'riparato da solo'], problema: ['danger', 'problema non risolto'], riavvio: ['busy', 'si sta riavviando'], spento: ['', 'autodiagnosi spenta'], }; // "Sospeso da Neuronal" con la possibilità di riattivare comunque. function autoNote(reason, kind, id) { return `<div class="auto-note"><b>Neuronal:</b> ${esc(reason)} <button class="ghost" data-force="${kind}" data-id="${id}">Riattiva comunque</button></div>`; } function wireForce(el) { el.querySelectorAll('[data-force]').forEach((b) => (b.onclick = () => { if (confirm('Riattivare comunque? Neuronal aveva rilevato che gli impediva di funzionare bene. Rispetterà la tua scelta fino al prossimo riavvio.')) send({ cmd: 'doctor_force', kind: b.dataset.force, id: Number(b.dataset.id) }); })); } const ROLE_LABELS = [['analisi', 'analisi'], ['controllo', 'controllo'], ['sicurezza', 'sicurezza'], ['riparazione', 'riparazione'], ['coordinamento', 'nucleo']]; const when = (t) => (t ? new Date(t * 1000).toLocaleString('it-IT', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' }) : 'mai'); function renderDiagnosisCard() { const li = document.createElement('li'); li.className = 'block diag'; const d = S.doctor; if (!d) { li.textContent = 'Rete della Diagnosi: in attesa del motore…'; return li; } const [cls, label] = HEALTH[d.status] || ['', d.status]; const legend = ROLE_LABELS.map(([r, l]) => `<span><i class="dot" style="background:${ROLE_COLORS[r]}"></i>${l}</span>`).join(''); let html = `<div class="block-head"><span class="swatch diag-swatch"></span><span class="block-name">Rete della Diagnosi</span> <span class="block-n">${Math.max(0, d.groups.length - 1)} presidi + nucleo</span></div> <span class="status ${cls}">${label}</span> <div class="block-fn">Presidi di neuroni sentinella distribuiti dentro ogni macroarea e coordinati da un nucleo centrale. Ogni presidio analizza l'attività dei suoi strati, controlla che la sua area funzioni, verifica la sicurezza dei suoi pesi e ripara o ricostruisce quando serve.</div> <div class="legend role-legend">${legend}</div> <div class="row"><label><input type="checkbox" data-act="network" ${d.network_on ? 'checked' : ''}> rete accesa</label> ${d.last_check ? `<span>ultimo controllo ${when(d.last_check)}</span>` : ''}</div>`; if (d.network_on) { html += '<ul class="groups">'; for (const g of d.groups) { const st = !g.enabled ? '<span class="status">spento</span>' : g.alarm ? '<span class="status danger">allarme</span>' : g.repairing ? '<span class="status busy">in riparazione</span>' : '<span class="status live">di guardia</span>'; const area = g.region === 0 ? 'coordina tutti i presidi' : `strati ${g.first}–${g.last}${g.ratio >= 0 ? ` · risposta ${Math.round(g.ratio * 100)}%` : ''}`; html += `<li><div class="group-head"><label><input type="checkbox" data-group="${g.index}" ${g.enabled ? 'checked' : ''}></label> <b>${esc(g.name)}</b> ${st}<span class="block-n">${area}</span></div> <div class="group-report">${esc(g.report)}</div></li>`; } html += '</ul>'; html += `<div class="block-stats"><b>Sicurezza dei pesi:</b> ${esc(d.security || 'non ancora controllata')} ${d.security_t ? `(${when(d.security_t)})` : ''} ${d.security_running ? ' · controllo in corso…' : ''}</div> <div class="block-stats"><b>Punto di ripristino sano:</b> ${when(d.snapshot)}</div>`; } // tutto quello che la rete ha sospeso o attenuato const notes = []; if (d.interventions_suspended) notes.push(autoNote('ha sospeso i tuoi interventi manuali sui neuroni (non cancellati).', 'interventions', 0)); for (const r of S.regions) if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) notes.push(autoNote(r.auto_reason, 'region', r.id)); for (const b of S.blocks) if (b.auto_off || b.auto_gain > 0) notes.push(autoNote(b.auto_reason, 'block', b.id)); if (notes.length) html += `<div class="auto-list">${notes.join('')}</div>`; const journal = (d.journal || []).slice().reverse(); if (journal.length) { const line = (e) => `<li><time>${new Date(e.t * 1000).toLocaleTimeString('it-IT')}</time> ${esc(e.text)}</li>`; html += `<ul class="journal">${journal.slice(0, 5).map(line).join('')}</ul>`; if (journal.length > 5) html += `<details><summary>Diario completo (${journal.length})</summary><ul class="journal">${journal.slice(5).map(line).join('')}</ul></details>`; } if (d.network_on) html += `<div class="btn-row"> <button class="primary" data-act="check" ${d.status === 'controllo' ? 'disabled' : ''}>Diagnosi ora</button> <button data-act="security" ${d.security_running ? 'disabled' : ''}>Controllo di sicurezza dei pesi</button> <button class="ghost danger" data-act="rebuild" ${d.snapshot ? '' : 'disabled'}>Ricostruisci dall'ultimo punto sano</button></div>`; li.innerHTML = html; li.querySelector('[data-act="network"]').onchange = (e) => { if (!e.target.checked && !confirm('Spegnere la Rete della Diagnosi? Neuronal smetterà di controllarsi, proteggersi e ripararsi da solo.')) { e.target.checked = true; return; } send({ cmd: e.target.checked ? 'network_on' : 'network_off' }); }; li.querySelectorAll('[data-group]').forEach((el) => (el.onchange = () => send({ cmd: 'sentinel_set', index: Number(el.dataset.group), enabled: el.checked }))); li.querySelector('[data-act="check"]')?.addEventListener('click', () => send({ cmd: 'doctor' })); li.querySelector('[data-act="security"]')?.addEventListener('click', () => send({ cmd: 'security_check' })); li.querySelector('[data-act="rebuild"]')?.addEventListener('click', () => { if (confirm(`Ricostruire tutto com'era all'ultimo punto sano (${when(d.snapshot)})? Blocchi e macroaree torneranno a quello stato e il motore si riavvierà.`)) send({ cmd: 'reconstruct' }); }); wireForce(li); return li; } function renderRegionCard(r, i) { const li = document.createElement('li'); li.className = 'block' + (i === S.focusRegion ? ' focus' : ''); const blk = r.block ? S.blocks.find((b) => b.id === r.block) : null; const busyBlock = S.regionBusy.get(r.id); const busy = busyBlock !== undefined ? (S.blockProgress.get(busyBlock) || 'In coda: Neuronal inizierà appena libero…') : null; const renamed = r.name !== r.original_name; let html = `<div class="block-head"><span class="swatch" style="background:${REGION_COLORS[i % REGION_COLORS.length]}"></span> <span class="block-name">${esc(r.name)}</span><span class="block-n">strati ${r.first}–${r.last}</span></div> ${STATE_LABEL[r.state] || ''}${renamed ? `<div class="block-stats">nome originale: ${esc(r.original_name)}</div>` : ''} <div class="block-fn">${esc(r.function)}</div>`; if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) html += autoNote(r.auto_reason, 'region', r.id); if (r.state === 'modificata') { html += `<div class="block-stats">${r.replace ? 'Sostituisce' : 'Si aggiunge a'} la funzione originale: «${esc(r.original_function)}»</div>`; if (blk && blk.applied) html += blockControls(blk); } else { html += `<div class="block-stats">${fmt(r.selective)} neuroni specializzati</div>`; } if (busy) html += `<div class="progress">${esc(busy)}</div>`; else if (isUi('region', r.id, 'rename')) html += renameForm(r.name); else if (isUi('region', r.id, 'use')) { html += `<textarea data-act="function" placeholder="Nuovo utilizzo di quest'area, per esempio: pianificare viaggi">${r.state === 'modificata' ? esc(r.function) : ''}</textarea> <div class="row"><label>neuroni da costruire <input type="number" data-act="neurons" min="1" max="512" value="${blk ? blk.neurons : 64}"></label> <label><input type="checkbox" data-act="replace" ${r.state !== 'modificata' || r.replace ? 'checked' : ''}> sostituisce la funzione originale</label></div> <div class="block-stats">Se sostituisce, i ${fmt(r.selective)} neuroni specializzati dell'area vengono attenuati al 30%; altrimenti la nuova funzione si aggiunge.</div> ${examplesField()} <div class="btn-row"><button class="primary" data-act="apply">Applica il nuovo utilizzo</button><button class="ghost" data-act="cancel">Annulla</button></div>`; } else if (isUi('region', r.id, 'delete')) { html += `<div class="warn">Eliminare «${esc(r.name)}»? <p><b>Solo la specializzazione</b>: si spengono i suoi ${fmt(r.selective)} neuroni specializzati. Neuronal continua a funzionare ma perde questa capacità.</p> <p><b>Completamente</b>: si spengono tutti i ${fmt((r.last - r.first + 1) * S.nFF)} neuroni dell'area. Nelle prove Neuronal ha cominciato a sbagliare o è rimasto muto. Puoi sempre ripristinarla.</p></div> <div class="btn-row"><button class="danger" data-act="del-spec">Elimina la specializzazione</button> <button class="danger" data-act="del-all">Elimina completamente</button><button class="ghost" data-act="cancel">Annulla</button></div>`; } else { html += '<div class="btn-row">'; html += '<button data-act="use">Cambia utilizzo</button><button class="ghost" data-act="rename">Rinomina</button>'; html += '<button class="ghost" data-act="show">Mostra nel cervello</button>'; if (!r.state.startsWith('eliminata')) html += '<button class="ghost danger" data-act="delete">Elimina</button>'; if (r.state !== 'normale' || renamed) html += '<button class="ghost" data-act="restore">Ripristina l\'originale</button>'; html += '</div>'; } li.innerHTML = html; if (blk) wireBlockControls(li, blk); wireForce(li); const on = (act, fn) => li.querySelector(`[data-act="${act}"]`)?.addEventListener('click', fn); on('rename', () => openUi('region', r.id, 'rename')); on('use', () => openUi('region', r.id, 'use')); on('delete', () => openUi('region', r.id, 'delete')); on('cancel', () => { S.ui = null; renderBlocks(); }); on('show', () => { showTab('atlas'); focusRegion(i); }); on('save-name', () => { const name = li.querySelector('[data-act="name"]').value.trim(); if (name) send({ cmd: 'region_rename', id: r.id, name }); S.ui = null; }); on('apply', () => { const fn = li.querySelector('[data-act="function"]').value.trim(); if (fn.length < 3) { li.querySelector('[data-act="function"]').focus(); return; } send({ cmd: 'region_apply', id: r.id, function: fn, examples: readExamples(li), neurons: Number(li.querySelector('[data-act="neurons"]').value) || 64, replace: li.querySelector('[data-act="replace"]').checked }); S.ui = null; S.regionBusy.set(r.id, 0); renderBlocks(); }); on('del-spec', () => { send({ cmd: 'region_delete', id: r.id, total: false }); S.ui = null; }); on('del-all', () => { send({ cmd: 'region_delete', id: r.id, total: true }); S.ui = null; }); on('restore', () => { if (!confirm(`Riportare «${r.name}» allo stato originale misurato?`)) return; send({ cmd: 'region_restore', id: r.id }); if (renamed) send({ cmd: 'region_rename', id: r.id, name: r.original_name }); }); return li; } function renderBlockCard(b, order) { const li = document.createElement('li'); li.className = 'block' + (b.id === S.focusBlock ? ' focus' : ''); li.dataset.id = b.id; const busy = S.blockProgress.get(b.id); const editing = !b.applied || isUi('block', b.id, 'function'); const status = busy ? '<span class="status busy">in elaborazione</span>' : !b.applied ? '<span class="status">in attesa di una funzione</span>' : b.enabled ? `<span class="status live">attivo · strati ${b.first}–${b.last}</span>` : '<span class="status">spento</span>'; let html = `<div class="block-head"><span class="swatch" style="background:${BLOCK_COLORS[order % BLOCK_COLORS.length]}"></span> <span class="block-name">${esc(b.name)}</span><span class="block-n">${fmt(b.neurons)} neuroni</span></div>${status}`; if (b.applied) html += `<div class="block-fn">${esc(b.function)}</div>` + blockControls(b); if (b.auto_off || b.auto_gain > 0) html += autoNote(b.auto_reason, 'block', b.id); if (busy) html += `<div class="progress">${esc(busy)}</div>`; else if (isUi('block', b.id, 'rename')) html += renameForm(b.name); else if (editing) { html += `<textarea data-act="function" placeholder="Che funzione deve avere? Per esempio: capire e comporre musica">${b.applied ? esc(b.function) : ''}</textarea> <div class="row"><label>neuroni <input type="number" data-act="neurons" min="1" max="512" value="${b.neurons}"></label></div> ${examplesField()} <div class="btn-row"><button class="primary" data-act="apply">Applica la funzione</button> ${b.applied ? '<button class="ghost" data-act="cancel">Annulla</button>' : ''} <button class="ghost" data-act="rename">Rinomina</button><button class="ghost danger" data-act="delete">Elimina</button></div>`; } else { html += `<div class="btn-row"><button data-act="edit">Modifica funzione o neuroni</button><button class="ghost" data-act="rename">Rinomina</button> <button class="ghost" data-act="show">Mostra nel cervello</button><button class="ghost danger" data-act="delete">Elimina</button></div>`; } li.innerHTML = html; if (b.applied) wireBlockControls(li, b); wireForce(li); const on = (act, fn) => li.querySelector(`[data-act="${act}"]`)?.addEventListener('click', fn); on('edit', () => openUi('block', b.id, 'function')); on('rename', () => openUi('block', b.id, 'rename')); on('cancel', () => { S.ui = null; renderBlocks(); }); on('show', () => openBlock(b.id)); on('save-name', () => { const name = li.querySelector('[data-act="name"]').value.trim(); if (name) send({ cmd: 'block_rename', id: b.id, name }); S.ui = null; }); on('apply', () => { const fnEl = li.querySelector('[data-act="function"]'); const fn = fnEl.value.trim(); if (fn.length < 3) { fnEl.focus(); return; } S.ui = null; S.blockProgress.set(b.id, 'Invio a Neuronal…'); send({ cmd: 'block_apply', id: b.id, function: fn, examples: readExamples(li), neurons: Number(li.querySelector('[data-act="neurons"]').value) || b.neurons }); renderBlocks(); }); on('delete', () => { if (confirm(`Eliminare il blocco «${b.name}» e i suoi ${b.neurons} neuroni?`)) send({ cmd: 'block_delete', id: b.id }); }); return li; } function renderBlocks() { const panel = $('panel-blocks'); const active = document.activeElement; if (panel.contains(active) && (active.tagName === 'TEXTAREA' || (active.tagName === 'INPUT' && active.type === 'text'))) return; // non interrompere chi scrive const regionsList = $('regions-edit'), list = $('blocks'); $('diagnosis').replaceChildren(renderDiagnosisCard()); regionsList.replaceChildren(...S.regions.map((r, i) => renderRegionCard(r, i))); const created = S.blocks.map((b, order) => [b, order]).filter(([b]) => !b.region); if (!created.length) { const li = document.createElement('li'); li.className = 'hint'; li.textContent = 'Nessun blocco creato. Scegli quanti neuroni vuoi e premi «Crea blocco».'; list.replaceChildren(li); } else { list.replaceChildren(...created.map(([b, order]) => renderBlockCard(b, order))); } } // ---------------------------------------------------------------- mappa function applyAtlas(atlas) { S.atlas = atlas; S.regionOfLayer = []; if (atlas) atlas.regions.forEach((r, i) => { for (let l = r.first; l <= r.last; l++) S.regionOfLayer[l] = i; }); if (S.nLayer) buildBrain(); renderAtlasPanel(); } function renderAtlasPanel() { const a = S.atlas; const list = $('regions'), nets = $('networks'); list.replaceChildren(); nets.replaceChildren(); if (!a) { $('atlas-intro').textContent = 'Mappa non ancora disponibile.'; return; } const selective = a.regions.reduce((s, r) => s + r.selective, 0); $('atlas-intro').textContent = `Misurata all'avvio: ${a.regions.length} macroaree su ${a.layers} strati. ` + `${fmt(selective)} neuroni su ${fmt(a.layers * a.neurons_per_layer)} sono specializzati. ` + `Nomi e funzioni li ha scelti il modello stesso guardando i dati.`; a.regions.forEach((r, i) => { const li = document.createElement('li'); li.className = 'region' + (i === S.focusRegion ? ' focus' : ''); li.tabIndex = 0; const chips = r.specialization.map((s) => `<span class="chip">${esc(s.category)} ×${s.enrichment.toFixed(1)}</span>`).join('') || '<span class="chip">nessuna specializzazione netta</span>'; const cur = S.regions[i]; const shownName = cur ? cur.name : r.name, shownFn = cur ? cur.function : r.function; const chip = cur && cur.state !== 'normale' ? STATE_LABEL[cur.state] : ''; li.innerHTML = `<div class="region-head"><span class="swatch" style="background:${REGION_COLORS[i % REGION_COLORS.length]}"></span> <span class="region-name">${esc(shownName)}</span><span class="region-layers">strati ${r.first}–${r.last}</span></div> ${chip}<div class="region-fn">${esc(shownFn)}</div><div class="chips">${chips}</div>`; const go = () => focusRegion(i === S.focusRegion ? -1 : i); li.onclick = go; li.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }; list.append(li); }); for (const n of a.networks) { const max = Math.max(1, ...n.per_layer); const li = document.createElement('li'); li.className = 'net-row'; li.title = `picco allo strato ${n.peak_layer}, estensione ${n.span[0]}–${n.span[1]}`; li.innerHTML = `<span>${esc(n.category)}</span><span class="net-bar">${n.per_layer.map((v) => `<i style="height:${Math.round((v / max) * 100)}%"></i>`).join('')}</span><span class="net-n">${fmt(n.selective)}</span>`; nets.append(li); } } function focusRegion(i) { S.focusRegion = i; buildBrain(); renderAtlasPanel(); if (i >= 0) { const r = S.atlas.regions[i]; const mid = Math.floor((r.first + r.last) / 2) * S.nFF * 3; controls.target.set(S.basePos[mid], 0, 0); } else { controls.target.set(0, 0, 0); } } // ---------------------------------------------------------------- schede const tabs = [...document.querySelectorAll('.tab')]; function showTab(name) { for (const t of tabs) { const on = t.dataset.tab === name; t.classList.toggle('active', on); t.setAttribute('aria-selected', on); $('panel-' + t.dataset.tab).hidden = !on; } if (name === 'procs') { renderLog(true); send({ cmd: 'logs' }); } } tabs.forEach((t) => (t.onclick = () => showTab(t.dataset.tab))); if (location.hash === '#mappa') showTab('atlas'); if (location.hash === '#blocchi') showTab('blocks'); if (location.hash === '#permessi') showTab('perms'); if (location.hash === '#memoria') showTab('memory'); // ---------------------------------------------------------------- memoria $('mem-form').onsubmit = (e) => { e.preventDefault(); const text = $('mem-text').value.trim(); if (!text) return; send({ cmd: 'memory_add', title: $('mem-title').value.trim(), text }); $('mem-text').value = ''; $('mem-title').value = ''; }; $('mem-test-form').onsubmit = (e) => { e.preventDefault(); const text = $('mem-test').value.trim(); if (text) { $('mem-test-out').textContent = 'Il navigatore cerca…'; send({ cmd: 'memory_test', text }); } }; function renderMemory() { const m = S.memory; if (!m) return; const usedBytes = m.used * (m.slot_bits / 8); $('mem-intro').innerHTML = `Ogni neurone ha un indirizzo. I neuroni sono divisi in <b>${fmt(m.groups)} gruppi da ${m.group_neurons}</b>, ognuno con <b>${m.slot_bits} bit</b> sul disco (un file per strato): in tutto <b>${fmt(m.capacity_bytes)} byte</b>. Occupati ${fmt(m.used)} gruppi (${fmt(usedBytes)} byte). Quando fai una domanda, il navigatore trova i gruppi che custodiscono il ricordo giusto e lo ricompone.`; const list = $('memories'); list.replaceChildren(); if (!m.memories.length) { const li = document.createElement('li'); li.className = 'hint'; li.textContent = 'Nessun ricordo ancora.'; list.append(li); return; } for (const mem of m.memories.slice().sort((a, b) => b.t - a.t)) { const per = m.per_layer; const files = [...new Set(mem.groups.map((g) => `strato_${String(Math.floor(g / per)).padStart(2, '0')}.bin`))]; const li = document.createElement('li'); li.className = 'block' + (mem.id === S.memFocus ? ' focus' : ''); li.innerHTML = `<div class="block-head"><span class="swatch" style="background:#ffd166"></span><span class="block-name">${esc(mem.title)}</span> <span class="block-n">${mem.bytes} byte · ${mem.groups.length} gruppi</span></div> ${mem.intact ? '' : '<span class="status danger">bit danneggiati</span>'} <div class="block-fn">${esc(mem.text)}</div> <div class="mem-where">gruppi ${mem.groups.map((g) => fmt(g)).join(', ')} · file ${files.join(', ')}</div> <div class="btn-row"><button class="ghost" data-act="show">${mem.id === S.memFocus ? 'Nascondi nel cervello' : 'Mostra nel cervello'}</button> <button class="ghost danger" data-act="delete">Dimentica</button></div>`; li.querySelector('[data-act="show"]').onclick = () => { if (S.memFocus === mem.id) { S.memFocus = -1; memGlowPersist = false; memGlowUntil = performance.now(); } else { S.memFocus = mem.id; showMemoryGroups(mem.groups, true); } renderMemory(); }; li.querySelector('[data-act="delete"]').onclick = () => { if (confirm(`Far dimenticare a Neuronal «${mem.title}»? I suoi ${mem.groups.length} gruppi tornano liberi.`)) send({ cmd: 'memory_delete', id: mem.id }); }; list.append(li); } } $('st-health').onclick = () => showTab('blocks'); const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]); // ---------------------------------------------------------------- chat condivisa const input = $('input'), sendBtn = $('send'), messages = $('messages'); const aiMsgs = new Map(); // richiesta -> messaggio di Neuronal in costruzione const pending = new Set(); // richieste non ancora concluse (da qualsiasi dispositivo) function addMsg(cls, text) { $('empty')?.remove(); const d = document.createElement('div'); d.className = 'msg ' + cls; if (cls === 'doctor-msg') d.onclick = () => { showTab('blocks'); }; d.textContent = text; messages.append(d); messages.scrollTop = messages.scrollHeight; return d; } function userMsg(device, voice, text) { const d = addMsg('user', ''); d.innerHTML = `<div class="from">${esc(device || '')}${voice ? ' · 🎙 a voce' : ''}</div>`; d.append(document.createTextNode(text)); messages.scrollTop = messages.scrollHeight; } function startAiMsg(voice) { $('empty')?.remove(); const d = document.createElement('div'); d.className = 'msg ai'; d.innerHTML = `<div class="who">NEURONAL${voice ? ' · 🔊' : ''}</div><details class="thought" hidden><summary>Ragionamento</summary><div></div></details><div class="body caret"></div><div class="meta"></div>`; messages.append(d); return { el: d, body: d.querySelector('.body'), thought: d.querySelector('.thought'), thoughtText: d.querySelector('.thought div'), words: 0, tok: 0, t0: performance.now() }; } const aiFor = (ev) => { let m = aiMsgs.get(ev.req); if (!m) { m = startAiMsg(ev.voice); aiMsgs.set(ev.req, m); } return m; }; function setGenerating(on) { S.generating = on; sendBtn.textContent = on ? 'Ferma' : 'Invia'; sendBtn.classList.toggle('primary', !on); } $('composer').onsubmit = (e) => { e.preventDefault(); if (S.generating && !input.value.trim()) { send({ cmd: 'stop' }); return; } const waiting = S.files.some((f) => f.state === 'lettura'); if (waiting) { addMsg('error', 'Aspetta: sto ancora leggendo gli allegati.'); return; } const ready = S.files.filter((f) => f.state === 'pronto'); const text = input.value.trim() || (ready.length ? 'Guarda gli allegati.' : ''); if (!text || !S.ws || S.ws.readyState !== 1) return; input.value = ''; autoGrow(); const image = !!S.attach; if (image) { sendImage(S.attach, 0); S.sentThumb = S.attach.thumb; clearAttach(); } S.files = S.files.filter((f) => f.state === 'lettura'); renderFiles(); send({ cmd: 'chat', text, thinking: $('think-on').checked, think_budget: Number($('think-budget').value), tools: $('tools-on').checked, web: $('web-on').checked, mode: $('mode').value, image }); }; input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('composer').requestSubmit(); } }); const autoGrow = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 160) + 'px'; }; input.addEventListener('input', autoGrow); const syncBudget = () => { $('budget-out').textContent = $('think-budget').value; $('budget-wrap').classList.toggle('off', !$('think-on').checked); }; $('think-budget').oninput = syncBudget; $('think-on').onchange = syncBudget; syncBudget(); $('btn-clear').onclick = () => { if (confirm('Iniziare una nuova conversazione per tutti i dispositivi collegati?')) send({ cmd: 'clear' }); }; function onToken(ev) { const m = aiFor(ev); m.tok++; const stick = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 40; if (ev.thought) { m.thought.hidden = false; m.thoughtText.textContent += ev.text; m.words = m.thoughtText.textContent.split(/\s+/).length; m.thought.querySelector('summary').textContent = `Ragionamento (${m.words} parole)`; } else { appendText(m, ev.text); } const secs = (performance.now() - m.t0) / 1000; if (secs > 0.3) $('st-speed').textContent = (m.tok / secs).toFixed(1); if (stick) messages.scrollTop = messages.scrollHeight; } // Il testo va in coda al corpo del messaggio, dopo le eventuali schede degli strumenti. function appendText(m, text) { let t = m.body.lastChild; if (!t || t.nodeType !== Node.TEXT_NODE) { if (t && !text.trim()) return; // niente a capo vuoti subito dopo una scheda t = m.body.appendChild(document.createTextNode(t ? text.replace(/^\s+/, '') : text)); return; } t.data += text; } // ---------------------------------------------------------------- strumenti di programmazione const TOOL_LABEL = { list_files: ['📁', 'Guarda i file'], read_file: ['📄', 'Legge'], write_file: ['✎', 'Scrive'], edit_file: ['✎', 'Modifica'], search_files: ['🔍', 'Cerca'], run_command: ['▶', 'Esegue'] }; function onTool(ev) { const m = aiFor(ev); let args = {}; try { args = JSON.parse(ev.args); } catch { /* argomenti non leggibili: il motore ha già risposto con l'errore */ } const [icon, label] = TOOL_LABEL[ev.name] || ['⚙', ev.name]; const target = args.path ?? args.command ?? args.pattern ?? ''; let card = m.body.querySelector(`.tool[data-step="${ev.step}"][data-name="${ev.name}"]:not(.done)`); if (!card) { card = document.createElement('details'); card.className = 'tool running'; card.dataset.step = ev.step; card.dataset.name = ev.name; card.innerHTML = `<summary><span class="tool-icon"></span><span class="tool-label"></span><code></code><span class="tool-state">…</span></summary>`; card.querySelector('.tool-icon').textContent = icon; card.querySelector('.tool-label').textContent = label; card.querySelector('code').textContent = target || (ev.name === 'list_files' ? 'lavori' : ''); if (ev.name === 'write_file' && args.content != null) addPre(card, args.content, 'tool-code'); if (ev.name === 'edit_file' && args.new_text != null) addPre(card, args.new_text, 'tool-code'); m.body.append(card); } if (ev.phase === 'end') { card.classList.remove('running'); card.classList.add('done', ev.ok ? 'ok' : 'fail'); card.querySelector('.tool-state').textContent = ev.ok ? '✓' : '✗'; addPre(card, ev.result || '', 'tool-out'); if (!ev.ok && ev.name === 'run_command') card.open = true; // gli errori si vedono subito } if (messages.scrollHeight - messages.scrollTop - messages.clientHeight < 160) messages.scrollTop = messages.scrollHeight; } function addPre(card, text, cls) { const pre = document.createElement('pre'); pre.className = cls; pre.textContent = text; card.append(pre); } function onDone(ev) { const m = aiFor(ev); m.body.classList.remove('caret'); if (!m.body.childNodes.length || !m.body.textContent.trim()) m.body.textContent = ev.answer || '(nessuna risposta)'; m.el.querySelector('.meta').textContent = `${ev.tokens} token · ${ev.seconds.toFixed(1)} s`; aiMsgs.delete(ev.req); pending.delete(ev.req); setGenerating(pending.size > 0); } function showHistory(ev) { messages.replaceChildren(); aiMsgs.clear(); for (const m of ev.messages) { if (m.role === 'user') userMsg(m.device, m.voice, m.text); else { const a = startAiMsg(m.voice); a.body.classList.remove('caret'); a.body.textContent = m.text; } } if (!ev.messages.length) { const e = document.createElement('div'); e.className = 'empty'; e.id = 'empty'; e.textContent = 'Parla con Neuronal da qui, da un altro dispositivo o con una chiamata: la conversazione è una sola.'; messages.append(e); } } // ---------------------------------------------------------------- chiamata vocale // Microfono -> 16 kHz mono, a pacchetti da 20 ms (320 campioni), con il livello per l'indicatore. const MIC_WORKLET = ` class Mic16k extends AudioWorkletProcessor { constructor() { super(); this.step = sampleRate / 16000; this.t = 0; this.prev = 0; this.out = new Int16Array(320); this.n = 0; this.e = 0; } process(inputs) { const ch = inputs[0] && inputs[0][0]; if (!ch) return true; let t = this.t; while (t < ch.length) { const i = Math.floor(t), f = t - i; const a = i === 0 ? this.prev : ch[i - 1], b = ch[i]; const v = Math.max(-1, Math.min(1, a + (b - a) * f)); this.out[this.n++] = v * 32767; this.e += v * v; if (this.n === 320) { this.port.postMessage({ pcm: this.out.buffer.slice(0), level: Math.sqrt(this.e / 320) }); this.n = 0; this.e = 0; } t += this.step; } this.t = t - ch.length; this.prev = ch[ch.length - 1]; return true; } } registerProcessor('mic-16k', Mic16k);`; const CALL_LABEL = { 'in ascolto': 'Ti ascolto…', 'ti ascolto': 'Stai parlando…', trascrivo: 'Ho sentito, trascrivo…', penso: 'Sto pensando…', parlo: 'Sto parlando' }; async function startCall() { if (S.call) return; if (!navigator.mediaDevices?.getUserMedia) { const url = S.tlsPort ? `https://${location.hostname}:${S.tlsPort}/` : ''; addMsg('error', location.protocol === 'https:' ? 'Questo browser non consente il microfono.' : `Il microfono funziona solo sulla pagina sicura. Apri ${url || "l'indirizzo https del PC"} (dal PC: pulsante «Telefono»).`); return; } try { // Tutto ciò che sblocca l'audio va fatto subito, dentro il tocco sul pulsante (prima di qualsiasi attesa). // La voce passa da un lettore <audio>: su iPhone l'audio "Web Audio" puro viene zittito dall'interruttore // del silenzioso e interrotto quando si accende il microfono. if (navigator.audioSession) { try { navigator.audioSession.type = 'play-and-record'; } catch { /* non supportato */ } } const ctx = new AudioContext(); const dest = ctx.createMediaStreamDestination(); const out = ctx.createGain(); out.gain.value = S.voiceMuted ? 0 : 1; out.connect(dest); const player = $('voice-out'); player.srcObject = dest.stream; player.play().catch(() => {}); ctx.resume(); const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true } }); if (ctx.state !== 'running') await ctx.resume(); // iPhone: il microfono può sospendere l'audio della pagina player.play().catch(() => {}); ctx.onstatechange = () => { if (ctx.state !== 'running' && S.call) ctx.resume().catch(() => {}); }; await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([MIC_WORKLET], { type: 'application/javascript' }))); const src = ctx.createMediaStreamSource(stream); const node = new AudioWorkletNode(ctx, 'mic-16k'); const mute = ctx.createGain(); mute.gain.value = 0; // il nodo deve essere collegato per lavorare, ma senza suonare src.connect(node).connect(mute).connect(ctx.destination); S.call = { ctx, stream, node, out, player, muted: false, next: 0, sources: [], received: 0 }; updateCallButtons(); node.port.onmessage = (e) => { if (!S.call) return; $('call-level').style.width = Math.min(100, e.data.level * 400) + '%'; if (S.call.muted || !S.ws || S.ws.readyState !== 1) return; const out = new Uint8Array(8 + e.data.pcm.byteLength); out.set([77, 1, 0, 0, 0, 0, 0, 0]); // 'M', versione 1 out.set(new Uint8Array(e.data.pcm), 8); S.ws.send(out.buffer); }; send({ cmd: 'call_start', voice: $('call-voice').value }); $('call-bar').hidden = false; $('btn-call').classList.add('in-call'); $('call-state').textContent = 'Chiamata in corso…'; } catch (err) { addMsg('error', 'Microfono non disponibile: ' + (err.message || err)); endCall(false); } } function endCall(notify = true) { if (notify) send({ cmd: 'call_end' }); if (S.call) { stopVoice(); S.call.stream?.getTracks().forEach((t) => t.stop()); if (S.call.player) { S.call.player.pause(); S.call.player.srcObject = null; } S.call.ctx?.close(); } stopCamera(); S.call = null; $('call-bar').hidden = true; $('btn-call').classList.remove('in-call'); } // La voce di Neuronal: 'P' u8 1, u16 frequenza, u32 chiamata, PCM int16 mono. I pezzi suonano uno dopo l'altro. function playVoice(buf) { const c = S.call; if (!c) return; const rate = new DataView(buf).getUint16(2, true); const pcm = new Int16Array(buf, 8, (buf.byteLength - 8) >> 1); const ab = c.ctx.createBuffer(1, pcm.length, rate); const ch = ab.getChannelData(0); for (let i = 0; i < pcm.length; i++) ch[i] = pcm[i] / 32768; const src = c.ctx.createBufferSource(); src.buffer = ab; src.connect(c.out); // -> volume (muto voce) -> lettore <audio> if (c.ctx.state !== 'running') c.ctx.resume().catch(() => {}); if (c.player.paused) c.player.play().catch(() => {}); c.received += ab.duration; $('call-recv').textContent = `voce ricevuta ${c.received.toFixed(1)} s`; const at = Math.max(c.ctx.currentTime + 0.05, c.next); src.start(at); c.next = at + ab.duration; c.sources.push(src); src.onended = () => { c.sources = c.sources.filter((x) => x !== src); }; } function stopVoice() { const c = S.call; if (!c) return; for (const s of c.sources) { try { s.stop(); } catch { /* già finita */ } } c.sources = []; c.next = 0; } $('btn-call').onclick = () => (S.call ? endCall() : startCall()); $('call-hang').onclick = () => endCall(); // Due interruttori separati: il tuo microfono e la voce di Neuronal (ricordata dal dispositivo). function updateCallButtons() { $('call-mute').textContent = S.call?.muted ? '🎙 Muto attivo' : '🎙 Muto'; $('call-mute').classList.toggle('active', !!S.call?.muted); $('call-speaker').textContent = S.voiceMuted ? '🔇 Audio spento' : '🔊 Audio'; $('call-speaker').classList.toggle('active', S.voiceMuted); } $('call-mute').onclick = () => { if (!S.call) return; S.call.muted = !S.call.muted; updateCallButtons(); }; $('call-speaker').onclick = () => { S.voiceMuted = !S.voiceMuted; store.set('neuronal_voice_muted', S.voiceMuted ? '1' : '0'); if (S.call) { S.call.out.gain.value = S.voiceMuted ? 0 : 1; if (!S.voiceMuted) S.call.player.play().catch(() => {}); } updateCallButtons(); }; // ---------------------------------------------------------------- collegare il telefono const IS_LOCAL = ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname); const DEVICE = IS_LOCAL ? 'PC' : /iPhone|Android.+Mobile|Mobi/i.test(navigator.userAgent) ? 'Telefono' : /iPad|Android|Tablet/i.test(navigator.userAgent) ? 'Tablet' : 'Computer'; const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* memoria del browser non disponibile */ } } }; let PIN = null; S.voiceMuted = store.get('neuronal_voice_muted') === '1'; $('call-voice').value = ['riccardo', 'paola', 'serena'].includes(store.get('neuronal_voice')) ? store.get('neuronal_voice') : 'riccardo'; $('call-voice').onchange = () => { store.set('neuronal_voice', $('call-voice').value); if (S.call) { stopVoice(); send({ cmd: 'call_voice', voice: $('call-voice').value }); } }; // Sessione di questa scheda (versione usa e getta): resta alla ricarica, sparisce quando chiudi la scheda. // Il QR del telefono la porta con sé (#s=...) così il telefono entra nella stessa sessione. const SESSION = (() => { let t = location.hash.match(/[#&]s=([a-z0-9]{8,32})/i)?.[1]; try { t = t || sessionStorage.getItem('neuronal_session'); } catch { /* niente sessionStorage */ } if (!t) t = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join(''); try { sessionStorage.setItem('neuronal_session', t); } catch { /* niente sessionStorage */ } return t; })(); { const m = location.hash.match(/pin=(\d{6})/); if (m) { PIN = m[1]; store.set('neuronal_pin', PIN); } else PIN = store.get('neuronal_pin'); if (/pin=|[#&]s=/.test(location.hash)) history.replaceState(null, '', location.pathname); } $('pin-form').onsubmit = (e) => { e.preventDefault(); const v = $('pin-input').value.replace(/\D/g, ''); if (v.length !== 6) { $('pin-err').textContent = 'Il PIN ha 6 cifre.'; return; } PIN = v; store.set('neuronal_pin', PIN); $('pin-overlay').hidden = true; connect(); }; function showPhonePanel() { const h = S.hello; if (h?.hosted) { // container: lo stesso indirizzo, e la stessa sessione const url = `${location.origin}/#s=${SESSION}${h.pin ? `&pin=${h.pin}` : ''}`; const q = qrcode(0, 'M'); q.addData(url); q.make(); $('qr').innerHTML = q.createSvgTag(5, 2); $('phone-url').textContent = location.origin; $('phone-pin').textContent = h.pin || '(non serve)'; $('phone-host-li').hidden = true; $('phone-overlay').hidden = false; return; } if (!h || !h.pin) return; const ip = (h.lan || [])[0]; if (!ip) { $('phone-url').textContent = 'Nessuna rete Wi-Fi trovata sul PC.'; $('phone-overlay').hidden = false; return; } const url = h.tls_port ? `https://${ip}:${h.tls_port}/#pin=${h.pin}` : `http://${ip}:8765/#pin=${h.pin}`; const q = qrcode(0, 'M'); q.addData(url); q.make(); $('qr').innerHTML = q.createSvgTag(6, 2); $('phone-url').textContent = url.replace(/#pin=\d+/, ''); $('phone-host-li').hidden = !(h.host && h.tls_port); if (h.host) $('phone-host').textContent = `https://${h.host}:${h.tls_port}/#pin=${h.pin}`; $('phone-pin').textContent = h.pin; $('phone-overlay').hidden = false; } $('btn-phone').onclick = showPhonePanel; $('phone-close').onclick = () => ($('phone-overlay').hidden = true); // ---------------------------------------------------------------- connessione function showBoot(text) { $('boot').hidden = false; $('boot-text').textContent = text; } function hideBoot() { $('boot').hidden = true; } function send(obj) { if (S.ws && S.ws.readyState === 1) S.ws.send(JSON.stringify(obj)); } function connect() { if (S.ended) return; const proto = location.protocol === 'https:' ? 'wss' : 'ws'; const q = `device=${encodeURIComponent(DEVICE)}&session=${SESSION}${!IS_LOCAL && PIN ? `&pin=${PIN}` : ''}`; const ws = new WebSocket(`${proto}://${location.host}/ws?${q}`); ws.binaryType = 'arraybuffer'; S.ws = ws; let opened = false; ws.onopen = () => { opened = true; $('st-conn').textContent = 'connesso'; $('st-conn').className = 'pill pill-on'; hfSend(); }; ws.onclose = () => { $('st-conn').textContent = 'non connesso'; $('st-conn').className = 'pill pill-off'; if (S.call) endCall(false); pending.clear(); setGenerating(false); if (S.ended) return; if (!opened && !IS_LOCAL) { // rifiutato o motore spento? Se la pagina risponde, il problema è il PIN fetch('/health', { cache: 'no-store' }).then((r) => r.ok).catch(() => false).then((up) => { if (!up) { showBoot('Preparo il cervello… riprovo tra poco.'); setTimeout(connect, 3000); return; } $('pin-err').textContent = PIN ? 'Il PIN non è stato accettato (o ci sono stati troppi tentativi: riprova tra qualche minuto).' : ''; $('pin-overlay').hidden = false; }); return; } showBoot('Motore non raggiungibile. Riprovo…'); setTimeout(connect, 2000); }; ws.onmessage = (e) => { if (typeof e.data !== 'string') { onFrame(e.data); return; } const ev = JSON.parse(e.data); switch (ev.ev) { case 'hello': S.hello = ev; hfSend(); $('tab-perms').hidden = !!ev.remote || !!ev.hosted; // i permessi si gestiscono solo dal PC $('queue-overlay').hidden = !ev.queued; if (ev.ephemeral && !ev.queued && !S.ephemeralShown) { S.ephemeralShown = true; $('ephemeral-note').hidden = false; } S.tlsPort = ev.tls_port; $('btn-phone').hidden = !(ev.pin || ev.hosted); if (S.nLayer !== ev.layers || S.nFF !== ev.neurons_per_layer) { S.nLayer = ev.layers; S.nFF = ev.neurons_per_layer; S.eeg = new Float32Array(S.nLayer); S.eegMax = new Float32Array(S.nLayer); showBoot('Costruzione del cervello…'); } break; case 'history': showHistory(ev); if (ev.generating) { pending.add(ev.generating); setGenerating(true); } break; case 'user_msg': userMsg(ev.device, ev.voice, ev.text); if (ev.image) showUserImage(ev); pending.add(ev.req); setGenerating(true); break; case 'atlas': applyAtlas(ev.atlas); hideBoot(); break; case 'interventions': S.factors = new Map(ev.neurons.map(([l, j, f]) => [l * S.nFF + j, f])); $('st-mod').textContent = fmt(ev.total); renderMarks(); refreshInspector(); break; case 'blocks': S.blocks = ev.blocks; blocksView.sync(S.blocks, !!S.basePos); renderBlocks(); break; case 'block_progress': S.blockProgress.set(ev.id, ev.message); renderBlocks(); break; case 'region_progress': S.regionBusy.set(ev.id, ev.block); renderBlocks(); break; case 'regions': { const before = S.regions.map((r) => r.state).join(); S.regions = ev.regions; for (const r of S.regions) if (S.regionBusy.get(r.id) && !S.blockProgress.has(S.regionBusy.get(r.id))) S.regionBusy.delete(r.id); if (before !== S.regions.map((r) => r.state).join() && S.basePos) buildBrain(); renderBlocks(); renderAtlasPanel(); break; } case 'block_done': S.blockProgress.delete(ev.id); for (const [rid, bid] of S.regionBusy) if (bid === ev.id) S.regionBusy.delete(rid); if (!ev.ok) addMsg('error', `Blocco ${ev.id}: ${ev.error}`); renderBlocks(); break; case 'synapses': onSynapses(ev); break; case 'infection': onInfection(ev); break; case 'memory': S.memory = ev.store; renderMemory(); break; case 'memory_recall': { const groups = ev.items.flatMap((i) => i.groups); showMemoryGroups(groups, false); addMsg('memory-msg', 'Ricordo recuperato dai neuroni: ' + ev.items.map((i) => `«${i.title}» (${i.groups.length} gruppi)`).join(', ')); break; } case 'memory_test': $('mem-test-out').innerHTML = ev.items.length ? ev.items.map((i) => `${i.recalled ? '<b>' : ''}${esc(i.title)} ${i.score.toFixed(2)}${i.recalled ? ' ✓ richiamato</b>' : ''}`).join(' · ') : 'Nessun ricordo salvato.'; break; case 'doctor': { const prev = S.doctor?.journal?.length || 0; S.doctor = ev; syncSentinels(false); const [cls, label] = HEALTH[ev.status] || ['', ev.status]; $('st-health').textContent = label; $('st-health').className = 'pill ' + (cls === 'live' ? 'pill-on' : cls === 'danger' ? 'pill-off' : cls === 'busy' ? 'pill-busy' : ''); // le riparazioni nuove compaiono anche nella conversazione for (const e of ev.journal.slice(prev)) if (prev && /ripar|sospes|ridott|rigenero|riavvio|dimenticato/i.test(e.text)) addMsg('doctor-msg', 'Autodiagnosi: ' + e.text); renderBlocks(); break; } case 'retry': { const m = aiMsgs.get(ev.req); if (m) { // si rigenera solo l'ultimo passaggio: le schede degli strumenti già usati restano const cards = m.body.querySelectorAll('.tool'); const last = cards[cards.length - 1]; if (last) { while (last.nextSibling) last.nextSibling.remove(); } else m.body.textContent = ''; m.thoughtText.textContent = ''; m.thought.hidden = true; m.el.querySelector('.meta').textContent = `Neuronal ha rigenerato la risposta: ${ev.reason}`; } stopVoice(); break; } case 'token': onToken(ev); break; case 'tool': onTool(ev); break; case 'modes': onModes(ev); break; case 'queue': $('queue-overlay').hidden = false; $('queue-text').textContent = ev.restarting ? 'Il visitatore prima di te ha finito: preparo un cervello nuovo…' : ev.free ? 'Tocca a te: sto entrando…' : `Un'altra persona sta usando il cervello di Neuronal. Sei il n. ${ev.position} in coda.`; if (ev.free) setTimeout(() => S.ws?.close(), 500); // ricollegandosi entra break; case 'session': $('session-bar').hidden = !ev.waiting; if (ev.waiting) $('session-bar').textContent = `${ev.waiting === 1 ? 'Una persona aspetta' : `${ev.waiting} persone aspettano`}: ` + `la sessione si chiude dopo ${Math.ceil(ev.idle_left / 60)} min di inattività (al massimo tra ${Math.ceil(ev.max_left / 60)} min).`; break; case 'session_end': S.ended = true; $('ended-why').textContent = ev.why; $('ended-overlay').hidden = false; break; case 'network': if (S.hello) { S.hello.lan = ev.lan; S.hello.host = ev.host; } if (!$('phone-overlay').hidden) showPhonePanel(); // il QR segue il nuovo indirizzo break; case 'settings': onSettings(ev); break; case 'procs': onProcs(ev); break; case 'call_saved': addMsg('memory-msg', `Ho salvato la trascrizione della chiamata (${ev.lines} frasi) in ${ev.path}, nella cartella di lavoro.`); break; case 'audio_progress': case 'audio_done': case 'audio_error': onAudio(ev); break; case 'logs': onLogs(ev); break; case 'log': onLogLine(ev); break; case 'security': onSecurity(ev); break; case 'focus_region': focusRegion(ev.region); break; case 'set_mode': if ([...$('mode').options].some((o) => o.value === ev.mode)) { $('mode').value = ev.mode; $('mode').onchange(); } break; case 'done': onDone(ev); break; case 'cleared': showHistory({ messages: [] }); break; case 'call': if (ev.state === 'chiusa' && S.call) endCall(false); break; case 'voice_state': if (S.call) $('call-state').textContent = (CALL_LABEL[ev.state] || ev.state) + (ev.state === 'parlo' || ev.state === 'penso' ? '' : ''); break; case 'voice_stop': stopVoice(); break; case 'error': addMsg('error', ev.message); if (S.call && /vocale/.test(ev.message)) endCall(false); break; } }; } // ---------------------------------------------------------------- processi e registri // Si vede un solo processo, il principale. I secondari (gli strumenti che ha lanciato, le ricerche, l'OCR, la GPU in // prestito) stanno sotto di lui: ci si arriva dal suo pulsante, o da «Vedi» quando ne sta usando uno. S.procs = { list: [], offset: 0 }; // offset: ora del motore meno ora del browser S.logs = { 1: [], 2: [], 4: [] }; // per vista: completo, voce, semplificato S.logView = Number(store.get('neuronal_log') || 4); S.procOpen = false; // i secondari sono aperti? const LOG_NAME = { 1: 'completo', 2: 'voce', 4: 'semplificato' }; const LOG_CAP = 500; function fmtDur(s) { s = Math.max(0, Math.round(s)); return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`; } // Il processo principale: quello in corso più importante (a parità, il più recente); se non ce n'è, l'ultimo finito. function pickMain(list) { const running = list.filter((p) => p.state === 1); if (running.length) return running.reduce((a, b) => (b.prio > a.prio || (b.prio === a.prio && b.t0 > a.t0) ? b : a)); return list.length ? list[0] : null; // il motore manda per primo il più recente } function onProcs(ev) { S.procs = { list: ev.list, offset: ev.now - Date.now() / 1000 }; renderProcs(); } function procElapsed(p) { const end = p.state === 1 ? Date.now() / 1000 + S.procs.offset : p.t1; return end - p.t0; } function renderProcs() { const main = pickMain(S.procs.list); const pill = $('proc-pill'); const running = main && main.state === 1; pill.hidden = !running; if (running) pill.textContent = main.title; const box = $('proc-main'); box.replaceChildren(); box.classList.toggle('idle', !running); if (!main) { box.textContent = 'Nessun processo in corso. Quando Neuronal lavora vedrai qui cosa sta facendo.'; $('proc-more').hidden = true; $('proc-kids').hidden = true; return; } const t = document.createElement('div'); t.className = 'p-title'; const dot = document.createElement('i'); dot.className = main.state === 1 ? 'dot-run' : main.state === 2 ? 'dot-ok' : 'dot-err'; const name = document.createElement('span'); name.textContent = running ? main.title : `${main.title} · ${main.state === 2 ? 'finito' : 'non riuscito'}`; const time = document.createElement('span'); time.className = 'p-time'; time.id = 'proc-time'; time.textContent = fmtDur(procElapsed(main)); t.append(dot, name, time); const d = document.createElement('div'); d.className = 'p-detail'; d.textContent = main.detail || (running ? 'in corso…' : ''); box.append(t, d); const kids = main.kids || []; const others = running ? S.procs.list.filter((p) => p.id !== main.id && p.state === 1) : []; const nowKid = kids.find((k) => k.state === 1); if (nowKid) { // il principale sta aspettando un secondario: ti porta lì const n = document.createElement('div'); n.className = 'p-now'; const tx = document.createElement('span'); tx.textContent = `Sta usando: ${nowKid.title}`; const go = document.createElement('button'); go.type = 'button'; go.className = 'ghost'; go.textContent = S.procOpen ? 'Nascondi' : 'Vedi'; go.onclick = () => { S.procOpen = !S.procOpen; renderProcs(); }; n.append(tx, go); box.append(n); } const total = kids.length + others.length; const more = $('proc-more'), list = $('proc-kids'); more.hidden = total === 0; more.textContent = (S.procOpen ? 'Nascondi' : 'Mostra') + ` i processi secondari (${total})`; more.onclick = () => { S.procOpen = !S.procOpen; renderProcs(); }; list.hidden = !S.procOpen || total === 0; list.replaceChildren(); const row = (p, cls) => { const li = document.createElement('li'); li.className = cls + (p.state === 1 ? ' run' : ''); const st = document.createElement('i'); st.textContent = p.state === 1 ? '●' : p.state === 2 ? '✓' : '✕'; st.style.color = p.state === 1 ? 'var(--accent)' : p.state === 2 ? '#5bd68a' : 'var(--danger)'; const tt = document.createElement('span'); tt.textContent = p.title; const tm = document.createElement('span'); tm.className = 'k-t'; tm.textContent = fmtDur(procElapsed(p)); li.append(st, tt, tm); if (p.detail) { const dd = document.createElement('span'); dd.className = 'k-d'; dd.textContent = p.detail; li.append(dd); } list.append(li); }; if (kids.length) kids.forEach((k) => row(k, 'kid')); if (others.length) { const sep = document.createElement('li'); sep.className = 'k-sep'; sep.textContent = 'In secondo piano'; list.append(sep); others.forEach((p) => row(p, 'bg')); } } setInterval(() => { // il tempo scorre anche senza messaggi dal motore const main = pickMain(S.procs.list); if (main && main.state === 1 && $('proc-time')) $('proc-time').textContent = fmtDur(procElapsed(main)); }, 500); $('proc-pill').onclick = () => showTab('procs'); // ---- registri ---- function addLog(c, t, x) { for (const k of [1, 2, 4]) if (c & k) { const a = S.logs[k]; a.push({ t, x, c }); if (a.length > LOG_CAP) a.shift(); } } function onLogs(ev) { S.logs = { 1: [], 2: [], 4: [] }; for (const [c, t, x] of ev.lines) addLog(c, t, x); renderLog(true); } function onLogLine(ev) { addLog(ev.c, ev.t, ev.x); if (!$('panel-procs').hidden) renderLog(false); } function logTime(t) { return new Date(t * 1000).toLocaleTimeString('it-IT'); } function renderLog(force) { const list = $('log-list'); const lines = S.logs[S.logView]; const stick = force || list.scrollHeight - list.scrollTop - list.clientHeight < 40; list.replaceChildren(); if (!lines.length) { const li = document.createElement('li'); li.innerHTML = '<span class="empty-log">Ancora niente in questo registro.</span>'; list.append(li); } for (const l of lines) { const li = document.createElement('li'); const tm = document.createElement('time'); tm.textContent = logTime(l.t); const tag = document.createElement('span'); tag.className = 'tag'; tag.textContent = S.logView === 1 && (l.c & 2) ? 'voce' : ''; const x = document.createElement('span'); x.className = 'x'; x.textContent = l.x; li.append(tm, tag, x); list.append(li); } if (stick) list.scrollTop = list.scrollHeight; } document.querySelectorAll('.seg button').forEach((b) => { b.classList.toggle('on', Number(b.dataset.log) === S.logView); b.onclick = () => { S.logView = Number(b.dataset.log); store.set('neuronal_log', String(S.logView)); document.querySelectorAll('.seg button').forEach((o) => o.classList.toggle('on', o === b)); renderLog(true); }; }); $('log-refresh').onclick = () => send({ cmd: 'logs' }); $('log-save').onclick = () => { const text = S.logs[S.logView].map((l) => `${new Date(l.t * 1000).toLocaleString('it-IT')} ${l.x}`).join('\n') + '\n'; const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); a.download = `neuronal-registro-${LOG_NAME[S.logView]}-${new Date().toISOString().slice(0, 10)}.txt`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 2000); }; if (location.hash === '#processi') showTab('procs'); // ---------------------------------------------------------------- ciclo di rendering // Distanza della camera tale che tutto il cervello (circa 15 x 6 unità) entri nella vista. function fitDistance() { const tanV = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)); return Math.max(7.8 / (tanV * camera.aspect), 3.6 / tanV) * 1.12; } function resize() { const w = canvas.clientWidth, h = canvas.clientHeight; renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix(); const dir = camera.position.clone().sub(controls.target).normalize(); camera.position.copy(controls.target).addScaledVector(dir, fitDistance()); } new ResizeObserver(resize).observe(canvas); let last = performance.now(), eegTick = 0; renderer.setAnimationLoop((now) => { const dt = Math.min(0.1, (now - last) / 1000); last = now; controls.update(); if (S.basePos) glowUpdate(dt); if (S.doctor?.status === 'controllo' && Math.random() < dt * 8) { const area = S.blocks.find((b) => b.region === -1 && b.applied); if (area) blocksView.setActivations(area.id, Float32Array.from({ length: area.neurons }, () => 0.4 + Math.random() * 0.6)); } if (!memGlowPersist && memGlowUntil && now > memGlowUntil) { memGlow.material.opacity = Math.max(0, memGlow.material.opacity - dt); if (memGlow.material.opacity <= 0) { memGlow.geometry.setDrawRange(0, 0); memGlowUntil = 0; } } blocksView.update(dt, particles); sentinelsView.update(dt, now / 1000, particles, S.generating || S.doctor?.status === 'controllo'); particles.update(dt); if ((eegTick += dt) > 0.05) { eegTick = 0; drawEEG(); if (S.selected) refreshInspector(); $('st-msg').textContent = fmt(S.msgCount); } renderer.render(scene, camera); }); resize(); connect(); // Coding acceso o spento: una preferenza di questo dispositivo. if (store.get('neuronal_tools') === '0') $('tools-on').checked = false; $('tools-on').onchange = () => store.set('neuronal_tools', $('tools-on').checked ? '1' : '0'); if (store.get('neuronal_web') === '0') $('web-on').checked = false; $('web-on').onchange = () => store.set('neuronal_web', $('web-on').checked ? '1' : '0'); // Modalità di comportamento: Neuronal (predefinita) più quelle in mind/prompts/modi. function onModes(ev) { const sel = $('mode'), keep = store.get('neuronal_mode') || ''; sel.replaceChildren(new Option('Neuronal', '')); for (const m of ev.list) { const o = new Option(m.name, m.id); o.title = m.desc; o.dataset.tools = m.tools ? '1' : ''; o.dataset.web = m.web ? '1' : ''; sel.append(o); } sel.value = [...sel.options].some((o) => o.value === keep) ? keep : ''; syncMode(); send({ cmd: 'set_mode', mode: sel.value }); // la modalità vale anche per le chiamate da questo dispositivo } function syncMode() { const o = $('mode').selectedOptions[0]; $('mode').title = o?.title || 'Assistente personale in stile JARVIS'; const forced = !!o?.dataset.tools; // una modalità di programmazione usa sempre gli strumenti $('tools-on').disabled = forced; if (forced) $('tools-on').checked = true; else $('tools-on').checked = store.get('neuronal_tools') !== '0'; const webForced = !!o?.dataset.web; // una modalità con internet lo tiene sempre acceso $('web-on').disabled = webForced; $('web-on').checked = webForced || store.get('neuronal_web') !== '0'; } $('mode').onchange = () => { store.set('neuronal_mode', $('mode').value); syncMode(); send({ cmd: 'set_mode', mode: $('mode').value }); }; // ---------------------------------------------------------------- visione // Immagine -> RGB ridotto (il lato lungo al massimo max px), pronto per il frame binario 'I'. function toRGB(source, sw, sh, max) { const k = Math.min(1, max / Math.max(sw, sh)); const w = Math.max(16, Math.round(sw * k)), h = Math.max(16, Math.round(sh * k)); const cv = document.createElement('canvas'); cv.width = w; cv.height = h; const g = cv.getContext('2d'); g.drawImage(source, 0, 0, w, h); const rgba = g.getImageData(0, 0, w, h).data, rgb = new Uint8Array(w * h * 3); for (let i = 0, j = 0; i < rgba.length; i += 4) { rgb[j++] = rgba[i]; rgb[j++] = rgba[i + 1]; rgb[j++] = rgba[i + 2]; } return { w, h, rgb, thumb: cv.toDataURL('image/jpeg', 0.7) }; } function sendImage(img, kind) { if (!S.ws || S.ws.readyState !== 1) return; const buf = new Uint8Array(8 + img.rgb.length), dv = new DataView(buf.buffer); buf[0] = 73; buf[1] = kind; // 'I' dv.setUint16(2, img.w, true); dv.setUint16(4, img.h, true); buf.set(img.rgb, 8); S.ws.send(buf); } // ---------------------------------------------------------------- allegati // Graffetta e trascinamento: foto, PDF, JSON e file di testo. Il testo si legge qui (anche dai PDF, con pdf.js // incluso nella cartella vendor) e si manda al motore; le foto e le pagine dei PDF scansionati partono come // immagini da salvare nella cartella di lavoro, dove lo strumento leggi_immagine (OCR) le trova. S.files = []; // {id, name, kind, state: 'lettura'|'pronto'|'errore', note, thumb} let fileSeq = 0; const TEXT_EXT = /\.(json|jsonl|txt|md|csv|tsv|xml|html?|log|ya?ml|ini|toml|py|m?js|ts|c|h|cpp|hpp|java|go|rs|sql|sh|bat|ps1|css)$/i; const MAX_FILE = 25 * 1024 * 1024; const MAX_AUDIO = 60 * 1024 * 1024; function clearAttach() { // solo la foto che Neuronal guarda subito (non gli altri allegati) S.attach = null; $('attach-file').value = ''; } function renderFiles() { const bar = $('attach-bar'); bar.replaceChildren(); bar.hidden = !S.files.length; for (const f of S.files) { const it = document.createElement('span'); it.className = 'attach-item' + (f.state === 'errore' ? ' err' : f.state === 'lettura' ? ' busy' : ''); if (f.thumb) { const im = document.createElement('img'); im.src = f.thumb; it.append(im); } else { const ic = document.createElement('span'); ic.className = 'ico'; ic.textContent = f.kind === 'pdf' ? '📕' : f.kind === 'json' ? '🧾' : f.kind === 'audio' ? '🎧' : '📄'; it.append(ic); } const nm = document.createElement('span'); nm.className = 'nm'; nm.textContent = f.name; nm.title = f.name; const st = document.createElement('small'); st.textContent = f.state === 'lettura' ? (f.note || 'lettura…') : f.state === 'errore' ? f.note : (f.note || ''); const x = document.createElement('button'); x.type = 'button'; x.className = 'x'; x.title = 'Togli'; x.textContent = '✕'; x.onclick = () => removeFile(f); it.append(nm, st, x); bar.append(it); } } function removeFile(f) { S.files = S.files.filter((g) => g !== f); if (S.attach && S.attach === f.vision) S.attach = null; if (f.state === 'pronto') send({ cmd: 'attach_clear', name: f.name }); renderFiles(); } // Byte di un'immagine ridotta (il lato lungo al massimo max px), in JPEG. function jpegBytes(source, sw, sh, max, quality) { const k = Math.min(1, max / Math.max(sw, sh)); const cv = document.createElement('canvas'); cv.width = Math.max(16, Math.round(sw * k)); cv.height = Math.max(16, Math.round(sh * k)); const g = cv.getContext('2d'); g.fillStyle = '#fff'; g.fillRect(0, 0, cv.width, cv.height); // le trasparenze diventano bianche g.drawImage(source, 0, 0, cv.width, cv.height); return new Promise((res) => cv.toBlob(async (b) => res(new Uint8Array(await b.arrayBuffer())), 'image/jpeg', quality)); } // 'G': immagine da salvare nella cartella di lavoro (flags bit0: pagina di un PDF). function sendFileImage(name, bytes, flags) { const nb = new TextEncoder().encode(name.slice(0, 80)); const buf = new Uint8Array(4 + nb.length + bytes.length), dv = new DataView(buf.buffer); buf[0] = 71; buf[1] = flags; dv.setUint16(2, nb.length, true); buf.set(nb, 4); buf.set(bytes, 4 + nb.length); S.ws.send(buf); } let pdfLib = null; async function loadPdf() { if (!pdfLib) { pdfLib = await import('./vendor/pdfjs/pdf.min.mjs'); pdfLib.GlobalWorkerOptions.workerSrc = './vendor/pdfjs/pdf.worker.min.mjs'; } return pdfLib; } async function readPdf(file, f) { const lib = await loadPdf(); const doc = await lib.getDocument({ data: new Uint8Array(await file.arrayBuffer()) }).promise; const pages = Math.min(doc.numPages, 200), base = file.name.replace(/\.[^.]*$/, ''); let out = '', scanned = 0, textPages = 0; for (let i = 1; i <= pages; i++) { f.note = `pagina ${i}/${pages}`; renderFiles(); const pg = await doc.getPage(i); const tc = await pg.getTextContent(); let t = ''; for (const it of tc.items) t += it.str + (it.hasEOL ? '\n' : ''); t = t.replace(/[ \t]+\n/g, '\n').trim(); if (t.length >= 20) { out += `\n--- pagina ${i} ---\n${t}\n`; textPages++; continue; } if (scanned >= 12) continue; // pagina senza testo: una scansione, si allega come immagine (al massimo 12) const vp1 = pg.getViewport({ scale: 1 }), vp = pg.getViewport({ scale: Math.min(3, 1700 / vp1.width) }); const cv = document.createElement('canvas'); cv.width = Math.round(vp.width); cv.height = Math.round(vp.height); await pg.render({ canvasContext: cv.getContext('2d'), viewport: vp }).promise; const bytes = await jpegBytes(cv, cv.width, cv.height, 1700, 0.85); sendFileImage(`${base}-p${i}.jpg`, bytes, 1); out += `\n--- pagina ${i} --- (senza testo: allegata come immagine ${base}-p${i}.jpg)\n`; scanned++; } if (doc.numPages > pages) out += `\n(PDF di ${doc.numPages} pagine: lette le prime ${pages})\n`; if (!textPages && !scanned) throw new Error('il PDF è vuoto'); f.note = `${pages} pag.` + (scanned ? `, ${scanned} scansionate` : ''); send({ cmd: 'attach', name: file.name, kind: 'pdf', text: out.trim().slice(0, 1200000) }); } async function addFile(file) { const f = { id: ++fileSeq, name: file.name, kind: 'testo', state: 'lettura', note: '' }; S.files.push(f); renderFiles(); try { if (file.size > (isAudio(file) ? MAX_AUDIO : MAX_FILE)) throw new Error(isAudio(file) ? 'più di 60 MB' : 'più di 25 MB'); if (/^image\//.test(file.type)) { f.kind = 'immagine'; const bmp = await createImageBitmap(file); f.thumb = (await new Promise((res) => { const c = document.createElement('canvas'); c.width = c.height = 56; const k = Math.max(56 / bmp.width, 56 / bmp.height); c.getContext('2d').drawImage(bmp, 0, 0, bmp.width * k, bmp.height * k); res(c.toDataURL('image/jpeg', 0.6)); })); const canSee = !S.hello?.remote || S.perms?.camera; if (!S.attach && canSee) { f.vision = S.attach = toRGB(bmp, bmp.width, bmp.height, 768); S.sentThumb = f.vision.thumb; } sendFileImage(file.name, await jpegBytes(bmp, bmp.width, bmp.height, 2000, 0.9), 0); // anche in alta risoluzione per l'OCR f.note = `${bmp.width}×${bmp.height}`; } else if (isAudio(file)) { f.kind = 'audio'; await sendAudio(file, f); return; // lo stato lo chiude la trascrizione (onAudio) } else if (/\.pdf$/i.test(file.name) || file.type === 'application/pdf') { f.kind = 'pdf'; await readPdf(file, f); } else if (TEXT_EXT.test(file.name) || /^text\//.test(file.type) || /json|xml/.test(file.type)) { f.kind = /\.jsonl?$/i.test(file.name) ? 'json' : 'testo'; const text = await file.text(); if (text.includes('\u0000')) throw new Error('non è un file di testo'); send({ cmd: 'attach', name: file.name, kind: f.kind, text: text.slice(0, 1200000) }); f.note = text.length > 9999 ? `${Math.round(text.length / 1000)}k car.` : `${text.length} car.`; } else { throw new Error('tipo non supportato'); } f.state = 'pronto'; } catch (e) { f.state = 'errore'; f.note = e && e.message && !/^(Invalid|Missing|Unexpected)/i.test(e.message) ? e.message : 'non riesco a leggerlo'; if (S.attach && S.attach === f.vision) S.attach = null; setTimeout(() => { S.files = S.files.filter((g) => g !== f); renderFiles(); }, 6000); } renderFiles(); } async function addFiles(list) { for (const file of [...list]) await addFile(file); input.focus(); } $('btn-attach').onclick = () => $('attach-file').click(); $('attach-file').onchange = () => { const l = $('attach-file').files; if (l.length) addFiles(l); $('attach-file').value = ''; }; // trascinare file in qualunque punto della pagina let dragDepth = 0; const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files'); addEventListener('dragenter', (e) => { if (hasFiles(e)) { e.preventDefault(); dragDepth++; $('drop-hint').hidden = false; } }); addEventListener('dragover', (e) => { if (hasFiles(e)) e.preventDefault(); }); addEventListener('dragleave', (e) => { if (hasFiles(e) && --dragDepth <= 0) { dragDepth = 0; $('drop-hint').hidden = true; } }); addEventListener('drop', (e) => { if (!hasFiles(e)) return; e.preventDefault(); dragDepth = 0; $('drop-hint').hidden = true; addFiles(e.dataTransfer.files); }); function showUserImage(ev) { const d = messages.lastElementChild; if (!d) return; if (S.sentThumb && !ev.voice) { const im = document.createElement('img'); im.className = 'msg-img'; im.src = S.sentThumb; d.append(im); S.sentThumb = null; } else { d.querySelector('.from')?.append(' · 📷 immagine'); } } // Camera durante la chiamata: un fotogramma ogni 1,5 s; Neuronal guarda l'ultimo quando finisci di parlare. async function startCamera() { if (S.cam) return; try { const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment', width: { ideal: 1280 } }, audio: false }); const v = $('cam-preview'); v.srcObject = stream; v.hidden = false; await v.play(); const timer = setInterval(() => { if (v.videoWidth) sendImage(toRGB(v, v.videoWidth, v.videoHeight, 640), 1); }, 1500); S.cam = { stream, timer }; $('call-cam').classList.add('on'); } catch { addMsg('error', 'La camera non è disponibile su questo dispositivo o il permesso è stato negato.'); } } function stopCamera() { if (!S.cam) return; clearInterval(S.cam.timer); S.cam.stream.getTracks().forEach((t) => t.stop()); $('cam-preview').srcObject = null; $('cam-preview').hidden = true; $('call-cam').classList.remove('on'); S.cam = null; } $('call-cam').onclick = () => (S.cam ? stopCamera() : startCamera()); // ---------------------------------------------------------------- permessi (solo dal PC) const PERM_INFO = [ ['lan', 'Collegarsi a Neuronal', 'Se lo spegni nessun altro dispositivo può aprire Neuronal, e quelli collegati vengono scollegati.'], ['calls', 'Fare chiamate vocali', 'Parlare con Neuronal usando il microfono del telefono.'], ['camera', 'Usare camera e foto', 'Mandare foto e far vedere a Neuronal la camera durante le chiamate.'], ['memory', 'Memoria e conversazione', 'Salvare ricordi («ricordati che…»), cancellarli, iniziare una nuova conversazione.'], ['brain', 'Modificare il cervello', 'Neuroni, blocchi, macroaree, infezione, mappatura e Rete della Diagnosi.'], ['web', 'Cercare su internet', "Con l'interruttore Internet: cercare sul web e leggere pagine. Le domande escono dal PC."], ['files', 'File di lavoro', 'Con il Coding: leggere e scrivere file nella cartella «lavori».'], ['run', 'Eseguire comandi sul PC', 'Con il Coding: python, gcc, git… I programmi girano sul PC con i tuoi permessi.', true], ]; function onSettings(ev) { S.perms = ev.perms; const list = $('perm-list'); list.replaceChildren(); for (const [key, label, desc, danger] of PERM_INFO) { const li = document.createElement('li'); li.className = 'perm' + (danger ? ' danger' : ''); li.innerHTML = `<label class="switch"><input type="checkbox"><span></span><b></b></label><small></small>`; li.querySelector('b').textContent = label; li.querySelector('small').textContent = desc; const cb = li.querySelector('input'); cb.checked = !!ev.perms[key]; cb.disabled = !!S.hello?.remote; cb.onchange = () => { if (key === 'run' && cb.checked && !confirm('Dal telefono si potranno far eseguire programmi su questo PC. Attivare?')) { cb.checked = false; return; } send({ cmd: 'set_perm', key, on: cb.checked }); }; list.append(li); } if (S.hello?.remote) { // sul telefono spariscono le funzioni non permesse $('btn-call').hidden = !ev.perms.calls; $('btn-attach').hidden = !ev.perms.camera && !ev.perms.files; $('call-cam').hidden = !ev.perms.camera; } } const since = (s) => (s < 60 ? `${s} s` : s < 3600 ? `${Math.floor(s / 60)} min` : `${Math.floor(s / 3600)} h ${Math.floor((s % 3600) / 60)} min`); function onSecurity(ev) { if (S.hello) S.hello.pin = ev.pin; $('perm-pin').textContent = ev.pin; const dl = $('perm-devices'); dl.replaceChildren(); const devs = ev.devices.slice().sort((a, b) => a.remote - b.remote); for (const d of devs) { const li = document.createElement('li'); li.className = 'perm-dev' + (d.remote ? ' remote' : ''); const mode = d.mode ? [...$('mode').options].find((o) => o.value === d.mode)?.textContent || d.mode : 'Neuronal'; li.innerHTML = `<span class="dev-icon">${d.remote ? '📱' : '🖥'}</span><span class="dev-main"><b></b><small></small></span><span class="dev-tags"></span>`; li.querySelector('b').textContent = d.remote ? d.device : `${d.device} · questo computer`; li.querySelector('small').textContent = `${d.ip} · collegato da ${since(d.seconds)} · modalità ${mode}`; const tags = li.querySelector('.dev-tags'); if (d.in_call) tags.insertAdjacentHTML('beforeend', '<span class="status live">in chiamata</span>'); if (d.camera) tags.insertAdjacentHTML('beforeend', '<span class="status live">camera</span>'); if (d.remote) { const b = document.createElement('button'); b.className = 'ghost danger'; b.textContent = 'Disconnetti'; b.onclick = () => send({ cmd: 'kick', id: d.id }); tags.append(b); } dl.append(li); } if (!devs.some((d) => d.remote)) dl.insertAdjacentHTML('beforeend', '<li class="hint">Nessun telefono collegato.</li>'); const log = $('perm-log'); log.replaceChildren(); for (const e of ev.log) { const li = document.createElement('li'); const tm = new Date(e.t * 1000); li.innerHTML = `<time></time><span></span>`; li.querySelector('time').textContent = tm.toLocaleString('it-IT', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); li.querySelector('span').textContent = e.text; if (/errato|rifiutato|bloccato|disconnesso/.test(e.text)) li.className = 'warn'; log.append(li); } if (!ev.log.length) log.insertAdjacentHTML('beforeend', '<li class="hint">Ancora nessun accesso dalla rete.</li>'); } $('pin-new').onclick = () => { if (confirm('Creare un PIN nuovo? I telefoni collegati verranno scollegati.')) send({ cmd: 'pin_new' }); }; // ---------------------------------------------------------------- login Hugging Face (facoltativo) // Senza login la GPU veloce usa i minuti inclusi nello Space, finché durano. Con il login usa quelli dell'account // del visitatore. Il login è «Sign in with Hugging Face» (OAuth con PKCE, tutto nel browser): la chiave resta solo // in questa scheda e, mentre la sessione dura, nel motore; non viene scritta da nessuna parte. const HF = { id: '', token: '', name: '' }; const hfGet = (k) => { try { return sessionStorage.getItem(k); } catch { return null; } }; const hfSet = (k, v) => { try { v == null ? sessionStorage.removeItem(k) : sessionStorage.setItem(k, v); } catch { /* niente sessionStorage */ } }; const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); const hfRedirect = () => location.origin + '/'; function hfSend() { if (HF.token) send({ cmd: 'hf_token', token: HF.token }); } function hfRender() { const b = $('btn-hf'); b.hidden = !HF.id; b.textContent = HF.token ? `🤗 ${HF.name || 'collegato'} · risposte veloci` : '🤗 Accedi per le risposte veloci'; b.title = HF.token ? 'La GPU veloce usa i minuti del tuo account Hugging Face. Clicca per uscire.' : 'Senza accesso Neuronal risponde lentamente. Accedi con Hugging Face per le risposte veloci: usano i tuoi minuti di GPU giornalieri'; } async function hfLogin() { const rnd = (n) => b64url(crypto.getRandomValues(new Uint8Array(n))); const verifier = rnd(48), state = rnd(16); hfSet('hf_verifier', verifier); hfSet('hf_state', state); const challenge = b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))); const q = new URLSearchParams({ client_id: HF.id, redirect_uri: hfRedirect(), response_type: 'code', scope: 'openid profile', state, code_challenge: challenge, code_challenge_method: 'S256' }); location.href = 'https://huggingface.co/oauth/authorize?' + q; } function hfLogout() { HF.token = ''; HF.name = ''; ['hf_token', 'hf_name', 'hf_until'].forEach((k) => hfSet(k, null)); send({ cmd: 'hf_token', token: '' }); hfRender(); } async function hfBack() { // si torna da Hugging Face con ?code=… const u = new URL(location.href); const code = u.searchParams.get('code'), state = u.searchParams.get('state'); if (!code || !state) return; history.replaceState(null, '', location.pathname); if (state !== hfGet('hf_state') || !hfGet('hf_verifier')) return; try { const r = await fetch('https://huggingface.co/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: 'Basic ' + btoa(HF.id + ':') }, body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: hfRedirect(), code_verifier: hfGet('hf_verifier'), client_id: HF.id }), }); const t = await r.json(); if (!t.access_token) throw new Error(t.error_description || 'nessuna chiave'); HF.token = t.access_token; hfSet('hf_token', HF.token); hfSet('hf_until', String(Date.now() + (t.expires_in || 3600) * 1000)); try { const me = await (await fetch('https://huggingface.co/oauth/userinfo', { headers: { Authorization: 'Bearer ' + HF.token } })).json(); HF.name = me.preferred_username || me.name || ''; hfSet('hf_name', HF.name); } catch { /* il nome è solo di cortesia */ } } catch (e) { console.warn('Login Hugging Face non riuscito:', e); } hfSet('hf_verifier', null); hfSet('hf_state', null); } async function hfInit() { try { HF.id = (await (await fetch('/login.json', { cache: 'no-store' })).json()).client_id || ''; } catch { HF.id = ''; } if (!HF.id) { hfRender(); return; } await hfBack(); if (!HF.token && hfGet('hf_token') && Number(hfGet('hf_until') || 0) > Date.now()) { HF.token = hfGet('hf_token'); HF.name = hfGet('hf_name') || ''; } $('btn-hf').onclick = () => (HF.token ? hfLogout() : hfLogin()); hfRender(); hfSend(); } hfInit(); // ---------------------------------------------------------------- area Ascolto // Un audio allegato si riascolta qui (dal file del tuo computer, senza che esca da lì) e si trascrive sul PC con Whisper, // nella lingua in cui è parlato, senza tradurlo. Il testo con i tempi entra nel messaggio successivo. S.audio = new Map(); // nome -> { file, url, segs, pct, state, text, lang, dur, f, el } const AUDIO_EXT = /\.(mp3|wav|m4a|ogg|oga|opus|flac|aac|weba|webm|wma|mp4)$/i; const isAudio = (file) => /^audio\//.test(file.type) || AUDIO_EXT.test(file.name); const mmss = (t) => { t = Math.floor(t); const h = Math.floor(t / 3600); return (h ? h + ':' : '') + String(Math.floor(t % 3600 / 60)).padStart(h ? 2 : 1, '0') + ':' + String(t % 60).padStart(2, '0'); }; const audioText = (a) => a.text || a.segs.map((s) => `[${mmss(s[0])}] ${s[2]}`).join('\n'); // 'U': audio a pezzi da 1 MB (flags bit0 primo, bit1 ultimo) async function sendAudio(file, f) { const name = file.name.slice(0, 80); const old = S.audio.get(name); if (old) { URL.revokeObjectURL(old.url); old.el?.remove(); } const a = { name, file, url: URL.createObjectURL(file), segs: [], pct: 0, state: 'invio 0%', text: '', lang: '', dur: 0, f }; S.audio.set(name, a); renderAudio(); const nb = new TextEncoder().encode(name), PIECE = 1024 * 1024; try { for (let off = 0, n = 0; ; off += PIECE, n++) { const part = new Uint8Array(await file.slice(off, off + PIECE).arrayBuffer()); const last = off + PIECE >= file.size; const buf = new Uint8Array(4 + nb.length + part.length); buf[0] = 85; buf[1] = (n === 0 ? 1 : 0) | (last ? 2 : 0); new DataView(buf.buffer).setUint16(2, nb.length, true); buf.set(nb, 4); buf.set(part, 4 + nb.length); if (!S.ws || S.ws.readyState !== 1) throw new Error('non sono collegato al motore'); S.ws.send(buf); a.state = `invio ${Math.min(100, Math.round(100 * (off + PIECE) / Math.max(file.size, 1)))}%`; f.note = a.state; renderFiles(); renderAudio(); while (S.ws.bufferedAmount > 4 * PIECE) await new Promise((r) => setTimeout(r, 40)); if (last) break; } } catch (e) { a.state = 'errore'; a.error = e.message || 'invio non riuscito'; f.state = 'errore'; f.note = a.error; setTimeout(() => { S.files = S.files.filter((g) => g !== f); renderFiles(); }, 6000); renderFiles(); renderAudio(); return; } a.state = 'trascrivo…'; f.state = 'lettura'; f.note = 'trascrivo…'; renderFiles(); renderAudio(); } function onAudio(ev) { const a = S.audio.get(ev.name); if (!a) return; if (ev.ev === 'audio_progress') { if (ev.dur) a.dur = ev.dur; if (ev.lang) a.lang = ev.lang; a.pct = ev.pct || a.pct; for (const s of ev.segs || []) a.segs.push(s); a.state = a.pct ? `trascrivo ${a.pct}%` : 'trascrivo…'; a.f.note = a.state; } else if (ev.ev === 'audio_done') { a.state = 'pronto'; a.pct = 100; a.text = ev.text; a.lang = ev.lang || a.lang; a.dur = ev.dur || a.dur; a.f.state = 'pronto'; a.f.note = mmss(a.dur); } else { a.state = 'errore'; a.error = ev.message; a.f.state = 'errore'; a.f.note = ev.message; setTimeout(() => { S.files = S.files.filter((g) => g !== a.f); renderFiles(); }, 6000); } renderFiles(); renderAudio(); } function buildAudioCard(a) { const card = document.createElement('div'); card.className = 'audio-card'; const h = document.createElement('h4'); const nm = document.createElement('span'); nm.textContent = '🎧 ' + a.name; nm.title = a.name; const meta = document.createElement('small'); meta.className = 'a-meta'; h.append(nm, meta); const au = document.createElement('audio'); au.controls = true; au.preload = 'metadata'; au.src = a.url; const st = document.createElement('div'); st.className = 'audio-state'; const bar = document.createElement('div'); bar.className = 'audio-bar'; bar.append(document.createElement('i')); const ol = document.createElement('ol'); ol.className = 'audio-segs'; const tools = document.createElement('div'); tools.className = 'audio-tools'; const mk = (t, fn) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'ghost'; b.textContent = t; b.onclick = fn; tools.append(b); }; mk('Chiedi a Neuronal', () => askAudio(a)); mk('Copia il testo', () => navigator.clipboard?.writeText(audioText(a))); mk('Scarica il testo', () => { const l = document.createElement('a'); l.href = URL.createObjectURL(new Blob([audioText(a) + '\n'], { type: 'text/plain;charset=utf-8' })); l.download = a.name.replace(/\.[^.]*$/, '') + '-trascrizione.txt'; l.click(); setTimeout(() => URL.revokeObjectURL(l.href), 2000); }); mk('Togli', () => { au.pause(); URL.revokeObjectURL(a.url); S.audio.delete(a.name); card.remove(); send({ cmd: 'attach_clear', name: a.name }); S.files = S.files.filter((g) => g !== a.f); renderFiles(); }); au.ontimeupdate = () => { // la frase che si sta ascoltando si evidenzia const t = au.currentTime; ol.querySelectorAll('li').forEach((li, i) => li.classList.toggle('now', !!a.segs[i] && t >= a.segs[i][0] && t < a.segs[i][1] + 0.3)); const cur = ol.querySelector('li.now'); if (cur && !au.paused) cur.scrollIntoView({ block: 'nearest' }); }; card.append(h, au, st, bar, ol, tools); return card; } function renderAudio() { const list = $('audio-list'); for (const a of S.audio.values()) { if (!a.el) { a.el = buildAudioCard(a); list.prepend(a.el); } // la scheda si crea una volta sola: il lettore non riparte a ogni aggiornamento const card = a.el; card.classList.toggle('err', a.state === 'errore'); card.querySelector('.a-meta').textContent = [a.lang && a.lang.toUpperCase(), a.dur && mmss(a.dur)].filter(Boolean).join(' · '); card.querySelector('.audio-state').textContent = a.state === 'errore' ? a.error : a.state === 'pronto' ? `Trascrizione pronta · ${a.segs.length} frasi` : a.state; card.querySelector('.audio-bar').hidden = a.state === 'pronto' || a.state === 'errore'; const inv = /^invio (\d+)%/.exec(a.state); card.querySelector('.audio-bar i').style.width = (inv ? Number(inv[1]) : a.pct) + '%'; const ol = card.querySelector('.audio-segs'); for (let i = ol.children.length; i < a.segs.length; i++) { // si aggiungono solo le frasi nuove const [t0, , txt] = a.segs[i]; const li = document.createElement('li'); const tm = document.createElement('time'); tm.textContent = mmss(t0); const x = document.createElement('span'); x.textContent = txt; li.append(tm, x); li.onclick = () => { const au = card.querySelector('audio'); au.currentTime = t0; au.play(); }; ol.append(li); } } } function askAudio(a) { if (a.state !== 'pronto') { addMsg('error', 'La trascrizione non è ancora pronta: aspetta che finisca.'); return; } send({ cmd: 'attach', name: a.name, kind: 'audio', text: a.text }); // allegata di nuovo, anche se un messaggio precedente l'aveva già usata S.files = S.files.filter((g) => g.name !== a.name); S.files.push({ id: ++fileSeq, name: a.name, kind: 'audio', state: 'pronto', note: mmss(a.dur) }); renderFiles(); showTab('chat'); input.value = input.value || 'Riassumi questo audio e dimmi i punti importanti.'; input.focus(); } $('audio-pick').onclick = () => $('audio-file').click(); $('audio-file').onchange = () => { const l = $('audio-file').files; if (l.length) addFiles(l); $('audio-file').value = ''; };
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { Particles } from './particles.js';
import { BlocksView, BLOCK_COLORS } from './blocks3d.js';
import { SentinelsView, ROLE_COLORS } from './sentinels3d.js';
import qrcode from './vendor/qrcode.mjs';
// Telefono o tablet: 3D alleggerito (un neurone ogni LITE_STRIDE) per restare fluido.
const LITE = matchMedia('(max-width: 900px)').matches || /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);
const LITE_STRIDE = 8;
const $ = (id) => document.getElementById(id);
const fmt = (n) => n.toLocaleString('it-IT');
const REGION_COLORS = ['#5ce1e6', '#7b8cff', '#c77dff', '#ff6fb5', '#ffb347', '#9be15d',
'#4dabf7', '#ff8c69', '#63e6be', '#e599f7', '#ffd43b', '#b2f2bb'];
const GLOW_CAP = 40000; // neuroni accesi contemporaneamente al massimo
const MARK_CAP = 20000; // neuroni modificati evidenziati
const S = {
nLayer: 0, nFF: 0,
atlas: null,
regionOfLayer: [],
basePos: null,
ws: null,
generating: false,
aiMsg: null,
factors: new Map(), // chiave L*nFF+idx -> fattore
eeg: new Float32Array(0),
eegMax: new Float32Array(0),
selected: null, // {L, idx}
focusRegion: -1,
tokCount: 0, tokStart: 0,
blocks: [], // blocchi dal motore
blockProgress: new Map(), // id -> messaggio di elaborazione in corso
editing: new Set(), // blocchi di cui si sta cambiando la funzione
focusBlock: -1,
regions: [], // macroaree con le modifiche dell'utente
regionBusy: new Map(), // id area -> id blocco in elaborazione (0 = in coda)
ui: null,
doctor: null, // stato dell'autodiagnosi e diario
memory: null, // memoria a gruppi di neuroni
memFocus: -1, // ricordo evidenziato nel 3D // modifica aperta: {kind: 'region'|'block', id, mode: 'rename'|'use'|'delete'|'function'}
synapses: null, // ultime sinapsi calcolate per il neurone selezionato
msgCount: 0,
};
// ---------------------------------------------------------------- scena
const canvas = $('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(LITE ? 1 : Math.min(devicePixelRatio, 2));
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
camera.position.set(0, 5, 16);
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.35;
let idleTimer;
controls.addEventListener('start', () => { controls.autoRotate = false; clearTimeout(idleTimer); });
controls.addEventListener('end', () => { idleTimer = setTimeout(() => (controls.autoRotate = true), 20000); });
function glowSprite() {
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d');
const grad = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grad.addColorStop(0, 'rgba(255,255,255,1)');
grad.addColorStop(0.25, 'rgba(255,255,255,0.55)');
grad.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = grad;
g.fillRect(0, 0, 64, 64);
return new THREE.CanvasTexture(c);
}
const sprite = glowSprite();
function pointsLayer(cap, material) {
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage));
geo.setAttribute('color', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage));
geo.setDrawRange(0, 0);
const pts = new THREE.Points(geo, material);
pts.frustumCulled = false;
scene.add(pts);
return pts;
}
let base = null; // tutti i neuroni
const glow = pointsLayer(GLOW_CAP, new THREE.PointsMaterial({
size: 0.11, map: sprite, vertexColors: true, transparent: true,
blending: THREE.AdditiveBlending, depthWrite: false }));
const marks = pointsLayer(MARK_CAP, new THREE.PointsMaterial({
size: 0.14, map: sprite, vertexColors: true, transparent: true, depthWrite: false, depthTest: false }));
marks.renderOrder = 2; // sempre visibili, sopra l'attività
const pick = pointsLayer(1, new THREE.PointsMaterial({
size: 0.45, map: sprite, color: 0xffffff, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
const posOf = (l, j) => {
const k = (l * S.nFF + j) * 3;