From e80064976a6726d8dc92856224026d6303c4bdac Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 9 Sep 2026 22:45:47 -0400 Subject: [PATCH] Add persistent destructible world structures and building kits --- client/src/building-panel.ts | 13 ++ client/src/content-editor.ts | 20 +- client/src/generated.ts | 39 ++++ client/src/main.ts | 17 +- client/src/player-content.ts | 3 +- client/src/world-view.ts | 3 +- docs/ARCHITECTURE.md | 7 + docs/MILESTONE-8A.md | 92 ++++++++ planning/PLAYWRIGHT-TODO.md | 2 + planning/SYSTEMS-ROADMAP.md | 2 +- planning/VISION.md | 3 + schemas/protocol.json | 54 ++++- server/content/balance.yaml | 11 + server/content/building.go | 78 +++++++ server/content/building_test.go | 26 +++ server/content/combat.go | 3 + server/content/content.go | 10 +- server/content/crafting.go | 3 + server/content/stats.go | 6 +- server/internal/game/admin_content.go | 5 + server/internal/game/building.go | 259 ++++++++++++++++++++++ server/internal/game/building_test.go | 127 +++++++++++ server/internal/game/combat.go | 28 ++- server/internal/game/crafting.go | 5 + server/internal/game/equipment.go | 3 + server/internal/game/gathering.go | 30 ++- server/internal/game/mobs.go | 18 +- server/internal/game/powers.go | 5 +- server/internal/game/revival.go | 2 +- server/internal/game/stats.go | 3 + server/internal/game/world.go | 13 +- server/internal/protocol/generated.go | 39 ++++ server/internal/store/catalog.go | 14 +- server/internal/store/catalog_ids_test.go | 3 +- server/internal/store/catalog_preview.go | 20 ++ server/internal/transport/powers.go | 9 + 36 files changed, 932 insertions(+), 43 deletions(-) create mode 100644 client/src/building-panel.ts create mode 100644 docs/MILESTONE-8A.md create mode 100644 server/content/building.go create mode 100644 server/content/building_test.go create mode 100644 server/internal/game/building.go create mode 100644 server/internal/game/building_test.go diff --git a/client/src/building-panel.ts b/client/src/building-panel.ts new file mode 100644 index 0000000..f533b8f --- /dev/null +++ b/client/src/building-panel.ts @@ -0,0 +1,13 @@ +import type {BuildingContent, Character} from './generated'; +import {api} from './portal-shared'; +import {node} from './character-stats'; + +export function buildingPanel(character:()=>Character|undefined,start:(id:string,rotation:string,range:number)=>void,prefix:string){ + const root=node('details'),summary=node('summary','Building'),list=node('div'),message=node('p');root.append(summary,node('p','Craft a structure kit, then choose a clear spot in the survival world. Placing consumes one kit. Structures can be destroyed by players and mobs.'),list,message); + root.addEventListener('toggle',()=>{if(root.open)void refresh()}); + async function refresh(){try{const b=await api(prefix+'/api/building'),c=character();list.replaceChildren(); + for(const d of b.definitions){const held=c?.inventory['kit_'+d.id]??0;if(!held)continue;const row=node('section'),rotation=node('select'),place=node('button','Choose placement');rotation.setAttribute('aria-label',d.name+' orientation');rotation.append(new Option('Width along east/west','0'),new Option('Width along north/south','1'));place.type='button';place.onclick=()=>start(d.id,rotation.value,b.range);row.append(node('h4',d.name+' · '+held+' kits'),node('p',`${d.width} × ${d.depth} × ${d.height}m · ${d.hp} health · ${d.profession} level ${d.level}`),rotation,place);list.append(row)} + message.textContent=list.children.length?'Click clear ground within '+b.range+'m after choosing placement. Esc cancels.':'No structure kits held. Craft one or ask an administrator for a playtest kit.'; + }catch(e){message.textContent=(e as Error).message}} + return root; +} diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index 3ed7219..419d053 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -9,7 +9,7 @@ function craftPool(){return repeat('Available crafted stats','Add pos const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),min=number(value?.min??1,-1000000),max=number(value?.max??5,-1000000),weight=number(value?.weight??1,.01,1000),percent=node('input');percent.type='checkbox';percent.checked=value?.percent??false; group.append(field('Stat',stat),field('Minimum roll',min),field('Maximum roll',max),field('Selection weight',weight),field('Percentage modifier',percent)); return {node:group,read:()=>({stat:stat.value,min:Number(min.value),max:Number(max.value),weight:Number(weight.value),percent:percent.checked})};},[],32);} -function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];} +function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),...(catalog.building?.definitions??[]).map(d=>({id:'kit_'+d.id,name:d.name+' kit'})),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];} function recipeForm(initial?:CraftRecipe){ if(editing||saving){show('Finish or cancel the open draft first.');return;} const values=identity(initial),profession=contentChoice(catalog.crafting?.professions??[],initial?.profession),level=number(initial?.level??1,1,1000,'1'),xp=number(initial?.xp??20,1,1000000,'1'); @@ -41,7 +41,7 @@ const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','world const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message'); const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms); let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false; -for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} +for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['buildings','Structures'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;} function show(text:string){message.textContent=text;message.hidden=false;} function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;} @@ -104,7 +104,8 @@ function previewView(result:ContentPreview){ const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers)); if(r.item?.craftPool?.length)root.append(node('p',`${r.item.craftRolls??0} random stat rolls per crafted item`),readableDefinition(r.item.craftPool)); if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(readableDefinition(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn)); - if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon)); + if(r.building)root.append(readableDefinition(r.building)); + if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon)); if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules)); if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),readableDefinition(r.stats));root.append(details);} return root; @@ -138,7 +139,8 @@ function statsForm(){ } function render(){ version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren(); - if(section==='powers'||section==='weapons'){powerList(); + if(section==='buildings'){buildingList(); + }else if(section==='powers'||section==='weapons'){powerList(); }else if(section.startsWith('craft-')){craftingList(); }else if(['attacks','mobs','loot','spawns'].includes(section)){combatList(); }else if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList(); @@ -166,7 +168,7 @@ function contentChoice(values:{id:string;name:string}[],initial?:string) { } function readableDefinition(value:unknown, context=''):HTMLElement { - const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])]; + const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.building?.definitions??[]).map(d=>({id:'kit_'+d.id,name:d.name+' kit'})),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])]; const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v); if(Array.isArray(value)) { const list=node('ul','','catalog-values'); @@ -277,3 +279,11 @@ function powerForm(){ const fields=form('Create spell or ability','create-power',()=>{const r=stats.read(),pre=parents.read();if(new Set(r.map(v=>v.stat)).size!==r.length||new Set(pre.map(v=>v.id)).size!==pre.length)throw new Error('Requirements must not repeat.');return {power:{...values.read(),kind:kind.value,attackId:resurrection.checked?'':attack.value,targeting:resurrection.checked?'target':targeting.value,resurrection:resurrection.checked,weapon:kind.value==='ability'?weapon.value:'',weaponLevel:Number(weaponLevel.value),requirements:{level:Number(level.value),stats:Object.fromEntries(r.map(v=>[v.stat,v.minimum])),titles:checks.filter(v=>v.input.checked).map(v=>v.id)},parents:kind.value==='ability'?{}:Object.fromEntries(pre.map(v=>[v.id,v.rank])),book:kind.value==='spell'&&book.checked,mana:Number(mana.value),castSeconds:resurrection.checked?0:Number(cast.value),cooldown:Number(cooldown.value),basePower:Number(basePower.value),rankScaling:Number(scaling.value),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:kind.value==='ability'?1:Number(max.value)}}}); fields.append(values.node,field('Kind',kind),field('Combat effect profile',attack),field('Targeting',targeting),field('Corpse resurrection (instant, adjacent, consent required)',resurrection),field('Learn from a consumable spell book',book),field('Weapon type for ability',weapon),field('Weapon level required',weaponLevel),field('Character level required',level),stats.node,titles,parents.node,field('Base effect power',basePower),field('Mana cost',mana),field('Cast time (seconds)',cast),field('Cooldown (seconds)',cooldown),field('Power increase per rank (0.03 = 3%)',scaling),field('XP to rank 2',base),field('Additional XP per rank',per),field('Maximum spell rank',max),node('p','A spell without a book automatically unlocks from its predecessor requirements. Abilities require the matching equipped weapon. Existing learned powers retain their definition. Aura profiles require a melee delivery, radius, and duration.','muted')); } + +function buildingList(){ + list.append(node('p','Publish a structure, then create a Builder recipe whose output is its kit. Placed structures keep their published dimensions and health.','muted'),button('Create structure',()=>{ + if(editing||saving)return;const values=identity(),model=select(['wall','camp','fort']),width=number(4,.5,8),depth=number(1,.5,8),height=number(2,.5,6),hp=number(250,1,1000000),profession=contentChoice(catalog.crafting?.professions??[],'builder'),level=number(1,1,1000,'1'); + const fields=form('Create structure','create-building',()=>({building:{...values.read(),model:model.value,width:Number(width.value),depth:Number(depth.value),height:Number(height.value),hp:Number(hp.value),profession:profession.value,level:Number(level.value)}})); + fields.append(values.node,field('Appearance preset',model),field('Width (m)',width),field('Depth (m)',depth),field('Height (m)',height),field('Health',hp),field('Placement profession',profession),field('Minimum profession level',level)); + }));for(const d of catalog.building?.definitions??[]){const row=node('details','','catalog-definition');row.append(node('summary',d.name),readableDefinition(d));list.append(row)} +} diff --git a/client/src/generated.ts b/client/src/generated.ts index 2d43ddc..f562268 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -11,6 +11,7 @@ export interface Protocol { } export interface ContentCatalog { + building?: BuildingContent; combat?: CombatContent; crafting?: CraftingContent; effectSets?: EffectSet[]; @@ -23,6 +24,27 @@ export interface ContentCatalog { version: number; } +export interface BuildingContent { + definitions: BuildingDefinition[]; + maxSlope: number; + maxStructures: number; + protectedRadius: number; + range: number; +} + +export interface BuildingDefinition { + depth: number; + description: string; + height: number; + hp: number; + id: string; + level: number; + model: string; + name: string; + profession: string; + width: number; +} + export interface CombatContent { attacks: CombatAttack[]; loot: LootTable[]; @@ -300,6 +322,7 @@ export interface TitleEffects { export interface ContentChange { attack?: CombatAttackDraft; biome?: BiomeDefinitionDraft; + building?: BuildingDraft; consumable?: GatheringConsumableDraft; craftMaterial?: CraftMaterialDraft; craftProfession?: GatheringSkillDraft; @@ -355,6 +378,19 @@ export interface BiomeDefinitionDraft { weight: number; } +export interface BuildingDraft { + depth: number; + description: string; + height: number; + hp: number; + id?: string; + level: number; + model: string; + name: string; + profession: string; + width: number; +} + export interface GatheringConsumableDraft { description: string; id?: string; @@ -579,6 +615,8 @@ export interface Chunk { } export interface Entity { + depth?: number; + height?: number; hp: number; id: string; kind: string; @@ -591,6 +629,7 @@ export interface Entity { resourceId?: string; skillId?: string; state: string; + width?: number; } export interface Vec3 { diff --git a/client/src/main.ts b/client/src/main.ts index 92b46a6..661f19b 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,5 +1,6 @@ import './style.css'; import { showTravel } from './travel'; +import { buildingPanel } from './building-panel'; import { craftingPanel } from './crafting-panel'; import { createPowerPanel, revivalPanel } from './power-panel'; import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide'; @@ -51,6 +52,7 @@ const avoidUntil = new Map(); let requestedClose = false; let input: InputActions; let powers:ReturnType; +let placement:{id:string;rotation:string;range:number}|undefined; let view: WorldView; const selectedWorld = new URLSearchParams(location.search).get('world'); const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : ''; @@ -69,14 +71,14 @@ function send(op: string, target = '', x = 0, z = 0, slot = '') { } function selection(entity?: Entity) { view.selected = entity; visible('target', !!entity); - if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} } + if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player','structure'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} } } function action(op: string) { if (!snapshot) return; const now = Date.now(); const kinds = op === 'attack' ? (snapshot.self.attack?.effect==='heal'?['player']:['boss', 'sentinel','mob']) : ['tree', 'ore', 'herb', 'corpse']; let target = view.selected; - if (!target || !kinds.includes(target.kind) || (avoidUntil.get(target.id) ?? 0) > now) { + if (!target || (!kinds.includes(target.kind)&&!(op==='attack'&&target.kind==='structure'&&snapshot.self.attack?.effect!=='heal')) || (avoidUntil.get(target.id) ?? 0) > now) { const p = snapshot.self.entity.position; target = [...snapshot.entities,...(snapshot.self.attack?.effect==='heal'?[snapshot.self.entity]:[])].filter(e => kinds.includes(e.kind) && (avoidUntil.get(e.id) ?? 0) <= now).sort((a, b) => Math.hypot(a.position.x - p.x, a.position.z - p.z) - Math.hypot(b.position.x - p.x, b.position.z - p.z))[0]; } @@ -201,7 +203,7 @@ async function boot() { else if(key==='inventory')$('inventory-toggle').click(); else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1); else if(key==='cancel-cast')send('cancel-cast'); - else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}} + else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse','structure'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}} else if(key==='heal'||key==='return'||key==='jump')send(key); }); view.start(); @@ -228,7 +230,7 @@ async function boot() { if (walkTo) { const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz); const target = actionTarget; - const range = pendingAction ? pendingAction.op === 'attack' ? (snapshot.self.attack?.range??config.attackRange) + (target?.id === 'boss' ? 3 : -0.5) : config.gatherRange - 0.5 : 0.8; + const range = pendingAction ? pendingAction.op === 'attack' ? (snapshot.self.attack?.range??config.attackRange) + (target?.id === 'boss' ? 3 : target?.kind==='structure'?Math.max(target.width??0,target.depth??0)/2-.5:-0.5) : config.gatherRange - 0.5 : 0.8; const reach = pendingAction?.op === 'attack' && target ? Math.hypot(distance, target.position.y-p.y) : distance; if (reach <= range) { if (!pendingAction) { walkTo = undefined; } @@ -262,7 +264,7 @@ async function boot() { }, 50); const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); config = loadedConfig; - powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings()); + powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());$('recipes').after(buildingPanel(()=>snapshot?.self,(id,rotation,range)=>{placement={id,rotation,range};input.clear();walkTo=undefined;pendingAction=undefined;send('move');$('inventory-toggle').click();notice('Click clear ground to build. Esc cancels.');},worldPrefix)); const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton); travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});}; $('zoom').value = String(view.distance); @@ -307,6 +309,7 @@ async function boot() { $('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); }; $('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high'); $('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); }; + window.addEventListener('keydown',e=>{if(e.code==='Escape'&&placement){placement=undefined;notice('Placement canceled.');}}); window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); }); document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } }); const movements: Record = { up:'north',down:'south',left:'west',right:'east' }; @@ -318,7 +321,9 @@ async function boot() { view.canvas.addEventListener('pointerdown', event => { if (!snapshot || hasOpenMenu() || $('arrival').open || $('ending').open || event.button !== 0) return; const hit = view.pick(event.clientX, event.clientY); - if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); } + if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;} + + if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); } else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; } }); Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true }); diff --git a/client/src/player-content.ts b/client/src/player-content.ts index 927347d..7a33307 100644 --- a/client/src/player-content.ts +++ b/client/src/player-content.ts @@ -1,7 +1,7 @@ import { api, el, type RecordCharacter } from './portal-shared'; import { statLabel } from './character-stats'; -type Catalog={powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]}; +type Catalog={building?:{definitions:{id:string;name:string}[]};powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]}; export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){ const root=el('section','','player-content');root.append(el('h3','Manage items and titles')); if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;} @@ -18,6 +18,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:() const v=record.character.view;choice.replaceChildren(); switch(operation.value){ case 'grant-item': + for(const d of catalog.building?.definitions??[])choice.append(new Option(d.name+' kit','kit_'+d.id)); choice.append(new Option('Revival stone','revival_stone'));for(const p of catalog.powers?.powers??[])if(p.book)choice.append(new Option(p.name+' spell book','book_'+p.id)); for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id)); for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id)); diff --git a/client/src/world-view.ts b/client/src/world-view.ts index e60f51b..93615ea 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -99,6 +99,7 @@ export class WorldView { this.batches.set('player', peers); const portalMesh = new T.InstancedMesh(new T.TorusGeometry(2,.22,8,40).translate(0,2.5,0),new T.MeshBasicMaterial({color:'#86ffe0'}),8); portalMesh.count=0;portalMesh.userData.kind='portal';this.scene.add(portalMesh);this.batches.set('portal',{parts:[portalMesh],entities:[]}); + const structureMesh=new T.InstancedMesh(new T.BoxGeometry(1,1,1).translate(0,.5,0),new T.MeshStandardMaterial({color:'#8c6744',roughness:1}),512);structureMesh.count=0;structureMesh.castShadow=true;structureMesh.receiveShadow=true;structureMesh.userData.kind='structure';this.scene.add(structureMesh);this.batches.set('structure',{parts:[structureMesh],entities:[]}); const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048); corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh); this.batches.set('corpse', { parts: [corpseMesh], entities: [] }); @@ -177,7 +178,7 @@ export class WorldView { const variation = e.id.split('').reduce((n, c) => n + c.charCodeAt(0), 0); this.dummy.rotation.set(0, e.kind === 'tree' || e.kind === 'ore' ? variation : 0, 0); const scale = e.kind === 'tree' ? 0.85 + (variation % 6) * 0.07 : 1; - this.dummy.scale.setScalar(e.kind==='area'?(e.radius??1):scale);if(e.kind==='area')this.dummy.rotation.x=-Math.PI/2; this.dummy.updateMatrix(); + this.dummy.scale.setScalar(e.kind==='area'?(e.radius??1):scale);if(e.kind==='area')this.dummy.rotation.x=-Math.PI/2; if(e.kind==='structure')this.dummy.scale.set(e.width??1,e.height??1,e.depth??1);this.dummy.updateMatrix(); for (const mesh of batch.parts) mesh.setMatrixAt(i, this.dummy.matrix); } for (const mesh of batch.parts) { mesh.count = count; mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere(); } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4055114..4f18d07 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -195,6 +195,13 @@ within a world fail restoration. Materials and consumables remain quantity stack ## Combat and mobs +Milestone 8a adds copied structure definitions and world-owned structure snapshots. +The server checks kit consumption, profession level, placement bounds/obstacles, +and protected locations. Swept box intersections support movement/projectile +collision and combat sight checks. Structures can be attacked and destroyed by +players and nearby aggressive/guard mobs. Housing is still pending; see the +[building checkpoint](MILESTONE-8A.md) for scope and manual verification. + Biomes now retain a stable ID with server-assigned revisions and archived resource assignments. Explicit resource ID lists replace reverse resource-to-biome lookup for revised/new biomes; legacy lists are resolved on first edit. New resource diff --git a/docs/MILESTONE-8A.md b/docs/MILESTONE-8A.md new file mode 100644 index 0000000..9cd5c42 --- /dev/null +++ b/docs/MILESTONE-8A.md @@ -0,0 +1,92 @@ +# Milestone 8a: world building checkpoint + +Milestone 8 is **in progress**. This checkpoint implements the independent world +building work. House instances, keys, invitations, storage, deletion, and recovery +are not implemented here. Their access and recovery decisions remain pending. + +## Playable building + +Control's **Structures** tab publishes named, reusable definitions with +server-generated IDs, dimensions, health, presentation preset, and required +crafting profession/level. Definitions are immutable; placed structures copy +their definition and retain their builder, placement time, and kit provenance. +Recipes can output a structure's kit, and administrators can grant kits through +player item controls. Existing recipes are unchanged; author kit recipes in Control. + +Inventory's **Building** section lists held kits. Choose orientation, select +**Choose placement**, then click clear ground within 8m. Esc cancels placement. +Go validates the location and consumes exactly one kit on success. Failed +placement consumes nothing. Crafting kits uses the existing discovery, failure, +provenance, and Builder XP system. Placement grants no additional XP. Kits can be +crafted in hubs without XP, but public hub construction is disabled. + +Default blueprints are a timber wall, camp platform, and solid fort block. +They currently render as simple timber-colored boxes with their actual physical +dimensions. The fort block is a building component, not a completed hollow fort. +The appearance preset is retained for later asset work. No new model files are +claimed. Place multiple components to assemble layouts. + +Structures persist in their owning survival world's snapshot after disconnect, +chunk unload, restart, or builder death. All players can damage them. Aggressive +and guard mobs can attack nearby structures; passive/healing mobs do not. +Projectile attacks visibly travel and hit the physical structure bounds; structures +also block healing projectiles. Melee, damage spells, and area damage can destroy +structures. Destruction removes health/collision without refunding a kit or creating +loot. It grants no new weapon/spell/character XP; legacy attack-attempt combat XP +continues to follow its existing behavior. + +Movement uses swept structure bounds, shared with mob collision and combat sight +checks. Players can jump onto sufficiently low components, stand/jump on their +tops, and fall off edges. Mob navigation keeps its existing bounded side steps; +this is not a new global pathfinder. Gathering, looting, and revival also respect +structure obstruction. + +Placement rejects overlapping buildings, living players, mobs, corpses, resources, +keystone return locations, excessive slope, and the world boundary. The protected +arrival/portal clearing remains open. New player and mob spawn locations avoid +structure interiors. This does not promise that players cannot enclose wider areas +with several structures; siege damage provides the current way through. + +Provisional tuning in `server/content/balance.yaml`: 256 structures/world, 8m +placement range, 18m protected clearing, and at most 1m ground variation (also +limited to half the component height). No repair, demolition refunds, private +structure rights, housing storage, decay, or cross-world structure transfer is +introduced. Structures belong to their destructible world and confer no survivor +passage or housing eligibility. + +## Manual playtest + +1. In Control, grant Timber wall kits and Camp platform kits to a living character. + Alternatively, create a Builder recipe that outputs the desired kit and craft it. + Recipe discovery stays private to characters who attempt the recipe. +2. Open Inventory → Building, choose orientation/placement, and click clear ground + beyond the arrival clearing. Check kit consumption and the visible dimensions. +3. Try overlapping a structure or resource, building too far away, and placing in + the arrival clearing or hub. Verify rejected placement preserves the kit. +4. Walk into a wall, jump onto a camp platform, jump again, and walk off its edge. +5. Target a structure and attack it with melee, projectiles, and damage spells. + Test a projectile aimed through a structure at a mob. Check structure health and + removal at zero HP; test an aggressive mob next to a wall. +6. Leave/reload the chunk and reconnect. Verify structures keep their health and + position after a server restart and after the builder's death. +7. Publish a custom structure and recipe through Control; preview invalid bounds + or a missing profession and confirm publication is rejected. + +Placement currently needs a pointer. Existing keyboard/controller combat targeting +includes structures. Full controller placement and a placement preview are follow-up +UI work. Browser automation remains deferred for manual testing. + +## Housing decisions pending + +- Whether a replacement must survive a world before exercising the creator's + recovery right. +- Initial rights for invited co-owners and guests. Key holders remain full owners + and cannot revoke other valid keys. +- Whether access ends immediately at last-key destruction or after the three-second + countdown. Qualifying recovery must reuse the same retained contents. +- Recovery without an established destructible death world must retain data; + no arbitrary purge deadline will be invented. + +The confirmed last-key count, three-second deletion, and recovery-until-death-world- +destruction rules remain unchanged. This checkpoint does not activate those rules +or claim to finish milestone 8. diff --git a/planning/PLAYWRIGHT-TODO.md b/planning/PLAYWRIGHT-TODO.md index 8c26de0..f9132b1 100644 --- a/planning/PLAYWRIGHT-TODO.md +++ b/planning/PLAYWRIGHT-TODO.md @@ -28,6 +28,8 @@ automation. These are future tasks, not completion gates for the current milesto cycling, cast interruption, useful-heal XP, moving auras, consent after reload, and empty-corpse item/spell revival with preserved progression. - [ ] Structures and house placement, keys/guest permissions, storage, and recovery UI. +- [ ] Milestone 8a: structure editor/kit recipe outputs, placement/cancellation, + overlap and protected-area rejection, health/destruction, and roof movement. - [ ] Last-key three-second deletion and recovery before the death-world deadline. - [ ] Cosmetics: ordinary drops, house placement, push/pull, and entitled/unentitled pickup. - [ ] Character creation, desktop/mobile layouts, and keyboard focus/accessibility. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index 202cc82..36d6b16 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -552,7 +552,7 @@ milestones, not time estimates or new tested-capacity claims. | 5. Playable hub travel | Hub instances/switching, survival-world entry, escape items, Harbinger victory portal | Implemented; [manual handoff](../docs/MILESTONE-5.md): admission, escape restrictions, single character/item ownership, hub XP restrictions | | 6. Crafting and item quality | Recipe discovery, nine professions, failure/refund curves, random stats, crafter provenance, hub crafting | Implemented; [manual handoff](../docs/MILESTONE-6.md): valid-recipe feedback, resource use, quality/provenance, discoveries without hub XP | | 7. Spells, abilities, resurrection | Spell books/ranks/unlocks, weapon proficiency, corpse revival, bindings/controller targeting | Implemented; [manual handoff](../docs/MILESTONE-7.md): useful-action XP, healing/auras, revival finality, costs, and controls | -| 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | Persistence, ownership, navigation changes, guest access, three-second deletion and recovery | +| 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | In progress: [8a building checkpoint](../docs/MILESTONE-8A.md); housing access/recovery decisions and implementation remain | | 9. Cosmetics and customization | Simple character creator, account cosmetic application, furniture exceptions, presentation polish | Entitlements, appearance compatibility, drop versus placement/push/pickup | | 10. Dungeons and social expansion | Portal instances and lifecycle; separately scoped communication, trade, parties, guilds | Instance population/reset/exit rules, item exchange, membership and permissions | diff --git a/planning/VISION.md b/planning/VISION.md index 1ceabcc..a33080c 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -171,6 +171,9 @@ Tracked across: - Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning? ## Backlog +- Milestone 8a adds persistent destructible world structures, craftable kits, + Control definitions, placement checks, and collision. Housing/key lifecycle work + remains pending; see `docs/MILESTONE-8A.md` for the checkpoint and open decisions. - Milestone 7 implements spell books/ranks/unlocks, weapon proficiency and abilities, healing/auras, bindable keyboard/controller slots, and durable corpse revival. See `docs/MILESTONE-7.md` for defaults, effect limits, and the manual handoff. diff --git a/schemas/protocol.json b/schemas/protocol.json index d4e8b21..05134fe 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -95,7 +95,8 @@ "gathering": {"$ref": "#/definitions/GatheringContent"}, "combat": {"$ref": "#/definitions/CombatContent"}, "crafting": {"$ref": "#/definitions/CraftingContent"}, - "powers": {"$ref": "#/definitions/PowerContent"} + "powers": {"$ref": "#/definitions/PowerContent"}, + "building": {"$ref": "#/definitions/BuildingContent"} }, "required": ["version", "titles", "items", "stats"] }, @@ -127,7 +128,8 @@ "craftMaterial": {"$ref": "#/definitions/CraftMaterialDraft"}, "craftRules": {"$ref": "#/definitions/CraftRules"}, "power": {"$ref": "#/definitions/PowerDraft"}, - "weapon": {"$ref": "#/definitions/GatheringSkillDraft"} + "weapon": {"$ref": "#/definitions/GatheringSkillDraft"}, + "building": {"$ref": "#/definitions/BuildingDraft"} }, "required": ["id", "expectedVersion", "op", "reason"] }, @@ -204,7 +206,10 @@ "skillId": {"type": "string"}, "requiredLevel": {"type": "integer"}, "model": {"type": "string"}, - "radius": {"type": "number"} + "radius": {"type": "number"}, + "width": {"type": "number"}, + "depth": {"type": "number"}, + "height": {"type": "number"} }, "required": ["id", "kind", "name", "position", "hp", "maxHp", "state"] }, @@ -932,6 +937,49 @@ "xpToNextLevel": {"type": "integer"} }, "required": ["id", "name", "xp", "level", "xpToNextLevel"] + }, + "BuildingDefinition": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "model": {"type": "string"}, + "profession": {"type": "string"}, + "width": {"type": "number"}, + "depth": {"type": "number"}, + "height": {"type": "number"}, + "hp": {"type": "number"}, + "level": {"type": "integer"} + }, + "required": ["id", "name", "description", "model", "profession", "width", "depth", "height", "hp", "level"] + }, + "BuildingDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "model": {"type": "string"}, + "profession": {"type": "string"}, + "width": {"type": "number"}, + "depth": {"type": "number"}, + "height": {"type": "number"}, + "hp": {"type": "number"}, + "level": {"type": "integer"} + }, + "required": ["name", "description", "model", "profession", "width", "depth", "height", "hp", "level"] + }, + "BuildingContent": { + "type": "object", "additionalProperties": false, + "properties": { + "definitions": {"type": "array", "items": {"$ref": "#/definitions/BuildingDefinition"}}, + "maxStructures": {"type": "integer"}, + "range": {"type": "number"}, + "protectedRadius": {"type": "number"}, + "maxSlope": {"type": "number"} + }, + "required": ["definitions", "maxStructures", "range", "protectedRadius", "maxSlope"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index f5ccff2..4f61f01 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -247,3 +247,14 @@ crafting: # Milestone 7 provisional progression and resurrection tuning. powers: {"weapons": [{"id": "blades", "name": "Blades", "description": "Blades proficiency", "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000}, {"id": "polearms", "name": "Polearms", "description": "Polearms proficiency", "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000}], "powers": [{"id": "arc_bolt", "name": "Arc bolt", "description": "Arc bolt", "kind": "spell", "attackId": "arc_bolt", "targeting": "target", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 5, "castSeconds": 0.5, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "mend", "name": "Mend", "description": "Mend", "kind": "spell", "attackId": "mend", "targeting": "target", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 5, "castSeconds": 0, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "renewal", "name": "Renewal aura", "description": "Renewal aura", "kind": "spell", "attackId": "renewal_aura", "targeting": "aura", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {"mend": 2}, "book": false, "mana": 10, "castSeconds": 0, "cooldown": 10, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "revive", "name": "Resurrection", "description": "Resurrection", "kind": "spell", "attackId": "", "targeting": "target", "resurrection": true, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 20, "castSeconds": 0, "cooldown": 30, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 0}, {"id": "cleave", "name": "Cleave", "description": "Cleave", "kind": "ability", "attackId": "cleave", "targeting": "target", "resurrection": false, "weapon": "blades", "weaponLevel": 2, "requirements": {"level": 1, "stats": {"strength": 2}, "titles": []}, "parents": {}, "book": false, "mana": 0, "castSeconds": 0, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1, "basePower": 0}], "weaponXp": 10, "spellXp": 10, "revivalRange": 3, "revivalHealth": 0.25} + +# Milestone 8a provisional structure limits and blueprints. Recipes are authored in Control. +building: + maxStructures: 256 + range: 8 + protectedRadius: 18 + maxSlope: 1 + definitions: + - {"id": "timber_wall", "name": "Timber wall", "description": "A persistent, destructible timber wall.", "model": "wall", "width": 4, "depth": 1, "height": 2, "hp": 250, "profession": "builder", "level": 1} + - {"id": "camp_platform", "name": "Camp platform", "description": "A persistent, destructible camp platform.", "model": "camp", "width": 4, "depth": 4, "height": 0.75, "hp": 300, "profession": "builder", "level": 1} + - {"id": "fort_block", "name": "Fort block", "description": "A persistent, destructible fort block.", "model": "fort", "width": 6, "depth": 3, "height": 3, "hp": 800, "profession": "builder", "level": 5} diff --git a/server/content/building.go b/server/content/building.go new file mode 100644 index 0000000..dd16bdb --- /dev/null +++ b/server/content/building.go @@ -0,0 +1,78 @@ +package content + +import ( + "fmt" + "slices" +) + +type BuildingDefinition struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Model string `json:"model" yaml:"model"` + Width float64 `json:"width" yaml:"width"` + Depth float64 `json:"depth" yaml:"depth"` + Height float64 `json:"height" yaml:"height"` + HP float64 `json:"hp" yaml:"hp"` + Profession string `json:"profession" yaml:"profession"` + Level int64 `json:"level" yaml:"level"` +} +type BuildingContent struct { + Definitions []BuildingDefinition `json:"definitions" yaml:"definitions"` + MaxStructures int `json:"maxStructures" yaml:"maxStructures"` + Range float64 `json:"range" yaml:"range"` + ProtectedRadius float64 `json:"protectedRadius" yaml:"protectedRadius"` + MaxSlope float64 `json:"maxSlope" yaml:"maxSlope"` +} + +func (d BuildingDefinition) Validate() error { + if !validSetIdentity(d.ID, d.Name, d.Description) || !slices.Contains([]string{"wall", "camp", "fort"}, d.Model) || !finiteRange(d.Width, .5, 8) || !finiteRange(d.Depth, .5, 8) || !finiteRange(d.Height, .5, 6) || !finiteRange(d.HP, 1, 1000000) || d.Level < 1 || d.Level > 1000 { + return fmt.Errorf("invalid structure definition %q", d.Name) + } + return nil +} +func (c Catalog) BuildingItems() map[string]string { + out := map[string]string{} + if c.Building != nil { + for _, d := range c.Building.Definitions { + out["kit_"+d.ID] = d.Name + " kit" + } + } + return out +} +func (c Catalog) validateBuilding() error { + if c.Building == nil { + return nil + } + b := c.Building + if len(b.Definitions) > 128 || b.MaxStructures < 1 || b.MaxStructures > 512 || !finiteRange(b.Range, 2, 12) || !finiteRange(b.ProtectedRadius, 12, 100) || !finiteRange(b.MaxSlope, .1, 3) { + return fmt.Errorf("invalid building limits") + } + seen := map[string]bool{} + for _, d := range b.Definitions { + if e := d.Validate(); e != nil { + return e + } + if seen[d.ID] { + return fmt.Errorf("duplicate building identity") + } + seen[d.ID] = true + if c.Crafting == nil || !slices.ContainsFunc(c.Crafting.Professions, func(p GatheringSkill) bool { return p.ID == d.Profession }) { + return fmt.Errorf("unknown building profession") + } + for _, i := range c.Items { + if i.ID == "kit_"+d.ID { + return fmt.Errorf("equipment conflicts with structure kit") + } + } + } + return nil +} + +// Existing catalogs gain the reusable structure definitions, while recipes remain +// authored separately. No publication rewrites already placed structures. +func (c *Catalog) RestoreBuilding(b Balance) { + if c.Building == nil { + c.Building = b.Building + } +} diff --git a/server/content/building_test.go b/server/content/building_test.go new file mode 100644 index 0000000..19c6371 --- /dev/null +++ b/server/content/building_test.go @@ -0,0 +1,26 @@ +package content + +import "testing" + +func TestBuildingKitsAndRequirements(t *testing.T) { + c, e := DefaultCatalog() + if e != nil { + t.Fatal(e) + } + c.Crafting.Recipes = append(c.Crafting.Recipes, CraftRecipe{ID: "wall_kit_recipe", Name: "Wall kit", Revision: 1, Profession: "builder", Level: 1, XP: 20, Inputs: map[string]int64{"wood": 6, "ore": 2}, Outputs: map[string]int64{"kit_timber_wall": 1}}) + if e = c.Validate(); e != nil { + t.Fatal("could not author kit recipe", e) + } + d := c.Building.Definitions[0] + d.Height = -1 + c.Building.Definitions[0] = d + if e = c.Validate(); e == nil { + t.Fatal("negative height allowed") + } + d.Height = 2 + d.Profession = "missing" + c.Building.Definitions[0] = d + if e = c.Validate(); e == nil { + t.Fatal("missing profession allowed") + } +} diff --git a/server/content/combat.go b/server/content/combat.go index 1645e49..411bfe4 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -129,6 +129,9 @@ func (c Catalog) validateCombat() error { attacks[a.ID] = true } items := map[string]bool{} + for id := range c.BuildingItems() { + items[id] = true + } for id := range c.PowerItems() { items[id] = true } diff --git a/server/content/content.go b/server/content/content.go index 961450f..389d70d 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,7 @@ type Recipe struct { } type Balance struct { + Building *BuildingContent `yaml:"building"` Powers *PowerContent `yaml:"powers"` Crafting *CraftingContent `yaml:"crafting"` Combat *CombatContent `yaml:"combat"` @@ -82,10 +83,13 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { - if err := (Catalog{Powers: b.Powers, Combat: b.Combat, Items: b.Items, Titles: b.Titles}).validatePowers(); err != nil { + if e := (Catalog{Building: b.Building, Crafting: b.Crafting, Items: b.Items}).validateBuilding(); e != nil { + return e + } + if err := (Catalog{Building: b.Building, Powers: b.Powers, Combat: b.Combat, Items: b.Items, Titles: b.Titles}).validatePowers(); err != nil { return err } - if err := (Catalog{Powers: b.Powers, Crafting: b.Crafting, Items: b.Items, Titles: b.Titles, Gathering: b.Gathering}).validateCrafting(); err != nil { + if err := (Catalog{Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Items: b.Items, Titles: b.Titles, Gathering: b.Gathering}).validateCrafting(); err != nil { return err } if b.CombatRules != nil { @@ -93,7 +97,7 @@ func (b Balance) Validate() error { return err } } - if err := (Catalog{Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { + if err := (Catalog{Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { return err } if b.Gathering != nil { diff --git a/server/content/crafting.go b/server/content/crafting.go index b72cd19..5ad7fe2 100644 --- a/server/content/crafting.go +++ b/server/content/crafting.go @@ -83,6 +83,9 @@ func SkillLevel(s GatheringSkill, xp int64) (int64, int64) { } func (c Catalog) StackIDs() map[string]bool { ids := map[string]bool{} + for id := range c.BuildingItems() { + ids[id] = true + } for id := range c.PowerItems() { ids[id] = true } diff --git a/server/content/stats.go b/server/content/stats.go index b8a8f4b..450371d 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -49,6 +49,7 @@ type ItemDefinition struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + Building *BuildingContent `json:"building,omitempty"` Powers *PowerContent `json:"powers,omitempty"` Crafting *CraftingContent `json:"crafting,omitempty"` Combat *CombatContent `json:"combat,omitempty"` @@ -134,6 +135,9 @@ func (item ItemDefinition) Validate() error { return ValidateModifiers(item.Modifiers) } func (c Catalog) Validate() error { + if e := c.validateBuilding(); e != nil { + return e + } if err := c.validatePowers(); err != nil { return err } @@ -215,5 +219,5 @@ func DefaultCatalog() (Catalog, error) { if err != nil { return Catalog{}, err } - return Catalog{Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil + return Catalog{Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil } diff --git a/server/internal/game/admin_content.go b/server/internal/game/admin_content.go index 445d2a3..ad47da0 100644 --- a/server/internal/game/admin_content.go +++ b/server/internal/game/admin_content.go @@ -31,6 +31,11 @@ func (w *World) AdminItems(c *Character, op, value string) error { } if op == "grant-item" { known := false + for key := range (content.Catalog{Building: w.Balance.Building}).BuildingItems() { + if key == id { + known = true + } + } for key := range (content.Catalog{Powers: w.Balance.Powers}).PowerItems() { if key == id { known = true diff --git a/server/internal/game/building.go b/server/internal/game/building.go new file mode 100644 index 0000000..826a522 --- /dev/null +++ b/server/internal/game/building.go @@ -0,0 +1,259 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "errors" + "math" + "sort" +) + +type Structure struct { + Entity p.Entity `json:"entity"` + Definition content.BuildingDefinition `json:"definition"` + Builder string `json:"builder"` + BuiltAt int64 `json:"builtAt"` + Provenance []p.CraftedStack `json:"provenance,omitempty"` +} + +func (w *World) restoreBuilding() error { + if w.Balance.Building == nil { + b, e := content.Load() + if e != nil { + return e + } + w.Balance.Building = b.Building + } + if w.Structures == nil { + w.Structures = map[string]*Structure{} + } + if len(w.Structures) > 512 { + return errors.New("too many saved structures") + } + for id, s := range w.Structures { + if s == nil || id != s.Entity.ID || s.Entity.Kind != "structure" || s.Definition.Validate() != nil || !finiteCraft(s.Entity.HP) || s.Entity.HP <= 0 || s.Entity.HP > s.Definition.HP || s.Entity.MaxHP != s.Definition.HP || s.Entity.Width == nil || s.Entity.Depth == nil || s.Entity.Height == nil { + return errors.New("invalid saved structure") + } + pos := s.Entity.Position + if math.IsNaN(pos.X) || math.IsNaN(pos.Y) || math.IsNaN(pos.Z) || math.IsInf(pos.X, 0) || math.IsInf(pos.Y, 0) || math.IsInf(pos.Z, 0) || math.Hypot(pos.X, pos.Z) > w.Balance.WorldRadius || *s.Entity.Height != s.Definition.Height || !((*s.Entity.Width == s.Definition.Width && *s.Entity.Depth == s.Definition.Depth) || (*s.Entity.Width == s.Definition.Depth && *s.Entity.Depth == s.Definition.Width)) { + return errors.New("invalid saved structure bounds") + } + } + return nil +} +func (w *World) Build(c *Character, id string, dx, dz float64, rotation string) error { + if c == nil || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || !w.AllowsXP() || c.PendingCast != nil { + return errors.New("cannot build here") + } + if w.Balance.Building == nil { + return errors.New("building unavailable") + } + b := w.Balance.Building + if math.IsNaN(dx) || math.IsNaN(dz) || math.IsInf(dx, 0) || math.IsInf(dz, 0) || math.Hypot(dx, dz) > 1 || (rotation != "0" && rotation != "1") { + return errors.New("invalid placement") + } + var d *content.BuildingDefinition + for i := range b.Definitions { + if b.Definitions[i].ID == id { + d = &b.Definitions[i] + break + } + } + if d == nil || c.View.Inventory["kit_"+id] < 1 { + return errors.New("structure kit required") + } + if c.View.Crafting[d.Profession].Level < d.Level { + return errors.New("building profession level too low") + } + if len(w.Structures) >= b.MaxStructures { + return errors.New("world structure limit reached") + } + pos := w.terrain.Position(c.View.Entity.Position.X+dx*b.Range, c.View.Entity.Position.Z+dz*b.Range) + width, depth, height := d.Width, d.Depth, d.Height + if rotation == "1" { + width, depth = depth, width + } + radius := math.Hypot(width, depth) / 2 + if math.Hypot(pos.X, pos.Z)-radius < b.ProtectedRadius || math.Hypot(pos.X, pos.Z)+radius >= w.SafeRadius() { + return errors.New("keep structures away from the arrival clearing, portal, and world boundary") + } + if _, blocked := w.combatLine(body(c.View.Entity.Position), body(pos), ""); blocked { + return errors.New("placement is obstructed") + } + low, high := pos.Y, pos.Y + for _, x := range []float64{pos.X - width/2, pos.X + width/2} { + for _, z := range []float64{pos.Z - depth/2, pos.Z + depth/2} { + h := w.terrain.Height(x, z) + low = math.Min(low, h) + high = math.Max(high, h) + } + } + if high-low > math.Min(b.MaxSlope, height/2) { + return errors.New("choose flatter ground") + } + pos.Y = low + entity := p.Entity{ID: "structure:" + ID(), Kind: "structure", Name: d.Name, Position: pos, HP: d.HP, MaxHP: d.HP, State: d.Model, Width: &width, Depth: &depth, Height: &height} + for _, s := range w.Structures { + if boxesOverlap(entity, s.Entity, .2) { + return errors.New("structures overlap") + } + } + occupied := func(e p.Entity) bool { + return math.Abs(e.Position.X-pos.X) < width/2+1 && math.Abs(e.Position.Z-pos.Z) < depth/2+1 + } + for _, other := range w.Characters { + if other.ReturnPosition != nil && occupied(p.Entity{Position: *other.ReturnPosition}) { + return errors.New("keep keystone return locations accessible") + } + if other.View.Entity.State != "dead" && occupied(other.View.Entity) { + return errors.New("a player occupies that space") + } + } + for _, m := range w.Mobs { + if m.Entity.HP > 0 && occupied(m.Entity) { + return errors.New("a mob occupies that space") + } + } + for _, corpse := range w.Corpses { + if occupied(corpse.Entity) { + return errors.New("keep corpses accessible") + } + } + for _, ch := range w.neighbors(pos) { + for _, resource := range ch.Resources { + if occupied(resource) { + return errors.New("keep resources accessible") + } + } + } + provenance := TakeStack(c, "kit_"+id, 1) + if w.Structures == nil { + w.Structures = map[string]*Structure{} + } + w.Structures[entity.ID] = &Structure{Entity: entity, Definition: *d, Builder: c.View.Entity.ID, BuiltAt: w.now.Unix(), Provenance: provenance} + c.Message = "Built " + d.Name + w.dirty = true + return nil +} +func boxesOverlap(a, b p.Entity, padding float64) bool { + return math.Abs(a.Position.X-b.Position.X) < (*a.Width+*b.Width)/2+padding && math.Abs(a.Position.Z-b.Position.Z) < (*a.Depth+*b.Depth)/2+padding +} + +// Swept segment/AABB intersection also catches thin walls between simulation ticks. +func boxFraction(from, to p.Vec3, e p.Entity, padding, below float64) (float64, bool) { + lo, hi := 0.0, 1.0 + starts := []float64{from.X, from.Y, from.Z} + ends := []float64{to.X, to.Y, to.Z} + mins := []float64{e.Position.X - *e.Width/2 - padding, e.Position.Y - below, e.Position.Z - *e.Depth/2 - padding} + maxs := []float64{e.Position.X + *e.Width/2 + padding, e.Position.Y + *e.Height - .001, e.Position.Z + *e.Depth/2 + padding} + for i, a := range starts { + d := ends[i] - a + if math.Abs(d) < 1e-9 { + if a < mins[i] || a > maxs[i] { + return 0, false + } + continue + } + u, v := (mins[i]-a)/d, (maxs[i]-a)/d + if u > v { + u, v = v, u + } + lo = math.Max(lo, u) + hi = math.Min(hi, v) + if lo > hi { + return 0, false + } + } + return lo, true +} +func (w *World) structureIDs() []string { + ids := make([]string, 0, len(w.Structures)) + for id := range w.Structures { + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} +func (w *World) combatLine(from, to p.Vec3, ignore string) (p.Vec3, bool) { + point, blocked := w.terrainHit(from, to) + best := math.Inf(1) + if blocked { + best = length3(from, point) + } + for _, id := range w.structureIDs() { + if id == ignore { + continue + } + s := w.Structures[id] + if f, ok := boxFraction(from, to, s.Entity, 0, 0); ok && f*length3(from, to) < best { + point = lerp3(from, to, f) + best = length3(from, point) + blocked = true + } + } + return point, blocked +} +func (w *World) structureBlocked(from, to p.Vec3) bool { + for _, s := range w.Structures { + if _, ok := boxFraction(from, to, s.Entity, .35, 1.7); ok { + return true + } + } + return false +} +func (w *World) floorAt(x, z, feet float64) float64 { + h := w.terrain.Height(x, z) + for _, s := range w.Structures { + e := s.Entity + top := e.Position.Y + *e.Height + if top <= feet+.05 && math.Abs(x-e.Position.X) <= *e.Width/2+.3 && math.Abs(z-e.Position.Z) <= *e.Depth/2+.3 { + h = math.Max(h, top) + } + } + return h +} +func (w *World) damageStructure(id string, power float64) { + s := w.Structures[id] + if s == nil || power <= 0 { + return + } + s.Entity.HP = math.Max(0, s.Entity.HP-power) + if s.Entity.HP == 0 { + delete(w.Structures, id) + } + w.dirty = true +} + +// Aggressive/guard mobs can destroy nearby structures, including ones concealing +// their target. Passive and healing mobs do not attack buildings. +func (w *World) attackNearbyStructure(m *Mob, a p.CombatAttack, power, aggro, leash float64) bool { + if a.Effect != "damage" { + return false + } + for _, id := range w.structureIDs() { + e := w.Structures[id].Entity + near := a.Range + math.Max(*e.Width, *e.Depth)/2 + if distance(m.Entity.Position, e.Position) > math.Min(aggro, near) || distance(e.Position, *m.Home) > leash { + continue + } + if _, blocked := w.combatLine(body(m.Entity.Position), body(e.Position), id); blocked { + continue + } + if w.Age()-m.LastAttack >= a.Cooldown { + if a.Delivery == "projectile" { + if len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles || (a.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas) { + return true + } + shot := &Projectile{ID: w.combatID("projectile"), Source: m.Entity.ID, Player: false, Position: body(m.Entity.Position), Destination: body(e.Position), Target: id, Attack: a, Power: power * a.Multiplier} + w.Projectiles[shot.ID] = shot + w.projectileVisual(*shot, "launch", "") + } else { + w.damageStructure(id, power*a.Multiplier) + } + m.LastAttack = w.Age() + w.dirty = true + } + return true + } + return false +} diff --git a/server/internal/game/building_test.go b/server/internal/game/building_test.go new file mode 100644 index 0000000..c4455ed --- /dev/null +++ b/server/internal/game/building_test.go @@ -0,0 +1,127 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "encoding/json" + "math" + "testing" + "time" +) + +func builtFixture(t *testing.T) (*World, *Character, *Structure) { + t.Helper() + w, c := fixture(t) + c.View.Inventory["kit_timber_wall"] = 2 + for x := 30.; x < 100; x += 5 { + c.View.Entity.Position = w.terrain.Position(x, 0) + if e := w.Build(c, "timber_wall", 0, .75, "0"); e == nil { + for _, s := range w.Structures { + return w, c, s + } + } + } + t.Fatal("could not place fixture structure") + return nil, nil, nil +} +func TestStructurePlacementOwnershipAndPersistence(t *testing.T) { + w, c, s := builtFixture(t) + if c.View.Inventory["kit_timber_wall"] != 1 { + t.Fatal("kit not consumed once") + } + if e := w.Build(c, "timber_wall", 0, .75, "0"); e == nil || c.View.Inventory["kit_timber_wall"] != 1 { + t.Fatal("overlap spent kit") + } + if e := w.Build(c, "timber_wall", math.NaN(), 0, "0"); e == nil { + t.Fatal("nonfinite placement accepted") + } + w.Kind = "hub" + if e := w.Build(c, "timber_wall", .75, 0, "0"); e == nil { + t.Fatal("hub construction accepted") + } + w.Kind = "survival" + w.damageStructure(s.Entity.ID, 20) + hp := s.Entity.HP + w.kill(c, "building persistence check") + raw, _ := json.Marshal(w) + var restored World + if e := json.Unmarshal(raw, &restored); e != nil { + t.Fatal(e) + } + if e := restored.Restore(w.now.Add(time.Second)); e != nil { + t.Fatal(e) + } + if restored.Structures[s.Entity.ID] == nil || restored.Structures[s.Entity.ID].Entity.HP != hp { + t.Fatal("death/restart lost or healed structure") + } + w.damageStructure(s.Entity.ID, 1000000) + if len(w.Structures) != 0 { + t.Fatal("destroyed structure retained collision") + } +} +func TestStructureCollisionProjectileAndMobDamage(t *testing.T) { + w, c, s := builtFixture(t) + e := s.Entity + c.View.Entity.Position = w.terrain.Position(e.Position.X, e.Position.Z-2) + c.MoveZ = 1 + for i := 0; i < 20; i++ { + w.moveCharacter(c, .05) + } + if c.View.Entity.Position.Z >= e.Position.Z-*e.Depth/2 { + t.Fatal("walked through wall") + } + from := body(w.terrain.Position(e.Position.X, e.Position.Z-4)) + to := body(w.terrain.Position(e.Position.X, e.Position.Z+4)) + if _, blocked := w.combatLine(from, to, ""); !blocked { + t.Fatal("wall did not block line of sight") + } + if _, blocked := w.combatLine(from, body(e.Position), e.ID); blocked { + t.Fatal("wall prevented its own targeting") + } + w.now = w.now.Add(time.Minute) + a := protocolAttack(w.Balance.Combat.Attacks[0]) + a.Effect = "damage" + a.Delivery = "projectile" + a.Speed = 100 + a.Radius = 0 + a.Duration = 0 + w.Projectiles["crossing"] = &Projectile{ID: "crossing", Source: c.View.Entity.ID, Player: true, Position: from, Destination: to, Attack: a, Power: 10} + hp := s.Entity.HP + w.updateCombat(.1) + if len(w.Projectiles) != 0 || s.Entity.HP != hp-10 { + t.Fatal("fast projectile tunneled through structure", s.Entity.HP) + } + home := w.terrain.Position(e.Position.X, e.Position.Z-2) + m := &Mob{Entity: p.Entity{ID: "attacker", Position: home, HP: 10}, Home: &home} + a.Effect = "damage" + a.Delivery = "melee" + a.Range = 3 + a.Multiplier = 1 + a.Cooldown = 1 + hp = s.Entity.HP + if !w.attackNearbyStructure(m, a, 12, 10, 100) || s.Entity.HP != hp-12 { + t.Fatal("mob did not damage structure") + } + hp = s.Entity.HP + w.attackNearbyStructure(m, a, 12, 10, 100) + if s.Entity.HP != hp { + t.Fatal("mob ignored cooldown") + } + // Roof support, jumping from a roof, and leaving the footprint use real height. + c.View.Entity.Position = p.Vec3{X: e.Position.X, Y: e.Position.Y + *e.Height, Z: e.Position.Z} + c.MoveZ = 0 + c.JumpVelocity = 0 + if err := w.jump(c); err != nil { + t.Fatal("could not jump from structure", err) + } + w.moveCharacter(c, .05) + if c.View.Entity.Position.Y <= e.Position.Y+*e.Height { + t.Fatal("jump did not rise above structure") + } + c.JumpVelocity = 0 + c.View.Entity.Position = p.Vec3{X: e.Position.X, Y: e.Position.Y + *e.Height, Z: e.Position.Z + *e.Depth/2 + .29} + c.MoveZ = 1 + w.moveCharacter(c, .05) + if c.View.Entity.Position.Y <= w.terrain.Height(c.View.Entity.Position.X, c.View.Entity.Position.Z) { + t.Fatal("walking off roof teleported to ground") + } +} diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go index 58e8f7f..cf2856d 100644 --- a/server/internal/game/combat.go +++ b/server/internal/game/combat.go @@ -90,6 +90,11 @@ func (w *World) combatTargets(player bool, effect string) []p.Entity { out = append(out, p.Entity{ID: "boss", Position: w.terrain.Position(0, 0), HP: w.BossHP}) } } + if effect == "damage" { + for _, id := range w.structureIDs() { + out = append(out, w.Structures[id].Entity) + } + } return out } func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) { @@ -129,13 +134,16 @@ func (w *World) attack(c *Character, target string) error { } from, to := body(c.View.Entity.Position), body(e.Position) extra := float64(0) + if e.Kind == "structure" { + extra = math.Max(*e.Width, *e.Depth) / 2 + } if target == "boss" { extra = 4 } if length3(from, to) > a.Range+extra { return errors.New("target out of reach") } - if _, blocked := w.terrainHit(from, to); blocked { + if _, blocked := w.combatLine(from, to, target); blocked { return errors.New("terrain blocks the attack") } if a.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles { @@ -206,7 +214,7 @@ func (w *World) areaPulse(shot Projectile) { if length3(body(e.Position), shot.Position) > shot.Attack.Radius { continue } - if _, blocked := w.terrainHit(shot.Position, body(e.Position)); blocked { + if _, blocked := w.combatLine(shot.Position, body(e.Position), e.ID); blocked { continue } w.combatHit(shot, e.ID) @@ -218,6 +226,12 @@ func (w *World) combatHit(shot Projectile, target string) { return } healing := shot.Attack.Effect == "heal" + if w.Structures[target] != nil { + if !healing { + w.damageStructure(target, shot.Power) + } + return + } if c := w.Characters[target]; c != nil { if c.View.Entity.State != "alive" || !c.Online || c.Sheltered { return @@ -301,7 +315,17 @@ func (w *World) updateCombat(dt float64) { } hit := "" hitPoint := obstacle + for _, id := range w.structureIDs() { + if f, ok := boxFraction(shot.Position, end, w.Structures[id].Entity, 0, 0); ok && f*length3(shot.Position, end) < best { + best = f * length3(shot.Position, end) + hit = id + hitPoint = lerp3(shot.Position, end, f) + } + } for _, e := range w.combatTargets(shot.Player, shot.Attack.Effect) { + if e.Kind == "structure" { + continue + } if e.ID == shot.Source && shot.Target != shot.Source { continue } diff --git a/server/internal/game/crafting.go b/server/internal/game/crafting.go index 2e866e8..3573632 100644 --- a/server/internal/game/crafting.go +++ b/server/internal/game/crafting.go @@ -13,6 +13,11 @@ import ( ) func (w *World) refreshCrafting(c *Character) { + for id, name := range (content.Catalog{Building: w.Balance.Building}).BuildingItems() { + if c.View.Inventory[id] > 0 { + c.View.StackNames[id] = name + } + } if c.View.Crafting == nil { c.View.Crafting = map[string]p.CraftProgress{} } diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go index 341396d..470d442 100644 --- a/server/internal/game/equipment.go +++ b/server/internal/game/equipment.go @@ -325,6 +325,9 @@ func (w *World) lootCorpse(c *Character, target string) error { if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange { return errors.New("corpse out of reach") } + if _, blocked := w.combatLine(body(c.View.Entity.Position), body(corpse.Entity.Position), ""); blocked { + return errors.New("corpse obstructed") + } seen := map[string]bool{} if err := validateOwnedItems(c.View.Items, seen); err != nil { return err diff --git a/server/internal/game/gathering.go b/server/internal/game/gathering.go index 098fa6c..c52cfab 100644 --- a/server/internal/game/gathering.go +++ b/server/internal/game/gathering.go @@ -176,6 +176,9 @@ func (w *World) gather(c *Character, target string) error { return errors.New("resource out of reach") } id := stringValue(e.ResourceID) + if _, blocked := w.combatLine(body(c.View.Entity.Position), body(e.Position), ""); blocked { + return errors.New("resource obstructed") + } if id == "" { id = e.Kind } @@ -271,7 +274,7 @@ func (w *World) consumeGathering(c *Character, id string) error { return errors.New("unknown gathering consumable") } func (w *World) jump(c *Character) error { - ground := w.terrain.Height(c.View.Entity.Position.X, c.View.Entity.Position.Z) + 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") } @@ -286,16 +289,21 @@ func (w *World) moveCharacter(c *Character, dt float64) { if math.Hypot(x, z) >= w.Balance.WorldRadius { x, z = pos.X, pos.Z } - ground := w.terrain.Height(x, z) - if c.JumpVelocity != 0 || pos.Y > w.terrain.Height(pos.X, pos.Z)+0.05 { - y := pos.Y + c.JumpVelocity*dt - w.Balance.GatheringRules.Gravity*dt*dt/2 + y := pos.Y + airborne := c.JumpVelocity != 0 || pos.Y > w.floorAt(pos.X, pos.Z, pos.Y)+.05 || (len(w.Structures) > 0 && pos.Y > w.floorAt(x, z, pos.Y)+.05) + if airborne { + y += c.JumpVelocity*dt - w.Balance.GatheringRules.Gravity*dt*dt/2 c.JumpVelocity -= w.Balance.GatheringRules.Gravity * dt - if y <= ground { - y = ground - c.JumpVelocity = 0 - } - c.View.Entity.Position = p.Vec3{X: x, Y: y, Z: z} - } else { - c.View.Entity.Position = w.terrain.Position(x, z) } + ground := w.floorAt(x, z, math.Max(pos.Y, y)) + next := p.Vec3{X: x, Y: math.Max(pos.Y, math.Max(y, ground)), Z: z} + if w.structureBlocked(pos, next) { + x, z = pos.X, pos.Z + ground = w.floorAt(x, z, math.Max(pos.Y, y)) + } + if y <= ground || !airborne { + y = ground + c.JumpVelocity = 0 + } + c.View.Entity.Position = p.Vec3{X: x, Y: y, Z: z} } diff --git a/server/internal/game/mobs.go b/server/internal/game/mobs.go index 3436c00..8f5089a 100644 --- a/server/internal/game/mobs.go +++ b/server/internal/game/mobs.go @@ -83,6 +83,9 @@ func (w *World) SpawnMobs(definition, value string) error { return errors.New("spawn would leave the surviving world") } positions = append(positions, w.terrain.Position(px, pz)) + if w.structureBlocked(positions[len(positions)-1], positions[len(positions)-1]) { + return errors.New("spawn intersects a structure") + } } for _, pos := range positions { id := w.combatID("mob") @@ -102,6 +105,9 @@ func (w *World) ensureMob(ch p.Chunk) { } hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) home := w.terrain.Position(x, z) + if w.structureBlocked(home, home) { + return + } w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: home, HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z), Home: &home, RespawnDelay: w.Balance.MobRespawnSeconds} w.dirty = true } @@ -131,6 +137,9 @@ func (w *World) updateSpawns(active map[string]bool) { continue } pos := w.terrain.Position(x, z) + if w.structureBlocked(pos, pos) { + continue + } near := false for _, c := range w.Characters { if c.Online && c.View.Entity.State == "alive" && distance(pos, c.View.Entity.Position) < rule.MinPlayerDistance { @@ -181,7 +190,7 @@ func (w *World) mobStep(m *Mob, to p.Vec3, speed, dt float64) { continue } dest := w.terrain.Position(x, z) - if math.Abs(dest.Y-from.Y) > w.Balance.CombatRules.MaxSlope*step { + if w.structureBlocked(from, dest) || math.Abs(dest.Y-from.Y) > w.Balance.CombatRules.MaxSlope*step { continue } m.Entity.Position = dest @@ -256,6 +265,9 @@ func (w *World) updateMobs(active map[string]bool, dt float64) { } continue } + if behavior != "passive" && w.attackNearbyStructure(m, attack, power, aggro, leash) { + continue + } var target *Character if c := w.Characters[m.Target]; c != nil && c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, *m.Home) <= leash { target = c @@ -270,7 +282,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) { } d := distance(c.View.Entity.Position, m.Entity.Position) if d < nearest && distance(c.View.Entity.Position, *m.Home) <= leash { - if _, blocked := w.terrainHit(body(m.Entity.Position), body(c.View.Entity.Position)); blocked { + if _, blocked := w.combatLine(body(m.Entity.Position), body(c.View.Entity.Position), ""); blocked { continue } target = c @@ -301,7 +313,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) { if w.Age()-m.LastAttack < attack.Cooldown { continue } - if _, blocked := w.terrainHit(body(m.Entity.Position), body(aim)); blocked { + if _, blocked := w.combatLine(body(m.Entity.Position), body(aim), targetID); blocked { w.mobStep(m, aim, speed, dt) continue } diff --git a/server/internal/game/powers.go b/server/internal/game/powers.go index 7e5258d..51d6b2c 100644 --- a/server/internal/game/powers.go +++ b/server/internal/game/powers.go @@ -278,6 +278,9 @@ func (w *World) checkPower(c *Character, v p.LearnedPower, target string) error for _, e := range w.combatTargets(true, v.Attack.Effect) { if e.ID == target { if length3(body(c.View.Entity.Position), body(e.Position)) > v.Attack.Range+func() float64 { + if e.Kind == "structure" { + return math.Max(*e.Width, *e.Depth) / 2 + } if target == "boss" { return 4 } @@ -285,7 +288,7 @@ func (w *World) checkPower(c *Character, v p.LearnedPower, target string) error }() { return errors.New("power target out of range") } - if _, blocked := w.terrainHit(body(c.View.Entity.Position), body(e.Position)); blocked { + if _, blocked := w.combatLine(body(c.View.Entity.Position), body(e.Position), e.ID); blocked { return errors.New("terrain blocks power") } found = true diff --git a/server/internal/game/revival.go b/server/internal/game/revival.go index 8347707..a586a20 100644 --- a/server/internal/game/revival.go +++ b/server/internal/game/revival.go @@ -19,7 +19,7 @@ func (w *World) Revive(caster *Character, corpseID, power string) (*Character, e if length3(caster.View.Entity.Position, corpse.Entity.Position) > w.Balance.Powers.RevivalRange { return nil, errors.New("stand next to the corpse") } - if _, blocked := w.terrainHit(body(caster.View.Entity.Position), body(corpse.Entity.Position)); blocked { + if _, blocked := w.combatLine(body(caster.View.Entity.Position), body(corpse.Entity.Position), ""); blocked { return nil, errors.New("terrain blocks the corpse") } if caster.PendingCast != nil { diff --git a/server/internal/game/stats.go b/server/internal/game/stats.go index fb9e346..9814f6d 100644 --- a/server/internal/game/stats.go +++ b/server/internal/game/stats.go @@ -173,6 +173,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error { if catalog.Combat != nil { w.Balance.Combat = catalog.Combat } + if catalog.Building != nil { + w.Balance.Building = catalog.Building + } if catalog.Powers != nil { w.Balance.Powers = catalog.Powers } diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 5009a04..e052423 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -76,6 +76,7 @@ type ResourceLayout struct { Resources []p.Entity `json:"resources"` } type World struct { + Structures map[string]*Structure `json:"structures,omitempty"` Kind string `json:"kind,omitempty"` ProjectileVisuals []p.ProjectileVisual `json:"projectileVisuals,omitempty"` Projectiles map[string]*Projectile `json:"projectiles,omitempty"` @@ -189,6 +190,9 @@ func (w *World) Restore(now time.Time) error { } w.dirty = true } + if e := w.restoreBuilding(); e != nil { + return e + } if w.ResourceLayouts == nil { w.ResourceLayouts = map[string]ResourceLayout{} } @@ -321,7 +325,7 @@ func (w *World) spawn(exclude string) (p.Vec3, error) { if radius > math.Max(0, math.Min(w.Balance.WorldRadius-32, w.SafeRadius()-8)) { break } - clear := true + clear := !w.structureBlocked(pos, pos) for id, c := range w.Characters { if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation { clear = false @@ -546,6 +550,8 @@ func (w *World) Intent(id string, i p.Intent) error { return w.consumeGathering(c, i.Target) case "gather": return w.gather(c, i.Target) + case "build": + return w.Build(c, i.Target, i.X, i.Z, i.Slot) case "learn": return w.LearnPower(c, i.Target) case "cast": @@ -895,6 +901,11 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { s.Entities = append(s.Entities, m.Entity) } } + for _, structure := range w.Structures { + if visible(structure.Entity.Position) { + s.Entities = append(s.Entities, structure.Entity) + } + } for _, corpse := range w.Corpses { if visible(corpse.Entity.Position) { s.Entities = append(s.Entities, corpse.Entity) diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index c0eaf5b..0b875cf 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -13,6 +13,7 @@ type Protocol struct { } type ContentCatalog struct { + Building *BuildingContent `json:"building,omitempty"` Combat *CombatContent `json:"combat,omitempty"` Crafting *CraftingContent `json:"crafting,omitempty"` EffectSets []EffectSet `json:"effectSets,omitempty"` @@ -25,6 +26,27 @@ type ContentCatalog struct { Version int64 `json:"version"` } +type BuildingContent struct { + Definitions []BuildingDefinition `json:"definitions"` + MaxSlope float64 `json:"maxSlope"` + MaxStructures int64 `json:"maxStructures"` + ProtectedRadius float64 `json:"protectedRadius"` + Range float64 `json:"range"` +} + +type BuildingDefinition struct { + Depth float64 `json:"depth"` + Description string `json:"description"` + HP float64 `json:"hp"` + Height float64 `json:"height"` + ID string `json:"id"` + Level int64 `json:"level"` + Model string `json:"model"` + Name string `json:"name"` + Profession string `json:"profession"` + Width float64 `json:"width"` +} + type CombatContent struct { Attacks []CombatAttack `json:"attacks"` Loot []LootTable `json:"loot"` @@ -302,6 +324,7 @@ type TitleEffects struct { type ContentChange struct { Attack *CombatAttackDraft `json:"attack,omitempty"` Biome *BiomeDefinitionDraft `json:"biome,omitempty"` + Building *BuildingDraft `json:"building,omitempty"` Consumable *GatheringConsumableDraft `json:"consumable,omitempty"` CraftMaterial *CraftMaterialDraft `json:"craftMaterial,omitempty"` CraftProfession *GatheringSkillDraft `json:"craftProfession,omitempty"` @@ -357,6 +380,19 @@ type BiomeDefinitionDraft struct { Weight int64 `json:"weight"` } +type BuildingDraft struct { + Depth float64 `json:"depth"` + Description string `json:"description"` + HP float64 `json:"hp"` + Height float64 `json:"height"` + ID *string `json:"id,omitempty"` + Level int64 `json:"level"` + Model string `json:"model"` + Name string `json:"name"` + Profession string `json:"profession"` + Width float64 `json:"width"` +} + type GatheringConsumableDraft struct { Description string `json:"description"` ID *string `json:"id,omitempty"` @@ -581,7 +617,9 @@ type Chunk struct { } type Entity struct { + Depth *float64 `json:"depth,omitempty"` HP float64 `json:"hp"` + Height *float64 `json:"height,omitempty"` ID string `json:"id"` Kind string `json:"kind"` MaxHP float64 `json:"maxHp"` @@ -593,6 +631,7 @@ type Entity struct { ResourceID *string `json:"resourceId,omitempty"` SkillID *string `json:"skillId,omitempty"` State string `json:"state"` + Width *float64 `json:"width,omitempty"` } type Vec3 struct { diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 15485c6..ef8388b 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,6 +17,7 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { + Building *content.BuildingDefinition `json:"building,omitempty"` Power *content.PowerDefinition `json:"power,omitempty"` Weapon *content.GatheringSkill `json:"weapon,omitempty"` CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"` @@ -53,7 +54,7 @@ type CatalogResult struct { // Explicit definition IDs are reserved for trusted seed/import code. Browser // publications omit them; the server assigns an ID after resolving request replay. func (c CatalogChange) HasDefinitionID() bool { - return (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "") + return (c.Building != nil && c.Building.ID != "") || (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "") } type CatalogAudit struct { @@ -138,6 +139,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) { } catalog.RestorePowers(b) } + if catalog.Building == nil { + b, e := content.Load() + if e != nil { + return catalog, e + } + catalog.RestoreBuilding(b) + } return catalog, catalog.Validate() } func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) { @@ -173,12 +181,14 @@ func (c CatalogChange) validate() error { } valid := false count := 0 - for _, present := range []bool{c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} { + for _, present := range []bool{c.Building != nil, c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} { if present { count++ } } switch c.Op { + case "create-building": + valid = c.Building != nil case "create-power": valid = c.Power != nil case "create-weapon": diff --git a/server/internal/store/catalog_ids_test.go b/server/internal/store/catalog_ids_test.go index aa05909..2f21874 100644 --- a/server/internal/store/catalog_ids_test.go +++ b/server/internal/store/catalog_ids_test.go @@ -26,6 +26,7 @@ func TestServerAssignedCatalogIDsSurviveReplayAndRestart(t *testing.T) { var last CatalogChange var lastResult CatalogResult for _, draft := range []CatalogChange{ + {Op: "create-building", Building: &content.BuildingDefinition{Name: "Same name", Model: "wall", Width: 4, Depth: 1, Height: 2, HP: 250, Profession: "builder", Level: 1}}, {Op: "create-requirement-set", RequirementSet: &content.RequirementSet{Name: "Same name", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 1}}}}, {Op: "create-effect-set", EffectSet: &content.EffectSet{Name: "Same name", Modifiers: []content.StatModifier{{Stat: "defence", Flat: 2}}}}, {Op: "create-title", Title: &content.Title{Name: "Same name", Scope: "personal", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 2}}}}, @@ -86,7 +87,7 @@ func TestServerAssignedCatalogIDsSurviveReplayAndRestart(t *testing.T) { t.Fatal("restart changed replay identity", err) } audits, err := reopened.CatalogChanges(ctx) - if err != nil || len(audits) != 8 || audits[0].Target != lastResult.ID { + if err != nil || len(audits) != len(seen) || audits[0].Target != lastResult.ID { t.Fatal("generated ID not persisted in audit", err) } } diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index 4e53af8..9e8ba3d 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -35,6 +35,9 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP } // Preview validates a provisional identity but does not reserve or expose it. if !change.HasDefinitionID() { + if resolved.Building != nil { + resolved.Building.ID = "" + } if resolved.Power != nil { resolved.Power.ID = "" } @@ -139,7 +142,24 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str } powers := *c.Powers c.Powers = &powers + if c.Building == nil { + b, e := content.Load() + if e != nil { + return invalid(e) + } + c.RestoreBuilding(b) + } + building := *c.Building + c.Building = &building switch change.Op { + case "create-building": + v := *change.Building + if v.ID == "" { + v.ID = "building_" + game.ID() + } + c.Building.Definitions = append(slices.Clone(c.Building.Definitions), v) + resolved.Building = &v + target = v.ID case "create-power": v := *change.Power if v.ID == "" { diff --git a/server/internal/transport/powers.go b/server/internal/transport/powers.go index 1e19f9b..22247b0 100644 --- a/server/internal/transport/powers.go +++ b/server/internal/transport/powers.go @@ -9,6 +9,15 @@ import ( ) func (h *HTTP) powerRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/building", func(w http.ResponseWriter, r *http.Request) { + if _, e := h.auth.account(r); e != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + respond(w, 200, h.s.world.Balance.Building) + }) mux.HandleFunc("GET /api/powers", func(w http.ResponseWriter, r *http.Request) { account, e := h.auth.account(r) if e != nil {