Add physical hub portals and shared housing entrances

This commit is contained in:
dingo
2026-09-11 05:31:18 -04:00
parent 9b01ee38e3
commit ca571577ad
22 changed files with 366 additions and 37 deletions
+1
View File
@@ -32,6 +32,7 @@ export function statsBreakdown(c:Character) {
}
export function itemDetails(item:ItemInstance,c:Character) {
const card=node('article','','gear-card');
if(item.houseId)card.append(node('p','A bearer key: use it on the shared housing entrance in any hub. Every valid key holder has owner rights.','progression-note'));
if(item.coating)card.append(node('p',`${item.coating.name}: +${item.coating.damage} weapon damage · ${item.coating.expiresAt>Date.now()/1000?'expires '+new Date(item.coating.expiresAt*1000).toLocaleTimeString():'expired'}`,'progression-note'));
const requirements=[`Level ${item.requirements.level}`,...Object.entries(item.requirements.stats??{}).map(([s,v])=>`${statLabel(s)} ${numberText(v)}`),...(item.requirements.titles??[]).map(id=>`Title: ${c.titles?.find(t=>t.id===id)?.name??id}`)];
card.append(node('strong',item.name),node('p',item.description,'progression-note'),node('p',`${statLabel(item.slot)} · Weight ${numberText(item.weight)}`,'progression-note'),node('p',`Requires ${requirements.join(' / ')}`,'gear-requirements'),modifiersView(item.modifiers));
+6 -5
View File
@@ -14,14 +14,15 @@ type InventoryView=Pick<HouseInventory,'inventory'|'items'> & {stackNames?:Recor
function choices(v:InventoryView):[string,string][]{return [...v.items.map(i=>[i.id,i.name] as [string,string]),...Object.entries(v.inventory).filter(([,n])=>n>0).map(([id,n])=>[id,`${v.stackNames?.[id]??id} × ${n}`] as [string,string])];}
export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean,onEnter:()=>void){
const root=node('section'),open=button('Housing & keys',()=>{dialog.showModal();menu.opened();void refresh(true)});
const root=node('section'),open=button('Housing & keys',()=>show());
const dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close controls',()=>dialog.close());
const toolbar=node('div','','house-toolbar');toolbar.hidden=true;toolbar.append(button('House controls',()=>show()),button('Return to hub',()=>void leave()));
const retry=button('Retry pending action',()=>{if(pending)void action(pending,true)});retry.hidden=true;
status.setAttribute('role','status');root.append(open);dialog.append(title,close,status,retry,body);document.body.append(dialog);
let entranceContext=false;
let pending:HouseRequest|undefined,state:HouseState|undefined,busy=false,loading=false,signature='',lastHouse='',selected='',latest:Character|undefined;
const menu=registerMenu(dialog,()=>dialog.close());dialog.addEventListener('cancel',e=>{e.preventDefault();dialog.close()});
function show(id=''){selected=id;if(!dialog.open)dialog.showModal();menu.opened();void refresh(true)}
function show(id='',atEntrance=false){entranceContext=atEntrance;selected=id;if(!dialog.open)dialog.showModal();menu.opened();void refresh(true)}
async function leave(){if(busy)return;if(character()?.houseId||state?.room)await action({op:'leave'});dialog.close();signature=''}
async function action(r:Omit<HouseRequest,'requestId'>,retrying=false){
if(busy)return;if(pending&&!retrying){status.textContent='Resolve the pending action before making another change.';return}busy=true;dialog.classList.add('housing-busy');status.textContent='Saving…';
@@ -43,9 +44,9 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
for(const key of c.items.filter(i=>i.houseId)){const row=node('p',key.name+' ');row.append(button('Destroy key',()=>confirmItemAction('Destroy '+key.name+'?','This takes three seconds. The key remains lootable until destruction completes.',()=>void action({op:'destroy-key',item:key.id}))));keys.append(row)}
const progress=node('p');progress.dataset.keyProgress='';keys.append(progress,button('Cancel key destruction',()=>void action({op:'cancel-key'})));body.append(keys);
if(!h){
body.append(node('p',isHub()?'Create or enter a house after surviving your first world. A carried key grants owner rights.':'Return to a hub to enter housing. Keys can be destroyed here.'));
body.append(node('p',isHub()?'After surviving your first world, walk to the shared housing entrance in this hub to enter a house. A carried key grants owner rights; guests need an invitation.':'Return to a hub to enter housing. Keys can be destroyed here.'));
if(isHub()){const name=node('input');name.maxLength=80;name.placeholder='House name';body.append(label('New house name',name),button('Create house',()=>void action({op:'create',name:name.value})))}
for(const entry of s.houses){const row=node('section');row.append(node('h3',entry.name),node('p',`${entry.state} · ${entry.role||'no access'} · ${entry.keys} valid keys`));if(isHub()&&entry.state==='active'&&entry.role)row.append(button('Enter',()=>void action({op:'enter',houseId:entry.id})));if(isHub()&&entry.creator&&entry.recoveryWorld&&entry.state!=='purged')row.append(button('Recover creator key',()=>void action({op:'recover',houseId:entry.id})));body.append(row)}return;
for(const entry of s.houses){const row=node('section');row.append(node('h3',entry.name),node('p',`${entry.state} · ${entry.role||'no access'} · ${entry.keys} valid keys`));if(isHub()&&entranceContext&&entry.state==='active'&&entry.role)row.append(button('Enter through housing entrance',()=>void action({op:'enter',houseId:entry.id})));if(isHub()&&entry.creator&&entry.recoveryWorld&&entry.state!=='purged')row.append(button('Recover creator key',()=>void action({op:'recover',houseId:entry.id})));body.append(row)}return;
}
body.prepend(node('p','Private house room · click the floor to choose a position, or furniture to select it. No experience is earned here.'));
const layout=node('div','','house-layout');layout.setAttribute('aria-label','House floor plan');
@@ -79,5 +80,5 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
}
}
setInterval(()=>{if(dialog.open&&!busy)void refresh();const a=character()?.destroyKey;const p=dialog.querySelector<HTMLElement>('[data-key-progress]');if(p)p.textContent=a?`Key destruction in progress · ${Math.max(0,a.finishesAt-Date.now()/1000).toFixed(1)}s remaining (server confirmed on completion)`:'No key destruction in progress.'},1000);
return {root,toolbar,open:show,leave,destroyKey:(id:string)=>{show();void action({op:'destroy-key',item:id})},update(c:Character){latest=c;toolbar.hidden=!c.houseId;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId){onEnter();dialog.close()}if(dialog.open)void refresh(true)}}};
return {root,toolbar,open:show,openEntrance:()=>show('',true),enter:(houseId:string,key:string)=>{show('',true);void action({op:'enter',houseId,item:key})},leave,destroyKey:(id:string)=>{show();void action({op:'destroy-key',item:id})},update(c:Character){latest=c;toolbar.hidden=!c.houseId;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId){onEnter();dialog.close()}if(dialog.open)void refresh(true)}}};
}
+5 -4
View File
@@ -3,7 +3,7 @@ import {api, APIError} from './portal-shared';
import {node} from './character-stats';
import {registerMenu} from './menu-focus';
type Options={character:()=>Character|undefined;prefix:string;panel:HTMLElement;hud:HTMLElement;notice:(text:string)=>void;send:(op:string,target?:string)=>void;aim:(inventory:boolean)=>void;selected:()=>string;place:(id:string)=>void;travel:()=>void;key:(id:string,destroy:boolean)=>void;assign:(id:string,slot?:string)=>HTMLElement};
type Options={character:()=>Character|undefined;prefix:string;panel:HTMLElement;hud:HTMLElement;notice:(text:string)=>void;send:(op:string,target?:string)=>void;aim:(inventory:boolean)=>void;selected:()=>string;place:(id:string)=>void;travel:()=>void;key:(id:string,destroy:boolean,target?:string)=>void;assign:(id:string,slot?:string)=>HTMLElement};
let controller:ReturnType<typeof createItemActions>|undefined;
export function itemControls(id:string,slot=''){return controller?.controls(id,slot)??node('div')}
export function chooseItemTarget(id:string){return controller?.choose(id)??false}
@@ -42,12 +42,13 @@ export function createItemActions(o:Options){
}
function aim(id:string){if(pending){o.notice('Resolve the pending item action first.');return}targetItem=id;o.aim(o.character()?.consumables?.find(i=>i.id===id)?.useEffect?.kind==='weapon-coating');update()}
function choose(target:string){if(!targetItem)return false;const id=targetItem;
if(id==='revival_stone'){targetItem='';update();void api(o.prefix+'/api/revive',{corpse:target,power:'item'}).then(()=>o.notice('Player revived.')).catch(e=>o.notice(e.message))}
if(o.character()?.items.find(i=>i.id===id)?.houseId){if(target!=='housing-entrance'){o.notice('Use this key on the housing entrance in a hub.');return true}targetItem='';update();o.key(id,false,target)}
else if(id==='revival_stone'){targetItem='';update();void api(o.prefix+'/api/revive',{corpse:target,power:'item'}).then(()=>o.notice('Player revived.')).catch(e=>o.notice(e.message))}
else void submit('use',id,target);return true;
}
function activate(id:string,slot=''){
const c=o.character();if(!c)return;const item=c.items.find(i=>i.id===id),consumable=c.consumables?.find(i=>i.id===id);
if(item?.houseId){o.key(id,false);return}if(item){void submit('equip',id,'',slot||item.slot);return}
if(item?.houseId){aim(id);return}if(item){void submit('equip',id,'',slot||item.slot);return}
if(id==='escape_stone'){o.travel();return}if(id.startsWith('book_')){o.send('learn',id);return}if(id.startsWith('kit_')){o.place(id);return}
if(id==='bandage'||consumable&&consumable.useEffect?.kind!=='weapon-coating'){void submit('consume',id);return}aim(id);
}
@@ -57,7 +58,7 @@ export function createItemActions(o:Options){
if(item&&!item.houseId&&!item.furniture)button('Equip',()=>activate(id,slot),!item.equippable);
if(!item&&(id==='bandage'||consumable&&consumable.useEffect?.kind!=='weapon-coating'||id==='escape_stone'||id.startsWith('book_')))button(id.startsWith('book_')?'Learn':'Consume',()=>activate(id));
if(id.startsWith('kit_'))button('Place',()=>o.place(id));
button('Use',()=>item?.houseId?o.key(id,false):aim(id));
button('Use',()=>aim(id));
button(item?'Drop':'Drop one',()=>o.send('drop',id));
button('Destroy',()=>confirmItemAction(`Destroy ${name(id)}?`,item?.houseId?'This starts the three-second key destruction action. The key remains lootable until it completes.':'Permanently destroy this item. For a stack, this destroys one unit.',()=>item?.houseId?o.key(id,true):void submit('destroy',id)));
if(item&&!item.houseId&&!item.furniture)button('Break down',()=>confirmItemAction(`Break down ${name(id)}?`,'This permanently destroys the equipment. Recovery depends on its original recipe and your crafting level, rounded down; you may recover nothing. Recipe discovery chance is 0.01%.',()=>void submit('breakdown',id)));
+58 -21
View File
@@ -56,6 +56,7 @@ 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');
@@ -79,6 +80,7 @@ function selection(entity?: Entity) {
}
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;
@@ -90,7 +92,7 @@ function action(op: string) {
selection(target);
const risk=snapshot.gatherRisks?.[target.resourceId??target.kind];
if(op==='gather'&&risk){
walkTo=undefined;pendingAction=undefined;
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;}
}
@@ -99,7 +101,28 @@ function action(op: string) {
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);
@@ -109,7 +132,7 @@ function connect() {
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;walkTo=undefined;gatherSent=0;}
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);
@@ -122,6 +145,7 @@ function connect() {
} 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;
@@ -132,7 +156,7 @@ function connect() {
};
}
function showEnding(title: string, detail: string, survivor: boolean) {
input.clear(); walkTo = undefined; pendingAction = undefined;
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;
@@ -170,6 +194,7 @@ function updateHUD(s: Snapshot) {
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}`;
@@ -210,11 +235,12 @@ async function boot() {
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'].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','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();
@@ -228,15 +254,26 @@ async function boot() {
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;view.moving=false;
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; }
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; }
if (!actionTarget || actionTarget.hp <= 0) { walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined; }
else walkTo = actionTarget.position;
}
if (walkTo) {
@@ -264,7 +301,7 @@ async function boot() {
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;
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; }
}
@@ -276,14 +313,14 @@ async function boot() {
}, 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;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;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;placement=undefined;send('move');visible('inventory',bag);visible('movement',!bag);if(bag)$('inventory').querySelector<HTMLButtonElement>('[data-view="bag"]')?.click();};
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:()=>$('travel').click(),key:(id,destroy)=>destroy?housing.destroyKey(id):housing.open(),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);
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='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;}});};
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);
@@ -314,21 +351,21 @@ async function boot() {
$(`${id}-toggle`).onclick=()=>{
if(!$(id).hidden){menu.close();return;}
if(id==='inventory'&&snapshot)inventory(snapshot.self);
input.clear();walkTo=undefined;pendingAction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
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;return;} selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
$('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'&&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'); } });
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}`;
@@ -343,8 +380,8 @@ async function boot() {
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(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; }
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.
+1 -1
View File
@@ -32,7 +32,7 @@ export async function showTravel(source?: Departure) {
select.append(new Option(`${w.id} · ${w.kind === 'hub' ? 'Hub' : w.phase === 'cataclysm' ? 'Collapsing world' : 'Survival world'} · ${w.living}/${w.capacity}`, w.id));
}
if ([...select.options].some(o => o.value === previous)) select.value = previous!;
go.textContent = transfer ? 'Finish travel' : source?.route === 'escape' ? 'Use escape stone & travel' : 'Travel';
go.textContent = transfer ? 'Finish travel' : source?.route === 'escape' ? 'Use escape stone & travel' : 'Enter portal';
go.disabled = !select.options.length || (!source && !transfer);
status.textContent = select.options.length ? '' : 'No destination is available. Your saved character remains safe in transit if departure already completed.';
} catch (e) { status.textContent = (e as Error).message; }
+6
View File
@@ -101,6 +101,12 @@ export class WorldView {
this.batches.set('player', peers);
const portalMesh = new T.InstancedMesh(new T.TorusGeometry(2,.22,8,40).translate(0,2.5,0),new T.MeshBasicMaterial({color:'#86ffe0'}),8);
portalMesh.count=0;portalMesh.userData.kind='portal';this.scene.add(portalMesh);this.batches.set('portal',{parts:[portalMesh],entities:[]});
const doorway:Batch={parts:[],entities:[]};
for(const [width,height,depth,x,y,color] of [[.3,3.3,.45,-1.1,1.65,'#d4bc84'],[.3,3.3,.45,1.1,1.65,'#d4bc84'],[2.5,.35,.45,0,3.3,'#d4bc84'],[1.9,3,.12,0,1.5,'#548f81']] as const){
const mesh=new T.InstancedMesh(new T.BoxGeometry(width,height,depth).translate(x,y,0),new T.MeshStandardMaterial({color,roughness:.65}),8);
mesh.count=0;mesh.castShadow=true;mesh.userData.kind='house-door';this.scene.add(mesh);doorway.parts.push(mesh);
}
this.batches.set('house-door',doorway);
const structureMesh=new T.InstancedMesh(new T.BoxGeometry(1,1,1).translate(0,.5,0),new T.MeshStandardMaterial({color:'#8c6744',roughness:1}),512);structureMesh.count=0;structureMesh.castShadow=true;structureMesh.receiveShadow=true;structureMesh.userData.kind='structure';this.scene.add(structureMesh);this.batches.set('structure',{parts:[structureMesh],entities:[]});
const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048);
corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh);