"
// e.g. "hostile go to blue zone"
// "ally come here"
// "wanderer dance"
// "everyone stop"
// No NPC name → defaults to ally (your team helper).
//
// Commands are PARSED IN-BROWSER and applied INSTANTLY. The parsed command
// also gets a 6-second voice-override window during which the AI doesn't
// re-target that NPC — so the player's intent isn't immediately overwritten.
// ────────────────────────────────────────────────────────────────────────────
function setupVoice() {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SR) {
document.getElementById('mic-text').textContent =
'speech API unsupported — use Chrome/Edge';
return false;
}
const r = new SR();
r.continuous = true;
r.interimResults = true;
r.lang = 'en-US';
r.maxAlternatives = 1;
r.onresult = e => {
let interim = '', final = '';
for (let i = e.resultIndex; i < e.results.length; i++) {
const t = e.results[i][0].transcript;
if (e.results[i].isFinal) final += t;
else interim += t;
}
const heardEl = document.getElementById('voice-heard');
if (interim && !final) {
heardEl.textContent = `"${interim.trim()}…"`;
heardEl.style.opacity = '0.55';
}
if (final) {
const cleaned = final.trim().toLowerCase();
heardEl.textContent = `"${cleaned}"`;
heardEl.style.opacity = '1';
state.lastVoiceText = cleaned;
handleVoiceCommand(cleaned);
}
};
r.onerror = ev => {
const m = document.getElementById('mic-text');
if (ev.error === 'not-allowed' || ev.error === 'service-not-allowed') {
m.textContent = 'mic blocked — allow mic in browser settings';
} else if (ev.error === 'no-speech') {
// expected when silent; ignore
} else {
m.textContent = `mic: ${ev.error}`;
}
};
r.onend = () => {
if (state.voiceActive) {
try { r.start(); } catch {}
}
};
state.recognition = r;
return true;
}
async function requestMicPermission() {
// Trigger the browser's explicit mic permission prompt by opening a
// throwaway audio stream. SpeechRecognition alone often fails silently
// when the page hasn't yet asked for mic access.
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
return { ok: false, reason: 'no-mediadevices' };
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
// Immediately stop — we just needed the permission, SpeechRecognition
// opens its own audio pipeline.
stream.getTracks().forEach(t => t.stop());
return { ok: true };
} catch (err) {
return { ok: false, reason: err.name || err.message };
}
}
async function toggleVoice() {
if (!state.recognition && !setupVoice()) return;
const m = document.getElementById('mic-text');
if (state.voiceActive) {
state.recognition.stop();
state.voiceActive = false;
document.getElementById('mic-dot').classList.remove('live');
m.textContent = 'voice OFF (V to enable)';
return;
}
// Step 1: get mic permission via the standard prompt.
m.textContent = 'requesting mic permission…';
const perm = await requestMicPermission();
if (!perm.ok) {
if (perm.reason === 'NotAllowedError') {
m.textContent = '❌ mic blocked — click 🔒 in URL bar → Microphone → Allow → reload';
} else if (perm.reason === 'NotFoundError') {
m.textContent = '❌ no microphone detected on this device';
} else if (perm.reason === 'no-mediadevices') {
m.textContent = '❌ getUserMedia unsupported — open page over http://localhost or https';
} else {
m.textContent = `❌ mic error: ${perm.reason}`;
}
return;
}
// Step 2: start SpeechRecognition (now that the page has mic permission).
try {
state.recognition.start();
state.voiceActive = true;
document.getElementById('mic-dot').classList.add('live');
m.textContent = 'listening… try "hostile go to blue zone" or "ally come here"';
} catch (err) {
m.textContent = 'mic error: ' + (err.message || err.name);
}
}
// ── Voice command parser ───────────────────────────────────────────────────
function handleVoiceCommand(text) {
// 1. Pick target NPC(s)
let targetRole = null;
if (/\b(everyone|everybody|all of you|all)\b/.test(text)) targetRole = 'all';
else if (/\bhostile\b/.test(text)) targetRole = 'hostile';
else if (/\bally\b/.test(text)) targetRole = 'ally';
else if (/\b(wanderer|wonderer|wonder|wander)\b/.test(text)) targetRole = 'wanderer';
else targetRole = 'ally'; // default
const targets = targetRole === 'all'
? state.npcs
: state.npcs.filter(n => n.userData.role === targetRole);
if (!targets.length) return;
// 2. Pick action + destination
let action = null, destination = null, sayLine = null, color = null;
if (/\bred\b/.test(text)) {
action = 'navigate'; destination = ZONES.red.pos.clone();
sayLine = 'Heading to the red zone!'; color = 'red';
} else if (/\bblue\b/.test(text)) {
action = 'navigate'; destination = ZONES.blue.pos.clone();
sayLine = 'Heading to the blue zone!'; color = 'blue';
} else if (/\bgreen\b/.test(text)) {
action = 'navigate'; destination = ZONES.green.pos.clone();
sayLine = 'Heading to the green zone!'; color = 'green';
} else if (/\b(come|follow|here)\b/.test(text)) {
action = 'follow'; sayLine = 'On my way!';
} else if (/\bdance\b/.test(text)) {
action = 'dance'; sayLine = "Let's dance!";
} else if (/\b(stop|wait|halt|freeze|stay)\b/.test(text)) {
action = 'stop'; sayLine = 'Standing by.';
} else if (/\b(coin|coins|collect|grab|pick)\b/.test(text)) {
action = 'coin'; sayLine = 'Going for the coins!';
} else if (/\b(run|flee|escape|away)\b/.test(text)) {
action = 'flee'; sayLine = 'Getting out of here!';
} else {
// No match — show what we heard but do nothing
document.getElementById('mic-text').textContent =
`heard but no command match — try a zone, "follow", "dance", or "stop"`;
setTimeout(() => {
if (state.voiceActive) document.getElementById('mic-text').textContent = 'listening…';
}, 2500);
return;
}
// 3. Apply the parsed command directly to each target NPC
const now = performance.now();
for (const npc of targets) {
if (action === 'navigate') {
npc.userData.target = destination.clone();
} else if (action === 'follow') {
npc.userData.target = state.player.position.clone();
} else if (action === 'coin') {
npc.userData.target = pickNearestCoin(npc.position);
} else if (action === 'flee') {
const away = npc.position.clone()
.sub(state.player.position).normalize().multiplyScalar(10);
npc.userData.target = npc.position.clone().add(away);
} else if (action === 'stop' || action === 'dance') {
npc.userData.target = null;
}
// 6-second voice-override window: AI inference for this NPC is paused
npc.userData.voiceOverrideUntil = now + 6000;
npc.userData.say = sayLine;
npc.userData.speakUntil = now + 4000;
showSayBubble(npc, sayLine);
// Update bottom HUD card so the user sees it took effect
const card = document.getElementById(`card-${npc.userData.role}`);
if (card) {
card.querySelector('.action').textContent = `voice: ${action}${color ? ' ' + color : ''}`;
card.querySelector('.say').textContent = `"${sayLine}"`;
}
}
// 4. Echo back the parsed command above the mic
const label = targetRole === 'all' ? 'EVERYONE' : targetRole.toUpperCase();
document.getElementById('mic-text').textContent =
`→ ${label}: ${action}${color ? ' ' + color + ' zone' : ''}`;
sfx.voiceAck();
setTimeout(() => {
if (state.voiceActive) document.getElementById('mic-text').textContent = 'listening…';
}, 2500);
}
// ────────────────────────────────────────────────────────────────────────────
// Recording (MediaRecorder on the canvas stream)
// ────────────────────────────────────────────────────────────────────────────
function toggleRecording() {
if (state.recording) {
state.recorder.stop();
state.recording = false;
document.getElementById('recording-badge').classList.remove('live');
return;
}
const stream = canvas.captureStream(30);
state.recordChunks = [];
state.recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp9' });
state.recorder.ondataavailable = e => state.recordChunks.push(e.data);
state.recorder.onstop = () => {
const blob = new Blob(state.recordChunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = `omninpc-${Date.now()}.webm`; a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
state.recorder.start();
state.recording = true;
document.getElementById('recording-badge').classList.add('live');
}
// ────────────────────────────────────────────────────────────────────────────
// Latency chart
// ────────────────────────────────────────────────────────────────────────────
const latCanvas = document.getElementById('lat-canvas');
const latCtx = latCanvas.getContext('2d');
function drawLatencyChart() {
const w = latCanvas.width = latCanvas.clientWidth * devicePixelRatio;
const h = latCanvas.height = latCanvas.clientHeight * devicePixelRatio;
latCtx.clearRect(0, 0, w, h);
const lats = state.latencies;
if (!lats.length) return;
const maxLat = Math.max(2000, ...lats);
const bw = w / Math.max(30, lats.length);
for (let i = 0; i < lats.length; i++) {
const v = lats[i];
const bh = (v / maxLat) * h;
const color = v < 1000 ? '#76b900' : v < 2500 ? '#facc15' : '#f87171';
latCtx.fillStyle = color;
latCtx.fillRect(i * bw, h - bh, bw - 1, bh);
}
// Stats
const avg = lats.reduce((a,b)=>a+b,0) / lats.length;
const sorted = [...lats].sort((a,b)=>a-b);
const p95 = sorted[Math.floor(sorted.length * 0.95)] || 0;
document.getElementById('lat-avg').textContent = `${Math.round(avg)}ms`;
document.getElementById('lat-p95').textContent = `${Math.round(p95)}ms`;
document.getElementById('lat-calls').textContent = state.totalCalls;
document.getElementById('lat-errors').textContent = state.errorCount || 0;
}
// ────────────────────────────────────────────────────────────────────────────
// Reasoning panel
// ────────────────────────────────────────────────────────────────────────────
function addThink(role, text) {
const list = document.getElementById('think-list');
const div = document.createElement('div');
const isSuper = role.includes('super');
div.className = 'think-entry' + (isSuper ? ' super-entry' : '');
div.innerHTML = `${role.toUpperCase()} ${escapeHtml(text.slice(0, 400))}${text.length > 400 ? '…' : ''}`;
list.insertBefore(div, list.firstChild);
while (list.childNodes.length > 10) list.removeChild(list.lastChild);
}
function escapeHtml(s) {
return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
// ────────────────────────────────────────────────────────────────────────────
// Player + NPC update loop
// ────────────────────────────────────────────────────────────────────────────
const clock = new THREE.Clock();
function tick() {
const dt = Math.min(0.05, clock.getDelta());
if (state.running) {
updatePlayer(dt);
updateNPCs(dt);
updateCoins(dt);
updateParticles(dt);
updateTimer(dt);
schedulePerception();
maybeRunDialogue(performance.now());
}
renderer.render(scene, camera);
requestAnimationFrame(tick);
}
function updatePlayer(dt) {
// Three.js camera looks toward -Z by default. With player.rotation.y = yaw:
// yaw=0 → forward = (0, 0, -1)
// yaw=π/2 → forward = (-1, 0, 0)
// So forward = (-sin yaw, 0, -cos yaw); right = (cos yaw, 0, -sin yaw).
const fwd = new THREE.Vector3(-Math.sin(state.yaw), 0, -Math.cos(state.yaw));
const right = new THREE.Vector3(Math.cos(state.yaw), 0, -Math.sin(state.yaw));
const v = new THREE.Vector3();
if (state.keys.KeyW) v.add(fwd);
if (state.keys.KeyS) v.sub(fwd);
if (state.keys.KeyA) v.sub(right);
if (state.keys.KeyD) v.add(right);
if (v.lengthSq() > 0) v.normalize();
const sp = state.keys.ShiftLeft || state.keys.ShiftRight ? PLAYER_SPEED * 1.6 : PLAYER_SPEED;
state.player.position.x += v.x * sp * dt;
state.player.position.z += v.z * sp * dt;
// Jump
if (state.keys.Space && state.onGround) {
state.velocityY = 6.5; state.onGround = false;
}
state.velocityY -= 18 * dt;
state.player.position.y += state.velocityY * dt;
if (state.player.position.y <= 0) {
state.player.position.y = 0; state.velocityY = 0; state.onGround = true;
}
// Clamp to arena
state.player.position.x = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, state.player.position.x));
state.player.position.z = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, state.player.position.z));
// Camera
state.player.rotation.y = state.yaw;
camPivot.rotation.x = state.pitch;
// Auto-pickup on touch
for (const c of state.coins) {
if (!c.alive) continue;
if (state.player.position.distanceTo(c.mesh.position) < PICKUP_DIST) {
c.alive = false; scene.remove(c.mesh);
state.scores.player++;
document.getElementById('score-player').textContent = state.scores.player;
emitParticles(c.mesh.position, 0xa3e635);
sfx.coinPlayer();
}
}
}
function tryPlayerPickup() {
for (const c of state.coins) {
if (!c.alive) continue;
if (state.player.position.distanceTo(c.mesh.position) < PICKUP_DIST + 0.3) {
c.alive = false; scene.remove(c.mesh);
state.scores.player++;
document.getElementById('score-player').textContent = state.scores.player;
emitParticles(c.mesh.position, 0xa3e635);
sfx.coinPlayer();
return;
}
}
}
function updateNPCs(dt) {
const now = performance.now();
for (const npc of state.npcs) {
const u = npc.userData;
let moved = false;
// ── Per-frame proximity reaction (no AI call needed) ──
// Runs every frame so the NPC reacts the instant the player is in range,
// not on the next inference (~2s away). The Nemotron action is still
// applied separately — this is just reflex.
const distP = state.player ? npc.position.distanceTo(state.player.position) : 999;
if (u.role === 'hostile' && distP < 4 && (u.voiceOverrideUntil || 0) < now) {
// Hostile sprints AWAY from player
const away = npc.position.clone().sub(state.player.position).setY(0).normalize().multiplyScalar(8);
u.target = npc.position.clone().add(away);
u.speed = NPC_SPEED * 1.6; // sprint
if (now > (u.proxSpokeUntil || 0) + 3500) {
const lines = ['Stay back!', 'Get away from me!', "I'm out!"];
const line = lines[Math.floor(Math.random() * lines.length)];
u.say = line; u.speakUntil = now + 2500; showSayBubble(npc, line);
u.proxSpokeUntil = now;
sfx.evade();
}
} else if (u.role === 'ally' && distP > 6 && (u.voiceOverrideUntil || 0) < now && !u.target) {
// Ally drifts toward you when too far
u.target = state.player.position.clone();
u.speed = NPC_SPEED;
} else {
u.speed = NPC_SPEED;
}
if (u.target) {
const dx = u.target.x - npc.position.x;
const dz = u.target.z - npc.position.z;
const d = Math.sqrt(dx*dx + dz*dz);
if (d > 0.3) {
const nx = dx / d, nz = dz / d;
npc.position.x += nx * u.speed * dt;
npc.position.z += nz * u.speed * dt;
npc.rotation.y = Math.atan2(nx, nz);
moved = true;
} else {
u.target = null;
}
}
// Clamp
npc.position.x = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, npc.position.x));
npc.position.z = Math.max(-ARENA_HALF + 0.5, Math.min(ARENA_HALF - 0.5, npc.position.z));
// NPC coin pickup
for (const c of state.coins) {
if (!c.alive) continue;
if (npc.position.distanceTo(c.mesh.position) < PICKUP_DIST) {
c.alive = false; scene.remove(c.mesh);
state.scores[u.role]++;
document.getElementById(`score-${u.role}`).textContent = state.scores[u.role];
emitParticles(c.mesh.position, 0xfff088);
sfx.coinNPC();
}
}
// Limb animation
if (moved) {
u.walkTime += dt * 8;
const swing = Math.sin(u.walkTime) * 0.5;
u.larm.rotation.x = swing;
u.rarm.rotation.x = -swing;
u.lleg.rotation.x = -swing;
u.rleg.rotation.x = swing;
} else {
u.larm.rotation.x *= 0.9;
u.rarm.rotation.x *= 0.9;
u.lleg.rotation.x *= 0.9;
u.rleg.rotation.x *= 0.9;
}
// Speech bubble fade
if (u.sayBubble && performance.now() > u.speakUntil) {
npc.remove(u.sayBubble);
u.sayBubble.material.map.dispose();
u.sayBubble.material.dispose();
u.sayBubble = null;
}
}
}
function updateCoins(dt) {
for (const c of state.coins) {
if (!c.alive) continue;
c.spin += dt * 3;
c.mesh.rotation.y = c.spin;
c.mesh.position.y = 0.7 + Math.sin(c.spin) * 0.1;
}
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.position.x += p.userData.vx * dt;
p.position.y += p.userData.vy * dt;
p.position.z += p.userData.vz * dt;
p.userData.vy -= 9 * dt;
p.userData.life -= dt;
if (p.userData.life <= 0) {
scene.remove(p); p.geometry.dispose(); p.material.dispose();
particles.splice(i, 1);
}
}
}
function updateTimer(dt) {
const before = state.timeLeft;
state.timeLeft -= dt;
// Per-second countdown beep in the last 5 seconds
const flBefore = Math.floor(before);
const flNow = Math.floor(state.timeLeft);
if (flNow !== flBefore && state.timeLeft > 0 && state.timeLeft < 5.5) {
sfx.countdown();
}
if (state.timeLeft <= 0) endGame();
const t = Math.max(0, state.timeLeft);
const el = document.getElementById('timer');
el.textContent = t.toFixed(1);
el.classList.toggle('urgent', t < 10);
}
function schedulePerception() {
const now = performance.now();
if (state.npcs.length === 0) return;
// Back off when NIM errors are happening (rate limit, 5xx). Once the
// window passes, the next call retries. This keeps the UI responsive.
if ((state.errorBackoffUntil || 0) > now) return;
const slotInterval = PERCEPTION_INTERVAL_MS;
for (let attempt = 0; attempt < state.npcs.length; attempt++) {
const npc = state.npcs[state.rrIndex % state.npcs.length];
state.rrIndex = (state.rrIndex + 1) % state.npcs.length;
if ((npc.userData.voiceOverrideUntil || 0) > now) continue;
if (now - (npc.userData.lastInferTime || 0) > slotInterval) {
npc.userData.lastInferTime = now;
callInfer(npc, '');
break;
}
}
if (now - state.lastSuperTime > SUPER_INTERVAL_MS) {
state.lastSuperTime = now;
callSuper();
}
}
// ────────────────────────────────────────────────────────────────────────────
// Game flow
// ────────────────────────────────────────────────────────────────────────────
function startGame() {
// Web Audio requires a user-gesture before playing — kick it now.
const ctx = sfx.ensure();
if (ctx && ctx.state === 'suspended') ctx.resume();
API_URL = document.getElementById('api-input').value.trim() || window.location.origin;
// probe health to give early feedback
fetch(`${API_URL}/health`).then(r => r.json()).then(h => {
if (!h.api_key_set) {
document.getElementById('directive').textContent =
'⚠ API key not set on server — set NVIDIA_NIM_API_KEY before /infer works.';
} else {
document.getElementById('directive').textContent = `connected · Nano=${h.nano_model.split('/').pop()}`;
}
}).catch(() => {
document.getElementById('directive').textContent =
`❌ cannot reach ${API_URL} — start api_server.py first.`;
});
document.getElementById('start-screen').style.display = 'none';
state.running = true;
state.startTime = performance.now();
state.timeLeft = ROUND_SECONDS;
state.scores = { player: 0, hostile: 0, ally: 0, wanderer: 0 };
for (const k of ['player','hostile','ally','wanderer']) {
document.getElementById(`score-${k}`).textContent = 0;
}
spawnCoins();
canvas.requestPointerLock();
state.lastSuperTime = performance.now() - SUPER_INTERVAL_MS + 2000; // first super in ~2s
}
function endGame() {
state.running = false;
if (state.recording) toggleRecording();
document.exitPointerLock();
const winner = Object.entries(state.scores).sort((a,b)=>b[1]-a[1])[0];
if (winner[0] === 'player') sfx.win(); else sfx.loss();
document.getElementById('end-title').textContent =
winner[0] === 'player' ? 'YOU WIN!' : `${winner[0].toUpperCase()} WINS`;
document.getElementById('end-stats').innerHTML = `
YOU: ${state.scores.player} coins
ALLY: ${state.scores.ally} coins
HOSTILE: ${state.scores.hostile} coins
WANDERER: ${state.scores.wanderer} coins
${state.totalCalls} Nano inference calls · avg ${Math.round(state.latencies.reduce((a,b)=>a+b,0)/Math.max(1,state.latencies.length))}ms
`;
document.getElementById('end-screen').classList.add('show');
}
document.getElementById('start-btn').onclick = startGame;
document.getElementById('end-restart').onclick = () => {
document.getElementById('end-screen').classList.remove('show');
document.getElementById('start-screen').style.display = 'flex';
// reset NPC positions
state.npcs[0].position.set(8, 0, 8);
state.npcs[1].position.set(-6, 0, -2);
state.npcs[2].position.set(-8, 0, 8);
state.player.position.set(0, 0, -8);
state.yaw = 0; state.pitch = 0;
};
tick();