Add persistent destructible world structures and building kits

This commit is contained in:
dingo
2026-09-09 22:46:06 -04:00
parent c2bef2a45f
commit e80064976a
36 changed files with 932 additions and 43 deletions
+11 -6
View File
@@ -1,5 +1,6 @@
import './style.css';
import { showTravel } from './travel';
import { buildingPanel } from './building-panel';
import { craftingPanel } from './crafting-panel';
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';
@@ -51,6 +52,7 @@ const avoidUntil = new Map<string, number>();
let requestedClose = false;
let input: InputActions;
let powers:ReturnType<typeof createPowerPanel>;
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}` : '';
@@ -69,14 +71,14 @@ function send(op: string, target = '', x = 0, z = 0, slot = '') {
}
function selection(entity?: Entity) {
view.selected = entity; visible('target', !!entity);
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player'].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'}`;} }
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;
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) || (avoidUntil.get(target.id) ?? 0) > now) {
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];
}
@@ -201,7 +203,7 @@ async function boot() {
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'].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==='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'].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();
@@ -228,7 +230,7 @@ async function boot() {
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 : -0.5) : config.gatherRange - 0.5 : 0.8;
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; }
@@ -262,7 +264,7 @@ async function boot() {
}, 50);
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
config = loadedConfig;
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());$('recipes').after(buildingPanel(()=>snapshot?.self,(id,rotation,range)=>{placement={id,rotation,range};input.clear();walkTo=undefined;pendingAction=undefined;send('move');$('inventory-toggle').click();notice('Click clear ground to build. Esc cancels.');},worldPrefix));
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton);
travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});};
$<HTMLInputElement>('zoom').value = String(view.distance);
@@ -307,6 +309,7 @@ async function boot() {
$('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'&&placement){placement=undefined;notice('Placement canceled.');}});
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); });
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } });
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
@@ -318,7 +321,9 @@ async function boot() {
view.canvas.addEventListener('pointerdown', event => {
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
const hit = view.pick(event.clientX, event.clientY);
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
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(hit.entity.kind==='portal'){$('travel').click();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; }
});
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 });