Through the see-through cabinet both rail faces showed as two grey boards, and a server of unknown height (drawn 1U, see-through) read as an empty shelf. Racks now have their four rail posts instead of panels; every server is solid, one of unknown height carries an amber outline (the elevation's ?U). A room whose machines' LLDP saw no switch and that NetBox has no cables for says so in the side panel, and how to enter cables by hand. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
467 lines
31 KiB
JavaScript
467 lines
31 KiB
JavaScript
'use strict';
|
||
// A room in 3D (three.js, loaded on first use): the floor's 600 mm tiles,
|
||
// racks at their places and real height, each server a block on the rack's
|
||
// front at its units, coloured by state, the sleds of one chassis side by
|
||
// side. The same data as the floor plan (sites.js); racks are placed in the
|
||
// 2D editor. The renderer outlives the page's re-render: its canvas moves
|
||
// into the new page and the scene is rebuilt only when what it shows changed.
|
||
|
||
const R3 = { gl: null, T: null, key: '', sig: '', orb: null, pick: [], trash: [], ctx: null, ro: null, queued: false };
|
||
const U_M = 0.04445, TILE = 0.6, PLINTH = 0.1, TOPCAP = 0.08, RAIL = 0.483; // 19" between the rails
|
||
|
||
const roomView = {
|
||
get() { try { return localStorage.getItem('rollcall.roomview') === '3d' ? '3d' : '2d'; } catch (e) { return '2d'; } },
|
||
set(v) { try { localStorage.setItem('rollcall.roomview', v); } catch (e) { /* the choice is not kept */ } },
|
||
};
|
||
|
||
// frontView: servers as their drawn fronts (fronts.js) or as blocks in their state's colour
|
||
const frontView = {
|
||
get() { try { return localStorage.getItem('rollcall.fronts') === 'state' ? 'state' : 'real'; } catch (e) { return 'real'; } },
|
||
set(v) { try { localStorage.setItem('rollcall.fronts', v); } catch (e) { /* the choice is not kept */ } },
|
||
};
|
||
|
||
// cablesView: the cables from the servers' ports to their switches, on or off
|
||
const cablesView = {
|
||
get() { try { return localStorage.getItem('rollcall.cables') !== 'off'; } catch (e) { return true; } },
|
||
set(v) { try { localStorage.setItem('rollcall.cables', v ? 'on' : 'off'); } catch (e) { /* the choice is not kept */ } },
|
||
};
|
||
const SWITCH_COLORS = ['#f2a33a', '#3fbf8f', '#c470e0', '#e05d5d', '#46b8d1', '#b5c43a', '#e07fb0', '#4f8cff']; // the selection's blue last
|
||
|
||
function loadThree() {
|
||
if (!loadThree.p) loadThree.p = import('./vendor/three/three.module.min.js').catch(e => { loadThree.p = null; throw e; });
|
||
return loadThree.p;
|
||
}
|
||
|
||
// room3dStop frees the renderer when no 3D room is shown
|
||
function room3dStop() {
|
||
if (!R3.gl) return;
|
||
clearScene(); R3.gl.dispose(); R3.gl.forceContextLoss(); R3.gl.domElement.remove();
|
||
if (R3.ro) R3.ro.disconnect();
|
||
Object.assign(R3, { gl: null, key: '', sig: '', orb: null, ro: null });
|
||
}
|
||
|
||
async function room3d(site, roomArg, racks) {
|
||
const el = $('#room3d'); if (!el) return;
|
||
let T;
|
||
try { T = await loadThree(); } catch (e) { el.innerHTML = `<div class="empty">3D did not load: ${esc(e.message)}</div>`; return; }
|
||
if (!el.isConnected) return; // the page moved on while loading
|
||
if (!R3.gl) {
|
||
try { R3.gl = new T.WebGLRenderer({ antialias: true }); } catch (e) {
|
||
el.innerHTML = '<div class="empty">This browser has no WebGL: use the 2D floor plan.</div>'; return;
|
||
}
|
||
R3.T = T; R3.scene = new T.Scene(); R3.camera = new T.PerspectiveCamera(45, 1, 0.05, 1000); R3.ray = new T.Raycaster();
|
||
R3.tip = document.createElement('div'); R3.tip.className = 'r3-tip';
|
||
R3.gl.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
|
||
controls(R3.gl.domElement);
|
||
}
|
||
R3.ctx = { site: site.name, roomArg };
|
||
el.append(R3.gl.domElement, R3.tip); R3.tip.hidden = true;
|
||
if (R3.ro) R3.ro.disconnect();
|
||
R3.ro = new ResizeObserver(() => { size(); draw(); }); R3.ro.observe(el);
|
||
const room = roomArg === '-' ? '' : roomArg, key = site.name + '|' + lc(room);
|
||
const blocks = racks.map(r => rackBlocks(r));
|
||
const css = getComputedStyle(document.body);
|
||
const sig = JSON.stringify([racks.map((r, i) => [r.name, r.x, r.y, r.facing, r.height, r.auto, Object.values(blocks[i].top).map(b => [b.unit, b.h, b.known, b.ms.map(m => m.id + m.state)])]),
|
||
racks.map((r, i) => Object.values(blocks[i].top).map(b => b.ms.map(m => [m.manufacturer, m.product, m.disks]))),
|
||
SITE.sel, frontView.get(), cablesView.get(), S.cabling, css.getPropertyValue('--bg'), css.getPropertyValue('--accent')]);
|
||
if (key !== R3.key) { R3.key = key; R3.orb = null; }
|
||
if (sig !== R3.sig) {
|
||
build(site, room, racks, blocks); R3.sig = sig;
|
||
const sw = JSON.stringify(R3.switches); // the side panel lists them: draw it again once they are known
|
||
if (sw !== R3.swSig) { R3.swSig = sw; render(); return; } // the switch list and the rack's elevation show them
|
||
}
|
||
if (!R3.orb) fit();
|
||
size(); draw();
|
||
}
|
||
|
||
function clearScene() {
|
||
for (const x of R3.trash) x.dispose();
|
||
R3.trash = []; R3.pick = [];
|
||
if (R3.scene) R3.scene.clear();
|
||
}
|
||
|
||
function build(site, room, racks, blocks) {
|
||
const T = R3.T, sc = R3.scene;
|
||
clearScene();
|
||
const keep = x => { R3.trash.push(x); return x; };
|
||
const css = getComputedStyle(document.body), cv = n => new T.Color(css.getPropertyValue(n).trim() || '#888888');
|
||
sc.background = cv('--bg');
|
||
const mats = {}; // one material per colour and look
|
||
const mat = (k, make) => mats[k] || (mats[k] = keep(make()));
|
||
const stateMat = (cls, known) => mat(cls + known, () => {
|
||
const c = cv({ ok: '--ok', warn: '--warn', bad: '--danger' }[cls] || '--muted');
|
||
return new T.MeshStandardMaterial({ color: c, emissive: c, emissiveIntensity: 0.25, roughness: 0.55 });
|
||
});
|
||
const lineMat = name => mat('l' + name, () => new T.LineBasicMaterial({ color: cv(name) }));
|
||
const box = (w, h, d) => keep(new T.BoxGeometry(w, h, d));
|
||
const real = frontView.get() === 'real', fronts = {}; // one texture per look of front
|
||
const colorOf = Object.fromEntries(['ok', 'warn', 'bad', 'idle'].map(k => [k, css.getPropertyValue({ ok: '--ok', warn: '--warn', bad: '--danger', idle: '--muted' }[k]).trim()]));
|
||
|
||
sc.add(new T.HemisphereLight(0xffffff, 0x50555c, 1.7));
|
||
const sun = new T.DirectionalLight(0xffffff, 1.3); sun.position.set(-6, 12, 8); sc.add(sun);
|
||
|
||
// the floor: tiles and the room's outline
|
||
const { W, D } = roomSize(site, room, racks);
|
||
const floor = new T.Mesh(keep(new T.PlaneGeometry(W * TILE, D * TILE)), mat('floor', () => new T.MeshStandardMaterial({ color: cv('--panel'), roughness: 1 })));
|
||
floor.rotation.x = -Math.PI / 2; floor.position.set(W * TILE / 2, 0, D * TILE / 2); sc.add(floor);
|
||
const grid = [];
|
||
for (let x = 1; x < W; x++) grid.push(x * TILE, 0.001, 0, x * TILE, 0.001, D * TILE);
|
||
for (let y = 1; y < D; y++) grid.push(0, 0.001, y * TILE, W * TILE, 0.001, y * TILE);
|
||
const lines = (pts, m) => { const g = keep(new T.BufferGeometry()); g.setAttribute('position', new T.Float32BufferAttribute(pts, 3)); return new T.LineSegments(g, m); };
|
||
sc.add(lines(grid, lineMat('--line')));
|
||
const w = W * TILE, d = D * TILE;
|
||
R3.room = { w, d, racks: racks.length ? [Math.min(...racks.map(r => r.x)) * TILE, Math.min(...racks.map(r => r.y)) * TILE,
|
||
Math.max(...racks.map(r => r.x + footprint(r).w)) * TILE, Math.max(...racks.map(r => r.y + footprint(r).h)) * TILE] : null };
|
||
sc.add(lines([0, 0.002, 0, w, 0.002, 0, w, 0.002, 0, w, 0.002, d, w, 0.002, d, 0, 0.002, d, 0, 0.002, d, 0, 0.002, 0], lineMat('--muted')));
|
||
|
||
const cab = S.cabling || { machines: [], switches: [] }, portsBy = new Map(cab.machines.map(x => [x.id, x.ports]));
|
||
const rears = {}, rackAt = {}, portAt = new Map();
|
||
racks.forEach((r, i) => {
|
||
const f = footprint(r), g = new T.Group(), H = r.height || 42, h = PLINTH + H * U_M + TOPCAP, sel = SITE.sel === r.name;
|
||
g.position.set((r.x + f.w / 2) * TILE, 0, (r.y + f.h / 2) * TILE);
|
||
g.rotation.y = { N: 0, S: Math.PI, E: -Math.PI / 2, W: Math.PI / 2 }[r.facing]; // the front is local -z
|
||
const st = rackState(site, r);
|
||
// the cabinet: steel, see-through like a perforated door, so the servers inside and the cables behind show
|
||
const body = new T.Mesh(box(TILE - 0.02, h, 2 * TILE - 0.02), mat('rack' + r.auto, () => new T.MeshStandardMaterial({ color: 0x7d8794, roughness: 0.6, metalness: 0.3, transparent: true, opacity: r.auto ? 0.18 : 0.32, depthWrite: false })));
|
||
body.position.y = h / 2;
|
||
body.userData = { rack: r.name, tip: `${r.name} · ${st.ms.length} machines · ${st.used}/${H}U used${r.auto ? ' · not placed yet' : ''}` };
|
||
const edges = new T.LineSegments(keep(new T.EdgesGeometry(body.geometry)), lineMat(sel ? '--accent' : '--muted'));
|
||
edges.position.copy(body.position);
|
||
// the four rail posts, front and back: where a unit is, without a panel to look through
|
||
const post = mat('post', () => new T.MeshStandardMaterial({ color: 0x4b535e, roughness: 0.6, metalness: 0.5 }));
|
||
const posts = [-1, 1].flatMap(sx => [-1, 1].map(sz => { const p = new T.Mesh(box(0.016, H * U_M, 0.016), post); p.position.set(sx * (RAIL / 2 + 0.01), PLINTH + H * U_M / 2, sz * (TILE - 0.014)); return p; }));
|
||
g.add(body, edges, ...posts); R3.pick.push(body);
|
||
g.updateMatrixWorld(true);
|
||
rackAt[lc(r.name)] = { g, H, h, r, used: blocks[i].covered };
|
||
for (const b of Object.values(blocks[i].top)) {
|
||
const span = Math.min(H, b.unit + b.h - 1) - b.unit + 1, hh = span * U_M - 0.004, y = PLINTH + (b.unit - 1) * U_M + 0.002 + hh / 2;
|
||
const n = b.node ? b.ms.length : 1;
|
||
// each server (or sled) gets the part of the front between cuts[k] and cuts[k+1], in metres
|
||
let cuts = [...Array(n + 1).keys()].map(k => -RAIL / 2 + RAIL * k / n), front = null;
|
||
if (real) {
|
||
const p = frontProfile(b, span), cls = b.ms.map(m => stateClass(m.state)), key = p.key + '|' + p.disks + '|' + cls.join(',');
|
||
front = fronts[key] || (fronts[key] = (() => {
|
||
const f = drawFront(p, span, cls, colorOf), tex = keep(new T.CanvasTexture(f.canvas));
|
||
tex.colorSpace = T.SRGBColorSpace; tex.anisotropy = R3.gl.capabilities.getMaxAnisotropy();
|
||
return { tex, ends: f.ends };
|
||
})());
|
||
if (n > 1 && front.ends.length === n - 1) cuts = [0, ...front.ends, MM.W].map(mm => -RAIL / 2 + RAIL * mm / MM.W);
|
||
}
|
||
b.ms.slice(0, n).forEach((m, k) => {
|
||
const sw = cuts[k + 1] - cuts[k];
|
||
let look = stateMat(stateClass(m.state), b.known);
|
||
if (front) { // the drawn front on the face towards the aisle (-z), the cabinet colour elsewhere
|
||
let tex = front.tex;
|
||
if (n > 1) { tex = keep(front.tex.clone()); tex.repeat.set(sw / RAIL, 1); tex.offset.set((cuts[k] + RAIL / 2) / RAIL, 0); tex.needsUpdate = true; }
|
||
const face = keep(new T.MeshStandardMaterial({ map: tex, emissiveMap: tex, emissive: 0xffffff, emissiveIntensity: 0.3, roughness: 0.7 }));
|
||
const side = mat('side', () => new T.MeshStandardMaterial({ color: 0x1c1e22, roughness: 0.8 }));
|
||
look = [side, side, side, side, side, face];
|
||
}
|
||
const s = new T.Mesh(box(sw - (front ? 0.001 : 0.006), hh, 0.03), look);
|
||
s.position.set(-(cuts[k] + cuts[k + 1]) / 2, y, -TILE - 0.006); // seen from the aisle, local +x is on the left
|
||
s.userData = { rack: r.name, id: m.id, tip: `${nameOf(m)} · ${m.state} · U${b.unit}${span > 1 ? '–' + (b.unit + span - 1) : ''}${b.known ? '' : ' (height unknown)'} · ${[m.manufacturer, m.product].filter(Boolean).join(' ')}` };
|
||
g.add(s); R3.pick.push(s);
|
||
if (!b.known) { // height unknown (drawn as 1U): an amber outline, as "?U" in the elevation
|
||
const o = new T.LineSegments(keep(new T.EdgesGeometry(s.geometry)), mat('unknownU', () => new T.LineBasicMaterial({ color: new T.Color(colorOf.warn) })));
|
||
o.position.copy(s.position); o.scale.set(1.01, 1.08, 1.2); g.add(o);
|
||
}
|
||
});
|
||
// the chassis between front and back: solid and dark, apart from the cabinet
|
||
const chassis = new T.Mesh(box(RAIL - 0.004, hh - 0.002, 2 * TILE - 0.07), mat('chassis', () => new T.MeshStandardMaterial({ color: 0x202328, roughness: 0.7, metalness: 0.4 })));
|
||
chassis.position.set(0, y, -0.006);
|
||
g.add(chassis);
|
||
// the back: PSUs, the BMC port and the network cards with their ports
|
||
const p = frontProfile(b, span), sleds = b.ms.slice(0, n).map(m => ({ ports: portsBy.get(m.id) || [] }));
|
||
const rkey = p.style + '|' + span + '|' + JSON.stringify(sleds);
|
||
const rear = rears[rkey] || (rears[rkey] = (() => {
|
||
const f = drawRear(p, span, sleds, colorOf), tex = keep(new T.CanvasTexture(f.canvas));
|
||
tex.colorSpace = T.SRGBColorSpace; tex.anisotropy = R3.gl.capabilities.getMaxAnisotropy();
|
||
const side = mat('rside', () => new T.MeshStandardMaterial({ color: 0x1c1e22, roughness: 0.8 }));
|
||
return { look: [side, side, side, side, keep(new T.MeshStandardMaterial({ map: tex, emissiveMap: tex, emissive: 0xffffff, emissiveIntensity: 0.3, roughness: 0.7 })), side], ports: f.ports };
|
||
})());
|
||
const rm = new T.Mesh(box(RAIL - 0.001, hh, 0.02), rear.look);
|
||
rm.position.set(0, y, TILE - 0.004);
|
||
rm.userData = { rack: r.name, id: n === 1 ? b.ms[0].id : '', tip: `${b.ms.map(nameOf).join(', ')} · the back · ${sleds.reduce((a, x) => a + x.ports.length, 0)} network ports` };
|
||
g.add(rm); R3.pick.push(rm);
|
||
for (const pt of rear.ports) {
|
||
const m = b.ms[pt.sled]; if (!m) continue;
|
||
portAt.set(m.id + '|' + pt.name, { rack: lc(r.name), lx: -RAIL / 2 + RAIL * pt.x / MM.W, ly: y + hh / 2 - hh * pt.y / (span * MM.U - 1) });
|
||
}
|
||
}
|
||
if (sel) { // the selected rack's footprint, in the accent colour
|
||
const p = new T.Mesh(keep(new T.PlaneGeometry(TILE + 0.1, 2 * TILE + 0.1)), mat('selp', () => new T.MeshBasicMaterial({ color: cv('--accent'), transparent: true, opacity: 0.35 })));
|
||
p.rotation.x = -Math.PI / 2; p.position.y = 0.003; g.add(p);
|
||
}
|
||
const label = labelSprite(r.name, css.getPropertyValue(sel ? '--accent' : '--fg').trim(), css.getPropertyValue('--panel').trim());
|
||
label.position.y = h + 0.22; g.add(label);
|
||
sc.add(g);
|
||
});
|
||
R3.switches = placeSwitches(site, room, cab, rackAt, portAt);
|
||
for (const sw of R3.switches) if (sw.at) drawSwitchIn(sw, rackAt[sw.at.rack], keep, mat, colorOf);
|
||
if (cablesView.get()) cables(cab, rackAt, portAt, keep, mat);
|
||
}
|
||
|
||
// placeSwitches: where each switch the room's machines lead to stands. Its
|
||
// stored place (NetBox, or set by hand) when that is a rack of this room;
|
||
// else, when it has none, the rack with most of its links, at the highest
|
||
// free unit (on top of the rack when none is free): an estimate. A switch
|
||
// placed in another room is reached by cables leaving through the ceiling.
|
||
function placeSwitches(site, room, cab, rackAt, portAt) {
|
||
const links = {}; // switch -> rack -> links
|
||
for (const mp of cab.machines) for (const pt of mp.ports) {
|
||
const at = pt.switch && portAt.get(mp.id + '|' + pt.name); if (!at) continue;
|
||
(links[pt.switch] = links[pt.switch] || {})[at.rack] = (links[pt.switch][at.rack] || 0) + 1;
|
||
}
|
||
const taken = {}; // rack -> units switches took, the placed ones first so estimates go around them
|
||
for (const s of cab.switches) if (links[s.name] && s.rack && s.unit && rackAt[lc(s.rack)] && sameRoom(s.room || '', room)) (taken[lc(s.rack)] = taken[lc(s.rack)] || []).push(s.unit);
|
||
return cab.switches.filter(s => links[s.name]).map((s, i) => {
|
||
const out = { ...s, color: SWITCH_COLORS[i % SWITCH_COLORS.length], here: Object.values(links[s.name]).reduce((a, b) => a + b, 0) };
|
||
const inRoom = s.rack && (!s.building || inSite(site, s.building)) && sameRoom(s.room || '', room) && rackAt[lc(s.rack)];
|
||
if (s.rack && !inRoom) { out.away = [s.building, s.room, s.rack].filter(Boolean).join(' / '); return out; }
|
||
const rack = inRoom ? lc(s.rack) : Object.entries(links[s.name]).sort((a, b) => b[1] - a[1])[0][0];
|
||
const ra = rackAt[rack]; let unit = inRoom ? s.unit : 0;
|
||
if (!unit) { for (let u = ra.H; u >= 1; u--) if (!ra.used.has(u) && !(taken[rack] || []).includes(u)) { unit = u; break; } }
|
||
if (!inRoom || !s.unit) (taken[rack] = taken[rack] || []).push(unit);
|
||
out.at = { rack, unit: unit || ra.H + 1 + (taken[rack].filter(u => !u).length - 1), estimated: !inRoom || !s.unit };
|
||
return out;
|
||
});
|
||
}
|
||
|
||
// switchPort: where a switch's port named like "ethernet1/1/12" or "Gi1/0/24" is on its drawing
|
||
function switchPortNo(name) { const m = /(\d+)\D*$/.exec(name || ''); return m ? Number(m[1]) : 0; }
|
||
|
||
function drawSwitchIn(sw, ra, keep, mat, colorOf) {
|
||
const T = R3.T, css = getComputedStyle(document.body);
|
||
const max = Math.max(48, ...((S.cabling || {}).machines || []).flatMap(mp => mp.ports.filter(p => p.switch === sw.name).map(p => switchPortNo(p.switch_port))));
|
||
const count = Math.min(128, Math.ceil(max / 2) * 2), d = drawSwitch(count, colorOf), tex = keep(new T.CanvasTexture(d.canvas));
|
||
tex.colorSpace = T.SRGBColorSpace; tex.anisotropy = R3.gl.capabilities.getMaxAnisotropy();
|
||
const side = mat('swside', () => new T.MeshStandardMaterial({ color: 0x15171a, roughness: 0.7 }));
|
||
const top = sw.at.unit > ra.H, y = top ? ra.h + U_M / 2 + 0.005 : PLINTH + (sw.at.unit - 1) * U_M + U_M / 2;
|
||
const look = [side, side, side, side, keep(new T.MeshStandardMaterial({ map: tex, emissiveMap: tex, emissive: 0xffffff, emissiveIntensity: 0.35, roughness: 0.6 })), side];
|
||
const m = new T.Mesh(keep(new T.BoxGeometry(RAIL - 0.001, U_M - 0.004, 0.45)), look);
|
||
m.position.set(0, y, TILE + 0.006 - 0.225);
|
||
if (SITE.sel && lc(SITE.sel) === lc(ra.r.name)) { // names on the selected rack only: switches sit a unit apart, labels would pile up
|
||
const tag = labelSprite(sw.name.split('.')[0], sw.color, css.getPropertyValue('--panel').trim());
|
||
tag.scale.set(0.5, 0.125, 1); tag.position.set((sw.at.unit % 2 ? 1 : -1) * 0.42, y, TILE + 0.1); ra.g.add(tag);
|
||
}
|
||
const edge = new T.LineSegments(keep(new T.EdgesGeometry(m.geometry)), mat('swl' + sw.color, () => new T.LineBasicMaterial({ color: new T.Color(sw.color) })));
|
||
edge.position.copy(m.position);
|
||
m.userData = { rack: ra.r.name, tip: `${sw.name}${sw.role === 'oob' ? ' (out-of-band)' : ''}${sw.model ? ' · ' + sw.model : ''} · ${sw.here} cables here · ${sw.at.estimated ? 'place estimated: ' + (sw.source ? 'no unit' : 'not in NetBox') + ', set it in the panel' : 'U' + sw.at.unit + ' (' + sw.source + ')'}` };
|
||
// its front at its unit on the front rails, named, so the switch reads from the cold aisle too
|
||
const ftex = keep(new T.CanvasTexture(drawSwitchFront(sw.name, sw.color, colorOf))); ftex.colorSpace = T.SRGBColorSpace; ftex.anisotropy = R3.gl.capabilities.getMaxAnisotropy();
|
||
const fm = keep(new T.MeshStandardMaterial({ map: ftex, emissiveMap: ftex, emissive: 0xffffff, emissiveIntensity: 0.35, roughness: 0.6 }));
|
||
const front = new T.Mesh(keep(new T.BoxGeometry(RAIL - 0.001, U_M - 0.004, 0.03)), [side, side, side, side, side, fm]);
|
||
front.position.set(0, y, -TILE - 0.006); front.userData = m.userData;
|
||
ra.g.add(m, edge, front); R3.pick.push(m, front);
|
||
sw.y = y;
|
||
sw.port = name => { const n = switchPortNo(name), p = d.at[n] || d.at['u' + (n % 6)]; return { lx: -RAIL / 2 + RAIL * p.x / MM.W, ly: y + (U_M - 0.004) / 2 - (U_M - 0.004) * p.y / (MM.U - 1) }; };
|
||
}
|
||
|
||
// cables, drawn like busbars so they read from across the room: per rack
|
||
// and switch, one bus up the back of the rack (thicker with more cables),
|
||
// a short stub from each port into it, a comb under the switch with a tail
|
||
// into each switch port; to a switch in another rack the bus crosses over
|
||
// the tops as a tray, to one in another room it rises to the ceiling. One
|
||
// colour per switch; a port without link has a grey stub; with a rack
|
||
// selected, the other racks' buses fade. All of it is a handful of
|
||
// instanced meshes (thousands of stubs would otherwise be thousands of draws).
|
||
function cables(cab, rackAt, portAt, keep, mat) {
|
||
const T = R3.T, byName = Object.fromEntries(R3.switches.map(s => [s.name, s]));
|
||
const W = (ra, x, y, z) => ra.g.localToWorld(new T.Vector3(x, y, z));
|
||
const look = (col, dim) => mat('bus' + col + dim, () => new T.MeshStandardMaterial({ color: new T.Color(col), emissive: new T.Color(col), emissiveIntensity: 0.4, roughness: 0.45, metalness: 0.2, transparent: dim, opacity: dim ? 0.12 : 1 }));
|
||
const bins = new Map(), dummy = new T.Object3D();
|
||
const bar = (a, b, t, m, data) => { // a square bar from a to b (world), t thick, overrunning the joints
|
||
const len = a.distanceTo(b); if (len < 1e-4) return;
|
||
dummy.position.copy(a).add(b).multiplyScalar(0.5); dummy.lookAt(b); dummy.scale.set(t, t, len + t); dummy.updateMatrix();
|
||
if (!bins.has(m)) bins.set(m, { m, mats: [], data: [] });
|
||
bins.get(m).mats.push(dummy.matrix.clone()); bins.get(m).data.push(data);
|
||
};
|
||
// the cables of each rack to each switch
|
||
const groups = new Map();
|
||
for (const mp of cab.machines) for (const pt of mp.ports) {
|
||
const a = pt.switch && portAt.get(mp.id + '|' + pt.name), sw = byName[pt.switch]; if (!a || !sw) continue;
|
||
const k = a.rack + '|' + sw.name;
|
||
if (!groups.has(k)) groups.set(k, { ra: rackAt[a.rack], sw, ports: [] });
|
||
groups.get(k).ports.push({ mp, pt, a });
|
||
}
|
||
// lanes behind each rack: its switches alternate left and right, further back each pair
|
||
const lanes = {};
|
||
const laneOf = (ra, sw) => {
|
||
const k = lc(ra.r.name), names = lanes[k] || (lanes[k] = [...new Set([...groups.values()].filter(g => g.ra === ra).map(g => g.sw.name)
|
||
.concat(R3.switches.filter(s => s.at && s.at.rack === k).map(s => s.name)))].sort());
|
||
const i = Math.max(0, names.indexOf(sw.name));
|
||
return { x: (i % 2 ? 1 : -1) * 0.255, z: TILE + 0.06 + 0.04 * Math.floor(i / 2) };
|
||
};
|
||
const combs = new Map(); // switch -> the ports reaching it, for its comb
|
||
for (const g of groups.values()) {
|
||
const { ra, sw, ports } = g, L = laneOf(ra, sw), n = ports.length;
|
||
const t = Math.min(0.045, 0.018 + 0.0035 * Math.sqrt(n));
|
||
const dim = SITE.sel && lc(SITE.sel) !== lc(ra.r.name) && !(sw.at && lc(SITE.sel) === sw.at.rack);
|
||
const busM = look(sw.color, dim), busData = dim ? null : { rack: ra.r.name, tip: `${n} cable${n > 1 ? 's' : ''} from ${ra.r.name} to ${sw.name}${sw.role === 'oob' ? ' (OOB)' : ''}${sw.away ? ' in ' + sw.away : ''}` };
|
||
// stubs: out of the back of each port, sideways into the bus
|
||
for (const p of ports) {
|
||
const m0 = S.machines.find(x => x.id === p.mp.id), pt = p.pt;
|
||
const data = dim ? null : { rack: ra.r.name, id: p.mp.id, tip: `${m0 ? nameOf(m0) : p.mp.id} ${pt.kind === 'bmc' ? 'BMC' : pt.name}${pt.speed ? ' ' + pt.speed : ''} → ${pt.switch}${sw.role === 'oob' ? ' (OOB)' : ''} ${pt.switch_port}${pt.vlan ? ' · VLAN ' + pt.vlan : ''}${pt.link === false ? ' · no link' : ''}${sw.away ? ' (in ' + sw.away + ')' : ''} · ${pt.source === 'lldp' ? 'seen by LLDP' : pt.source === 'netbox' ? 'NetBox cable' : 'entered by hand'}${pt.netbox_says ? ' · NetBox says ' + pt.netbox_says : ''}` };
|
||
const sm = look(pt.link === false ? '#8a8f96' : sw.color, dim);
|
||
bar(W(ra, p.a.lx, p.a.ly, TILE + 0.008), W(ra, p.a.lx, p.a.ly, L.z), 0.007, sm, data);
|
||
bar(W(ra, p.a.lx, p.a.ly, L.z), W(ra, L.x, p.a.ly, L.z), 0.007, sm, data);
|
||
if (sw.at) { const c = combs.get(sw) || []; c.push({ pt, dim, data }); combs.set(sw, c); }
|
||
}
|
||
const y0 = Math.min(...ports.map(p => p.a.ly));
|
||
const rb = sw.at && rackAt[sw.at.rack];
|
||
if (rb === ra) { // up the back to the comb under the switch
|
||
bar(W(ra, L.x, y0, L.z), W(ra, L.x, sw.y - U_M / 2 - 0.02, L.z), t, busM, busData);
|
||
continue;
|
||
}
|
||
const yT = Math.max(ra.h, rb ? rb.h : 0) + 0.14 + 0.03 * (R3.switches.indexOf(sw) % 5); // the tray over the tops
|
||
bar(W(ra, L.x, y0, L.z), W(ra, L.x, yT, L.z), t, busM, busData);
|
||
if (!rb) { bar(W(ra, L.x, yT, L.z), W(ra, L.x, 2.9, L.z), t, busM, busData); continue; } // another room: through the ceiling
|
||
const LB = laneOf(rb, sw);
|
||
bar(W(ra, L.x, yT, L.z), W(rb, LB.x, yT, LB.z), t, busM, busData);
|
||
bar(W(rb, LB.x, yT, LB.z), W(rb, LB.x, sw.y - U_M / 2 - 0.02, LB.z), t, busM, busData);
|
||
}
|
||
// combs: under each switch from its lane to its farthest port, a tail up into each port
|
||
for (const [sw, list] of combs) {
|
||
const rb = rackAt[sw.at.rack], L = laneOf(rb, sw), yc = sw.y - U_M / 2 - 0.02;
|
||
const xs = list.map(c => sw.port(c.pt.switch_port).lx), far = L.x < 0 ? Math.max(...xs) : Math.min(...xs);
|
||
const dim = list.every(c => c.dim), t = Math.min(0.035, 0.014 + 0.003 * Math.sqrt(list.length));
|
||
bar(W(rb, L.x, yc, L.z), W(rb, far, yc, L.z), t, look(sw.color, dim), dim ? null : { rack: rb.r.name, tip: `${sw.name}: ${list.length} cables here` });
|
||
for (const c of list) {
|
||
const p = sw.port(c.pt.switch_port), m = look(c.pt.link === false ? '#8a8f96' : sw.color, c.dim);
|
||
bar(W(rb, p.lx, yc, L.z), W(rb, p.lx, p.ly, L.z), 0.006, m, c.data);
|
||
bar(W(rb, p.lx, p.ly, L.z), W(rb, p.lx, p.ly, TILE + 0.012), 0.006, m, c.data);
|
||
}
|
||
}
|
||
const geo = keep(new T.BoxGeometry(1, 1, 1));
|
||
for (const b of bins.values()) {
|
||
const im = new T.InstancedMesh(geo, b.m, b.mats.length);
|
||
b.mats.forEach((mx, i) => im.setMatrixAt(i, mx));
|
||
im.userData = { items: b.data }; R3.scene.add(im);
|
||
if (b.data.some(Boolean)) R3.pick.push(im);
|
||
}
|
||
}
|
||
|
||
// labelSprite: a rack's name on a pill, drawn over everything so a rack in
|
||
// front never hides it
|
||
function labelSprite(text, color, bg) {
|
||
const T = R3.T, c = document.createElement('canvas'); c.width = 256; c.height = 64;
|
||
const x = c.getContext('2d'), t = text.length > 12 ? '…' + text.slice(-11) : text;
|
||
x.font = '600 34px ui-monospace, Menlo, Consolas, monospace';
|
||
const w = Math.min(248, x.measureText(t).width + 28);
|
||
x.globalAlpha = 0.85; x.fillStyle = bg; x.beginPath(); x.roundRect(128 - w / 2, 8, w, 48, 12); x.fill();
|
||
x.globalAlpha = 1; x.fillStyle = color; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillText(t, 128, 33);
|
||
const tex = new T.CanvasTexture(c); tex.colorSpace = T.SRGBColorSpace; R3.trash.push(tex);
|
||
const m = new T.SpriteMaterial({ map: tex, transparent: true, depthTest: false, depthWrite: false }); R3.trash.push(m);
|
||
const s = new T.Sprite(m); s.scale.set(0.9, 0.225, 1); s.renderOrder = 10;
|
||
return s;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- camera
|
||
// orbit around a target on the floor: theta 0 looks from the south (+z)
|
||
// fit: the racks in view (the room when it has none)
|
||
function fit() {
|
||
const { w, d, racks } = R3.room || { w: 5, d: 4 };
|
||
const b = racks || [0, 0, w, d], sw = b[2] - b[0], sd = b[3] - b[1];
|
||
R3.orb = { theta: 0.35, phi: 0.95, r: Math.max(sw, sd, 2) * 1.25 + 2.5, t: new R3.T.Vector3((b[0] + b[2]) / 2, 0.8, (b[1] + b[3]) / 2) };
|
||
R3.maxR = Math.max(w, d) * 4 + 10;
|
||
}
|
||
|
||
function size() {
|
||
const el = R3.gl && R3.gl.domElement.parentElement; if (!el) return;
|
||
const w = el.clientWidth, h = el.clientHeight; if (!w || !h) return;
|
||
R3.gl.setSize(w, h); R3.camera.aspect = w / h; R3.camera.updateProjectionMatrix();
|
||
}
|
||
|
||
function draw() {
|
||
if (R3.queued || !R3.gl) return;
|
||
R3.queued = true;
|
||
requestAnimationFrame(() => {
|
||
R3.queued = false; if (!R3.gl || !R3.orb) return;
|
||
const o = R3.orb, c = R3.camera;
|
||
c.position.set(o.t.x + o.r * Math.sin(o.phi) * Math.sin(o.theta), o.t.y + o.r * Math.cos(o.phi), o.t.z + o.r * Math.sin(o.phi) * Math.cos(o.theta));
|
||
c.lookAt(o.t);
|
||
R3.gl.render(R3.scene, c);
|
||
});
|
||
}
|
||
|
||
function hitAt(ev) {
|
||
const rc = R3.gl.domElement.getBoundingClientRect();
|
||
R3.ray.setFromCamera(new R3.T.Vector2((ev.clientX - rc.left) / rc.width * 2 - 1, -(ev.clientY - rc.top) / rc.height * 2 + 1), R3.camera);
|
||
const h = R3.ray.intersectObjects(R3.pick, false).find(x => !x.object.isInstancedMesh || x.object.userData.items[x.instanceId]);
|
||
if (!h) return null;
|
||
const d = h.object.isInstancedMesh ? h.object.userData.items[h.instanceId] : h.object.userData; // a bus or stub: what it carries
|
||
return { ...d, point: h.point, obj: h.object };
|
||
}
|
||
|
||
// controls: drag turns, right-drag or shift-drag moves, wheel or pinch zooms;
|
||
// a click selects a rack (and on the selected rack's servers opens the
|
||
// machine), a double click brings the rack close
|
||
function controls(cv) {
|
||
const pts = new Map(); let drag = null, hoverQ = false;
|
||
const clampPhi = p => Math.min(1.5, Math.max(0.08, p));
|
||
const spread = () => { const [a, b] = [...pts.values()]; return Math.hypot(a.x - b.x, a.y - b.y); };
|
||
cv.style.touchAction = 'none';
|
||
cv.addEventListener('contextmenu', ev => ev.preventDefault());
|
||
cv.addEventListener('pointerdown', ev => {
|
||
try { cv.setPointerCapture(ev.pointerId); } catch (e) { /* not a live pointer */ }
|
||
pts.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
|
||
if (pts.size === 1) drag = { moved: 0, pan: ev.button === 2 || ev.shiftKey || ev.ctrlKey || ev.metaKey, pinch: 0 };
|
||
else if (drag) { drag.pinch = spread(); drag.moved = 99; }
|
||
R3.tip.hidden = true;
|
||
});
|
||
cv.addEventListener('pointermove', ev => {
|
||
const p = pts.get(ev.pointerId);
|
||
if (!p) { // hover: what is under the pointer
|
||
if (hoverQ) return; hoverQ = true;
|
||
requestAnimationFrame(() => {
|
||
hoverQ = false; if (!R3.gl || !R3.orb) return;
|
||
const h = hitAt(ev), rc = cv.getBoundingClientRect();
|
||
cv.style.cursor = h ? 'pointer' : 'grab';
|
||
R3.tip.hidden = !h;
|
||
if (h) { R3.tip.textContent = h.tip; R3.tip.style.left = (ev.clientX - rc.left + 14) + 'px'; R3.tip.style.top = (ev.clientY - rc.top + 14) + 'px'; }
|
||
});
|
||
return;
|
||
}
|
||
const dx = ev.clientX - p.x, dy = ev.clientY - p.y, o = R3.orb; if (!o) return;
|
||
p.x = ev.clientX; p.y = ev.clientY; drag.moved += Math.abs(dx) + Math.abs(dy);
|
||
if (pts.size >= 2) { const s = spread(); if (drag.pinch) o.r = Math.min(R3.maxR, Math.max(0.8, o.r * drag.pinch / s)); drag.pinch = s; }
|
||
else if (drag.pan) {
|
||
const k = o.r * 0.0016, st = Math.sin(o.theta), ct = Math.cos(o.theta);
|
||
o.t.x += -ct * dx * k - st * dy * k; o.t.z += st * dx * k - ct * dy * k;
|
||
} else { o.theta -= dx * 0.008; o.phi = clampPhi(o.phi - dy * 0.008); }
|
||
draw();
|
||
});
|
||
const up = ev => {
|
||
if (!pts.delete(ev.pointerId)) return;
|
||
if (pts.size || !drag) return;
|
||
const click = drag.moved < 6 && ev.type === 'pointerup' && ev.button === 0; drag = null;
|
||
if (!click) return;
|
||
const at = { clientX: ev.clientX, clientY: ev.clientY }; // a double click is not two clicks
|
||
clearTimeout(R3.clickT); R3.clickT = setTimeout(() => { if (R3.gl) clicked(at); }, 240);
|
||
};
|
||
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
|
||
cv.addEventListener('pointerleave', () => { if (!pts.size) R3.tip.hidden = true; });
|
||
cv.addEventListener('wheel', ev => {
|
||
ev.preventDefault(); const o = R3.orb; if (!o) return;
|
||
o.r = Math.min(R3.maxR, Math.max(0.8, o.r * Math.exp(ev.deltaY * 0.0015))); draw();
|
||
}, { passive: false });
|
||
cv.addEventListener('dblclick', ev => {
|
||
clearTimeout(R3.clickT);
|
||
const h = hitAt(ev), o = R3.orb; if (!h || !o) return;
|
||
const p = new R3.T.Vector3(); (h.obj.parent === R3.scene ? h.obj : h.obj.parent).getWorldPosition(p);
|
||
if (h.obj.isInstancedMesh) p.copy(h.point); // a cable: close in where it was clicked
|
||
o.t.set(p.x, 1, p.z); o.r = 3.2; draw();
|
||
});
|
||
}
|
||
|
||
function clicked(ev) {
|
||
const h = hitAt(ev), c = R3.ctx; if (!c) return;
|
||
const base = '#/sites/' + encodeURIComponent(c.site) + '/' + encodeURIComponent(c.roomArg);
|
||
if (!h) { if (SITE.sel) location.hash = base; return; }
|
||
if (h.id && SITE.sel === h.rack) { location.hash = '#/machine/' + h.id; return; }
|
||
location.hash = SITE.sel === h.rack ? base : base + '/' + encodeURIComponent(h.rack);
|
||
}
|
||
|
||
function room3dReset() { R3.orb = null; fit(); draw(); }
|
||
function room3dTurn() { if (R3.orb) { R3.orb.theta += Math.PI; draw(); } }
|