413 lines
35 KiB
TypeScript
413 lines
35 KiB
TypeScript
import './style.css';
|
|
import { createAppearanceEditor } from './appearance-editor';
|
|
import {createItemActions} from './item-actions';
|
|
import { showTravel } from './travel';
|
|
import { createHousingPanel } from './housing-panel';
|
|
import { buildingPanel } from './building-panel';
|
|
import { createPlayerDrawer } from './player-drawer';
|
|
import { createPowerPanel, revivalPanel } from './power-panel';
|
|
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
|
|
import { WorldView } from './world-view';
|
|
import type { BuildingContent, Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
|
import { experienceText, statPointsText, updateExperienceMeter } from './progression';
|
|
import { InputActions, isEditing, type InputAction } from './input-actions';
|
|
import { hasOpenMenu, registerMenu } from './menu-focus';
|
|
import { carryStatus } from './character-stats';
|
|
|
|
type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; playerSpeed: number; gatherRange: number; attackRange: number };
|
|
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
|
|
const visible = (id: string, show: boolean) => { $(id).hidden = !show; };
|
|
const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase());
|
|
const time = (seconds: number) => seconds >= 86400 ? `${Math.floor(seconds / 86400)}d ${Math.floor(seconds % 86400 / 3600)}h` : seconds >= 3600 ? `${Math.floor(seconds / 3600)}h ${Math.floor(seconds % 3600 / 60)}m` : `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`;
|
|
let config: Config;
|
|
let snapshot: Snapshot | undefined;
|
|
let ws: WebSocket | undefined;
|
|
let sequence = 0;
|
|
let lastNotice = '';
|
|
let noticeTimer: ReturnType<typeof setTimeout>;
|
|
let inputElapsed = 0;
|
|
let walkTo: { x: number; z: number } | undefined;
|
|
let pendingAction: { op: string; target: string } | undefined;
|
|
let actionElapsed = 0;
|
|
let riskyArmed = "", gatherSent = 0;
|
|
// A gather target can stay legitimately, persistently unreachable for a long time (a
|
|
// depleted resource waits out a real respawn timer measured in minutes, not a stray
|
|
// frame) -- retrying it forever would starve everything else. But a *working* attack is
|
|
// mostly cooldown rejections between the hits that land, so "stuck" can't just mean
|
|
// "hasn't succeeded since the click": it has to mean no progress at all for a while.
|
|
// Track a per-target progress signal (target HP for attack, held-item count for
|
|
// gather/loot) and only give up once that's stopped moving for a wall-clock budget --
|
|
// not a frame/attempt count, since a throttled or backgrounded tab can go seconds
|
|
// between rendered frames, and counting attempts instead of real elapsed time let a
|
|
// "few tries" balloon into tens of real seconds.
|
|
let lastProgress: number | undefined;
|
|
let lastProgressAt = 0;
|
|
function progressSignature(): number | undefined {
|
|
if (!pendingAction || !snapshot) return undefined;
|
|
if (pendingAction.op === 'attack') {
|
|
if (pendingAction.target === snapshot.self.entity.id) return snapshot.self.entity.hp;
|
|
if (pendingAction.target === 'boss') return snapshot.world.bossHp;
|
|
return snapshot.entities.find(e => e.id === pendingAction!.target)?.hp;
|
|
}
|
|
return Object.values(snapshot.self.inventory).reduce((a: number, b: number) => a + b, 0) + (snapshot.self.items?.length ?? 0);
|
|
}
|
|
const avoidUntil = new Map<string, number>();
|
|
let requestedClose = false;
|
|
let input: InputActions;
|
|
let powers:ReturnType<typeof createPowerPanel>;
|
|
let housing:ReturnType<typeof createHousingPanel>;
|
|
let drawer:ReturnType<typeof createPlayerDrawer>;
|
|
let items:ReturnType<typeof createItemActions>;
|
|
let pendingInteraction:{id:string;key?:string;progressAt:number;position:Entity['position']}|undefined;
|
|
let placement:{id:string;rotation:string;range:number}|undefined;
|
|
let view: WorldView;
|
|
const selectedWorld = new URLSearchParams(location.search).get('world');
|
|
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
|
|
|
|
async function api<T>(path: string, body?: unknown): Promise<T> {
|
|
const response = await fetch(path.startsWith('/api/') ? worldPrefix + path : path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
const result = await response.json();
|
|
if (!response.ok) throw new Error(result.error ?? `Request failed (${response.status})`);
|
|
return result as T;
|
|
}
|
|
function notice(message: string) { $('notice').textContent = message; visible('notice', true); clearTimeout(noticeTimer); noticeTimer = setTimeout(() => visible('notice', false), 3500); }
|
|
function send(op: string, target = '', x = 0, z = 0, slot = '') {
|
|
if (ws?.readyState !== WebSocket.OPEN || !snapshot || !['alive','eligible'].includes(snapshot.self.entity.state)) return;
|
|
const intent: Intent = { op, target, x, z, slot, seq: ++sequence };
|
|
ws.send(JSON.stringify(intent));
|
|
}
|
|
function selection(entity?: Entity) {
|
|
view.selected = entity; visible('target', !!entity);
|
|
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player','structure'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} }
|
|
}
|
|
function action(op: string) {
|
|
if (!snapshot) return;
|
|
pendingInteraction=undefined;
|
|
const now = Date.now();
|
|
const kinds = op === 'attack' ? (snapshot.self.attack?.effect==='heal'?['player']:['boss', 'sentinel','mob']) : ['tree', 'ore', 'herb', 'corpse'];
|
|
let target = view.selected;
|
|
if (!target || (!kinds.includes(target.kind)&&!(op==='attack'&&target.kind==='structure'&&snapshot.self.attack?.effect!=='heal')) || (avoidUntil.get(target.id) ?? 0) > now) {
|
|
const p = snapshot.self.entity.position;
|
|
target = [...snapshot.entities,...(snapshot.self.attack?.effect==='heal'?[snapshot.self.entity]:[])].filter(e => kinds.includes(e.kind) && (avoidUntil.get(e.id) ?? 0) <= now).sort((a, b) => Math.hypot(a.position.x - p.x, a.position.z - p.z) - Math.hypot(b.position.x - p.x, b.position.z - p.z))[0];
|
|
}
|
|
if (!target) { notice('No target nearby.'); return; }
|
|
selection(target);
|
|
const risk=snapshot.gatherRisks?.[target.resourceId??target.kind];
|
|
if(op==='gather'&&risk){
|
|
walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;
|
|
if(!risk.allowed){notice('This resource is more than 20 levels above your effective gathering level.');return;}
|
|
if(risk.failure>0&&riskyArmed!==target.id){riskyArmed=target.id;notice(`Dangerous attempt: ${risk.failure.toFixed(0)}% failure. Inspect the target risks, then press Gather again to attempt.`);return;}
|
|
}
|
|
riskyArmed='';gatherSent=0;
|
|
pendingAction = { op: target.kind === 'corpse' ? 'loot' : op, target: target.id };
|
|
walkTo = target.position;
|
|
lastProgress = undefined; lastProgressAt = Date.now();
|
|
}
|
|
function entranceDistance(e:Entity){const p=snapshot!.self.entity.position;return Math.hypot(e.position.x-p.x,e.position.y-p.y,e.position.z-p.z)}
|
|
function useEscapeStone(){
|
|
if(!snapshot||config.kind==='hub'||!['gathering','cataclysm'].includes(snapshot.world.phase)||!(snapshot.self.inventory.escape_stone>0)){notice('Use a world portal here.');return}
|
|
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;items.cancel();send('move');
|
|
void showTravel({worldId:config.worldId,route:'escape',beforeTravel:()=>{requestedClose=true},afterTravel:departed=>{requestedClose=departed}});
|
|
}
|
|
function openEntrance(e:Entity,key?:string){
|
|
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move');
|
|
if(e.kind==='portal')void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':'portal',beforeTravel:()=>{requestedClose=true},afterTravel:departed=>{requestedClose=departed}});
|
|
else if(e.kind==='house-door'){
|
|
if(key){const item=snapshot?.self.items.find(i=>i.id===key);if(item?.houseId)housing.enter(item.houseId,key);else notice('That key is no longer in your inventory.')}
|
|
else housing.openEntrance();
|
|
}
|
|
}
|
|
function approachEntrance(e:Entity,key?:string){
|
|
if(!snapshot||snapshot.self.houseId)return;
|
|
items.cancel();input.clear();pendingAction=undefined;send('move');visible('inventory',false);visible('settings',false);selection(e);
|
|
if(entranceDistance(e)<=config.gatherRange-.4){openEntrance(e,key);return}
|
|
pendingInteraction={id:e.id,key,progressAt:Date.now(),position:{...snapshot.self.entity.position}};walkTo=e.position;notice('Approaching '+e.name+'. Movement or Esc cancels.');
|
|
}
|
|
function connect() {
|
|
pendingInteraction=undefined;
|
|
requestedClose = false; sequence = 0; snapshot = undefined;
|
|
powers.hotbar.hidden = true;
|
|
visible('game-controls',false); visible('movement',false); visible('inventory',false);
|
|
const ending = $<HTMLDialogElement>('ending'); ending.close();
|
|
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}${worldPrefix}/ws`);
|
|
ws.onopen = () => { $('connection-status').textContent = 'Synchronizing world'; };
|
|
ws.onmessage = event => {
|
|
const value = JSON.parse(event.data) as Snapshot;
|
|
if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; }
|
|
if(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;pendingInteraction=undefined;walkTo=undefined;gatherSent=0;}
|
|
if(gatherSent && value.self.ack>=gatherSent)gatherSent=0;
|
|
const previousState = snapshot?.self.entity.state;
|
|
snapshot = value; view.update(value); updateHUD(value);
|
|
$('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline');
|
|
const state = value.self.entity.state;
|
|
const ending = $<HTMLDialogElement>('ending');
|
|
if (previousState === 'dead' && state !== 'dead') ending.close();
|
|
if (state === 'dead') {
|
|
if (!ending.open) showEnding('A life, remembered.', 'Your belongings remain on your corpse. Revival requires another player and your consent; replacement makes this death final.', false);
|
|
} else if (value.self.remainingSeconds <= 0 && !ending.open) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
|
};
|
|
ws.onclose = async () => {
|
|
pendingInteraction=undefined;
|
|
powers.hotbar.hidden = true;
|
|
visible('game-controls',false); visible('movement',false); visible('inventory',false);
|
|
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined;
|
|
if (requestedClose || $<HTMLDialogElement>('ending').open) return;
|
|
let detail = 'The connection ended. Your character state is held by the server.';
|
|
try { const me = await api<{ character?: Character }>('/api/me'); if (me.character?.entity.state === 'dead') { showEnding('A life, remembered.', 'This character is permanently dead.', false); return; } if (me.character?.remainingSeconds === 0) detail = 'Daily play time is complete. Return after 00:00 UTC.'; } catch { detail = 'Your session ended. Sign in again to continue.'; }
|
|
showEnding('Connection interrupted.', detail, false); visible('reconnect', true);
|
|
};
|
|
}
|
|
function showEnding(title: string, detail: string, survivor: boolean) {
|
|
input.clear(); walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined;
|
|
if(powers)powers.hotbar.hidden=true;
|
|
visible('game-controls',false);visible('movement',false);visible('inventory',false);
|
|
$('ending-title').textContent = title; $('ending-detail').textContent = detail;
|
|
$('ending-eyebrow').textContent = survivor ? 'WORLD SURVIVED' : 'JOURNEY PAUSED';
|
|
if (snapshot?.self.entity.state === 'dead') $('ending-eyebrow').textContent = 'JOURNEY ENDED';
|
|
const destinations = $('destinations'); destinations.replaceChildren();
|
|
if (survivor) for (const destination of config.worlds.filter(w => w.id !== config.worldId)) {
|
|
const link = document.createElement('a'); link.href = destination.url; link.textContent = `Travel to ${destination.id}`; link.rel = 'noopener'; destinations.append(link);
|
|
}
|
|
if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); }
|
|
visible('reconnect', false);
|
|
visible('new-character', snapshot?.self.entity.state === 'dead' && ['gathering','cataclysm'].includes(snapshot.world.phase));
|
|
$('ending').querySelector('.revival-panel')?.remove();if(snapshot?.self.entity.state==='dead')$('ending').append(revivalPanel(worldPrefix));
|
|
$<HTMLDialogElement>('ending').show();
|
|
}
|
|
function inventory(c: Character) {
|
|
drawer.update(c);
|
|
}
|
|
function minimap(s: Snapshot) {
|
|
const canvas = $<HTMLCanvasElement>('minimap'), ctx = canvas.getContext('2d')!;
|
|
const p = s.self.entity.position, radius = s.world.radius;
|
|
ctx.clearRect(0, 0, 140, 140); ctx.save(); ctx.beginPath(); ctx.arc(70, 70, 66, 0, Math.PI * 2); ctx.clip();
|
|
ctx.fillStyle = '#263c30'; ctx.fillRect(0, 0, 140, 140);
|
|
ctx.strokeStyle = '#77916a50'; ctx.lineWidth = 1;
|
|
for (let i = 6; i < 140; i += 16) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 140); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(140, i); ctx.stroke(); }
|
|
ctx.strokeStyle = s.world.phase === 'cataclysm' ? '#e18a8a' : '#aebc92'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(70, 70, 62 * s.world.safeRadius / radius, 0, Math.PI * 2); ctx.stroke();
|
|
if (s.world.phase === 'cataclysm') { ctx.fillStyle = '#ed7963'; ctx.fillRect(67, 67, 6, 6); }
|
|
ctx.fillStyle = '#ecedbd'; ctx.beginPath(); ctx.arc(70 + p.x / radius * 62, 70 + p.z / radius * 62, 3, 0, Math.PI * 2); ctx.fill();
|
|
ctx.fillStyle = '#d4debf'; ctx.font = '9px sans-serif'; ctx.fillText('N', 67, 15); ctx.restore();
|
|
}
|
|
function updateHUD(s: Snapshot) {
|
|
const c = s.self, w = s.world;
|
|
housing?.update(c);
|
|
powers?.update(c);
|
|
items?.update();
|
|
const playable=['alive','eligible'].includes(c.entity.state)&&c.remainingSeconds>0;
|
|
powers.hotbar.hidden=!playable;
|
|
visible('travel',playable&&!c.houseId&&config.kind!=='hub'&&['gathering','cataclysm'].includes(w.phase)&&c.inventory.escape_stone>0);
|
|
visible('game-controls', playable); visible('movement', playable && !hasOpenMenu());
|
|
$('character-name').textContent = c.entity.name;
|
|
$('character-level').textContent = `Level ${c.level || 1}`;
|
|
$('character-experience').textContent = experienceText(c);
|
|
updateExperienceMeter($<HTMLProgressElement>('experience-meter'), c);
|
|
$('stat-point-bank').textContent = statPointsText(c);
|
|
const carry = carryStatus(c);
|
|
$('carry-weight').textContent = carry.weight;
|
|
// Keep the explanation visible even when the bag is closed. The server owns
|
|
// the movement factor; do not reproduce encumbrance tuning in the browser.
|
|
if ($('carry-movement').textContent !== carry.movement) $('carry-movement').textContent = carry.movement;
|
|
$('carry-manage').classList.toggle('encumbered', carry.impaired);
|
|
$('carry-manage').title = `${carry.help} Open bag to manage carried items.`.trim();
|
|
const titleCount = c.titles?.length ?? 0;
|
|
$('title-count').textContent = `${titleCount} title${titleCount === 1 ? '' : 's'}`;
|
|
$('health-number').textContent = `${Math.max(0, Math.ceil(c.entity.hp))} / ${Math.ceil(c.entity.maxHp)}`;
|
|
$('health-fill').style.width = `${Math.max(0, c.entity.hp / c.entity.maxHp * 100)}%`;
|
|
$('play-time').textContent = `${time(c.remainingSeconds)} left today`;
|
|
$('kills').textContent = `${c.kills} kills`;
|
|
$('bandage-count').textContent = String(c.inventory.bandage ?? 0);
|
|
$<HTMLButtonElement>('heal').disabled = !c.inventory.bandage || c.entity.hp >= c.entity.maxHp;
|
|
$<HTMLButtonElement>('keystone').disabled = !c.hasKeystone;
|
|
$('world-name').textContent = `${w.id} / ${w.online} online`;
|
|
$('phase-label').textContent = w.phase === 'gathering' ? 'THE GATHERING' : w.phase === 'cataclysm' ? 'THE UNRAVELING' : w.phase === 'won' ? 'WORLD SURVIVED' : 'WORLD LOST';
|
|
$('season-clock').textContent = time(w.phase === 'gathering' ? w.bossInSeconds : w.collapseInSeconds);
|
|
$('season-detail').textContent = w.phase === 'gathering' ? 'Until the Harbinger' : `${Math.round(w.safeRadius)}m of world remaining`;
|
|
$('season-progress').style.width = `${w.safeRadius / w.radius * 100}%`;
|
|
visible('boss-bar', w.phase === 'cataclysm' || w.phase === 'won'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = w.phase==='won'?'Portal at 0, 0':`${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`;
|
|
$('coordinates').textContent = `${Math.round(c.entity.position.x)}, ${Math.round(c.entity.position.z)}`;
|
|
$('chunk-count').textContent = `${view.chunks.size} chunks`;
|
|
if (!$('inventory').hidden) inventory(c);
|
|
if(w.kind==='hub'){ $('phase-label').textContent='THE HUB';$('season-clock').textContent='Permanent haven';$('season-detail').textContent='Crafting allowed · No experience gained'; }
|
|
if(w.phase==='won'){ $('season-clock').textContent='Portal open';$('season-detail').textContent='Find the victory portal at 0, 0'; }
|
|
visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger');
|
|
visible('dev-boss',config.development&&w.kind!=='hub');
|
|
$<HTMLButtonElement>('attack').disabled=w.kind==='hub'||w.phase==='won';$<HTMLButtonElement>('gather').disabled=w.kind==='hub'||w.phase==='won';
|
|
if(c.houseId){$('phase-label').textContent=s.house?.name??'HOUSE';$('season-detail').textContent='WASD / stick to walk · Jump onto furniture · I for house controls';$('coordinates').textContent=`${c.housePosition?.x.toFixed(1)??0}, ${c.housePosition?.z.toFixed(1)??0}`;}
|
|
selection(view.selected); minimap(s);
|
|
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
|
|
}
|
|
async function boot() {
|
|
$('carry-manage').onclick = () => {
|
|
if ($('inventory').hidden) $('inventory-toggle').click();
|
|
const bag = $('inventory').querySelector<HTMLButtonElement>('[data-view="bag"]');
|
|
bag?.click();
|
|
bag?.focus();
|
|
};
|
|
$<HTMLAnchorElement>('login').href = `/auth/login?return=${encodeURIComponent(location.pathname + location.search)}`;
|
|
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
|
|
view = new WorldView($<HTMLCanvasElement>('world'));
|
|
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
|
if(snapshot?.self.houseId){if(key==='inventory'||key==='gather'){housing.open();return}if(key==='jump'){send('jump');return}return}
|
|
if((key==='attack'||key==='gather')&&items?.targeting){const target=view.selected?.id;if(target)items.choose(target);else notice('Select a target first.');return}
|
|
if((key==='attack'||key==='gather')&&view.selected&&['portal','house-door'].includes(view.selected.kind)){approachEntrance(view.selected);return}
|
|
if(key==='attack'||key==='gather')action(key);
|
|
else if(key==='inventory')$('inventory-toggle').click();
|
|
else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1);
|
|
else if(key==='cancel-cast')send('cancel-cast');
|
|
else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse','structure','portal','house-door'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}}
|
|
else if(key==='heal'||key==='return'||key==='jump')send(key);
|
|
});
|
|
view.start();
|
|
// Send bounded intents on elapsed wall time, independently of GPU frame rate.
|
|
// A delayed timer performs one update; it never replays a backlog of inputs.
|
|
let lastInputAt = performance.now();
|
|
window.setInterval(() => {
|
|
const now = performance.now(), dt = (now - lastInputAt) / 1000;
|
|
lastInputAt = now;
|
|
inputElapsed += dt;
|
|
input.pollController();
|
|
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
|
|
if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){
|
|
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;view.moving=false;
|
|
if(inputElapsed>=0.05){send('move');inputElapsed=0;}return;
|
|
}
|
|
if(snapshot.self.houseId){let {x,z}=input.movement;if(x||z)walkTo=undefined;const p=snapshot.self.housePosition;if(walkTo&&p){const dx=walkTo.x-p.x,dz=walkTo.z-p.z,n=Math.hypot(dx,dz);if(n>.25){x=dx/n;z=dz/n}else walkTo=undefined}if(inputElapsed>=.05){send('move','',x,z);inputElapsed=0}return}
|
|
let {x,z} = input.movement;
|
|
if (x || z) { walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined; }
|
|
if(pendingInteraction){
|
|
const p=snapshot.self.entity.position,previous=pendingInteraction.position;
|
|
if(Math.hypot(p.x-previous.x,p.z-previous.z)>.1){pendingInteraction.progressAt=Date.now();pendingInteraction.position={...p}}
|
|
if(Date.now()-pendingInteraction.progressAt>5000){pendingInteraction=undefined;walkTo=undefined;notice('Approach stopped. Check your carry weight or choose a clear path.');}
|
|
}
|
|
if(pendingInteraction){
|
|
const e=snapshot.entities.find(e=>e.id===pendingInteraction!.id);
|
|
if(!e){pendingInteraction=undefined;walkTo=undefined;notice('Entrance is no longer available.');}
|
|
else if(entranceDistance(e)<=config.gatherRange-.4){const key=pendingInteraction.key;openEntrance(e,key);return}
|
|
else walkTo=e.position;
|
|
}
|
|
const actionTarget = pendingAction?.target === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === pendingAction?.target);
|
|
if (pendingAction?.op === 'attack') {
|
|
if (!actionTarget || actionTarget.hp <= 0) { walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined; }
|
|
else walkTo = actionTarget.position;
|
|
}
|
|
if (walkTo) {
|
|
const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz);
|
|
const target = actionTarget;
|
|
const range = pendingAction ? pendingAction.op === 'attack' ? (snapshot.self.attack?.range??config.attackRange) + (target?.id === 'boss' ? 3 : target?.kind==='structure'?Math.max(target.width??0,target.depth??0)/2-.5:-0.5) : config.gatherRange - 0.5 : 0.8;
|
|
const reach = pendingAction?.op === 'attack' && target ? Math.hypot(distance, target.position.y-p.y) : distance;
|
|
if (reach <= range) {
|
|
if (!pendingAction) { walkTo = undefined; }
|
|
// A single fire-and-forget attempt can land a hair outside the authoritative
|
|
// server position (which may lag a stale/throttled client render) and get
|
|
// rejected with no second chance, so retry at a conservative cadence (well
|
|
// under the intent rate limit) instead of giving up forever -- the server's
|
|
// own action cooldown makes repeat attempts harmless. But a target can also be
|
|
// legitimately, persistently rejected (a depleted resource waits out a real
|
|
// respawn timer), so give up on THIS target after a wall-clock budget and let
|
|
// the next action() pick a fresh one rather than retrying a lost cause forever.
|
|
else {
|
|
actionElapsed += dt;
|
|
if (actionElapsed >= 0.3) {
|
|
actionElapsed = 0;
|
|
const sig = progressSignature();
|
|
if (sig !== undefined && sig !== lastProgress) { lastProgress = sig; lastProgressAt = Date.now(); }
|
|
const attackWait = pendingAction.op === 'attack' && snapshot.self.attack ? snapshot.self.attack.cooldown + snapshot.self.attack.range / snapshot.self.attack.speed + 2 : 0;
|
|
if (Date.now() - lastProgressAt > Math.max(5000,attackWait*1000,((snapshot.gatherRisks?.[target?.resourceId??target?.kind??'']?.seconds??0)+2)*1000)) {
|
|
avoidUntil.set(pendingAction.target, Date.now() + 8000);
|
|
const retryOp = pendingAction.op === 'loot' ? 'gather' : pendingAction.op;
|
|
walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined;
|
|
if(retryOp!=='gather' && snapshot.self.attack?.effect!=='heal')action(retryOp);else notice('Action stopped. Select a target to try again.');
|
|
} else if(pendingAction.op!=='gather'||!gatherSent) { send(pendingAction.op, pendingAction.target);if(pendingAction.op==='gather')gatherSent=sequence; }
|
|
}
|
|
}
|
|
} else if (distance > .01) { x = dx / distance; z = dz / distance; actionElapsed = 0.3; }
|
|
}
|
|
view.moving = !!(x || z);
|
|
if (inputElapsed >= 0.05) { send('move', '', x, z); inputElapsed = 0; }
|
|
}, 50);
|
|
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
|
|
config = loadedConfig;
|
|
housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub',()=>{input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;placement=undefined;visible('inventory',false);selection()});$('hud').append(housing.toolbar);
|
|
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix,(id,slot)=>items.activate(id,slot));$('hud').append(powers.hotbar);$('settings').append(input.settings());
|
|
const aim=(bag:boolean)=>{input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;placement=undefined;send('move');visible('inventory',bag);visible('movement',!bag);if(bag)$('inventory').querySelector<HTMLButtonElement>('[data-view="bag"]')?.click();};
|
|
const startPlacement=(id:string,rotation:string,range:number)=>{items?.cancel();aim(false);placement={id,rotation,range};notice('Click clear ground to build. Esc cancels.');};
|
|
items=createItemActions({panel:$('inventory'),hud:$('hud'),character:()=>snapshot?.self,prefix:worldPrefix,send,notice,aim,selected:()=>view.selected?.id??'',assign:(id,slot)=>powers.assignItem(id,slot),travel:()=>useEscapeStone(),key:(id,destroy,target)=>{if(destroy)housing.destroyKey(id);else{const door=snapshot?.entities.find(e=>e.id===target&&e.kind==='house-door');if(door)approachEntrance(door,id);else notice('Select the housing entrance in a hub.')}},place:id=>{void api<BuildingContent>('/api/building').then(b=>{const d=b.definitions.find(d=>'kit_'+d.id===id);if(!d)throw new Error('This kit has no structure definition.');startPlacement(d.id,'0',b.range)}).catch(e=>notice(e.message))}});$('hud').append(items.bar);
|
|
drawer=createPlayerDrawer($('inventory'),powers,send,worldPrefix,housing.root,buildingPanel(()=>snapshot?.self,startPlacement,worldPrefix));
|
|
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Use escape stone';travelButton.title='Consume an escape stone to reach a hub';travelButton.hidden=true;$('inventory-toggle').before(travelButton);
|
|
travelButton.onclick=()=>useEscapeStone();
|
|
$<HTMLInputElement>('zoom').value = String(view.distance);
|
|
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
|
|
visible('dev-boss', config.development);
|
|
let me: { character: Character | null; active?: { worldId: string; state: string; name: string } } | undefined;
|
|
try { me = await api('/api/me'); } catch { if (config.development) { await api('/auth/dev', {}); me = await api('/api/me'); } }
|
|
$('connection-status').textContent = 'World online';
|
|
if (!me && !config.development) { visible('join-form', false); visible('login', true); }
|
|
else if (me?.character) {
|
|
$<HTMLDialogElement>('arrival').close();
|
|
if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false);
|
|
else connect();
|
|
} else {
|
|
if(me&&!me.active)$('passages').append(revivalPanel(worldPrefix));
|
|
if (me?.active) {
|
|
visible('join-form', false);
|
|
const link = document.createElement('a'); link.href = me.active.state==='transit'?'/':`/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = me.active.state==='transit'?'Resume travel from your account':`Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
|
|
}
|
|
if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';}
|
|
}
|
|
let characterEditor: ReturnType<typeof createAppearanceEditor> | undefined;
|
|
if (me && !me.character && !me.active && config.kind !== 'hub') {
|
|
characterEditor = createAppearanceEditor(['human'], undefined, [], true);
|
|
$('arrival').classList.add('arrival-creator');
|
|
$('arrival-status').textContent = 'Choose your name and appearance. This is who you will be in this life.';
|
|
$('join-form').insertBefore(characterEditor.node, $('join'));
|
|
}
|
|
$<HTMLFormElement>('join-form').onsubmit = async event => {
|
|
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
|
|
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '', appearance: characterEditor?.read() }); $<HTMLDialogElement>('arrival').close(); characterEditor?.dispose(); connect(); }
|
|
catch (e) { $('arrival-error').textContent = (e as Error).message; }
|
|
finally { button.disabled = false; }
|
|
};
|
|
for (const id of ['inventory', 'settings']) {
|
|
const menu=registerMenu($(id),()=>{visible(id,false);visible('movement',$('inventory').hidden&&$('settings').hidden&&!!snapshot)});
|
|
$(`${id}-toggle`).onclick=()=>{
|
|
if(!$(id).hidden){menu.close();return;}
|
|
if(id==='inventory'&&snapshot)inventory(snapshot.self);
|
|
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
|
|
};
|
|
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
|
|
}
|
|
$('jump').onclick = () => input.trigger('jump'); $('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
|
|
$('target-boss').onclick = () => { if(snapshot?.world.phase==='won'){walkTo={x:0,z:0};pendingAction=undefined;pendingInteraction=undefined;return;} selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
|
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
|
|
$('reconnect').onclick = () => location.reload();
|
|
$('new-character').onclick = () => { requestedClose = true; ws?.close(); location.reload(); };
|
|
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
|
|
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
|
|
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
|
|
window.addEventListener('keydown',e=>{if(e.code==='Escape'&&pendingInteraction){pendingInteraction=undefined;walkTo=undefined;input.clear();send('move');notice('Approach canceled.')}if(e.code==='Escape'&&placement){placement=undefined;notice('Placement canceled.');}});
|
|
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined;pendingInteraction=undefined; send('move'); });
|
|
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined;pendingInteraction=undefined; send('move'); } });
|
|
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
|
|
document.querySelectorAll<HTMLButtonElement>('[data-move]').forEach(button => {
|
|
const key = movements[button.dataset.move!],source=`pointer-${button.dataset.move}`;
|
|
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); input.press(source,key); };
|
|
button.onpointerup = button.onpointercancel = button.onlostpointercapture = () => input.release(source);
|
|
});
|
|
view.canvas.addEventListener('pointerdown', event => {
|
|
if (event.defaultPrevented || !snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open) return;
|
|
if (!items.targeting && input.mouse(event) || event.button !== 0) return;
|
|
const hit = view.pick(event.clientX, event.clientY);
|
|
if(items.targeting){if(hit.entity)items.choose(hit.entity.id);else notice('Select a player, mob, or item as the target.');return}
|
|
if(snapshot.self.houseId){if(hit.entity?.kind==='house-exit')void housing.leave();else if(hit.entity)housing.open(hit.entity.id);else if(hit.point)walkTo=hit.point;return}
|
|
if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;}
|
|
|
|
if (hit.entity) { if(['portal','house-door'].includes(hit.entity.kind)){approachEntrance(hit.entity);return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
|
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined;pendingInteraction=undefined; }
|
|
});
|
|
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
|
|
// Authentication and all input handlers must be ready before character creation.
|
|
$<HTMLButtonElement>('join').disabled = !me || !!me.character || !!me.active || config.kind === 'hub';
|
|
}
|
|
boot().catch(error => { console.error(error); $('arrival-error').textContent = `Unable to enter the world: ${error.message}`; $('connection-status').textContent = 'Unavailable'; });
|