<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Consistent Hash Ring Monitor // FUI</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts: Orbitron & JetBrains Mono -->
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Orbitron:wght@400;500;700;900&display=swap" rel="stylesheet">
<!-- Tailwind Configuration -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'neon-cyan': '#00f3ff',
'neon-magenta': '#ff00ff',
'neon-amber': '#ff9500',
'deep-black': '#050505',
},
fontFamily: {
'mono': ['"JetBrains Mono"', 'monospace'],
'futura': ['"Orbitron"', 'sans-serif'],
},
boxShadow: {
'glow-cyan': '0 0 10px #00f3ff, 0 0 20px #00f3ff',
'glow-magenta': '0 0 10px #ff00ff, 0 0 20px #ff00ff',
'glow-amber': '0 0 10px #ff9500, 0 0 20px #ff9500',
}
}
}
}
</script>
<style>
/* Base & CRTs */
body {
background-color: #050505;
color: #00f3ff;
overflow: hidden;
margin: 0;
user-select: none;
}
/* Scanline Overlay */
.scanlines {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: linear-gradient(
to bottom,
rgba(255,255,255,0),
rgba(255,255,255,0) 50%,
rgba(0,0,0,0.1) 50%,
rgba(0,0,0,0.1)
);
background-size: 100% 4px;
pointer-events: none;
z-index: 50;
}
/* Vignette */
.vignette {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: radial-gradient(circle, rgba(0,0,0,0) 60%, rgba(0,10,20,0.8) 100%);
pointer-events: none;
z-index: 40;
}
/* HUD Borders */
.hud-corner {
position: absolute;
width: 40px;
height: 40px;
border: 2px solid #00f3ff;
transition: all 0.3s ease;
}
.hud-corner-tl { top: 20px; left: 20px; border-right: none; border-bottom: none; }
.hud-corner-tr { top: 20px; right: 20px; border-left: none; border-bottom: none; }
.hud-corner-bl { bottom: 20px; left: 20px; border-right: none; border-top: none; }
.hud-corner-br { bottom: 20px; right: 20px; border-left: none; border-top: none; }
/* Decoding Effect Class */
.decode-text {
font-family: 'JetBrains Mono', monospace;
display: inline-block;
min-width: 60px;
text-align: right;
}
/* Glitch Animation */
@keyframes glitch {
0% { transform: translate(0); }
20% { transform: translate(-2px, 2px); }
40% { transform: translate(-2px, -2px); }
60% { transform: translate(2px, 2px); }
80% { transform: translate(2px, -2px); }
100% { transform: translate(0); }
}
.glitch-active {
animation: glitch 0.3s cubic-bezier(.25, .46, .45, .94) both infinite;
color: #ff00ff;
}
/* Canvas positioning */
#ring-canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 10;
}
</style>
</head>
<body class="font-mono">
<!-- Visual Overlays -->
<div class="scanlines"></div>
<div class="vignette"></div>
<!-- HUD Corners -->
<div class="hud-corner hud-corner-tl"></div>
<div class="hud-corner hud-corner-tr"></div>
<div class="hud-corner hud-corner-bl"></div>
<div class="hud-corner hud-corner-br"></div>
<!-- Top Bar -->
<div class="absolute top-0 left-0 w-full p-5 flex justify-between items-start z-20 pointer-events-none">
<div>
<h1 class="text-2xl font-futura font-bold text-neon-cyan tracking-widest" style="text-shadow: 0 0 10px #00f3ff;">CONSISTENT HASH</h1>
<h2 class="text-sm text-neon-magenta tracking-[0.5em]">MONITOR SYSTEM</h2>
</div>
<div class="text-right">
<div class="text-xs text-gray-400">SYSTEM TIME</div>
<div id="clock" class="text-xl font-bold">00:00:00:000</div>
<div class="mt-1 text-xs px-2 py-0.5 border border-neon-cyan inline-block bg-black/50">
STATUS: <span id="status-indicator" class="text-neon-cyan font-bold">OPTIMAL</span>
</div>
</div>
</div>
<!-- Left Panel: Metrics -->
<div class="absolute left-8 top-1/2 transform -translate-y-1/2 w-72 border-l-2 border-neon-cyan/30 pl-6 z-20 flex flex-col gap-6">
<div>
<div class="text-neon-magenta text-xs tracking-widest mb-1">TOTAL NODES</div>
<div id="total-nodes" class="text-3xl font-bold font-futura">10</div>
</div>
<div>
<div class="text-neon-magenta text-xs tracking-widest mb-1">VIRTUAL NODES</div>
<div id="total-vnodes" class="text-2xl font-bold font-futura decode-text">100</div>
</div>
<div>
<div class="text-neon-magenta text-xs tracking-widest mb-1">KEYS DISTRIBUTED</div>
<div id="total-keys" class="text-2xl font-bold font-futura decode-text">0</div>
</div>
<div class="border-t border-neon-cyan/30 pt-4">
<div class="text-xs text-gray-400 mb-2">IMBALANCE METRIC</div>
<div class="flex items-center gap-3">
<div class="w-32 h-2 bg-gray-900 border border-neon-cyan/50 relative">
<div id="imbalance-bar" class="h-full bg-neon-amber transition-all duration-300" style="width: 0%"></div>
</div>
<span id="imbalance-val" class="text-sm font-bold text-neon-amber w-12 text-right">0.0</span>
</div>
<div class="text-[10px] text-gray-500 mt-1">STD DEVIATION %</div>
</div>
<div class="border-t border-neon-cyan/30 pt-4">
<div class="text-xs text-gray-400 mb-2">HOTSPOT DETECTION</div>
<div id="hotspot-count" class="text-xl text-neon-magenta font-bold decode-text">0</div>
<div class="text-[10px] text-gray-500">SEGMENTS > THRESHOLD</div>
</div>
</div>
<!-- Right Panel: Node List -->
<div class="absolute right-8 top-1/2 transform -translate-y-1/2 w-80 border-r-2 border-neon-magenta/30 pr-6 z-20">
<div class="text-sm text-neon-magenta mb-4 tracking-widest">NODE TELEMETRY</div>
<div class="w-full overflow-x-auto">
<table class="w-full text-left text-xs border-collapse">
<thead>
<tr class="border-b border-neon-magenta/30">
<th class="py-1 text-gray-500 font-normal">ID</th>
<th class="py-1 text-gray-500 font-normal text-right">LOAD</th>
<th class="py-1 text-gray-500 font-normal text-right">CAP</th>
</tr>
</thead>
<tbody id="node-table-body" class="font-mono text-sm">
<!-- Rows injected via JS -->
</tbody>
</table>
</div>
<div class="mt-6 flex gap-2">
<button id="add-key-btn" class="flex-1 border border-neon-cyan text-neon-cyan px-2 py-1 text-xs hover:bg-neon-cyan/10 transition-colors">
INJECT LOAD (+100)
</button>
<button id="rebalance-btn" class="flex-1 border border-neon-magenta text-neon-magenta px-2 py-1 text-xs hover:bg-neon-magenta/10 transition-colors">
REBALANCE RING
</button>
</div>
</div>
<!-- Bottom Bar: Logs -->
<div class="absolute bottom-4 left-8 right-8 h-32 z-20 flex flex-col">
<div class="text-xs text-gray-400 mb-1 font-mono">AUDIT TRAIL</div>
<div id="event-log" class="flex-1 overflow-y-auto font-mono text-xs p-2 bg-black/40 border border-gray-800 scrollbar-hide">
<!-- Logs -->
</div>
</div>
<!-- Main Canvas -->
<canvas id="ring-canvas" width="800" height="800"></canvas>
<!-- Particle Background Canvas -->
<canvas id="particle-canvas" class="fixed top-0 left-0 w-full h-full pointer-events-none" style="z-index: 1;"></canvas>
<script>
/**
* ------------------------------------------------------------------
* UTILS: TEXT SCRAMBLE DECODER
* Simulates data decoding from random characters.
* ------------------------------------------------------------------
*/
class TextScramble {
constructor(el) {
this.el = el;
this.chars = '!<>-_\\/{}[]=+*^?#________';
this.update = this.update.bind(this);
}
setText(newText) {
const oldText = this.el.innerText;
const length = Math.max(oldText.length, newText.length);
const promise = new Promise((resolve) => this.resolve = resolve);
this.queue = [];
for (let i = 0; i < length; i++) {
const from = oldText[i] || '';
const to = newText[i] || '';
const start = Math.floor(Math.random() * 40);
const end = start + Math.floor(Math.random() * 40);
this.queue.push({ from, to, start, end });
}
cancelAnimationFrame(this.frameRequest);
this.frame = 0;
this.update();
return promise;
}
update() {
let output = '';
let complete = 0;
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i];
if (this.frame >= end) {
complete++;
output += to;
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar();
this.queue[i].char = char;
}
output += `<span class="text-gray-500">${char}</span>`;
} else {
output += from;
}
}
this.el.innerHTML = output;
if (complete === this.queue.length) {
this.resolve();
} else {
this.frameRequest = requestAnimationFrame(this.update);
this.frame++;
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)];
}
}
const scramblers = {};
function initScramble(id, initial) {
const el = document.getElementById(id);
scramblers[id] = new TextScramble(el);
scramblers[id].setText(initial);
}
function updateScramble(id, value) {
if (!scramblers[id]) initScramble(id, value);
scramblers[id].setText(value);
}
/**
* ------------------------------------------------------------------
* CORE LOGIC: CONSISTENT HASH RING
* ------------------------------------------------------------------
*/
class HashRing {
constructor(numNodes, vnodesPerNode) {
this.numNodes = numNodes;
this.vnodesPerNode = vnodesPerNode;
this.nodes = []; // Physical nodes
this.vnodes = []; // Virtual nodes (points on ring)
this.totalKeys = 0;
this.transition = 0; // 0 to 1 for animations
}
init() {
this.nodes = [];
this.vnodes = [];
// Create physical nodes equidistant initially
for (let i = 0; i < this.numNodes; i++) {
this.nodes.push({
id: i,
name: `SRV-${(i+1).toString().padStart(3, '0')}`,
angle: (i / this.numNodes) * Math.PI * 2,
load: 0,
targetLoad: 0,
color: '#00f3ff',
hotspots: []
});
}
this.assignVirtualNodes();
this.distributeKeys(this.totalKeys); // Initial distribution
}
// Create vnodes distributed among physical nodes
assignVirtualNodes() {
this.vnodes = [];
for (let n = 0; n < this.numNodes; n++) {
const node = this.nodes[n];
for (let v = 0; v < this.vnodesPerNode; v++) {
// Evenly space vnodes around the ring for the node, plus small random jitter
let baseAngle = node.angle;
// We want vnodes to cover the area "between" the previous node and next node
// For simplicity, we treat physical node as the owner of vnodes in its segment
// Actually consistent hashing: vnodes have random positions, assigned to a physical node.
// We'll simulate this by generating random angles for each vnode, but keeping them strictly closer to the node's angle is complex.
// Simplified approach for visualization: The ring is divided into segments by physical nodes.
// VNodes belonging to a node reside in that segment.
// Determine segment boundaries
const prevAngle = (n === 0) ? this.nodes[this.numNodes-1].angle - Math.PI*2 : this.nodes[n-1].angle;
const nextAngle = this.nodes[(n+1) % this.numNodes].angle;
// Distribute K vnodes linearly across the segment
// Add small offset to avoid perfect overlap
const step = (nextAngle - prevAngle) / ((this.numNodes * this.vnodesPerNode) + 1); // just rough
// Better: segment length / vnodesPerNode
const segmentLength = nextAngle - prevAngle;
const spacing = segmentLength / this.vnodesPerNode;
for(let k=0; k<this.vnodesPerNode; k++) {
const angle = nextAngle - spacing * (k + 1) + (segmentLength/this.numNodes) * n; // rough placement
// Actually easier: just place vnodes exactly evenly distributed globally and assign to nearest physical node.
// But we need to visualize ownership clearly.
}
}
}
// Let's rebuild: simplest robust model for UI.
// 1. Generate a huge list of random angles representing vnodes. Assign them to nodes based on proximity.
// 2. Keep them separate for drawing.
}
generateVnodes() {
this.vnodes = [];
const totalV = this.numNodes * this.vnodesPerNode;
for(let i=0; i<totalV; i++) {
const angle = Math.random() * Math.PI * 2;
// Determine closest physical node clockwise or nearest?
// We'll just assign during key lookup.
this.vnodes.push({ angle, keys: 0, ownerId: -1 });
}
// Reassign owners
this.assignVnodeOwners();
}
assignVnodeOwners() {
// Sort nodes by angle
const sortedNodes = [...this.nodes].sort((a,b) => a.angle - b.angle);
// Sort vnodes
this.vnodes.sort((a,b) => a.angle - b.angle);
// For each vnode, find the node whose angle is <= vnode angle and is greatest.
// Wrap around at 0/2PI
let nodeIdx = 0;
for (let v of this.vnodes) {
// Advance nodeIdx until node.angle <= v.angle and next node.angle > v.angle
while (nodeIdx < sortedNodes.length && sortedNodes[(nodeIdx+1) % sortedNodes.length].angle <= v.angle) {
nodeIdx++;
// Handle wrap around logic implicitly by logic, simpler to compare angles directly though.
}
// Check successor
let nextIdx = (nodeIdx + 1) % sortedNodes.length;
if (sortedNodes[nextIdx].angle <= v.angle) {
// v.angle is somewhere after last node?
// This gets messy with sorting modulo 2PI.
// Better: map angle to [0, 1) relative to first node.
}
}
// SIMPLER: Map all angles to 0..2PI range.
// Ensure nodes are sorted 0..2PI. Force first node angle to 0 for simplicity? No.
// Let's just standardize: Physical nodes are placed at fixed equal intervals. Vnodes are random.
// The owner of a vnode is the physical node with the smallest clockwise distance.
// That means we go around the ring.
const sortedAngles = sortedNodes.map(n => n.angle);
for(let v of this.vnodes) {
// Find index i such that v.angle is between sortedAngles[i] and sortedAngles[i+1]
let assigned = false;
for(let i=0; i<sortedAngles.length; i++) {
const curr = sortedAngles[i];
const next = (i+1 < sortedAngles.length) ? sortedAngles[i+1] : sortedAngles[0] + Math.PI*2;
if (v.angle >= curr && v.angle < next) {
v.ownerId = sortedNodes[i].id;
assigned = true;
break;
}
}
if(!assigned) {
// Edge case floating point
v.ownerId = sortedNodes[0].id;
}
}
}
distributeKeys(numKeys) {
this.totalKeys = numKeys;
// Clear loads
for(let n of this.nodes) n.load = 0;
for(let v of this.vnodes) v.keys = 0;
const hashFn = (i) => {
// Simple pseudo-random but consistent based on i
const x = Math.sin(i) * 10000;
return x - Math.floor(x);
};
for (let i = 0; i < numKeys; i++) {
const r = hashFn(i); // angle 0..1
const angle = r * Math.PI * 2;
// Find vnode that owns this key (first vnode >= angle)
// Since vnodes are sorted by angle
let found = false;
for (let v of this.vnodes) {
if (v.angle >= angle) {
v.keys++;
found = true;
break;
}
}
if (!found) {
this.vnodes[0].keys++; // Wrap to first
}
}
// Aggregates to physical nodes
for (let v of this.vnodes) {
const node = this.nodes.find(n => n.id === v.ownerId);
if (node) node.load += v.keys;
}
// Calculate ideal and targets
return this.calculateStats();
}
calculateStats() {
const ideal = this.totalKeys / this.numNodes;
let deviations = this.nodes.map(n => n.load - ideal);
let variance = deviations.reduce((a,b) => a + b*b, 0) / this.numNodes;
let stdDev = Math.sqrt(variance);
let stdDevPct = (stdDev / ideal) * 100;
// Hotspots: Segments of arc where density > avg density by factor
// Partition ring into, say, 36 segments (10 deg each)
const segCount = 36;
const keysPerSeg = new Array(segCount).fill(0);
for(let v of this.vnodes) {
const segIdx = Math.floor((v.angle / (Math.PI*2)) * segCount) % segCount;
keysPerSeg[segIdx] += v.keys;
}
const avgSegLoad = this.totalKeys / segCount;
const hotspots = keysPerSeg.filter(k => k > avgSegLoad * 1.5).length;
return { ideal, stdDevPct, hotspots, total: this.totalKeys };
}
triggerRebalance() {
// Simulate consistent hashing rebalance: add/remove nodes logic?
// For this monitor: We move the physical node angles slightly to "rebalance" ownership?
// Actually consistent hashing rebalances by adding/removing nodes or virtual nodes.
// To visualize "auto-rebalance", we will redistribute vnodes.
// Process:
// 1. Calculate target loads.
// 2. Transfer vnodes from overloaded nodes to underloaded ones by moving vnode.ownerId.
const ideal = this.totalKeys / this.numNodes;
// Sort nodes by load descending
const sortedByLoad = [...this.nodes].sort((a,b) => b.load - a.load);
// Identify overloaded (> ideal) and underloaded (< ideal)
const overloaded = sortedByLoad.filter(n => n.load > ideal * 1.05);
const underloaded = sortedByLoad.filter(n => n.load < ideal * 0.95);
if(overloaded.length === 0 || underloaded.length === 0) return false;
// Simple greedy transfer: move vnodes from most overloaded to most underloaded
let donor = overloaded[0];
let receiver = underloaded[0];
// Find a vnode belonging to donor
const donorVnodes = this.vnodes.filter(v => v.ownerId === donor.id);
if (donorVnodes.length === 0) return false;
// Pick one and reassign
const v = donorVnodes[Math.floor(Math.random() * donorVnodes.length)];
// Reassign owner
v.ownerId = receiver.id;
// Animate the visual transfer? The vnode stays at same angle but color changes.
// To make it cool, we can animate a "beam" from donor to receiver.
this.animateTransfer(donor, receiver, v);
// Recalculate loads immediately for next frame visualization
// In a real scenario, keys would eventually move. For simulation, we assume move happens instantly.
donor.load -= v.keys;
receiver.load += v.keys;
return true;
}
animateTransfer(donor, receiver, vnode) {
// Store temporary animation state in renderer
transfers.push({
startAngle: vnode.angle,
endReceiverId: receiver.id,
progress: 0,
duration: 60 // frames
});
}
}
/**
* ------------------------------------------------------------------
* VISUALIZATION ENGINE (CANVAS)
* ------------------------------------------------------------------
*/
const canvas = document.getElementById('ring-canvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const centerX = width / 2;
const centerY = height / 2;
// 3D Tilt Constants
const ringRadiusX = 280;
const ringRadiusY = 280 * 0.4; // Flattened ellipse
const nodeRadius = 12;
let ringSystem;
let transfers = []; // Animation queue
function initRing() {
ringSystem = new HashRing(10, 20); // 10 nodes, 20 vnodes each = 200 vnodes
ringSystem.generateVnodes();
ringSystem.distributeKeys(2000); // Start with 2000 keys
// Init scramblers
['total-nodes', 'total-vnodes', 'total-keys', 'imbalance-val', 'hotspot-count'].forEach(id => {
const el = document.getElementById(id);
scramblers[id] = new TextScramble(el);
});
requestAnimationFrame(loop);
}
function drawHUD() {
const stats = ringSystem.calculateStats();
// Update Text Elements (using Scramble occasionally)
// We don't scramble every frame, only when big changes.
// For smoothness, we just update raw text for most static things, but let's scramble stats.
// Node Table
const tbody = document.getElementById('node-table-body');
tbody.innerHTML = '';
ringSystem.nodes.sort((a,b) => a.load - b.load).forEach(node => {
const loadPct = ringSystem.totalKeys > 0 ? (node.load / ringSystem.totalKeys * 100).toFixed(1) : 0;
const color = loadPct > 12 ? 'text-neon-magenta' : 'text-neon-cyan';
const borderColor = loadPct > 12 ? 'border-neon-magenta' : 'border-neon-cyan';
const row = `
<tr class="border-b border-gray-800 hover:bg-white/5">
<td class="py-2 ${color}">${node.name}</td>
<td class="py-2 text-right font-bold ${color}">${node.load}</td>
<td class="py-2 text-right text-[10px] text-gray-500">${loadPct}%</td>
</tr>
`;
tbody.innerHTML += row;
});
// Metrics
document.getElementById('total-nodes').innerText = ringSystem.numNodes;
document.getElementById('total-vnodes').innerText = ringSystem.vnodes.length;
// Only scramble if changed
const currentKeys = parseInt(document.getElementById('total-keys').dataset.val || 0);
if (currentKeys !== ringSystem.totalKeys) {
updateScramble('total-keys', ringSystem.totalKeys);
document.getElementById('total-keys').dataset.val = ringSystem.totalKeys;
}
const imbalancePct = stats.stdDevPct;
updateScramble('imbalance-val', imbalancePct.toFixed(1) + '%');
document.getElementById('imbalance-bar').style.width = Math.min(imbalancePct * 2, 100) + '%';
if (imbalancePct > 15) {
document.getElementById('imbalance-bar').className = 'h-full bg-neon-magenta animate-pulse';
document.getElementById('status-indicator').innerText = 'WARNING';
document.getElementById('status-indicator').style.color = '#ff00ff';
} else if (imbalancePct > 8) {
document.getElementById('imbalance-bar').className = 'h-full bg-neon-amber';
document.getElementById('status-indicator').innerText = 'ELEVATED';
document.getElementById('status-indicator').style.color = '#ff9500';
} else {
document.getElementById('imbalance-bar').className = 'h-full bg-neon-cyan';
document.getElementById('status-indicator').innerText = 'OPTIMAL';
document.getElementById('status-indicator').style.color = '#00f3ff';
}
updateScramble('hotspot-count', stats.hotspots);
}
function drawRingScene() {
// Clear
ctx.fillStyle = '#050505';
ctx.clearRect(0, 0, width, height);
// Setup transform
ctx.save();
ctx.translate(centerX, centerY);
// Draw Outer Grid (HUD circle)
ctx.strokeStyle = 'rgba(0, 243, 255, 0.1)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.ellipse(0, 0, ringRadiusX + 30, ringRadiusY + 30, 0, 0, Math.PI * 2);
ctx.stroke();
// Draw Hash Ring (Track)
ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
ctx.lineWidth = 4;
ctx.beginPath();
ctx.ellipse(0, 0, ringRadiusX, ringRadiusY, 0, 0, Math.PI * 2);
ctx.stroke();
// Draw VNodes (Segments/Arcs)
// We will group vnodes by owner to draw contiguous arcs? Or individual tiny arcs?
// Individual arcs look cooler (like a bar chart around a circle).
const maxVnodeKeys = Math.max(...ringSystem.vnodes.map(v => v.keys), 1);
const arcHeightScale = 8;
// Sort vnodes by angle
const sortedVnodes = [...ringSystem.vnodes].sort((a,b) => a.angle - b.angle);
for (let v of sortedVnodes) {
const owner = ringSystem.nodes.find(n => n.id === v.ownerId);
const intensity = v.keys / maxVnodeKeys; // 0..1
// Color based on owner color, mix with white for load
let color = owner.color;
// Hotspot detection per segment? Just color if too many keys
if (v.keys > 50) {
color = '#ff9500'; // Amber
} else if (v.keys > 80) {
color = '#ff00ff'; // Magenta
}
const arcLen = (Math.PI * 2) / ringSystem.vnodes.length * 0.8; // gap visualized
const startAngle = v.angle - arcLen/2;
// Draw bar (elliptical arc)
ctx.save();
ctx.rotate(v.angle); // Align to radius
ctx.translate(0, -ringRadiusY); // Move to ring edge
// We draw a vertical rectangle representing the arc segment width/depth
// Actually simpler: draw ellipse arc with lineWidth proportional to keys
ctx.lineWidth = 0.5 + intensity * arcHeightScale;
ctx.strokeStyle = color;
ctx.shadowColor = color;
ctx.shadowBlur = intensity * 10;
// Draw partial arc
ctx.beginPath();
// This is tricky with rotation. Let's not rotate context, use ellipse().
ctx.restore();
// Use ellipse path method
ctx.beginPath();
// We want an arc segment from startAngle to endAngle, but we need to handle the ellipse radius difference.
// Simulating "thickness" along the radius direction:
// Draw another ellipse with radiusX+thickness? No, that's outside.
// Ideally: Draw a cone-shaped segment.
// Approx: Draw a thick stroke on the main ring.
}
// Alternative draw: Use the main ring path, change lineWidth per point? Too hard.
// Let's draw "chunks": small thick lines radiating outward.
for (let v of sortedVnodes) {
const owner = ringSystem.nodes.find(n => n.id === v.ownerId);
const intensity = v.keys / maxVnodeKeys;
if (intensity < 0.05) continue; // Skip empty
const color = owner.color;
const len = 20 + intensity * 40;
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(v.angle);
// Draw a line along the radius pointing outward
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.shadowBlur = 5;
ctx.shadowColor = color;
ctx.beginPath();
ctx.moveTo(ringRadiusX, 0);
ctx.lineTo(ringRadiusX + len, 0);
ctx.stroke();
ctx.restore();
}
// Draw Physical Nodes (Large Markers)
for (let node of ringSystem.nodes) {
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(node.angle);
const x = ringRadiusX;
const y = 0;
// Node Glow
ctx.fillStyle = node.color;
ctx.shadowBlur = 15;
ctx.shadowColor = node.color;
// Draw Triangle/Chevron pointing outward
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + 15, y - 8);
ctx.lineTo(x + 15, y + 8);
ctx.closePath();
ctx.fill();
// Draw Label (Rotated)
ctx.shadowBlur = 0;
ctx.fillStyle = '#fff';
ctx.font = '12px "JetBrains Mono"';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
// Save rotation to draw non-rotated text?
// HUD text usually stays upright. But FUI often aligns text along rim.
// Let's keep upright by reversing rotation.
ctx.rotate(-node.angle);
ctx.fillText(node.name, x + 20, 0);
ctx.restore();
}
// Draw Transfers (Beams)
for (let i = transfers.length - 1; i >= 0; i--) {
const tr = transfers[i];
const startX = centerX + Math.cos(tr.startAngle) * ringRadiusX;
const startY = centerY + Math.sin(tr.startAngle) * ringRadiusY;
// Find receiver position (angle)?
// We just animate a packet moving to receiver center?
// For simplicity: line to center of ring highlighting target node?? Not perfect.
// Let's do a arc effect expanding outward.
ctx.strokeStyle = '#ff00ff';
ctx.lineWidth = 2;
ctx.shadowBlur = 10;
ctx.shadowColor = '#ff00ff';
ctx.beginPath();
ctx.arc(centerX, centerY, ringRadiusX + 30, tr.startAngle, tr.startAngle + 0.5);
ctx.stroke();
tr.progress++;
if(tr.progress > tr.duration) transfers.splice(i, 1);
}
ctx.restore();
}
function loop() {
drawHUD();
drawRingScene();
requestAnimationFrame(loop);
}
/**
* ------------------------------------------------------------------
* INTERACTION & EVENTS
* ------------------------------------------------------------------
*/
// Clock
setInterval(() => {
const now = new Date();
const timeStr = now.toISOString().split('T')[1].replace('Z', '');
document.getElementById('clock').innerText = timeStr;
}, 10);
// Logger
function log(msg, type='info') {
const el = document.getElementById('event-log');
const entry = document.createElement('div');
const color = type==='warn' ? 'text-neon-magenta' : 'text-neon-cyan';
entry.innerHTML = `<span class="text-gray-500">[${new Date().toLocaleTimeString('en-GB')}]</span> <span class="${color}">${msg}</span>`;
el.prepend(entry); // Newest top
if (el.childElementCount > 20) el.lastChild.remove();
}
// Buttons
document.getElementById('add-key-btn').addEventListener('click', () => {
// Simulate adding keys (increase load)
const newKeys = ringSystem.totalKeys + 100;
ringSystem.distributeKeys(newKeys);
log(`INJECTED 100 KEYS. TOTAL: ${newKeys}`, 'info');
});
document.getElementById('rebalance-btn').addEventListener('click', () => {
const stats = ringSystem.calculateStats();
if (stats.stdDevPct < 5) {
log('REBALANCE ABORTED: LOAD ALREADY OPTIMAL.', 'warn');
return;
}
log('INITIATING AUTO-REBALANCE PROTOCOL...', 'warn');
// Perform multiple reassignments
let count = 0;
const interval = setInterval(() => {
const moved = ringSystem.triggerRebalance();
if (!moved) {
clearInterval(interval);
log('REBALANCE COMPLETE. DISTRIBUTION STABILIZED.', 'info');
} else {
count++;
}
}, 50);
});
// Particle System (Background)
const pCanvas = document.getElementById('particle-canvas');
const pCtx = pCanvas.getContext('2d');
let particles = [];
function resizeParticles() {
pCanvas.width = window.innerWidth;
pCanvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeParticles);
resizeParticles();
class Particle {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * pCanvas.width;
this.y = Math.random() * pCanvas.height;
this.vx = (Math.random() - 0.5) * 0.5;
this.vy = (Math.random() - 0.5) * 0.5;
this.size = Math.random() * 2;
this.alpha = Math.random() * 0.5 + 0.1;
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > pCanvas.width || this.y < 0 || this.y > pCanvas.height) this.reset();
}
draw() {
pCtx.fillStyle = `rgba(0, 243, 255, ${this.alpha})`;
pCtx.beginPath();
pCtx.arc(this.x, this.y, this.size, 0, Math.PI*2);
pCtx.fill();
}
}
for(let i=0; i<100; i++) particles.push(new Particle());
function animateParticles() {
pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
particles.forEach(p => {
p.update();
p.draw();
});
requestAnimationFrame(animateParticles);
}
animateParticles();
// Initial startup
window.onload = () => {
initRing();
log('SYSTEM INITIALIZED. WAITING FOR TELEMETRY.', 'info');
};
</script>
</body>
</html>