Add item actions, targeting, bindings, and encumbrance
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import type { Character } from './generated';
|
||||
import {itemControls,chooseItemTarget} from './item-actions';
|
||||
import { itemIcon } from './item-icon';
|
||||
import { experienceText, permanentTitles } from './progression';
|
||||
import { equipmentSlots, itemDetails, modifiersView, node, numberText, primaryStats, statLabel, statsBreakdown } from './character-stats';
|
||||
@@ -25,22 +26,28 @@ function render(){
|
||||
const titles=node('details','','stat-inspection');titles.dataset.key='titles';titles.append(node('summary',`Titles (${c.titles?.length??0})`),permanentTitles(c.titles));body.append(titles);
|
||||
} else if(selected==='equipment'){
|
||||
const grid=node('div','','equipment-grid');
|
||||
for(const slot of equipmentSlots){const item=c.items?.find(i=>i.id===c.equipment?.[slot]),card=node('article','','equipment-slot');card.append(itemIcon(slot.startsWith('ring')?'ring':slot),node('small',statLabel(slot)),node('strong',item?.name??'Empty'));if(item){const inspect=node('details');inspect.dataset.key=`gear-${slot}`;inspect.append(node('summary','Inspect'),itemDetails(item,c));card.append(inspect,button('Unequip',`unequip-${slot}`,()=>request('unequip',slot),!active()));}grid.append(card);}body.append(grid);
|
||||
for(const slot of equipmentSlots){const item=c.items?.find(i=>i.id===c.equipment?.[slot]),card=node('article','','equipment-slot');card.append(itemIcon(slot.startsWith('ring')?'ring':slot),node('small',statLabel(slot)),node('strong',item?.name??'Empty'));if(item){const inspect=node('details');inspect.dataset.key=`gear-${slot}`;inspect.append(node('summary','Inspect'),itemDetails(item,c));card.append(inspect,button('Target this item',`target-${item.id}`,()=>{chooseItemTarget(item.id)},!active()),itemControls(item.id,slot),button('Unequip',`unequip-${slot}`,()=>request('unequip',slot),!active()));}grid.append(card);}body.append(grid);
|
||||
const effects=node('details','','stat-inspection');effects.dataset.key='equipment-effects';effects.append(node('summary','Equipment modifiers'));
|
||||
for(const item of c.items??[])if(Object.values(c.equipment??{}).includes(item.id))effects.append(node('h3',item.name),modifiersView(item.modifiers));body.append(effects);
|
||||
} else {
|
||||
body.append(node('p',`Carry weight ${numberText(c.carryWeight)} / ${numberText(c.stats?.carryCapacity?.final)} (advisory)`,'progression-note'));
|
||||
body.append(node('p',`Carry weight ${numberText(c.carryWeight)} / ${numberText(c.stats?.carryCapacity?.final)} · Movement ${Math.round((c.movementFactor??1)*100)}%${c.movementFactor===0?' · Drop or store items to move again':''}`,'progression-note'));
|
||||
const held=new Set(Object.values(c.equipment??{})),grid=node('div','','bag-grid'),inspection=node('div','','bag-inspection');
|
||||
grid.setAttribute('aria-label','Bag items');
|
||||
function tile(id:string,name:string,count:number,category:string){const b=button('',`item-${id}`,()=>{selectedItem=selectedItem===id?'':id;signature='';render()});b.className='bag-slot';b.title=name;b.setAttribute('aria-label',`${name} × ${count}`);b.setAttribute('aria-pressed',String(selectedItem===id));b.append(itemIcon(category),node('span',name,'bag-name'),node('b',String(count),'bag-count'));grid.append(b);return selectedItem===id;}
|
||||
function tile(id:string,name:string,count:number,category:string){const b=button('',`item-${id}`,()=>{if(chooseItemTarget(id))return;selectedItem=selectedItem===id?'':id;signature='';render()});b.className='bag-slot';b.title=name;b.setAttribute('aria-label',`${name} × ${count}`);b.setAttribute('aria-pressed',String(selectedItem===id));b.append(itemIcon(category),node('span',name,'bag-name'),node('b',String(count),'bag-count'));grid.append(b);return selectedItem===id;}
|
||||
for(const item of c.items??[])if(!held.has(item.id)){
|
||||
if(!tile(item.id,item.name,1,item.houseId?'key':item.slot))continue;
|
||||
const card=itemDetails(item,c),actions=node('div','','gear-actions');let slot=item.slot;
|
||||
if(slot==='ring'){const label=node('label','Ring slot'),select=node('select');select.dataset.focusKey=`ring-${item.id}`;select.setAttribute('aria-label',`Ring slot for ${item.name}`);for(let n=1;n<=8;n++)select.append(new Option(`Ring ${n}${c.equipment?.[`ring${n}`]?' · Occupied':' · Empty'}`,`ring${n}`));select.value=rings.get(item.id)??equipmentSlots.find(s=>s.startsWith('ring')&&!c.equipment?.[s])??'ring1';slot=select.value;select.onchange=()=>{slot=select.value;rings.set(item.id,slot)};label.append(select);actions.append(label);}
|
||||
if(!item.houseId)actions.append(button('Equip',`equip-${item.id}`,()=>request('equip',item.id,slot),!active()||!item.equippable));
|
||||
actions.append(button('Drop',`drop-${item.id}`,()=>request('drop',item.id),!active()));card.append(actions);inspection.append(card);
|
||||
if(slot==='ring'){const label=node('label','Ring slot'),select=node('select');select.dataset.focusKey=`ring-${item.id}`;select.setAttribute('aria-label',`Ring slot for ${item.name}`);for(let n=1;n<=8;n++)select.append(new Option(`Ring ${n}${c.equipment?.[`ring${n}`]?' · Occupied':' · Empty'}`,`ring${n}`));select.value=rings.get(item.id)??equipmentSlots.find(s=>s.startsWith('ring')&&!c.equipment?.[s])??'ring1';slot=select.value;select.onchange=()=>{rings.set(item.id,select.value);signature='';render()};label.append(select);actions.append(label);}
|
||||
actions.append(itemControls(item.id,slot));card.append(actions);inspection.append(card);
|
||||
}
|
||||
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){
|
||||
const consumable=c.consumables?.find(v=>v.id===key);
|
||||
if(!tile(key,c.stackNames?.[key]??statLabel(key),count,consumable||key==='bandage'?'consumable':key.startsWith('book_')?'book':key))continue;
|
||||
const card=node('article','','stack-card');card.append(node('strong',`${c.stackNames?.[key]??statLabel(key)} × ${count}`));
|
||||
if(consumable){card.append(node('p',consumable.description),modifiersView(consumable.modifiers));const e=consumable.useEffect;card.append(node('p',e?e.kind==='heal'?`Heals ${e.amount} health`:`Weapon coating: +${e.amount} damage for ${consumable.seconds}s`:`Duration: ${consumable.seconds}s`))}
|
||||
card.append(itemControls(key));
|
||||
for(const batch of c.craftedStacks??[])if(batch.item===key)card.append(node('small',`${batch.quantity} crafted by ${batch.provenance.crafterName} in ${batch.provenance.worldId}`));inspection.append(card);
|
||||
}
|
||||
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const consumable=c.consumables?.find(v=>v.id===key);if(!tile(key,c.stackNames?.[key]??statLabel(key),count,consumable||key==='bandage'?'consumable':key.startsWith('book_')?'book':key))continue;const card=node('article','','stack-card');card.append(node('strong',`${c.stackNames?.[key]??statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));if(consumable)card.append(node('p',`${consumable.description} · ${consumable.seconds}s`),modifiersView(consumable.modifiers),button('Use',`consume-${key}`,()=>request('consume',key),!active()));for(const batch of c.craftedStacks??[])if(batch.item===key)card.append(node('small',`${batch.quantity} crafted by ${batch.provenance.crafterName} in ${batch.provenance.worldId}`));inspection.append(card);}
|
||||
if(!grid.children.length)body.append(node('p','Your bag is empty.','progression-note'));
|
||||
else body.append(node('p','Select an item to inspect it and see available actions.','progression-note'));
|
||||
body.append(grid,inspection);
|
||||
|
||||
@@ -32,6 +32,7 @@ export function statsBreakdown(c:Character) {
|
||||
}
|
||||
export function itemDetails(item:ItemInstance,c:Character) {
|
||||
const card=node('article','','gear-card');
|
||||
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));
|
||||
if(item.provenance)card.append(node('p',`Crafted by ${item.provenance.crafterName} in ${item.provenance.worldId} · ${statLabel(item.provenance.profession)} level ${item.provenance.level}`,'progression-note'));
|
||||
|
||||
@@ -214,13 +214,14 @@ function gatheringForm(kind:string,existing?:NonNullable<Catalog['gathering']>['
|
||||
const fields=form(existing?`Edit ${existing.name} · publish revision ${(existing.revision??1)+1}`:'Create biome',existing?'update-biome':'create-biome',()=>({...existing?{targetId:existing.id}:{},biome:{...values.read(),color:color.value,weight:Number(weight.value),resources:checks.filter(c=>c.input.checked).map(c=>c.id)}}));
|
||||
fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),resources,node('p','Reuse any existing resource. Published biome revisions affect unexplored chunks; explored layouts remain unchanged. Adding a new resource from the resource editor also versions its selected biomes.','muted'));
|
||||
}else{
|
||||
const seconds=number(120,1,86400),effects=modifiers();
|
||||
const fields=form('Create gathering consumable','create-consumable',()=>{const mods=effects.read();if(!mods.length||mods.some(m=>!m.stat.startsWith('gathering')))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods}}});
|
||||
fields.append(values.node,field('Duration (seconds)',seconds),effects.node,node('p','Grant this item from Characters → Manage items and titles. Players use it from their bag. Reuse refreshes this consumable’s duration; distinct sources combine. Expiry uses real time, including time offline.','muted'));
|
||||
const seconds=number(120,1,86400),effects=modifiers(),kind=select(['gathering-buff','heal','weapon-coating']),amount=number(10,.1,10000);
|
||||
const fields=form('Create consumable','create-consumable',()=>{const mods=kind.value==='gathering-buff'?effects.read():[];if(kind.value==='gathering-buff'&&(!mods.length||mods.some(m=>!m.stat.startsWith('gathering'))))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods,...kind.value==='gathering-buff'?{}:{useEffect:{kind:kind.value,amount:Number(amount.value)}}}}});
|
||||
kind.onchange=()=>{effects.node.hidden=kind.value!=='gathering-buff';amount.parentElement!.hidden=kind.value==='gathering-buff';seconds.parentElement!.hidden=kind.value==='heal'};
|
||||
fields.append(values.node,field('Use effect',kind),field('Duration (seconds)',seconds),field('Healing or extra weapon damage',amount),effects.node,node('p','Healing can target yourself, a nearby player, or a mob. Coatings target a carried damage weapon and add damage to its hits for the duration; a new coating replaces the old one. Timers include time offline. Grant items from Characters → Manage items and titles.','muted'));kind.dispatchEvent(new Event('change'));
|
||||
}
|
||||
}
|
||||
function gatheringList(){
|
||||
const labels:Record<string,string>={gathering:'gathering skill',resources:'resource',biomes:'biome',consumables:'gathering consumable'};
|
||||
const labels:Record<string,string>={gathering:'gathering skill',resources:'resource',biomes:'biome',consumables:'consumable'};
|
||||
list.append(button(`Create ${labels[section]}`,()=>gatheringForm(section)));
|
||||
const g=catalog.gathering;const entries=section==='gathering'?g?.skills:section==='resources'?g?.resources:section==='biomes'?g?.biomes:g?.consumables;
|
||||
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));
|
||||
|
||||
+50
-14
@@ -1,15 +1,17 @@
|
||||
// Code generated from schemas/protocol.json. DO NOT EDIT.
|
||||
export interface Protocol {
|
||||
catalog?: ContentCatalog;
|
||||
catalogChange?: ContentChange;
|
||||
catalogPreview?: ContentPreview;
|
||||
catalogResult?: ContentResult;
|
||||
craftRequest?: CraftRequest;
|
||||
craftResult?: CraftResult;
|
||||
houseRequest?: HouseRequest;
|
||||
houseState?: HouseState;
|
||||
intent: Intent;
|
||||
snapshot: Snapshot;
|
||||
catalog?: ContentCatalog;
|
||||
catalogChange?: ContentChange;
|
||||
catalogPreview?: ContentPreview;
|
||||
catalogResult?: ContentResult;
|
||||
craftRequest?: CraftRequest;
|
||||
craftResult?: CraftResult;
|
||||
houseRequest?: HouseRequest;
|
||||
houseState?: HouseState;
|
||||
intent: Intent;
|
||||
itemActionRequest?: ItemActionRequest;
|
||||
itemActionResult?: ItemActionResult;
|
||||
snapshot: Snapshot;
|
||||
}
|
||||
|
||||
export interface ContentCatalog {
|
||||
@@ -123,10 +125,11 @@ export interface MobSpawn {
|
||||
}
|
||||
|
||||
export interface CraftingContent {
|
||||
materials: CraftMaterial[];
|
||||
professions: GatheringSkill[];
|
||||
recipes: CraftRecipe[];
|
||||
rules: CraftRules;
|
||||
materials: CraftMaterial[];
|
||||
professions: GatheringSkill[];
|
||||
recipeHistory?: CraftRecipe[];
|
||||
recipes: CraftRecipe[];
|
||||
rules: CraftRules;
|
||||
}
|
||||
|
||||
export interface CraftMaterial {
|
||||
@@ -210,6 +213,12 @@ export interface GatheringConsumable {
|
||||
modifiers: StatModifier[];
|
||||
name: string;
|
||||
seconds: number;
|
||||
useEffect?: ItemUseEffect;
|
||||
}
|
||||
|
||||
export interface ItemUseEffect {
|
||||
amount: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
export interface ResourceDefinition {
|
||||
@@ -407,6 +416,7 @@ export interface GatheringConsumableDraft {
|
||||
modifiers: StatModifier[];
|
||||
name: string;
|
||||
seconds: number;
|
||||
useEffect?: ItemUseEffect;
|
||||
}
|
||||
|
||||
export interface CraftMaterialDraft {
|
||||
@@ -686,6 +696,7 @@ export interface CraftProvenance {
|
||||
|
||||
export interface ItemInstance {
|
||||
attack?: CombatAttack;
|
||||
coating?: WeaponCoating;
|
||||
definitionId: string;
|
||||
description: string;
|
||||
equippable: boolean;
|
||||
@@ -702,6 +713,13 @@ export interface ItemInstance {
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface WeaponCoating {
|
||||
damage: number;
|
||||
expiresAt: number;
|
||||
name: string;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface HouseFurniture {
|
||||
contents: HouseInventory;
|
||||
item: ItemInstance;
|
||||
@@ -718,6 +736,23 @@ export interface Intent {
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface ItemActionRequest {
|
||||
characterId: string;
|
||||
id: string;
|
||||
item: string;
|
||||
op: string;
|
||||
quantity: number;
|
||||
slot: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface ItemActionResult {
|
||||
id: string;
|
||||
message: string;
|
||||
recipe?: KnownRecipe;
|
||||
returned: { [key: string]: number };
|
||||
}
|
||||
|
||||
export interface Snapshot {
|
||||
chunkKeys: string[];
|
||||
chunks: Chunk[];
|
||||
@@ -813,6 +848,7 @@ export interface Character {
|
||||
level: number;
|
||||
mana: number;
|
||||
manaChoices: number;
|
||||
movementFactor?: number;
|
||||
pendingVitalChoices: number;
|
||||
playedSeconds: number;
|
||||
powers?: { [key: string]: LearnedPower };
|
||||
|
||||
@@ -3,6 +3,7 @@ import {api, APIError} from './portal-shared';
|
||||
import {node} from './character-stats';
|
||||
import {registerMenu} from './menu-focus';
|
||||
import './housing.css';
|
||||
import {confirmItemAction} from './item-actions';
|
||||
|
||||
const permissions:Record<string,string>={moveFurniture:'Move furniture',openFurniture:'Open furniture',placeFurniture:'Place furniture',depositItems:'Put items in furniture',pickupItems:'Pick up items in the house',dropItems:'Drop items in the house'};
|
||||
const label=(text:string,control:HTMLElement)=>{const el=node('label',text);el.append(control);return el};
|
||||
@@ -39,7 +40,7 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
|
||||
const c=latest,s=state;if(!c||!s)return;body.replaceChildren();const h=s.room;
|
||||
title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Walk around':'Close';
|
||||
const keys=node('section');keys.append(node('h3','Carried keys'),node('p','Destroying a key takes three seconds. Death, dropping the key, leaving the world, or disconnecting cancels the action.'));
|
||||
for(const key of c.items.filter(i=>i.houseId)){const row=node('p',key.name+' ');row.append(button('Destroy key',()=>void action({op:'destroy-key',item:key.id})));keys.append(row)}
|
||||
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.'));
|
||||
@@ -78,5 +79,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,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,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)}}};
|
||||
}
|
||||
|
||||
@@ -4,18 +4,25 @@ const defaults:Record<string,InputAction>={KeyW:'north',ArrowUp:'north',KeyS:'so
|
||||
const padDefaults:Record<string,InputAction>={'0':'jump','1':'gather','2':'attack','3':'heal','4':'previous-target','5':'next-target','6':'slot1','7':'slot2','9':'inventory','12':'slot3','13':'slot4','14':'slot5','15':'slot6'};
|
||||
export function isEditing(target:EventTarget|null){return target instanceof HTMLElement&&!!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');}
|
||||
const valid=(a:unknown):a is InputAction=>typeof a==='string'&&actionNames.includes(a as InputAction);
|
||||
const codes=['',...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(k=>'Key'+k),...Array.from({length:10},(_,i)=>'Digit'+i),'Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Enter','Tab','Backspace','Delete','Home','End','PageUp','PageDown','Insert','Minus','Equal','BracketLeft','BracketRight','Backslash','Semicolon','Quote','Backquote','Comma','Period','Slash',...Array.from({length:12},(_,i)=>'F'+(i+1)),...Array.from({length:10},(_,i)=>'Numpad'+i),'NumpadAdd','NumpadSubtract','NumpadMultiply','NumpadDivide','NumpadDecimal','NumpadEnter',...Array.from({length:5},(_,i)=>'Mouse'+i)];
|
||||
const modifiers=['','Ctrl+','Alt+','Ctrl+Alt+'];
|
||||
const chord=(code:string,e:{ctrlKey:boolean;altKey:boolean})=>(e.ctrlKey?'Ctrl+':'')+(e.altKey?'Alt+':'')+code;
|
||||
const validCode=(value:string)=>modifiers.some(m=>value.startsWith(m)&&codes.includes(value.slice(m.length))&&value!==m);
|
||||
import { closeFocusedMenu } from './menu-focus';
|
||||
export class InputActions {
|
||||
private held=new Map<string,InputAction>();
|
||||
private bindings={...defaults};private padBindings={...padDefaults};private padPressed=new Set<string>();
|
||||
private padX=0;private padZ=0;
|
||||
constructor(private blocked:()=>boolean,private onAction:(action:InputAction)=>void){
|
||||
try{const data=JSON.parse(localStorage.getItem('aeternalis.controls.v1')??'null');if(data){this.bindings={};this.padBindings={};for(const [code,a] of Object.entries(data.keyboard??{}))if(valid(a)&&code!=='Escape')this.bindings[code]=a;for(const [code,a] of Object.entries(data.gamepad??{}))if(valid(a)&&/^\d+$/.test(code)&&Number(code)<32)this.padBindings[code]=a;}}catch{/* Defaults remain usable when storage is unavailable. */}
|
||||
window.addEventListener('keydown',e=>{const a=this.bindings[e.code];if(!a||e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||isEditing(e.target)||blocked())return;e.preventDefault();if(['north','south','west','east'].includes(a))this.held.set(e.code,a);else if(!e.repeat)this.trigger(a);});
|
||||
window.addEventListener('keyup',e=>this.held.delete(e.code));window.addEventListener('blur',()=>this.clear());
|
||||
try{const data=JSON.parse(localStorage.getItem('aeternalis.controls.v1')??'null');if(data){this.bindings={};this.padBindings={};for(const [code,a] of Object.entries(data.keyboard??{}))if(valid(a)&&validCode(code))this.bindings[code]=a;for(const [code,a] of Object.entries(data.gamepad??{}))if(valid(a)&&/^\d+$/.test(code)&&Number(code)<32)this.padBindings[code]=a;}}catch{/* Defaults remain usable when storage is unavailable. */}
|
||||
window.addEventListener('keydown',e=>{if(e.code.startsWith('Control')||e.code.startsWith('Alt'))this.clear();const a=this.bindings[chord(e.code,e)];if(!a||e.defaultPrevented||e.metaKey||isEditing(e.target)||blocked())return;e.preventDefault();if(['north','south','west','east'].includes(a))this.held.set(e.code,a);else if(!e.repeat)this.trigger(a);});
|
||||
window.addEventListener('keyup',e=>{this.held.delete(e.code);if(e.code.startsWith('Control')||e.code.startsWith('Alt'))this.clear()});window.addEventListener('blur',()=>this.clear());
|
||||
window.addEventListener('pointerup',e=>this.held.delete('Mouse'+e.button));window.addEventListener('pointercancel',()=>this.clear());
|
||||
window.addEventListener('contextmenu',e=>{if(e.target instanceof HTMLCanvasElement&&this.bindings[chord('Mouse2',e)]&&!blocked())e.preventDefault()});
|
||||
document.addEventListener('visibilitychange',()=>{if(document.hidden)this.clear()});document.addEventListener('focusin',e=>{if(isEditing(e.target)||blocked())this.clear()});
|
||||
}
|
||||
trigger(action:InputAction){if(!this.blocked()&&!document.hidden)this.onAction(action)}
|
||||
mouse(e:PointerEvent){const code='Mouse'+e.button,a=this.bindings[chord(code,e)];if(!a||e.metaKey||this.blocked()||isEditing(e.target))return false;e.preventDefault();if(['north','south','west','east'].includes(a))this.held.set(code,a);else this.trigger(a);return true}
|
||||
press(source:string,action:InputAction){if(!this.blocked())this.held.set(source,action)}
|
||||
release(source:string){this.held.delete(source)}
|
||||
clear(){this.held.clear();this.padX=this.padZ=0}
|
||||
@@ -37,11 +44,17 @@ export class InputActions {
|
||||
if(i===0&&focused&&!['INPUT','SELECT'].includes(focused.tagName))focused.click();
|
||||
}
|
||||
settings(){
|
||||
const root=document.createElement('details');const title=document.createElement('summary');title.textContent='Keyboard and controller bindings';root.append(title);
|
||||
const note=document.createElement('p');note.textContent='Left stick moves. Button numbers use the browser gamepad mapping. Esc always closes the focused menu. Bindings are saved on this browser.';root.append(note);
|
||||
const render=()=>{root.querySelectorAll('label').forEach(e=>e.remove());for(const a of actionNames){const label=document.createElement('label');label.textContent=a.replaceAll('-',' ');const keyboard=document.createElement('select'),pad=document.createElement('select');keyboard.setAttribute('aria-label',a+' keyboard');pad.setAttribute('aria-label',a+' gamepad');for(const code of ['',...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(k=>'Key'+k),...Array.from({length:10},(_,i)=>'Digit'+i),'Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'])keyboard.append(new Option(code||'Unbound',code));for(let i=-1;i<32;i++)pad.append(new Option(i<0?'Unbound':'Button '+i,i<0?'':String(i)));keyboard.value=Object.keys(this.bindings).find(k=>this.bindings[k]===a)??'';pad.value=Object.keys(this.padBindings).find(k=>this.padBindings[k]===a)??'';
|
||||
const change=(map:Record<string,InputAction>,code:string)=>{for(const k of Object.keys(map))if(map[k]===a)delete map[k];if(code)map[code]=a;this.clear();this.save();render();root.querySelector<HTMLSelectElement>(`select[aria-label="${a} ${map===this.bindings?'keyboard':'gamepad'}"]`)?.focus()};keyboard.onchange=()=>change(this.bindings,keyboard.value);pad.onchange=()=>change(this.padBindings,pad.value);label.append(keyboard,pad);root.append(label);
|
||||
}};render();const reset=document.createElement('button');reset.type='button';reset.textContent='Reset bindings';reset.onclick=()=>{this.bindings={...defaults};this.padBindings={...padDefaults};this.clear();this.save();render()};root.append(reset);return root;
|
||||
const root=document.createElement('details'),title=document.createElement('summary'),rows=document.createElement('div');title.textContent='Keyboard, mouse and controller bindings';root.append(title);
|
||||
const note=document.createElement('p');note.textContent='Select a key or mouse button, with optional Ctrl / Alt modifiers. Left stick moves. Controller numbers use the browser mapping. Esc always closes the focused menu. Some browser shortcuts cannot be overridden. Saved on this browser.';root.append(note,rows);
|
||||
const render=()=>{rows.replaceChildren();for(const a of actionNames){
|
||||
const label=document.createElement('label');label.textContent=a.replaceAll('-',' ');
|
||||
const keyboard=document.createElement('select'),modifier=document.createElement('select'),pad=document.createElement('select');keyboard.setAttribute('aria-label',a+' keyboard');modifier.setAttribute('aria-label',a+' modifier');pad.setAttribute('aria-label',a+' gamepad');
|
||||
for(const code of codes)keyboard.append(new Option(code||'Unbound',code));for(const m of modifiers)modifier.append(new Option(m||'No modifier',m));for(let i=-1;i<32;i++)pad.append(new Option(i<0?'Unbound':'Button '+i,i<0?'':String(i)));
|
||||
const current=Object.keys(this.bindings).find(k=>this.bindings[k]===a)??'',parts=current.split('+');keyboard.value=parts.pop()??'';modifier.value=parts.length?parts.join('+')+'+':'';pad.value=Object.keys(this.padBindings).find(k=>this.padBindings[k]===a)??'';
|
||||
const change=(map:Record<string,InputAction>,code:string,focus:string)=>{for(const k of Object.keys(map))if(map[k]===a)delete map[k];if(code)map[code]=a;this.clear();this.save();render();rows.querySelector<HTMLSelectElement>(`select[aria-label="${a} ${focus}"]`)?.focus()};
|
||||
keyboard.onchange=()=>change(this.bindings,keyboard.value?modifier.value+keyboard.value:'','keyboard');modifier.onchange=()=>change(this.bindings,keyboard.value?modifier.value+keyboard.value:'','modifier');pad.onchange=()=>change(this.padBindings,pad.value,'gamepad');label.append(modifier,keyboard,pad);rows.append(label);
|
||||
}};
|
||||
for(const device of ['Keyboard / mouse','Controller']){const reset=document.createElement('button');reset.type='button';reset.textContent='Reset '+device+' bindings';reset.onclick=()=>{if(device==='Controller')this.padBindings={...padDefaults};else this.bindings={...defaults};this.clear();this.save();render()};root.append(reset)}render();return root;
|
||||
}
|
||||
private save(){try{localStorage.setItem('aeternalis.controls.v1',JSON.stringify({keyboard:this.bindings,gamepad:this.padBindings}))}catch{/* Session bindings still work. */}}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import type {Character, ItemActionRequest, ItemActionResult} from './generated';
|
||||
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};
|
||||
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}
|
||||
|
||||
export function confirmItemAction(title:string,detail:string,action:()=>void){
|
||||
const dialog=node('dialog','','item-confirm'),cancel=node('button','Cancel'),confirm=node('button','Confirm');
|
||||
cancel.type=confirm.type='button';dialog.append(node('h2',title),node('p',detail),cancel,confirm);document.body.append(dialog);
|
||||
const close=()=>{dialog.close();menu.dispose();dialog.remove()},menu=registerMenu(dialog,close);
|
||||
cancel.onclick=close;confirm.onclick=()=>{close();action()};dialog.addEventListener('cancel',e=>{e.preventDefault();close()});dialog.showModal();menu.opened();
|
||||
}
|
||||
|
||||
export function createItemActions(o:Options){
|
||||
const bar=node('section','','item-action-status'),text=node('p'),retry=node('button','Retry pending item action'),cancel=node('button','Cancel use'),self=node('button','Use on myself'),selected=node('button','Use selected target'),bag=node('button','Choose item from bag');
|
||||
for(const b of [retry,cancel,self,selected,bag])b.type='button';bar.hidden=true;bar.setAttribute('aria-live','polite');bar.append(text,retry,self,selected,bag,cancel);
|
||||
let targetItem='',pending:ItemActionRequest|undefined,busy=false,character='',message='';
|
||||
const key=()=>`aeternalis.item-action.${o.prefix}.${character}`;
|
||||
const remember=()=>{try{if(pending)sessionStorage.setItem(key(),JSON.stringify(pending));else sessionStorage.removeItem(key())}catch{/* Keep the request in memory while this page is open. */}};
|
||||
function update(){const c=o.character();if(!c)return;if(character!==c.entity.id){character=c.entity.id;pending=undefined;targetItem='';try{const v=JSON.parse(sessionStorage.getItem(key())??'null');if(v?.characterId===character&&typeof v.id==='string')pending=v}catch{}}
|
||||
const inBag=!o.panel.hidden,host=inBag?o.panel:o.hud;bar.classList.toggle('in-bag',inBag);if(bar.parentElement!==host){if(inBag)host.prepend(bar);else host.append(bar)}
|
||||
if(c.entity.state!=='alive'||c.remainingSeconds<=0||c.houseId)targetItem='';
|
||||
if(targetItem&&!c.items.some(i=>i.id===targetItem)&&!(c.inventory[targetItem]>0))targetItem='';
|
||||
bar.hidden=!targetItem&&!pending;retry.hidden=!pending;retry.disabled=busy;
|
||||
for(const b of [cancel,self,selected,bag])b.hidden=!targetItem;
|
||||
text.textContent=pending?(busy?'Saving item action…':message||'An item action is awaiting its saved result. Retry to resolve it.'):`Use ${name(targetItem)}: choose a target in the world or your bag. Esc cancels.`;
|
||||
}
|
||||
function name(id:string){const c=o.character();return c?.items.find(i=>i.id===id)?.name??c?.stackNames?.[id]??id.replaceAll('_',' ')}
|
||||
async function submit(op:string,item:string,target='',slot='',quantity=1){
|
||||
if(busy)return;update();const c=o.character();if(!c)return;
|
||||
if(pending){o.notice('Retry the pending item action before starting another.');return}
|
||||
pending={id:crypto.randomUUID(),characterId:c.entity.id,op,item,target,slot,quantity};remember();await execute();
|
||||
}
|
||||
async function execute(){if(busy||!pending)return;busy=true;update();
|
||||
try{const result=await api<ItemActionResult>(o.prefix+'/api/item-action',pending);pending=undefined;remember();targetItem='';message='';const returned=Object.entries(result.returned).map(([id,n])=>`${name(id)} × ${n}`).join(', ');o.notice(result.message+(returned?' · Recovered '+returned:''))}
|
||||
catch(e){message=(e as Error).message;if(e instanceof APIError&&e.status>=400&&e.status<500&&e.status!==408&&e.status!==429){pending=undefined;remember()}o.notice(message+(pending?' Retry the saved request to resolve the result.':''))}
|
||||
finally{busy=false;update()}
|
||||
}
|
||||
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))}
|
||||
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(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);
|
||||
}
|
||||
function controls(id:string,slot:string){
|
||||
const row=node('div','','gear-actions'),c=o.character();if(!c)return row;const item=c.items.find(i=>i.id===id),consumable=c.consumables?.find(i=>i.id===id),disabled=c.entity.state!=='alive'||c.remainingSeconds<=0||!!c.houseId;
|
||||
function button(label:string,fn:()=>void,extra=false){const b=node('button',label);b.type='button';b.dataset.focusKey=`${label}-${id}`;b.disabled=(label.startsWith('Drop')&&c!.entity.state==='eligible'?c!.remainingSeconds<=0||!!c!.houseId:disabled)||extra;b.onclick=fn;row.append(b)}
|
||||
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(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)));
|
||||
if(!item?.houseId&&!item?.furniture&&(item||consumable||['bandage','revival_stone','escape_stone'].includes(id)))row.append(o.assign(id,item?slot:undefined));
|
||||
return row;
|
||||
}
|
||||
retry.onclick=()=>void execute();cancel.onclick=()=>{targetItem='';update()};self.onclick=()=>{const id=o.character()?.entity.id;if(id)choose(id)};selected.onclick=()=>{const id=o.selected();if(id)choose(id);else o.notice('Select a target first.')};bag.onclick=()=>o.aim(true);
|
||||
window.addEventListener('keydown',e=>{if(e.code==='Escape'&&targetItem){targetItem='';update()}});
|
||||
const result={bar,update,controls,choose,activate,cancel:()=>{targetItem='';update()},get targeting(){return !!targetItem}};controller=result;return result;
|
||||
}
|
||||
+13
-4
@@ -1,4 +1,5 @@
|
||||
import './style.css';
|
||||
import {createItemActions} from './item-actions';
|
||||
import { showTravel } from './travel';
|
||||
import { createHousingPanel } from './housing-panel';
|
||||
import { buildingPanel } from './building-panel';
|
||||
@@ -6,7 +7,7 @@ import { createPlayerDrawer } from './player-drawer';
|
||||
import { createPowerPanel, revivalPanel } from './power-panel';
|
||||
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
|
||||
import { WorldView } from './world-view';
|
||||
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
import type { BuildingContent, Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
import { experienceText, statPointsText, updateExperienceMeter } from './progression';
|
||||
import { InputActions, isEditing, type InputAction } from './input-actions';
|
||||
import { hasOpenMenu, registerMenu } from './menu-focus';
|
||||
@@ -54,6 +55,7 @@ let input: InputActions;
|
||||
let powers:ReturnType<typeof createPowerPanel>;
|
||||
let housing:ReturnType<typeof createHousingPanel>;
|
||||
let drawer:ReturnType<typeof createPlayerDrawer>;
|
||||
let items:ReturnType<typeof createItemActions>;
|
||||
let placement:{id:string;rotation:string;range:number}|undefined;
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
@@ -165,6 +167,7 @@ function updateHUD(s: Snapshot) {
|
||||
const c = s.self, w = s.world;
|
||||
housing?.update(c);
|
||||
powers?.update(c);
|
||||
items?.update();
|
||||
const playable=['alive','eligible'].includes(c.entity.state)&&c.remainingSeconds>0;
|
||||
powers.hotbar.hidden=!playable;
|
||||
visible('game-controls', playable); visible('movement', playable && !hasOpenMenu());
|
||||
@@ -206,6 +209,7 @@ async function boot() {
|
||||
view = new WorldView($<HTMLCanvasElement>('world'));
|
||||
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
||||
if(snapshot?.self.houseId){if(key==='inventory'||key==='gather'){housing.open();return}if(key==='jump'){send('jump');return}return}
|
||||
if((key==='attack'||key==='gather')&&items?.targeting){const target=view.selected?.id;if(target)items.choose(target);else notice('Select a target first.');return}
|
||||
if(key==='attack'||key==='gather')action(key);
|
||||
else if(key==='inventory')$('inventory-toggle').click();
|
||||
else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1);
|
||||
@@ -273,8 +277,11 @@ async function boot() {
|
||||
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);$('hud').append(powers.hotbar);$('settings').append(input.settings());
|
||||
drawer=createPlayerDrawer($('inventory'),powers,send,worldPrefix,housing.root,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));
|
||||
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();};
|
||||
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);
|
||||
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;}});};
|
||||
$<HTMLInputElement>('zoom').value = String(view.distance);
|
||||
@@ -329,8 +336,10 @@ async function boot() {
|
||||
button.onpointerup = button.onpointercancel = button.onlostpointercapture = () => input.release(source);
|
||||
});
|
||||
view.canvas.addEventListener('pointerdown', event => {
|
||||
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
if (event.defaultPrevented || !snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open) return;
|
||||
if (!items.targeting && input.mouse(event) || event.button !== 0) return;
|
||||
const hit = view.pick(event.clientX, event.clientY);
|
||||
if(items.targeting){if(hit.entity)items.choose(hit.entity.id);else notice('Select a player, mob, or item as the target.');return}
|
||||
if(snapshot.self.houseId){if(hit.entity?.kind==='house-exit')void housing.leave();else if(hit.entity)housing.open(hit.entity.id);else if(hit.point)walkTo=hit.point;return}
|
||||
if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;}
|
||||
|
||||
|
||||
@@ -14,3 +14,9 @@
|
||||
#inventory>section:last-child{border-top:1px solid #72896844;margin-top:18px;padding-top:14px}.equipment-slot>svg{float:right;color:#c6d8a8}.equipment-slot details>summary{cursor:pointer;padding:8px 0;font-size:12px}.equipment-slot .gear-card{padding:6px;border:0}
|
||||
@media(max-width:800px){#inventory.inventory{top:80px;max-height:calc(100dvh - 98px);padding:14px}.drawer-nav{top:-14px}.bag-grid{gap:4px}.bag-slot{min-height:70px}.drawer-content .equipment-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
@media(max-height:520px){#inventory.inventory{top:66px;max-height:calc(100dvh - 78px)}}
|
||||
.item-action-status { position:fixed; left:50%; transform:translateX(-50%); top:5rem; z-index:45; width:min(32rem,90vw); padding:.75rem; border:1px solid var(--line,#53615d); border-radius:.75rem; background:var(--panel,#14201e); box-shadow:0 5px 24px #0008; pointer-events:auto; }
|
||||
.item-action-status p { margin:0 0 .5rem; }
|
||||
.item-action-status button { margin:.15rem; }
|
||||
.item-action-status.in-bag { position:static; transform:none; width:100%; margin-bottom:.75rem; }
|
||||
.item-confirm { max-width:min(32rem,90vw); padding:1.5rem; border-radius:1rem; }
|
||||
.item-confirm button { margin-right:.5rem; }
|
||||
|
||||
@@ -2,14 +2,24 @@ import type {Character,Entity} from './generated';
|
||||
import {node,statLabel} from './character-stats';
|
||||
import {api} from './portal-shared';
|
||||
|
||||
export function createPowerPanel(send:(op:string,target?:string,x?:number,z?:number,slot?:string)=>void,target:()=>Entity|undefined,notice:(s:string)=>void,prefix:string){
|
||||
export function createPowerPanel(send:(op:string,target?:string,x?:number,z?:number,slot?:string)=>void,target:()=>Entity|undefined,notice:(s:string)=>void,prefix:string,useItem:(id:string,slot?:string)=>void){
|
||||
const root=node('section','','power-panel'),abilities=node('section','','power-panel'),hotbar=node('div','','power-hotbar'),bookList=node('div'),known=node('div'),casting=node('p'),abilityList=node('div');root.append(casting,bookList,known);abilities.append(node('p','Train a weapon to unlock abilities, then assign them to action slots.'),abilityList);hotbar.hidden=true;
|
||||
let latest:Character,signature='',slots:string[]=[],character='',busy=false;
|
||||
const use=async(id:string)=>{if(!latest||busy)return;const power=latest.powers?.[id];if(!power&&id!=='item')return;const selected=target();if(id==='item'||power?.definition.resurrection){if(selected?.kind!=='corpse'){notice('Select a player corpse and stand next to it.');return}busy=true;try{await api(prefix+'/api/revive',{corpse:selected.id,power:id});notice('Player revived.')}catch(e){notice((e as Error).message)}finally{busy=false}}else {const aim=power!.definition.targeting;if(aim==='target'&&!selected){notice('Select a target first.');return}send('cast',aim==='target'?selected!.id:latest.entity.id,0,0,id)}};
|
||||
const use=async(id:string)=>{if(!latest||busy)return;if(id?.startsWith('gear|')||id?.startsWith('item|')){const [,item,slot]=id.split('|');useItem(item,slot);return}const power=latest.powers?.[id];if(!power&&id!=='item')return;const selected=target();if(id==='item'||power?.definition.resurrection){if(selected?.kind!=='corpse'){notice('Select a player corpse and stand next to it.');return}busy=true;try{await api(prefix+'/api/revive',{corpse:selected.id,power:id});notice('Player revived.')}catch(e){notice((e as Error).message)}finally{busy=false}}else {const aim=power!.definition.targeting;if(aim==='target'&&!selected){notice('Select a target first.');return}send('cast',aim==='target'?selected!.id:latest.entity.id,0,0,id)}};
|
||||
const buttons=Array.from({length:8},(_,i)=>{const b=node('button',String(i+1));b.type='button';b.onclick=()=>void use(slots[i]);hotbar.append(b);return b});
|
||||
function refreshSlots(){buttons.forEach((b,i)=>{const p=latest.powers?.[slots[i]];b.textContent=p?`${i+1} · ${p.definition.name}`:`${i+1} · Empty`;b.disabled=!p||!['alive','eligible'].includes(latest.entity.state);b.title=p?`${p.definition.mana} mana · ${p.definition.cooldown}s cooldown`:'Assign a learned power in Inventory';})}
|
||||
function refreshSlots(){buttons.forEach((b,i)=>{
|
||||
const value=slots[i]??'',p=latest.powers?.[value],parts=value.split('|'),item=parts[0]==='gear'?latest.items.find(v=>v.id===parts[1]):undefined,count=parts[0]==='item'?latest.inventory[parts[1]]??0:0;
|
||||
const label=p?.definition.name??item?.name??(count>0?`${latest.stackNames?.[parts[1]]??statLabel(parts[1])} × ${count}`:'');
|
||||
b.textContent=label?`${i+1} · ${label}`:`${i+1} · Empty`;b.disabled=!label||latest.entity.state!=='alive';b.title=p?`${p.definition.mana} mana · ${p.definition.cooldown}s cooldown`:item?'Equip this exact item':count?'Use this consumable':'Assign an item or learned power from the drawer';
|
||||
})}
|
||||
function assignItem(id:string,slot?:string){
|
||||
const value=slot?`gear|${id}|${slot}`:`item|${id}`,select=node('select');select.setAttribute('aria-label','Action slot for item');select.dataset.focusKey='assign-'+id;select.append(new Option('Add to hotbar…',''));for(let i=0;i<8;i++)select.append(new Option('Slot '+(i+1),String(i)));const at=slots.indexOf(value);select.value=at<0?'':String(at);select.onchange=()=>{slots=slots.map(v=>v===value?'':v);if(select.value!=='')slots[Number(select.value)]=value;save()};return select;
|
||||
}
|
||||
const save=()=>{try{localStorage.setItem('aeternalis.slots.'+character,JSON.stringify(slots))}catch{};signature='';refreshSlots()};
|
||||
function update(c:Character){latest=c;if(character!==c.entity.id){character=c.entity.id;signature='';slots=[];try{slots=JSON.parse(localStorage.getItem('aeternalis.slots.'+character)??'[]');if(!Array.isArray(slots))slots=[]}catch{slots=[]}}
|
||||
const previousSlots=JSON.stringify(slots);
|
||||
slots=slots.slice(0,8).map(value=>{if(typeof value!=='string')return '';const [kind,id]=value.split('|');if(kind==='gear'&&!c.items.some(i=>i.id===id)||kind==='item'&&!(c.inventory[id]>0))return '';return value});
|
||||
if(previousSlots!==JSON.stringify(slots))try{localStorage.setItem('aeternalis.slots.'+character,JSON.stringify(slots))}catch{}
|
||||
casting.textContent=`Mana ${Math.floor(c.mana??0)} / ${Math.floor(c.stats?.manaPoints?.final??0)} · Stamina ${Math.floor(c.stamina??0)}${c.casting?' · '+c.casting:''}`;refreshSlots();const sig=JSON.stringify([c.powers,c.weapons,c.inventory]);if(sig===signature)return;signature=sig;
|
||||
const open=new Set(Array.from([...known.querySelectorAll('details[open]'),...abilityList.querySelectorAll('details[open]')]).map(e=>(e as HTMLElement).dataset.power));
|
||||
const focus=(document.activeElement as HTMLElement)?.dataset.powerFocus;
|
||||
@@ -20,7 +30,7 @@ export function createPowerPanel(send:(op:string,target?:string,x?:number,z?:num
|
||||
if(!abilityList.children.length)abilityList.append(node('p','No abilities learned yet.'));
|
||||
if(focus)Array.from([...known.querySelectorAll<HTMLElement>('[data-power-focus]'),...abilityList.querySelectorAll<HTMLElement>('[data-power-focus]')]).find(e=>e.dataset.powerFocus===focus)?.focus({preventScroll:true});
|
||||
}
|
||||
return {root,abilities,hotbar,update,useSlot:(i:number)=>void use(slots[i])};
|
||||
return {root,abilities,hotbar,update,assignItem,useSlot:(i:number)=>void use(slots[i])};
|
||||
}
|
||||
|
||||
export function revivalPanel(prefix:string){
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Item actions — revised milestone 2
|
||||
|
||||
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
|
||||
from the bag destroys one unit. House-key destruction uses the existing three-second
|
||||
action and cancellation rules, including its last-key recovery/deletion contract.
|
||||
|
||||
Use selects a target. Click a world entity, choose yourself or the selected target,
|
||||
or select a bag item. Equipped items have a Target this item button. Esc first closes
|
||||
the focused menu, then cancels an outstanding use context. Unsupported combinations
|
||||
return an explanation without consuming the item. House keys open existing housing
|
||||
controls; physical door targeting remains milestone 3. Structure kits start placement;
|
||||
the Skills building view still provides orientation selection. Books, revival stones
|
||||
and escape stones use their established server operations and lifecycle constraints.
|
||||
|
||||
Admins can create three consumable profiles: gathering modifiers, immediate healing,
|
||||
and weapon coating. Healing reaches a nearby living player or mob through an
|
||||
unobstructed line, with no resurrection. A coating targets an owned damage weapon,
|
||||
adds its configured amount to weapon attacks, and expires in real time, including
|
||||
offline time. New coatings replace the old coating. The first coating profile adds
|
||||
hit damage; damage-over-time/status variants are not defined by this milestone.
|
||||
Projectiles still have to collide before damage applies, and spells do not inherit
|
||||
weapon coatings. Copied coating data stays with the exact weapon on drop/loot/travel.
|
||||
|
||||
Consumables can occupy the same eight hotbar slots as powers. A consumable binding
|
||||
uses its item type and clears when the final unit leaves inventory. Equipment binds
|
||||
an exact instance and destination slot for quick swaps; losing that instance clears
|
||||
its binding. These browser preferences remain scoped to the character. Settings
|
||||
support keyboard and mouse buttons, Ctrl/Alt combinations, gamepad buttons, and
|
||||
separate keyboard/mouse and controller resets. Left-stick movement remains available.
|
||||
Controller hotbar groups await playtesting; browser-reserved shortcuts may take priority.
|
||||
|
||||
## Authoritative rules
|
||||
|
||||
- `POST /api/item-action` authenticates the active character and validates ownership,
|
||||
state, quantity, target, range, obstruction and cooldown. Equip, destroy, breakdown,
|
||||
consume and targeted use save their complete result and request receipt atomically.
|
||||
Retry pending action resolves an uncertain save with the same request ID, including
|
||||
after a page reload in the same tab. A changed request cannot reuse a receipt. A
|
||||
replay reports the original outcome without changing inventory or reactivating a life.
|
||||
- Carry weight includes all carried gear and unit-weight stacks. Movement remains
|
||||
normal at capacity, becomes 99% at 1.1×, 75% at 1.5×, and zero at 2× or more with
|
||||
the initial quadratic curve. Apply this after speed and capacity modifiers, in
|
||||
worlds and houses. Immobilization also prevents starting a jump. Gravity still
|
||||
finishes an existing fall. Survivors can drop weight after victory to reach a portal.
|
||||
- Breakdown uses the item's original recipe revision. Future recipe publications
|
||||
archive their preceding revision. Old crafted items whose original revision is
|
||||
unavailable cannot be salvaged by substituting a newer recipe. Unmarked equipment
|
||||
requires one unambiguous recipe producing it. Houses, furniture and keys cannot
|
||||
be broken down.
|
||||
- Base material recovery is 25% at the required crafting level. Under-level recovery
|
||||
decreases exponentially; higher levels approach 75%. Recovery is divided across
|
||||
the original output batch and rounded down, possibly to zero. Armor uses armor
|
||||
making; primary weapons use weapon smithing; other items use their recipe profession.
|
||||
Recovery never fabricates crafted provenance. Every valid breakdown has a flat
|
||||
0.01% recipe discovery chance and grants no XP, including in a hub.
|
||||
- Curve, salvage percentages, discovery chance and item cooldown are configured in
|
||||
`server/content/balance.yaml`; old snapshots acquire defaults once. Further balance
|
||||
changes should follow manual playtesting. Permanent-death, replacement, travel,
|
||||
daily-time and housing access rules still apply.
|
||||
|
||||
## Manual playtest handoff
|
||||
|
||||
1. Swap two weapons in the same slot; move a ring between occupied slots. Confirm
|
||||
neither item disappears and no instance is assigned twice. Assign gear to a
|
||||
hotbar slot and use it after closing the drawer.
|
||||
2. Cancel and confirm destroy/breakdown. Inspect surviving stacks' crafting origin.
|
||||
Revise a recipe after crafting gear, then break that gear down; it should recover
|
||||
from the old inputs. A zero-resource result is possible at low skill levels.
|
||||
3. Create healing and coating consumables in Control and grant them. Heal yourself,
|
||||
another player and a mob. Try distant/blocked/full-health targets. Apply a coating
|
||||
to a carried weapon, equip it and compare hits before/after expiry. A failed use
|
||||
must leave the consumable intact.
|
||||
4. Assign a consumable to a hotbar slot; consume/drop its last unit and confirm the
|
||||
slot clears. Reload to check saved bindings. Exercise Ctrl/Alt combos, a mouse
|
||||
binding, controller controls and each separate reset. Confirm menus remain usable.
|
||||
5. Load up above capacity, then at twice capacity. Check movement and jumping in a
|
||||
world and house; drop/store weight to recover. Check victory-portal movement too.
|
||||
6. Confirm key destruction shows a three-second action and that death/drop/disconnect
|
||||
cancellation still works. Check recipe/consumable use after travel without XP in hubs.
|
||||
7. If a save loses its response, use Retry pending item action and confirm the result
|
||||
is applied once. Reloading the same tab should retain an unresolved request.
|
||||
|
||||
Automated browser expansion/full-suite runs remain deferred to the existing TODO.
|
||||
Required TypeScript/build and Go checks cover this milestone; focused Go regressions
|
||||
cover inventory recovery, transactional retries, target isolation, restart/death,
|
||||
coating expiry, recipe history and encumbrance. PostgreSQL variants require
|
||||
`TEST_DATABASE_URL` in an environment with a database.
|
||||
@@ -1,5 +1,9 @@
|
||||
# Player interface — revised milestone 1
|
||||
|
||||
The subsequent [item-action milestone](ITEM-ACTIONS.md) implements the weight,
|
||||
targeting, breakdown and binding follow-ups described below. This document records
|
||||
the original presentation milestone and its manual checks.
|
||||
|
||||
The character drawer now separates Bag, Character, Equipment, Skills, Abilities,
|
||||
and Spells with six labeled icon buttons. Open with the backpack / Inventory and
|
||||
crafting button or the existing inventory binding. Collapse with its close button,
|
||||
|
||||
@@ -213,3 +213,8 @@ Milestone 1 handoff: [Player drawer](../docs/PLAYER-DRAWER.md). Weight penalties
|
||||
new item-use behaviors, source-filtered stats, and expanded binding semantics are
|
||||
not implemented by the first presentation slice. Character-owned worlds-survived
|
||||
display needs an authoritative snapshot field; it must not be inferred from titles.
|
||||
|
||||
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.
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
"craftRequest": {
|
||||
"$ref": "#/definitions/CraftRequest"
|
||||
},
|
||||
"itemActionRequest": {"$ref": "#/definitions/ItemActionRequest"},
|
||||
"itemActionResult": {"$ref": "#/definitions/ItemActionResult"},
|
||||
"craftResult": {
|
||||
"$ref": "#/definitions/CraftResult"
|
||||
},
|
||||
@@ -238,6 +240,7 @@
|
||||
"mana": {"type": "number"},
|
||||
"stamina": {"type": "number"},
|
||||
"carryWeight": {"type": "number"},
|
||||
"movementFactor": {"type": "number"},
|
||||
"pendingVitalChoices": {"type": "integer"},
|
||||
"healthChoices": {"type": "integer"},
|
||||
"manaChoices": {"type": "integer"},
|
||||
@@ -294,6 +297,7 @@
|
||||
"ItemInstance": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"coating": {"$ref": "#/definitions/WeaponCoating"},
|
||||
"id": {"type": "string"},
|
||||
"definitionId": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
@@ -462,9 +466,20 @@
|
||||
},
|
||||
"required": ["name", "description", "color", "weight"]
|
||||
},
|
||||
"ItemUseEffect": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"kind": {"type": "string"}, "amount": {"type": "number"}},
|
||||
"required": ["kind", "amount"]
|
||||
},
|
||||
"WeaponCoating": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"source": {"type": "string"}, "name": {"type": "string"}, "expiresAt": {"type": "number"}, "damage": {"type": "number"}},
|
||||
"required": ["source", "name", "expiresAt", "damage"]
|
||||
},
|
||||
"GatheringConsumable": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"useEffect": {"$ref": "#/definitions/ItemUseEffect"},
|
||||
"id": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
@@ -476,6 +491,7 @@
|
||||
"GatheringConsumableDraft": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"useEffect": {"$ref": "#/definitions/ItemUseEffect"},
|
||||
"id": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
@@ -795,6 +811,7 @@
|
||||
"professions": {"type": "array", "items": {"$ref": "#/definitions/GatheringSkill"}},
|
||||
"materials": {"type": "array", "items": {"$ref": "#/definitions/CraftMaterial"}},
|
||||
"recipes": {"type": "array", "items": {"$ref": "#/definitions/CraftRecipe"}},
|
||||
"recipeHistory": {"type": "array", "items": {"$ref": "#/definitions/CraftRecipe"}},
|
||||
"rules": {"$ref": "#/definitions/CraftRules"}
|
||||
},
|
||||
"required": ["professions", "materials", "recipes", "rules"]
|
||||
@@ -843,6 +860,25 @@
|
||||
},
|
||||
"required": ["recipe", "discoveredAt"]
|
||||
},
|
||||
"ItemActionRequest": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "characterId": {"type": "string"},
|
||||
"op": {"type": "string"}, "item": {"type": "string"},
|
||||
"target": {"type": "string"}, "slot": {"type": "string"},
|
||||
"quantity": {"type": "integer"}
|
||||
},
|
||||
"required": ["id", "characterId", "op", "item", "target", "slot", "quantity"]
|
||||
},
|
||||
"ItemActionResult": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "message": {"type": "string"},
|
||||
"returned": {"type": "object", "additionalProperties": {"type": "integer"}},
|
||||
"recipe": {"$ref": "#/definitions/KnownRecipe"}
|
||||
},
|
||||
"required": ["id", "message", "returned"]
|
||||
},
|
||||
"CraftRequest": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
|
||||
@@ -71,6 +71,7 @@ tickHz: 20
|
||||
snapshotHz: 5
|
||||
chunkSize: 128
|
||||
terrainResolution: 16
|
||||
inventory: { stopWeightRatio: 2, slowdownExponent: 2, breakdownBase: 25, breakdownMax: 75, breakdownLevelScale: 25, recipeChance: 0.01, actionCooldown: 1 }
|
||||
worldRadius: 1024
|
||||
maxPlayers: 100
|
||||
spawnSeparation: 48
|
||||
|
||||
@@ -19,6 +19,7 @@ type Recipe struct {
|
||||
}
|
||||
|
||||
type Balance struct {
|
||||
Inventory *InventoryRules `yaml:"inventory"`
|
||||
XPCurve *XPCurve `yaml:"xpCurve"`
|
||||
Housing *HousingRules `yaml:"housing"`
|
||||
Building *BuildingContent `yaml:"building"`
|
||||
@@ -85,6 +86,11 @@ func Parse(data []byte) (Balance, error) {
|
||||
return b, b.Validate()
|
||||
}
|
||||
func (b Balance) Validate() error {
|
||||
if b.Inventory != nil {
|
||||
if e := b.Inventory.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if b.XPCurve != nil {
|
||||
if e := b.XPCurve.Validate(); e != nil {
|
||||
return e
|
||||
|
||||
@@ -46,10 +46,11 @@ type CraftRules struct {
|
||||
Cooldown float64 `json:"cooldown" yaml:"cooldown"`
|
||||
}
|
||||
type CraftingContent struct {
|
||||
Professions []GatheringSkill `json:"professions" yaml:"professions"`
|
||||
Materials []CraftMaterial `json:"materials" yaml:"materials"`
|
||||
Recipes []CraftRecipe `json:"recipes" yaml:"recipes"`
|
||||
Rules CraftRules `json:"rules" yaml:"rules"`
|
||||
RecipeHistory []CraftRecipe `json:"recipeHistory,omitempty" yaml:"recipeHistory"`
|
||||
Professions []GatheringSkill `json:"professions" yaml:"professions"`
|
||||
Materials []CraftMaterial `json:"materials" yaml:"materials"`
|
||||
Recipes []CraftRecipe `json:"recipes" yaml:"recipes"`
|
||||
Rules CraftRules `json:"rules" yaml:"rules"`
|
||||
}
|
||||
|
||||
func (r CraftRules) Validate() error {
|
||||
@@ -131,7 +132,7 @@ func (c Catalog) validateCrafting() error {
|
||||
return nil
|
||||
}
|
||||
v := c.Crafting
|
||||
if len(v.Professions) < 1 || len(v.Professions) > 64 || len(v.Materials) > 256 || len(v.Recipes) > 512 {
|
||||
if len(v.Professions) < 1 || len(v.Professions) > 64 || len(v.Materials) > 256 || len(v.Recipes) > 512 || len(v.RecipeHistory) > 4096 {
|
||||
return fmt.Errorf("invalid crafting content limits")
|
||||
}
|
||||
if err := v.Rules.Validate(); err != nil {
|
||||
@@ -163,6 +164,27 @@ func (c Catalog) validateCrafting() error {
|
||||
titles[t.ID] = true
|
||||
}
|
||||
ids, combinations := map[string]bool{}, map[string]bool{}
|
||||
history := map[string]bool{}
|
||||
for _, r := range v.RecipeHistory {
|
||||
key := fmt.Sprintf("%s:%d", r.ID, r.Revision)
|
||||
if history[key] {
|
||||
return fmt.Errorf("duplicate archived recipe revision")
|
||||
}
|
||||
history[key] = true
|
||||
for _, current := range v.Recipes {
|
||||
if current.ID == r.ID && current.Revision <= r.Revision {
|
||||
return fmt.Errorf("archived recipe must precede current revision")
|
||||
}
|
||||
}
|
||||
copy := *v
|
||||
copy.Recipes = []CraftRecipe{r}
|
||||
copy.RecipeHistory = nil
|
||||
catalog := c
|
||||
catalog.Crafting = ©
|
||||
if err := catalog.validateCrafting(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, r := range v.Recipes {
|
||||
if !validSetIdentity(r.ID, r.Name, r.Description) || ids[r.ID] || r.Revision < 1 || !professions[r.Profession] || r.Level < 1 || r.Level > 1000 || r.XP < 1 || r.XP > 1000000 || len(r.Inputs) < 1 || len(r.Inputs) > 16 || len(r.Outputs) < 1 || len(r.Outputs) > 8 || len(r.Stats) > 32 || len(r.Titles) > 16 {
|
||||
return fmt.Errorf("invalid crafting recipe %q", r.Name)
|
||||
|
||||
@@ -40,6 +40,7 @@ type BiomeDefinition struct {
|
||||
Weight int64 `json:"weight" yaml:"weight"`
|
||||
}
|
||||
type GatheringConsumable struct {
|
||||
UseEffect *ItemUseEffect `json:"useEffect,omitempty" yaml:"useEffect"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
@@ -144,9 +145,12 @@ func (g GatheringContent) Validate() error {
|
||||
}
|
||||
}
|
||||
for _, c := range g.Consumables {
|
||||
if !identity(c.ID, c.Name, c.Description) || !finiteRange(c.Seconds, 1, 86400) || len(c.Modifiers) < 1 {
|
||||
if !identity(c.ID, c.Name, c.Description) || !finiteRange(c.Seconds, 1, 86400) || (c.UseEffect == nil && len(c.Modifiers) < 1) {
|
||||
return fmt.Errorf("invalid consumable %q", c.ID)
|
||||
}
|
||||
if c.UseEffect != nil && (len(c.Modifiers) != 0 || !c.UseEffect.Valid()) {
|
||||
return fmt.Errorf("invalid consumable use effect")
|
||||
}
|
||||
if err := ValidateModifiers(c.Modifiers); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package content
|
||||
|
||||
import "fmt"
|
||||
|
||||
type ItemUseEffect struct {
|
||||
Kind string `json:"kind" yaml:"kind"`
|
||||
Amount float64 `json:"amount" yaml:"amount"`
|
||||
}
|
||||
|
||||
func (e ItemUseEffect) Valid() bool {
|
||||
return (e.Kind == "heal" || e.Kind == "weapon-coating") && finiteRange(e.Amount, .1, 10000)
|
||||
}
|
||||
|
||||
type InventoryRules struct {
|
||||
StopWeightRatio float64 `yaml:"stopWeightRatio"`
|
||||
SlowdownExponent float64 `yaml:"slowdownExponent"`
|
||||
BreakdownBase float64 `yaml:"breakdownBase"`
|
||||
BreakdownMax float64 `yaml:"breakdownMax"`
|
||||
BreakdownLevelScale float64 `yaml:"breakdownLevelScale"`
|
||||
RecipeChance float64 `yaml:"recipeChance"`
|
||||
ActionCooldown float64 `yaml:"actionCooldown"`
|
||||
}
|
||||
|
||||
func (r InventoryRules) Validate() error {
|
||||
if r.StopWeightRatio != 2 || !finiteRange(r.SlowdownExponent, 1, 4) || !finiteRange(r.BreakdownBase, 0, 100) || !finiteRange(r.BreakdownMax, r.BreakdownBase, 99) || !finiteRange(r.BreakdownLevelScale, 1, 1000) || r.RecipeChance != .01 || !finiteRange(r.ActionCooldown, .1, 30) {
|
||||
return fmt.Errorf("invalid inventory rules")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -153,6 +153,11 @@ func (w *World) attack(c *Character, target string) error {
|
||||
return errors.New("area effect limit reached")
|
||||
}
|
||||
power := c.View.Stats[a.Stat].Final * a.Multiplier
|
||||
// Coatings add damage to this weapon attack, so they use the same server
|
||||
// collision, defence and credit rules. Spells do not inherit weapon coatings.
|
||||
if i := ownedItem(c, c.View.Equipment["weapon"]); a.Effect == "damage" && i != nil && i.Coating != nil && i.Coating.ExpiresAt > float64(w.now.UnixMilli())/1000 {
|
||||
power += i.Coating.Damage
|
||||
}
|
||||
if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
power *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
|
||||
@@ -42,6 +42,9 @@ func (w *World) refreshCrafting(c *Character) {
|
||||
}
|
||||
}
|
||||
func (w *World) restoreCrafting(c *Character) error {
|
||||
if !finiteCraft(c.ItemReadyAt) {
|
||||
return errors.New("invalid item cooldown")
|
||||
}
|
||||
if len(c.View.Crafting) > 64 || len(c.View.DiscoveredRecipes) > 512 || math.IsNaN(c.CraftReadyAt) || math.IsInf(c.CraftReadyAt, 0) || c.CraftReadyAt < 0 {
|
||||
return errors.New("invalid crafting history")
|
||||
}
|
||||
|
||||
@@ -133,6 +133,11 @@ func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemIns
|
||||
}
|
||||
func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
for _, item := range items {
|
||||
if v := item.Coating; v != nil {
|
||||
if item.Slot != "weapon" || item.HouseID != nil || item.Furniture != nil || v.Name == "" || len(v.Name) > 100 || v.Source == "" || len(v.Source) > 100 || !finiteCraft(v.ExpiresAt) || v.ExpiresAt <= 0 || !finiteCraft(v.Damage) || v.Damage <= 0 || v.Damage > 10000 {
|
||||
return errors.New("invalid weapon coating")
|
||||
}
|
||||
}
|
||||
if item.Provenance != nil && !validProvenance(*item.Provenance) {
|
||||
return errors.New("invalid equipment provenance")
|
||||
}
|
||||
@@ -281,14 +286,16 @@ func (w *World) equip(c *Character, itemID, slot string) error {
|
||||
if c.View.Equipment == nil {
|
||||
c.View.Equipment = map[string]string{}
|
||||
}
|
||||
if c.View.Equipment[slot] != "" {
|
||||
return errors.New("unequip the occupied slot first")
|
||||
}
|
||||
for _, id := range c.View.Equipment {
|
||||
for equippedSlot, id := range c.View.Equipment {
|
||||
if id == itemID {
|
||||
return errors.New("item is already equipped")
|
||||
if equippedSlot == slot {
|
||||
return nil
|
||||
}
|
||||
delete(c.View.Equipment, equippedSlot)
|
||||
}
|
||||
}
|
||||
// Both items remain owned. The displaced item is already in Items and returns
|
||||
// to the bag when its equipment assignment is replaced.
|
||||
c.View.Equipment[slot] = itemID
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
|
||||
@@ -46,8 +46,8 @@ func TestEquipmentSlotsAndRequirements(t *testing.T) {
|
||||
if w.equip(c, "missing", "weapon") == nil || w.equip(c, "slot_ring1", "ring9") == nil {
|
||||
t.Fatal("invalid ownership/slot accepted")
|
||||
}
|
||||
if w.equip(c, "slot_ring1", "ring2") == nil {
|
||||
t.Fatal("same instance equipped twice")
|
||||
if w.equip(c, "slot_ring1", "ring2") != nil || c.View.Equipment["ring1"] != "" || c.View.Equipment["ring2"] != "slot_ring1" || ownedItem(c, "slot_ring2") == nil {
|
||||
t.Fatal("ring swap duplicated assignment or lost displaced item")
|
||||
}
|
||||
if err := w.unequip(c, "helmet"); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -121,7 +121,11 @@ func (w *World) refreshGathering(c *Character) {
|
||||
for _, v := range w.Balance.Gathering.Consumables {
|
||||
if c.View.Inventory[v.ID] > 0 {
|
||||
c.View.StackNames[v.ID] = v.Name
|
||||
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
|
||||
var effect *p.ItemUseEffect
|
||||
if v.UseEffect != nil {
|
||||
effect = &p.ItemUseEffect{Kind: v.UseEffect.Kind, Amount: v.UseEffect.Amount}
|
||||
}
|
||||
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers), UseEffect: effect})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,6 +251,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
}
|
||||
for _, v := range w.Balance.Gathering.Consumables {
|
||||
if v.ID == id {
|
||||
if v.UseEffect != nil {
|
||||
return errors.New("use this item through its targeted item action")
|
||||
}
|
||||
if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) {
|
||||
return errors.New("too many active gathering effects")
|
||||
}
|
||||
@@ -261,6 +268,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
return errors.New("unknown gathering consumable")
|
||||
}
|
||||
func (w *World) jump(c *Character) error {
|
||||
if w.EncumbranceFactor(c) == 0 {
|
||||
return errors.New("too encumbered to jump")
|
||||
}
|
||||
ground := w.floorAt(c.View.Entity.Position.X, c.View.Entity.Position.Z, c.View.Entity.Position.Y)
|
||||
if c.JumpVelocity != 0 || c.View.Entity.Position.Y > ground+0.05 {
|
||||
return errors.New("already airborne")
|
||||
|
||||
@@ -76,6 +76,9 @@ func (w *World) houseIntent(c *Character, i p.Intent) error {
|
||||
c.LastMove = w.now
|
||||
return nil
|
||||
case "jump":
|
||||
if w.EncumbranceFactor(c) == 0 {
|
||||
return errors.New("too encumbered to jump")
|
||||
}
|
||||
if math.Abs(c.View.HousePosition.Y-roomGround(c.HouseRoom, *c.View.HousePosition)) > .02 || c.JumpVelocity != 0 {
|
||||
return errors.New("already jumping")
|
||||
}
|
||||
@@ -94,8 +97,9 @@ func (w *World) moveHouse(c *Character, dt float64) {
|
||||
old := *c.View.HousePosition
|
||||
pos := old
|
||||
r := w.Balance.Housing
|
||||
speed := r.WalkSpeed * w.EncumbranceFactor(c)
|
||||
// Small substeps prevent tunneling through narrow furniture on a delayed tick.
|
||||
steps := max(1, int(math.Ceil(dt*r.WalkSpeed/.1)))
|
||||
steps := max(1, int(math.Ceil(dt*speed/.1)))
|
||||
step := dt / float64(steps)
|
||||
for range steps {
|
||||
if c.JumpVelocity != 0 || pos.Y > roomGround(room, pos) {
|
||||
@@ -108,12 +112,12 @@ func (w *World) moveHouse(c *Character, dt float64) {
|
||||
c.JumpVelocity = math.Min(0, c.JumpVelocity)
|
||||
}
|
||||
next := pos
|
||||
next.X += c.MoveX * r.WalkSpeed * step
|
||||
next.X += c.MoveX * speed * step
|
||||
if w.HousePositionValid(room, next) {
|
||||
pos.X = next.X
|
||||
}
|
||||
next = pos
|
||||
next.Z += c.MoveZ * r.WalkSpeed * step
|
||||
next.Z += c.MoveZ * speed * step
|
||||
if w.HousePositionValid(room, next) {
|
||||
pos.Z = next.Z
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ValidItemAction(r p.ItemActionRequest) bool {
|
||||
return len(r.ID) >= 32 && len(r.ID) <= 36 && strings.Trim(r.ID, "0123456789abcdef-") == "" && len(r.CharacterID) == 32 && strings.Trim(r.CharacterID, "0123456789abcdef") == "" && len(r.Item) > 0 && len(r.Item) <= 100 && len(r.Target) <= 100 && len(r.Slot) <= 64 && r.Quantity >= 1 && r.Quantity <= 1000 && slices.Contains([]string{"equip", "destroy", "breakdown", "consume", "use"}, r.Op)
|
||||
}
|
||||
|
||||
// Invoked only on a staged world; the store commits the result and replay receipt
|
||||
// together before returning it to the browser.
|
||||
func (w *World) ItemAction(c *Character, r p.ItemActionRequest) (p.ItemActionResult, error) {
|
||||
out := p.ItemActionResult{ID: r.ID, Returned: map[string]int64{}}
|
||||
if !ValidItemAction(r) || c == nil || c.View.Entity.ID != r.CharacterID || !c.Online || c.Sheltered || HouseID(c) != "" || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
return out, errors.New("character cannot use items")
|
||||
}
|
||||
now := float64(w.now.UnixMilli()) / 1000
|
||||
if now < c.ItemReadyAt {
|
||||
return out, errors.New("item action cooldown")
|
||||
}
|
||||
item := ownedItem(c, r.Item)
|
||||
if item == nil && c.View.Inventory[r.Item] < r.Quantity {
|
||||
return out, errors.New("item not owned in that quantity")
|
||||
}
|
||||
if item != nil && r.Quantity != 1 {
|
||||
return out, errors.New("equipment actions require one instance")
|
||||
}
|
||||
if r.Op != "use" && r.Target != "" || r.Op != "equip" && r.Slot != "" {
|
||||
return out, errors.New("unexpected item target or slot")
|
||||
}
|
||||
var err error
|
||||
switch r.Op {
|
||||
case "equip":
|
||||
if r.Quantity != 1 {
|
||||
return out, errors.New("equip one item")
|
||||
}
|
||||
err = w.equip(c, r.Item, r.Slot)
|
||||
out.Message = "Equipment updated"
|
||||
case "destroy":
|
||||
if item != nil {
|
||||
if item.HouseID != nil {
|
||||
return out, errors.New("house keys require the three-second key destruction action")
|
||||
}
|
||||
w.removeOwnedItem(c, item.ID)
|
||||
} else {
|
||||
TakeStack(c, r.Item, r.Quantity)
|
||||
}
|
||||
out.Message = "Item destroyed"
|
||||
case "breakdown":
|
||||
if item == nil {
|
||||
return out, errors.New("only equipment can be broken down")
|
||||
}
|
||||
err = w.breakdown(c, *item, &out)
|
||||
case "consume", "use":
|
||||
if r.Quantity != 1 {
|
||||
return out, errors.New("use one item at a time")
|
||||
}
|
||||
err = w.useItem(c, r.Item, r.Target, r.Op == "consume")
|
||||
out.Message = "Item used"
|
||||
}
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
c.ItemReadyAt = now + w.Balance.Inventory.ActionCooldown
|
||||
w.RefreshStats(c)
|
||||
c.Message = out.Message
|
||||
w.dirty = true
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (w *World) removeOwnedItem(c *Character, id string) {
|
||||
c.View.Items = slices.DeleteFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id })
|
||||
for slot, item := range c.View.Equipment {
|
||||
if item == id {
|
||||
delete(c.View.Equipment, slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *World) breakdownRecipe(item p.ItemInstance) *content.CraftRecipe {
|
||||
if item.HouseID != nil || item.Furniture != nil || w.Balance.Crafting == nil {
|
||||
return nil
|
||||
}
|
||||
if item.Provenance != nil {
|
||||
for _, list := range [][]content.CraftRecipe{w.Balance.Crafting.Recipes, w.Balance.Crafting.RecipeHistory} {
|
||||
for _, r := range list {
|
||||
if r.ID == item.Provenance.RecipeID && r.Revision == item.Provenance.RecipeRevision && r.Outputs[item.DefinitionID] > 0 {
|
||||
copy := r
|
||||
return ©
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil // Never substitute a later recipe revision for the original.
|
||||
}
|
||||
var found *content.CraftRecipe
|
||||
for _, r := range w.Balance.Crafting.Recipes {
|
||||
if r.Outputs[item.DefinitionID] > 0 {
|
||||
if found != nil {
|
||||
return nil
|
||||
}
|
||||
copy := r
|
||||
found = ©
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (w *World) breakdown(c *Character, item p.ItemInstance, out *p.ItemActionResult) error {
|
||||
r := w.breakdownRecipe(item)
|
||||
if r == nil {
|
||||
return errors.New("no unambiguous original recipe is available for this item")
|
||||
}
|
||||
profession := r.Profession
|
||||
if item.Slot == "weapon" {
|
||||
profession = "weapon_smithing"
|
||||
} else if slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "cape"}, item.Slot) {
|
||||
profession = "armor_making"
|
||||
}
|
||||
w.refreshCrafting(c)
|
||||
level := c.View.Crafting[profession].Level
|
||||
if level < 1 {
|
||||
return errors.New("breakdown profession unavailable")
|
||||
}
|
||||
rules := w.Balance.Inventory
|
||||
gap := float64(level - max(r.Level, item.Requirements.Level))
|
||||
rate := rules.BreakdownBase
|
||||
if gap < 0 {
|
||||
rate *= math.Exp(gap / rules.BreakdownLevelScale)
|
||||
} else {
|
||||
rate += (rules.BreakdownMax - rate) * (1 - math.Exp(-gap/rules.BreakdownLevelScale))
|
||||
}
|
||||
units := int64(0)
|
||||
for _, n := range r.Outputs {
|
||||
units += n
|
||||
}
|
||||
if units < 1 {
|
||||
return errors.New("invalid original recipe")
|
||||
}
|
||||
for id, n := range r.Inputs {
|
||||
// Divide by the complete output batch: breaking down each output cannot
|
||||
// multiply the batch's inputs. Return material stacks only.
|
||||
if slices.ContainsFunc(w.Balance.Items, func(i content.ItemDefinition) bool { return i.ID == id }) {
|
||||
return errors.New("equipment ingredients cannot be recovered by breakdown")
|
||||
}
|
||||
amount := int64(math.Floor(float64(n) * rate / 100 / float64(units)))
|
||||
if amount > 0 {
|
||||
if c.View.Inventory[id] > math.MaxInt64-amount {
|
||||
return errors.New("inventory overflow")
|
||||
}
|
||||
out.Returned[id] = amount
|
||||
}
|
||||
}
|
||||
if len(c.View.DiscoveredRecipes) >= 512 {
|
||||
if _, ok := c.View.DiscoveredRecipes[r.ID]; !ok {
|
||||
return errors.New("recipe discovery capacity reached")
|
||||
}
|
||||
}
|
||||
w.removeOwnedItem(c, item.ID)
|
||||
for id, n := range out.Returned {
|
||||
c.View.Inventory[id] += n
|
||||
}
|
||||
if w.roll(rules.RecipeChance) {
|
||||
old, known := c.View.DiscoveredRecipes[r.ID]
|
||||
if !known || old.Recipe.Revision < r.Revision {
|
||||
raw, _ := json.Marshal(r)
|
||||
var recipe p.CraftRecipe
|
||||
_ = json.Unmarshal(raw, &recipe)
|
||||
d := p.KnownRecipe{Recipe: recipe, DiscoveredAt: float64(w.now.UnixMilli()) / 1000}
|
||||
c.View.DiscoveredRecipes[r.ID] = d
|
||||
out.Recipe = &d
|
||||
}
|
||||
}
|
||||
out.Message = fmt.Sprintf("Broke down %s (%.1f%% recovery, rounded down)", item.Name, rate)
|
||||
if out.Recipe != nil {
|
||||
out.Message += "; recipe discovered"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *World) useItem(c *Character, id, target string, consume bool) error {
|
||||
if target == "" || consume {
|
||||
target = c.View.Entity.ID
|
||||
}
|
||||
if c.View.Inventory[id] < 1 {
|
||||
return errors.New("this item has no supported use effect")
|
||||
}
|
||||
healing := float64(0)
|
||||
if id == "bandage" {
|
||||
healing = w.Balance.BandageHealing
|
||||
}
|
||||
for _, definition := range w.Balance.Gathering.Consumables {
|
||||
if definition.ID != id || definition.UseEffect == nil {
|
||||
continue
|
||||
}
|
||||
effect := definition.UseEffect
|
||||
if effect.Kind == "heal" {
|
||||
healing = effect.Amount
|
||||
}
|
||||
if effect.Kind == "weapon-coating" {
|
||||
weapon := ownedItem(c, target)
|
||||
if consume || weapon == nil || weapon.Slot != "weapon" || weapon.Furniture != nil || weapon.HouseID != nil || (weapon.Attack != nil && weapon.Attack.Effect != "damage") {
|
||||
return errors.New("select one of your damage weapons to apply this coating")
|
||||
}
|
||||
TakeStack(c, id, 1)
|
||||
weapon.Coating = &p.WeaponCoating{Source: id, Name: definition.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + definition.Seconds, Damage: effect.Amount}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if healing > 0 {
|
||||
var entity *p.Entity
|
||||
if other := w.Characters[target]; other != nil && other.Online && !other.Sheltered && HouseID(other) == "" && other.View.Entity.State == "alive" {
|
||||
entity = &other.View.Entity
|
||||
}
|
||||
if mob := w.Mobs[target]; mob != nil && mob.Entity.HP > 0 && !w.IsHub() {
|
||||
entity = &mob.Entity
|
||||
}
|
||||
if entity == nil || entity.HP >= entity.MaxHP {
|
||||
return errors.New("target cannot be healed")
|
||||
}
|
||||
if length3(body(c.View.Entity.Position), body(entity.Position)) > w.Balance.GatherRange {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
if _, blocked := w.combatLine(body(c.View.Entity.Position), body(entity.Position), ""); blocked {
|
||||
return errors.New("target obstructed")
|
||||
}
|
||||
TakeStack(c, id, 1)
|
||||
entity.HP = math.Min(entity.MaxHP, entity.HP+healing)
|
||||
return nil
|
||||
}
|
||||
if target != c.View.Entity.ID {
|
||||
return errors.New("this item can only be used on yourself")
|
||||
}
|
||||
return w.consumeGathering(c, id)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func itemRequest(c *Character, op, item string) p.ItemActionRequest {
|
||||
return p.ItemActionRequest{ID: ID(), CharacterID: c.View.Entity.ID, Op: op, Item: item, Quantity: 1}
|
||||
}
|
||||
|
||||
func TestDestroyConsumesCraftedStackWithoutLosingRemainingProvenance(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: "recipe_bandage", RecipeRevision: 1, Profession: "alchemist", Level: 1}
|
||||
c.View.Inventory["bandage"] = 3
|
||||
c.View.CraftedStacks = []p.CraftedStack{{ID: ID(), Item: "bandage", Quantity: 3, Provenance: provenance}}
|
||||
req := itemRequest(c, "destroy", "bandage")
|
||||
req.Quantity = 2
|
||||
for _, mode := range []string{"offline", "sheltered", "dead", "capped"} {
|
||||
c.Online = true
|
||||
c.Sheltered = false
|
||||
c.View.Entity.State = "alive"
|
||||
c.View.RemainingSeconds = 100
|
||||
switch mode {
|
||||
case "offline":
|
||||
c.Online = false
|
||||
case "sheltered":
|
||||
c.Sheltered = true
|
||||
case "dead":
|
||||
c.View.Entity.State = "dead"
|
||||
case "capped":
|
||||
c.View.RemainingSeconds = 0
|
||||
}
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 3 {
|
||||
t.Fatalf("accepted %s destruction", mode)
|
||||
}
|
||||
}
|
||||
c.Online = true
|
||||
c.Sheltered = false
|
||||
c.View.Entity.State = "alive"
|
||||
c.View.RemainingSeconds = 100
|
||||
if _, err := w.ItemAction(c, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["bandage"] != 1 || len(c.View.CraftedStacks) != 1 || c.View.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Provenance != provenance {
|
||||
t.Fatal("destroy corrupted retained crafted stack")
|
||||
}
|
||||
req = itemRequest(c, "destroy", "bandage")
|
||||
req.Quantity = 2
|
||||
c.ItemReadyAt = 0
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 1 {
|
||||
t.Fatal("destroyed more than owned")
|
||||
}
|
||||
w.Balance.Inventory = nil
|
||||
raw, _ := json.Marshal(w)
|
||||
var old World
|
||||
_ = json.Unmarshal(raw, &old)
|
||||
if err := old.Restore(w.now); err != nil || old.Balance.Inventory == nil || old.Balance.Inventory.StopWeightRatio != 2 {
|
||||
t.Fatal("old snapshot missing inventory migration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncumbranceMovementRecoveryAndVictory(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Items = nil
|
||||
w.RefreshStats(c)
|
||||
capacity := c.View.Stats["carryCapacity"].Final
|
||||
for _, tt := range []struct{ ratio, factor float64 }{{0, 1}, {1, 1}, {1.1, .99}, {1.5, .75}, {2, 0}, {3, 0}} {
|
||||
item := testGear("weight", "helmet")
|
||||
item.Weight = capacity * tt.ratio
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
w.RefreshStats(c)
|
||||
if math.Abs(w.playerSpeed(c)/c.View.Stats["moveSpeed"].Final-tt.factor) > 1e-8 || math.Abs(*c.View.MovementFactor-tt.factor) > 1e-8 {
|
||||
t.Fatalf("wrong movement at %.1fx capacity", tt.ratio)
|
||||
}
|
||||
}
|
||||
before := c.View.Entity.Position
|
||||
c.MoveX = 1
|
||||
w.moveCharacter(c, .1)
|
||||
if c.View.Entity.Position.X != before.X || w.jump(c) == nil {
|
||||
t.Fatal("immobilized player moved or jumped")
|
||||
}
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
house := ID()
|
||||
pos := p.Vec3{}
|
||||
c.View.HouseID = &house
|
||||
c.View.HousePosition = &pos
|
||||
c.HouseRoom = &p.HouseScene{ID: house, Size: 20}
|
||||
c.LastMove = w.now
|
||||
w.moveHouse(c, .1)
|
||||
if c.View.HousePosition.X != 0 || w.houseIntent(c, p.Intent{Op: "jump"}) == nil {
|
||||
t.Fatal("house bypassed encumbrance")
|
||||
}
|
||||
c.View.HouseID = nil
|
||||
c.View.HousePosition = nil
|
||||
c.HouseRoom = nil
|
||||
w.Kind = "survival"
|
||||
w.Phase = "won"
|
||||
c.View.Entity.State = "eligible"
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Seq: 1, Op: "drop", Target: "weight"}); err != nil {
|
||||
t.Fatal("winner cannot shed weight to reach portal", err)
|
||||
}
|
||||
if w.EncumbranceFactor(c) != 1 {
|
||||
t.Fatal("dropping weight did not restore movement")
|
||||
}
|
||||
}
|
||||
|
||||
func TestItemActionsRejectWithoutConsumptionAndHealTargets(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory["bandage"] = 5
|
||||
other, err := w.Join("other", "Other")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(other.View.Entity.ID)
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
other.View.Entity.HP = 1
|
||||
req := itemRequest(c, "use", "bandage")
|
||||
req.Target = other.View.Entity.ID
|
||||
for _, mode := range []string{"far", "dead", "sheltered", "house", "full"} {
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
other.View.Entity.State = "alive"
|
||||
other.Sheltered = false
|
||||
other.View.HouseID = nil
|
||||
other.View.Entity.HP = 1
|
||||
switch mode {
|
||||
case "far":
|
||||
other.View.Entity.Position.X += 100
|
||||
case "dead":
|
||||
other.View.Entity.State = "dead"
|
||||
case "sheltered":
|
||||
other.Sheltered = true
|
||||
case "house":
|
||||
other.View.HouseID = stringPtr(ID())
|
||||
case "full":
|
||||
other.View.Entity.HP = other.View.Entity.MaxHP
|
||||
}
|
||||
if _, err = w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 5 {
|
||||
t.Fatalf("accepted invalid healing target %s", mode)
|
||||
}
|
||||
}
|
||||
other.View.Entity.HP = 1
|
||||
if _, err = w.ItemAction(c, req); err != nil || other.View.Entity.HP != math.Min(other.View.Entity.MaxHP, 1+w.Balance.BandageHealing) || c.View.Inventory["bandage"] != 4 {
|
||||
t.Fatal("targeted healing failed", err)
|
||||
}
|
||||
if _, err = w.ItemAction(c, req); err == nil {
|
||||
t.Fatal("item cooldown bypassed")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
mob := &Mob{Entity: p.Entity{ID: "heal-target", Kind: "mob", State: "alive", HP: 1, MaxHP: 100, Position: c.View.Entity.Position}}
|
||||
w.Mobs[mob.Entity.ID] = mob
|
||||
req.Target = mob.Entity.ID
|
||||
if _, err = w.ItemAction(c, req); err != nil || mob.Entity.HP <= 1 {
|
||||
t.Fatal("mob healing failed", err)
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
key := testGear("key", "bag")
|
||||
key.HouseID = stringPtr(ID())
|
||||
c.View.Items = append(c.View.Items, key)
|
||||
if _, err = w.ItemAction(c, itemRequest(c, "destroy", key.ID)); err == nil || ownedItem(c, key.ID) == nil {
|
||||
t.Fatal("generic destruction bypassed key timer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBreakdownOriginalRecipeBatchAndDiscovery(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory = map[string]int64{}
|
||||
old := content.CraftRecipe{ID: "original", Revision: 1, Name: "Old spear", Profession: "weapon_smithing", Level: 1, XP: 20, Inputs: map[string]int64{"wood": 100, "ore": 20}, Outputs: map[string]int64{"spear": 2}}
|
||||
current := old
|
||||
current.Revision = 2
|
||||
current.Inputs = map[string]int64{"herb": 100}
|
||||
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
|
||||
w.Balance.Crafting.Recipes = []content.CraftRecipe{current}
|
||||
item := testGear("old-spear", "weapon")
|
||||
item.DefinitionID = "spear"
|
||||
item.Provenance = &p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, Profession: old.Profession, Level: 1, RecipeID: old.ID, RecipeRevision: 1}
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
|
||||
// Find a deterministic success for the actual 0.01% boundary, not a modified rule.
|
||||
for w.randomUnit() >= .0001 {
|
||||
}
|
||||
w.RandomCounter--
|
||||
result, err := w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
|
||||
if err != nil || c.View.Inventory["wood"] != 12 || c.View.Inventory["ore"] != 2 || c.View.Inventory["herb"] != 0 || len(c.View.Items) != 0 {
|
||||
t.Fatal("breakdown did not use original recipe divided by output batch", result, err)
|
||||
}
|
||||
if result.Recipe == nil || result.Recipe.Recipe.Revision != 1 || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != 0 {
|
||||
t.Fatal("wrong discovery or unexpected experience")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
w.Balance.Crafting.RecipeHistory = nil
|
||||
if _, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID)); err == nil || len(c.View.Items) != 1 {
|
||||
t.Fatal("missing historical recipe substituted current revision")
|
||||
}
|
||||
// In a hub, high crafting skill raises recovery but never awards XP.
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
|
||||
cp := c.View.Crafting["weapon_smithing"]
|
||||
cp.XP = 1000000
|
||||
c.View.Crafting[cp.ID] = cp
|
||||
result, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
|
||||
if err != nil || result.Returned["wood"] <= 12 || result.Returned["wood"] >= 38 || c.View.Crafting[cp.ID].XP != cp.XP {
|
||||
t.Fatal("higher skill recovery or hub XP changed", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumableCoatingOwnershipExpiryAndRestore(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
definition := content.GatheringConsumable{ID: "poison", Name: "Weapon poison", Seconds: 10, UseEffect: &content.ItemUseEffect{Kind: "weapon-coating", Amount: 7}}
|
||||
w.Balance.Gathering.Consumables = append(w.Balance.Gathering.Consumables, definition)
|
||||
c.View.Inventory[definition.ID] = 2
|
||||
weapon := testGear("coated", "weapon")
|
||||
c.View.Items = append(c.View.Items, weapon)
|
||||
req := itemRequest(c, "use", definition.ID)
|
||||
req.Target = "not-owned"
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory[definition.ID] != 2 {
|
||||
t.Fatal("coated unowned weapon")
|
||||
}
|
||||
req.Target = weapon.ID
|
||||
if _, err := w.ItemAction(c, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
coating := ownedItem(c, weapon.ID).Coating
|
||||
if coating == nil || coating.Damage != 7 || c.View.Inventory[definition.ID] != 1 {
|
||||
t.Fatal("coating was not copied onto exact item")
|
||||
}
|
||||
if err := w.consumeGathering(c, definition.ID); err == nil {
|
||||
t.Fatal("legacy consume bypassed target requirement")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
_ = json.Unmarshal(raw, &restored)
|
||||
if err := restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(ownedItem(restored.Characters[c.View.Entity.ID], weapon.ID).Coating, coating) {
|
||||
t.Fatal("restore lost coating")
|
||||
}
|
||||
_ = w.equip(c, weapon.ID, "weapon")
|
||||
w.Balance.CriticalMultiplier = 1
|
||||
mob := &Mob{Entity: p.Entity{ID: "damage-target", Kind: "mob", State: "alive", HP: 1000, MaxHP: 1000, Position: c.View.Entity.Position}}
|
||||
w.Mobs[mob.Entity.ID] = mob
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
if err := w.attack(c, mob.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
coatedDamage := 1000 - mob.Entity.HP
|
||||
w.now = w.now.Add(20 * time.Second)
|
||||
mob.Entity.HP = 1000
|
||||
if err := w.attack(c, mob.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
normalDamage := 1000 - mob.Entity.HP
|
||||
if math.Abs(coatedDamage-normalDamage-7) > 1e-8 {
|
||||
t.Fatal("coating damage did not expire", coatedDamage, normalDamage)
|
||||
}
|
||||
}
|
||||
@@ -198,5 +198,18 @@ func (c *Character) titleEffects() p.TitleEffects {
|
||||
}
|
||||
|
||||
func (w *World) playerSpeed(c *Character) float64 {
|
||||
return c.View.Stats["moveSpeed"].Final
|
||||
return c.View.Stats["moveSpeed"].Final * w.EncumbranceFactor(c)
|
||||
}
|
||||
|
||||
// Apply after all speed/capacity modifiers, so gear cannot override immobilization.
|
||||
func (w *World) EncumbranceFactor(c *Character) float64 {
|
||||
capacity, weight := c.View.Stats["carryCapacity"].Final, c.View.CarryWeight
|
||||
if weight <= capacity {
|
||||
return 1
|
||||
}
|
||||
if capacity <= 0 {
|
||||
return 0
|
||||
}
|
||||
excess := (weight/capacity - 1) / (w.Balance.Inventory.StopWeightRatio - 1)
|
||||
return math.Max(0, 1-math.Pow(excess, w.Balance.Inventory.SlowdownExponent))
|
||||
}
|
||||
|
||||
@@ -105,6 +105,8 @@ func (w *World) RefreshStats(c *Character) {
|
||||
for _, n := range c.View.Inventory {
|
||||
c.View.CarryWeight += float64(n)
|
||||
}
|
||||
factor := w.EncumbranceFactor(c)
|
||||
c.View.MovementFactor = &factor
|
||||
}
|
||||
func (w *World) initializeStats(c *Character) error {
|
||||
newResources := c.View.Stats == nil
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
ItemReadyAt float64 `json:"itemReadyAt"`
|
||||
HouseRoom *p.HouseScene `json:"-"`
|
||||
XPCurveVersion int `json:"xpCurveVersion"`
|
||||
PendingCast *PendingCast `json:"pendingCast,omitempty"`
|
||||
@@ -124,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.Inventory == nil {
|
||||
defaults, err := content.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.Inventory = defaults.Inventory
|
||||
w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Inventory.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.Kind == "" {
|
||||
w.Kind = "survival"
|
||||
}
|
||||
@@ -533,7 +545,7 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" {
|
||||
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" && i.Op != "drop" {
|
||||
return errors.New("use the victory portal to continue")
|
||||
}
|
||||
if w.IsHub() && (i.Op == "attack" || i.Op == "gather") {
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
package protocol
|
||||
|
||||
type Protocol struct {
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
|
||||
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
|
||||
CatalogResult *ContentResult `json:"catalogResult,omitempty"`
|
||||
CraftRequest *CraftRequest `json:"craftRequest,omitempty"`
|
||||
CraftResult *CraftResult `json:"craftResult,omitempty"`
|
||||
HouseRequest *HouseRequest `json:"houseRequest,omitempty"`
|
||||
HouseState *HouseState `json:"houseState,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
|
||||
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
|
||||
CatalogResult *ContentResult `json:"catalogResult,omitempty"`
|
||||
CraftRequest *CraftRequest `json:"craftRequest,omitempty"`
|
||||
CraftResult *CraftResult `json:"craftResult,omitempty"`
|
||||
HouseRequest *HouseRequest `json:"houseRequest,omitempty"`
|
||||
HouseState *HouseState `json:"houseState,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
ItemActionRequest *ItemActionRequest `json:"itemActionRequest,omitempty"`
|
||||
ItemActionResult *ItemActionResult `json:"itemActionResult,omitempty"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
@@ -125,10 +127,11 @@ type MobSpawn struct {
|
||||
}
|
||||
|
||||
type CraftingContent struct {
|
||||
Materials []CraftMaterial `json:"materials"`
|
||||
Professions []GatheringSkill `json:"professions"`
|
||||
Recipes []CraftRecipe `json:"recipes"`
|
||||
Rules CraftRules `json:"rules"`
|
||||
Materials []CraftMaterial `json:"materials"`
|
||||
Professions []GatheringSkill `json:"professions"`
|
||||
RecipeHistory []CraftRecipe `json:"recipeHistory,omitempty"`
|
||||
Recipes []CraftRecipe `json:"recipes"`
|
||||
Rules CraftRules `json:"rules"`
|
||||
}
|
||||
|
||||
type CraftMaterial struct {
|
||||
@@ -212,6 +215,12 @@ type GatheringConsumable struct {
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
UseEffect *ItemUseEffect `json:"useEffect,omitempty"`
|
||||
}
|
||||
|
||||
type ItemUseEffect struct {
|
||||
Amount float64 `json:"amount"`
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
|
||||
type ResourceDefinition struct {
|
||||
@@ -409,6 +418,7 @@ type GatheringConsumableDraft struct {
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
UseEffect *ItemUseEffect `json:"useEffect,omitempty"`
|
||||
}
|
||||
|
||||
type CraftMaterialDraft struct {
|
||||
@@ -688,6 +698,7 @@ type CraftProvenance struct {
|
||||
|
||||
type ItemInstance struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
Coating *WeaponCoating `json:"coating,omitempty"`
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
@@ -704,6 +715,13 @@ type ItemInstance struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type WeaponCoating struct {
|
||||
Damage float64 `json:"damage"`
|
||||
ExpiresAt float64 `json:"expiresAt"`
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
type HouseFurniture struct {
|
||||
Contents HouseInventory `json:"contents"`
|
||||
Item ItemInstance `json:"item"`
|
||||
@@ -720,6 +738,23 @@ type Intent struct {
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type ItemActionRequest struct {
|
||||
CharacterID string `json:"characterId"`
|
||||
ID string `json:"id"`
|
||||
Item string `json:"item"`
|
||||
Op string `json:"op"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
Slot string `json:"slot"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
type ItemActionResult struct {
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
Recipe *KnownRecipe `json:"recipe,omitempty"`
|
||||
Returned map[string]int64 `json:"returned"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
ChunkKeys []string `json:"chunkKeys"`
|
||||
Chunks []Chunk `json:"chunks"`
|
||||
@@ -815,6 +850,7 @@ type Character struct {
|
||||
Level int64 `json:"level"`
|
||||
Mana float64 `json:"mana"`
|
||||
ManaChoices int64 `json:"manaChoices"`
|
||||
MovementFactor *float64 `json:"movementFactor,omitempty"`
|
||||
PendingVitalChoices int64 `json:"pendingVitalChoices"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
Powers map[string]LearnedPower `json:"powers,omitempty"`
|
||||
|
||||
@@ -186,6 +186,7 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
|
||||
}
|
||||
v.ID = c.Crafting.Recipes[i].ID
|
||||
v.Revision = c.Crafting.Recipes[i].Revision + 1
|
||||
c.Crafting.RecipeHistory = append(slices.Clone(c.Crafting.RecipeHistory), c.Crafting.Recipes[i])
|
||||
c.Crafting.Recipes = slices.Clone(c.Crafting.Recipes)
|
||||
c.Crafting.Recipes[i] = v
|
||||
} else {
|
||||
|
||||
@@ -208,6 +208,9 @@ func TestCraftRecipeRevision(t *testing.T) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got := revised.Crafting.Recipes[len(revised.Crafting.Recipes)-1]
|
||||
if len(revised.Crafting.RecipeHistory) != 1 || !reflect.DeepEqual(revised.Crafting.RecipeHistory[0], made) || len(firstCatalog.Crafting.RecipeHistory) != 0 {
|
||||
t.Fatal("recipe publication lost the immutable salvage revision or mutated the old catalog")
|
||||
}
|
||||
if got.ID != made.ID || got.Revision != 2 || len(revised.Crafting.Recipes) != len(firstCatalog.Crafting.Recipes) || made.Inputs["wood"] != 5 {
|
||||
t.Fatal("revision duplicated identity or mutated prior version")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var ErrItemAction = errors.New("item action rejected")
|
||||
|
||||
// Namespaced IDs share the existing durable action receipt transaction without
|
||||
// colliding with crafting attempts. Store full requests to reject changed retries.
|
||||
func (l *Lease) ItemAction(ctx context.Context, live *game.World, account string, req p.ItemActionRequest) (p.ItemActionResult, error) {
|
||||
fail := func(message string) (p.ItemActionResult, error) {
|
||||
return p.ItemActionResult{}, fmt.Errorf("%w: %s", ErrItemAction, message)
|
||||
}
|
||||
if !game.ValidItemAction(req) {
|
||||
return fail("invalid request")
|
||||
}
|
||||
id := "item:" + req.ID
|
||||
request, _ := json.Marshal(req)
|
||||
var previous, resultJSON string
|
||||
err := l.DB.sql.QueryRowContext(ctx, l.DB.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, id).Scan(&previous, &resultJSON)
|
||||
if err == nil {
|
||||
if previous != string(request) {
|
||||
return fail("request ID already used for another action")
|
||||
}
|
||||
var result p.ItemActionResult
|
||||
err = json.Unmarshal([]byte(resultJSON), &result)
|
||||
return result, err
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
active, err := l.DB.ActiveCharacter(ctx, account)
|
||||
if err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
if active == nil || active.ID != req.CharacterID || active.WorldID != live.ID || active.State != "alive" {
|
||||
return fail("character is not active in this world")
|
||||
}
|
||||
original := live.Characters[req.CharacterID]
|
||||
if original == nil || original.Account != account {
|
||||
return fail("character unavailable")
|
||||
}
|
||||
staged := stageTitleWorld(live)
|
||||
for _, c := range staged.Characters {
|
||||
raw, err := json.Marshal(c.View)
|
||||
if err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
var view p.Character
|
||||
if err = json.Unmarshal(raw, &view); err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
c.View = view
|
||||
}
|
||||
staged.Mobs = make(map[string]*game.Mob, len(live.Mobs))
|
||||
for id, m := range live.Mobs {
|
||||
copy := *m
|
||||
staged.Mobs[id] = ©
|
||||
}
|
||||
result, err := staged.ItemAction(staged.Characters[req.CharacterID], req)
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{id, account, req.CharacterID, string(request), string(raw)}
|
||||
if err = l.save(ctx, staged, "", nil, "", receipt, nil, nil); err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
*live.Characters[id] = *c
|
||||
}
|
||||
live.Mobs = staged.Mobs
|
||||
live.RandomCounter = staged.RandomCounter
|
||||
live.PendingTitles = nil
|
||||
live.Saved()
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestItemActionDurability(t *testing.T) {
|
||||
testItemActionDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "items.db")))
|
||||
}
|
||||
func TestPostgresItemActionDurability(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testItemActionDurability(t, dsn)
|
||||
}
|
||||
func testItemActionDurability(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, err := content.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
w := game.New("items-"+game.ID(), 1, now, b)
|
||||
lease, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := w.Join("items-"+game.ID(), "Owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(c.View.Entity.ID)
|
||||
other, err := w.Join("target-"+game.ID(), "Target")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(other.View.Entity.ID)
|
||||
c.View.Inventory["bandage"] = 5
|
||||
other.View.Entity.HP = 1
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
if err = lease.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := p.ItemActionRequest{ID: game.ID(), CharacterID: c.View.Entity.ID, Op: "use", Item: "bandage", Target: other.View.Entity.ID, Quantity: 1}
|
||||
before, _ := json.Marshal(w)
|
||||
stale := *lease
|
||||
stale.Revision--
|
||||
if _, err = stale.ItemAction(ctx, w, c.Account, req); !errors.Is(err, ErrOwnership) {
|
||||
t.Fatal("stale item action not fenced", err)
|
||||
}
|
||||
after, _ := json.Marshal(w)
|
||||
if string(after) != string(before) {
|
||||
t.Fatal("failed save mutated acting player or healing target")
|
||||
}
|
||||
result, err := lease.ItemAction(ctx, w, c.Account, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["bandage"] != 4 || other.View.Entity.HP <= 1 || w.Characters[c.View.Entity.ID] != c {
|
||||
t.Fatal("saved result not published to live pointers")
|
||||
}
|
||||
committed, _ := json.Marshal(w)
|
||||
replay, err := lease.ItemAction(ctx, w, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("retry changed result", err)
|
||||
}
|
||||
after, _ = json.Marshal(w)
|
||||
if string(after) != string(committed) {
|
||||
t.Fatal("retry consumed or healed again")
|
||||
}
|
||||
changed := req
|
||||
changed.Quantity = 2
|
||||
if _, err = lease.ItemAction(ctx, w, c.Account, changed); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("changed request reused receipt", err)
|
||||
}
|
||||
if _, err = lease.ItemAction(ctx, w, other.Account, req); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("other account recovered receipt", err)
|
||||
}
|
||||
if err = lease.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored := game.New(w.ID, 1, now, b)
|
||||
lease, raw, err := db.Acquire(ctx, restored)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = json.Unmarshal(raw, restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c = restored.Characters[c.View.Entity.ID]
|
||||
other = restored.Characters[other.View.Entity.ID]
|
||||
if c.View.Inventory["bandage"] != 4 || other.View.Entity.HP <= 1 {
|
||||
t.Fatal("restart lost committed item action")
|
||||
}
|
||||
replay, err = lease.ItemAction(ctx, restored, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("restart lost receipt", err)
|
||||
}
|
||||
_ = restored.Connect(c.View.Entity.ID)
|
||||
c.ItemReadyAt = 0
|
||||
// A saved result remains a receipt after death; replay never reactivates a life.
|
||||
c.View.Entity.State = "dead"
|
||||
if err = lease.Save(ctx, restored, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err = lease.ItemAction(ctx, restored, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) || c.View.Entity.State != "dead" {
|
||||
t.Fatal("replay changed dead life", err)
|
||||
}
|
||||
changed = req
|
||||
changed.ID = game.ID()
|
||||
if _, err = lease.ItemAction(ctx, restored, c.Account, changed); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("dead life used new action", err)
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.portalRoutes(mux)
|
||||
h.travelRoutes(mux)
|
||||
h.craftingRoutes(mux)
|
||||
h.itemActionRoutes(mux)
|
||||
h.powerRoutes(mux)
|
||||
h.housingRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
|
||||
@@ -142,7 +142,7 @@ func TestHTTPAndSocketSecurity(t *testing.T) {
|
||||
t.Fatal("cross-origin crafting accepted")
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/api/revive", "/api/revival/consent"} {
|
||||
for _, path := range []string{"/api/revive", "/api/revival/consent", "/api/item-action"} {
|
||||
r := request(path, "https://evil.example", "{}", cookie)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 403 {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/internal/store"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *HTTP) itemActionRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/item-action", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req p.ItemActionRequest
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid item action")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if err = h.s.refreshCatalog(r.Context()); err != nil {
|
||||
fail(w, 503, "item catalog unavailable")
|
||||
return
|
||||
}
|
||||
result, err := h.s.lease.ItemAction(r.Context(), h.s.world, account, req)
|
||||
if errors.Is(err, store.ErrItemAction) {
|
||||
fail(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.s.ready.Store(false)
|
||||
for _, peer := range h.s.peers {
|
||||
peer.close()
|
||||
}
|
||||
fail(w, 503, "item save unavailable; retry the same action after reconnecting")
|
||||
return
|
||||
}
|
||||
respond(w, 200, result)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user