Files
ploxion-mega-forge/app.blade.php

1228 lines
170 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{{-- PL0XION mega-forge 🛠️ — LA GRANDE FORGE (rs-4, RS-7 : « pas un hub — UNE seule grande forge qui prend
TOUS les bions et TOUS les ploxions comme palette, et on BUILD dedans, façon Premiere Pro / SolidWorks »).
Atelier pro : BIBLIOTHÈQUE (parts jOSKit + tous les ploxions + tous les bions) · VIEWPORT 3D (jOSEngine,
clic-sol = poser) · INSPECTEUR (props du sélectionné) · ARBRE du document. On compose → ▶ jouer / ⚒ forger
= un vrai nouveau ploxion. Moteur partagé window.jOSForgeStudio (aussi utilisé par les ploxions forgés). --}}
<style>
.fs{position:absolute;inset:0;display:grid;grid-template-columns:186px 1fr 210px;grid-template-rows:40px 1fr 128px;grid-template-areas:"bar bar bar" "lib view insp" "lib tree insp";background:#06070e;color:#dfe7ff;font-family:var(--xr-font-ui,ui-sans-serif,system-ui);font-size:.78rem;overflow:hidden}
.fs__bar{grid-area:bar;display:flex;align-items:center;gap:8px;padding:0 10px;border-bottom:1px solid #16233c;background:#080c16;overflow-x:auto;overflow-y:hidden}
.fs__bar>*{flex:0 0 auto}
.fs__bar b{font-weight:800}.fs__sp{flex:1}.fs__bar .fs__sp{flex:1 1 0}
.fs__b{cursor:pointer;border:0;border-radius:7px;background:#5fe0c0;color:#04120e;font:inherit;font-weight:800;font-size:.74rem;padding:6px 10px}
.fs__b.sec{background:rgba(30,48,84,.7);color:#dbe9ff;border:1px solid #2a3a62;font-weight:600}
.fs__lib{grid-area:lib;border-right:1px solid #16233c;display:flex;flex-direction:column;min-height:0;background:#080b14}
.fs__tabs{display:flex;border-bottom:1px solid #16233c}
.fs__tab{flex:1;text-align:center;padding:6px 2px;cursor:pointer;font-size:.68rem;color:#8397c0;border-bottom:2px solid transparent}
.fs__tab.on{color:#5fe0c0;border-bottom-color:#5fe0c0;font-weight:700}
.fs__q{margin:6px;background:#0c1626;border:1px solid #22344f;color:#cfe;border-radius:6px;padding:5px 7px;font:inherit;font-size:.72rem}
.fs__items{flex:1;overflow:auto;padding:0 6px 8px}
.fs__it{display:flex;align-items:center;gap:6px;padding:5px 6px;border-radius:6px;cursor:pointer;font-size:.72rem;border:1px solid transparent}
.fs__it:hover{background:rgba(95,224,192,.1);border-color:#284a44}
.fs__it .i{font-size:.95rem;width:18px;text-align:center}
.fs__view{grid-area:view;position:relative;overflow:hidden}.fs__view canvas{width:100%;height:100%;display:block;cursor:crosshair}
.fs__hint{position:absolute;left:8px;bottom:8px;font:.66rem ui-monospace;color:#9ab;background:rgba(5,7,14,.6);padding:2px 7px;border-radius:5px;pointer-events:none}
.fs__panel{position:absolute;width:240px;height:180px;background:#0a0e18;border:1px solid #2a3a62;border-radius:8px;overflow:hidden;box-shadow:0 8px 24px rgba(0,0,0,.5);display:flex;flex-direction:column;z-index:4}
.fs__ph{cursor:move;background:#111a2c;padding:3px 7px;font-size:.66rem;display:flex;align-items:center;gap:5px;border-bottom:1px solid #223}
.fs__ph .x{margin-left:auto;cursor:pointer;color:#8aa}.fs__pb{flex:1;position:relative;overflow:auto}
.fs__insp{grid-area:insp;border-left:1px solid #16233c;padding:9px;overflow:auto;background:#080b14}
.fs__insp h4{font-size:.6rem;text-transform:uppercase;letter-spacing:.07em;color:#6a7bb0;margin:0 0 7px}
.fs__row{display:flex;align-items:center;gap:6px;margin-bottom:6px}.fs__row label{flex:0 0 42px;font-size:.66rem;color:#8397c0}
.fs__insp input{flex:1;min-width:0;background:#0c1626;border:1px solid #22344f;color:#cfe;border-radius:5px;padding:4px 6px;font:inherit;font-size:.72rem}
.fs__tree{grid-area:tree;border-top:1px solid #16233c;overflow:auto;padding:6px 8px;background:#080b14}
.fs__tt{font-size:.6rem;text-transform:uppercase;letter-spacing:.07em;color:#6a7bb0;margin-bottom:5px}
.fs__tn{display:flex;align-items:center;gap:6px;padding:3px 6px;border-radius:5px;cursor:pointer;font-size:.72rem}
.fs__tn.sel{background:rgba(95,224,192,.16)}.fs__tn .x{margin-left:auto;color:#8aa;cursor:pointer}
.fs__muted{color:#6a7bb0;font-size:.7rem}
.fs__seg{display:flex;border:1px solid #2a3a62;border-radius:7px;overflow:hidden;margin-right:6px}
.fs__seg button{border:0;background:transparent;color:#8397c0;font:inherit;font-size:.72rem;padding:5px 9px;cursor:pointer}
.fs__seg button.on{background:#5fe0c0;color:#04120e;font-weight:800}
.fs__wire{position:absolute;inset:0;background:radial-gradient(circle at 30% 20%,#0a1120,#06070e);overflow:auto;display:none}
.fs__wire.on{display:block}
.fs__wsvg{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
.fs__wsvg path{stroke:#5fe0c0;stroke-width:2;fill:none;pointer-events:stroke;cursor:pointer}
.fs__wnode{position:absolute;min-width:118px;background:linear-gradient(150deg,#132038,#0b1424);border:1px solid #2a3a62;border-radius:13px;font-size:.7rem;user-select:none;box-shadow:0 4px 14px rgba(0,0,0,.4),inset 0 1px 0 rgba(120,180,255,.08);transition:box-shadow .15s,transform .1s}
.fs__wnode:hover{box-shadow:0 6px 20px rgba(0,0,0,.5),0 0 0 1px rgba(95,224,192,.3)}
.fs__wnode.sel{border-color:#5fe0c0}.fs__wnode.selm{outline:2px dashed #5fe0c0;outline-offset:2px}
.fs__wnode.bion{border-color:#3a6a8a}.fs__wnode.cubion{border-color:#a07bff;background:linear-gradient(150deg,#241a3c,#150e26)}
.fs__wnode.plugion{border-color:#f0a35f;background:linear-gradient(150deg,#2a2014,#181008);border-radius:20px}
.fs__wnode .hd{display:flex;align-items:center;gap:5px;padding:5px 8px;cursor:move;border-bottom:1px solid rgba(120,150,200,.12);font-weight:600}
.fs__wnode .hd .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:96px}
.fs__wnode .hd .z{margin-left:auto;cursor:pointer;color:#6ad;font-size:.8rem}
.fs__wnode .body{display:flex;justify-content:space-between;gap:12px;padding:5px 3px}
.fs__wnode .ins,.fs__wnode .outs{display:flex;flex-direction:column;gap:5px}.fs__wnode .outs{align-items:flex-end}
.fs__wnode .port{display:flex;align-items:center;gap:4px;font-size:.58rem;color:#93a7cc}.fs__wnode .outs .port{flex-direction:row-reverse}
.fs__wnode .members{font-size:.56rem;color:#b7a3e6;padding:2px 8px 5px}
.fs__pin{display:inline-block;width:12px;height:12px;border-radius:50%;background:#1c2740;border:2px solid #5fe0c0;cursor:crosshair;flex:0 0 auto}
.fs__pin.in{margin-left:-9px}.fs__pin.out{margin-right:-9px;background:#5fe0c0;border-color:#8ff0d8}
.fs__pin:hover{transform:scale(1.3)}
.fs__wbar{position:absolute;top:8px;left:8px;z-index:3;display:flex;gap:6px}
.fs__wtip{position:absolute;left:8px;bottom:8px;font:.66rem ui-monospace;color:#9ab;background:rgba(5,7,14,.6);padding:2px 7px;border-radius:5px;pointer-events:none}
.fs__2d{position:absolute;inset:0;width:100%;height:100%;display:none;background:radial-gradient(circle at 50% 40%,#0a1120,#06070e)}
.fs__code{position:absolute;inset:0;margin:0;display:none;overflow:auto;background:#06070e;color:#bfe0d0;font:.72rem ui-monospace;padding:14px;white-space:pre-wrap}
.fs__xerv{position:absolute;inset:0;display:none;background:#06070e}
.fs__knob{display:flex;align-items:center;gap:6px;margin:3px 0}.fs__knob label{flex:0 0 46px;font-size:.62rem;color:#8397c0}.fs__knob input{flex:1}
.fs__crumb{position:absolute;top:8px;left:8px;z-index:4;display:flex;gap:5px;align-items:center;font-size:.7rem}
.fs__crumb .cb{cursor:pointer;background:rgba(30,48,84,.8);border:1px solid #2a3a62;border-radius:6px;padding:3px 8px;color:#dbe9ff}
.fs__crumb .cb.core{background:#5fe0c0;color:#04120e;font-weight:700}
/* ===== VUES VAGUE 2 (rs-4) : éclatée · fusion · connexions · forge · suggestions ===== */
.fs__over{position:absolute;inset:0;display:none;overflow:auto;background:radial-gradient(circle at 40% 15%,#0a1120,#06070e);color:#dfe7ff;box-sizing:border-box}
.fs__cmsg{padding:26px;text-align:center;color:#7f93bd}
.fs__exui{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);z-index:6;display:none;align-items:center;gap:10px;background:rgba(8,12,22,.92);border:1px solid #2a3a62;border-radius:11px;padding:8px 14px;box-shadow:0 6px 20px rgba(0,0,0,.55)}
.fs__exui.on{display:flex}.fs__exui input[type=range]{width:150px;accent-color:#5fe0c0}
.fs__fwrap{display:flex;flex-direction:column;align-items:center;gap:14px;padding:22px 12px}
.fs__ftitle{font-weight:800;font-size:.92rem}
.fs__fshape{display:flex;flex-wrap:wrap;align-content:center;justify-content:center;gap:5px;padding:14px;border:1px solid #2a3a62;background:radial-gradient(circle,rgba(95,224,192,.12),rgba(10,17,32,.55));box-shadow:0 0 34px rgba(95,224,192,.16),inset 0 0 22px rgba(0,0,0,.45)}
.fs__fchip{font-size:.56rem;color:#04120e;font-weight:800;border-radius:5px;padding:2px 5px;max-width:72px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.fs__fstats{font-size:.9rem}.fs__fstats b{color:#8ff0d8}
.fs__cbar{position:sticky;top:0;padding:8px 12px;background:#080c16;border-bottom:1px solid #16233c;font-weight:700;font-size:.8rem;z-index:2}
.fs__cscroll{overflow:auto;padding:8px}
.fs__cleg{display:flex;flex-wrap:wrap;gap:8px;padding:8px 12px 16px}
.fs__cli{display:flex;align-items:center;gap:5px;font-size:.62rem;color:#8397c0}.fs__cli i{width:11px;height:11px;border-radius:3px;display:inline-block}
.fs__fgwrap{display:flex;flex-direction:column;gap:12px;padding:14px;min-height:100%;box-sizing:border-box}
.fs__fgtitle{font-weight:800;font-size:.92rem}.fs__fgtitle b{color:#8ff0d8}
.fs__fgstats{display:flex;flex-wrap:wrap;gap:14px;font-size:.78rem;color:#8397c0}.fs__fgstats b{color:#dfe7ff;font-size:1rem}
.fs__fgcols{display:flex;flex-wrap:wrap;gap:12px;flex:1;min-height:0}
.fs__fgcol{flex:1 1 240px;min-width:0;background:#0a0e18;border:1px solid #22344f;border-radius:11px;padding:10px;display:flex;flex-direction:column;min-height:160px}
.fs__fgcol h4{margin:0 0 7px;font-size:.6rem;text-transform:uppercase;letter-spacing:.06em;color:#6a7bb0}
.fs__fglist{margin:0;padding-left:18px;font-size:.74rem;line-height:1.7;overflow:auto}
.fs__fgprev{flex:1;min-height:150px;position:relative;overflow:auto;border-radius:8px}
.fs__fgacts{display:flex;flex-wrap:wrap;gap:8px}
.fs__sgwrap{display:flex;flex-direction:column;gap:10px;padding:14px}
.fs__sgtitle{font-weight:800;font-size:.9rem}
.fs__sglist{display:flex;flex-direction:column;gap:8px}
.fs__sgcard{display:flex;align-items:center;gap:10px;text-align:left;cursor:pointer;background:#0c1424;border:1px solid #22344f;border-radius:11px;padding:9px 11px;color:#dfe7ff;font:inherit}
.fs__sgcard:hover{border-color:#5fe0c0;background:rgba(95,224,192,.08)}
.fs__sgico{font-size:1.1rem;flex:0 0 auto}
.fs__sgtxt{display:flex;flex-direction:column;min-width:0;flex:1}.fs__sgtxt b{font-size:.8rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.fs__sgadd{flex:0 0 auto;font-size:.66rem;font-weight:800;color:#04120e;background:#5fe0c0;border-radius:7px;padding:4px 9px}
</style>
<script>
(function () {
'use strict';
// Ports typés par bion — pour CÂBLER TOUS LES BIONS (RS-7). Défaut = in/out génériques si inconnu.
var BIONPORTS = { jOSSound: { in: ['play', 'pause'], out: ['state'] }, jOSNexus: { in: ['push'], out: ['pull'] }, jOSChart: { in: ['data'], out: [] }, jOSPorts: { in: ['emit'], out: ['bus'] }, jOSEngine: { in: ['spawn'], out: ['frame'] }, jOSKit: { in: ['make'], out: [] }, jOSBoxion: { in: ['save'], out: ['loaded'] }, jOSSwipe: { in: ['add'], out: ['pick'] }, jOSGlyphCodec: { in: ['notation'], out: ['svg'] }, jOSTsoin: { in: ['record'], out: ['mark'] }, jOSWire: { in: [], out: ['packet'] }, jOSForge: { in: ['add'], out: ['forged'] }, jOS3D: { in: ['add'], out: [] }, jOSViewer: { in: ['load'], out: [] }, jOSPlayer: { in: ['play', 'pause'], out: ['ended'] } };
function portsOf(b) { var p = BIONPORTS[b]; return p ? { in: (p.in || []).slice(), out: (p.out || []).slice() } : { in: ['in'], out: ['out'] }; }
// TYPES DE XER (RS-7 : « choisir le type de xer ») — chaque bloc EST un xer typé (couleur = sens).
var XERTYPES = [{ id: 'cube', name: 'cube', col: 0x3a6a8a }, { id: 'media', name: 'média', col: 0xff8a5c }, { id: 'data', name: 'données', col: 0x5fe0c0 }, { id: 'compute', name: 'calcul', col: 0xb56aff }, { id: 'io', name: 'I/O', col: 0xf0d05f }, { id: 'ui', name: 'UI', col: 0x6fd0ff }, { id: 'logic', name: 'logique', col: 0x9aff9a }, { id: 'net', name: 'réseau', col: 0xff6a9a }];
function xerColor(id) { for (var i = 0; i < XERTYPES.length; i++) if (XERTYPES[i].id === id) return XERTYPES[i].col; return 0x3a6a8a; }
// EXEMPLES (RS-7 : « montre comment le ploxion carte est fait, avec ses bions et ses xers ») — décompositions
// réelles en cubes-bions typés autour du core, avec faces=ploxions I/O. Un point de départ pédagogique.
var EXAMPLES = {
carte: { label: '🗺️ carte', cubes: [
{ bion: 'jOS3D', xer: 'ui', d: [0, 1, 0], faces: { up: { dir: 'out' } } },
{ bion: 'jOSNexus', xer: 'net', d: [1, 0, 0], faces: { east: { dir: 'out', ploxion: 'map-amis' } } },
{ bion: 'jOSBoxion', xer: 'data', d: [-1, 0, 0], faces: { west: { dir: 'in' } } },
{ bion: 'jOSPorts', xer: 'logic', d: [0, 0, 1] },
{ bion: 'jOSViewer', xer: 'media', d: [0, 0, -1] }
] },
son: { label: '🔊 son', cubes: [
{ bion: 'jOSSound', xer: 'media', d: [0, 1, 0] },
{ bion: 'jOSPlayer', xer: 'media', d: [1, 0, 0] },
{ bion: 'jOSPorts', xer: 'logic', d: [-1, 0, 0] }
] }
};
// SERVICES & SYSTÈMES DU BOXION (RS-7 : « des blocs pour tous les services qui tournent sur le boxion,
// pour avoir la vue du boxion »). deps = docking par dépendance → la vue du boxion est une structure dockée.
var BOXION = [
{ id: 'traefik', label: '🚦 traefik', xer: 'net', deps: [] },
{ id: 'app', label: '🌐 mw2-app', xer: 'ui', deps: ['db', 'xion'] },
{ id: 'db', label: '🗄 postgres', xer: 'data', deps: [] },
{ id: 'xion', label: '⚛ xion daemon', xer: 'compute', deps: ['db'] },
{ id: 'nexus', label: '🌐 nexus', xer: 'net', deps: ['xion'] },
{ id: 'repoverse', label: '📦 repoverse', xer: 'data', deps: ['db'] },
{ id: 'fs', label: '📁 fs', xer: 'io', deps: [] },
{ id: 'sso', label: '🔑 sso', xer: 'net', deps: ['db'] },
{ id: 'security', label: '🛡 security-watch', xer: 'logic', deps: [] },
{ id: 'epoch', label: '⏱ epoch ticker', xer: 'logic', deps: ['xion'] }
];
/* ===== MOTEUR PARTAGÉ : reconstruit un « document forge » (parts 3D + panneaux-ploxions) dans un
conteneur. Utilisé par l'atelier (preview/jouer) ET par chaque ploxion forgé. ===== */
if (!window.jOSForgeStudio) window.jOSForgeStudio = {
// pulse visuel d'une part dans la scène (réaction d'entrée par défaut)
pulsePart: function (en, obj, n) { if (!obj) return; try { en.sfx(520 + (n && n.nid || 0) % 6 * 60, .08); en.particles({ x: obj.position.x, y: obj.position.y + .3, z: obj.position.z, count: 18, spread: 2.2, life: .5, color: 0x7be0c0 }); var s0 = obj.scale.x; obj.scale.setScalar(s0 * 1.35); setTimeout(function () { try { obj.scale.setScalar(s0); } catch (x) {} }, 140); } catch (x) {} },
run: function (container, doc, opts) {
opts = opts || {}; doc = doc || { nodes: [], wires: [] };
container.innerHTML = ''; if (getComputedStyle(container).position === 'static') container.style.position = 'relative';
var cv = document.createElement('canvas'); cv.style.cssText = 'width:100%;height:100%;display:block'; container.appendChild(cv);
var parts = doc.nodes.filter(function (n) { return n.type === 'part'; });
var panels = doc.nodes.filter(function (n) { return n.type === 'ploxion'; });
var mounted = [], unsubs = [], reg = {}; // reg : nid -> nœud runtime (fire/recv) = le câblage
function node(recv) { var outs = []; return { outs: outs, recv: recv || function () {}, fire: function (pl) { outs.forEach(function (f) { try { f(pl); } catch (x) {} }); } }; }
var e = jOSEngine.create(cv, { ground: false, grid: !opts.play, fog: opts.play, dist: opts.play ? 8 : 16, onReady: function (en) {
jOSKit.make(en, 'ground', { size: 140 }); if (opts.play) en.world.scene.add(new en.THREE.GridHelper(140, 70, 0x14233c, 0x0e1a2c));
var player = opts.play ? jOSKit.make(en, 'character', { mode: opts.mode || 'third' }) : null; var portals = [];
parts.forEach(function (n) { var o = Object.assign({ player: player }, n.opts || {}, { x: n.x, y: n.y, z: n.z });
var nd = node(); reg[n.nid] = nd;
if (n.part === 'coin') o.onGet = function () { nd.fire('coin'); }; // sorties : la part émet quand on interagit
if (n.part === 'trigger') o.onEnter = function () { nd.fire('enter'); };
var r = jOSKit.make(en, n.part, o); var obj = r && r.isObject3D ? r : (r && r.mesh) ? r.mesh : null;
nd.recv = function (pl) { window.jOSForgeStudio.pulsePart(en, obj, n); }; // entrée : pulse
if (n.part === 'portion') portals.push(r); });
for (var i = 0; i + 1 < portals.length; i += 2) { portals[i].to = portals[i + 1]; portals[i + 1].to = portals[i]; }
// structure de CUBES (xerboxion-core + bions + cubions/spherions)
doc.nodes.filter(function (n) { return n.cube && !n.parent; }).forEach(function (n) { var c = n.cube, isS = n.shape === 'sphere', size = n.size || 0.95, vide = n.bion === 'vide';
var geo = isS ? new en.THREE.SphereGeometry(size * 0.6, 24, 20) : new en.THREE.BoxGeometry(size, size, size);
var col = n.core ? 0x5fe0c0 : n.type === 'cubion' ? (isS ? 0xb56aff : 0xa07bff) : vide ? 0x8aa0c0 : xerColor(n.xer);
var m = new en.THREE.Mesh(geo, new en.THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: n.core ? 0.6 : (vide ? 0.06 : 0.38), metalness: 0.1, roughness: 0.35, transparent: true, opacity: vide ? 0.1 : (n.core ? 0.95 : (isS ? 0.9 : 0.82)) }));
m.add(new en.THREE.LineSegments(new en.THREE.EdgesGeometry(geo), new en.THREE.LineBasicMaterial({ color: n.core ? 0x9ff0e0 : vide ? 0xaab8d8 : 0x6fd0ff, transparent: true, opacity: 0.65 })));
m.position.set(c.x, c.y + 0.5, c.z); en.add(m); });
wireUp(); // relie tout une fois les parts prêtes
if (opts.play) { en.input.onLock = function (l) { var hi = container.querySelector('.fs__hint'); if (hi) hi.style.display = l ? 'none' : ''; };
var hint = document.createElement('div'); hint.className = 'fs__hint'; hint.textContent = '🎯 clique pour jouer · Échap/Ctrl-droit = sortir'; container.appendChild(hint);
cv.addEventListener('click', function () { try { en.input.lock(); } catch (x) {} }); }
} });
// panneaux = ploxions vivants embarqués (l'app composée d'apps)
panels.forEach(function (n) {
var p = document.createElement('div'); p.className = 'fs__panel'; p.style.left = (n.px || 20) + 'px'; p.style.top = (n.py || 20) + 'px';
var man = (window.jOSApps[n.ploxion] && window.jOSApps[n.ploxion].manifest) || { name: n.ploxion, icon: '▦' };
p.innerHTML = '<div class="fs__ph">' + (man.icon || '▦') + ' ' + (man.name || n.ploxion) + '</div><div class="fs__pb"></div>';
container.appendChild(p);
try { var inst = window.jOSApps[n.ploxion].mount(p.querySelector('.fs__pb'), {}); mounted.push(inst); } catch (x) { p.querySelector('.fs__pb').innerHTML = '<div style="padding:10px;color:#8aa">' + (man.icon || '▦') + ' ' + (man.name || n.ploxion) + '</div>'; }
var nd = node(function () { p.style.outline = '2px solid #5fe0c0'; setTimeout(function () { p.style.outline = ''; }, 220); try { jOSPorts.emit(n.ploxion, 'signal', 'forge'); } catch (x) {} }); reg[n.nid] = nd;
// SORTIE d'un ploxion = toute activité qu'il émet sur le bus (jOSPorts)
try { unsubs.push(jOSPorts.on('*', function (payload, topic) { if (topic && topic.indexOf('ploxion.' + n.ploxion + '.') === 0) nd.fire(payload); })); } catch (x) {}
dragMove(p, p.querySelector('.fs__ph'));
});
// bions : nœud « capacité » — entrée = invoquer le bion + déclencher les ploxions des FACES d'entrée ;
// sortie = l'activité des ploxions des FACES de sortie relance le nœud (I/O par face, RS-7).
doc.nodes.filter(function (n) { return n.type === 'bion'; }).forEach(function (n) {
var nd = node(function (pl) { try { var b = window[n.bion]; if (typeof b === 'function') b(pl); else if (b && typeof b.pulse === 'function') b.pulse(pl); else if (b && typeof b.emit === 'function') b.emit('forge', 'signal', pl); else if (b && typeof b.beep === 'function') b.beep(); } catch (x) {}
if (n.faces) for (var f in n.faces) { var fc = n.faces[f]; if (fc && fc.ploxion && fc.dir === 'in') { try { jOSPorts.emit(fc.ploxion, 'signal', 'face'); } catch (x) {} } } });
reg[n.nid] = nd;
if (n.faces) Object.keys(n.faces).forEach(function (f2) { var fc = n.faces[f2]; if (fc && fc.ploxion && fc.dir === 'out') { try { unsubs.push(jOSPorts.on('*', function (pl, topic) { if (topic && topic.indexOf('ploxion.' + fc.ploxion + '.') === 0) nd.fire(pl); })); } catch (x) {} } }); });
// cubions : bloc-de-bions — recv fane vers tous les membres ; toute sortie d'un membre = sortie du cubion
doc.nodes.filter(function (n) { return n.type === 'cubion'; }).forEach(function (n) { var members = n.members || []; var nd = node(function (pl) { members.forEach(function (m) { if (reg[m]) reg[m].recv(pl); }); }); reg[n.nid] = nd;
members.forEach(function (m) { if (reg[m]) reg[m].outs.push(function (pl) { nd.fire(pl); }); }); });
// plugions : docking = relais pur (recv → fire) reliant deux cubions
doc.nodes.filter(function (n) { return n.type === 'plugion'; }).forEach(function (n) { var nd = node(function (pl) { nd.fire(pl); }); reg[n.nid] = nd; });
// CÂBLAGE : chaque fil relie une sortie de nœud à l'entrée d'un autre (jOSPorts sous le capot pour les ploxions).
// Appelé une seule fois depuis onReady (après enregistrement des parts, panneaux ET bions), sinon doublons.
function wireUp() { (doc.wires || []).forEach(function (w) { var s = reg[w.from], t = reg[w.to]; if (s && t) s.outs.push(function (pl) { t.recv(pl); }); }); }
return { unmount: function () { unsubs.forEach(function (u) { try { u(); } catch (x) {} }); mounted.forEach(function (m) { try { m && m.unmount && m.unmount(); } catch (x) {} }); try { e.dispose(); } catch (x) {} container.innerHTML = ''; } };
},
/* ===== PARSEUR XOS1 (déterministe, zéro LLM) : texte .xos → modèle { nom, col, meta, quota, ploxions[], wires[] }.
Symétrique du compilateur compileXos() : ce qu'il ÉCRIT ligne par ligne, on le RELIT à l'identique.
Un ploxion = ses éléments box/txt/var/bind/btn ; son n° = l'INDEX D'ORDRE dans le fichier (0 = premier
plx.new) — c'est cet index que les câbles xos.wire adressent (comme le métal mappe index→slot). ===== */
parseXos: function (xosText) {
var model = { nom: 'OS', col: '3fe0d0', meta: {}, quota: {}, ploxions: [], wires: [] };
var cur = null; // ploxion courant (entre plx.new … plx.run)
String(xosText == null ? '' : xosText).split(/\r?\n/).forEach(function (raw) {
var t = raw.trim().split(/\s+/), op = t[0]; if (!op) return;
if (op === 'xos.new') { model.nom = t.slice(1).join(' ') || model.nom; model.ploxions = []; model.wires = []; }
else if (op === 'xos.meta') { if (t[1]) model.meta[t[1]] = t.slice(2).join(' '); }
else if (op === 'xos.col') { if (t[1]) model.col = t[1]; }
else if (op === 'xos.quota') { model.quota[+t[1]] = +t[2]; }
else if (op === 'plx.new') { cur = { title: t.slice(2).join(' ') || ('PLOXION ' + model.ploxions.length), col: model.col, vars: {}, els: [] }; model.ploxions.push(cur); } // slot (t[1]) ignoré : l'ordre fait foi
else if (op === 'plx.col') { if (cur) cur.col = t[2]; }
else if (op === 'plx.var') { if (cur) cur.vars[+t[2]] = (+t[3] || 0); }
else if (op === 'plx.box') { if (cur) cur.els.push({ k: 'box', x: +t[2], y: +t[3], w: +t[4], h: +t[5], col: t[6] || '8aa0c0' }); }
else if (op === 'plx.txt') { if (cur) cur.els.push({ k: 'txt', x: +t[2], y: +t[3], sz: (+t[4] || 1), text: t.slice(5).join(' ') }); }
else if (op === 'plx.btn') { if (cur) cur.els.push({ k: 'btn', x: +t[2], y: +t[3], w: +t[4], h: +t[5], vi: (+t[6] || 0), delta: (+t[7] || 1), label: t.slice(8).join(' ') || 'ENERGIE' }); }
else if (op === 'plx.bind') { if (cur) cur.els.push({ k: 'bind', x: +t[2], y: +t[3], sz: (+t[4] || 1), vi: (+t[5] || 0) }); }
else if (op === 'plx.run') { cur = null; }
else if (op === 'xos.wire') { model.wires.push({ ia: +t[1], va: +t[2], ib: +t[3], vb: +t[4], delta: (+t[5] || 1) }); }
});
return model;
},
/* ===== RUNTIME WEB d'un OS forgé : rejoue un .xos DANS LE NAVIGATEUR (pas que sur le métal QEMU).
Chaque ploxion → une carte chill-tekk (sombre, néon, coins doux) dans une grille responsive ;
un btn incrémente SA var (var[vi] += delta) + re-render du bind ; PUIS les câbles xos.wire à
UN SAUT (pas de transitivité) : var<va> de <ia> bougée → var<vb> de <ib> += delta, re-render —
le MÊME comportement prouvé sur le kernel (cliquer ENERGIE du réacteur incrémente l'écran).
Retourne une session { unmount } comme run(). Mobile-first : cartes qui wrappent, cibles ≥44px. ===== */
runXos: function (container, xosText, opts) {
opts = opts || {}; var self = this; var model = self.parseXos(xosText);
function esc(s) { return window.jOSb.esc(s); }
function hx(c, d) { c = String(c == null ? '' : c).replace(/[^0-9a-fA-F]/g, ''); return c.length === 6 ? ('#' + c) : (d || '#5fe0c0'); }
// CSS injecté UNE fois (zéro CDN) — coins doux + boutons ≥44px pour le tactile iPhone
if (!document.getElementById('josxos-css')) {
var st = document.createElement('style'); st.id = 'josxos-css';
st.textContent = '.xosr{display:flex;flex-direction:column;gap:12px;padding:12px;box-sizing:border-box;min-height:100%;font-family:ui-sans-serif,system-ui;color:#dfe7ff}'
+ '.xosr__hd{display:flex;align-items:center;gap:8px;font-weight:800;flex-wrap:wrap}'
+ '.xosr__dot{width:11px;height:11px;border-radius:50%;flex:0 0 auto;box-shadow:0 0 8px currentColor}'
+ '.xosr__grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:12px;align-content:start}'
+ '.xosr__card{background:linear-gradient(160deg,#0d1424,#080c16);border:1px solid #22344f;border-radius:14px;padding:11px;display:flex;flex-direction:column;gap:9px;box-shadow:0 6px 18px rgba(0,0,0,.35);min-width:0}'
+ '.xosr__t{display:flex;align-items:center;gap:7px;font-weight:700;font-size:.86rem;min-width:0}'
+ '.xosr__t .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}'
+ '.xosr__q{margin-left:auto;font-size:.6rem;color:#7f93bd;border:1px solid #22344f;border-radius:20px;padding:1px 7px;flex:0 0 auto}'
+ '.xosr__chips{display:flex;flex-wrap:wrap;gap:6px}'
+ '.xosr__chip{font-size:.64rem;color:#04120e;font-weight:800;border-radius:7px;padding:4px 8px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
+ '.xosr__desc{font-size:.66rem;color:#7f93bd;line-height:1.35}'
+ '.xosr__ctrl{display:flex;flex-wrap:wrap;gap:8px;align-items:stretch;margin-top:2px}'
+ '.xosr__btn{cursor:pointer;border:0;border-radius:10px;background:#5fe0c0;color:#04120e;font:inherit;font-weight:800;font-size:.74rem;padding:0 14px;min-height:44px;flex:1 1 120px}'
+ '.xosr__btn:active{transform:translateY(1px)}'
+ '.xosr__read{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:44px;min-width:56px;padding:4px 12px;border-radius:10px;background:#0c1626;border:1px solid #2a3a62;flex:0 0 auto}'
+ '.xosr__read b{font-size:1.15rem;font-weight:800;color:#8ff0d8;line-height:1}'
+ '.xosr__read span{font-size:.52rem;color:#7f93bd;letter-spacing:.06em;text-transform:uppercase;margin-top:3px}'
+ '.xosr__pulse{animation:xosrpulse .5s ease}'
+ '@keyframes xosrpulse{0%{box-shadow:0 0 0 0 rgba(95,224,192,.55)}100%{box-shadow:0 0 0 14px rgba(95,224,192,0)}}'
+ '.xosr__empty{color:#7f93bd;padding:22px;text-align:center}';
(document.head || document.documentElement).appendChild(st);
}
container.innerHTML = ''; if (getComputedStyle(container).position === 'static') container.style.position = 'relative';
var root = document.createElement('div'); root.className = 'xosr'; container.appendChild(root);
root.innerHTML = '<div class="xosr__hd"><span class="xosr__dot" style="color:' + hx(model.col) + ';background:' + hx(model.col) + '"></span><span class="nm">🧿 ' + esc(model.nom) + '</span> <span style="font-weight:500;color:#7f93bd;font-size:.72rem">· ' + model.ploxions.length + ' ploxions · ' + model.wires.length + ' câbles</span></div>';
if (!model.ploxions.length) { root.innerHTML += '<div class="xosr__empty">OS vide (aucun ploxion).</div>'; return { unmount: function () { try { container.innerHTML = ''; } catch (x) {} }, model: model }; }
var grid = document.createElement('div'); grid.className = 'xosr__grid'; root.appendChild(grid);
// une carte par ploxion : les box (couleur+label) en chips, les txt libres en description, les btn/bind en contrôles
model.ploxions.forEach(function (p, pi) {
var boxes = p.els.filter(function (e2) { return e2.k === 'box'; });
var txts = p.els.filter(function (e2) { return e2.k === 'txt'; });
var btns = p.els.filter(function (e2) { return e2.k === 'btn'; });
var binds = p.els.filter(function (e2) { return e2.k === 'bind'; });
var usedTxt = {}; // un txt à (box.x+3, box.y+7) = le LABEL de cette box (layout du compilateur) ; le reste = description
function labelFor(b) { for (var i = 0; i < txts.length; i++) { if (usedTxt[i]) continue; var tx = txts[i]; if (Math.abs(tx.x - (b.x + 3)) <= 5 && Math.abs(tx.y - (b.y + 7)) <= 12) { usedTxt[i] = 1; return tx.text; } } return ''; }
var chips = boxes.map(function (b) { var lab = labelFor(b); return '<span class="xosr__chip" style="background:' + hx(b.col, '#8aa0c0') + '">' + (esc(lab) || '▢') + '</span>'; }).join('');
var desc = txts.filter(function (tx, i) { return !usedTxt[i]; }).map(function (tx) { return '<div class="xosr__desc">' + esc(tx.text) + '</div>'; }).join('');
var ctrl = btns.map(function (b, bi) { return '<button class="xosr__btn" data-bp="' + pi + '" data-bi="' + bi + '">⚡ ' + esc(b.label) + '</button>'; }).join('')
+ binds.map(function (bd) { return '<div class="xosr__read" data-rp="' + pi + '" data-rvi="' + bd.vi + '"><b data-rval>' + esc(p.vars[bd.vi] || 0) + '</b><span>var ' + bd.vi + '</span></div>'; }).join('');
var q = model.quota[pi]; var qHtml = (q != null && !isNaN(q)) ? '<span class="xosr__q">' + esc(q) + ' bions</span>' : '';
var card = document.createElement('div'); card.className = 'xosr__card'; card.setAttribute('data-card', pi);
card.innerHTML = '<div class="xosr__t"><span class="xosr__dot" style="color:' + hx(p.col) + ';background:' + hx(p.col) + '"></span><span class="nm">' + esc(p.title) + '</span>' + qHtml + '</div>'
+ (chips ? '<div class="xosr__chips">' + chips + '</div>' : '') + desc + (ctrl ? '<div class="xosr__ctrl">' + ctrl + '</div>' : '');
grid.appendChild(card);
});
function renderBinds(pi, vi) { var p = model.ploxions[pi]; if (!p) return; var val = (p.vars[vi] || 0);
[].forEach.call(root.querySelectorAll('.xosr__read[data-rp="' + pi + '"][data-rvi="' + vi + '"] [data-rval]'), function (rv) { rv.textContent = val; }); }
function pulseCard(pi) { var c = root.querySelector('[data-card="' + pi + '"]'); if (!c) return; c.classList.remove('xosr__pulse'); void c.offsetWidth; c.classList.add('xosr__pulse'); }
// LES CÂBLES (redstone 1 saut) : var<va> de <ia> bougée → var<vb> de <ib> += delta, re-render du bind cible
function fireWires(ia, va) { (model.wires || []).forEach(function (w) { if (w.ia !== ia || w.va !== va) return; var tp = model.ploxions[w.ib]; if (!tp) return;
tp.vars[w.vb] = (tp.vars[w.vb] || 0) + w.delta; renderBinds(w.ib, w.vb); pulseCard(w.ib);
try { window.jOSPorts && jOSPorts.emit('xos', 'wire', JSON.stringify({ nom: model.nom, ia: ia, va: va, ib: w.ib, vb: w.vb, delta: w.delta })); } catch (x) {}
try { window.jOSTsoin && jOSTsoin.mark && jOSTsoin.mark('xos.wire', { nom: model.nom, ia: ia, ib: w.ib, delta: w.delta }); } catch (x) {} }); }
[].forEach.call(grid.querySelectorAll('[data-bi]'), function (bEl) { bEl.addEventListener('click', function () {
var pi = +bEl.getAttribute('data-bp'), bi = +bEl.getAttribute('data-bi'); var p = model.ploxions[pi]; if (!p) return;
var btn = p.els.filter(function (e2) { return e2.k === 'btn'; })[bi]; if (!btn) return;
p.vars[btn.vi] = (p.vars[btn.vi] || 0) + btn.delta; renderBinds(pi, btn.vi); // le bouton bouge SA var + affiche
bEl.classList.remove('xosr__pulse'); void bEl.offsetWidth; bEl.classList.add('xosr__pulse');
fireWires(pi, btn.vi); }); }); // PUIS le redstone vers les autres ploxions
try { window.jOSTsoin && jOSTsoin.mark && jOSTsoin.mark('xos.run', { nom: model.nom, ploxions: model.ploxions.length, wires: model.wires.length }); } catch (x) {}
try { window.jOSPorts && jOSPorts.emit('xos', 'run', JSON.stringify({ nom: model.nom, ploxions: model.ploxions.length, wires: model.wires.length })); } catch (x) {}
return { unmount: function () { try { container.innerHTML = ''; } catch (x) {} }, model: model };
}
};
function dragMove(el, handle) { handle.addEventListener('pointerdown', function (ev) { if (ev.target.classList.contains('x')) return; ev.preventDefault(); var sx = ev.clientX, sy = ev.clientY, ox = el.offsetLeft, oy = el.offsetTop;
function mv(e2) { el.style.left = (ox + e2.clientX - sx) + 'px'; el.style.top = (oy + e2.clientY - sy) + 'px'; } function up() { document.removeEventListener('pointermove', mv); document.removeEventListener('pointerup', up); }
document.addEventListener('pointermove', mv); document.addEventListener('pointerup', up); }); }
/* ===== BIBLIOTHÈQUE : tout le xerboxion comme palette ===== */
function partItems() { return (window.jOSKit ? jOSKit.parts : []).map(function (p) { return { kind: 'part', id: p, label: p, icon: '🧩' }; }); }
function ploxionItems() { var out = [], seen = {}; try { (window.__PLOXIONS__ || []).forEach(function (p) { if (p && p.id) { seen[p.id] = 1; out.push({ kind: 'ploxion', id: p.id, label: p.name || p.id, icon: p.icon || '▦' }); } }); } catch (x) {}
try { Object.keys(window.jOSApps || {}).forEach(function (id) { if (seen[id] || id === 'mega-forge') return; var m = (jOSApps[id].manifest) || {}; out.push({ kind: 'ploxion', id: id, label: m.name || id, icon: m.icon || '▦' }); }); } catch (x) {}
return out.sort(function (a, b) { return a.label.localeCompare(b.label); }); }
// BLOCS SYSTÈME (RS-7) : le xion, le nexus, le xerboxion + les liens (cubion-link, ploxion-link, plugion)
var SYS = [{ id: 'xion', label: '⚛ xion (bus)', icon: '⚛' }, { id: 'nexus', label: '🌐 nexus', icon: '🌐' }, { id: 'xerboxion', label: '🔮 xerboxion', icon: '🔮' }, { id: 'cubion-link', label: '🔗 cubion-link', icon: '🔗' }, { id: 'ploxion-link', label: '⛓ ploxion-link', icon: '⛓' }, { id: 'plugion', label: '🔌 plugion', icon: '🔌' }];
// + blocs 3D RÉELS (RS-7 : « brancher OpenSCAD, PCB, tout ce qui fait de la 3D »)
var THREED = [{ id: 'openscad', label: '🖨 openscad (3D)', icon: '🖨' }, { id: 'pcb', label: '🔌 pcb', icon: '🔌' }];
var SYSXER = { xion: 'net', nexus: 'net', xerboxion: 'compute', 'cubion-link': 'io', 'ploxion-link': 'io', plugion: 'logic', openscad: 'io', pcb: 'compute' };
// Ce que FAIT chaque bloc système (affiché dans l'inspecteur, à côté des ports réels de jOSSysBlocks).
var SYSDOC = { xion: 'tap live sur le bus xion (jOSPorts) — écoute et réémet vers l\'aval', nexus: 'push/pull réel vers le nexus (jOSNexus) — pont vers le 2e VPS', 'cubion-link': 'liaison typée de 2 cubions : ne fane que vers les bions partagés', 'ploxion-link': 'ouvre/relie un ploxion (jOS.openPloxion) au signal', 'xerboxion-core': 'source d\'énergie racine : émet « power » dans tout le graphe', plugion: 'docking : relais pur reliant deux cubions' };
function bionItems() { var out = []; try { Object.keys(window).forEach(function (k) { if (/^jOS[A-Z]/.test(k) && k !== 'jOSApps' && (typeof window[k] === 'object' || typeof window[k] === 'function')) out.push({ kind: 'bion', id: k, label: k, icon: '🧬' }); }); } catch (x) {} out.sort(function (a, b) { return a.label.localeCompare(b.label); });
var head = [{ id: 'vide', label: '▢ bloc vide (structure)', icon: '▢' }].concat(SYS).concat(THREED).map(function (s) { return { kind: 'bion', id: s.id, label: s.label, icon: s.icon }; });
return head.concat(out); }
function exampleItems() { return [{ kind: 'exemple', id: '__boxion__', label: '🖥 vue du boxion', icon: '🖥' }, { kind: 'exemple', id: '__xerboxion__', label: '🔮 reconstruire le xerboxion', icon: '🔮' }].concat(Object.keys(EXAMPLES).map(function (k) { return { kind: 'exemple', id: k, label: EXAMPLES[k].label, icon: '📦' }; })); }
// KIONS (Vague 3, de forge-kion) : window.jOSKion = le renderer géométrique du kion (carré de koins) ; on
// liste les kions PAR NOMBRE DE KOINS (1kion→octakion via jOSKion.name) + wormion/portion, posables comme
// des cubes-bions (brushBion). Si jOSKionFloat existe : ses atomes flottants (bouton/label/knob…) en bonus.
function kionItems() { if (!window.jOSKion && !window.jOSKionFloat) return [{ kind: 'kion', id: '', label: '⬡ jOSKion absent', icon: '⬡', dis: 1 }];
var out = [];
if (window.jOSKion) { for (var n = 1; n <= 8; n++) { var nm = ''; try { nm = String(jOSKion.name(n) || ''); } catch (x) {} out.push({ kind: 'kion', id: 'kion-' + n, label: '⬡ ' + (nm || (n + 'kion')) + ' · ' + n + ' koins', icon: '⬡' }); }
out.push({ kind: 'kion', id: 'wormion', label: '◯ wormion', icon: '◯' }); out.push({ kind: 'kion', id: 'portion', label: '▢ portion', icon: '▢' }); }
if (window.jOSKionFloat && jOSKionFloat.TYPES) { try { (jOSKionFloat.TYPES || []).forEach(function (t) { out.push({ kind: 'kfloat', id: t, label: '✦ ' + t + ' (flottant)', icon: '✦' }); }); } catch (x) {} }
return out.length ? out : [{ kind: 'kion', id: '', label: '⬡ aucun kion', icon: '⬡', dis: 1 }]; }
// JEUX (Vague 3, de forge-jeu) : window.jOSGames.list() = registre des jeux du xerboxion (arcade/doom/
// découverte/minecraft/logique + archétypes moteur). Posables comme panneaux jouables (voir addGame).
function gameItems() { if (!window.jOSGames || typeof jOSGames.list !== 'function') return [{ kind: 'game', id: '', label: '🎮 jOSGames absent', icon: '🎮', dis: 1 }];
var out = []; try { (jOSGames.list() || []).forEach(function (g) { out.push({ kind: 'game', id: g.id, label: (g.icon || '🎮') + ' ' + (g.name || g.id), icon: g.icon || '🎮' }); }); } catch (x) {}
return out.length ? out : [{ kind: 'game', id: '', label: '🎮 aucun jeu', icon: '🎮', dis: 1 }]; }
function mount(container, ctx) {
if (!window.jOSEngine || !window.jOSKit) { container.innerHTML = '<div style="padding:16px;color:#8aa">jOSEngine / jOSKit absents.</div>'; return { unmount: function () { container.innerHTML = ''; } }; }
var seedPloxion = ctx && ctx.seed ? ctx.seed : null; // RS-7 : la forge s'ouvre DEPUIS un ploxion (partir de lui pour forger plus loin)
var doc = { nodes: [], wires: [] }, nid = 1, sel = null, tab = 'bion', pending = null, brushBion = null, viewMode = 'scene', cells = {}, e = null, ground = null, ray = null, ndc = null, ghost = null, camDrag = null, forgeIO = window.__PLOXION_IO__ || null;
try { var saved = JSON.parse(localStorage.getItem('forge:doc') || 'null'); if (saved && saved.nodes) doc = saved; } catch (x) {}
doc.wires = doc.wires || []; doc.nodes.forEach(function (n) { if (n.nid >= nid) nid = n.nid + 1; });
// ===== CONSTRUCTEUR DE CUBES (RS-7) : on part du cube xerboxion-core, on ajoute des cubes-bions
// autour ; un amas connecté = un plus gros cube (cubion) ; selon le nb de bions → collapse en Spherion. =====
function cellKey(x, y, z) { return x + ',' + y + ',' + z; }
// CHAQUE FACE = une fonction (RS-7). +axes = sorties, -axes = entrées → coller un cube crée LA bonne
// connexion selon la face touchée (le câblage devient spatial). Le signal circule dans le sens +.
var FACEFN = { up: { dir: 'out', port: 'up' }, east: { dir: 'out', port: 'east' }, north: { dir: 'out', port: 'north' }, down: { dir: 'in', port: 'down' }, west: { dir: 'in', port: 'west' }, south: { dir: 'in', port: 'south' } };
function faceName(x, y, z) { return y > 0 ? 'up' : y < 0 ? 'down' : x > 0 ? 'east' : x < 0 ? 'west' : z > 0 ? 'north' : 'south'; }
function opposite(f) { return { up: 'down', down: 'up', east: 'west', west: 'east', north: 'south', south: 'north' }[f]; }
function connectByFace(A, B, fx, fy, fz) { var fa = faceName(fx, fy, fz), fb = opposite(fa), da = FACEFN[fa], db = FACEFN[fb], w = null;
if (da.dir === 'out' && db.dir === 'in') { w = { from: A.nid, fromPort: da.port, to: B.nid, toPort: db.port }; doc.wires.push(w); }
else if (da.dir === 'in' && db.dir === 'out') { w = { from: B.nid, fromPort: db.port, to: A.nid, toPort: da.port }; doc.wires.push(w); }
if (w) logAct({ act: 'wire', from: w.from, fromPort: w.fromPort, to: w.to, toPort: w.toPort }); refreshWireIfOpen(); }
function markTsoin(act, d) { try { window.jOSTsoin && jOSTsoin.mark && jOSTsoin.mark('forge.' + act, d); } catch (x) {} }
function reindexCells() { cells = {}; doc.nodes.forEach(function (n) { if (n.cube && !n.parent) cells[cellKey(n.cube.x, n.cube.y, n.cube.z)] = n.nid; }); }
function spawnCubeMesh(n) { if (!e || !e.THREE || n._cube) return; var T = e.THREE, c = n.cube, isS = n.shape === 'sphere', size = n.size || 0.95;
var geo = isS ? new T.SphereGeometry(size * 0.6, 24, 20) : new T.BoxGeometry(size, size, size);
var vide = n.bion === 'vide';
var col = n.core ? 0x5fe0c0 : n.type === 'cubion' ? (isS ? 0xb56aff : 0xa07bff) : vide ? 0x8aa0c0 : xerColor(n.xer);
var op = vide ? 0.1 : (n.core ? 0.95 : (isS ? 0.9 : 0.82));
var m = new T.Mesh(geo, new T.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: n.core ? 0.6 : (vide ? 0.06 : 0.38), metalness: 0.1, roughness: 0.35, transparent: true, opacity: op }));
m.add(new T.LineSegments(new T.EdgesGeometry(geo), new T.LineBasicMaterial({ color: n.core ? 0x9ff0e0 : vide ? 0xaab8d8 : 0x6fd0ff, transparent: true, opacity: 0.65 }))); // arêtes néon = look hologramme
m.position.set(c.x, c.y + 0.5, c.z); m.userData.nid = n.nid; e.add(m); n._cube = m; }
function rebuildCubes() { if (!doc.nodes.some(function (n) { return n.core; })) { var core = { nid: nid++, type: 'bion', bion: 'xerboxion-core', core: true, cube: { x: 0, y: 0, z: 0 }, name: 'xerboxion-core' }; doc.nodes.push(core); }
doc.nodes.forEach(function (n) { if (n.cube && !n.parent) spawnCubeMesh(n); }); reindexCells(); updateCount(); }
function addBionCube(bion, x, y, z) { if (cells[cellKey(x, y, z)]) return null; var n = { nid: nid++, type: 'bion', bion: bion, cube: { x: x, y: y, z: z }, name: bion }; if (SYSXER[bion]) n.xer = SYSXER[bion];
doc.nodes.push(n); cells[cellKey(x, y, z)] = n.nid; spawnCubeMesh(n); markTsoin('cube', { bion: bion, x: x, y: y, z: z }); logAct({ act: 'cube', bion: bion, x: x, y: y, z: z }); select(n); renderTree(); refreshWireIfOpen(); updateCount(); return n; }
// ENREGISTREMENT DU BUILD (Vague 0) : chaque geste réel → jOSForgeLog (persisté, rejouable). Fallback
// tableau local buildLog si le moteur est absent. `replaying` coupe l'enregistrement pendant un rejeu.
function logAct(a) { if (replaying) return; if (window.jOSForgeLog && jOSForgeLog.push) { try { jOSForgeLog.push(a); } catch (x) {} } else { buildLog.push(a); } snapshot(); }
// SIMULER : fait couler la donnée typée dans le graphe (jOSBionSim, déterministe) → allume les cubes
// sous tension, affiche leur valeur près du cube, marque en rouge les câbles de types incompatibles.
function runSim() {
if (!window.jOSBionSim || !jOSBionSim.run) { // FALLBACK : ancien pulse redstone si le moteur manque
var srcs = doc.nodes.filter(function (n) { return n.cube && !n.parent && (n.core || !(doc.wires || []).some(function (w) { return w.to === n.nid; })); }); srcs.forEach(function (n) { powerCube(n, 0, {}); }); return null; }
var r = null; try { r = jOSBionSim.run(doc, { io: forgeIO }); } catch (x) { return null; }
lastSim = r; applySim(r); return r; }
function applySim(r) { if (!r) return; var on = {}; (r.active || []).forEach(function (id) { on[id] = 1; });
doc.nodes.forEach(function (n) { if (!n._cube || !n._cube.material) return; var base = n.core ? 0.6 : (n.bion === 'vide' ? 0.06 : 0.38); n._cube.material.emissiveIntensity = on[n.nid] ? 1.3 : base; }); // cubes allumés = émissifs
renderSimHud(r);
if (viewMode === 'wire') { try { drawWires(); } catch (x) {} } else if (viewMode === '2d') { try { render2D(); } catch (x) {} } // câbles dropped en rouge
if (hintEl) hintEl.textContent = '🔬 simulation · ' + (r.active || []).length + ' cubes sous tension · ' + (r.dropped || []).length + ' câbles incompatibles' + (r.cyclic ? ' · cycle' : ''); }
// labels de valeur projetés au-dessus de chaque cube (vue 3D uniquement)
function renderSimHud(r) { if (!simHud) { simHud = document.createElement('div'); simHud.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:5;overflow:hidden'; if (view) view.appendChild(simHud); }
if (viewMode !== 'scene' || !e || !e.THREE || !e.world || !e.world.camera) { simHud.innerHTML = ''; return; }
var cam = e.world.camera, T = e.THREE, w = cv.clientWidth, h = cv.clientHeight, html = '';
doc.nodes.forEach(function (n) { if (!n._cube || n.parent) return; var val = r.values ? r.values[n.nid] : null; if (val == null) return;
var v = new T.Vector3(n.cube.x, n.cube.y + 0.5, n.cube.z); v.project(cam); if (v.z > 1) return;
var sx = Math.round((v.x * 0.5 + 0.5) * w), sy = Math.round((-v.y * 0.5 + 0.5) * h); var lit = r.active && r.active.indexOf(n.nid) >= 0;
html += '<div style="position:absolute;left:' + sx + 'px;top:' + sy + 'px;transform:translate(-50%,-150%);padding:1px 5px;border-radius:6px;white-space:nowrap;font:.6rem ui-monospace;background:rgba(5,7,14,.82);color:' + (lit ? '#8ff0d8' : '#7f93bd') + ';border:1px solid ' + (lit ? '#2a6a5a' : '#22344f') + '">' + xesc(typeof val === 'number' ? (Math.round(val * 100) / 100) : val) + '</div>'; });
simHud.innerHTML = html; }
function clearSimHud() { if (simHud) simHud.innerHTML = ''; doc.nodes.forEach(function (n) { if (n._cube && n._cube.material) n._cube.material.emissiveIntensity = n.core ? 0.6 : (n.bion === 'vide' ? 0.06 : 0.38); }); if (viewMode === 'wire') { try { drawWires(); } catch (x) {} } }
function toggleSim() { var b = container.querySelector('[data-sim]'); if (simTimer) { clearInterval(simTimer); simTimer = null; lastSim = null; b.textContent = '🔬 simuler'; clearSimHud(); return; }
b.textContent = '⏹ stop'; runSim(); simTimer = setInterval(runSim, 1600); }
// REJOUER : rejoue le PROCESSUS de construction depuis jOSForgeLog (poses de cubes, collapses, docks…),
// via jOSForgeLog.replay(log, applyFn, {speed}). Fallback buildLog local si le moteur est absent.
function replayApply(a) { if (!a) return; if (a.act === 'cube') addBionCube(a.bion, a.x, a.y, a.z); else if (a.act === 'collapse') collapse(); else if (a.act === 'autodock') autoDock(); }
function replayBuild() { var log = (window.jOSForgeLog && jOSForgeLog.list) ? jOSForgeLog.list() : buildLog.slice(); if (!log.length) return;
doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }).forEach(function (n) { removeNode(n); }); // repartir du core
replaying = true;
if (window.jOSForgeLog && jOSForgeLog.replay) { jOSForgeLog.replay(log, replayApply, { speed: 260 }).then(function () { replaying = false; }); }
else { var i = 0; (function step() { if (i >= log.length) { replaying = false; return; } replayApply(log[i++]); setTimeout(step, 260); })(); } }
// ⏱ SCRUBBER (Premiere) sur le forgelog (Vague 1) : glisser = revoir la construction étape par étape.
// onSeek(i) rejoue le build jusqu'à l'action i (repart du core). Démonté (destroy) à la fermeture.
function seekBuild(idx) { var log = (window.jOSForgeLog && jOSForgeLog.list) ? jOSForgeLog.list() : buildLog.slice();
replaying = true;
try { doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }).forEach(function (n) { removeNode(n); });
for (var i = 0; i <= idx && i < log.length; i++) { replayApply(log[i]); } } catch (x) {}
replaying = false; }
function timelineOverlay() { if (!window.jOSTimeline || !jOSTimeline.mount) return;
var log = (window.jOSForgeLog && jOSForgeLog.list) ? jOSForgeLog.list() : buildLog.slice();
var ov = document.createElement('div'); ov.style.cssText = 'position:absolute;left:0;right:0;bottom:0;z-index:13;background:#080c16;border-top:1px solid #16233c;padding:8px';
var bar = document.createElement('div'); bar.style.cssText = 'display:flex;align-items:center;gap:8px;margin-bottom:6px';
bar.innerHTML = '<b style="font-size:.74rem">⏱ processus de construction</b><span class="fs__muted">' + log.length + ' étapes — glisse pour revoir</span><span style="flex:1"></span>';
var close = document.createElement('button'); close.className = 'fs__b sec'; close.textContent = '✕ fermer'; bar.appendChild(close);
var host = document.createElement('div'); ov.appendChild(bar); ov.appendChild(host); ensureOverlayHost().appendChild(ov);
if (tlSess) { try { tlSess.destroy(); } catch (x) {} tlSess = null; }
try { tlSess = jOSTimeline.mount(host, { actions: log, labelOf: function (a, i) { return (a && (a.act || a.type)) ? ((a.act || a.type) + (a.bion ? ':' + a.bion : '')) : ('#' + (i + 1)); }, onSeek: function (i) { seekBuild(i); } }); } catch (x) {}
close.addEventListener('click', function () { if (tlSess) { try { tlSess.destroy(); } catch (x) {} tlSess = null; } try { ov.remove(); } catch (x) {} }); }
function cubeCount() { return doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }).length; }
function updateCount() { if (!hintEl) return; var c = cubeCount(); var cam = ' · molette=zoom, clic-milieu=orbite · dbl-clic=entrer dans le bion (fractal)';
hintEl.textContent = (brushBion ? ('clique une FACE pour ajouter « ' + brushBion + ' » (clic-droit=casser) · ' + c + ' bions · ⬛ collapser ≥12→Spherion') : ('cube xerboxion-core au centre — choisis un bion (biblio) → clique une face · ' + c + ' bions')) + cam; }
// COLLAPSE : l'amas de cubes-bions → un plus gros cube (cubion) ou une SPHÈRE (spherion) selon le nombre.
function collapse() { var cubes = doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }); if (cubes.length < 2) { updateCount(); return; }
var cx = 0, cy = 0, cz = 0; cubes.forEach(function (n) { cx += n.cube.x; cy += n.cube.y; cz += n.cube.z; }); var count = cubes.length; cx = Math.round(cx / count); cy = Math.round(cy / count); cz = Math.round(cz / count);
var sphere = count >= 12, side = Math.max(1.3, Math.cbrt(count) * 1.1);
cubes.forEach(function (n) { if (n._cube) { try { e.world.scene.remove(n._cube); } catch (x) {} n._cube = null; } n.parent = 'c' + nid; });
var cub = { nid: nid++, type: 'cubion', name: sphere ? 'spherion' : 'cubion', members: cubes.map(function (n) { return n.nid; }), cube: { x: cx, y: cy, z: cz }, shape: sphere ? 'sphere' : 'cube', size: side, count: count };
cubes.forEach(function (n) { n.parent = cub.nid; });
(doc.wires || []).forEach(function (w) { var fi = cub.members.indexOf(w.from) >= 0, ti = cub.members.indexOf(w.to) >= 0; if (fi && ti) return; if (fi) { w.from = cub.nid; w.fromPort = 'out'; } if (ti) { w.to = cub.nid; w.toPort = 'in'; } });
doc.nodes.push(cub); spawnCubeMesh(cub); reindexCells(); markTsoin('collapse', { into: cub.name, count: count }); logAct({ act: 'collapse', into: cub.name, count: count }); select(cub); renderTree(); refreshWireIfOpen(); updateCount(); }
// REDSTONE : un signal se propage à travers les blocs CONNECTÉS (par les faces), les allumant en aval.
function powerCube(n, depth, seen) { if (!n) return; seen = seen || {}; if (seen[n.nid] || depth > 16) return; seen[n.nid] = 1;
var m = n._cube; if (m && m.material) { var e0 = m.material.emissiveIntensity; m.material.emissiveIntensity = 1.4; setTimeout(function () { try { m.material.emissiveIntensity = e0; } catch (x) {} }, 300); }
if (depth === 0) markTsoin('signal', { from: n.nid });
(doc.wires || []).filter(function (w) { return w.from === n.nid; }).forEach(function (w) { var t = byId(w.to); if (t) setTimeout(function () { powerCube(t, depth + 1, seen); }, 150); }); }
// RANGER : compacte l'amas de cubes-bions en boule autour du core (optimise le futur cubion).
// AUTO-DOCKING (RS-7) : le mécanisme de docking s'automatise — relie toute paire de blocs ADJACENTS
// par leur face touchante (CubionLink : chaque bloc offre ses I/O, les compatibles s'accrochent), et
// appaire les plugions non connectés (dock↔dock). Reconstruit tout le graphe de connexions d'un coup.
function wireExists(a, b) { return (doc.wires || []).some(function (w) { return (w.from === a.nid && w.to === b.nid) || (w.from === b.nid && w.to === a.nid); }); }
function autoDock() { reindexCells(); var added = 0;
doc.nodes.filter(function (n) { return n.cube && !n.parent; }).forEach(function (a) { [[1, 0, 0], [0, 1, 0], [0, 0, 1]].forEach(function (o) { var b = byId(cells[cellKey(a.cube.x + o[0], a.cube.y + o[1], a.cube.z + o[2])]); if (b && !wireExists(a, b)) { connectByFace(a, b, o[0], o[1], o[2]); added++; } }); });
var plugs = doc.nodes.filter(function (n) { return n.type === 'plugion' && !n.parent; });
for (var i = 0; i < plugs.length; i++) { if ((doc.wires || []).some(function (w) { return w.from === plugs[i].nid || w.to === plugs[i].nid; })) continue; for (var j = i + 1; j < plugs.length; j++) { if (!wireExists(plugs[i], plugs[j])) { doc.wires.push({ from: plugs[i].nid, fromPort: 'dock', to: plugs[j].nid, toPort: 'dock' }); added++; break; } } }
markTsoin('autodock', { added: added }); logAct({ act: 'autodock', added: added }); refreshWireIfOpen(); updateCount(); }
// VUE ÉCLATÉE / FUSION : écarte (ou rassemble) les cubes depuis le centre, sans changer leur cellule logique.
function applyExplode() { var cubes = doc.nodes.filter(function (n) { return n._cube; }); if (!cubes.length) return; var cx = 0, cy = 0, cz = 0; cubes.forEach(function (n) { cx += n.cube.x; cy += n.cube.y; cz += n.cube.z; }); var k = cubes.length; cx /= k; cy /= k; cz /= k;
cubes.forEach(function (n) { var c = n.cube; n._cube.position.set(cx + (c.x - cx) * (1 + explodeF), (cy + (c.y - cy) * (1 + explodeF)) + 0.5, cz + (c.z - cz) * (1 + explodeF)); }); }
function cycleExplode() { explodeF = explodeF >= 1.6 ? 0 : (explodeF + 0.8); applyExplode(); var b = container.querySelector('[data-explode]'); if (b) b.textContent = explodeF === 0 ? '💥 éclater' : explodeF >= 1.6 ? '🧲 fusion' : '💥 +'; }
function ranger() { explodeF = 0; var cubes = doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }).sort(function (a, b) { return String(a.xer).localeCompare(String(b.xer)); }); if (!cubes.length) return;
var core = doc.nodes.filter(function (n) { return n.core; })[0]; var ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
var offs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], vis = {}, ring = [[ox, oy, oz]], targets = []; vis[cellKey(ox, oy, oz)] = 1;
while (targets.length < cubes.length && ring.length) { var next = []; ring.forEach(function (c) { offs.forEach(function (o) { var p = [c[0] + o[0], c[1] + o[1], c[2] + o[2]], k = cellKey(p[0], p[1], p[2]); if (!vis[k]) { vis[k] = 1; targets.push(p); next.push(p); } }); }); ring = next; }
cubes.forEach(function (n, i) { var t = targets[i]; if (t) { n.cube = { x: t[0], y: t[1], z: t[2] }; if (n._cube) n._cube.position.set(t[0], t[1] + 0.5, t[2]); } });
reindexCells(); updateCount(); markTsoin('ranger', { count: cubes.length }); }
// ===== 🔗 LIER (Vague 3, de cubionlink/craftion) : relie 2 cubions par leur NOYAU COMMUN = les
// types de bions présents dans les DEUX (intersection). Sans noyau commun, pas de lien (honnête).
// Sélection = les cubions marqués (selM, vue Logique) ; sinon les 2 cubions du doc s'il n'y en a que 2.
function bionTypesOf(cub) { var s = {}; (cub && cub.members || []).forEach(function (m) { var mn = byId(m); if (mn && mn.bion) s[mn.bion] = 1; }); return s; }
function lierCubions() { var cubs = selM.map(byId).filter(function (n) { return n && n.type === 'cubion'; });
if (cubs.length < 2) { var all = doc.nodes.filter(function (n) { return n.type === 'cubion' && !n.parent; }); if (all.length === 2) cubs = all; }
if (cubs.length < 2) { if (hintEl) hintEl.textContent = '🔗 marque 2 cubions (vue 🔗 Logique) puis 🔗 lier'; setView('wire'); return; }
var A = cubs[0], B = cubs[1], sa = bionTypesOf(A), sb = bionTypesOf(B), shared = Object.keys(sa).filter(function (k) { return sb[k]; });
if (!shared.length) { if (hintEl) hintEl.textContent = '🔗 pas de noyau commun entre « ' + (A.name || 'cubion') + ' » et « ' + (B.name || 'cubion') + ' » (aucun bion partagé)'; return; }
if (!wireExists(A, B)) { doc.wires.push({ from: A.nid, fromPort: 'out', to: B.nid, toPort: 'in', core: shared.join(',') }); }
markTsoin('cubionlink', { core: shared.join(','), a: A.nid, b: B.nid }); logAct({ act: 'cubionlink', a: A.nid, b: B.nid, core: shared.join(',') });
selM = []; refreshWireIfOpen(); renderTree(); if (hintEl) hintEl.textContent = '🔗 lié par noyau commun : ' + shared.join(', '); }
// ===== 🎲 MÉLANGER (Vague 3, de blocs/craftion) : génère un cubion ALÉATOIRE DÉTERMINISTE depuis la
// palette de bions. Seed = le nom de la création → même nom = même mélange (reproductible, zéro Date).
// Pose 3–6 bions autour du core, les colore, puis les collapse en cubion (SANS toucher au reste du build).
function mixRand(seed) { var t = seed >>> 0; return function () { t += 0x6D2B79F5; var r = Math.imul(t ^ (t >>> 15), 1 | t); r ^= r + Math.imul(r ^ (r >>> 7), 61 | r); return ((r ^ (r >>> 14)) >>> 0) / 4294967296; }; }
function mixHash(s) { var h = 2166136261 >>> 0; for (var i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
function melanger() { setView('scene'); reindexCells();
var pool = bionItems().filter(function (it) { return it.kind === 'bion' && /^jOS/.test(it.id); });
if (!pool.length) { if (hintEl) hintEl.textContent = '🎲 aucun bion en palette'; return; }
var name = (container.querySelector('[data-name]').value || 'mix').trim(), rnd = mixRand(mixHash(name));
var count = 3 + Math.floor(rnd() * 4); // 3..6, déterministe
var core = doc.nodes.filter(function (n) { return n.core; })[0], ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
var offs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], vis = {}, ring = [[ox, oy, oz]], targets = []; vis[cellKey(ox, oy, oz)] = 1;
while (targets.length < count && ring.length) { var next = []; ring.forEach(function (c) { offs.forEach(function (o) { var p = [c[0] + o[0], c[1] + o[1], c[2] + o[2]], k = cellKey(p[0], p[1], p[2]); if (!vis[k]) { vis[k] = 1; if (!cells[k]) targets.push(p); next.push(p); } }); }); ring = next; }
var picked = []; for (var i = 0; i < count && i < targets.length; i++) { var b = pool[Math.floor(rnd() * pool.length)].id, t = targets[i], nn = addBionCube(b, t[0], t[1], t[2]); if (nn) { nn.xer = XERTYPES[Math.floor(rnd() * XERTYPES.length)].id; recolorCube(nn); picked.push(nn); } }
if (picked.length >= 2) { // collapse SCOPÉ : uniquement les bions mélangés → un cubion (le reste du build est intact)
var cx = 0, cy = 0, cz = 0; picked.forEach(function (n) { cx += n.cube.x; cy += n.cube.y; cz += n.cube.z; }); var cnt = picked.length; cx = Math.round(cx / cnt); cy = Math.round(cy / cnt); cz = Math.round(cz / cnt);
var sphere = cnt >= 12, side = Math.max(1.3, Math.cbrt(cnt) * 1.1);
picked.forEach(function (n) { if (n._cube) { try { e.world.scene.remove(n._cube); } catch (x) {} n._cube = null; } });
var cub = { nid: nid++, type: 'cubion', name: 'mix-' + osSlug(name).slice(0, 8), members: picked.map(function (n) { return n.nid; }), cube: { x: cx, y: cy, z: cz }, shape: sphere ? 'sphere' : 'cube', size: side, count: cnt };
picked.forEach(function (n) { n.parent = cub.nid; });
(doc.wires || []).forEach(function (w) { var fi = cub.members.indexOf(w.from) >= 0, ti = cub.members.indexOf(w.to) >= 0; if (fi && ti) return; if (fi) { w.from = cub.nid; w.fromPort = 'out'; } if (ti) { w.to = cub.nid; w.toPort = 'in'; } });
doc.nodes.push(cub); spawnCubeMesh(cub); reindexCells(); select(cub); }
markTsoin('melange', { count: picked.length, seed: name }); try { snapshot(); } catch (x) {} renderTree(); refreshWireIfOpen(); updateCount();
if (hintEl) hintEl.textContent = '🎲 cubion mélangé : ' + picked.length + ' bions (seed « ' + name + ' »)'; }
container.innerHTML =
'<div class="fs"><div class="fs__bar"><b>🔮 Ultimate Forge</b><span class="fs__muted" data-crumb title="seed: zlorbion · Finch · xerion">· Spherion · seed zlorbion · Finch · xerion</span><input class="fs__q" data-name value="Ma création" style="margin:0 0 0 8px;flex:0 0 130px"><span class="fs__sp"></span>'
+ '<span class="fs__seg"><button class="on" data-view="scene">🧊 3D</button><button data-view="2d">▦ 2D</button><button data-view="wire">🔗 Logique</button><button data-view="explode">💥 Éclatée</button><button data-view="fusion">🧲 Fusion</button><button data-view="connexions">🔌 Connexions</button><button data-view="forge">⚒ Forge</button><button data-view="suggest">✨ Suggestions</button><button data-view="code">💻 Code</button><button data-view="xer">👁 Xer</button></span>'
+ '<button class="fs__b sec" data-autodock>🧲 auto-dock</button><button class="fs__b sec" data-explode>💥 éclater</button><button class="fs__b sec" data-ranger>⤢ réorganiser</button><button class="fs__b sec" data-collapse>⬛ collapser</button><button class="fs__b sec" data-fractale>🔺 fractale</button><button class="fs__b sec" data-sim>🔬 simuler</button><button class="fs__b sec" data-replay>⏺ rejouer</button><button class="fs__b sec" data-timeline title="scrubber du processus de construction (Premiere)">⏱</button><button class="fs__b sec" data-undo title="annuler" disabled>↶</button><button class="fs__b sec" data-redo title="rétablir" disabled>↷</button><button class="fs__b sec" data-save>💾</button><button class="fs__b sec" data-play>▶ jouer</button><button class="fs__b" data-forge>⚒ forger</button><button class="fs__b sec" data-metal title="forger un OS : .xos pour le XERBOXION-OS — envoyer avec xos-send.sh">🧿 OS (.xos)</button><button class="fs__b sec" data-xos-import title="importer un .xos — re-poser les composantes en cubes">📂 .xos</button><button class="fs__b sec" data-oslib title="Bibliotheque d OS : sauver, rejouer dans le navigateur, exporter">🧿 Mes OS</button><button class="fs__b sec" data-lier title="lier 2 cubions par leur noyau commun (bions partages)">🔗 lier</button><button class="fs__b sec" data-melanger title="generer un cubion aleatoire deterministe (seed = nom)">🎲 melanger</button><button class="fs__b" data-publish title="publier durablement dans ton boxion (Mes creations)">📤 publier</button><button class="fs__b sec" data-publib title="Mes creations publiees (rouvrir / .xos / supprimer)">📚 creations</button></div>'
+ '<div class="fs__lib"><div class="fs__tabs"><div class="fs__tab" data-tab="parts">Parts</div><div class="fs__tab" data-tab="ploxion">Ploxions</div><div class="fs__tab on" data-tab="bion">Bions</div><div class="fs__tab" data-tab="kion">Kions</div><div class="fs__tab" data-tab="jeu">Jeux</div><div class="fs__tab" data-tab="exemple">Ex.</div></div>'
+ '<input class="fs__q" data-q placeholder="filtrer…"><div class="fs__items" data-items></div></div>'
+ '<div class="fs__view"><canvas></canvas><div class="fs__hint" data-hint>choisis une part → clique le sol · un ploxion → panneau vivant · clic-droit = retirer</div>'
+ '<div class="fs__wire" data-wire><div class="fs__wbar"><button class="fs__b" data-cubion>⬛ former un cubion</button><button class="fs__b sec" data-plugion>🔌 plugion</button></div><svg class="fs__wsvg" data-wsvg></svg><div class="fs__wtip">clic un bloc = sélectionner · tire sortie→entrée = câbler · clic fil = couper · ⚡ = tester · sélectionne des bions → ⬛ cubion → 🔌 plugion → connecte deux plugions = ploxion</div></div>'
+ '<canvas class="fs__2d" data-2d></canvas><pre class="fs__code" data-code></pre><div class="fs__xerv" data-xerv></div>'
+ '<div class="fs__over" data-fusion></div><div class="fs__over" data-conn></div><div class="fs__over" data-forgev></div><div class="fs__over" data-suggest></div>'
+ '<div class="fs__exui" data-exui><span style="font-size:.66rem;color:#8397c0">💥 éclatement</span><input type="range" min="0" max="100" value="38" data-exrange><span class="fs__muted" data-exval>écarter</span></div>'
+ '<div class="fs__crumb" data-crumbbar></div></div>'
+ '<div class="fs__insp" data-insp></div>'
+ '<div class="fs__tree"><div class="fs__tt">document</div><div data-tree></div></div></div>';
var itemsEl = container.querySelector('[data-items]'), qEl = container.querySelector('[data-q]'), treeEl = container.querySelector('[data-tree]'),
inspEl = container.querySelector('[data-insp]'), hintEl = container.querySelector('[data-hint]'), cv = container.querySelector('canvas'), view = container.querySelector('.fs__view');
// ---- viewport 3D (édition) ----
e = jOSEngine.create(cv, { ground: false, grid: false, orbit: false, shadows: false, dist: 11, el: 0.62, az: 0.7, minDist: 3, maxDist: 120, onReady: function (en) { var T = en.THREE; ray = new T.Raycaster(); ndc = new T.Vector2();
// PAS DE SOL — on construit dans le vide, façon hologramme (RS-7). Plan invisible juste pour le raycast des parts.
ground = new T.Mesh(new T.PlaneGeometry(300, 300), new T.MeshBasicMaterial({ visible: false })); ground.rotation.x = -Math.PI / 2; en.add(ground);
ghost = new T.Mesh(new T.BoxGeometry(1, 1, 1), new T.MeshBasicMaterial({ color: 0x5fe0c0, transparent: true, opacity: 0.22 })); ghost.visible = false; ghost.add(new T.LineSegments(new T.EdgesGeometry(new T.BoxGeometry(1, 1, 1)), new T.LineBasicMaterial({ color: 0x9ff0e0 }))); en.add(ghost);
rebuildParts(); rebuildCubes(); e.world.cam.target.set(0, 0.5, 0);
if (seedPloxion) { var core = doc.nodes.filter(function (n) { return n.core; })[0]; var cx = core ? core.cube.x : 0, cy = core ? core.cube.y : 0, cz = core ? core.cube.z : 0; var sn = addBionCube(seedPloxion, cx, cy + 1, cz); if (sn) { sn.name = seedPloxion; sn.xer = 'ui'; sn.faces = defaultFaces(); sn.faces.up.ploxion = seedPloxion; recolorCube(sn); if (core) connectByFace(core, sn, 0, 1, 0); } seedPloxion = null; } } });
function cubeMeshes() { return doc.nodes.filter(function (n) { return n._cube; }).map(function (n) { return n._cube; }); }
// ---- caméra façon BLENDER : molette = zoom · clic-milieu = orbite · Shift+milieu (ou Alt) = pan ----
cv.addEventListener('pointerdown', function (ev) { var orbit = ev.button === 1 || (ev.button === 0 && ev.altKey); if (!orbit) return; ev.preventDefault();
camDrag = { mode: (ev.shiftKey ? 'pan' : 'orbit'), x: ev.clientX, y: ev.clientY }; });
function onWinMove(ev) { var c = e && e.world && e.world.cam; if (!c || !c.target) return;
if (camDrag) { var dx = ev.clientX - camDrag.x, dy = ev.clientY - camDrag.y; camDrag.x = ev.clientX; camDrag.y = ev.clientY;
if (camDrag.mode === 'orbit') { c.az -= dx * 0.01; c.el = Math.max(0.05, Math.min(1.5, c.el - dy * 0.01)); }
else { var k = c.dist * 0.0016, rx = -Math.sin(c.az), rz = Math.cos(c.az); c.target.x -= rx * dx * k; c.target.z -= rz * dx * k; c.target.y = Math.max(0, c.target.y + dy * k); } return; }
// survol : fantôme Minecraft sur la face visée
if (viewMode !== 'scene' || !brushBion || !ghost || !ray) { if (ghost) ghost.visible = false; return; }
var hit = rayCubes(ev); if (hit && hit.object.userData.nid != null) { var b = byId(hit.object.userData.nid); var nm = hit.face.normal;
if (b && b.cube) { ghost.position.set(b.cube.x + Math.round(nm.x), b.cube.y + Math.round(nm.y) + 0.5, b.cube.z + Math.round(nm.z)); ghost.visible = true; return; } }
ghost.visible = false; }
function onWinUp() { camDrag = null; }
window.addEventListener('pointermove', onWinMove); window.addEventListener('pointerup', onWinUp);
cv.addEventListener('wheel', function (ev) { ev.preventDefault(); var c = e && e.world && e.world.cam; if (c) c.dist = Math.max(3, Math.min(120, c.dist + (ev.deltaY > 0 ? 2.5 : -2.5))); }, { passive: false });
function obj3dOf(r) { return r && r.isObject3D ? r : (r && r.mesh) ? r.mesh : null; }
function rebuildParts() { doc.nodes.forEach(function (n) { if (n.type === 'part' && !n._obj) { var r = jOSKit.make(e, n.part, Object.assign({}, n.opts, { x: n.x, y: n.y, z: n.z })); n._obj = obj3dOf(r); } }); }
function addPart(part, x, z) { var n = { nid: nid++, type: 'part', part: part, name: part, x: x, y: part === 'coin' ? 0.7 : 0, z: z, opts: {} };
var r = jOSKit.make(e, part, { x: x, y: n.y, z: z }); n._obj = obj3dOf(r); doc.nodes.push(n); select(n); renderTree(); refreshWireIfOpen(); }
function addPloxion(id) { var n = { nid: nid++, type: 'ploxion', ploxion: id, name: id, px: 24 + (doc.nodes.length % 5) * 18, py: 24 + (doc.nodes.length % 5) * 18 };
doc.nodes.push(n); mountPanel(n); select(n); renderTree(); refreshWireIfOpen(); }
function addBion(id) { var n = { nid: nid++, type: 'bion', bion: id, name: id }; doc.nodes.push(n); select(n); renderTree(); refreshWireIfOpen(); }
// POSER UN JEU (Vague 3) : jeu ploxion-backed déjà chargé → panneau vivant (addPloxion) ; archétype
// moteur → panneau jouable via jOSGames.make ; sinon → ouvre le ploxion du jeu (jOSGames.open). Bloc jouable.
function addGame(gid) { if (!gid || !window.jOSGames || typeof jOSGames.list !== 'function') return; var g = null; try { (jOSGames.list() || []).forEach(function (x) { if (x.id === gid) g = x; }); } catch (x) {} if (!g) return;
if (g.ploxion && window.jOSApps && window.jOSApps[g.ploxion]) { addPloxion(g.ploxion); if (hintEl) hintEl.textContent = '🎮 posé (panneau jouable) : ' + g.name; return; }
if (g.engine) { var pid = 'game-' + g.id; window.jOSApps = window.jOSApps || {};
if (!window.jOSApps[pid]) window.jOSApps[pid] = { manifest: { id: pid, name: g.name, icon: g.icon || '🎮' }, mount: function (c) { try { return jOSGames.make(g.id, c); } catch (x) { c.innerHTML = '<div style="padding:10px;color:#8aa">jeu indisponible</div>'; return { unmount: function () { c.innerHTML = ''; } }; } } };
addPloxion(pid); if (hintEl) hintEl.textContent = '🎮 posé (archétype moteur) : ' + g.name; return; }
try { jOSGames.open(g.id); } catch (x) {} if (hintEl) hintEl.textContent = '🎮 ouvert : ' + g.name; }
var panelEls = {};
function mountPanel(n) { var p = document.createElement('div'); p.className = 'fs__panel'; p.style.left = n.px + 'px'; p.style.top = n.py + 'px';
var man = (window.jOSApps[n.ploxion] && window.jOSApps[n.ploxion].manifest) || { name: n.ploxion, icon: '▦' };
p.innerHTML = '<div class="fs__ph">' + (man.icon || '▦') + ' ' + (man.name || n.ploxion) + '<span class="x" title="retirer">✕</span></div><div class="fs__pb"></div>';
view.appendChild(p); panelEls[n.nid] = p;
try { n._inst = window.jOSApps[n.ploxion].mount(p.querySelector('.fs__pb'), {}); } catch (x) { p.querySelector('.fs__pb').innerHTML = '<div style="padding:10px;color:#8aa">' + (man.name || n.ploxion) + '</div>'; }
p.querySelector('.x').addEventListener('click', function () { removeNode(n); });
p.querySelector('.fs__ph').addEventListener('pointerdown', function () { select(n); });
dragMove(p, p.querySelector('.fs__ph'));
}
function removeNode(n) { if (n.type === 'part' && n._obj) { try { e.world.scene.remove(n._obj); } catch (x) {} }
if (n.type === 'ploxion') { try { n._inst && n._inst.unmount && n._inst.unmount(); } catch (x) {} if (panelEls[n.nid]) { panelEls[n.nid].remove(); delete panelEls[n.nid]; } }
if (n.type === 'cubion') { (n.members || []).forEach(function (m) { var mn = byId(m); if (mn) mn.parent = null; }); } // dissoudre : les bions redeviennent libres
if (n._cube) { try { e.world.scene.remove(n._cube); } catch (x) {} n._cube = null; }
var sel0 = selM.indexOf(n.nid); if (sel0 >= 0) selM.splice(sel0, 1);
doc.nodes = doc.nodes.filter(function (x) { return x !== n; }); doc.wires = (doc.wires || []).filter(function (w) { return w.from !== n.nid && w.to !== n.nid; }); if (sel === n) select(null); reindexCells(); updateCount(); renderTree(); refreshWireIfOpen(); snapshot(); }
// ---- placement au clic (parts) ----
function hitGround(ev) { var r = cv.getBoundingClientRect(); ndc.x = (ev.clientX - r.left) / r.width * 2 - 1; ndc.y = -((ev.clientY - r.top) / r.height * 2 - 1); ray.setFromCamera(ndc, e.world.camera); var h = ray.intersectObject(ground)[0]; return h ? h.point : null; }
function rayCubes(ev) { var r = cv.getBoundingClientRect(); ndc.x = (ev.clientX - r.left) / r.width * 2 - 1; ndc.y = -((ev.clientY - r.top) / r.height * 2 - 1); ray.setFromCamera(ndc, e.world.camera); return ray.intersectObjects(cubeMeshes())[0] || null; }
cv.addEventListener('click', function (ev) { if (!ground) return;
if (brushBion) { var hit = rayCubes(ev); if (hit && hit.object.userData.nid != null) { var base = byId(hit.object.userData.nid); var nm = hit.face.normal; var fx = Math.round(nm.x), fy = Math.round(nm.y), fz = Math.round(nm.z);
if (base && base.cube) { var nn = addBionCube(brushBion, base.cube.x + fx, base.cube.y + fy, base.cube.z + fz); if (nn) connectByFace(base, nn, fx, fy, fz); } } return; }
if (pending) { var p = hitGround(ev); if (p) addPart(pending, Math.round(p.x), Math.round(p.z)); } });
cv.addEventListener('contextmenu', function (ev) { ev.preventDefault(); if (!ground) return;
var hit = rayCubes(ev); if (hit && hit.object.userData.nid != null) { var n = byId(hit.object.userData.nid); if (n && !n.core) { removeNode(n); return; } if (n && n.core) return; }
var p = hitGround(ev); if (!p) return; var best = null, bd = 4; doc.nodes.forEach(function (n) { if (n.type === 'part') { var d = Math.hypot(n.x - p.x, n.z - p.z); if (d < bd) { bd = d; best = n; } } }); if (best) removeNode(best); });
cv.addEventListener('dblclick', function (ev) { var hit = rayCubes(ev); if (hit && hit.object.userData.nid != null) enterBion(byId(hit.object.userData.nid)); }); // double-clic = ENTRER dans le bion (fractal)
// ---- bibliothèque ----
function defaultFaces() { return { up: { dir: 'out' }, east: { dir: 'out' }, north: { dir: 'out' }, down: { dir: 'in' }, west: { dir: 'in' }, south: { dir: 'in' } }; }
function recolorCube(n) { if (n._cube && n._cube.material) { var c = n.bion === 'vide' ? 0x8aa0c0 : xerColor(n.xer); n._cube.material.color.setHex(c); n._cube.material.emissive.setHex(c); } }
function loadExample(k) { var ex = EXAMPLES[k]; if (!ex) return; var core = doc.nodes.filter(function (n) { return n.core; })[0]; var ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
ex.cubes.forEach(function (cb) { var n = addBionCube(cb.bion, ox + cb.d[0], oy + cb.d[1], oz + cb.d[2]); if (n) { n.xer = cb.xer || 'cube'; n.faces = Object.assign(defaultFaces(), cb.faces || {}); recolorCube(n); if (core) connectByFace(core, n, cb.d[0], cb.d[1], cb.d[2]); } });
setView('scene'); markTsoin('exemple', { ex: k }); }
// RECONSTRUIRE LE XERBOXION (RS-7 : « reconstruire le xerboxion dans la forge, trouver sa fractale ») :
// importe TOUS les ploxions comme cubes-bions autour du core (chacun porte son ploxion en face out), puis auto-dock.
function reconstructXerboxion() { var plox = ploxionItems(); reindexCells();
var core = doc.nodes.filter(function (n) { return n.core; })[0]; var ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
var offs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], vis = {}, ring = [[ox, oy, oz]], targets = []; vis[cellKey(ox, oy, oz)] = 1;
while (targets.length < plox.length && ring.length) { var next = []; ring.forEach(function (c) { offs.forEach(function (o) { var p = [c[0] + o[0], c[1] + o[1], c[2] + o[2]], k = cellKey(p[0], p[1], p[2]); if (!vis[k]) { vis[k] = 1; if (!cells[k]) targets.push(p); next.push(p); } }); }); ring = next; }
var i = 0; plox.forEach(function (p) { if (i >= targets.length) return; var t = targets[i++]; var n = addBionCube(p.id, t[0], t[1], t[2]); if (n) { n.name = p.label; n.xer = 'ui'; n.faces = defaultFaces(); n.faces.up.ploxion = p.id; recolorCube(n); } });
autoDock(); setView('scene'); markTsoin('reconstruct-xerboxion', { count: plox.length }); }
// TROUVER LA FRACTALE (RS-7) : détecte les sous-structures AUTO-SIMILAIRES (mêmes blocs + mêmes voisins)
// dans la construction → l'auto-similarité du xerboxion ; highlight le motif dominant + PARTAGE au nexus.
function findFractal() { var cubes = doc.nodes.filter(function (n) { return n.cube && !n.parent; }); if (!cubes.length) return;
function sig(n) { var nb = []; (doc.wires || []).forEach(function (w) { if (w.from === n.nid) { var t = byId(w.to); if (t) nb.push(t.bion || t.type); } if (w.to === n.nid) { var f = byId(w.from); if (f) nb.push(f.bion || f.type); } }); return (n.bion || n.type) + '[' + nb.sort().join(',') + ']'; }
var groups = {}; cubes.forEach(function (n) { var s = sig(n); (groups[s] = groups[s] || []).push(n); });
var motifs = Object.keys(groups).filter(function (s) { return groups[s].length >= 2; }).sort(function (a, b) { return groups[b].length - groups[a].length; });
if (motifs.length) groups[motifs[0]].forEach(function (n) { if (n._cube) { n._cube.material.emissiveIntensity = 1.3; setTimeout(function () { try { n._cube.material.emissiveIntensity = 0.38; } catch (x) {} }, 1400); } });
var result = { motifs: motifs.map(function (s) { return { sig: s, count: groups[s].length }; }), blocs: cubes.length };
if (hintEl) hintEl.textContent = '🔺 fractale : ' + motifs.length + ' motifs auto-similaires' + (motifs.length ? ' · dominant ×' + groups[motifs[0]].length : ' (rien de répété)');
markTsoin('fractale', { motifs: motifs.length });
try { window.jOSNexus && jOSNexus.push && jOSNexus.push('fractale', result); } catch (x) {} // PARTAGE au nexus (partager des fractales avec des gens)
return result; }
// VUE DU BOXION : blocs pour tous les SERVICES/SYSTÈMES du boxion, DOCKÉS par leurs dépendances.
function reconstructBoxion() { reindexCells();
var core = doc.nodes.filter(function (n) { return n.core; })[0]; var ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
var offs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], vis = {}, ring = [[ox, oy, oz]], targets = []; vis[cellKey(ox, oy, oz)] = 1;
while (targets.length < BOXION.length && ring.length) { var next = []; ring.forEach(function (c) { offs.forEach(function (o) { var p = [c[0] + o[0], c[1] + o[1], c[2] + o[2]], k = cellKey(p[0], p[1], p[2]); if (!vis[k]) { vis[k] = 1; if (!cells[k]) targets.push(p); next.push(p); } }); }); ring = next; }
var map = {}, i = 0; BOXION.forEach(function (s) { if (i >= targets.length) return; var t = targets[i++]; var n = addBionCube(s.id, t[0], t[1], t[2]); if (n) { n.name = s.label; n.xer = s.xer; n.faces = defaultFaces(); recolorCube(n); map[s.id] = n; } });
BOXION.forEach(function (s) { var to = map[s.id]; if (!to) return; (s.deps || []).forEach(function (d) { var from = map[d]; if (from && !wireExists(from, to)) doc.wires.push({ from: from.nid, fromPort: 'up', to: to.nid, toPort: 'down' }); }); }); // DOCKING par dépendances
autoDock(); setView('scene'); refreshWireIfOpen(); markTsoin('reconstruct-boxion', { count: BOXION.length });
// STATUT VIVANT : teinte chaque service selon son état réel (up=vert · down=rouge · na=gris)
try { fetch('/px/boxion/status', { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (st) { Object.keys(map).forEach(function (id) { var n = map[id], s = st[id]; if (!n || !n._cube) return; var col = s === 'up' ? 0x3fd07a : s === 'down' ? 0xd0463f : 0x55617a; n._cube.material.color.setHex(col); n._cube.material.emissive.setHex(col); n.status = s; }); if (hintEl) hintEl.textContent = '🖥 vue du boxion — vert=up · rouge=down · gris=n/a'; }).catch(function () {}); } catch (x) {} }
function renderLib() { var q = (qEl.value || '').toLowerCase();
var list = tab === 'parts' ? partItems() : tab === 'ploxion' ? ploxionItems() : tab === 'exemple' ? exampleItems() : tab === 'kion' ? kionItems() : tab === 'jeu' ? gameItems() : bionItems();
itemsEl.innerHTML = list.filter(function (it) { return !q || it.label.toLowerCase().indexOf(q) >= 0; })
.map(function (it) { return '<div class="fs__it" data-add="' + it.kind + ':' + it.id + '"><span class="i">' + it.icon + '</span>' + it.label + '</div>'; }).join('') || '<div class="fs__muted" style="padding:6px">rien</div>';
}
itemsEl.addEventListener('click', function (ev) { var it = ev.target.closest('[data-add]'); if (!it) return; var v = it.getAttribute('data-add'), k = v.slice(0, v.indexOf(':')), id = v.slice(v.indexOf(':') + 1);
if (!id) return; // items placeholder (« absent » / « aucun ») : rien à poser
if (k === 'part') { pending = id; brushBion = null; if (ghost) ghost.visible = false; hintEl.textContent = 'clique le sol pour poser : ' + id + ' (clic-droit = retirer)'; }
else if (k === 'ploxion') addPloxion(id); else if (k === 'exemple') { if (id === '__xerboxion__') reconstructXerboxion(); else if (id === '__boxion__') reconstructBoxion(); else loadExample(id); }
else if (k === 'kfloat') { try { window.jOSKionFloat && jOSKionFloat.float({ type: id, label: id, action: '' }); } catch (x) {} } // kion/bouton FLOTTANT (jOSKionFloat) — se dépose ailleurs
else if (k === 'game') { addGame(id); } // jeu → panneau jouable dans la forge
else { brushBion = id; pending = null; setView('scene'); updateCount(); if (k === 'kion' && hintEl) hintEl.textContent = 'clique une FACE pour poser le kion « ' + id + ' »'; } });
container.querySelectorAll('[data-tab]').forEach(function (t) { t.addEventListener('click', function () { tab = t.getAttribute('data-tab'); container.querySelectorAll('[data-tab]').forEach(function (x) { x.classList.toggle('on', x === t); }); renderLib(); }); });
qEl.addEventListener('input', renderLib);
// ---- inspecteur ----
function select(n) { disposeScad(); sel = n; renderTree(); if (!n) { inspEl.innerHTML = '<h4>inspecteur</h4><div class="fs__muted">sélectionne un élément.</div>'; return; }
if (n.type === 'part') { inspEl.innerHTML = '<h4>' + n.part + '</h4>'
+ row('nom', 'text', n.name) + row('X', 'number', n.x) + row('Y', 'number', n.y) + row('Z', 'number', n.z)
+ '<button class="fs__b sec" data-del style="width:100%;margin-top:6px">🗑 retirer</button>';
bind('nom', function (v) { n.name = v; renderTree(); }); bind('X', function (v) { n.x = +v; place(n); }); bind('Y', function (v) { n.y = +v; place(n); }); bind('Z', function (v) { n.z = +v; place(n); });
} else if (n.type === 'ploxion') { inspEl.innerHTML = '<h4>ploxion : ' + n.ploxion + '</h4><div class="fs__muted" style="margin-bottom:6px">panneau vivant (Scène) — bloc câblable (Câblage).</div>' + '<button class="fs__b sec" data-del style="width:100%">🗑 retirer</button>';
} else if (n.type === 'cubion') { inspEl.innerHTML = '<h4>⬛ cubion</h4>' + row('nom', 'text', n.name) + '<div class="fs__muted" style="margin:2px 0 6px">' + (n.members || []).length + ' bions assemblés. Pose un 🔌 plugion pour le docker.</div><button class="fs__b sec" data-dissolve style="width:100%;margin-bottom:5px">⬗ dissoudre</button><button class="fs__b sec" data-del style="width:100%">🗑 retirer</button>';
bind('nom', function (v) { n.name = v; renderTree(); refreshWireIfOpen(); }); var ds = inspEl.querySelector('[data-dissolve]'); if (ds) ds.addEventListener('click', function () { removeNode(n); });
} else if (n.type === 'plugion') { inspEl.innerHTML = '<h4>🔌 plugion</h4><div class="fs__muted" style="margin-bottom:6px">docking : relie une sortie (dock) à l\'entrée dock d\'un autre plugion → deux cubions dockés = un ploxion.</div>' + '<button class="fs__b sec" data-del style="width:100%">🗑 retirer</button>';
} else { n.xer = n.xer || 'cube'; n.faces = n.faces || defaultFaces(); var plops = ploxionItems();
var xopts = XERTYPES.map(function (t) { return '<option value="' + t.id + '"' + (n.xer === t.id ? ' selected' : '') + '>' + t.name + '</option>'; }).join('');
function frow(f) { var fc = n.faces[f] || (n.faces[f] = { dir: FACEFN[f].dir }); var po = '<option value="">—</option>' + plops.map(function (p) { return '<option value="' + p.id + '"' + (fc.ploxion === p.id ? ' selected' : '') + '>' + p.label + '</option>'; }).join('');
return '<div class="fs__row"><button class="fs__b sec fdir" data-face="' + f + '" style="flex:0 0 32px;padding:3px 0">' + (fc.dir || 'in') + '</button><label style="flex:0 0 32px">' + f + '</label><select class="fple" data-face="' + f + '" style="flex:1;min-width:0">' + po + '</select></div>'; }
inspEl.innerHTML = '<h4>' + (n.bion === 'vide' ? '▢ bloc vide' : '🧊 ' + n.bion + ' — xer') + '</h4>' + row('nom', 'text', n.name)
+ '<div class="fs__row"><label>xer</label><select data-xer style="flex:1">' + xopts + '</select></div>'
+ '<div class="fs__muted" style="margin:5px 0 2px">faces = ploxions (I/O) :</div>' + ['up', 'east', 'north', 'down', 'west', 'south'].map(frow).join('')
+ '<div class="fs__muted" style="margin:5px 0 2px">knobs → bion :</div>' + [0, 1, 2].map(function (ki) { var v = (n.knobs && n.knobs[ki] != null) ? n.knobs[ki] : 50; return '<div class="fs__knob"><label>k' + ki + '</label><input type="range" min="0" max="100" value="' + v + '" data-knob="' + ki + '"></div>'; }).join('')
+ '<button class="fs__b sec" data-power style="width:100%;margin-top:6px">⚡ signal (redstone)</button>'
+ '<button class="fs__b sec" data-del style="width:100%;margin-top:4px">🗑 retirer</button>';
n.knobs = n.knobs || [50, 50, 50];
[].forEach.call(inspEl.querySelectorAll('[data-knob]'), function (r) { r.addEventListener('input', function () { var ki = +this.getAttribute('data-knob'); n.knobs[ki] = +this.value; try { window.jOSPorts && jOSPorts.emit(n.bion, 'knob', { k: ki, v: n.knobs[ki] }); } catch (x) {} logAct({ act: 'knob', nid: n.nid, key: ki, val: n.knobs[ki] }); if (n._cube && n._cube.material) n._cube.material.emissiveIntensity = 0.2 + n.knobs[ki] / 100; }); });
bind('nom', function (v) { n.name = v; renderTree(); refreshWireIfOpen(); });
inspEl.querySelector('[data-xer]').addEventListener('change', function () { n.xer = this.value; recolorCube(n); });
[].forEach.call(inspEl.querySelectorAll('.fdir'), function (b) { b.addEventListener('click', function () { var f = this.getAttribute('data-face'); n.faces[f] = n.faces[f] || {}; n.faces[f].dir = (n.faces[f].dir === 'out' ? 'in' : 'out'); this.textContent = n.faces[f].dir; }); });
[].forEach.call(inspEl.querySelectorAll('.fple'), function (s) { s.addEventListener('change', function () { var f = this.getAttribute('data-face'); n.faces[f] = n.faces[f] || { dir: FACEFN[f].dir }; n.faces[f].ploxion = this.value || null; }); });
inspEl.querySelector('[data-power]').addEventListener('click', function () { powerCube(n, 0, {}); });
if (n.bion === 'openscad' || n.bion === 'pcb') { var extra = document.createElement('div'); extra.style.marginTop = '6px';
var canRender = !!(window.jOSScad && jOSScad.render && window.jOSEngine); // moteur SCAD/PCB dispo ?
var prevHtml = canRender ? '<button class="fs__b" data-scadprev style="width:100%;margin-top:4px">🔬 aperçu 3D</button><div data-scadhost style="display:none;height:150px;margin-top:4px;border:1px solid #22344f;border-radius:6px;overflow:hidden;position:relative"></div>' : '';
if (n.bion === 'openscad') extra.innerHTML = '<textarea data-scad style="width:100%;height:58px;box-sizing:border-box;background:#0c1626;border:1px solid #22344f;color:#cfe;border-radius:5px;font:.66rem ui-monospace" placeholder="cube([10,10,10]);">' + xesc(n.scad || '') + '</textarea>' + prevHtml + '<button class="fs__b sec" data-oscad style="width:100%;margin-top:4px">🖨 ouvrir OpenSCAD</button>';
else extra.innerHTML = prevHtml + '<button class="fs__b sec" data-opcb style="width:100%;margin-top:4px">🔌 ouvrir le PCB</button>';
inspEl.insertBefore(extra, inspEl.querySelector('[data-power]'));
var ta = inspEl.querySelector('[data-scad]'); if (ta) ta.addEventListener('input', function () { n.scad = this.value; });
var sp = inspEl.querySelector('[data-scadprev]'); if (sp) sp.addEventListener('click', function () { var host = inspEl.querySelector('[data-scadhost]'); if (host) { host.style.display = 'block'; mountScadPreview(host, n); } });
var ob = inspEl.querySelector('[data-oscad]'); if (ob) ob.addEventListener('click', function () { try { jOS.openPloxion('openscad'); } catch (x) {} });
var pb = inspEl.querySelector('[data-opcb]'); if (pb) pb.addEventListener('click', function () { try { jOS.openPloxion('pcb'); } catch (x) {} }); } }
// BLOC SYSTÈME VIVANT (Vague 1) : si le bion est un bloc système, montre ce qu'il FAIT + ses ports
// RÉELS via jOSSysBlocks (au lieu du générique 6-faces). Fallback silencieux si le bion est absent.
if (n.bion && window.jOSSysBlocks && jOSSysBlocks.has && jOSSysBlocks.has(n.bion)) { var sb = null; try { sb = jOSSysBlocks.create(n.bion); } catch (x) {}
if (sb) { var sbk = (jOSSysBlocks.typeOf ? jOSSysBlocks.typeOf(n) : n.bion) || n.bion; var sbdesc = SYSDOC[sbk] || 'bloc système vivant.';
var sbports = ''; try { if (sb.exports) { var ex = sb.exports(); sbports = 'sorties: ' + ((ex.out || []).join(', ') || '—') + ((ex.in && ex.in.length) ? ' · entrées: ' + ex.in.join(', ') : ''); } else if (sb.ports) { sbports = 'ports: ' + ((sb.ports() || []).join(', ') || '—'); } } catch (x) {}
var pwr = inspEl.querySelector('[data-power]'); if (pwr) { var info = document.createElement('div'); info.style.cssText = 'margin-top:6px;padding:6px 8px;border:1px solid #2a4a62;border-radius:6px;background:rgba(20,44,62,.35);font-size:.64rem;color:#9fd0e0';
info.innerHTML = '<b>⚙ ' + xesc(sb.kind || sbk) + '</b> — ' + xesc(sbdesc) + (sbports ? '<div class="fs__muted" style="margin-top:3px">' + xesc(sbports) + '</div>' : ''); inspEl.insertBefore(info, pwr); } } }
var del = inspEl.querySelector('[data-del]'); if (del) del.addEventListener('click', function () { removeNode(n); });
}
function row(lab, type, val) { return '<div class="fs__row"><label>' + lab + '</label><input data-f="' + lab + '" type="' + type + '" value="' + (val != null ? val : '') + '"></div>'; }
function bind(lab, cb) { var el = inspEl.querySelector('[data-f="' + lab + '"]'); if (el) el.addEventListener('input', function () { cb(el.value); }); }
function place(n) { if (n._obj) n._obj.position.set(n.x, n.y, n.z); }
// APERÇU 3D SCAD/PCB dans l'inspecteur (Vague 1) : rend le MESH RÉEL via jOSScad (mini jOSEngine dédié,
// même instance Three partagée). Disposé à la désélection → pas de fuite WebGL. Fallback : le bouton
// « ouvrir » (ploxion externe) reste dispo si jOSScad/jOSEngine absents ou si le rendu échoue.
function disposeScad() { if (!scadSess) return; try { scadSess.art && scadSess.art.dispose && scadSess.art.dispose(); } catch (x) {} try { scadSess.eng && scadSess.eng.dispose && scadSess.eng.dispose(); } catch (x) {} scadSess = null; }
function mountScadPreview(host, n) { disposeScad(); if (!window.jOSScad || !window.jOSEngine || !host) return; host.innerHTML = '';
var cvp = document.createElement('canvas'); cvp.style.cssText = 'width:100%;height:100%;display:block'; host.appendChild(cvp);
var eng = null; try { eng = jOSEngine.create(cvp, { ground: false, grid: true, dist: 7, onReady: function (en) { try { en.world.cam.target.set(0, 0, 0); } catch (x) {} } }); } catch (x) { host.innerHTML = '<div style="padding:8px;color:#8aa;font-size:.66rem">aperçu indisponible</div>'; return; }
scadSess = { eng: eng, art: null };
var prom = (n.bion === 'pcb') ? jOSScad.footprintMesh(n.scad || n.name || 'ic', {}) : jOSScad.render(n.scad || 'cube([10,10,10]);', {});
try { prom.then(function (res) { if (!res || !scadSess || scadSess.eng !== eng) { try { res && res.dispose && res.dispose(); } catch (y) {} return; } scadSess.art = res; try { eng.add(res.mesh); } catch (x) {} }).catch(function () {}); } catch (x) {} }
// ---- arbre ----
function renderTree() { treeEl.innerHTML = doc.nodes.filter(function (n) { return !n.parent; }).map(function (n) {
return '<div class="fs__tn' + (n === sel ? ' sel' : '') + '" data-sel="' + n.nid + '">' + iconOf(n) + ' ' + (n.name || n.ploxion || n.bion || n.type) + (n.type === 'cubion' ? ' <span class="fs__muted">×' + (n.members || []).length + '</span>' : '') + '<span class="x" data-rm="' + n.nid + '">✕</span></div>'; }).join('') || '<div class="fs__muted">vide — ajoute des bions, assemble des cubions.</div>'; }
treeEl.addEventListener('click', function (ev) { var rm = ev.target.closest('[data-rm]'); if (rm) { var n = doc.nodes.filter(function (x) { return x.nid == rm.getAttribute('data-rm'); })[0]; if (n) removeNode(n); return; }
var s = ev.target.closest('[data-sel]'); if (s) { var n2 = doc.nodes.filter(function (x) { return x.nid == s.getAttribute('data-sel'); })[0]; select(n2 || null); } });
// ---- toolbar ----
// docCopy(src) : snapshot JSON du doc (src ou le doc courant). PRÉSERVE gx/gy (layout vue Logique) et
// copie n.inner RÉCURSIVEMENT (chaque bion a son propre monde fractal) → l'édition fractale + le layout
// wire survivent au save/reload (localStorage 'forge:doc').
function docCopy(src) { var d0 = src || doc; return { nodes: d0.nodes.map(function (n) { var c = { nid: n.nid, type: n.type, name: n.name };
if (n.type === 'part') { c.part = n.part; c.x = n.x; c.y = n.y; c.z = n.z; c.opts = n.opts || {}; }
else if (n.type === 'ploxion') { c.ploxion = n.ploxion; c.px = n.px; c.py = n.py; }
else if (n.type === 'cubion') { c.members = (n.members || []).slice(); }
else if (n.type === 'plugion') { /* dock pur */ }
else { c.bion = n.bion; }
if (n.core) c.core = true; if (n.cube) c.cube = { x: n.cube.x, y: n.cube.y, z: n.cube.z }; if (n.shape) c.shape = n.shape; if (n.size) c.size = n.size; if (n.count) c.count = n.count;
if (n.xer) c.xer = n.xer; if (n.faces) c.faces = JSON.parse(JSON.stringify(n.faces)); if (n.knobs) c.knobs = n.knobs.slice(); if (n.scad) c.scad = n.scad;
if (n.gx != null) c.gx = n.gx; if (n.gy != null) c.gy = n.gy; // layout vue Logique préservé
if (n.inner && n.inner.nodes) c.inner = docCopy(n.inner); // RÉCURSIF : monde intérieur (fractal)
if (n.parent) c.parent = n.parent; return c; }),
wires: (d0.wires || []).map(function (w) { return { from: w.from, fromPort: w.fromPort || 'out', to: w.to, toPort: w.toPort || 'in' }; }) }; }
function rootDoc() { return docStack.length ? docStack[0].doc : doc; } // la racine (si on est entré dans un bion)
// UNDO/REDO (Vague 1) : pile de SNAPSHOTS via jOSForgeHistory (cap 50). On enregistre après chaque
// mutation (logAct + removeNode) au niveau RACINE ; applyingHist coupe l'enregistrement pendant un
// undo/redo (garde-fou anti-boucle). Restaurer = remplacer le doc racine + rebuildAll.
function snapshot() { if (!hist || applyingHist || replaying || docStack.length) return; try { hist.record(docCopy(rootDoc())); } catch (x) {} updateHistBtns(); }
function updateHistBtns() { var u = container.querySelector('[data-undo]'), r = container.querySelector('[data-redo]'); if (u) u.disabled = !(hist && hist.canUndo && hist.canUndo()); if (r) r.disabled = !(hist && hist.canRedo && hist.canRedo()); }
function applyHistDoc(d) { if (!d || docStack.length) return; applyingHist = true;
try { clearScene(); doc = d; doc.nodes = doc.nodes || []; doc.wires = doc.wires || []; doc.nodes.forEach(function (n) { if (n.nid >= nid) nid = n.nid + 1; }); selM = []; sel = null; rebuildAll(); } catch (x) {}
applyingHist = false; }
function doUndo() { if (!hist) return; var d = hist.undo(); if (d) applyHistDoc(d); updateHistBtns(); }
function doRedo() { if (!hist) return; var d = hist.redo(); if (d) applyHistDoc(d); updateHistBtns(); }
container.querySelector('[data-save]').addEventListener('click', function () { try { localStorage.setItem('forge:doc', JSON.stringify(docCopy(rootDoc()))); } catch (x) {} var b = container.querySelector('[data-save]'); b.textContent = '✓'; setTimeout(function () { b.textContent = '💾'; }, 900); });
container.querySelector('[data-autodock]').addEventListener('click', autoDock);
container.querySelector('[data-fractale]').addEventListener('click', findFractal);
container.querySelector('[data-sim]').addEventListener('click', toggleSim);
container.querySelector('[data-replay]').addEventListener('click', replayBuild);
container.querySelector('[data-timeline]').addEventListener('click', timelineOverlay);
container.querySelector('[data-explode]').addEventListener('click', cycleExplode);
container.querySelector('[data-ranger]').addEventListener('click', ranger);
container.querySelector('[data-collapse]').addEventListener('click', collapse);
container.querySelector('[data-play]').addEventListener('click', function () { playOverlay(false); });
container.querySelector('[data-forge]').addEventListener('click', function () {
var name = (container.querySelector('[data-name]').value || 'Création').trim(), id = 'crea-' + Date.now().toString(36), d = docCopy();
window.jOSApps[id] = { manifest: { id: id, name: name, icon: '🧰' }, mount: function (c) { return window.jOSForgeStudio.run(c, d, { play: true }); } };
try { window.jOSForge && jOSForge.add && jOSForge.add({ id: id, name: name, icon: '🧰', kind: 'forge-studio', doc: d }); } catch (x) {}
markTsoin('forge', { id: id, cubes: d.nodes.filter(function (n) { return n.cube; }).length });
logAct({ act: 'forge', nom: name, blocs: d.nodes.filter(function (n) { return n.cube; }).length, wires: (d.wires || []).length });
try { window.jOS && jOS.openPloxion && jOS.openPloxion(id); } catch (x) {}
});
// 🧿 OS (.xos) : la composition de l'ultimate-forge devient UN OS FORGÉ COMPLET —
// export XOS1 (contrat : xerboxion-core docs/XOS1.md) au lieu d'un simple .plx plat.
// Chaque AMAS CONNEXE de cubes = un ploxion PLX1 embarqué (mêmes boxes/labels que l'ancien
// export métal + bouton ENERGIE lié à var0) ; les wires ENTRE amas = des xos.wire — le
// redstone de la forge qui devient réel sur le métal. Envoyé avec xos-send.sh ; un vieux
// kernel ignore les lignes xos.* et exécute quand même les plx.* (rétro-compatible).
// ASCII pur sur toutes les lignes générées (le métal ne parle pas UTF-8).
function asciiUp(s, n) { return String(s == null ? '' : s).normalize('NFKD').replace(/[^\x20-\x7E]/g, '').toUpperCase().slice(0, n || 16); }
// COMPILATEUR XOS1 pur (déterministe, zéro LLM) : {nodes, wires} → { lines, blocs, ploxions, wires }.
// AMAS = composantes connexes via les wires de FACES (blocs ADJACENTS, distance manhattan 1 —
// ceux que posent connectByFace/autoDock) ; un wire LONGUE-PORTÉE (tiré dans la vue Logique
// entre deux amas séparés) ne colle pas : il devient le xos.wire entre leurs ploxions.
// Les cubions comptent comme UN nœud (leurs wires internes sont déjà repliés par collapse()).
function compileXos(nom, doc2) {
var COLS = { bion: '40ff80', ploxion: 'b060ff', part: 'ffb45c', cubion: 'a07bff' };
var tops = doc2.nodes.filter(function (n) { return n.cube && !n.parent; }).slice(0, 30);
if (!tops.length) return null;
// union-find sur les nœuds top-level à cube
var idx = {}; tops.forEach(function (n, i) { idx[n.nid] = i; });
var par = tops.map(function (n, i) { return i; });
function find(i) { while (par[i] !== i) { par[i] = par[par[i]]; i = par[i]; } return i; }
function adj(a, b) { return Math.abs(a.cube.x - b.cube.x) + Math.abs(a.cube.y - b.cube.y) + Math.abs(a.cube.z - b.cube.z) === 1; }
(doc2.wires || []).forEach(function (w) { var a = idx[w.from], b = idx[w.to]; if (a == null || b == null || !adj(tops[a], tops[b])) return; var ra = find(a), rb = find(b); if (ra !== rb) par[ra] = rb; });
var byRoot = {}, list = [];
tops.forEach(function (n, i) { var r = find(i); if (!byRoot[r]) { byRoot[r] = []; list.push(byRoot[r]); } byRoot[r].push(n); });
function hasCore(c) { return c.some(function (n) { return n.core; }); }
// le core (xerboxion-core) rejoint la composante qu'il TOUCHE (déjà fait via les wires de faces) ; isolé → la première
for (var ci = 0; ci < list.length; ci++) if (hasCore(list[ci]) && list[ci].length === 1 && list.length > 1) { var lone = list.splice(ci, 1)[0][0]; list[0].unshift(lone); break; }
// ordre du fichier : la composante du core d'abord, puis par taille décroissante
list.sort(function (a, b) { return (hasCore(b) ? 1 : 0) - (hasCore(a) ? 1 : 0) || b.length - a.length; });
var compOf = {}; list.forEach(function (c, i2) { c.forEach(function (n) { compOf[n.nid] = i2; }); });
var blocs = 0; list.forEach(function (c) { blocs += c.length; });
// enveloppe XOS1 : xos.new + méta + couleur d'identité, puis les blocs plx, puis les câbles, puis xos.run
var out = ['xos.new ' + nom, 'xos.meta forge ultimate-forge', 'xos.meta blocs ' + blocs, 'xos.meta ploxions ' + list.length, 'xos.col 3fe0d0'];
// chaque composante = UN ploxion PLX1 (layout de l'ancien export métal : 1 cube = box 22x22
// sur la grille x/z RELATIVE à l'amas, label 3 lettres, signature, bouton ENERGIE + bind var0)
list.forEach(function (c, i3) {
var cubs = c.filter(function (n) { return n.type === 'cubion'; });
var titre = (cubs.length === 1 && c.every(function (n) { return n.type === 'cubion' || n.core; })) ? (asciiUp(cubs[0].name, 16) || 'CUBION') : asciiUp(nom, 13) + '-' + i3;
out.push('plx.new a ' + titre, 'plx.col a 3fe0d0', 'plx.var a 0 0');
var minx = Math.min.apply(null, c.map(function (n) { return n.cube.x; }));
var minz = Math.min.apply(null, c.map(function (n) { return n.cube.z; }));
c.forEach(function (n) { var px = 10 + (n.cube.x - minx) * 30, py = 8 + (n.cube.z - minz) * 30;
out.push('plx.box a ' + px + ' ' + py + ' 22 22 ' + (n.core ? '3fe0d0' : (COLS[n.type] || '8aa0c0')));
var lab = asciiUp(n.name || n.bion || '?', 3); if (lab) out.push('plx.txt a ' + (px + 3) + ' ' + (py + 7) + ' 1 ' + lab); });
var by = 8 + Math.max.apply(null, c.map(function (n) { return n.cube.z - minz; })) * 30 + 34;
out.push('plx.txt a 10 ' + by + ' 1 forge par l ultimate-forge . ' + c.length + ' blocs');
out.push('plx.btn a 10 ' + (by + 16) + ' 130 26 0 1 ENERGIE +1');
out.push('plx.bind a 150 ' + (by + 20) + ' 2 0');
out.push('plx.run a'); });
// le REDSTONE entre amas : chaque wire inter-composantes → xos.wire <ia> 0 <ib> 0 1
// (index d'ORDRE des ploxions dans le fichier, var0 → var0, delta 1) — dédupliqué par paire orientée
var seen = {}, wn = 0;
(doc2.wires || []).forEach(function (w) { var a = compOf[w.from], b = compOf[w.to]; if (a == null || b == null || a === b) return; var k = a + '>' + b; if (seen[k]) return; seen[k] = 1; out.push('xos.wire ' + a + ' 0 ' + b + ' 0 1'); wn++; });
out.push('xos.run'); // l'OS démarre à la FIN (badge topbar + xion.xos.run côté kernel)
return { lines: out, blocs: blocs, ploxions: list.length, wires: wn };
}
container.querySelector('[data-metal]').addEventListener('click', function () {
var name = (container.querySelector('[data-name]').value || 'CREATION').trim();
var nom = asciiUp(name, 16) || 'CREATION';
var os = compileXos(nom, doc); if (!os) return;
var blob = new Blob([os.lines.join('\n') + '\n'], { type: 'text/plain' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = nom.toLowerCase().replace(/[^a-z0-9-]/g, '-') + '.xos';
document.body.appendChild(a); a.click(); a.remove();
markTsoin('forge-xos', { blocs: os.blocs, ploxions: os.ploxions, wires: os.wires });
try { window.jOSPorts && jOSPorts.emit('mega-forge', 'xos', JSON.stringify({ nom: nom, blocs: os.blocs, ploxions: os.ploxions, wires: os.wires })); } catch (x) {}
});
// 🧿 MES OS : ouvre la bibliothèque d'OS forgés (sauver / rejouer-web / exporter / importer)
container.querySelector('[data-oslib]').addEventListener('click', function () { osLibOverlay(); });
// Vague 3-4 : lier (cubionlink) · mélanger (cubion déterministe) · publier + Mes créations (durable)
container.querySelector('[data-lier]').addEventListener('click', lierCubions);
container.querySelector('[data-melanger]').addEventListener('click', melanger);
container.querySelector('[data-publish]').addEventListener('click', function () { var e2 = pubPublish(); var b = container.querySelector('[data-publish]'); if (b) { b.textContent = e2 ? '✓ publié' : '📤 publier'; setTimeout(function () { b.textContent = '📤 publier'; }, 1000); } });
container.querySelector('[data-publib]').addEventListener('click', function () { pubLibOverlay(); });
// 📂 IMPORT .xos (best-effort HONNÊTE) : relit un OS forgé — chaque bloc plx.new = une composante,
// ses plx.box 22x22 → des cubes génériques (bion « vide ») re-posés en grille (la géométrie 2D
// des box redevient du x/z spatial), chaque xos.wire → un fil entre les premiers cubes des deux
// composantes. PAS une restauration exacte (les bions réels ne voyagent pas dans le .xos) :
// c'est la STRUCTURE de l'OS qui revient dans la forge, nommée par les labels 3 lettres.
var xosInput = document.createElement('input'); xosInput.type = 'file'; xosInput.accept = '.xos,.plx,text/plain'; xosInput.style.display = 'none'; container.appendChild(xosInput);
container.querySelector('[data-xos-import]').addEventListener('click', function () { xosInput.value = ''; xosInput.click(); });
xosInput.addEventListener('change', function () { var f = xosInput.files && xosInput.files[0]; if (!f) return; var rd = new FileReader(); rd.onload = function () { importXos(String(rd.result || '')); }; rd.readAsText(f); });
function importXos(txt) {
var comps = [], cur = null, xwires = [];
txt.split(/\r?\n/).forEach(function (ln) { var t = ln.trim().split(/\s+/);
if (t[0] === 'plx.new') { cur = { boxes: [], labs: {} }; comps.push(cur); }
else if (cur && t[0] === 'plx.box' && t[4] === '22' && t[5] === '22') cur.boxes.push({ px: +t[2], py: +t[3] });
else if (cur && t[0] === 'plx.txt') cur.labs[t[2] + ',' + t[3]] = t.slice(5).join(' ');
else if (t[0] === 'xos.wire') xwires.push({ a: +t[1], b: +t[3] }); });
comps = comps.filter(function (c) { return c.boxes.length; }); if (!comps.length) return;
reindexCells(); var ox = 2; doc.nodes.forEach(function (n) { if (n.cube && !n.parent) ox = Math.max(ox, n.cube.x + 2); }); // on pose À CÔTÉ de l'existant
var firsts = [], total = 0;
comps.forEach(function (c) { var w = 1, first = null;
c.boxes.forEach(function (b) { if (total >= 60) return; total++; // garde-fou : 60 cubes max
var gx = Math.round((b.px - 10) / 30), gz = Math.round((b.py - 8) / 30); if (gx + 1 > w) w = gx + 1;
var n = addBionCube('vide', ox + gx, 0, gz);
if (n) { var lab = c.labs[(b.px + 3) + ',' + (b.py + 7)]; if (lab) n.name = lab; if (!first) first = n; } });
firsts.push(first); ox += w + 1; }); // composantes côte à côte, espacées d'une cellule
xwires.forEach(function (w2) { var a2 = firsts[w2.a], b2 = firsts[w2.b]; if (a2 && b2 && !wireExists(a2, b2)) doc.wires.push({ from: a2.nid, fromPort: 'out', to: b2.nid, toPort: 'in' }); });
setView('scene'); select(null); renderTree(); refreshWireIfOpen(); updateCount(); markTsoin('import-xos', { ploxions: comps.length, blocs: total });
}
// ▶ JOUER (Vague 1) : deux modes dans l'overlay — 👁 aperçu (jOSForgeStudio.run) ↔ 🎮 jouer (jOSGameRun.play,
// le doc-forge devient une scène jouable FPS). Démonté proprement à chaque bascule et à la sortie.
function playOverlay(none) { var ov = document.createElement('div'); ov.style.cssText = 'position:absolute;inset:0;z-index:9;background:#05070e';
var host = document.createElement('div'); host.style.cssText = 'position:absolute;inset:0'; ov.appendChild(host);
var back = document.createElement('button'); back.textContent = '⬅ éditer'; back.className = 'fs__b sec'; back.style.cssText = 'position:absolute;top:8px;left:8px;z-index:10'; ov.appendChild(back);
var canGame = !!(window.jOSGameRun && jOSGameRun.play);
var toggle = document.createElement('button'); toggle.className = 'fs__b'; toggle.style.cssText = 'position:absolute;top:8px;left:88px;z-index:10'; if (canGame) ov.appendChild(toggle);
view.appendChild(ov); var mode = 'preview';
function startMode(m) { try { playSess && playSess.unmount && playSess.unmount(); } catch (x) {} playSess = null; host.innerHTML = ''; mode = m; toggle.textContent = (m === 'game') ? '👁 aperçu' : '🎮 jouer';
try { playSess = (m === 'game') ? jOSGameRun.play(host, docCopy(), { mode: 'fps' }) : window.jOSForgeStudio.run(host, docCopy(), { play: true }); } catch (x) { host.innerHTML = '<div style="padding:14px;color:#8aa">indisponible</div>'; } }
toggle.addEventListener('click', function () { startMode(mode === 'game' ? 'preview' : 'game'); });
startMode('preview');
back.addEventListener('click', function () { try { playSess && playSess.unmount && playSess.unmount(); } catch (x) {} playSess = null; ov.remove(); }); }
// ===== 🧿 MES OS : bibliothèque d'OS forgés. Sauver le doc courant en .xos (compileXos), le REJOUER
// dans le navigateur (jOSForgeStudio.runXos = le même 1-saut que le métal), l'exporter (.xos / prêt
// xos-send.sh), l'importer, le supprimer. Stock jOSBoxion ns=xos (clé = slug, contrat XOS1) + miroir
// localStorage qui sert de source à la LISTE (le boxion n'expose pas d'API list-keys). =====
// graine de démo « premier » (l'OS 2 ploxions REACTEUR→ECRAN de distro/plx/premier.xos, en dur) :
var XOS_SEED = ['xos.new PREMIER', 'xos.meta forge ultimate-forge', 'xos.meta blocs 5', 'xos.meta ploxions 2', 'xos.col 3fe0d0', 'xos.quota 0 24', 'xos.quota 1 8', 'plx.new a REACTEUR', 'plx.col a 40ff80', 'plx.var a 0 0', 'plx.box a 10 8 22 22 3fe0d0', 'plx.txt a 13 15 1 COR', 'plx.box a 40 8 22 22 40ff80', 'plx.txt a 43 15 1 SON', 'plx.txt a 10 44 1 forge par l ultimate-forge . 2 blocs', 'plx.btn a 10 60 130 26 0 1 ENERGIE +1', 'plx.bind a 150 64 2 0', 'plx.run a', 'plx.new a ECRAN', 'plx.col a b060ff', 'plx.var a 0 0', 'plx.box a 10 8 22 22 b060ff', 'plx.txt a 13 15 1 PIX', 'plx.txt a 10 44 1 recoit le signal du reacteur', 'plx.bind a 10 60 3 0', 'plx.run a', 'xos.wire 0 0 1 0 1', 'xos.run', ''].join('\n');
function xesc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'; }); }
function osSlug(s) { return String(s == null ? '' : s).toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'os'; }
function osLibLoad() { var lib = {}; try { var raw = localStorage.getItem('xos:library'); if (raw) lib = JSON.parse(raw) || {}; } catch (x) {} return lib; }
function osLibSave(lib) { try { localStorage.setItem('xos:library', JSON.stringify(lib)); } catch (x) {} try { if (window.jOSBoxion && jOSBoxion.saveSoon) jOSBoxion.saveSoon('xos', '__library__', lib, 'Bibliotheque OS'); } catch (x) {} }
function osLibPut(entry) { var lib = osLibLoad(); lib[entry.slug] = entry; osLibSave(lib); try { if (window.jOSBoxion && jOSBoxion.saveSoon) jOSBoxion.saveSoon('xos', entry.slug, entry, entry.nom); } catch (x) {} return lib; } // clé = slug (contrat)
function osLibDel(slug) { var lib = osLibLoad(); delete lib[slug]; osLibSave(lib); try { if (window.jOSBoxion && jOSBoxion.del) jOSBoxion.del('xos', slug); } catch (x) {} return lib; }
// seed UNE fois : si la biblio est vide ET jamais seedée (flag), pose « premier »
function osSeedIfEmpty() { var lib = osLibLoad(); var seeded = false; try { seeded = localStorage.getItem('xos:seeded') === '1'; } catch (x) {} if (Object.keys(lib).length || seeded) return lib; try { localStorage.setItem('xos:seeded', '1'); } catch (x) {} return osLibPut({ slug: 'premier', nom: 'PREMIER', xos: XOS_SEED, date: Date.now(), blocs: 5, ploxions: 2, wires: 1 }); }
function osDownload(entry) { try { var blob = new Blob([entry.xos], { type: 'text/plain' }); var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = (entry.slug || 'os') + '.xos'; document.body.appendChild(a); a.click(); a.remove(); } catch (x) {} }
function osSaveCurrent() { var name = (container.querySelector('[data-name]').value || 'CREATION').trim(); var nom = asciiUp(name, 16) || 'CREATION'; var os = compileXos(nom, doc); if (!os) return null;
var entry = { slug: osSlug(name), nom: nom, xos: os.lines.join('\n') + '\n', date: Date.now(), blocs: os.blocs, ploxions: os.ploxions, wires: os.wires }; osLibPut(entry); markTsoin('xos-save', { slug: entry.slug, blocs: os.blocs }); return entry; }
// hôte des overlays = le container ENTIER (couvre tout, mobile-first), positionné au besoin
function ensureOverlayHost() { if (getComputedStyle(container).position === 'static') container.style.position = 'relative'; return container; }
// ▶ REJOUER un OS forgé dans le navigateur (overlay plein-panneau + bouton retour) — comme playOverlay
function osRunOverlay(entry) { var ov = document.createElement('div'); ov.style.cssText = 'position:absolute;top:0;right:0;bottom:0;left:0;z-index:12;background:#05070e;display:flex;flex-direction:column';
var bar = document.createElement('div'); bar.style.cssText = 'flex:0 0 auto;display:flex;align-items:center;gap:8px;padding:8px;border-bottom:1px solid #16233c;background:#080c16';
var back = document.createElement('button'); back.textContent = '⬅ retour'; back.className = 'fs__b sec';
var ttl = document.createElement('div'); ttl.style.cssText = 'font-weight:800;font-size:.82rem'; ttl.textContent = '🧿 ' + entry.nom;
bar.appendChild(back); bar.appendChild(ttl);
var host = document.createElement('div'); host.style.cssText = 'flex:1;min-height:0;position:relative;overflow:auto';
ov.appendChild(bar); ov.appendChild(host); ensureOverlayHost().appendChild(ov);
var sess = null; try { sess = window.jOSForgeStudio.runXos(host, entry.xos, {}); } catch (x) { host.innerHTML = '<div style="padding:16px;color:#8aa">run indisponible</div>'; }
back.addEventListener('click', function () { try { sess && sess.unmount && sess.unmount(); } catch (x) {} ov.remove(); }); return ov; }
function osFmtDate(ts) { if (!ts) return ''; var d = new Date(ts); return d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); }
// 🧿 le PANNEAU bibliothèque
function osLibOverlay() { var ov = document.createElement('div'); ov.style.cssText = 'position:absolute;top:0;right:0;bottom:0;left:0;z-index:11;background:#070a12;display:flex;flex-direction:column';
var bar = document.createElement('div'); bar.style.cssText = 'flex:0 0 auto;display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:9px;border-bottom:1px solid #16233c;background:#080c16';
bar.innerHTML = '<b style="font-size:.86rem">🧿 Mes OS</b><span class="fs__muted">bibliotheque d OS forges — rejoue-les dans le navigateur</span><span style="flex:1;min-width:8px"></span>'
+ '<button class="fs__b" data-os-save>💾 sauver l OS courant</button><button class="fs__b sec" data-os-import>📂 importer .xos</button><button class="fs__b sec" data-os-close>⬅ retour</button>';
var listWrap = document.createElement('div'); listWrap.style.cssText = 'flex:1;min-height:0;overflow:auto;padding:10px;display:flex;flex-direction:column;gap:8px';
var fileIn = document.createElement('input'); fileIn.type = 'file'; fileIn.accept = '.xos,.plx,text/plain'; fileIn.style.display = 'none';
ov.appendChild(bar); ov.appendChild(listWrap); ov.appendChild(fileIn); ensureOverlayHost().appendChild(ov);
function renderList() { var lib = osSeedIfEmpty(); var slugs = Object.keys(lib).sort(function (a, b) { return (lib[b].date || 0) - (lib[a].date || 0); });
if (!slugs.length) { listWrap.innerHTML = '<div class="fs__muted" style="padding:22px;text-align:center">aucun OS — 💾 sauve l OS courant ou 📂 importe un .xos</div>'; return; }
listWrap.innerHTML = slugs.map(function (s) { var it = lib[s]; return '<div data-slug="' + xesc(s) + '" style="display:flex;align-items:center;gap:9px;flex-wrap:wrap;background:#0c1424;border:1px solid #22344f;border-radius:11px;padding:9px 11px">'
+ '<div style="min-width:0;flex:1 1 130px"><div style="font-weight:800;font-size:.82rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">🧿 ' + xesc(it.nom || s) + '</div>'
+ '<div class="fs__muted" style="font-size:.62rem">' + xesc(osFmtDate(it.date)) + ' · ' + (it.blocs || 0) + ' blocs · ' + (it.ploxions != null ? it.ploxions : '?') + ' ploxions · ' + (it.wires || 0) + ' câbles</div></div>'
+ '<button class="fs__b" data-run style="min-height:40px">▶ Run</button><button class="fs__b sec" data-dl style="min-height:40px">⬇ .xos</button>'
+ '<button class="fs__b sec" data-metal2 style="min-height:40px" title="prêt pour xos-send.sh (métal)">🧿 métal</button><button class="fs__b sec" data-del2 style="min-height:40px">🗑</button></div>'; }).join('');
}
listWrap.addEventListener('click', function (ev) { var row = ev.target.closest ? ev.target.closest('[data-slug]') : null; if (!row) return; var slug = row.getAttribute('data-slug'); var it = osLibLoad()[slug]; if (!it) return;
if (ev.target.closest('[data-run]')) osRunOverlay(it);
else if (ev.target.closest('[data-dl]')) osDownload(it);
else if (ev.target.closest('[data-metal2]')) { osDownload(it); markTsoin('forge-xos', { slug: slug, blocs: it.blocs }); try { window.jOSPorts && jOSPorts.emit('mega-forge', 'xos', JSON.stringify({ nom: it.nom, blocs: it.blocs, ploxions: it.ploxions, wires: it.wires })); } catch (x) {} }
else if (ev.target.closest('[data-del2]')) { osLibDel(slug); renderList(); } });
bar.querySelector('[data-os-close]').addEventListener('click', function () { ov.remove(); });
bar.querySelector('[data-os-save]').addEventListener('click', function () { var e2 = osSaveCurrent(); var b = bar.querySelector('[data-os-save]'); b.textContent = e2 ? '✓ sauvé' : '⚠ rien à forger'; setTimeout(function () { b.textContent = '💾 sauver l OS courant'; }, 1100); if (e2) renderList(); });
bar.querySelector('[data-os-import]').addEventListener('click', function () { fileIn.value = ''; fileIn.click(); });
fileIn.addEventListener('change', function () { var f = fileIn.files && fileIn.files[0]; if (!f) return; var rd = new FileReader(); rd.onload = function () { var txt = String(rd.result || ''); var m = /xos\.new\s+(\S+)/.exec(txt); var nm = m ? m[1] : (f.name.replace(/\.[a-z0-9]+$/i, '') || 'OS');
var entry = { slug: osSlug(nm) + '-' + Date.now().toString(36), nom: asciiUp(nm, 16) || 'OS', xos: txt, date: Date.now(), blocs: (txt.match(/plx\.box/g) || []).length, ploxions: (txt.match(/plx\.new/g) || []).length, wires: (txt.match(/xos\.wire/g) || []).length };
osLibPut(entry); markTsoin('xos-import-lib', { slug: entry.slug }); renderList(); }; rd.readAsText(f); });
renderList(); return ov; }
// ===== 📤 PUBLICATION DURABLE (Vague 4, non-destructif) : la création COURANTE (docCopy du doc racine +
// .xos compilé) sauvée dans le store du boxion de RS-7 via jOSBoxion (ns='forge-creations', clé=slug du
// nom) — {nom, doc, xos, date, blocs}. C'est le flywheel : forge → publie dans TON boxion (pas de push
// public, pas d'écriture de config code). « Mes créations » (docs de forge) ≠ « Mes OS » (.xos purs) :
// deux bibliothèques distinctes, aucune collision. Fallback + miroir localStorage 'forge:creations'
// (source plein-doc + hors-ligne) ; jOSBoxion.list fusionne les clés durables d'un autre appareil. =====
function pubLoad() { var lib = {}; try { var raw = localStorage.getItem('forge:creations'); if (raw) lib = JSON.parse(raw) || {}; } catch (x) {} return lib; }
function pubSaveLocal(lib) { try { localStorage.setItem('forge:creations', JSON.stringify(lib)); } catch (x) {} }
function pubPut(entry) { var lib = pubLoad(); lib[entry.slug] = entry; pubSaveLocal(lib); try { if (window.jOSBoxion && jOSBoxion.save) jOSBoxion.save('forge-creations', entry.slug, entry, entry.nom); } catch (x) {} return lib; }
function pubDel(slug) { var lib = pubLoad(); delete lib[slug]; pubSaveLocal(lib); try { if (window.jOSBoxion && jOSBoxion.del) jOSBoxion.del('forge-creations', slug); } catch (x) {} return lib; }
// résout l'entrée COMPLÈTE (doc + xos) : miroir local d'abord, sinon jOSBoxion.load (pull cross-device)
function pubResolve(slug, cb) { var lib = pubLoad(); if (lib[slug] && lib[slug].doc) { cb(lib[slug]); return; }
if (window.jOSBoxion && jOSBoxion.load) { jOSBoxion.load('forge-creations', slug).then(function (item) { cb(item && item.data ? item.data : (lib[slug] || null)); }, function () { cb(lib[slug] || null); }); }
else cb(lib[slug] || null); }
// PUBLIER la création courante : snapshot du doc RACINE + .xos compilé → store durable (clé = slug du nom)
function pubPublish() { var name = (container.querySelector('[data-name]').value || 'Ma création').trim();
var d = docCopy(rootDoc()), nomAscii = asciiUp(name, 16) || 'CREATION', os = null; try { os = compileXos(nomAscii, rootDoc()); } catch (x) {}
var blocs = d.nodes.filter(function (n) { return n.cube; }).length;
var entry = { slug: osSlug(name), nom: name, doc: d, xos: os ? (os.lines.join('\n') + '\n') : '', date: Date.now(), blocs: blocs, ploxions: os ? os.ploxions : 0, wires: (d.wires || []).length };
pubPut(entry); markTsoin('publish', { slug: entry.slug, blocs: blocs });
try { window.jOSPorts && jOSPorts.emit('mega-forge', 'publish', JSON.stringify({ nom: name, slug: entry.slug, blocs: blocs })); } catch (x) {}
return entry; }
// ROUVRIR une création publiée DANS la forge (remplace le doc courant ; le store n'est pas modifié)
function pubReopen(entry) { if (!entry || !entry.doc) return; if (docStack.length) goUpTo(0); try { clearScene(); } catch (x) {}
var nd; try { nd = JSON.parse(JSON.stringify(entry.doc)); } catch (x) { return; }
doc = nd; doc.nodes = doc.nodes || []; doc.wires = doc.wires || []; nid = 1; doc.nodes.forEach(function (n) { if (n.nid >= nid) nid = n.nid + 1; }); selM = []; sel = null;
try { rebuildAll(); } catch (x) {} setView('scene'); try { snapshot(); } catch (x) {}
try { container.querySelector('[data-name]').value = entry.nom || 'Ma création'; } catch (x) {}
if (hintEl) hintEl.textContent = '📤 rouvert : ' + (entry.nom || entry.slug); }
// 📚 le PANNEAU « Mes créations » (liste jOSBoxion + miroir) : ▶ rouvrir · 🧿 .xos · 🗑
function pubLibOverlay() { var ov = document.createElement('div'); ov.style.cssText = 'position:absolute;top:0;right:0;bottom:0;left:0;z-index:11;background:#070a12;display:flex;flex-direction:column';
var bar = document.createElement('div'); bar.style.cssText = 'flex:0 0 auto;display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:9px;border-bottom:1px solid #16233c;background:#080c16';
bar.innerHTML = '<b style="font-size:.86rem">📤 Mes créations</b><span class="fs__muted">publiées dans ton boxion — durable, cross-device</span><span style="flex:1;min-width:8px"></span>'
+ '<button class="fs__b" data-pub-now>📤 publier l actuelle</button><button class="fs__b sec" data-pub-close>⬅ retour</button>';
var listWrap = document.createElement('div'); listWrap.style.cssText = 'flex:1;min-height:0;overflow:auto;padding:10px;display:flex;flex-direction:column;gap:8px';
ov.appendChild(bar); ov.appendChild(listWrap); ensureOverlayHost().appendChild(ov);
function renderList() { var map = pubLoad();
function paint() { var slugs = Object.keys(map).sort(function (a, b) { return (map[b].date || 0) - (map[a].date || 0); });
if (!slugs.length) { listWrap.innerHTML = '<div class="fs__muted" style="padding:22px;text-align:center">aucune création publiée — 📤 publie l actuelle (ou depuis la barre).</div>'; return; }
listWrap.innerHTML = slugs.map(function (s) { var it = map[s]; return '<div data-slug="' + xesc(s) + '" style="display:flex;align-items:center;gap:9px;flex-wrap:wrap;background:#0c1424;border:1px solid #22344f;border-radius:11px;padding:9px 11px">'
+ '<div style="min-width:0;flex:1 1 130px"><div style="font-weight:800;font-size:.82rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">📦 ' + xesc(it.nom || s) + (it._stub ? ' <span class="fs__muted" style="font-weight:500">(autre appareil)</span>' : '') + '</div>'
+ '<div class="fs__muted" style="font-size:.62rem">' + xesc(osFmtDate(it.date)) + ' · ' + (it.blocs != null ? it.blocs : '?') + ' blocs · ' + (it.ploxions != null ? it.ploxions : '?') + ' ploxions</div></div>'
+ '<button class="fs__b" data-reopen style="min-height:40px">▶ rouvrir</button><button class="fs__b sec" data-xos3 style="min-height:40px">🧿 .xos</button><button class="fs__b sec" data-del3 style="min-height:40px">🗑</button></div>'; }).join('');
}
paint();
// cross-device : fusionne les clés durables absentes du miroir local (résolues à la demande)
try { if (window.jOSBoxion && jOSBoxion.authed && jOSBoxion.authed() && jOSBoxion.list) {
jOSBoxion.list('forge-creations').then(function (items) { var chg = false; (items || []).forEach(function (m) { if (m && m.key && !map[m.key]) { map[m.key] = { slug: m.key, nom: m.name || m.key, date: m.savedAt || 0, _stub: 1 }; chg = true; } }); if (chg) paint(); }, function () {}); } } catch (x) {}
}
listWrap.addEventListener('click', function (ev) { var row = ev.target.closest ? ev.target.closest('[data-slug]') : null; if (!row) return; var slug = row.getAttribute('data-slug');
if (ev.target.closest('[data-reopen]')) { pubResolve(slug, function (e2) { if (e2 && e2.doc) { pubReopen(e2); ov.remove(); } else if (hintEl) hintEl.textContent = '📤 création incomplète (doc absent)'; }); }
else if (ev.target.closest('[data-xos3]')) { pubResolve(slug, function (e2) { if (e2 && e2.xos) osDownload({ slug: e2.slug || slug, xos: e2.xos }); }); }
else if (ev.target.closest('[data-del3]')) { pubDel(slug); renderList(); } });
bar.querySelector('[data-pub-close]').addEventListener('click', function () { ov.remove(); });
bar.querySelector('[data-pub-now]').addEventListener('click', function () { var e2 = pubPublish(); var b = bar.querySelector('[data-pub-now]'); b.textContent = e2 ? '✓ publié' : '⚠'; setTimeout(function () { b.textContent = '📤 publier l actuelle'; }, 1100); renderList(); });
renderList(); return ov; }
// ===== VUE CÂBLAGE : forge à CUBIONS — bions/ploxions/parts en BLOCS Lego, câblés par ports typés.
// bions (blocs) → ⬛ cubion (bloc de bions) → 🔌 plugion (docking I/O) → connecte 2 plugions = ploxion. =====
var wireEl = container.querySelector('[data-wire]'), wsvg = container.querySelector('[data-wsvg]'), wnodes = {}, selM = [];
var d2 = container.querySelector('[data-2d]'), codeEl = container.querySelector('[data-code]'), crumbBar = container.querySelector('[data-crumbbar]'), docStack = [], crumbLabel = 'Spherion', explodeF = 0, xerSess = null, simTimer = null, buildLog = [], replaying = false, lastSim = null, simHud = null, scadSess = null, hist = null, applyingHist = false, tlSess = null, playSess = null;
function byId(id) { return doc.nodes.filter(function (x) { return x.nid == id; })[0] || null; }
function iconOf(n) { return n.type === 'part' ? '🧩' : n.type === 'cubion' ? '⬛' : n.type === 'plugion' ? '🔌' : n.type === 'ploxion' ? ((jOSApps[n.ploxion] && jOSApps[n.ploxion].manifest && jOSApps[n.ploxion].manifest.icon) || '▦') : '🧬'; }
// ports = les 6 FACES (RS-7 : chaque face une fonction) : +axes sorties (up/east/north), -axes entrées (down/west/south)
function nodePorts(n) { var F = { in: ['down', 'west', 'south'], out: ['up', 'east', 'north'] };
return n.type === 'bion' ? F : n.type === 'cubion' ? F : n.type === 'part' ? { in: ['pulse'], out: ['hit'] } : n.type === 'ploxion' ? { in: ['signal'], out: ['event'] } : n.type === 'plugion' ? { in: ['dock'], out: ['dock'] } : { in: ['in'], out: ['out'] }; }
function refreshWireIfOpen() { if (viewMode === 'wire') renderWire(); else if (viewMode === '2d') render2D(); else if (viewMode === 'code') renderCode(); }
var xerv = container.querySelector('[data-xerv]');
// === VUES VAGUE 2 (rs-4) : refs + sessions dédiées ===
var fusionEl = container.querySelector('[data-fusion]'), connEl = container.querySelector('[data-conn]'), forgevEl = container.querySelector('[data-forgev]'), suggestEl = container.querySelector('[data-suggest]'), exuiEl = container.querySelector('[data-exui]');
var forgeSess = null, explodeLines = null; // aperçu .xos jouable (Forge) + lignes 3D de l'éclatée
var exRange = exuiEl ? exuiEl.querySelector('[data-exrange]') : null;
if (exRange) exRange.addEventListener('input', function () { explodeF = (+this.value) / 100 * 2.4; applyExplode(); explodeLinesUpdate(); var ev2 = exuiEl.querySelector('[data-exval]'); if (ev2) ev2.textContent = explodeF <= 0.05 ? 'compact' : (Math.round(explodeF * 10) / 10) + '×'; });
function setView(m) { var prev = viewMode; viewMode = m; container.querySelectorAll('[data-view]').forEach(function (b) { b.classList.toggle('on', b.getAttribute('data-view') === m); });
wireEl.classList.toggle('on', m === 'wire'); d2.style.display = m === '2d' ? 'block' : 'none'; codeEl.style.display = m === 'code' ? 'block' : 'none'; xerv.style.display = m === 'xer' ? 'block' : 'none';
fusionEl.style.display = m === 'fusion' ? 'block' : 'none'; connEl.style.display = m === 'connexions' ? 'block' : 'none'; forgevEl.style.display = m === 'forge' ? 'block' : 'none'; suggestEl.style.display = m === 'suggest' ? 'block' : 'none';
exuiEl.classList.toggle('on', m === 'explode');
if (m !== 'xer' && xerSess) { try { xerSess.unmount(); } catch (x) {} xerSess = null; }
if (m !== 'forge' && forgeSess) { try { forgeSess.unmount(); } catch (x) {} forgeSess = null; }
if (prev === 'explode' && m !== 'explode') explodeReset(); // quitter l'éclatée = recompacter la scène
if (m === 'wire') renderWire(); else if (m === '2d') render2D(); else if (m === 'code') renderCode();
else if (m === 'xer') { try { xerSess = window.jOSForgeStudio.run(xerv, docCopy(), { play: false }); } catch (x) { xerv.innerHTML = '<div style="padding:14px;color:#8aa">aperçu indisponible</div>'; } }
else if (m === 'explode') renderExplode(); else if (m === 'fusion') renderFusion(); else if (m === 'connexions') renderConnexions(); else if (m === 'forge') renderForgeView(); else if (m === 'suggest') renderSuggest(); }
// ===== 💥 ÉCLATÉE : la scène 3D visible, cubes écartés du centre par un slider (explodeF), avec les
// liens du doc tracés en 3D entre les cubes écartés (LineSegments dans la scène → suit la caméra). =====
function explodeLinesUpdate() { if (!e || !e.THREE || !e.world) return;
if (explodeLines) { try { e.world.scene.remove(explodeLines); } catch (x) {} explodeLines = null; }
if (viewMode !== 'explode') return; var T = e.THREE, pts = [];
(doc.wires || []).forEach(function (w) { var a = byId(w.from), b = byId(w.to); if (a && a._cube && b && b._cube) { pts.push(a._cube.position.clone(), b._cube.position.clone()); } });
if (!pts.length) return; var geo = new T.BufferGeometry().setFromPoints(pts);
explodeLines = new T.LineSegments(geo, new T.LineBasicMaterial({ color: 0x5fe0c0, transparent: true, opacity: 0.55 })); try { e.add(explodeLines); } catch (x) {} }
function renderExplode() { if (!(explodeF > 0)) explodeF = 0.9; if (exRange) exRange.value = Math.round(explodeF / 2.4 * 100);
var ev2 = exuiEl.querySelector('[data-exval]'); if (ev2) ev2.textContent = (Math.round(explodeF * 10) / 10) + '×'; applyExplode(); explodeLinesUpdate(); }
function explodeReset() { if (explodeLines && e && e.world) { try { e.world.scene.remove(explodeLines); } catch (x) {} } explodeLines = null; explodeF = 0; try { applyExplode(); } catch (x) {} }
// ===== 🧲 FUSION : PRÉVISUALISATION du collapse (cubion/Spherion) SANS muter le doc. Rassemble tous les
// cubes-bions au centre en une forme compacte + stats. Un bouton lance le vrai collapse() si voulu. =====
function renderFusion() { var cubes = doc.nodes.filter(function (n) { return n.type === 'bion' && n.cube && !n.core && !n.parent; }); var count = cubes.length;
if (count < 2) { fusionEl.innerHTML = '<div class="fs__cmsg"><div style="font-size:2rem">🧲</div><h3 style="margin:8px 0;color:#dfe7ff">Fusion</h3>il faut au moins 2 cubes-bions pour prévisualiser un collapse.</div>'; return; }
var sphere = count >= 12, side = Math.max(1.3, Math.cbrt(count) * 1.1);
var chips = cubes.map(function (n) { var hex = '#' + ('000000' + (n.bion === 'vide' ? 0x8aa0c0 : xerColor(n.xer)).toString(16)).slice(-6); return '<span class="fs__fchip" style="background:' + hex + '">' + xesc((n.name || n.bion || '').slice(0, 8)) + '</span>'; }).join('');
var d = Math.min(240, 96 + count * 8);
fusionEl.innerHTML = '<div class="fs__fwrap">'
+ '<div class="fs__ftitle">🧲 Fusion <span class="fs__muted">— aperçu du collapse (ne modifie rien)</span></div>'
+ '<div class="fs__fshape" style="width:' + d + 'px;height:' + d + 'px;border-radius:' + (sphere ? '50%' : '16px') + '">' + chips + '</div>'
+ '<div class="fs__fstats"><b>' + count + '</b> bions → <b>' + (sphere ? '⚪ Spherion' : '⬛ cubion') + '</b> · taille ' + (Math.round(side * 10) / 10) + '</div>'
+ '<div class="fs__muted" style="max-width:340px;text-align:center">' + (sphere ? 'à ≥12 bions, l amas se collapse en Spherion (sphère).' : 'sous 12 bions, l amas se collapse en cubion (cube).') + '</div>'
+ '<button class="fs__b" data-do-collapse>⬛ collapser pour de vrai</button></div>';
var btn = fusionEl.querySelector('[data-do-collapse]'); if (btn) btn.addEventListener('click', function () { collapse(); setView('scene'); }); }
// ===== 🔌 CONNEXIONS : la vue d'ENSEMBLE lisible (n8n propre, LECTURE SEULE). Tous les liens du doc +
// les faces I/O (ploxions) + les liens de plugions (jOSPlug) sur un graphe circulaire ; couleur = type de
// xer (XERTYPES), câbles jugés incompatibles par la dernière simulation (lastSim.dropped) en ROUGE. =====
function renderConnexions() { var nodes = doc.nodes.filter(function (n) { return !n.parent; });
if (!nodes.length) { connEl.innerHTML = '<div class="fs__cmsg">rien à connecter — pose des bions.</div>'; return; }
var N = nodes.length, R = Math.max(120, N * 24), cx = R + 80, cy = R + 60, W = Math.round(cx * 2), H = Math.round(cy * 2 + 10), pos = {};
nodes.forEach(function (n, i) { var a = (i / N) * Math.PI * 2 - Math.PI / 2; pos[n.nid] = { x: cx + Math.cos(a) * R, y: cy + Math.sin(a) * R }; });
if (N === 1) pos[nodes[0].nid] = { x: cx, y: cy };
function hexOf(n) { return '#' + ('000000' + (n.core ? 0x5fe0c0 : n.type === 'cubion' ? 0xa07bff : n.type === 'plugion' ? 0xf0a35f : n.type === 'ploxion' ? 0x6fd0ff : n.bion === 'vide' ? 0x8aa0c0 : xerColor(n.xer)).toString(16)).slice(-6); }
var edges = ''; (doc.wires || []).forEach(function (w) { var a = pos[w.from], b = pos[w.to]; if (!a || !b) return; var an = byId(w.from), dr = isDropped(w), c = dr ? '#ff5a5a' : hexOf(an || {});
edges += '<line x1="' + a.x.toFixed(1) + '" y1="' + a.y.toFixed(1) + '" x2="' + b.x.toFixed(1) + '" y2="' + b.y.toFixed(1) + '" stroke="' + c + '" stroke-width="' + (dr ? 2.4 : 1.5) + '"' + (dr ? ' stroke-dasharray="6 5"' : ' opacity="0.55"') + '></line>'; });
// jOSPlug : liens de plugions entre ploxions présents dans le doc ; le reste = compté (externe)
var plugEdges = '', plugExtern = 0;
try { var pw = (window.jOSPlug && window.jOSPlug.wires) ? window.jOSPlug.wires() : null;
if (pw && pw.length) { var byPlox = {}; nodes.forEach(function (n) { if (n.type === 'ploxion') byPlox[n.ploxion] = n.nid; });
pw.forEach(function (w) { if (!w || !w.from || !w.to) return; var fn = byPlox[w.from.p], tn = byPlox[w.to.p]; if (fn != null && tn != null && pos[fn] && pos[tn]) { var a = pos[fn], b = pos[tn]; plugEdges += '<line x1="' + a.x.toFixed(1) + '" y1="' + a.y.toFixed(1) + '" x2="' + b.x.toFixed(1) + '" y2="' + b.y.toFixed(1) + '" stroke="#f0a35f" stroke-width="2" opacity="0.75" stroke-dasharray="1 4" stroke-linecap="round"></line>'; } else plugExtern++; }); } } catch (x) {}
var faceStubs = '', blobs = '';
nodes.forEach(function (n) { var p = pos[n.nid], c = hexOf(n), lab = xesc((n.name || n.ploxion || n.bion || n.type).slice(0, 12));
blobs += '<circle cx="' + p.x.toFixed(1) + '" cy="' + p.y.toFixed(1) + '" r="9" fill="' + c + '" stroke="#0a0e18" stroke-width="1.5"></circle><text x="' + p.x.toFixed(1) + '" y="' + (p.y - 13).toFixed(1) + '" fill="#cfe" font-size="10" text-anchor="middle" font-family="ui-monospace">' + lab + '</text>';
if (n.faces) { var fi = 0; Object.keys(n.faces).forEach(function (f) { var fc = n.faces[f]; if (!fc || !fc.ploxion) return; var base = Math.atan2(p.y - cy, p.x - cx), ang = base + (fi - 1) * 0.42; fi++; var ex = p.x + Math.cos(ang) * 30, ey = p.y + Math.sin(ang) * 30, fcol = fc.dir === 'out' ? '#5fe0c0' : '#f0d05f';
faceStubs += '<line x1="' + p.x.toFixed(1) + '" y1="' + p.y.toFixed(1) + '" x2="' + ex.toFixed(1) + '" y2="' + ey.toFixed(1) + '" stroke="' + fcol + '" stroke-width="1" opacity="0.45" stroke-dasharray="2 2"></line><text x="' + ex.toFixed(1) + '" y="' + ey.toFixed(1) + '" fill="' + fcol + '" font-size="8" text-anchor="middle" font-family="ui-monospace">' + xesc(fc.ploxion.slice(0, 10)) + '</text>'; }); } });
var nDrop = (lastSim && lastSim.dropped) ? lastSim.dropped.length : 0;
var bar = '🔌 Connexions — vue d ensemble <span class="fs__muted">· ' + (doc.wires || []).length + ' câbles' + (nDrop ? ' · <span style="color:#ff7a7a">' + nDrop + ' incompatibles</span>' : '') + (plugExtern ? ' · +' + plugExtern + ' liens plug externes' : '') + '</span>';
var leg = XERTYPES.map(function (t) { return '<span class="fs__cli"><i style="background:#' + ('000000' + Number(t.col).toString(16)).slice(-6) + '"></i>' + xesc(t.name) + '</span>'; }).join('') + '<span class="fs__cli"><i style="background:#ff5a5a"></i>incompatible</span><span class="fs__cli"><i style="background:#f0a35f"></i>plugion</span>';
connEl.innerHTML = '<div class="fs__cbar">' + bar + '</div><div class="fs__cscroll"><svg width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '">' + edges + plugEdges + faceStubs + blobs + '</svg></div><div class="fs__cleg">' + leg + '</div>'; }
// ===== ⚒ FORGE : le récap « prêt à forger » — nom, compteurs, la liste des ploxions qui seront générés
// (via compileXos → parseXos = ce que donne le .xos), un APERÇU .xos jouable (runXos, léger, zéro WebGL)
// et les 3 actions rassemblées (▶ jouer · ⚒ forger le ploxion · 🧿 OS .xos). =====
function renderForgeView() { var name = (container.querySelector('[data-name]').value || 'Création').trim(), nom = asciiUp(name, 16) || 'CREATION', os = compileXos(nom, doc);
if (!os) { forgevEl.innerHTML = '<div class="fs__cmsg">rien à forger — pose au moins un cube.</div>'; return; }
var xosText = os.lines.join('\n') + '\n', model = null; try { model = window.jOSForgeStudio.parseXos(xosText); } catch (x) {}
var plist = ((model && model.ploxions) || []).map(function (p) { return '<li><b>' + xesc(p.title) + '</b> <span class="fs__muted">· ' + p.els.filter(function (e2) { return e2.k === 'box'; }).length + ' blocs</span></li>'; }).join('');
forgevEl.innerHTML = '<div class="fs__fgwrap">'
+ '<div class="fs__fgtitle">⚒ Prêt à forger : <b>' + xesc(name) + '</b></div>'
+ '<div class="fs__fgstats"><span><b>' + os.blocs + '</b> blocs</span><span><b>' + os.ploxions + '</b> ploxions</span><span><b>' + os.wires + '</b> câbles</span></div>'
+ '<div class="fs__fgcols"><div class="fs__fgcol"><h4>ploxions générés</h4><ol class="fs__fglist">' + (plist || '<li class="fs__muted">—</li>') + '</ol></div>'
+ '<div class="fs__fgcol"><h4>aperçu (.xos jouable)</h4><div class="fs__fgprev" data-fgprev></div></div></div>'
+ '<div class="fs__fgacts"><button class="fs__b sec" data-fg-play>▶ jouer</button><button class="fs__b" data-fg-forge>⚒ forger le ploxion</button><button class="fs__b sec" data-fg-os>🧿 OS (.xos)</button></div></div>';
var host = forgevEl.querySelector('[data-fgprev]'); if (host) { try { forgeSess = window.jOSForgeStudio.runXos(host, xosText, {}); } catch (x) { host.innerHTML = '<div class="fs__muted" style="padding:10px">aperçu indisponible</div>'; } }
var pb = forgevEl.querySelector('[data-fg-play]'); if (pb) pb.addEventListener('click', function () { playOverlay(false); });
var fb = forgevEl.querySelector('[data-fg-forge]'); if (fb) fb.addEventListener('click', function () { var b = container.querySelector('[data-forge]'); if (b) b.click(); }); // réutilise le handler existant
var ob = forgevEl.querySelector('[data-fg-os]'); if (ob) ob.addEventListener('click', function () { var b = container.querySelector('[data-metal]'); if (b) b.click(); }); }
// ===== ✨ SUGGESTIONS : window.jOSSynthPalette (déterministe, zéro LLM) propose les prochaines compos à
// partir des bions déjà posés (suggestFor) + les paires jamais assemblées (candidates). Chaque carte =
// « et si tu ajoutais X » cliquable → pose la composition (2 cubes source→view câblés). =====
function renderSuggest() { suggestEl.innerHTML = '<div class="fs__sgwrap"><div class="fs__sgtitle">✨ Suggestions <span class="fs__muted">compositions déterministes (zéro LLM)</span></div><div class="fs__sglist" data-sglist><div class="fs__muted" style="padding:12px">chargement…</div></div></div>';
var listEl = suggestEl.querySelector('[data-sglist]'), pal = window.jOSSynthPalette;
if (!pal) { listEl.innerHTML = '<div class="fs__muted" style="padding:12px">jOSSynthPalette absent — pas de suggestions.</div>'; return; }
function paint() { var cands = [], seen = {};
try { var bnodes = doc.nodes.filter(function (n) { return n.type === 'bion' && !n.parent && !n.core; });
bnodes.forEach(function (n) { if (typeof pal.suggestFor !== 'function') return; (pal.suggestFor(n, { limit: 6 }) || []).forEach(function (c) { if (c && !seen[c.id]) { seen[c.id] = 1; cands.push(c); } }); });
if (typeof pal.candidates === 'function') (pal.candidates() || []).forEach(function (c) { if (c && !seen[c.id]) { seen[c.id] = 1; cands.push(c); } }); } catch (x) { cands = []; }
if (!cands.length) { listEl.innerHTML = '<div class="fs__muted" style="padding:12px">aucune suggestion pour cette construction.</div>'; return; }
listEl.innerHTML = cands.slice(0, 30).map(function (c, i) { var label = xesc(c.label || c.id || ('composition ' + (i + 1))), sub = xesc((c.sourceBion || '') + (c.viewBion ? ' + ' + c.viewBion : '') + (c.tier != null ? ' · tier ' + c.tier : ''));
return '<button class="fs__sgcard" data-sg="' + i + '"><span class="fs__sgico">✨</span><span class="fs__sgtxt"><b>' + label + '</b>' + (sub ? '<span class="fs__muted">' + sub + '</span>' : '') + '</span><span class="fs__sgadd">+ poser</span></button>'; }).join('');
[].forEach.call(listEl.querySelectorAll('[data-sg]'), function (b) { b.addEventListener('click', function () { applySuggestion(cands[+b.getAttribute('data-sg')]); }); }); }
if (typeof pal.load === 'function') { try { var pr = pal.load(); if (pr && pr.then) pr.then(function () { paint(); }, function () { paint(); }); else paint(); } catch (x) { paint(); } } else paint(); }
// pose une suggestion : candidate source→view = 2 cubes-bions adjacents câblés ; sinon 1 cube.
function applySuggestion(c) { if (!c) return; setView('scene'); reindexCells();
var core = doc.nodes.filter(function (n) { return n.core; })[0], ox = core ? core.cube.x : 0, oy = core ? core.cube.y : 0, oz = core ? core.cube.z : 0;
function freeCell() { var offs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]; for (var r = 1; r < 10; r++) { for (var i = 0; i < offs.length; i++) { var x = ox + offs[i][0] * r, y = oy + offs[i][1] * r, z = oz + offs[i][2] * r; if (!cells[cellKey(x, y, z)]) return [x, y, z]; } } return [ox + 1, oy, oz]; }
if (c.source && c.view) { var t = freeCell(), a = addBionCube(c.sourceBion, t[0], t[1], t[2]); if (a) a.synthId = c.source; reindexCells();
var t2 = (!cells[cellKey(t[0] + 1, t[1], t[2])]) ? [t[0] + 1, t[1], t[2]] : freeCell(), b = addBionCube(c.viewBion, t2[0], t2[1], t2[2]); if (b) b.synthId = c.view;
if (a && b) { var fx = t2[0] - t[0], fy = t2[1] - t[1], fz = t2[2] - t[2]; if (Math.abs(fx) + Math.abs(fy) + Math.abs(fz) === 1) connectByFace(a, b, fx, fy, fz); else doc.wires.push({ from: a.nid, fromPort: 'out', to: b.nid, toPort: 'in' }); }
if (hintEl) hintEl.textContent = '✨ posé : ' + c.sourceBion + ' → ' + c.viewBion; }
else { var t3 = freeCell(), n = addBionCube(c.viewBion || c.sourceBion || c.bion || c.id, t3[0], t3[1], t3[2]); if (n && c.id) n.synthId = c.id; if (hintEl) hintEl.textContent = '✨ posé : ' + (c.label || c.id); }
markTsoin('suggest-apply', { id: c.id }); renderTree(); refreshWireIfOpen(); updateCount(); } // VUE XER = aperçu réel du rendu
function render2D() { var r = d2.getBoundingClientRect(); var dpr = Math.min(2, window.devicePixelRatio || 1); d2.width = r.width * dpr; d2.height = r.height * dpr; var g = d2.getContext('2d'); g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, r.width, r.height);
var cubes = doc.nodes.filter(function (n) { return n.cube && !n.parent; }); if (!cubes.length) return;
var minx = 1e9, maxx = -1e9, minz = 1e9, maxz = -1e9; cubes.forEach(function (n) { minx = Math.min(minx, n.cube.x); maxx = Math.max(maxx, n.cube.x); minz = Math.min(minz, n.cube.z); maxz = Math.max(maxz, n.cube.z); });
var pad = 44, s = Math.max(18, Math.min(60, Math.min((r.width - pad * 2) / ((maxx - minx) + 1), (r.height - pad * 2) / ((maxz - minz) + 1))));
function px(x) { return pad + (x - minx) * s + s / 2; } function pz(z) { return pad + (z - minz) * s + s / 2; }
g.lineWidth = 1.5; (doc.wires || []).forEach(function (w) { var a = byId(w.from), b = byId(w.to); if (a && a.cube && b && b.cube) { g.strokeStyle = isDropped(w) ? 'rgba(255,90,90,.8)' : 'rgba(95,224,192,.45)'; g.beginPath(); g.moveTo(px(a.cube.x), pz(a.cube.z)); g.lineTo(px(b.cube.x), pz(b.cube.z)); g.stroke(); } });
cubes.forEach(function (n) { var hex = '#' + ('000000' + (n.core ? 0x5fe0c0 : n.bion === 'vide' ? 0x8aa0c0 : xerColor(n.xer)).toString(16)).slice(-6); g.globalAlpha = n.bion === 'vide' ? 0.3 : 0.88; g.fillStyle = hex; var w = s * 0.82; g.fillRect(px(n.cube.x) - w / 2, pz(n.cube.z) - w / 2, w, w); g.globalAlpha = 1; g.fillStyle = '#04120e'; g.font = '9px ui-monospace'; g.textAlign = 'center'; g.fillText((n.name || n.bion || '').slice(0, 7), px(n.cube.x), pz(n.cube.z) + 3); }); }
function renderCode() { var L = ['# ' + (container.querySelector('[data-name]').value || 'création') + ' (Spherion · niveau ' + docStack.length + ')', ''];
doc.nodes.filter(function (n) { return !n.parent; }).forEach(function (n) { L.push('· ' + n.type + ' ' + (n.name || n.bion || n.ploxion || '') + (n.cube ? ' @(' + n.cube.x + ',' + n.cube.y + ',' + n.cube.z + ')' : '') + (n.xer ? ' :' + n.xer : '') + (n.type === 'cubion' ? ' {' + (n.members || []).length + ' bions}' : ''));
if (n.faces) Object.keys(n.faces).forEach(function (f) { var fc = n.faces[f]; if (fc && fc.ploxion) L.push(' face ' + f + ' ' + (fc.dir || '') + ' → ' + fc.ploxion); }); });
if ((doc.wires || []).length) { L.push('', '# connexions'); doc.wires.forEach(function (w) { var a = byId(w.from), b = byId(w.to); L.push(' ' + (a ? (a.name || a.bion || a.type) : w.from) + '.' + (w.fromPort || '') + ' → ' + (b ? (b.name || b.bion || b.type) : w.to) + '.' + (w.toPort || '')); }); }
codeEl.textContent = L.join('\n'); }
// ===== ÉDITION FRACTALE : entrer DANS un bion → son propre monde 3D (des blocs dans des blocs) =====
function clearScene() { if (explodeLines && e && e.world) { try { e.world.scene.remove(explodeLines); } catch (x) {} explodeLines = null; }
doc.nodes.forEach(function (n) { if (n._cube) { try { e.world.scene.remove(n._cube); } catch (x) {} n._cube = null; } if (n._obj) { try { e.world.scene.remove(n._obj); } catch (x) {} n._obj = null; } if (n._inst) { try { n._inst.unmount && n._inst.unmount(); } catch (x) {} n._inst = null; } }); Object.keys(panelEls).forEach(function (k) { try { panelEls[k].remove(); } catch (x) {} }); panelEls = {}; }
function rebuildAll() { explodeF = 0; reindexCells(); rebuildParts(); rebuildCubes(); doc.nodes.filter(function (n) { return n.type === 'ploxion'; }).forEach(function (n) { mountPanel(n); }); select(null); renderTree(); refreshWireIfOpen(); updateCount(); }
function enterBion(n) { if (!n || n.core) return; n.inner = n.inner || { nodes: [], wires: [] }; docStack.push({ doc: doc, label: crumbLabel }); clearScene(); doc = n.inner; doc.wires = doc.wires || []; crumbLabel = (n.name || n.bion); doc.nodes.forEach(function (x) { if (x.nid >= nid) nid = x.nid + 1; }); rebuildAll(); renderCrumb(); markTsoin('enter', { bion: n.bion }); logAct({ act: 'enter', bion: n.bion }); }
function goUpTo(idx) { if (!docStack.length) return; clearScene(); while (docStack.length > idx) { var prev = docStack.pop(); doc = prev.doc; crumbLabel = prev.label; } doc.wires = doc.wires || []; rebuildAll(); renderCrumb(); }
function renderCrumb() { if (!crumbBar) return; if (!docStack.length) { crumbBar.innerHTML = ''; return; }
var html = '<span class="cb core" data-up="0">⌂</span>'; docStack.forEach(function (s, i) { if (i > 0) html += '<span class="cb" data-up="' + i + '">' + s.label + '</span>'; }); html += '<span class="cb">▸ ' + crumbLabel + '</span>';
crumbBar.innerHTML = html; [].forEach.call(crumbBar.querySelectorAll('[data-up]'), function (b) { b.addEventListener('click', function () { goUpTo(+b.getAttribute('data-up')); }); }); }
container.querySelectorAll('[data-view]').forEach(function (b) { b.addEventListener('click', function () { setView(b.getAttribute('data-view')); }); });
container.querySelector('[data-cubion]').addEventListener('click', formCubion);
container.querySelector('[data-plugion]').addEventListener('click', addPlugion);
function pinCenter(nid, dir, port) { var el = wnodes[nid]; if (!el) return null; var pin = el.querySelector('.fs__pin.' + dir + '[data-port="' + port + '"]'); if (!pin) return null; var wr = wireEl.getBoundingClientRect(), pr = pin.getBoundingClientRect();
return { x: pr.left - wr.left + wireEl.scrollLeft + pr.width / 2, y: pr.top - wr.top + wireEl.scrollTop + pr.height / 2 }; }
// un câble est « dropped » si la dernière simulation l'a jugé de types incompatibles (jOSBionSim)
function isDropped(w) { if (!lastSim || !lastSim.dropped) return false; for (var i = 0; i < lastSim.dropped.length; i++) { var d = lastSim.dropped[i]; if (d.from === w.from && d.to === w.to) return true; } return false; }
function drawWires(temp) {
wsvg.innerHTML = (doc.wires || []).map(function (w, i) { var a = pinCenter(w.from, 'out', w.fromPort || 'out'), b = pinCenter(w.to, 'in', w.toPort || 'in'); if (!a || !b) return ''; var dr = isDropped(w); return '<path data-wi="' + i + '"' + (dr ? ' style="stroke:#ff5a5a;stroke-dasharray:6 5"' : '') + ' d="' + segPath(a, b) + '"></path>'; }).join('') + (temp ? '<path style="stroke:#f0a35f;stroke-dasharray:5 4" d="' + segPath(temp.a, temp.b) + '"></path>' : ''); }
function segPath(a, b) { var dx = Math.max(30, Math.abs(b.x - a.x) * .5); return 'M' + a.x + ',' + a.y + ' C' + (a.x + dx) + ',' + a.y + ' ' + (b.x - dx) + ',' + b.y + ' ' + b.x + ',' + b.y; }
function renderWire() {
Object.keys(wnodes).forEach(function (k) { wnodes[k].remove(); }); wnodes = {};
doc.nodes.filter(function (n) { return !n.parent; }).forEach(function (n, i) { if (n.gx == null) { n.gx = 40 + (i % 4) * 165; n.gy = 54 + Math.floor(i / 4) * 100; }
var P = nodePorts(n); var el = document.createElement('div'); el.className = 'fs__wnode ' + n.type + (n === sel ? ' sel' : '') + (selM.indexOf(n.nid) >= 0 ? ' selm' : ''); el.style.left = n.gx + 'px'; el.style.top = n.gy + 'px';
var ins = P.in.map(function (p) { return '<div class="port"><span class="fs__pin in" data-nid="' + n.nid + '" data-port="' + p + '"></span>' + p + '</div>'; }).join('');
var outs = P.out.map(function (p) { return '<div class="port"><span class="fs__pin out" data-nid="' + n.nid + '" data-port="' + p + '"></span>' + p + '</div>'; }).join('');
var mem = n.type === 'cubion' ? '<div class="members">' + (n.members || []).map(function (m) { var mn = byId(m); return mn ? iconOf(mn) : ''; }).join(' ') + ' (' + (n.members || []).length + ' bions)</div>' : '';
el.innerHTML = '<div class="hd"><span class="sm" title="sélectionner">' + (selM.indexOf(n.nid) >= 0 ? '▪' : '▫') + '</span>' + iconOf(n) + '<span class="nm">' + (n.name || n.ploxion || n.bion || n.type) + '</span><span class="z" title="tester">⚡</span></div><div class="body"><div class="ins">' + ins + '</div><div class="outs">' + outs + '</div></div>' + mem;
wireEl.appendChild(el); wnodes[n.nid] = el;
el.querySelector('.sm').addEventListener('click', function (ev) { ev.stopPropagation(); var i2 = selM.indexOf(n.nid); if (i2 >= 0) selM.splice(i2, 1); else selM.push(n.nid); renderWire(); });
el.querySelector('.hd').addEventListener('pointerdown', function (ev) { if (ev.target.classList.contains('z') || ev.target.classList.contains('sm')) return; select(n); dragNode(n, el, ev); });
el.querySelector('.z').addEventListener('click', function (ev) { ev.stopPropagation(); testPulse(n); });
[].forEach.call(el.querySelectorAll('.fs__pin.out'), function (pin) { pin.addEventListener('pointerdown', function (ev) { ev.preventDefault(); ev.stopPropagation(); startLink(n, pin.getAttribute('data-port'), ev); }); });
});
drawWires();
}
function dragNode(n, el, ev) { ev.preventDefault(); var sx = ev.clientX, sy = ev.clientY, ox = n.gx, oy = n.gy;
function mv(e2) { n.gx = Math.max(0, Math.round((ox + e2.clientX - sx) / 8) * 8); n.gy = Math.max(0, Math.round((oy + e2.clientY - sy) / 8) * 8); el.style.left = n.gx + 'px'; el.style.top = n.gy + 'px'; drawWires(); }
function up() { document.removeEventListener('pointermove', mv); document.removeEventListener('pointerup', up); }
document.addEventListener('pointermove', mv); document.addEventListener('pointerup', up); }
function startLink(n, port, ev) { var a = pinCenter(n.nid, 'out', port);
function mv(e2) { var wr = wireEl.getBoundingClientRect(); drawWires({ a: a, b: { x: e2.clientX - wr.left + wireEl.scrollLeft, y: e2.clientY - wr.top + wireEl.scrollTop } }); }
function up(e2) { document.removeEventListener('pointermove', mv); document.removeEventListener('pointerup', up);
var tgt = document.elementFromPoint(e2.clientX, e2.clientY); var pin = tgt && tgt.closest ? tgt.closest('.fs__pin.in') : null; var box = tgt && tgt.closest ? tgt.closest('.fs__wnode') : null;
var tid = pin ? +pin.getAttribute('data-nid') : null, tport = pin ? pin.getAttribute('data-port') : null;
if (!tid && box) { Object.keys(wnodes).forEach(function (k) { if (wnodes[k] === box) tid = +k; }); tport = nodePorts(byId(tid)).in[0]; }
if (tid && tid !== n.nid && !doc.wires.some(function (w) { return w.from === n.nid && w.fromPort === port && w.to === tid && w.toPort === tport; })) { doc.wires.push({ from: n.nid, fromPort: port, to: tid, toPort: tport }); }
drawWires(); }
document.addEventListener('pointermove', mv); document.addEventListener('pointerup', up); }
wsvg.addEventListener('click', function (ev) { var p = ev.target.closest('path[data-wi]'); if (!p) return; var i = +p.getAttribute('data-wi'); doc.wires.splice(i, 1); drawWires(); });
function testPulse(n) { (doc.wires || []).filter(function (w) { return w.from === n.nid; }).forEach(function (w) { var el = wnodes[w.to]; if (el) { el.style.boxShadow = '0 0 0 2px #5fe0c0'; setTimeout(function () { el.style.boxShadow = ''; }, 260); } });
var src = wnodes[n.nid]; if (src) { src.style.boxShadow = '0 0 0 2px #f0a35f'; setTimeout(function () { src.style.boxShadow = ''; }, 200); } }
// ⬛ CUBION : assemble les blocs sélectionnés en UN bloc-de-bions ; fils externes redirigés vers ses ports in/out.
function formCubion() { if (selM.length < 1) { setView('wire'); return; } var members = selM.slice();
var gx = 0, gy = 0; members.forEach(function (m) { var mn = byId(m); if (mn) { gx += mn.gx || 0; gy += mn.gy || 0; } }); gx = Math.round(gx / members.length); gy = Math.round(gy / members.length) + 40;
var cub = { nid: nid++, type: 'cubion', name: 'cubion', members: members, gx: gx, gy: gy };
members.forEach(function (m) { var mn = byId(m); if (mn) mn.parent = cub.nid; });
(doc.wires || []).forEach(function (w) { var fi = members.indexOf(w.from) >= 0, ti = members.indexOf(w.to) >= 0; if (fi && ti) return; if (fi) { w.from = cub.nid; w.fromPort = 'out'; } if (ti) { w.to = cub.nid; w.toPort = 'in'; } });
doc.nodes.push(cub); selM = []; select(cub); renderWire(); renderTree(); }
// 🔌 PLUGION : docking posé sur un cubion (relais I/O) ; connecte 2 plugions = docke 2 cubions → ploxion.
function addPlugion() { var host = (selM.length === 1 ? byId(selM[0]) : (sel && sel.type === 'cubion' ? sel : null));
var plug = { nid: nid++, type: 'plugion', name: 'plugion', gx: (host ? (host.gx || 40) + 155 : 40), gy: (host ? host.gy || 54 : 54) };
doc.nodes.push(plug); if (host && host.type === 'cubion') doc.wires.push({ from: host.nid, fromPort: 'out', to: plug.nid, toPort: 'dock' });
selM = []; select(plug); renderWire(); renderTree(); }
// ===== PORTS/TYPES EXTERNALISÉS (Vague 0) : /ploxion-io.json fait foi ; les littéraux BIONPORTS/XERTYPES
// restent en FALLBACK si le fetch échoue. Async, non bloquant : on ré-rend quand ça arrive. =====
try { fetch('/ploxion-io.json', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (d) {
if (!d) return; forgeIO = d; // registre I/O pour la simulation typée
if (d._bionPorts) BIONPORTS = d._bionPorts; // clé PRÉFIXÉE _bionPorts
if (d._xerTypes && d._xerTypes.length) XERTYPES = d._xerTypes.map(function (t) { return { id: t.id, name: t.name, col: Number(t.col) }; });
try { window.__PLOXION_IO__ = d; } catch (x) {} // cache global (jOSBionSim.run le relit)
try { renderLib(); if (sel) select(sel); } catch (x) {} // ré-render biblio + inspecteur
}).catch(function () {}); } catch (x) {}
// INIT UNDO/REDO : pile fraîche (pas la globale partagée) + snapshot de départ + branchement des boutons.
hist = (window.jOSForgeHistory && jOSForgeHistory.create) ? jOSForgeHistory.create({ cap: 50 }) : (window.jOSForgeHistory || null);
try { if (hist && hist.record) hist.record(docCopy(rootDoc())); } catch (x) {}
var ubtn = container.querySelector('[data-undo]'); if (ubtn) ubtn.addEventListener('click', doUndo);
var rbtn = container.querySelector('[data-redo]'); if (rbtn) rbtn.addEventListener('click', doRedo);
updateHistBtns();
renderLib(); renderTree(); select(null);
return { unmount: function () { if (simTimer) clearInterval(simTimer); if (xerSess) { try { xerSess.unmount(); } catch (x) {} } if (forgeSess) { try { forgeSess.unmount(); } catch (x) {} } disposeScad(); if (tlSess) { try { tlSess.destroy(); } catch (x) {} } if (playSess) { try { playSess.unmount(); } catch (x) {} } window.removeEventListener('pointermove', onWinMove); window.removeEventListener('pointerup', onWinUp); doc.nodes.forEach(function (n) { try { n._inst && n._inst.unmount && n._inst.unmount(); } catch (x) {} }); try { e.dispose(); } catch (x) {} container.innerHTML = ''; } };
}
window.jOSApps = window.jOSApps || {};
// ===== XUI (contrat v0, bion jOSXui) : describe() = ce que la forge a produit, non monté =====
// p1 = mes créations publiées (LA donnée maîtresse : forge:creations, le miroir local de
// pubPut) ; p2 = la bibliothèque d'OS .xos (xos:library). Pur, jamais le DOM, ne throw jamais.
function describe() {
var items = [];
try {
var lib = {}; try { lib = JSON.parse(localStorage.getItem('forge:creations')) || {}; } catch (x) {}
var slugs = Object.keys(lib);
items.push({ p: 1, kind: 'stat', label: '🔮 créations forgées', value: slugs.length });
var arr = slugs.map(function (s) { return lib[s]; }).filter(function (e) { return e && e.nom; })
.sort(function (a, b) { return (b.date || 0) - (a.date || 0); });
if (arr.length) items.push({ p: 2, kind: 'list', label: 'dernières', items: arr.slice(0, 4).map(function (e) {
return { label: String(e.nom).slice(0, 24), value: (e.blocs | 0) + ' blocs' + (e.ploxions ? ' · ' + e.ploxions + ' px' : '') }; }) });
var xos = {}; try { xos = JSON.parse(localStorage.getItem('xos:library')) || {}; } catch (x) {}
items.push({ p: 3, kind: 'stat', label: 'OS .xos en bibliothèque', value: Object.keys(xos).length });
} catch (e) { items = [{ p: 1, kind: 'text', label: '🔮 forge', value: 'bibliothèque indisponible' }]; }
return { v: 1, id: 'mega-forge', title: 'Ultimate Forge', icon: '🔮', items: items };
}
window.jOSApps['mega-forge'] = { manifest: { id: 'mega-forge', name: 'Ultimate Forge', icon: '🔮' }, mount: mount, describe: describe };
try { window.jOSApps['ultimate-forge'] = window.jOSApps['mega-forge']; } catch (x) {} // alias : la forge ultime = le premier Spherion
// helper global : ouvrir la Ultimate Forge EN PARTANT d'un ploxion (dispo depuis n'importe où)
window.jOSForgeFrom = function (id) { try { if (window.jOS && jOS.openPloxion) jOS.openPloxion('mega-forge', { seed: id }); } catch (x) {} };
})();
</script>