From ca571577ade72b390414d86ec8b86f8bd20690cf Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 11 Sep 2026 05:31:18 -0400 Subject: [PATCH] Add physical hub portals and shared housing entrances --- client/src/character-stats.ts | 1 + client/src/housing-panel.ts | 11 +-- client/src/item-actions.ts | 9 ++- client/src/main.ts | 79 +++++++++++++----- client/src/travel.ts | 2 +- client/src/world-view.ts | 6 ++ docs/ARCHITECTURE.md | 6 ++ docs/ITEM-ACTIONS.md | 4 + docs/MILESTONE-5.md | 4 + docs/WORLD-ENTRANCES.md | 74 +++++++++++++++++ planning/Changes-Needed.md | 5 ++ server/content/balance.yaml | 1 + server/content/content.go | 6 ++ server/content/entrances.go | 18 +++++ server/internal/game/entrances_test.go | 85 ++++++++++++++++++++ server/internal/game/travel.go | 23 +++++- server/internal/game/world.go | 22 ++++- server/internal/store/house_presence_test.go | 1 + server/internal/store/house_recovery_test.go | 3 + server/internal/store/housing.go | 15 ++++ server/internal/store/housing_test.go | 11 ++- server/internal/store/travel_test.go | 17 +++- 22 files changed, 366 insertions(+), 37 deletions(-) create mode 100644 docs/WORLD-ENTRANCES.md create mode 100644 server/content/entrances.go create mode 100644 server/internal/game/entrances_test.go diff --git a/client/src/character-stats.ts b/client/src/character-stats.ts index b21b3af..4d998d2 100644 --- a/client/src/character-stats.ts +++ b/client/src/character-stats.ts @@ -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)); diff --git a/client/src/housing-panel.ts b/client/src/housing-panel.ts index 6d52855..b2df9b9 100644 --- a/client/src/housing-panel.ts +++ b/client/src/housing-panel.ts @@ -14,14 +14,15 @@ type InventoryView=Pick & {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,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('[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)}}}; } diff --git a/client/src/item-actions.ts b/client/src/item-actions.ts index 2772241..b15b096 100644 --- a/client/src/item-actions.ts +++ b/client/src/item-actions.ts @@ -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|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))); diff --git a/client/src/main.ts b/client/src/main.ts index d62df83..547954e 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -56,6 +56,7 @@ let powers:ReturnType; let housing:ReturnType; let drawer:ReturnType; let items:ReturnType; +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) || $('arrival').open || $('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 || $('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('/api/config'), api('/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('[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('[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('/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('/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(); $('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(`[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(); }; $('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high'); $('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 = { up:'north',down:'south',left:'west',right:'east' }; document.querySelectorAll('[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. diff --git a/client/src/travel.ts b/client/src/travel.ts index a21f53c..6f68379 100644 --- a/client/src/travel.ts +++ b/client/src/travel.ts @@ -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; } diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 155295b..821a1bf 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -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); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f3ff4fa..dd9cb83 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,6 +33,12 @@ The highest-risk requirements are: ## Implemented boundaries +Revised milestone 3 places a world portal and one shared housing entrance in each +hub. Source-owner travel and housing transactions validate physical proximity and +obstruction; key-targeted entry also validates the exact active carried key. Existing +transfer escrow and housing permission/recovery ledgers remain authoritative. See +[physical entrances](WORLD-ENTRANCES.md) for the manual handoff. + Planning update: the vision now includes corpse-based item/spell resurrection, key-owned hub housing, crafting rolls/provenance, and portal dungeon instances. Milestone 7 now implements corpse resurrection for new deaths. Milestone 8b adds diff --git a/docs/ITEM-ACTIONS.md b/docs/ITEM-ACTIONS.md index b4eb199..0df8e98 100644 --- a/docs/ITEM-ACTIONS.md +++ b/docs/ITEM-ACTIONS.md @@ -1,5 +1,9 @@ # Item actions — revised milestone 2 +The subsequent [physical-entrance milestone](WORLD-ENTRANCES.md) connects key Use +to a shared housing doorway and replaces general travel with portal/stone actions. +The descriptions below retain the original milestone 2 handoff context. + The bag and equipment views share item actions. Equip swaps an occupied slot while keeping both exact instances. Rings retain an explicit destination. Destroy and breakdown require confirmation. Dropping a stack drops one unit; destroying a stack diff --git a/docs/MILESTONE-5.md b/docs/MILESTONE-5.md index 2d04ae5..3bcc6d6 100644 --- a/docs/MILESTONE-5.md +++ b/docs/MILESTONE-5.md @@ -1,5 +1,9 @@ # Milestone 5: playable hub travel +The revised [physical-entrance milestone](WORLD-ENTRANCES.md) supersedes the general +Travel shortcut below: hub/victory travel uses physical portals; early survival-world +departure uses an explicit escape-stone action. The same durable transfer rules apply. + Implemented for manual testing. Milestone 4.5 presentation work remains pending; the user explicitly requested proceeding with 5. Terrain depth/traversal remains in [the environment backlog](../planning/ENVIRONMENT-BACKLOG.md). diff --git a/docs/WORLD-ENTRANCES.md b/docs/WORLD-ENTRANCES.md new file mode 100644 index 0000000..238fa6a --- /dev/null +++ b/docs/WORLD-ENTRANCES.md @@ -0,0 +1,74 @@ +# Physical entrances — revised milestone 3 + +Each hub now has a world portal at the center (0, 0) and a shared housing doorway +nearby (initially 12, 0). Both use server terrain height and appear only within the +player's chunk interest window. Housing uses one shared entrance per hub, as agreed; +it selects existing instanced houses rather than allocating a separate world door +for every house. Doorway location is saved in world tuning and defaults once for +older snapshots from `entrances` in `server/content/balance.yaml`. + +Click a portal or doorway to approach it. Once nearby, a portal opens available +destinations and the housing entrance opens your house directory. Movement, Esc, +opening a menu, disconnecting, or a blocked approach cancels the walk. This is a +direct walk intent, not pathfinding around obstacles. If blocked, walk around the +obstacle and select the entrance again. Keyboard/controller target cycling includes +both entrances; Gather or Attack interacts with a selected entrance. + +The housing directory shows entry buttons when opened from the physical doorway. +Ordinary Housing & keys controls retain creation, key destruction, recovery, and +inspection. Selecting Use on a house key starts targeting: select the shared +housing doorway to approach it and enter that key's house. Keys are not consumed. +The existing indoor exit and house controls still return to the same hub location. + +The old general Travel shortcut is replaced with Use escape stone when a survival +character owns one and the world has not ended. Bag and hotbar escape actions use +the same explicit stone flow. Hub travel starts at the hub portal; victory travel +starts at the portal opened by defeating the Harbinger. Canceling destination +selection consumes nothing. Departure still consumes a required stone once, and +an interrupted transfer still resumes through the account's durable travel record. + +## Server boundaries + +- Hub travel and victory travel require a living, connected, unsheltered character + with daily time remaining, outside housing, within gathering distance in three + dimensions, and with an unobstructed line to the authoritative portal position. +- House entry requires the shared hub entrance's proximity and clear line in + addition to existing survival, active-house, key/invitation, and ownership rules. + Explicit key use verifies that exact carried key is active and belongs to the + requested house, even if the player also has an invitation. An unrelated key + cannot satisfy the request. +- Checks run in the existing fenced housing/travel transactions. A rejected + request changes no ownership or transit state. Replays return the already-saved + result rather than re-entering or spending another item. +- Guest/co-owner permissions, valid key holders' owner rights, three-second key + destruction, creator recovery, and shared cross-hub housing contents are unchanged. +- No Harbinger evacuation, infinite-world, frontier, or chunk-depletion rules are + introduced here. Those remain revised milestones 4 and 5. + +## Manual playtest + +1. Enter a hub. Find the teal world portal at 0, 0 and the framed housing doorway + at 12, 0. Click each from a short distance and confirm the character walks over + before its controls open. Cancel an approach with movement or Esc. +2. At the world portal, choose another hub or a survival world. Check that the + same character, progression, gear, and remaining daily allowance arrive. +3. In a survival world, cancel an escape-stone destination selection and confirm + no stone is spent. Complete escape and confirm exactly one is spent. Defeat + the Harbinger and use its portal without an escape stone. +4. With a house key, select Bag → key → Use, then the housing doorway. Confirm + direct entry to that house and retention of the exact key. Try targeting a + different object; the key should remain untouched. +5. As an invited guest without a key, click the housing doorway and choose the + invited house. Verify existing furniture/storage permissions and the indoor exit. +6. Open ordinary Housing & keys away from the entrance: it should offer management + without a remote-entry shortcut. Verify another hub's doorway accesses the same + house and stored contents. Check last-key destruction and recovery as before. +7. Try clicking an entrance while immobilized by carry weight or behind an obstacle. + The approach should stop with guidance; dropping weight or walking around the + obstruction should allow another attempt. + +Required TypeScript/build and Go checks cover this change. Go regressions include +entrance visibility, vertical distance and obstruction, legacy snapshot migration, +rejected travel escrow, wrong-key rejection, repeated entry, cross-hub guests, and +death/recovery continuity. Routine Playwright authoring and full-suite runs remain +deferred for manual playtesting. diff --git a/planning/Changes-Needed.md b/planning/Changes-Needed.md index 9cedac8..4073273 100644 --- a/planning/Changes-Needed.md +++ b/planning/Changes-Needed.md @@ -218,3 +218,8 @@ Milestone 2 handoff: [Item actions](../docs/ITEM-ACTIONS.md). Shared actions, targeted consumables, gear swaps, hotbar item assignments, Ctrl/Alt/mouse bindings, encumbrance and equipment breakdown are implemented. Source-filtered stats and worlds-survived display remain separate follow-ups; physical portals/doors are next. + +Milestone 3 handoff: [Physical entrances](../docs/WORLD-ENTRANCES.md). Each hub +has a world portal and one shared housing entrance, confirmed for this milestone. +Key-targeted entry and invited-house selection use that doorway. Finalizing the +expanding-world/spawning/destruction lifecycle contract is the next milestone. diff --git a/server/content/balance.yaml b/server/content/balance.yaml index 44b2aeb..38ceb5c 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -72,6 +72,7 @@ snapshotHz: 5 chunkSize: 128 terrainResolution: 16 inventory: { stopWeightRatio: 2, slowdownExponent: 2, breakdownBase: 25, breakdownMax: 75, breakdownLevelScale: 25, recipeChance: 0.01, actionCooldown: 1 } +entrances: { housingX: 12, housingZ: 0 } worldRadius: 1024 maxPlayers: 100 spawnSeparation: 48 diff --git a/server/content/content.go b/server/content/content.go index b8e5c20..12886e6 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,7 @@ type Recipe struct { } type Balance struct { + Entrances *EntranceRules `yaml:"entrances"` Inventory *InventoryRules `yaml:"inventory"` XPCurve *XPCurve `yaml:"xpCurve"` Housing *HousingRules `yaml:"housing"` @@ -86,6 +87,11 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { + if b.Entrances != nil { + if e := b.Entrances.Validate(); e != nil { + return e + } + } if b.Inventory != nil { if e := b.Inventory.Validate(); e != nil { return e diff --git a/server/content/entrances.go b/server/content/entrances.go new file mode 100644 index 0000000..465ab30 --- /dev/null +++ b/server/content/entrances.go @@ -0,0 +1,18 @@ +package content + +import ( + "fmt" + "math" +) + +type EntranceRules struct { + HousingX float64 `yaml:"housingX"` + HousingZ float64 `yaml:"housingZ"` +} + +func (r EntranceRules) Validate() error { + if !finiteRange(r.HousingX, -64, 64) || !finiteRange(r.HousingZ, -64, 64) || math.Hypot(r.HousingX, r.HousingZ) < 6 { + return fmt.Errorf("housing entrance must be near, but separate from, the central world portal") + } + return nil +} diff --git a/server/internal/game/entrances_test.go b/server/internal/game/entrances_test.go new file mode 100644 index 0000000..a46205c --- /dev/null +++ b/server/internal/game/entrances_test.go @@ -0,0 +1,85 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "encoding/json" + "testing" +) + +func TestHubEntrancesScopeProximityAndMigration(t *testing.T) { + w, c := fixture(t) + entrances := func() map[string]p.Entity { + out := map[string]p.Entity{} + for _, e := range w.Snapshot(c.View.Entity.ID, nil).Entities { + if e.Kind == "portal" || e.Kind == "house-door" { + out[e.ID] = e + } + } + return out + } + if len(entrances()) != 0 { + t.Fatal("survival world exposed hub entrances before victory") + } + w.Kind = "hub" + w.Phase = "hub" + c.View.Entity.Position = w.PortalPosition() + if e := w.Departure(c, "hub"); e != nil { + t.Fatal(e) + } + visible := entrances() + if len(visible) != 2 || visible["housing-entrance"].Position != w.HousingEntrancePosition() || visible["hub-portal"].Position != w.PortalPosition() { + t.Fatal("hub entrance identity or location missing", visible) + } + c.View.Entity.Position.Y += w.Balance.GatherRange + 1 + if w.Departure(c, "hub") == nil { + t.Fatal("portal ignored vertical distance") + } + c.View.Entity.Position = w.HousingEntrancePosition() + if !w.NearEntrance(c, w.HousingEntrancePosition()) || w.Departure(c, "hub") == nil { + t.Fatal("different entrance bypassed portal proximity") + } + c.View.HouseID = stringPtr(ID()) + if len(entrances()) != 0 || w.Departure(c, "hub") == nil { + t.Fatal("indoor character accessed world entrances") + } + c.View.HouseID = nil + c.View.Entity.Position.X = 600 + if len(entrances()) != 0 { + t.Fatal("entrances escaped chunk interest bounds") + } + c.View.Entity.Position = w.PortalPosition() + w.Balance.Entrances = nil + raw, _ := json.Marshal(w) + var restored World + _ = json.Unmarshal(raw, &restored) + if e := restored.Restore(w.now); e != nil { + t.Fatal("old snapshot migration failed", e) + } + rc := restored.Characters[c.View.Entity.ID] + _ = restored.Connect(rc.View.Entity.ID) + if restored.Balance.Entrances == nil || restored.Departure(rc, "hub") != nil { + t.Fatal("restore lost portal eligibility") + } + if restored.Departure(nil, "hub") == nil { + t.Fatal("missing character traveled") + } +} + +func TestEntranceObstructionUsesServerGeometry(t *testing.T) { + w, c := fixture(t) + w.Kind = "hub" + w.Phase = "hub" + c.View.Entity.Position = w.PortalPosition() + c.View.Entity.Position.X -= 2 + position := w.PortalPosition() + position.X -= 1 + width, depth, height := .4, 3., 4. + w.Structures["obstacle"] = &Structure{Entity: p.Entity{ID: "obstacle", Kind: "structure", Position: position, Width: &width, Depth: &depth, Height: &height, HP: 100}} + if w.Departure(c, "hub") == nil { + t.Fatal("portal ignored an obstruction") + } + delete(w.Structures, "obstacle") + if e := w.Departure(c, "hub"); e != nil { + t.Fatal("clear portal remained blocked", e) + } +} diff --git a/server/internal/game/travel.go b/server/internal/game/travel.go index a21cc58..e7abeee 100644 --- a/server/internal/game/travel.go +++ b/server/internal/game/travel.go @@ -10,23 +10,42 @@ func (w *World) AllowsXP() bool { return w.Kind == "survival" && (w.Phase == "gathering" || w.Phase == "cataclysm") } func (w *World) PortalPosition() p.Vec3 { return w.terrain.Position(0, 0) } +func (w *World) HousingEntrancePosition() p.Vec3 { + return w.terrain.Position(w.Balance.Entrances.HousingX, w.Balance.Entrances.HousingZ) +} + +// Interactions use the same authoritative terrain height, distance and obstruction +// rules as other world actions. A client click never supplies the server position. +func (w *World) NearEntrance(c *Character, position p.Vec3) bool { + if c == nil || HouseID(c) != "" || length3(c.View.Entity.Position, position) > w.Balance.GatherRange { + return false + } + _, blocked := w.combatLine(body(c.View.Entity.Position), body(position), "") + return !blocked +} // Escape is an explicit one-item action. It grants no victory/survival credit. func (w *World) Departure(c *Character, route string) error { + if c == nil { + return errors.New("character cannot travel") + } if HouseID(c) != "" { return errors.New("leave the house before traveling") } - if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { + if !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { return errors.New("character cannot travel") } if w.IsHub() { if route != "hub" { return errors.New("choose hub travel") } + if !w.NearEntrance(c, w.PortalPosition()) { + return errors.New("stand next to the hub world portal") + } return nil } if w.Phase == "won" && c.View.Entity.State == "eligible" { - if route != "portal" || distance(c.View.Entity.Position, w.PortalPosition()) > w.Balance.GatherRange { + if route != "portal" || !w.NearEntrance(c, w.PortalPosition()) { return errors.New("stand next to the victory portal") } return nil diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 79866cc..e0b88c4 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -125,6 +125,17 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World { return w } func (w *World) Restore(now time.Time) error { + if w.Balance.Entrances == nil { + defaults, err := content.Load() + if err != nil { + return err + } + w.Balance.Entrances = defaults.Entrances + w.dirty = true + } + if err := w.Balance.Entrances.Validate(); err != nil { + return err + } if w.Balance.Inventory == nil { defaults, err := content.Load() if err != nil { @@ -957,8 +968,15 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { s.Entities = append(s.Entities, p.Entity{ID: area.ID, Kind: "area", Name: area.Attack.Name, Position: area.Position, State: area.Attack.Effect, Radius: &radius, HP: 1, MaxHP: 1}) } } - if w.Phase == "won" && visible(w.PortalPosition()) { - s.Entities = append(s.Entities, p.Entity{ID: "hub-portal", Kind: "portal", Name: "Portal to the hub", Position: w.PortalPosition(), HP: 1, MaxHP: 1, State: "open"}) + if HouseID(c) == "" && (w.Phase == "won" || w.IsHub()) && visible(w.PortalPosition()) { + name := "Portal to the hub" + if w.IsHub() { + name = "World portal" + } + s.Entities = append(s.Entities, p.Entity{ID: "hub-portal", Kind: "portal", Name: name, Position: w.PortalPosition(), HP: 1, MaxHP: 1, State: "open"}) + } + if HouseID(c) == "" && w.IsHub() && visible(w.HousingEntrancePosition()) { + s.Entities = append(s.Entities, p.Entity{ID: "housing-entrance", Kind: "house-door", Name: "Housing entrance", Position: w.HousingEntrancePosition(), HP: 1, MaxHP: 1, State: "open"}) } sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID }) return s diff --git a/server/internal/store/house_presence_test.go b/server/internal/store/house_presence_test.go index ee20fad..f06e7ba 100644 --- a/server/internal/store/house_presence_test.go +++ b/server/internal/store/house_presence_test.go @@ -31,6 +31,7 @@ func TestHouseVisitorsAcrossHubOwners(t *testing.T) { _ = w.Connect(c.View.Entity.ID) w.Kind = "hub" w.Phase = "hub" + c.View.Entity.Position = w.HousingEntrancePosition() l, _, e := db.Acquire(ctx, w) if e != nil { t.Fatal(e) diff --git a/server/internal/store/house_recovery_test.go b/server/internal/store/house_recovery_test.go index d418071..d884a3b 100644 --- a/server/internal/store/house_recovery_test.go +++ b/server/internal/store/house_recovery_test.go @@ -27,6 +27,7 @@ func TestHouseDeathTravelAndRecovery(t *testing.T) { _ = hub.Connect(c.View.Entity.ID) hub.Kind = "hub" hub.Phase = "hub" + c.View.Entity.Position = hub.HousingEntrancePosition() hl, _, e := db.Acquire(ctx, hub) if e != nil { t.Fatal(e) @@ -62,6 +63,7 @@ func TestHouseDeathTravelAndRecovery(t *testing.T) { t.Fatal(e) } // Traveling cancels the action, retains the exact key, and never creates another owner copy. + c.View.Entity.Position = hub.PortalPosition() act(hl, hub, c, HouseRequest{Op: "destroy-key", Item: key}) oldWorld := *hub oldWorld.Characters = map[string]*game.Character{c.View.Entity.ID: c} @@ -140,6 +142,7 @@ func TestHouseDeathTravelAndRecovery(t *testing.T) { if v := state(hub, replacement); v.Houses[0].Keys != 2 { t.Fatal("creator recovery invalidated corpse key") } + replacement.View.Entity.Position = hub.HousingEntrancePosition() act(hl, hub, replacement, HouseRequest{Op: "enter", HouseID: house}) if state(hub, replacement).Room.Floor.Inventory["wood"] != 7 { t.Fatal("recovery recreated or lost contents") diff --git a/server/internal/store/housing.go b/server/internal/store/housing.go index 754c9fa..45b3bc3 100644 --- a/server/internal/store/housing.go +++ b/server/internal/store/housing.go @@ -301,6 +301,21 @@ func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game return houseError("a carried key or invitation is required") } if r.Op == "enter" { + if !w.NearEntrance(c, w.HousingEntrancePosition()) { + return houseError("stand next to the housing entrance in this hub") + } + if r.Item != "" { + // Explicit key use must name a carried, active key for this exact house; + // an invitation cannot make a wrong or destroyed key usable. + carried := slices.ContainsFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == r.Item && i.HouseID != nil && *i.HouseID == h.View.ID }) + var active int + if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), r.Item, h.View.ID).Scan(&active); e != nil { + return e + } + if !carried || active != 1 { + return houseError("use a carried key for this house") + } + } if c.WorldsSurvived < 1 { return houseError("survive a world before entering housing") } diff --git a/server/internal/store/housing_test.go b/server/internal/store/housing_test.go index 542d1fd..0a328ef 100644 --- a/server/internal/store/housing_test.go +++ b/server/internal/store/housing_test.go @@ -51,6 +51,9 @@ func testHousingLifecycle(t *testing.T, dsn string) { // Seed arrivals before making this fixture a hub; travel itself has separate coverage. w.Kind = "hub" w.Phase = "hub" + for _, c := range []*game.Character{owner, guest, coowner} { + c.View.Entity.Position = w.HousingEntrancePosition() + } save := func() { t.Helper() if e := l.Save(ctx, w, ""); e != nil { @@ -109,7 +112,13 @@ func testHousingLifecycle(t *testing.T, dsn string) { key := owner.View.Items[len(owner.View.Items)-1].ID reject(owner, HouseRequest{Op: "create", Name: "Duplicate"}) reject(guest, HouseRequest{Op: "enter", HouseID: house}) - act(owner, HouseRequest{Op: "enter", HouseID: house}) + owner.View.Entity.Position.X += 100 + reject(owner, HouseRequest{Op: "enter", HouseID: house, Item: key}) + owner.View.Entity.Position = w.HousingEntrancePosition() + reject(owner, HouseRequest{Op: "enter", HouseID: house, Item: "unowned-key"}) + entry := HouseRequest{RequestID: game.ID(), Op: "enter", HouseID: house, Item: key} + act(owner, entry) + act(owner, entry) // Replaying an entry from inside the room must not enter twice. if e := w.Intent(owner.View.Entity.ID, p.Intent{Seq: 1, Op: "attack"}); e == nil { t.Fatal("world action inside house") } diff --git a/server/internal/store/travel_test.go b/server/internal/store/travel_test.go index 73584ff..e825041 100644 --- a/server/internal/store/travel_test.go +++ b/server/internal/store/travel_test.go @@ -203,7 +203,22 @@ func runTravelTests(t *testing.T, dsn string) { if current == hub { switchTo, switchLease = other, ol } - switched, e := lease.PrepareTravel(ctx, current, c.Account, game.ID(), switchTo.ID, "hub") + traveler := current.ForAccount(c.Account) + traveler.View.Entity.Position.X += 100 + beforePortal, _ := json.Marshal(current) + requestAtPortal := game.ID() + if _, e = lease.PrepareTravel(ctx, current, c.Account, requestAtPortal, switchTo.ID, "hub"); !errors.Is(e, ErrTravel) { + t.Fatal("remote hub travel accepted", e) + } + afterPortal, _ := json.Marshal(current) + if string(beforePortal) != string(afterPortal) { + t.Fatal("remote portal rejection mutated source") + } + if pending, e := db.PendingTransfer(ctx, c.Account); e != nil || pending != nil { + t.Fatal("remote portal rejection created transit escrow", e) + } + traveler.View.Entity.Position = current.PortalPosition() + switched, e := lease.PrepareTravel(ctx, current, c.Account, requestAtPortal, switchTo.ID, "hub") if e != nil { t.Fatal(e) }