1 Commits

Author SHA1 Message Date
Alexander Whitestone
232a0ed9d2 feat: Session Power Meter — 3D balance visualizer (#17)
Some checks failed
CI / Typecheck & Lint (pull_request) Failing after 0s
Add a glowing orb power meter to the Workshop scene that reflects the
session balance in real time.

- power-meter.js: new Three.js module — transparent outer shell,
  inner orb that scales 0→1 with fill fraction, lightning bolt overlay,
  point light and equator ring accent; DOM text label projected above
  the orb shows current sats. Color interpolates red→yellow→cyan.
  Pulses bright on 'fill' event, quick flicker on 'drain'.
- session.js: imports meter helpers; tracks _sessionMax (initial
  deposit); calls setMeterVisible/setMeterBalance in _applySessionUI;
  triggers fill/drain pulses on payment and job deduction; exports
  openSessionPanel() for click-to-open wiring; clears meter on
  _clearSession.
- websocket.js: handles session_balance_update WS event — updates
  fill level and fires pulse.
- interaction.js: adds registerClickTarget(group, callback) — wired
  for both FPS pointer-lock and non-lock modes and short taps.
- main.js: wires initPowerMeter/updatePowerMeter/disposePowerMeter
  into the build/animate/teardown cycle; registers meter as click
  target that opens the session panel.

Fixes #17

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 22:31:43 -04:00
5 changed files with 372 additions and 9 deletions

View File

@@ -16,6 +16,9 @@ let _camera = null;
let _timmyGroup = null;
let _applySlap = null;
// Registered 3D click targets: Array of { group: THREE.Object3D, callback: fn }
const _clickTargets = [];
const _raycaster = new THREE.Raycaster();
const _pointer = new THREE.Vector2();
const _noCtxMenu = e => e.preventDefault();
@@ -33,6 +36,15 @@ export function registerSlapTarget(timmyGroup, applyFn) {
_applySlap = applyFn;
}
/**
* Register a Three.js Object3D as a clickable target.
* @param {THREE.Object3D} group The mesh/group to raycast against.
* @param {Function} callback Called when the user clicks the object.
*/
export function registerClickTarget(group, callback) {
_clickTargets.push({ group, callback });
}
export function initInteraction(camera, renderer) {
_camera = camera;
_canvas = renderer.domElement;
@@ -52,6 +64,7 @@ export function disposeInteraction() {
_camera = null;
_timmyGroup = null;
_applySlap = null;
_clickTargets.length = 0;
}
// ── Internal ──────────────────────────────────────────────────────────────────
@@ -120,6 +133,20 @@ function _tryAgentInspect(clientX, clientY) {
let _tapStart = 0;
let _tapX = 0, _tapY = 0;
function _tryClickTargets(clientX, clientY) {
if (!_clickTargets.length || !_camera || !_canvas) return false;
const rect = _canvas.getBoundingClientRect();
_pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
_pointer.y = ((clientY - rect.top) / rect.height) * -2 + 1;
_raycaster.setFromCamera(_pointer, _camera);
for (const target of _clickTargets) {
if (!target.group.visible) continue;
const hits = _raycaster.intersectObject(target.group, true);
if (hits.length > 0) { target.callback(); return true; }
}
return false;
}
function _onPointerDown(event) {
// Record tap start for short-tap detection
_tapStart = Date.now();
@@ -135,21 +162,30 @@ function _onPointerDown(event) {
const dt = Date.now() - _tapStart;
const moved = Math.hypot(upEvent.clientX - _tapX, upEvent.clientY - _tapY);
if (dt < 220 && moved < 18) {
// Short tap — try slap then inspect
if (!_hitTestTimmy(upEvent.clientX, upEvent.clientY)) {
_tryAgentInspect(upEvent.clientX, upEvent.clientY);
// Short tap — try click targets, then slap, then inspect
if (!_tryClickTargets(upEvent.clientX, upEvent.clientY)) {
if (!_hitTestTimmy(upEvent.clientX, upEvent.clientY)) {
_tryAgentInspect(upEvent.clientX, upEvent.clientY);
}
}
}
};
_canvas.addEventListener('pointerup', onUp, { once: true });
} else {
// Desktop click: only fire when pointer lock is already active
// (otherwise navigation.js requests lock on this same click — that's fine,
// both can fire; slap + lock request together is acceptable)
if (document.pointerLockElement === _canvas) {
// Cast from screen center in FPS mode
// FPS mode: cast from screen centre
_pointer.set(0, 0);
_raycaster.setFromCamera(_pointer, _camera);
// Check registered click targets first
for (const target of _clickTargets) {
if (!target.group.visible) continue;
const hits = _raycaster.intersectObject(target.group, true);
if (hits.length > 0) {
target.callback();
event.stopImmediatePropagation();
return;
}
}
if (_timmyGroup && _applySlap) {
const hits = _raycaster.intersectObject(_timmyGroup, true);
if (hits.length > 0) {
@@ -157,6 +193,9 @@ function _onPointerDown(event) {
event.stopImmediatePropagation();
}
}
} else {
// Not in pointer lock — still handle click targets (e.g. power meter)
_tryClickTargets(event.clientX, event.clientY);
}
}
}

View File

@@ -7,10 +7,10 @@ import {
} from './agents.js';
import { initEffects, updateEffects, disposeEffects, updateJobIndicators } from './effects.js';
import { initUI, updateUI } from './ui.js';
import { initInteraction, disposeInteraction, registerSlapTarget } from './interaction.js';
import { initInteraction, disposeInteraction, registerSlapTarget, registerClickTarget } from './interaction.js';
import { initWebSocket, getConnectionState, getJobCount } from './websocket.js';
import { initPaymentPanel } from './payment.js';
import { initSessionPanel } from './session.js';
import { initSessionPanel, openSessionPanel } from './session.js';
import { initNostrIdentity } from './nostr-identity.js';
import { warmup as warmupEdgeWorker, onReady as onEdgeWorkerReady } from './edge-worker-client.js';
import { setEdgeWorkerReady } from './ui.js';
@@ -18,6 +18,7 @@ import { initTimmyId } from './timmy-id.js';
import { AGENT_DEFS } from './agent-defs.js';
import { initNavigation, updateNavigation, disposeNavigation } from './navigation.js';
import { initHudLabels, updateHudLabels, disposeHudLabels } from './hud-labels.js';
import { initPowerMeter, updatePowerMeter, disposePowerMeter, getMeterGroup } from './power-meter.js';
let running = false;
let canvas = null;
@@ -29,6 +30,7 @@ function buildWorld(firstInit, stateSnapshot) {
initEffects(scene);
initAgents(scene);
initPowerMeter(scene);
if (stateSnapshot) applyAgentStates(stateSnapshot);
@@ -37,6 +39,7 @@ function buildWorld(firstInit, stateSnapshot) {
initInteraction(camera, renderer);
registerSlapTarget(getTimmyGroup(), applySlap);
registerClickTarget(getMeterGroup(), openSessionPanel);
// AR floating labels
initHudLabels(camera, AGENT_DEFS, TIMMY_WORLD_POS);
@@ -82,6 +85,7 @@ function buildWorld(firstInit, stateSnapshot) {
updateEffects(now);
updateAgents(now);
updateJobIndicators(now);
updatePowerMeter(now, camera, renderer);
updateUI({
fps: currentFps,
agentCount: getAgentCount(),
@@ -121,6 +125,7 @@ function teardown({ scene, renderer, ac }) {
disposeNavigation();
disposeInteraction();
disposeHudLabels();
disposePowerMeter();
disposeEffects();
disposeAgents();
disposeWorld(renderer, scene);

View File

@@ -0,0 +1,291 @@
/**
* power-meter.js — 3D Session Power Meter
*
* A glowing orb that fills proportionally to the session balance.
* - Pulses brightly on payment received
* - Drains visibly on job cost deduction
* - Visible only when a funded session is active
* - Clicking the meter opens the session panel
*/
import * as THREE from 'three';
// ── World position (bottom-right corner, visible from default camera) ──────────
const METER_WORLD_POS = new THREE.Vector3(4.5, 0.85, 2.0);
const DEFAULT_MAX_SATS = 5000;
// ── Module state ───────────────────────────────────────────────────────────────
let _scene = null;
let _meterGroup = null;
let _innerOrb = null;
let _outerShell = null;
let _boltMesh = null;
let _orbMat = null;
let _shellMat = null;
let _meterLight = null;
let _labelEl = null;
let _fillFraction = 0; // 0..1, currently displayed fill
let _targetFill = 0; // 0..1, desired fill
let _pulseIntensity = 0; // 0..1, extra brightness from pulse
let _pulseDecay = 0; // per-frame decay rate
let _visible = false;
let _maxSats = DEFAULT_MAX_SATS;
let _currentSats = 0;
// ── Public API ─────────────────────────────────────────────────────────────────
export function initPowerMeter(scene) {
_scene = scene;
_labelEl = _createLabelEl();
_meterGroup = new THREE.Group();
_meterGroup.position.copy(METER_WORLD_POS);
_meterGroup.visible = false;
// Outer transparent shell
_shellMat = new THREE.MeshPhysicalMaterial({
color: 0x00aacc,
emissive: 0x003344,
emissiveIntensity: 0.4,
transparent: true,
opacity: 0.18,
roughness: 0.05,
metalness: 0.15,
side: THREE.DoubleSide,
});
_outerShell = new THREE.Mesh(new THREE.SphereGeometry(0.48, 24, 18), _shellMat);
_meterGroup.add(_outerShell);
// Equatorial ring accent
const ringMat = new THREE.MeshBasicMaterial({
color: 0x00ccff,
transparent: true,
opacity: 0.55,
});
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.48, 0.012, 8, 40), ringMat);
ring.rotation.x = Math.PI / 2;
_meterGroup.add(ring);
// Inner fill orb — scales with balance
_orbMat = new THREE.MeshStandardMaterial({
color: 0x00ffcc,
emissive: 0x00ffcc,
emissiveIntensity: 1.4,
roughness: 0.05,
transparent: true,
opacity: 0.90,
});
_innerOrb = new THREE.Mesh(new THREE.SphereGeometry(0.38, 20, 16), _orbMat);
_innerOrb.scale.setScalar(0.01);
_meterGroup.add(_innerOrb);
// Lightning bolt — flat shape rendered in front of sphere
_boltMesh = _makeBolt();
_boltMesh.position.set(0, 0, 0.50);
_meterGroup.add(_boltMesh);
// Point light — intensity tracks balance + pulse
_meterLight = new THREE.PointLight(0x00ccff, 0.0, 6);
_meterGroup.add(_meterLight);
scene.add(_meterGroup);
return _meterGroup;
}
/**
* Update balance and target fill level.
* @param {number} sats Current balance in satoshis
* @param {number} [maxSats] Session deposit cap (sets the "full" reference)
*/
export function setMeterBalance(sats, maxSats) {
_currentSats = Math.max(0, sats);
if (maxSats !== undefined && maxSats > 0) _maxSats = maxSats;
_targetFill = Math.min(1, _currentSats / _maxSats);
if (_labelEl) _labelEl.textContent = `${_currentSats}`;
}
/**
* Fire a pulse animation on the meter.
* @param {'fill'|'drain'} type
*/
export function triggerMeterPulse(type) {
if (type === 'fill') {
_pulseIntensity = 1.0;
_pulseDecay = 0.022; // slow bright flash
} else {
_pulseIntensity = 0.45;
_pulseDecay = 0.040; // quick drain flicker
}
}
/** Show or hide the power meter and its text label. */
export function setMeterVisible(visible) {
_visible = visible;
if (_meterGroup) _meterGroup.visible = visible;
if (_labelEl) _labelEl.style.display = visible ? 'block' : 'none';
if (!visible) {
_pulseIntensity = 0;
_fillFraction = 0;
_targetFill = 0;
if (_innerOrb) _innerOrb.scale.setScalar(0.01);
if (_meterLight) _meterLight.intensity = 0;
}
}
/** Returns the Three.js Group for raycasting. */
export function getMeterGroup() {
return _meterGroup;
}
/**
* Called every animation frame.
* @param {number} now performance.now() value
* @param {THREE.Camera} camera
* @param {THREE.WebGLRenderer} renderer
*/
export function updatePowerMeter(now, camera, renderer) {
if (!_meterGroup || !_visible) return;
const t = now * 0.001;
// Smooth fill toward target
_fillFraction += (_targetFill - _fillFraction) * 0.06;
const s = Math.max(0.01, _fillFraction * 0.94);
_innerOrb.scale.setScalar(s);
// Colour interpolation: empty=red → mid=orange/yellow → full=cyan
_updateOrbColor(_fillFraction, _pulseIntensity);
// Pulse decay
if (_pulseIntensity > 0) {
_pulseIntensity = Math.max(0, _pulseIntensity - _pulseDecay);
}
// Point light
_meterLight.intensity = _fillFraction * 1.6 + _pulseIntensity * 4.5;
// Shell emissive pulse
_shellMat.emissiveIntensity = 0.3 + _pulseIntensity * 1.8 + _fillFraction * 0.35;
// Gentle bob + slow rotation
_meterGroup.position.y = METER_WORLD_POS.y + Math.sin(t * 1.4) * 0.06;
_meterGroup.rotation.y = t * 0.35;
// Bolt scale pulses with balance and on payment
const boltS = 1.0 + _pulseIntensity * 0.55 + Math.sin(t * 3.2) * 0.05;
_boltMesh.scale.setScalar(boltS);
// DOM label
if (_labelEl && camera && renderer) {
_updateLabelPosition(camera, renderer);
}
}
export function disposePowerMeter() {
if (_meterGroup && _scene) {
_scene.remove(_meterGroup);
_meterGroup.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const mats = Array.isArray(child.material) ? child.material : [child.material];
mats.forEach(m => m.dispose());
}
});
_meterGroup = null;
}
if (_labelEl) {
_labelEl.remove();
_labelEl = null;
}
_scene = null;
}
// ── Internals ──────────────────────────────────────────────────────────────────
function _makeBolt() {
const shape = new THREE.Shape();
shape.moveTo( 0.075, 0.28);
shape.lineTo(-0.030, 0.04);
shape.lineTo( 0.040, 0.04);
shape.lineTo(-0.075, -0.28);
shape.lineTo( 0.030, -0.04);
shape.lineTo(-0.040, -0.04);
shape.closePath();
const mat = new THREE.MeshBasicMaterial({
color: 0xffee00,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.95,
});
return new THREE.Mesh(new THREE.ShapeGeometry(shape), mat);
}
function _updateOrbColor(fill, pulse) {
let r, g, b;
if (fill < 0.5) {
const k = fill * 2; // 0→1
r = 1.0 - k * 0.30; // 1.00 → 0.70
g = k * 0.70; // 0.00 → 0.70
b = k * 0.20; // 0.00 → 0.20
} else {
const k = (fill - 0.5) * 2; // 0→1
r = 0.70 - k * 0.70; // 0.70 → 0.00
g = 0.70 + k * 0.30; // 0.70 → 1.00
b = 0.20 + k * 0.80; // 0.20 → 1.00
}
// Pulse brightens toward white
const pr = r + pulse * (1 - r);
const pg = g + pulse * (1 - g);
const pb = b + pulse * (1 - b);
_orbMat.color.setRGB(pr, pg, pb);
_orbMat.emissive.setRGB(pr * 0.8, pg * 0.8, pb * 0.8);
_orbMat.emissiveIntensity = 1.0 + fill * 0.8 + pulse * 2.5;
_meterLight.color.setRGB(pr, pg, pb);
}
function _createLabelEl() {
const el = document.createElement('div');
el.style.cssText = [
'position:fixed',
'pointer-events:none',
'color:#00ffee',
'font-size:11px',
'font-family:monospace',
'font-weight:bold',
'text-align:center',
'text-shadow:0 0 6px #00ffcc,0 0 14px #00aaff',
'display:none',
'z-index:50',
'transform:translateX(-50%)',
'white-space:nowrap',
].join(';');
document.body.appendChild(el);
return el;
}
function _updateLabelPosition(camera, renderer) {
const canvas = renderer.domElement;
const rect = canvas.getBoundingClientRect();
// Project a point slightly above the orb center
const worldPos = METER_WORLD_POS.clone();
worldPos.y += 0.72;
worldPos.project(camera);
if (worldPos.z > 1) { // behind camera
_labelEl.style.display = 'none';
return;
}
_labelEl.style.display = 'block';
const x = rect.left + ( worldPos.x * 0.5 + 0.5) * rect.width;
const y = rect.top + (-worldPos.y * 0.5 + 0.5) * rect.height;
_labelEl.style.left = `${x}px`;
_labelEl.style.top = `${y}px`;
}

View File

@@ -16,6 +16,7 @@ import { setSpeechBubble, setMood } from './agents.js';
import { appendSystemMessage, setSessionSendHandler, setInputBarSessionMode } from './ui.js';
import { getOrRefreshToken } from './nostr-identity.js';
import { sentiment } from './edge-worker-client.js';
import { setMeterBalance, triggerMeterPulse, setMeterVisible } from './power-meter.js';
const API = '/api';
const LS_KEY = 'timmy_session_v1';
@@ -33,6 +34,7 @@ let _pollTimer = null;
let _inFlight = false;
let _selectedSats = 500; // deposit amount selection
let _topupSats = 500; // topup amount selection
let _sessionMax = 500; // max sats for this session (initial deposit)
// ── Public API ────────────────────────────────────────────────────────────────
@@ -105,6 +107,11 @@ export function isSessionActive() {
return _sessionState === 'active' || _sessionState === 'paused';
}
/** Public entry-point used by the 3D power meter click handler. */
export function openSessionPanel() {
_openPanel();
}
// Called by ui.js when user submits the input bar while session is active
export async function sessionSendHandler(text) {
if (!_sessionId || !_macaroon || _inFlight) return;
@@ -156,6 +163,7 @@ export async function sessionSendHandler(text) {
_sessionState = _balanceSats < MIN_BALANCE ? 'paused' : 'active';
_saveToStorage();
_applySessionUI();
triggerMeterPulse('drain');
const reply = data.result || data.reason || '…';
setSpeechBubble(reply);
@@ -287,9 +295,11 @@ function _startDepositPolling() {
if (data.state === 'active') {
_macaroon = data.macaroon;
_balanceSats = data.balanceSats;
_sessionMax = _balanceSats; // initial deposit = full bar
_sessionState = 'active';
_saveToStorage();
_applySessionUI();
triggerMeterPulse('fill');
_closePanel(); // panel auto-closes; user types in input bar
appendSystemMessage(`Session active — ${_balanceSats} sats`);
return;
@@ -404,8 +414,10 @@ function _startTopupPolling() {
_balanceSats = data.balanceSats;
_macaroon = data.macaroon || _macaroon;
_sessionState = data.state === 'active' ? 'active' : _sessionState;
_sessionMax = Math.max(_sessionMax, _balanceSats);
_saveToStorage();
_applySessionUI();
triggerMeterPulse('fill');
_setStep('active');
_updateActiveStep();
_setStatus('active', `⚡ Topped up! ${_balanceSats} sats`, '#22aa66');
@@ -512,6 +524,10 @@ function _applySessionUI() {
// Low balance notice above input bar
const $notice = document.getElementById('low-balance-notice');
if ($notice) $notice.style.display = lowBal ? '' : 'none';
// 3D power meter visibility
setMeterVisible(anyActive);
if (anyActive) setMeterBalance(_balanceSats, _sessionMax);
}
function _updateActiveStep() {
@@ -530,7 +546,9 @@ function _clearSession() {
_macaroon = null;
_balanceSats = 0;
_sessionState = null;
_sessionMax = 500;
localStorage.removeItem(LS_KEY);
setMeterVisible(false);
setInputBarSessionMode(false);
setSessionSendHandler(null);
const $hud = document.getElementById('session-hud');

View File

@@ -6,6 +6,7 @@ import { sentiment } from './edge-worker-client.js';
import { setLabelState } from './hud-labels.js';
import { createJobIndicator, dissolveJobIndicator } from './effects.js';
import { getPubkey } from './nostr-identity.js';
import { setMeterBalance, triggerMeterPulse } from './power-meter.js';
function resolveWsUrl() {
const explicit = import.meta.env.VITE_WS_URL;
@@ -190,6 +191,15 @@ function handleMessage(msg) {
break;
}
case 'session_balance_update': {
// Real-time balance push from server: animate fill level and pulse
if (typeof msg.balanceSats === 'number') {
setMeterBalance(msg.balanceSats, msg.maxSats);
triggerMeterPulse(msg.delta > 0 ? 'fill' : 'drain');
}
break;
}
case 'agent_count':
case 'visitor_count':
break;