diff --git a/client/src/character-stats.ts b/client/src/character-stats.ts index 9f62d0a..363fd1c 100644 --- a/client/src/character-stats.ts +++ b/client/src/character-stats.ts @@ -31,6 +31,7 @@ export function itemDetails(item:ItemInstance,c:Character) { const card=node('article','','gear-card'); 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.attack)card.append(node('p',`${item.attack.name} · ${item.attack.delivery} · ${item.attack.effect} · ${item.attack.range}m range · ${item.attack.cooldown}s cooldown · ${item.attack.stamina} stamina · ${item.attack.radius}m area · ${item.attack.duration}s duration`,'progression-note')); if(item.requirementMessage)card.append(node('p',item.requirementMessage,'gear-requirements')); return card; } diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index b241138..c8aa3e8 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -8,7 +8,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'],['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'],['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;} @@ -63,13 +63,13 @@ function form(title:string,op:string,payload:()=>object){ } function previewView(result:ContentPreview){ const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`)); - const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable; + const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn; if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p','Permanent ID assigned on publication.','muted')); const requirements=r.title?.requirements??r.requirementSet?.requirements; if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / '))); if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`)); const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers)); - if(r.gatheringSkill||r.resource||r.biome||r.consumable)root.append(node('pre',JSON.stringify(r.gatheringSkill??r.resource??r.biome??r.consumable,null,2))); + if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(node('pre',JSON.stringify(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn,null,2))); 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'),node('pre',JSON.stringify(r.stats,null,2)));root.append(details);} return root; } @@ -87,8 +87,9 @@ function itemForm(){ const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select([...statKeys,'gatheringLevel','gatheringYield','gatheringSpeed','gatheringXP'],value?.stat),minimum=number(value?.value??1);group.append(field('Stat',stat),field('Minimum value',minimum));return {node:group,read:()=>({stat:stat.value,value:Number(minimum.value)})}},[],statKeys.length); const titles=node('fieldset','','catalog-title-choices');titles.append(node('legend','Required titles'));const checks=(catalog.titles??[]).map(t=>{const input=node('input');input.type='checkbox';titles.append(field(t.name,input));return {id:t.id,input}}); const sets=setChoices(true); - const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),slot:slot.value,weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}}); - fields.append(values.node,field('Equipment slot',slot),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node); + const attack=contentChoice([{id:'',name:'Basic melee / none'},...(catalog.combat?.attacks??[])]);attack.required=false; + const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.value}:{}),weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}}); + fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node); } function statsForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} @@ -99,7 +100,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(['gathering','resources','biomes','consumables'].includes(section)){gatheringList(); + if(['attacks','mobs','loot','spawns'].includes(section)){combatList(); + }else if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList(); }else if(section==='titles'){ list.append(button('Create title',titleForm));for(const t of catalog.titles??[]){const d=node('details','','catalog-definition');d.append(node('summary',t.name),node('p',`${t.id} · ${t.scope} · ${t.description}`),node('p',(t.requirements??[]).map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')),modifiersView(t.effects.modifiers));if(t.effects.damage||t.effects.moveSpeed)d.append(node('p',`Damage ${t.effects.damage}; movement ${t.effects.moveSpeed}`));list.append(d);} }else if(section==='items'){ @@ -152,3 +154,35 @@ function gatheringList(){ 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),node('pre',JSON.stringify(v,null,2)));list.append(d);} } + +function combatForm(kind:string){ + if(editing||saving){show('Finish the open draft first.');return;} + const values=identity(),c=catalog.combat; + if(kind==='attacks'){ + const delivery=select(['melee','projectile']),effect=select(['damage','heal']),stat=select(['meleeDamage','rangedDamage','magicDamage']); + const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Projectile speed (m/s)',35,1,100],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const; + const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max)})); + const fields=form('Create attack profile','create-attack',()=>({attack:{...values.read(),delivery:delivery.value,effect:effect.value,stat:stat.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); + fields.append(values.node,field('Delivery',delivery),field('Effect',effect),field('Player stat to scale',stat),...inputs.map(v=>field(v.label,v.input)),node('p','Damage targets opponents; healing targets allies. Players currently target mobs and the Harbinger, while player healing targets living players. Projectiles fly toward the selected position and can miss. Areas remain fixed at impact. Damage is sampled at attack time.','muted')); + }else if(kind==='mobs'){ + const model=select(['sentinel','boss']),behavior=select(['aggressive','guard','passive']),attack=contentChoice(c?.attacks??[]),loot=contentChoice([{id:'',name:'No loot'},...(c?.loot??[])]);loot.required=false; + const settings=[['level','Level',1,1,10000],['hp','Base health per level',54,1,1000000],['damage','Base attack power per level',6,0,100000],['defence','Flat defence',0,0,100000],['speed','Movement speed',4,.1,30],['aggroRange','Detection range',24,1,128],['leashRange','Maximum distance from home',160,1,512],['scalePerDay','World-age scaling per day',.1,0,10],['xp','Character XP on defeat',50,0,1000000000]] as const; + const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max,key==='xp'||key==='level'?'1':'any')})); + const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); + fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted')); + }else if(kind==='loot'){ + const items=[...catalog.items,...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))]; + const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32); + const fields=form('Create loot table','create-loot',()=>({loot:{...values.read(),entries:entries.read()}}));fields.append(values.node,entries.node,node('p','Blank groups roll independently; 100% is guaranteed. Each named group selects one entry by weight, then rolls that entry’s chance. Finisher luck affects non-guaranteed chances. New mobs leave a lootable corpse; the corpse is shared and may be looted by nearby players.','muted')); + }else{ + const mob=contentChoice(c?.mobs??[]),settings=[['x','Center X',0,-100000,100000],['z','Center Z',0,-100000,100000],['radius','Region radius',20,0,512],['count','Maximum population',1,1,32],['respawn','Respawn delay (seconds)',60,1,604800],['minPlayerDistance','Minimum player distance at spawn',15,0,128]] as const,inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max,key==='count'?'1':'any')})); + const biomes=node('fieldset','','catalog-title-choices');biomes.append(node('legend','Allowed biomes (none = any)'));const checks=(catalog.gathering?.biomes??[]).map(b=>{const i=node('input');i.type='checkbox';biomes.append(field(b.name,i));return{id:b.id,input:i}}); + const fields=form('Create mob spawn rule','create-spawn',()=>({spawn:{...values.read(),mobId:mob.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)])),biomes:checks.filter(v=>v.input.checked).map(v=>v.id)}}));fields.append(values.node,field('Mob definition',mob),...inputs.map(v=>field(v.label,v.input)),biomes,node('p','Rules run in each survival world, inside its surviving boundary, when players subscribe to the region. Spawn positions are deterministic and slots retain identity across respawns. For a one-time spawn in one world, use Worlds → Actions → Spawn mobs.','muted')); + } +} +function combatList(){ + const c=catalog.combat,entries=section==='attacks'?c?.attacks:section==='mobs'?c?.mobs:section==='loot'?c?.loot:c?.spawns; + const labels:Record={attacks:'attack profile',mobs:'mob',loot:'loot table',spawns:'mob spawn rule'}; + list.append(button(`Create ${labels[section]}`,()=>combatForm(section))); + for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d)} +} diff --git a/client/src/control.ts b/client/src/control.ts index b4fd6b7..bc2621c 100644 --- a/client/src/control.ts +++ b/client/src/control.ts @@ -1,4 +1,5 @@ import './portal.css'; +import { showMobSpawner } from './mob-spawner'; import { permanentTitles, progressionSummary } from './progression'; import { statsBreakdown, equipmentDetails } from './character-stats'; import { showCatalog, hasCatalogDraft } from './content-editor'; @@ -14,10 +15,11 @@ let busy = false; let draft: Draft; const commandMenu=registerMenu($('command-dialog'),()=>$('command-dialog').close()); const characterMenu=registerMenu($('character-dialog'),()=>$('character-dialog').close()); -const labels: Record = { 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' }; +const labels: Record = { 'spawn-mobs':'Spawn mobs', 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' }; Object.assign(labels, { 'grant-item':'Add item', 'remove-item':'Remove item', 'grant-title':'Add / restore title', 'revoke-title':'Remove title' }); function notify(message: string) { $('control-message').textContent = message; $('control-message').hidden = false; } function openCommand(op: string, worldId = '', target = '', value = '') { + if(op==='spawn-mobs'){void showMobSpawner(worldId,()=>{notify('Mob spawn queued. Check the audit for its result.');void refresh()});return;} draft = { id: crypto.randomUUID(), worldId, op, target, value }; $('command-form').reset(); const create = op === 'create-world', rename = op === 'rename'; @@ -74,7 +76,7 @@ function render() { const row = body.insertRow(); const link = el('a', w.id, 'record-link'); link.href = gameURL(w.id); const worldName = el('div'); worldName.append(link, el('small', `Catalog ${w.catalogVersion ?? 0}`, 'muted block')); cell(row, worldName); const status = el('div', '', 'badge-group'); status.append(badge(w.phase)); if (!w.available) status.append(badge('offline')); else if (w.closed) status.append(badge('closed')); cell(row, status); cell(row, `${w.living} / ${w.capacity}`); cell(row, String(w.dead)); cell(row, date(w.bossAt)); - const options = [w.closed ? 'open-admissions' : 'close-admissions']; if (w.phase === 'gathering') options.push('awaken-boss'); options.push('end-world'); + const options = [w.closed ? 'open-admissions' : 'close-admissions']; if (w.phase === 'gathering') options.push('awaken-boss'); options.push('spawn-mobs','end-world'); cell(row, actions(w.id, options, '', '', !w.available || ['won','lost'].includes(w.phase))); count++; } parent.append(node); $('table-note').textContent = 'Availability reflects the world-owner lease. Living counts include offline characters.'; diff --git a/client/src/generated.ts b/client/src/generated.ts index 786742c..2837dac 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -9,6 +9,7 @@ export interface Protocol { } export interface ContentCatalog { + combat?: CombatContent; effectSets?: EffectSet[]; gathering?: GatheringContent; items: ItemDefinition[]; @@ -18,6 +19,78 @@ export interface ContentCatalog { version: number; } +export interface CombatContent { + attacks: CombatAttack[]; + loot: LootTable[]; + mobs: MobDefinition[]; + spawns: MobSpawn[]; +} + +export interface CombatAttack { + cooldown: number; + delivery: string; + description: string; + duration: number; + effect: string; + id: string; + interval: number; + multiplier: number; + name: string; + radius: number; + range: number; + speed: number; + stamina: number; + stat: string; +} + +export interface LootTable { + description: string; + entries: LootEntry[]; + id: string; + name: string; +} + +export interface LootEntry { + amount: number; + chance: number; + group: string; + item: string; + weight: number; +} + +export interface MobDefinition { + aggroRange: number; + attackId: string; + behavior: string; + damage: number; + defence: number; + description: string; + hp: number; + id: string; + leashRange: number; + level: number; + lootId: string; + model: string; + name: string; + scalePerDay: number; + speed: number; + xp: number; +} + +export interface MobSpawn { + biomes: string[]; + count: number; + description: string; + id: string; + minPlayerDistance: number; + mobId: string; + name: string; + radius: number; + respawn: number; + x: number; + z: number; +} + export interface EffectSet { description: string; id: string; @@ -81,6 +154,7 @@ export interface GatheringSkill { } export interface ItemDefinition { + attackId?: string; description: string; dropChance: number; id: string; @@ -131,6 +205,7 @@ export interface TitleEffects { } export interface ContentChange { + attack?: CombatAttackDraft; biome?: BiomeDefinitionDraft; consumable?: GatheringConsumableDraft; effectSet?: EffectSetDraft; @@ -139,15 +214,35 @@ export interface ContentChange { gatheringSkill?: GatheringSkillDraft; id: string; item?: ItemDraft; + loot?: LootTableDraft; + mob?: MobDefinitionDraft; op: string; reason: string; requirementSet?: RequirementSetDraft; requirementSetIds?: string[]; resource?: ResourceDefinitionDraft; + spawn?: MobSpawnDraft; stats?: ContentStatsRules; title?: TitleDraft; } +export interface CombatAttackDraft { + cooldown: number; + delivery: string; + description: string; + duration: number; + effect: string; + id?: string; + interval: number; + multiplier: number; + name: string; + radius: number; + range: number; + speed: number; + stamina: number; + stat: string; +} + export interface BiomeDefinitionDraft { color: string; description: string; @@ -181,6 +276,7 @@ export interface GatheringSkillDraft { } export interface ItemDraft { + attackId?: string; description: string; dropChance: number; id?: string; @@ -191,6 +287,32 @@ export interface ItemDraft { weight: number; } +export interface LootTableDraft { + description: string; + entries: LootEntry[]; + id?: string; + name: string; +} + +export interface MobDefinitionDraft { + aggroRange: number; + attackId: string; + behavior: string; + damage: number; + defence: number; + description: string; + hp: number; + id?: string; + leashRange: number; + level: number; + lootId: string; + model: string; + name: string; + scalePerDay: number; + speed: number; + xp: number; +} + export interface RequirementSetDraft { description: string; id?: string; @@ -214,6 +336,20 @@ export interface ResourceDefinitionDraft { xp: number; } +export interface MobSpawnDraft { + biomes: string[]; + count: number; + description: string; + id?: string; + minPlayerDistance: number; + mobId: string; + name: string; + radius: number; + respawn: number; + x: number; + z: number; +} + export interface TitleDraft { description: string; effects: TitleEffects; @@ -274,8 +410,10 @@ export interface Entity { id: string; kind: string; maxHp: number; + model?: string; name: string; position: Vec3; + radius?: number; requiredLevel?: number; resourceId?: string; skillId?: string; @@ -300,6 +438,7 @@ export interface GatheringRisk { export interface Character { ack: number; allocatedStats: { [key: string]: number }; + attack?: CombatAttack; carryWeight: number; consumables?: GatheringConsumable[]; entity: Entity; @@ -355,6 +494,7 @@ export interface TimedGatheringEffect { } export interface ItemInstance { + attack?: CombatAttack; definitionId: string; description: string; equippable: boolean; diff --git a/client/src/main.ts b/client/src/main.ts index 65f6171..891fc80 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -39,6 +39,7 @@ let lastProgressAt = 0; function progressSignature(): number | undefined { if (!pendingAction || !snapshot) return undefined; if (pendingAction.op === 'attack') { + if (pendingAction.target === snapshot.self.entity.id) return snapshot.self.entity.hp; if (pendingAction.target === 'boss') return snapshot.world.bossHp; return snapshot.entities.find(e => e.id === pendingAction!.target)?.hp; } @@ -65,16 +66,16 @@ 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', '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'].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' ? ['boss', 'sentinel'] : ['tree', 'ore', 'herb', 'corpse']; + 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) { const p = snapshot.self.entity.position; - target = snapshot.entities.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]; + 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]; } if (!target) { notice('No target nearby.'); return; } selection(target); @@ -202,11 +203,17 @@ async function boot() { } let {x,z} = input.movement; if (x || z) { walkTo = undefined; pendingAction = undefined; } + const actionTarget = pendingAction?.target === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === pendingAction?.target); + if (pendingAction?.op === 'attack') { + if (!actionTarget || actionTarget.hp <= 0) { walkTo = undefined; pendingAction = undefined; } + else walkTo = actionTarget.position; + } 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 = snapshot.entities.find(e => e.id === pendingAction?.target); - const range = pendingAction ? pendingAction.op === 'attack' ? config.attackRange + (target?.kind === 'boss' ? 3 : -0.5) : config.gatherRange - 0.5 : 0.8; - if (distance <= range) { + 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 reach = pendingAction?.op === 'attack' && target ? Math.hypot(distance, target.position.y-p.y) : distance; + if (reach <= range) { if (!pendingAction) { walkTo = undefined; } // A single fire-and-forget attempt can land a hair outside the authoritative // server position (which may lag a stale/throttled client render) and get @@ -222,15 +229,16 @@ async function boot() { actionElapsed = 0; const sig = progressSignature(); if (sig !== undefined && sig !== lastProgress) { lastProgress = sig; lastProgressAt = Date.now(); } - if (Date.now() - lastProgressAt > Math.max(5000,((snapshot.gatherRisks?.[target?.resourceId??target?.kind??'']?.seconds??0)+2)*1000)) { + const attackWait = pendingAction.op === 'attack' && snapshot.self.attack ? snapshot.self.attack.cooldown + snapshot.self.attack.range / snapshot.self.attack.speed + 2 : 0; + if (Date.now() - lastProgressAt > Math.max(5000,attackWait*1000,((snapshot.gatherRisks?.[target?.resourceId??target?.kind??'']?.seconds??0)+2)*1000)) { avoidUntil.set(pendingAction.target, Date.now() + 8000); const retryOp = pendingAction.op === 'loot' ? 'gather' : pendingAction.op; walkTo = undefined; pendingAction = undefined; - if(retryOp!=='gather')action(retryOp);else notice('Gathering stopped. Select a resource to try again.'); + if(retryOp!=='gather' && snapshot.self.attack?.effect!=='heal')action(retryOp);else notice('Action stopped. Select a target to try again.'); } else if(pendingAction.op!=='gather'||!gatherSent) { send(pendingAction.op, pendingAction.target);if(pendingAction.op==='gather')gatherSent=sequence; } } } - } else { x = dx / distance; z = dz / distance; actionElapsed = 0.3; } + } else if (distance > .01) { x = dx / distance; z = dz / distance; actionElapsed = 0.3; } } view.moving = !!(x || z); if (inputElapsed >= 0.05) { send('move', '', x, z); inputElapsed = 0; } @@ -295,7 +303,7 @@ 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) { selection(hit.entity); action(['boss', 'sentinel'].includes(hit.entity.kind) ? 'attack' : 'gather'); } + if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel','mob','player'].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/mob-spawner.ts b/client/src/mob-spawner.ts new file mode 100644 index 0000000..5de54f1 --- /dev/null +++ b/client/src/mob-spawner.ts @@ -0,0 +1,17 @@ +import { api, el } from './portal-shared'; +import type { ContentCatalog } from './generated'; +import { registerMenu } from './menu-focus'; + +export async function showMobSpawner(worldId:string,onQueued:()=>void){ + const dialog=el('dialog'),form=el('form'),heading=el('h2',`Spawn mobs in ${worldId}`),mob=el('select'),count=el('input'),x=el('input'),z=el('input'),reason=el('textarea'),error=el('p','','error'),preview=el('p','','muted'),submit=el('button','Queue spawn','button'),cancel=el('button','Cancel','button secondary'); + const field=(name:string,input:HTMLElement)=>{const label=el('label',name);label.append(input);return label}; + for(const input of [count,x,z]){input.type='number';input.required=true;input.value='0';input.step='any'}count.min='1';count.max='32';count.step='1';count.value='1';mob.required=true;reason.required=true;reason.minLength=5;reason.maxLength=240; + const footer=el('footer');cancel.type='button';submit.type='submit';submit.disabled=true;footer.append(cancel,submit);form.append(heading,field('Mob definition',mob),field('Count',count),field('World X',x),field('World Z',z),preview,field('Reason',reason),error,footer);dialog.append(form);document.body.append(dialog); + const focus=registerMenu(dialog,()=>{dialog.close();dialog.remove();focus.dispose()});cancel.onclick=()=>focus.close();dialog.addEventListener('close',()=>{if(dialog.isConnected)focus.close()});const previous=document.activeElement;dialog.showModal();focus.opened(previous); + const update=()=>{preview.textContent=`Spawn ${count.value} × ${mob.selectedOptions[0]?.text??'selected creature'} near X ${x.value}, Z ${z.value}. Multiple mobs use a 2m grid. These mobs can attack immediately and do not respawn.`};form.oninput=update; + try{const data=await api<{catalog:ContentCatalog}>('/api/control/catalog');if(!dialog.isConnected)return;for(const d of data.catalog.combat?.mobs??[])mob.append(new Option(`${d.name} · level ${d.level}`,d.id));submit.disabled=!mob.options.length;update()}catch(e){error.textContent=(e as Error).message} + let id=crypto.randomUUID(),last='',busy=false; + form.onsubmit=async event=>{event.preventDefault();if(busy)return;const body={worldId,op:'spawn-mobs',target:mob.value,value:`${Number(count.value)},${Number(x.value)},${Number(z.value)}`,reason:reason.value.trim()};const serialized=JSON.stringify(body);if(last&&last!==serialized)id=crypto.randomUUID();last=serialized;busy=true;submit.disabled=true;error.textContent=''; + try{await api('/api/control/commands',{id,...body});focus.close();onQueued()}catch(e){error.textContent=(e as Error).message}finally{busy=false;submit.disabled=false} + }; +} diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 57adbe6..021319f 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -72,7 +72,7 @@ export class WorldView { gltf.scene.traverse(child => { if (!(child instanceof T.Mesh)) return; const geometry = child.geometry.clone().applyMatrix4(child.matrixWorld); - const mesh = new T.InstancedMesh(geometry, child.material, kind === 'boss' ? 1 : 2048); + const mesh = new T.InstancedMesh(geometry, child.material, 2048); mesh.count = 0; mesh.instanceMatrix.setUsage(T.DynamicDrawUsage); mesh.castShadow = true; @@ -99,6 +99,11 @@ export class WorldView { 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: [] }); + for(const kind of ['projectile','area-damage','area-heal']){ + const geometry=kind==='projectile'?new T.SphereGeometry(.2,6,4):new T.RingGeometry(.92,1,40); + const mesh=new T.InstancedMesh(geometry,new T.MeshBasicMaterial({color:kind==='area-heal'?'#81ebb0':kind==='area-damage'?'#ed855e':'#ffe0a3',side:T.DoubleSide,transparent:kind!=='projectile',opacity:.7,depthWrite:false}),2048); + mesh.count=0;mesh.userData.kind=kind;this.scene.add(mesh);this.batches.set(kind,{parts:[mesh],entities:[]}); + } } resize() { const width = innerWidth, height = innerHeight, aspect = width / height; @@ -160,7 +165,7 @@ export class WorldView { } updateEntities(entities: Entity[]) { for (const batch of this.batches.values()) batch.entities = []; - for (const entity of entities) this.batches.get(entity.kind)?.entities.push(entity); + for (const entity of entities) this.batches.get(entity.model??(entity.kind==='area'?`area-${entity.state}`:entity.kind))?.entities.push(entity); for (const batch of this.batches.values()) { const count = Math.min(2048, batch.entities.length); for (let i = 0; i < count; i++) { @@ -169,7 +174,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(scale); 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; 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(); } @@ -191,13 +196,13 @@ export class WorldView { const danger = snapshot.world.phase === 'cataclysm'; (this.scene.background as T.Color).set(danger ? '#c19f9e' : '#b9ccd0'); (this.scene.fog as T.Fog).color.copy(this.scene.background as T.Color); - if (this.selected) this.selected = snapshot.entities.find(e => e.id === this.selected!.id); + if (this.selected) this.selected = this.selected.id === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === this.selected!.id); } pick(clientX: number, clientY: number): { entity?: Entity; point?: T.Vector3 } { const rect = this.canvas.getBoundingClientRect(); this.ray.setFromCamera(new T.Vector2((clientX - rect.left) / rect.width * 2 - 1, -(clientY - rect.top) / rect.height * 2 + 1), this.camera); const objects: T.Object3D[] = []; - for (const batch of this.batches.values()) objects.push(...batch.parts); + for (const [kind,batch] of this.batches)if(kind!=='projectile'&&!kind.startsWith('area-'))objects.push(...batch.parts); const hit = this.ray.intersectObjects(objects, false)[0]; if (hit?.instanceId !== undefined) { const batch = this.batches.get(hit.object.userData.kind); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d3f67e3..af5d53a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -170,6 +170,18 @@ from enabling themselves or each other. Invalidated equipment returns to the bag Legacy knife/spear stacks migrate once, including corpses; duplicate instance IDs within a world fail restoration. Materials and consumables remain quantity stacks. +## Combat and mobs + +Combat attack definitions are copied into weapon and mob instances. Go resolves +straight projectiles with swept target collision and terrain obstruction, and +bounded stationary damage/healing areas. Living-source checks preserve death and +shelter boundaries. Projectiles, areas, mob identity/home/health, and loot rolls +are persisted in world snapshots; impacts and spawn-command outcomes commit before +publication. Mob motion crosses chunks with local slope checks and home leashes; +inactive mobs retain state. Region spawn rules use persisted explored biome IDs +(legacy layouts fall back to their stored biome names). See +[milestone 4 handoff](MILESTONE-4.md) for behavior, limits, and manual checks. + ## Security scope - Production login: OIDC verification (issuer, audience, signature, expiry), PKCE, diff --git a/docs/MILESTONE-4.md b/docs/MILESTONE-4.md new file mode 100644 index 0000000..92f5387 --- /dev/null +++ b/docs/MILESTONE-4.md @@ -0,0 +1,117 @@ +# Milestone 4: combat and mobs + +Implemented for manual playtesting. Milestone 4.5 (rigs, equipment attachments, +animation, and sound) has not started. This build uses existing model presets. + +## Combat + +Control → Content → Attacks defines reusable melee/projectile attacks, damage or +healing, the player stat used for power, multiplier, range, cooldown, stamina cost, +projectile speed, area radius, duration, and pulse interval. Weapon definitions can +select an attack. Acquired weapon instances copy that attack, so later catalog +publication does not rewrite existing equipment. Weapons without one retain basic +melee. Weapon switching cannot bypass a cooldown already incurred. + +For this playtest, ranged combat uses **selected targets**. Clicking a creature or +pressing F approaches to range and attacks. A projectile flies toward the position +where its target was when fired; moving targets can dodge it, and another eligible +target can intercept it. Terrain blocks attacks. The server owns range, cooldowns, +costs, movement, collision, damage, healing, and rewards. Ammunition, free aiming, +weapon proficiency, learned spells, and ability unlocks remain future work. + +Damage is PvE: player attacks hit creatures; creature attacks hit living players. +Player healing can target self or other living players. Creature healing supports +self/nearby creatures while engaged. Healing cannot resurrect a corpse or heal a +sheltered/offline player. Player power uses the chosen final stat; mob power uses +its damage value, scaling, and attack multiplier. Healing uses the same power +calculation without critical rolls. Existing defence/dodge rules still apply. + +Radius creates a burst at impact. Positive duration adds a stationary area that +pulses at its interval through its deadline, in addition to the initial impact. +Areas can damage or heal across chunk edges; nearest targets are processed first, +with stable ID ordering for ties. Rings show persistent areas; instantaneous bursts +currently have no lingering ring. This is the area-effect foundation, not the later +buff/debuff, moving aura, spell XP, or resurrection system. + +Projectiles and areas retain IDs, sampled power, positions, and deadlines in world +checkpoints. Impact and reward changes are persisted before publication. Movement +uses the existing one-second checkpoint cadence; a crash can roll back intervening +movement. Restoring does not replay an impact or catch up missed area pulses in a +burst. Source death, shelter, or world completion cancels outstanding effects. + +## Mobs, loot, and spawning + +Four new Content tabs follow the existing preview, version check, server-generated +IDs, audited publication, and retry-safe workflow: Attacks, Mobs, Loot tables, and +Mob spawns. Definitions remain append-only. + +Mobs select a model preset, level, health, damage, defence, speed, aggro range, +pursuit limit, world-age scaling, kill XP, attack, and optional loot table. Behaviors: + +- Aggressive: acquire nearby players, pursue within the home leash. +- Guard: acquire nearby players, remain within the home aggro radius. +- Passive: retaliate when damaged, without initiating attacks. + +Health and damage at spawn/respawn use +`base × level × (1 + world age in days × scale per day)`. +These are provisional tuning rules. Instances retain their definition, attack, +loot table, health, home, and identity across chunk crossings and restarts. They +simulate when their current or home chunk is active and return home beyond their +pursuit limit. Movement checks slopes and uses deterministic sidesteps; it is not +full pathfinding around forests or future structures. Tree collision remains deferred. + +Loot tables support independent entries and weighted groups. Every ungrouped entry +rolls its chance; each named group chooses one entry by weight and then rolls that +entry's chance. Chance 100 guarantees the listed quantity; luck modifies lower +chances. Equipment/materials/consumables are supported. Loot rolls once into a +shared lootable corpse, using existing inventory transfer and persistence rules. +There is no personal loot reservation, recursive table, or condition editor yet. +Existing procedural sentinels retain their legacy direct-to-inventory rewards. + +Mob spawn definitions place deterministic populations in a configured region, +optionally filtered by biome, with respawn and minimum player-distance settings. +They apply to **every world receiving the catalog**, activate around subscribed +chunks, and supplement existing procedural sentinels. Explored biome assignments +are retained when catalog weights change. Initial content has no regional rules. + +For a specific world, Control → Worlds → Spawn mobs queues 1–32 mobs near supplied +X/Z coordinates (a 2m grid for groups). The world owner validates the entire batch +before spawning. Live admin spawns do not respawn. Command completion and the +world snapshot commit together; retrying the same request cannot duplicate mobs. +Ended worlds reject spawning. Events, directed swarms, announcements, and delaying +the Harbinger remain on the later live-operations roadmap. + +Initial work caps in balance.yaml are 512 mobs, 256 projectiles, 64 persistent or +pending areas, and 64 targets per area pulse. These are bounds, not increased +tested-capacity claims. Region rules can be skipped when the mob cap is reached. + +## Manual playtest + +1. In Content → Equipment, create a level-1 weapon using **Bow shot**. Grant it to + your test character in Characters → Manage items and titles, then equip it. + Click a sentinel from a distance: approach to range, visible travel, delayed hit, + stamina consumption. Unequip and confirm basic melee still works. +2. In Worlds → Spawn mobs, choose **Ash guard**, count 2, near your character's + displayed coordinates. Check the audit result. Defeat one, gather its corpse, + and confirm loot cannot be collected twice. Test a disposable character for death. +3. Lead a mob across an X/Z multiple of 128. It should retain health/identity and + keep pursuing. Lead it beyond its configured leash; it should return home. +4. Create/equip a weapon using **Blast shot**, then hit a group. Nearby creatures + should take damage, including across a chunk edge. Verify player allies are safe. +5. Create a weapon using **Healing field**, with a +10 flat **magic damage** modifier + (the base magic-damage stat can be zero). Equip it on an injured test character. + F with no selected player targets self; click another player to target them. + Check the green area, repeated healing, maximum-health clamp, expiry, and + inability to revive a corpse. Movement or opening a menu stops repeated attacks. +6. Create your own attack, loot table, mob, and regional spawn using previews. + Try passive and guard behaviors, short respawn, and a biome filter. Walk away + beyond minimum spawn distance and return after the respawn time. Remember this + rule applies across worlds; use live Spawn mobs for a world-specific test. +7. Restart after a mob crosses a chunk, after a kill, or with an active area. Check + health, loot, and remaining effect lifetime. Check Esc on each new editor/dialog. + +Required checks: TypeScript, production build, protocol binding consistency, and +the Go suite. Focused server coverage includes projectile hits/misses/costs, +cooldown swaps, cross-chunk pursuit, damage/healing areas, source death, persisted +effects, loot/respawn, work limits, catalog publication, and admin command retries +across restart. Playwright runs remain deferred for the user's manual testing. diff --git a/planning/PLAYWRIGHT-TODO.md b/planning/PLAYWRIGHT-TODO.md index 80fa9fe..9ca98da 100644 --- a/planning/PLAYWRIGHT-TODO.md +++ b/planning/PLAYWRIGHT-TODO.md @@ -13,6 +13,8 @@ automation. These are future tasks, not completion gates for the current milesto - [ ] Gathering: skill/resource/biome/consumable editors, scoped bonus displays, dangerous-attempt second press, one attempt per action, expiry, and own-material names. - [ ] Melee/ranged targeting, cross-chunk mobs/projectiles/AoE, loot, and admin spawns. +- [ ] Milestone 4 attack/mob/loot/region editors, healing self/others, moving-target + misses, profile changes on equip, and spawn-dialog retries/focus restoration. - [ ] Equipment attachments, animation transitions, and sound settings/event playback. - [ ] Hub-instance switching, admission limits, escape items, and victory portals. - [ ] Craft discovery/valid failure, materials, quality rolls, and maker/world labels. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index 17a595d..15f7d0a 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -526,7 +526,11 @@ Milestone 3 implementation and manual handoff: [Terrain, movement, and gathering](../docs/MILESTONE-3.md). New-generation terrain, jumping, a closer camera, reusable gathering skills/resources/biomes, scoped modifiers, gathering consumables, and risky under-level attempts are ready for -manual testing. Milestone 4 has not started. +manual testing. +Milestone 4 implementation and manual handoff: +[Combat and mobs](../docs/MILESTONE-4.md). Attack/mob/loot/spawn editors, selected-target +projectiles, damage/healing areas, cross-chunk pursuit, and live admin spawning are +ready for manual testing. Milestone 4.5 has not started. This replaces the earlier proposed order. Each milestone produces a reviewable slice, followed by commit/push and a user testing handoff. These are dependency-based diff --git a/planning/VISION.md b/planning/VISION.md index 9c98dc8..a530b38 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -170,6 +170,10 @@ Tracked across: - Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning? ## Backlog +- Milestone 4 implements reusable combat/mob/loot/spawn definitions, selected-target + projectiles, stationary damage/healing areas, cross-chunk pursuit, and live admin + spawning. These use existing model presets and provisional PvE targeting/scaling; + see `docs/MILESTONE-4.md` for manual testing and remaining scope. - Milestone 3 implements reusable gathering definitions: initial lumberjack, herbalist, and miner skills use one character-owned XP methodology. Equipment, titles, and consumables can modify effective level, yield, speed, and profession diff --git a/schemas/protocol.json b/schemas/protocol.json index 67bacba..370bcd9 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -39,9 +39,15 @@ "ItemDefinition": { "type": "object", "additionalProperties": false, "properties": { - "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "slot": {"type": "string"}, - "weight": {"type": "number"}, "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"}, - "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}} + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "slot": {"type": "string"}, + "weight": {"type": "number"}, + "dropChance": {"type": "number"}, + "requirements": {"$ref": "#/definitions/ItemRequirements"}, + "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, + "attackId": {"type": "string"} }, "required": ["id", "name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -62,7 +68,8 @@ "stats": {"$ref": "#/definitions/ContentStatsRules"}, "requirementSets": {"type": "array", "items": {"$ref": "#/definitions/RequirementSet"}}, "effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}}, - "gathering": {"$ref": "#/definitions/GatheringContent"} + "gathering": {"$ref": "#/definitions/GatheringContent"}, + "combat": {"$ref": "#/definitions/CombatContent"} }, "required": ["version", "titles", "items", "stats"] }, @@ -83,7 +90,11 @@ "gatheringSkill": {"$ref": "#/definitions/GatheringSkillDraft"}, "resource": {"$ref": "#/definitions/ResourceDefinitionDraft"}, "biome": {"$ref": "#/definitions/BiomeDefinitionDraft"}, - "consumable": {"$ref": "#/definitions/GatheringConsumableDraft"} + "consumable": {"$ref": "#/definitions/GatheringConsumableDraft"}, + "attack": {"$ref": "#/definitions/CombatAttackDraft"}, + "mob": {"$ref": "#/definitions/MobDefinitionDraft"}, + "loot": {"$ref": "#/definitions/LootTableDraft"}, + "spawn": {"$ref": "#/definitions/MobSpawnDraft"} }, "required": ["id", "expectedVersion", "op", "reason"] }, @@ -103,9 +114,15 @@ "ItemDraft": { "type": "object", "additionalProperties": false, "properties": { - "id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "slot": {"type": "string"}, - "weight": {"type": "number"}, "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"}, - "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}} + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "slot": {"type": "string"}, + "weight": {"type": "number"}, + "dropChance": {"type": "number"}, + "requirements": {"$ref": "#/definitions/ItemRequirements"}, + "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, + "attackId": {"type": "string"} }, "required": ["name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -149,7 +166,9 @@ "state": {"type": "string"}, "resourceId": {"type": "string"}, "skillId": {"type": "string"}, - "requiredLevel": {"type": "integer"} + "requiredLevel": {"type": "integer"}, + "model": {"type": "string"}, + "radius": {"type": "number"} }, "required": ["id", "kind", "name", "position", "hp", "maxHp", "state"] }, @@ -183,7 +202,8 @@ "gatheringEffects": {"type": "array", "items": {"$ref": "#/definitions/TimedGatheringEffect"}}, "gatherAttempt": {"type": "integer"}, "consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}}, - "stackNames": {"type": "object", "additionalProperties": {"type": "string"}} + "stackNames": {"type": "object", "additionalProperties": {"type": "string"}}, + "attack": {"$ref": "#/definitions/CombatAttack"} }, "required": ["entity", "inventory", "skills", "level", "experience", "experienceToNextLevel", "statPoints", "titles", "allocatedStats", "stats", "mana", "stamina", "carryWeight", "pendingVitalChoices", "healthChoices", "manaChoices", "items", "equipment", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone", "gatherAttempt"] }, @@ -215,9 +235,17 @@ "ItemInstance": { "type": "object", "additionalProperties": false, "properties": { - "id": {"type": "string"}, "definitionId": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "slot": {"type": "string"}, "weight": {"type": "number"}, - "requirements": {"$ref": "#/definitions/ItemRequirements"}, "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, - "equippable": {"type": "boolean"}, "requirementMessage": {"type": "string"} + "id": {"type": "string"}, + "definitionId": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "slot": {"type": "string"}, + "weight": {"type": "number"}, + "requirements": {"$ref": "#/definitions/ItemRequirements"}, + "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, + "equippable": {"type": "boolean"}, + "requirementMessage": {"type": "string"}, + "attack": {"$ref": "#/definitions/CombatAttack"} }, "required": ["id", "definitionId", "name", "description", "slot", "weight", "requirements", "modifiers", "equippable", "requirementMessage"] }, @@ -425,6 +453,165 @@ "allowed": {"type": "boolean"} }, "required": ["failure", "destruction", "negative", "damage", "seconds", "allowed"] + }, + "CombatAttack": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "delivery": {"type": "string"}, + "effect": {"type": "string"}, + "stat": {"type": "string"}, + "multiplier": {"type": "number"}, + "range": {"type": "number"}, + "cooldown": {"type": "number"}, + "stamina": {"type": "number"}, + "speed": {"type": "number"}, + "radius": {"type": "number"}, + "duration": {"type": "number"}, + "interval": {"type": "number"} + }, + "required": ["id", "name", "description", "delivery", "effect", "stat", "multiplier", "range", "cooldown", "stamina", "speed", "radius", "duration", "interval"] + }, + "CombatAttackDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "delivery": {"type": "string"}, + "effect": {"type": "string"}, + "stat": {"type": "string"}, + "multiplier": {"type": "number"}, + "range": {"type": "number"}, + "cooldown": {"type": "number"}, + "stamina": {"type": "number"}, + "speed": {"type": "number"}, + "radius": {"type": "number"}, + "duration": {"type": "number"}, + "interval": {"type": "number"} + }, + "required": ["name", "description", "delivery", "effect", "stat", "multiplier", "range", "cooldown", "stamina", "speed", "radius", "duration", "interval"] + }, + "LootEntry": { + "type": "object", "additionalProperties": false, + "properties": { + "item": {"type": "string"}, + "amount": {"type": "integer"}, + "chance": {"type": "number"}, + "group": {"type": "string"}, + "weight": {"type": "integer"} + }, + "required": ["item", "amount", "chance", "group", "weight"] + }, + "LootTable": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "entries": {"type": "array", "items": {"$ref": "#/definitions/LootEntry"}} + }, + "required": ["id", "name", "description", "entries"] + }, + "LootTableDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "entries": {"type": "array", "items": {"$ref": "#/definitions/LootEntry"}} + }, + "required": ["name", "description", "entries"] + }, + "MobDefinition": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "model": {"type": "string"}, + "behavior": {"type": "string"}, + "level": {"type": "integer"}, + "hp": {"type": "number"}, + "damage": {"type": "number"}, + "defence": {"type": "number"}, + "speed": {"type": "number"}, + "aggroRange": {"type": "number"}, + "leashRange": {"type": "number"}, + "scalePerDay": {"type": "number"}, + "xp": {"type": "integer"}, + "attackId": {"type": "string"}, + "lootId": {"type": "string"} + }, + "required": ["id", "name", "description", "model", "behavior", "level", "hp", "damage", "defence", "speed", "aggroRange", "leashRange", "scalePerDay", "xp", "attackId", "lootId"] + }, + "MobDefinitionDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "model": {"type": "string"}, + "behavior": {"type": "string"}, + "level": {"type": "integer"}, + "hp": {"type": "number"}, + "damage": {"type": "number"}, + "defence": {"type": "number"}, + "speed": {"type": "number"}, + "aggroRange": {"type": "number"}, + "leashRange": {"type": "number"}, + "scalePerDay": {"type": "number"}, + "xp": {"type": "integer"}, + "attackId": {"type": "string"}, + "lootId": {"type": "string"} + }, + "required": ["name", "description", "model", "behavior", "level", "hp", "damage", "defence", "speed", "aggroRange", "leashRange", "scalePerDay", "xp", "attackId", "lootId"] + }, + "MobSpawn": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "mobId": {"type": "string"}, + "x": {"type": "number"}, + "z": {"type": "number"}, + "radius": {"type": "number"}, + "count": {"type": "integer"}, + "respawn": {"type": "number"}, + "minPlayerDistance": {"type": "number"}, + "biomes": {"type": "array", "items": {"type": "string"}} + }, + "required": ["id", "name", "description", "mobId", "x", "z", "radius", "count", "respawn", "minPlayerDistance", "biomes"] + }, + "MobSpawnDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "mobId": {"type": "string"}, + "x": {"type": "number"}, + "z": {"type": "number"}, + "radius": {"type": "number"}, + "count": {"type": "integer"}, + "respawn": {"type": "number"}, + "minPlayerDistance": {"type": "number"}, + "biomes": {"type": "array", "items": {"type": "string"}} + }, + "required": ["name", "description", "mobId", "x", "z", "radius", "count", "respawn", "minPlayerDistance", "biomes"] + }, + "CombatContent": { + "type": "object", "additionalProperties": false, + "properties": { + "attacks": {"type": "array", "items": {"$ref": "#/definitions/CombatAttack"}}, + "mobs": {"type": "array", "items": {"$ref": "#/definitions/MobDefinition"}}, + "loot": {"type": "array", "items": {"$ref": "#/definitions/LootTable"}}, + "spawns": {"type": "array", "items": {"$ref": "#/definitions/MobSpawn"}} + }, + "required": ["attacks", "mobs", "loot", "spawns"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index d591c4d..1d54d99 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -1,4 +1,27 @@ version: 1 +combatRules: + maxMobs: 512 + maxProjectiles: 256 + maxAreas: 64 + maxTargets: 64 + maxSlope: 1.2 + hitRadius: 1.2 +combat: + attacks: + - { id: bow_shot, name: Bow shot, description: A straight projectile that can miss., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 45, cooldown: 1, stamina: 2, speed: 35, radius: 0, duration: 0, interval: 1 } + - { id: blast_shot, name: Blast shot, description: A projectile with a damage burst., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 35, cooldown: 3, stamina: 8, speed: 25, radius: 6, duration: 0, interval: 1 } + - { id: healing_field, name: Healing field, description: A projectile that creates a stationary healing area., delivery: projectile, effect: heal, stat: magicDamage, multiplier: 1, range: 30, cooldown: 8, stamina: 10, speed: 25, radius: 6, duration: 5, interval: 1 } + - { id: sentinel_strike, name: Sentinel strike, description: Close range damage., delivery: melee, effect: damage, stat: meleeDamage, multiplier: 1, range: 3, cooldown: 1.8, stamina: 0, speed: 1, radius: 0, duration: 0, interval: 1 } + mobs: + - { id: ash_guard, name: Ash guard, description: A territorial guardian., model: sentinel, behavior: aggressive, level: 1, hp: 54, damage: 6, defence: 0, speed: 4, aggroRange: 24, leashRange: 160, scalePerDay: 0.1, xp: 50, attackId: sentinel_strike, lootId: common_mob_loot } + loot: + - id: common_mob_loot + name: Common creature loot + description: Guaranteed herbs and an independent chance of ore. + entries: + - { item: herb, amount: 1, chance: 100, group: '', weight: 1 } + - { item: ore, amount: 1, chance: 20, group: '', weight: 1 } + spawns: [] # Provisional milestone 3 tuning. The +20 attempt ceiling is a gameplay rule. gatheringRules: failureBase: 70 diff --git a/server/content/combat.go b/server/content/combat.go new file mode 100644 index 0000000..bc0265e --- /dev/null +++ b/server/content/combat.go @@ -0,0 +1,176 @@ +package content + +import ( + "fmt" + "slices" +) + +type CombatAttack struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Delivery string `json:"delivery" yaml:"delivery"` + Effect string `json:"effect" yaml:"effect"` + Stat string `json:"stat" yaml:"stat"` + Multiplier float64 `json:"multiplier" yaml:"multiplier"` + Range float64 `json:"range" yaml:"range"` + Cooldown float64 `json:"cooldown" yaml:"cooldown"` + Stamina float64 `json:"stamina" yaml:"stamina"` + Speed float64 `json:"speed" yaml:"speed"` + Radius float64 `json:"radius" yaml:"radius"` + Duration float64 `json:"duration" yaml:"duration"` + Interval float64 `json:"interval" yaml:"interval"` +} + +func (a CombatAttack) Validate() error { + if !validSetIdentity(a.ID, a.Name, a.Description) || !slices.Contains([]string{"melee", "projectile"}, a.Delivery) || !slices.Contains([]string{"damage", "heal"}, a.Effect) || !slices.Contains([]string{"meleeDamage", "rangedDamage", "magicDamage"}, a.Stat) || !finiteRange(a.Multiplier, .01, 100) || !finiteRange(a.Range, 1, 128) || !finiteRange(a.Cooldown, .1, 120) || !finiteRange(a.Stamina, 0, 10000) || !finiteRange(a.Speed, 1, 100) || !finiteRange(a.Radius, 0, 24) || !finiteRange(a.Duration, 0, 60) || !finiteRange(a.Interval, .2, 60) { + return fmt.Errorf("invalid attack %q", a.ID) + } + if a.Duration > 0 && (a.Radius <= 0 || a.Interval > a.Duration) { + return fmt.Errorf("timed areas need radius and interval <= duration") + } + return nil +} + +type LootEntry struct { + Item string `json:"item" yaml:"item"` + Amount int64 `json:"amount" yaml:"amount"` + Chance float64 `json:"chance" yaml:"chance"` + Group string `json:"group" yaml:"group"` + Weight int64 `json:"weight" yaml:"weight"` +} +type LootTable struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Entries []LootEntry `json:"entries" yaml:"entries"` +} +type MobDefinition 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"` + Behavior string `json:"behavior" yaml:"behavior"` + Level int64 `json:"level" yaml:"level"` + HP float64 `json:"hp" yaml:"hp"` + Damage float64 `json:"damage" yaml:"damage"` + Defence float64 `json:"defence" yaml:"defence"` + Speed float64 `json:"speed" yaml:"speed"` + AggroRange float64 `json:"aggroRange" yaml:"aggroRange"` + LeashRange float64 `json:"leashRange" yaml:"leashRange"` + ScalePerDay float64 `json:"scalePerDay" yaml:"scalePerDay"` + XP int64 `json:"xp" yaml:"xp"` + AttackID string `json:"attackId" yaml:"attackId"` + LootID string `json:"lootId" yaml:"lootId"` +} +type MobSpawn struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + MobID string `json:"mobId" yaml:"mobId"` + X float64 `json:"x" yaml:"x"` + Z float64 `json:"z" yaml:"z"` + Radius float64 `json:"radius" yaml:"radius"` + Count int64 `json:"count" yaml:"count"` + Respawn float64 `json:"respawn" yaml:"respawn"` + MinPlayerDistance float64 `json:"minPlayerDistance" yaml:"minPlayerDistance"` + Biomes []string `json:"biomes" yaml:"biomes"` +} +type CombatContent struct { + Attacks []CombatAttack `json:"attacks" yaml:"attacks"` + Mobs []MobDefinition `json:"mobs" yaml:"mobs"` + Loot []LootTable `json:"loot" yaml:"loot"` + Spawns []MobSpawn `json:"spawns" yaml:"spawns"` +} +type CombatRules struct { + MaxMobs int `yaml:"maxMobs"` + MaxProjectiles int `yaml:"maxProjectiles"` + MaxAreas int `yaml:"maxAreas"` + MaxTargets int `yaml:"maxTargets"` + MaxSlope float64 `yaml:"maxSlope"` + HitRadius float64 `yaml:"hitRadius"` +} + +func (r CombatRules) Validate() error { + if r.MaxMobs < 1 || r.MaxMobs > 2048 || r.MaxProjectiles < 1 || r.MaxProjectiles > 512 || r.MaxAreas < 1 || r.MaxAreas > 128 || r.MaxTargets < 1 || r.MaxTargets > 128 || !finiteRange(r.MaxSlope, .1, 4) || !finiteRange(r.HitRadius, .1, 3) { + return fmt.Errorf("invalid combat work limits") + } + return nil +} +func (c Catalog) validateCombat() error { + if c.Combat == nil { + return nil + } + v := c.Combat + if len(v.Attacks) > 256 || len(v.Mobs) > 256 || len(v.Loot) > 256 || len(v.Spawns) > 256 { + return fmt.Errorf("too much combat content") + } + ids := map[string]bool{} + identity := func(id, name, desc string) bool { + if ids[id] || !validSetIdentity(id, name, desc) { + return false + } + ids[id] = true + return true + } + attacks, loot, mobs := map[string]bool{}, map[string]bool{}, map[string]bool{} + for _, a := range v.Attacks { + if !identity(a.ID, a.Name, a.Description) { + return fmt.Errorf("duplicate attack") + } + if err := a.Validate(); err != nil { + return err + } + attacks[a.ID] = true + } + items := map[string]bool{} + for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} { + items[id] = true + } + for _, i := range c.Items { + items[i.ID] = true + } + if c.Gathering != nil { + for _, r := range c.Gathering.Resources { + if r.Output == "self" { + items[r.ID] = true + } + } + for _, i := range c.Gathering.Consumables { + items[i.ID] = true + } + } + for _, l := range v.Loot { + if !identity(l.ID, l.Name, l.Description) || len(l.Entries) > 32 { + return fmt.Errorf("invalid loot table") + } + loot[l.ID] = true + for _, e := range l.Entries { + if !items[e.Item] || e.Amount < 1 || e.Amount > 100 || !finiteRange(e.Chance, 0, 100) || len(e.Group) > 40 || e.Weight < 1 || e.Weight > 10000 { + return fmt.Errorf("invalid loot entry") + } + } + } + for _, m := range v.Mobs { + if !identity(m.ID, m.Name, m.Description) || !slices.Contains([]string{"sentinel", "boss"}, m.Model) || !slices.Contains([]string{"aggressive", "guard", "passive"}, m.Behavior) || m.Level < 1 || m.Level > 10000 || !finiteRange(m.HP, 1, 1000000) || !finiteRange(m.Damage, 0, 100000) || !finiteRange(m.Defence, 0, 100000) || !finiteRange(m.Speed, .1, 30) || !finiteRange(m.AggroRange, 1, 128) || !finiteRange(m.LeashRange, m.AggroRange, 512) || !finiteRange(m.ScalePerDay, 0, 10) || m.XP < 0 || m.XP > 1000000000 || !attacks[m.AttackID] || (m.LootID != "" && !loot[m.LootID]) { + return fmt.Errorf("invalid mob %q or missing attack/loot reference", m.ID) + } + mobs[m.ID] = true + } + for _, s := range v.Spawns { + if !identity(s.ID, s.Name, s.Description) || !mobs[s.MobID] || !finiteRange(s.X, -100000, 100000) || !finiteRange(s.Z, -100000, 100000) || !finiteRange(s.Radius, 0, 512) || s.Count < 1 || s.Count > 32 || !finiteRange(s.Respawn, 1, 604800) || !finiteRange(s.MinPlayerDistance, 0, 128) || len(s.Biomes) > 32 { + return fmt.Errorf("invalid spawn") + } + for _, id := range s.Biomes { + if c.Gathering == nil || !slices.ContainsFunc(c.Gathering.Biomes, func(b BiomeDefinition) bool { return b.ID == id }) { + return fmt.Errorf("unknown spawn biome") + } + } + } + for _, i := range c.Items { + if i.AttackID != "" && (!attacks[i.AttackID] || i.Slot != "weapon") { + return fmt.Errorf("weapon references unknown attack") + } + } + return nil +} diff --git a/server/content/content.go b/server/content/content.go index aba4d81..7022f81 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,8 @@ type Recipe struct { } type Balance struct { + Combat *CombatContent `yaml:"combat"` + CombatRules *CombatRules `yaml:"combatRules"` Gathering *GatheringContent `yaml:"gathering"` GatheringRules *GatheringRules `yaml:"gatheringRules"` Version int `yaml:"version"` @@ -78,6 +80,14 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { + if b.CombatRules != nil { + if err := b.CombatRules.Validate(); err != nil { + return err + } + } + if err := (Catalog{Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { + return err + } if b.Gathering != nil { if err := b.Gathering.Validate(); err != nil { return err diff --git a/server/content/stats.go b/server/content/stats.go index eb4edee..1016434 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -35,6 +35,7 @@ type ItemRequirements struct { Titles []string `json:"titles" yaml:"titles"` } type ItemDefinition struct { + AttackID string `json:"attackId,omitempty" yaml:"attackId"` ID string `json:"id" yaml:"id"` Name string `json:"name" yaml:"name"` Description string `json:"description" yaml:"description"` @@ -45,6 +46,7 @@ type ItemDefinition struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + Combat *CombatContent `json:"combat,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` Version int64 `json:"version"` Titles []Title `json:"titles"` @@ -124,6 +126,9 @@ func (item ItemDefinition) Validate() error { return ValidateModifiers(item.Modifiers) } func (c Catalog) Validate() error { + if err := c.validateCombat(); err != nil { + return err + } if c.Gathering != nil { if err := c.Gathering.Validate(); err != nil { return err @@ -196,5 +201,5 @@ func DefaultCatalog() (Catalog, error) { if err != nil { return Catalog{}, err } - return Catalog{Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil + return Catalog{Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil } diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go new file mode 100644 index 0000000..d266914 --- /dev/null +++ b/server/internal/game/combat.go @@ -0,0 +1,452 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "encoding/json" + "errors" + "fmt" + "math" + "sort" +) + +type Projectile struct { + Target string `json:"target"` + ID string `json:"id"` + Source string `json:"source"` + Player bool `json:"player"` + Position p.Vec3 `json:"position"` + Destination p.Vec3 `json:"destination"` + Attack p.CombatAttack `json:"attack"` + Power float64 `json:"power"` +} +type CombatArea struct { + Projectile + NextAt float64 `json:"nextAt"` + ExpiresAt float64 `json:"expiresAt"` +} + +func protocolAttack(a content.CombatAttack) p.CombatAttack { + return p.CombatAttack{ID: a.ID, Name: a.Name, Description: a.Description, Delivery: a.Delivery, Effect: a.Effect, Stat: a.Stat, Multiplier: a.Multiplier, Range: a.Range, Cooldown: a.Cooldown, Stamina: a.Stamina, Speed: a.Speed, Radius: a.Radius, Duration: a.Duration, Interval: a.Interval} +} +func (w *World) playerAttack(c *Character) p.CombatAttack { + for _, i := range c.View.Items { + if i.ID == c.View.Equipment["weapon"] && i.Attack != nil { + return *i.Attack + } + } + return p.CombatAttack{ID: "basic_melee", Name: "Melee attack", Delivery: "melee", Effect: "damage", Stat: "meleeDamage", Multiplier: 1, Range: w.Balance.AttackRange, Cooldown: w.Balance.AttackCooldown, Speed: 1, Interval: 1} +} +func length3(a, b p.Vec3) float64 { + return math.Sqrt((a.X-b.X)*(a.X-b.X) + (a.Y-b.Y)*(a.Y-b.Y) + (a.Z-b.Z)*(a.Z-b.Z)) +} +func body(pos p.Vec3) p.Vec3 { pos.Y += 1; return pos } +func lerp3(a, b p.Vec3, t float64) p.Vec3 { + return p.Vec3{X: a.X + (b.X-a.X)*t, Y: a.Y + (b.Y-a.Y)*t, Z: a.Z + (b.Z-a.Z)*t} +} +func (w *World) combatID(kind string) string { + w.CombatSequence++ + return fmt.Sprintf("%s:%d", kind, w.CombatSequence) +} +func (w *World) sourceActive(source string, player bool) bool { + if w.Phase == "won" || w.Phase == "lost" { + return false + } + if player { + c := w.Characters[source] + return c != nil && c.View.Entity.State == "alive" && !c.Sheltered + } + m := w.Mobs[source] + return m != nil && m.Entity.HP > 0 +} +func (w *World) combatTargets(player bool, effect string) []p.Entity { + out := []p.Entity{} + if (player && effect == "heal") || (!player && effect == "damage") { + for _, c := range w.orderedCharacters() { + if c.Online && c.View.Entity.State == "alive" && !c.Sheltered { + out = append(out, c.View.Entity) + } + } + } else { + for _, id := range w.mobIDs() { + m := w.Mobs[id] + if m.Entity.HP > 0 { + out = append(out, m.Entity) + } + } + if w.Phase == "cataclysm" { + out = append(out, p.Entity{ID: "boss", Position: w.terrain.Position(0, 0), HP: w.BossHP}) + } + } + return out +} +func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) { + steps := max(1, int(math.Ceil(length3(a, b)*2))) + for i := 1; i <= steps; i++ { + v := lerp3(a, b, float64(i)/float64(steps)) + if v.Y < w.terrain.Height(v.X, v.Z)+.05 { + return v, true + } + } + return b, false +} +func (w *World) attack(c *Character, target string) error { + a := w.playerAttack(c) + if w.Age() < c.AttackReadyAt || w.Age()-c.LastAttack < a.Cooldown { + return errors.New("attack cooldown") + } + if c.View.Stamina < a.Stamina { + return errors.New("not enough stamina") + } + var e *p.Entity + for _, v := range w.combatTargets(true, a.Effect) { + if v.ID == target { + copy := v + e = © + break + } + } + if e == nil { + return errors.New("invalid attack target") + } + from, to := body(c.View.Entity.Position), body(e.Position) + extra := float64(0) + 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 { + return errors.New("terrain blocks the attack") + } + if a.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles { + return errors.New("projectile limit reached") + } + if a.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas { + return errors.New("area effect limit reached") + } + power := c.View.Stats[a.Stat].Final * a.Multiplier + if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) { + power *= w.Balance.CriticalMultiplier + } + c.LastAttack = w.Age() + c.AttackReadyAt = w.Age() + a.Cooldown + c.View.Stamina -= a.Stamina + w.dirty = true + shot := Projectile{ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: from, Destination: to, Attack: a, Power: power} + if a.Delivery == "projectile" { + w.Projectiles[shot.ID] = &shot + } else { + shot.Position = to + w.impact(shot, target) + } + c.View.Skills["combat"] += w.Balance.SkillXpPerAction + w.evaluateTitles(c) + return nil +} +func (w *World) pendingAreas() int { + n := 0 + for _, p := range w.Projectiles { + if p.Attack.Duration > 0 { + n++ + } + } + return n +} +func (w *World) impact(shot Projectile, target string) { + if !w.sourceActive(shot.Source, shot.Player) { + return + } + if shot.Attack.Radius > 0 { + w.areaPulse(shot) + } else if target != "" { + w.combatHit(shot, target) + } + if shot.Attack.Duration > 0 && w.sourceActive(shot.Source, shot.Player) { + id := w.combatID("area") + shot.ID = id + w.Areas[id] = &CombatArea{Projectile: shot, NextAt: w.Age() + shot.Attack.Interval, ExpiresAt: w.Age() + shot.Attack.Duration} + } + w.dirty = true +} +func (w *World) areaPulse(shot Projectile) { + targets := w.combatTargets(shot.Player, shot.Attack.Effect) + sort.Slice(targets, func(i, j int) bool { + a, b := length3(body(targets[i].Position), shot.Position), length3(body(targets[j].Position), shot.Position) + if a == b { + return targets[i].ID < targets[j].ID + } + return a < b + }) + n := 0 + for _, e := range targets { + if n >= w.Balance.CombatRules.MaxTargets || !w.sourceActive(shot.Source, shot.Player) { + break + } + if length3(body(e.Position), shot.Position) > shot.Attack.Radius { + continue + } + if _, blocked := w.terrainHit(shot.Position, body(e.Position)); blocked { + continue + } + w.combatHit(shot, e.ID) + n++ + } +} +func (w *World) combatHit(shot Projectile, target string) { + if !w.sourceActive(shot.Source, shot.Player) { + return + } + healing := shot.Attack.Effect == "heal" + if c := w.Characters[target]; c != nil { + if c.View.Entity.State != "alive" || !c.Online || c.Sheltered { + return + } + if healing && shot.Player { + c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+shot.Power) + } else if !healing && !shot.Player { + w.damageCharacter(c, shot.Power) + if c.View.Entity.HP <= 0 { + w.kill(c, "A creature's attack ended this character's journey.") + } + } + w.dirty = true + return + } + if target == "boss" { + if w.Phase != "cataclysm" { + return + } + if healing && !shot.Player { + w.BossHP = math.Min(w.Balance.BossHp, w.BossHP+shot.Power) + } else if !healing && shot.Player { + w.damageBoss(w.Characters[shot.Source], shot.Power) + } + w.dirty = true + return + } + m := w.Mobs[target] + if m == nil || m.Entity.HP <= 0 { + return + } + if healing && !shot.Player { + m.Entity.HP = math.Min(m.Entity.MaxHP, m.Entity.HP+shot.Power) + } else if !healing && shot.Player { + defence := float64(0) + if m.Definition != nil { + defence = m.Definition.Defence + } + m.Entity.HP = math.Max(0, m.Entity.HP-math.Max(0, shot.Power-defence)) + m.Target = shot.Source + if m.Entity.HP == 0 { + w.mobKilled(w.Characters[shot.Source], m) + } + } + w.dirty = true +} +func (w *World) updateCombat(dt float64) { + ids := make([]string, 0, len(w.Projectiles)) + for id := range w.Projectiles { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + shot := w.Projectiles[id] + if !w.sourceActive(shot.Source, shot.Player) { + delete(w.Projectiles, id) + w.dirty = true + continue + } + remaining := length3(shot.Position, shot.Destination) + step := math.Min(remaining, shot.Attack.Speed*dt) + t := float64(1) + if remaining > 0 { + t = step / remaining + } + end := lerp3(shot.Position, shot.Destination, t) + obstacle, blocked := w.terrainHit(shot.Position, end) + best := math.Inf(1) + if blocked { + best = length3(shot.Position, obstacle) + } + hit := "" + hitPoint := obstacle + for _, e := range w.combatTargets(shot.Player, shot.Attack.Effect) { + if e.ID == shot.Source && shot.Target != shot.Source { + continue + } + center := body(e.Position) + ab := length3(shot.Position, end) + fraction := float64(0) + if ab > 0 { + fraction = ((center.X-shot.Position.X)*(end.X-shot.Position.X) + (center.Y-shot.Position.Y)*(end.Y-shot.Position.Y) + (center.Z-shot.Position.Z)*(end.Z-shot.Position.Z)) / (ab * ab) + } + fraction = math.Max(0, math.Min(1, fraction)) + point := lerp3(shot.Position, end, fraction) + radius := w.Balance.CombatRules.HitRadius + if e.ID == "boss" { + radius += 3 + } + dist := length3(shot.Position, point) + if length3(point, center) <= radius && dist < best { + best = dist + hit = e.ID + hitPoint = point + } + } + if hit != "" || blocked || t >= 1 { + copy := *shot + copy.Position = end + if hit != "" || blocked { + copy.Position = hitPoint + } + delete(w.Projectiles, id) + w.impact(copy, hit) + } else { + shot.Position = end + } + } + ids = ids[:0] + for id := range w.Areas { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + area := w.Areas[id] + if !w.sourceActive(area.Source, area.Player) || w.Age() > area.ExpiresAt { + delete(w.Areas, id) + w.dirty = true + continue + } + if w.Age() >= area.NextAt { + w.areaPulse(area.Projectile) + area.NextAt = w.Age() + area.Attack.Interval + w.dirty = true + } + } +} +func (w *World) mobKilled(c *Character, m *Mob) { + if m.Entity.State == "dead" { + return + } + m.Entity.State = "dead" + m.Target = "" + m.RespawnAt = w.Age() + m.RespawnDelay + c.View.Kills++ + c.WorldKills++ + if m.Definition == nil { + c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final) + for _, item := range w.Balance.Items { + if w.roll(item.DropChance * c.View.Stats["dropRate"].Final / 100) { + _ = w.grantItems(c, item.ID, 1) + } + } + w.grantXP(c, w.Balance.Progression.MobKillXP) + } else { + inventory := map[string]int64{} + items := []p.ItemInstance{} + entries := m.Loot.Entries + selected := []content.LootEntry{} + groups := map[string][]content.LootEntry{} + for _, e := range entries { + if e.Group == "" { + selected = append(selected, e) + } else { + groups[e.Group] = append(groups[e.Group], e) + } + } + keys := make([]string, 0, len(groups)) + for key := range groups { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + pool := groups[key] + total := int64(0) + for _, e := range pool { + total += e.Weight + } + for _, e := range pool { + if w.roll(float64(e.Weight) * 100 / float64(total)) { + selected = append(selected, e) + break + } + total -= e.Weight + } + } + for _, e := range selected { + chance := e.Chance + if chance < 100 { + chance *= c.View.Stats["dropRate"].Final / 100 + } + if w.roll(chance) { + _ = w.addInventoryItems(&inventory, &items, e.Item, e.Amount) + } + } + if len(inventory) > 0 || len(items) > 0 { + id := w.combatID("loot") + entity := m.Entity + entity.ID = id + entity.Kind = "corpse" + entity.Model = nil + w.Corpses[id] = &Corpse{Entity: entity, Inventory: inventory, Items: items} + } + w.grantXP(c, m.Definition.XP) + } + w.RefreshStats(c) + w.evaluateTitles(c) + w.dirty = true +} +func (w *World) restoreCombat() error { + if w.Projectiles == nil { + w.Projectiles = map[string]*Projectile{} + } + if w.Areas == nil { + w.Areas = map[string]*CombatArea{} + } + if len(w.Projectiles) > w.Balance.CombatRules.MaxProjectiles || len(w.Areas) > w.Balance.CombatRules.MaxAreas { + return errors.New("persisted combat exceeds work limits") + } + validate := func(shot Projectile) error { + raw, _ := json.Marshal(shot.Attack) + var a content.CombatAttack + _ = json.Unmarshal(raw, &a) + if err := a.Validate(); err != nil { + return err + } + for _, v := range []float64{shot.Position.X, shot.Position.Y, shot.Position.Z, shot.Destination.X, shot.Destination.Y, shot.Destination.Z, shot.Power} { + if math.IsNaN(v) || math.IsInf(v, 0) { + return errors.New("invalid persisted projectile") + } + } + return nil + } + for id, v := range w.Projectiles { + if v == nil || id != v.ID { + return errors.New("invalid projectile identity") + } + if err := validate(*v); err != nil { + return err + } + } + for id, v := range w.Areas { + if v == nil || id != v.ID || math.IsNaN(v.NextAt) || math.IsNaN(v.ExpiresAt) || math.IsInf(v.NextAt, 0) || math.IsInf(v.ExpiresAt, 0) { + return errors.New("invalid area identity or deadline") + } + if err := validate(v.Projectile); err != nil { + return err + } + } + for _, m := range w.Mobs { + if m == nil { + return errors.New("invalid persisted mob") + } + if m.Home == nil { + v := w.terrain.Position((float64(m.HomeX)+.55)*w.Balance.ChunkSize, (float64(m.HomeZ)+.55)*w.Balance.ChunkSize) + m.Home = &v + m.RespawnDelay = w.Balance.MobRespawnSeconds + } + } + return nil +} diff --git a/server/internal/game/combat_test.go b/server/internal/game/combat_test.go new file mode 100644 index 0000000..7f8df04 --- /dev/null +++ b/server/internal/game/combat_test.go @@ -0,0 +1,252 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "encoding/json" + "testing" + "time" +) + +func combatFixture(t *testing.T) (*World, *Character, *Mob) { + t.Helper() + w, c := fixture(t) + w.now = w.CreatedAt.Add(time.Minute) + d := *w.mobDefinition("ash_guard") + d.Behavior = "passive" + d.HP = 200 + d.ScalePerDay = 0 + m := w.newMob("combat-target", d, w.terrain.Position(20, 0), 60) + w.Mobs[m.Entity.ID] = m + a := protocolAttack(w.Balance.Combat.Attacks[0]) + c.View.Items = append(c.View.Items, p.ItemInstance{ID: "bow", DefinitionID: "bow", Name: "Bow", Slot: "weapon", Requirements: p.ItemRequirements{Level: 1}, Attack: &a}) + c.View.Equipment["weapon"] = "bow" + w.RefreshStats(c) + return w, c, m +} +func advanceProjectiles(w *World, steps int) { + for i := 0; i < steps; i++ { + w.now = w.now.Add(50 * time.Millisecond) + w.updateCombat(.05) + } +} +func TestProjectileHitMissCostsAndWeaponSwap(t *testing.T) { + w, c, m := combatFixture(t) + stamina := c.View.Stamina + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Target: m.Entity.ID, Seq: 1}); err != nil { + t.Fatal(err) + } + if m.Entity.HP != m.Entity.MaxHP || len(w.Projectiles) != 1 || c.View.Stamina != stamina-2 { + t.Fatal("projectile applied instant damage or wrong cost") + } + if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Target: m.Entity.ID, Seq: 1}); err == nil { + t.Fatal("sequence replay accepted") + } + if err := w.unequip(c, "weapon"); err != nil { + t.Fatal(err) + } + if err := w.attack(c, m.Entity.ID); err == nil { + t.Fatal("weapon swap bypassed cooldown") + } + advanceProjectiles(w, 20) + if m.Entity.HP >= m.Entity.MaxHP || len(w.Projectiles) != 0 { + t.Fatal("projectile failed to hit") + } + w, c, m = combatFixture(t) + if err := w.attack(c, m.Entity.ID); err != nil { + t.Fatal(err) + } + m.Entity.Position = w.terrain.Position(20, 12) + advanceProjectiles(w, 25) + if m.Entity.HP != m.Entity.MaxHP { + t.Fatal("straight projectile homed on moving target") + } + w, c, m = combatFixture(t) + c.View.Stamina = 0 + if err := w.attack(c, m.Entity.ID); err == nil || len(w.Projectiles) != 0 { + t.Fatal("insufficient stamina spawned projectile") + } +} +func TestCrossChunkPursuitRetainsIdentityAndHealth(t *testing.T) { + w, c, m := combatFixture(t) + m.Definition.Behavior = "aggressive" + m.HomeX = 0 + m.HomeZ = 0 + home := w.terrain.Position(125, 10) + m.Home = &home + m.Entity.Position = home + m.Entity.HP = 123 + c.View.Entity.Position = w.terrain.Position(141, 10) + for i := 0; i < 8; i++ { + w.updateMobs(map[string]bool{"0:0": true, "1:0": true}, .25) + } + if m.Entity.Position.X <= 128 || m.Entity.HP != 123 || w.Mobs[m.Entity.ID] != m { + t.Fatal("chunk edge blocked/reset pursuit") + } + x := m.Entity.Position.X + w.updateMobs(map[string]bool{"1:0": true}, .25) + if m.Entity.Position.X <= x { + t.Fatal("mob froze when only destination chunk active") + } + raw, _ := json.Marshal(w) + var restored World + _ = json.Unmarshal(raw, &restored) + if err := restored.Restore(w.now); err != nil { + t.Fatal(err) + } + if restored.Mobs[m.Entity.ID].Entity.Position.X != m.Entity.Position.X || restored.Mobs[m.Entity.ID].Entity.HP != 123 { + t.Fatal("restart reset traveling mob") + } +} +func TestAreaHealingBoundariesAndSourceDeath(t *testing.T) { + w, c, m := combatFixture(t) + c.View.Entity.Position = w.terrain.Position(127, 10) + m.Entity.Position = w.terrain.Position(129, 10) + shot := Projectile{Source: c.View.Entity.ID, Player: true, Position: body(c.View.Entity.Position), Power: 10, Attack: p.CombatAttack{ID: "test_area", Name: "Area", Delivery: "melee", Effect: "damage", Stat: "rangedDamage", Multiplier: 1, Range: 6, Cooldown: 1, Speed: 1, Radius: 6, Duration: 4, Interval: 1}} + w.impact(shot, "") + if m.Entity.HP != 190 || len(w.Areas) != 1 { + t.Fatal("AoE clipped chunk boundary") + } + other, err := w.Join("other", "Other") + if err != nil { + t.Fatal(err) + } + other.Online = true + other.View.Entity.Position = w.terrain.Position(128, 10) + other.View.Entity.HP = 30 + c.View.Entity.HP = 40 + shot.Attack.Effect = "heal" + w.impact(shot, "") + if other.View.Entity.HP != 40 || c.View.Entity.HP != 50 { + t.Fatal("area did not heal living allies") + } + w.kill(other, "test death") + w.areaPulse(shot) + if other.View.Entity.HP != 0 || other.View.Entity.State != "dead" { + t.Fatal("area resurrected a corpse") + } + w.kill(c, "source died") + hp := m.Entity.HP + advanceProjectiles(w, 30) + if m.Entity.HP != hp || len(w.Areas) != 0 { + t.Fatal("dead source area continued damaging") + } +} +func TestProjectileAndAreaRestartDoesNotRepeatDamage(t *testing.T) { + w, c, m := combatFixture(t) + a := w.playerAttack(c) + a.Radius = 4 + a.Duration = 2 + a.Interval = 1 + c.View.Items[len(c.View.Items)-1].Attack = &a + if err := w.attack(c, m.Entity.ID); err != nil { + t.Fatal(err) + } + advanceProjectiles(w, 4) + raw, _ := json.Marshal(w) + var restored World + _ = json.Unmarshal(raw, &restored) + if err := restored.Restore(w.now); err != nil { + t.Fatal(err) + } + advanceProjectiles(&restored, 12) + rm := restored.Mobs[m.Entity.ID] + hp := rm.Entity.HP + if hp >= 200 || len(restored.Areas) != 1 { + t.Fatal("saved projectile did not complete") + } + raw, _ = json.Marshal(&restored) + var again World + _ = json.Unmarshal(raw, &again) + if err := again.Restore(restored.now); err != nil { + t.Fatal(err) + } + again.updateCombat(.01) + if again.Mobs[m.Entity.ID].Entity.HP != hp { + t.Fatal("restore repeated impact or early area tick") + } + advanceProjectiles(&again, 60) + if len(again.Areas) != 0 || len(again.Projectiles) != 0 { + t.Fatal("effects outlived their deadlines") + } +} +func TestMobLootOnceAndRespawn(t *testing.T) { + w, c, m := combatFixture(t) + m.Loot.Entries = []content.LootEntry{{Item: "herb", Amount: 2, Chance: 100, Weight: 1}, {Item: "wood", Amount: 1, Chance: 100, Weight: 1, Group: "one"}, {Item: "ore", Amount: 1, Chance: 100, Weight: 2, Group: "one"}} + shot := Projectile{Source: c.View.Entity.ID, Player: true, Attack: p.CombatAttack{Effect: "damage"}, Power: 1000} + w.combatHit(shot, m.Entity.ID) + w.combatHit(shot, m.Entity.ID) + if len(w.Corpses) != 1 || c.View.Kills != 1 { + t.Fatal("duplicate loot or kill credit") + } + for _, corpse := range w.Corpses { + if corpse.Inventory["herb"] != 2 || corpse.Inventory["wood"]+corpse.Inventory["ore"] != 1 { + t.Fatal("guaranteed/weighted loot wrong") + } + } + raw, _ := json.Marshal(w) + var restored World + _ = json.Unmarshal(raw, &restored) + if err := restored.Restore(w.now); err != nil { + t.Fatal(err) + } + restored.now = restored.now.Add(61 * time.Second) + restored.updateMobs(map[string]bool{Key(m.HomeX, m.HomeZ): true}, .05) + if restored.Mobs[m.Entity.ID].Entity.HP <= 0 || len(restored.Corpses) != 1 { + t.Fatal("respawn rerolled old loot") + } +} +func TestTerrainObstructionAndCombatLimits(t *testing.T) { + w, c, m := combatFixture(t) + if _, blocked := w.terrainHit(p.Vec3{X: 0, Y: -2}, p.Vec3{X: 20, Y: -2}); !blocked { + t.Fatal("terrain penetration allowed") + } + w.Balance.CombatRules.MaxProjectiles = 1 + if err := w.attack(c, m.Entity.ID); err != nil { + t.Fatal(err) + } + w.now = w.now.Add(2 * time.Second) + stamina := c.View.Stamina + if err := w.attack(c, m.Entity.ID); err == nil || c.View.Stamina != stamina { + t.Fatal("work limit spent resources") + } + w.kill(c, "permanent death") + advanceProjectiles(w, 30) + if m.Entity.HP != m.Entity.MaxHP { + t.Fatal("dead character's projectile hit") + } + if err := w.SpawnMobs("ash_guard", "33,0,0"); err == nil { + t.Fatal("spawn limit ignored") + } + if _, _, _, err := ParseMobSpawn("1,NaN,0"); err == nil { + t.Fatal("nonfinite spawn accepted") + } +} + +func TestRegionalSpawnsRespectExploredBiomeAndPlayerDistance(t *testing.T) { + w, c, _ := combatFixture(t) + w.Mobs = map[string]*Mob{} + w.ResourceLayouts["0:0"] = ResourceLayout{BiomeID: "forest", Biome: "Forest"} + w.Balance.Combat.Spawns = []content.MobSpawn{{ID: "test_region", MobID: "ash_guard", X: 20, Z: 0, Count: 1, Respawn: 5, MinPlayerDistance: 10, Biomes: []string{"meadow"}}} + active := map[string]bool{"0:0": true} + w.updateSpawns(active) + if len(w.Mobs) != 0 { + t.Fatal("spawn ignored explored biome") + } + w.Balance.Combat.Spawns[0].Biomes = []string{"forest"} + c.View.Entity.Position = w.terrain.Position(20, 0) + w.updateSpawns(active) + if len(w.Mobs) != 0 { + t.Fatal("spawn ignored player distance") + } + c.View.Entity.Position = w.terrain.Position(0, 0) + w.updateSpawns(map[string]bool{}) + if len(w.Mobs) != 0 { + t.Fatal("spawn activated an unsubscribed chunk") + } + w.updateSpawns(active) + w.updateSpawns(active) + if len(w.Mobs) != 1 || w.Mobs["spawn:test_region:0"] == nil { + t.Fatal("regional slot was missing or duplicated") + } +} diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go index 9774c2e..a0cd4e1 100644 --- a/server/internal/game/equipment.go +++ b/server/internal/game/equipment.go @@ -64,6 +64,14 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn for _, modifier := range definition.Modifiers { item.Modifiers = append(item.Modifiers, p.StatModifier{Skill: stringPtr(modifier.Skill), Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent}) } + if definition.AttackID != "" { + for _, a := range w.Balance.Combat.Attacks { + if a.ID == definition.AttackID { + v := protocolAttack(a) + item.Attack = &v + } + } + } created = append(created, item) } *items = append(*items, created...) diff --git a/server/internal/game/mobs.go b/server/internal/game/mobs.go new file mode 100644 index 0000000..23924cc --- /dev/null +++ b/server/internal/game/mobs.go @@ -0,0 +1,324 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "errors" + "fmt" + "math" + "slices" + "sort" + "strconv" + "strings" +) + +func (w *World) mobIDs() []string { + ids := make([]string, 0, len(w.Mobs)) + for id := range w.Mobs { + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} +func ParseMobSpawn(value string) (int, float64, float64, error) { + parts := strings.Split(value, ",") + if len(parts) != 3 { + return 0, 0, 0, errors.New("spawn requires count,x,z") + } + n, e1 := strconv.Atoi(parts[0]) + x, e2 := strconv.ParseFloat(parts[1], 64) + z, e3 := strconv.ParseFloat(parts[2], 64) + if e1 != nil || e2 != nil || e3 != nil || n < 1 || n > 32 || math.IsNaN(x) || math.IsNaN(z) || math.IsInf(x, 0) || math.IsInf(z, 0) || math.Abs(x) > 100000 || math.Abs(z) > 100000 { + return 0, 0, 0, errors.New("choose 1-32 mobs and finite world coordinates") + } + return n, x, z, nil +} +func (w *World) mobDefinition(id string) *content.MobDefinition { + for i := range w.Balance.Combat.Mobs { + if w.Balance.Combat.Mobs[i].ID == id { + return &w.Balance.Combat.Mobs[i] + } + } + return nil +} +func (w *World) newMob(id string, d content.MobDefinition, pos p.Vec3, respawn float64) *Mob { + scale := float64(d.Level) * (1 + w.Age()/86400*d.ScalePerDay) + hp := d.HP * scale + home := pos + m := &Mob{Entity: p.Entity{ID: id, Kind: "mob", Model: stringPtr(d.Model), Name: d.Name, Position: pos, HP: hp, MaxHP: hp, State: "alive"}, Definition: &d, Home: &home, HomeX: ChunkCoord(pos.X, w.Balance.ChunkSize), HomeZ: ChunkCoord(pos.Z, w.Balance.ChunkSize), RespawnDelay: respawn, Power: d.Damage * scale} + for _, a := range w.Balance.Combat.Attacks { + if a.ID == d.AttackID { + m.Attack = protocolAttack(a) + } + } + for _, l := range w.Balance.Combat.Loot { + if l.ID == d.LootID { + m.Loot = l + } + } + return m +} +func (w *World) SpawnMobs(definition, value string) error { + if w.Phase == "won" || w.Phase == "lost" { + return errors.New("world has ended") + } + n, x, z, err := ParseMobSpawn(value) + if err != nil { + return err + } + d := w.mobDefinition(definition) + if d == nil { + return errors.New("unknown mob definition") + } + if len(w.Mobs)+n > w.Balance.CombatRules.MaxMobs { + return errors.New("world mob limit reached") + } + positions := []p.Vec3{} + for i := 0; i < n; i++ { + px, pz := x+float64(i%6)*2, z+float64(i/6)*2 + if math.Hypot(px, pz) >= w.SafeRadius() { + return errors.New("spawn would leave the surviving world") + } + positions = append(positions, w.terrain.Position(px, pz)) + } + for _, pos := range positions { + id := w.combatID("mob") + w.Mobs[id] = w.newMob(id, *d, pos, 0) + } + w.dirty = true + return nil +} +func (w *World) ensureMob(ch p.Chunk) { + id := "m:" + ch.Key + if _, ok := w.Mobs[id]; ok || len(w.Mobs) >= w.Balance.CombatRules.MaxMobs { + return + } + x, z := (float64(ch.X)+.55)*ch.Size, (float64(ch.Z)+.55)*ch.Size + if math.Hypot(x, z) > w.Balance.WorldRadius { + return + } + hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + home := w.terrain.Position(x, z) + 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 +} +func (w *World) updateSpawns(active map[string]bool) { + for _, rule := range w.Balance.Combat.Spawns { + d := w.mobDefinition(rule.MobID) + if d == nil { + continue + } + for i := int64(0); i < rule.Count; i++ { + id := fmt.Sprintf("spawn:%s:%d", rule.ID, i) + if _, ok := w.Mobs[id]; ok { + continue + } + if len(w.Mobs) >= w.Balance.CombatRules.MaxMobs { + return + } + angle := float64(i) * 2.399963229728653 + radius := rule.Radius * math.Sqrt(float64(i+1)/float64(rule.Count)) + x, z := rule.X+math.Cos(angle)*radius, rule.Z+math.Sin(angle)*radius + cx, cz := ChunkCoord(x, w.Balance.ChunkSize), ChunkCoord(z, w.Balance.ChunkSize) + if !active[Key(cx, cz)] || math.Hypot(x, z) > w.SafeRadius() { + continue + } + biomeID := w.mobBiome(cx, cz) + if len(rule.Biomes) > 0 && !slices.Contains(rule.Biomes, biomeID) { + continue + } + pos := w.terrain.Position(x, z) + near := false + for _, c := range w.Characters { + if c.Online && c.View.Entity.State == "alive" && distance(pos, c.View.Entity.Position) < rule.MinPlayerDistance { + near = true + break + } + } + if near { + continue + } + w.Mobs[id] = w.newMob(id, *d, pos, rule.Respawn) + w.Mobs[id].MinPlayerDistance = rule.MinPlayerDistance + w.dirty = true + } + } +} + +func (w *World) mobBiome(x, z int) string { + if layout, ok := w.ResourceLayouts[Key(x, z)]; ok { + if layout.BiomeID != "" { + return layout.BiomeID + } + // Older explored layouts persisted only the display name. Keep their + // established biome instead of recalculating from new catalog weights. + for _, biome := range w.Balance.Gathering.Biomes { + if biome.Name == layout.Biome { + return biome.ID + } + } + return "" + } + return w.terrain.biome(x, z).ID +} + +// Local slope checks and deterministic side steps cross chunk edges. Future solid +// structures can extend this one movement/line-of-sight boundary. +func (w *World) mobStep(m *Mob, to p.Vec3, speed, dt float64) { + from := m.Entity.Position + d := distance(from, to) + if d < .01 { + return + } + step := math.Min(d, speed*dt) + angle := math.Atan2(to.Z-from.Z, to.X-from.X) + for _, offset := range []float64{0, .7, -.7, 1.3, -1.3} { + x, z := from.X+math.Cos(angle+offset)*step, from.Z+math.Sin(angle+offset)*step + if math.Hypot(x, z) >= w.SafeRadius() { + continue + } + dest := w.terrain.Position(x, z) + if math.Abs(dest.Y-from.Y) > w.Balance.CombatRules.MaxSlope*step { + continue + } + m.Entity.Position = dest + return + } +} +func (w *World) updateMobs(active map[string]bool, dt float64) { + w.updateSpawns(active) + for _, id := range w.mobIDs() { + m := w.Mobs[id] + if m.Home == nil { + pos := w.terrain.Position((float64(m.HomeX)+.55)*w.Balance.ChunkSize, (float64(m.HomeZ)+.55)*w.Balance.ChunkSize) + m.Home = &pos + m.RespawnDelay = w.Balance.MobRespawnSeconds + } + homeActive := active[Key(m.HomeX, m.HomeZ)] + currentActive := active[Key(ChunkCoord(m.Entity.Position.X, w.Balance.ChunkSize), ChunkCoord(m.Entity.Position.Z, w.Balance.ChunkSize))] + if m.Entity.HP <= 0 { + if m.RespawnDelay == 0 { + delete(w.Mobs, id) + w.dirty = true + continue + } + if !homeActive || w.Age() < m.RespawnAt { + continue + } + blocked := false + for _, c := range w.Characters { + if c.Online && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, *m.Home) < m.MinPlayerDistance { + blocked = true + break + } + } + if blocked { + continue + } + hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + if m.Definition != nil { + d := m.Definition + scale := float64(d.Level) * (1 + w.Age()/86400*d.ScalePerDay) + hp = d.HP * scale + m.Power = d.Damage * scale + } + m.Entity.HP = hp + m.Entity.MaxHP = hp + m.Entity.State = "alive" + m.Entity.Position = *m.Home + m.Target = "" + w.dirty = true + } + if !homeActive && !currentActive { + continue + } + speed, aggro, leash := w.Balance.MobSpeed, w.Balance.MobAggroRange, w.Balance.ChunkSize*2 + behavior := "aggressive" + attack := p.CombatAttack{ID: "legacy_mob", Name: "Sentinel strike", Delivery: "melee", Effect: "damage", Stat: "meleeDamage", Range: w.Balance.MobAttackRange, Cooldown: w.Balance.MobCooldown, Multiplier: 1, Speed: 1, Interval: 1} + power := w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + if d := m.Definition; d != nil { + speed, aggro, leash, behavior = d.Speed, d.AggroRange, d.LeashRange, d.Behavior + attack = m.Attack + power = m.Power + } + if distance(m.Entity.Position, *m.Home) > leash { + m.Returning = true + m.Target = "" + } + if m.Returning { + if distance(m.Entity.Position, *m.Home) < 1 { + m.Returning = false + } else { + w.mobStep(m, *m.Home, speed, dt) + } + 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 + } + if target == nil { + m.Target = "" + if behavior != "passive" { + nearest := aggro + for _, c := range w.orderedCharacters() { + if !c.Online || c.Sheltered || c.View.Entity.State != "alive" { + continue + } + 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 { + continue + } + target = c + nearest = d + } + } + } + } + if target == nil { + if distance(m.Entity.Position, *m.Home) > 1 { + w.mobStep(m, *m.Home, speed, dt) + } + continue + } + m.Target = target.View.Entity.ID + if behavior == "guard" && distance(target.View.Entity.Position, *m.Home) > aggro { + m.Target = "" + w.mobStep(m, *m.Home, speed, dt) + continue + } + aim := target.View.Entity.Position + targetID := target.View.Entity.ID + if attack.Effect == "heal" { + aim = m.Entity.Position + targetID = m.Entity.ID + } + if length3(body(m.Entity.Position), body(aim)) <= attack.Range { + if w.Age()-m.LastAttack < attack.Cooldown { + continue + } + if _, blocked := w.terrainHit(body(m.Entity.Position), body(aim)); blocked { + w.mobStep(m, aim, speed, dt) + continue + } + if attack.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles { + continue + } + if attack.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas { + continue + } + shot := Projectile{ID: w.combatID("projectile"), Source: id, Player: false, Position: body(m.Entity.Position), Destination: body(aim), Attack: attack, Power: power * attack.Multiplier, Target: targetID} + m.LastAttack = w.Age() + if attack.Delivery == "projectile" { + w.Projectiles[shot.ID] = &shot + } else { + shot.Position = body(aim) + w.impact(shot, targetID) + } + w.dirty = true + } else { + w.mobStep(m, aim, speed, dt) + } + } +} diff --git a/server/internal/game/stats.go b/server/internal/game/stats.go index 28d142f..e5d4c93 100644 --- a/server/internal/game/stats.go +++ b/server/internal/game/stats.go @@ -89,6 +89,8 @@ func (w *World) RefreshStats(c *Character) { w.revalidateEquipment(c) c.View.Stats = w.statValues(c, true) w.refreshGathering(c) + attack := w.playerAttack(c) + c.View.Attack = &attack c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final c.View.Entity.HP = math.Min(c.View.Entity.HP, c.View.Entity.MaxHP) c.View.Mana = math.Max(0, math.Min(c.View.Mana, c.View.Stats["manaPoints"].Final)) @@ -166,6 +168,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error { w.Balance.Gathering = catalog.Gathering w.terrain.B.Gathering = catalog.Gathering } + if catalog.Combat != nil { + w.Balance.Combat = catalog.Combat + } w.Balance.Titles = catalog.Titles w.Balance.Items = catalog.Items w.Balance.Stats = &catalog.Stats diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 0b95ecf..5a5602a 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -15,6 +15,7 @@ import ( ) type Character struct { + AttackReadyAt float64 `json:"attackReadyAt"` JumpVelocity float64 `json:"jumpVelocity"` GatherReadyAt float64 `json:"gatherReadyAt"` @@ -46,6 +47,16 @@ type Corpse struct { Items []p.ItemInstance `json:"items"` } type Mob struct { + Definition *content.MobDefinition `json:"definition,omitempty"` + Attack p.CombatAttack `json:"attack"` + Loot content.LootTable `json:"loot"` + Home *p.Vec3 `json:"home,omitempty"` + Power float64 `json:"power"` + Target string `json:"target"` + Returning bool `json:"returning"` + RespawnDelay float64 `json:"respawnDelay"` + MinPlayerDistance float64 `json:"minPlayerDistance"` + Entity p.Entity `json:"entity"` HomeX int `json:"homeX"` HomeZ int `json:"homeZ"` @@ -53,11 +64,16 @@ type Mob struct { RespawnAt float64 `json:"respawnAt"` } type ResourceLayout struct { + BiomeID string `json:"biomeId,omitempty"` Biome string `json:"biome"` Color *string `json:"color"` Resources []p.Entity `json:"resources"` } type World struct { + Projectiles map[string]*Projectile `json:"projectiles,omitempty"` + Areas map[string]*CombatArea `json:"areas,omitempty"` + CombatSequence uint64 `json:"combatSequence"` + ResourceLayouts map[string]ResourceLayout `json:"resourceLayouts,omitempty"` Version int `json:"version"` @@ -159,6 +175,19 @@ func (w *World) Restore(now time.Time) error { if w.ResourceLayouts == nil { w.ResourceLayouts = map[string]ResourceLayout{} } + if w.Balance.Combat == nil || w.Balance.CombatRules == nil { + b, e := content.Load() + if e != nil { + return e + } + if w.Balance.Combat == nil { + w.Balance.Combat = b.Combat + } + if w.Balance.CombatRules == nil { + w.Balance.CombatRules = b.CombatRules + } + w.dirty = true + } if err := w.Balance.Validate(); err != nil { return err } @@ -188,6 +217,9 @@ func (w *World) Restore(now time.Time) error { c.MoveZ = 0 c.View.ACK = 0 } + if err := w.restoreCombat(); err != nil { + return err + } return w.restoreCorpseEquipment() } func (w *World) Age() float64 { @@ -324,6 +356,7 @@ func (w *World) Import(c *Character) error { c.MoveZ = 0 c.View.ACK = 0 c.LastAttack = 0 + c.AttackReadyAt = 0 c.LastGather = 0 c.GatherReadyAt = 0 c.JumpVelocity = 0 @@ -383,7 +416,7 @@ func (w *World) chunk(x, z int) p.Chunk { if layout, ok := w.ResourceLayouts[key]; ok { c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources } else { - w.ResourceLayouts[key] = ResourceLayout{Biome: c.Biome, Color: c.Color, Resources: c.Resources} + w.ResourceLayouts[key] = ResourceLayout{BiomeID: w.terrain.biome(x, z).ID, Biome: c.Biome, Color: c.Color, Resources: c.Resources} w.dirty = true } w.chunks[key] = c @@ -498,69 +531,27 @@ func (w *World) craft(c *Character, name string) error { w.dirty = true return nil } -func (w *World) attack(c *Character, target string) error { - if w.Age()-c.LastAttack < w.Balance.AttackCooldown { - return errors.New("attack cooldown") - } - damage := c.View.Stats["meleeDamage"].Final - if target == "boss" { - if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 { - return errors.New("boss out of reach") - } - if w.roll(c.View.Stats["criticalChance"].Final) { - damage *= w.Balance.CriticalMultiplier - } - w.BossHP = math.Max(0, w.BossHP-damage) - if w.BossHP == 0 { - c.BossKills++ - w.grantXP(c, w.Balance.Progression.BossKillXP) - w.evaluateTitles(c) - w.Phase = "won" - ended := w.now - w.EndedAt = &ended - // Stable order for simultaneous survivor milestone candidates. - for _, survivor := range w.orderedCharacters() { - if survivor.View.Entity.State == "alive" { - survivor.WorldsSurvived++ - w.evaluateTitles(survivor) - survivor.View.Entity.State = "eligible" - survivor.MoveX = 0 - survivor.MoveZ = 0 - survivor.Message = "The world is saved. Passage is open." - } +func (w *World) damageBoss(c *Character, damage float64) { + w.BossHP = math.Max(0, w.BossHP-damage) + if w.BossHP == 0 { + c.BossKills++ + w.grantXP(c, w.Balance.Progression.BossKillXP) + w.evaluateTitles(c) + w.Phase = "won" + ended := w.now + w.EndedAt = &ended + // Stable order for simultaneous survivor milestone candidates. + for _, survivor := range w.orderedCharacters() { + if survivor.View.Entity.State == "alive" { + survivor.WorldsSurvived++ + w.evaluateTitles(survivor) + survivor.View.Entity.State = "eligible" + survivor.MoveX = 0 + survivor.MoveZ = 0 + survivor.Message = "The world is saved. Passage is open." } } - } else { - m := w.Mobs[target] - if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange { - return errors.New("target out of reach") - } - if w.roll(c.View.Stats["criticalChance"].Final) { - damage *= w.Balance.CriticalMultiplier - } - m.Entity.HP = math.Max(0, m.Entity.HP-damage) - if m.Entity.HP == 0 { - m.Entity.State = "dead" - m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds - c.View.Kills++ - c.WorldKills++ - c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final) - for _, item := range w.Balance.Items { - if w.roll(item.DropChance * c.View.Stats["dropRate"].Final / 100) { - if err := w.grantItems(c, item.ID, 1); err != nil { - return err - } - } - } - w.RefreshStats(c) - w.grantXP(c, w.Balance.Progression.MobKillXP) - } } - c.LastAttack = w.Age() - c.View.Skills["combat"] += w.Balance.SkillXpPerAction - w.evaluateTitles(c) - w.dirty = true - return nil } func (w *World) kill(c *Character, reason string) { if c.View.Entity.State != "alive" { @@ -596,6 +587,8 @@ func (w *World) kill(c *Character, reason string) { // Operator changes use the same simulation and persistence path as gameplay. func (w *World) Control(op, target, value, reason string) error { switch op { + case "spawn-mobs": + return w.SpawnMobs(target, value) case "close-admissions", "open-admissions": if w.Phase == "won" || w.Phase == "lost" { return errors.New("world has ended") @@ -718,6 +711,7 @@ func (w *World) Advance(now time.Time, dt float64) { } } w.updateMobs(active, dt) + w.updateCombat(dt) if w.Phase == "cataclysm" { if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown { for _, c := range characters { @@ -759,76 +753,6 @@ func (w *World) Advance(now time.Time, dt float64) { } } } -func (w *World) ensureMob(ch p.Chunk) { - id := "m:" + ch.Key - if _, ok := w.Mobs[id]; ok { - return - } - x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size - if math.Hypot(x, z) > w.Balance.WorldRadius { - return - } - hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) - w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)} -} -func (w *World) updateMobs(active map[string]bool, dt float64) { - mobIDs := make([]string, 0, len(w.Mobs)) - for id := range w.Mobs { - mobIDs = append(mobIDs, id) - } - sort.Strings(mobIDs) - characters := w.orderedCharacters() - for _, id := range mobIDs { - m := w.Mobs[id] - key := Key(m.HomeX, m.HomeZ) - if !active[key] { - if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) { - delete(w.Mobs, id) - } - continue - } - if m.Entity.HP <= 0 { - if w.Age() >= m.RespawnAt { - m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay) - m.Entity.MaxHP = m.Entity.HP - m.Entity.State = "alive" - } - continue - } - var target *Character - nearest := w.Balance.MobAggroRange - for _, c := range characters { - if !c.Online || c.View.Entity.State != "alive" || c.Sheltered { - continue - } - d := distance(c.View.Entity.Position, m.Entity.Position) - if d < nearest { - nearest = d - target = c - } - } - if target == nil { - continue - } - if nearest <= w.Balance.MobAttackRange { - if w.Age()-m.LastAttack >= w.Balance.MobCooldown { - w.damageCharacter(target, w.Balance.MobDamage*(1+w.Age()/86400*w.Balance.MobScalePerDay)) - m.LastAttack = w.Age() - w.dirty = true - if target.View.Entity.HP <= 0 { - w.kill(target, "An ash sentinel ended this character's journey.") - } - } - } else { - pos, to := m.Entity.Position, target.View.Entity.Position - step := math.Min(nearest, w.Balance.MobSpeed*dt) - x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step - if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ { - m.Entity.Position = w.terrain.Position(x, z) - } - } - } -} func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { c := w.Characters[id] s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}} @@ -892,6 +816,17 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) { s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"}) } + for _, shot := range w.Projectiles { + if visible(shot.Position) { + s.Entities = append(s.Entities, p.Entity{ID: shot.ID, Kind: "projectile", Name: shot.Attack.Name, Position: shot.Position, State: shot.Attack.Effect, HP: 1, MaxHP: 1}) + } + } + for _, area := range w.Areas { + if visible(area.Position) { + radius := area.Attack.Radius + s.Entities = append(s.Entities, p.Entity{ID: area.ID, Kind: "area", Name: area.Attack.Name, Position: area.Position, State: area.Attack.Effect, Radius: &radius, HP: 1, MaxHP: 1}) + } + } sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID }) return s } diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index 13c612a..9d91811 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -11,6 +11,7 @@ type Protocol struct { } type ContentCatalog struct { + Combat *CombatContent `json:"combat,omitempty"` EffectSets []EffectSet `json:"effectSets,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` Items []ItemDefinition `json:"items"` @@ -20,6 +21,78 @@ type ContentCatalog struct { Version int64 `json:"version"` } +type CombatContent struct { + Attacks []CombatAttack `json:"attacks"` + Loot []LootTable `json:"loot"` + Mobs []MobDefinition `json:"mobs"` + Spawns []MobSpawn `json:"spawns"` +} + +type CombatAttack struct { + Cooldown float64 `json:"cooldown"` + Delivery string `json:"delivery"` + Description string `json:"description"` + Duration float64 `json:"duration"` + Effect string `json:"effect"` + ID string `json:"id"` + Interval float64 `json:"interval"` + Multiplier float64 `json:"multiplier"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Range float64 `json:"range"` + Speed float64 `json:"speed"` + Stamina float64 `json:"stamina"` + Stat string `json:"stat"` +} + +type LootTable struct { + Description string `json:"description"` + Entries []LootEntry `json:"entries"` + ID string `json:"id"` + Name string `json:"name"` +} + +type LootEntry struct { + Amount int64 `json:"amount"` + Chance float64 `json:"chance"` + Group string `json:"group"` + Item string `json:"item"` + Weight int64 `json:"weight"` +} + +type MobDefinition struct { + AggroRange float64 `json:"aggroRange"` + AttackID string `json:"attackId"` + Behavior string `json:"behavior"` + Damage float64 `json:"damage"` + Defence float64 `json:"defence"` + Description string `json:"description"` + HP float64 `json:"hp"` + ID string `json:"id"` + LeashRange float64 `json:"leashRange"` + Level int64 `json:"level"` + LootID string `json:"lootId"` + Model string `json:"model"` + Name string `json:"name"` + ScalePerDay float64 `json:"scalePerDay"` + Speed float64 `json:"speed"` + XP int64 `json:"xp"` +} + +type MobSpawn struct { + Biomes []string `json:"biomes"` + Count int64 `json:"count"` + Description string `json:"description"` + ID string `json:"id"` + MinPlayerDistance float64 `json:"minPlayerDistance"` + MobID string `json:"mobId"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Respawn float64 `json:"respawn"` + X float64 `json:"x"` + Z float64 `json:"z"` +} + type EffectSet struct { Description string `json:"description"` ID string `json:"id"` @@ -83,6 +156,7 @@ type GatheringSkill struct { } type ItemDefinition struct { + AttackID *string `json:"attackId,omitempty"` Description string `json:"description"` DropChance float64 `json:"dropChance"` ID string `json:"id"` @@ -133,6 +207,7 @@ type TitleEffects struct { } type ContentChange struct { + Attack *CombatAttackDraft `json:"attack,omitempty"` Biome *BiomeDefinitionDraft `json:"biome,omitempty"` Consumable *GatheringConsumableDraft `json:"consumable,omitempty"` EffectSet *EffectSetDraft `json:"effectSet,omitempty"` @@ -141,15 +216,35 @@ type ContentChange struct { GatheringSkill *GatheringSkillDraft `json:"gatheringSkill,omitempty"` ID string `json:"id"` Item *ItemDraft `json:"item,omitempty"` + Loot *LootTableDraft `json:"loot,omitempty"` + Mob *MobDefinitionDraft `json:"mob,omitempty"` Op string `json:"op"` Reason string `json:"reason"` RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"` RequirementSetIDS []string `json:"requirementSetIds,omitempty"` Resource *ResourceDefinitionDraft `json:"resource,omitempty"` + Spawn *MobSpawnDraft `json:"spawn,omitempty"` Stats *ContentStatsRules `json:"stats,omitempty"` Title *TitleDraft `json:"title,omitempty"` } +type CombatAttackDraft struct { + Cooldown float64 `json:"cooldown"` + Delivery string `json:"delivery"` + Description string `json:"description"` + Duration float64 `json:"duration"` + Effect string `json:"effect"` + ID *string `json:"id,omitempty"` + Interval float64 `json:"interval"` + Multiplier float64 `json:"multiplier"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Range float64 `json:"range"` + Speed float64 `json:"speed"` + Stamina float64 `json:"stamina"` + Stat string `json:"stat"` +} + type BiomeDefinitionDraft struct { Color string `json:"color"` Description string `json:"description"` @@ -183,6 +278,7 @@ type GatheringSkillDraft struct { } type ItemDraft struct { + AttackID *string `json:"attackId,omitempty"` Description string `json:"description"` DropChance float64 `json:"dropChance"` ID *string `json:"id,omitempty"` @@ -193,6 +289,32 @@ type ItemDraft struct { Weight float64 `json:"weight"` } +type LootTableDraft struct { + Description string `json:"description"` + Entries []LootEntry `json:"entries"` + ID *string `json:"id,omitempty"` + Name string `json:"name"` +} + +type MobDefinitionDraft struct { + AggroRange float64 `json:"aggroRange"` + AttackID string `json:"attackId"` + Behavior string `json:"behavior"` + Damage float64 `json:"damage"` + Defence float64 `json:"defence"` + Description string `json:"description"` + HP float64 `json:"hp"` + ID *string `json:"id,omitempty"` + LeashRange float64 `json:"leashRange"` + Level int64 `json:"level"` + LootID string `json:"lootId"` + Model string `json:"model"` + Name string `json:"name"` + ScalePerDay float64 `json:"scalePerDay"` + Speed float64 `json:"speed"` + XP int64 `json:"xp"` +} + type RequirementSetDraft struct { Description string `json:"description"` ID *string `json:"id,omitempty"` @@ -216,6 +338,20 @@ type ResourceDefinitionDraft struct { XP int64 `json:"xp"` } +type MobSpawnDraft struct { + Biomes []string `json:"biomes"` + Count int64 `json:"count"` + Description string `json:"description"` + ID *string `json:"id,omitempty"` + MinPlayerDistance float64 `json:"minPlayerDistance"` + MobID string `json:"mobId"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Respawn float64 `json:"respawn"` + X float64 `json:"x"` + Z float64 `json:"z"` +} + type TitleDraft struct { Description string `json:"description"` Effects TitleEffects `json:"effects"` @@ -272,16 +408,18 @@ type Chunk struct { } type Entity struct { - HP float64 `json:"hp"` - ID string `json:"id"` - Kind string `json:"kind"` - MaxHP float64 `json:"maxHp"` - Name string `json:"name"` - Position Vec3 `json:"position"` - RequiredLevel *int64 `json:"requiredLevel,omitempty"` - ResourceID *string `json:"resourceId,omitempty"` - SkillID *string `json:"skillId,omitempty"` - State string `json:"state"` + HP float64 `json:"hp"` + ID string `json:"id"` + Kind string `json:"kind"` + MaxHP float64 `json:"maxHp"` + Model *string `json:"model,omitempty"` + Name string `json:"name"` + Position Vec3 `json:"position"` + Radius *float64 `json:"radius,omitempty"` + RequiredLevel *int64 `json:"requiredLevel,omitempty"` + ResourceID *string `json:"resourceId,omitempty"` + SkillID *string `json:"skillId,omitempty"` + State string `json:"state"` } type Vec3 struct { @@ -302,6 +440,7 @@ type GatheringRisk struct { type Character struct { ACK int64 `json:"ack"` AllocatedStats map[string]int64 `json:"allocatedStats"` + Attack *CombatAttack `json:"attack,omitempty"` CarryWeight float64 `json:"carryWeight"` Consumables []GatheringConsumable `json:"consumables,omitempty"` Entity Entity `json:"entity"` @@ -357,6 +496,7 @@ type TimedGatheringEffect struct { } type ItemInstance struct { + Attack *CombatAttack `json:"attack,omitempty"` DefinitionID string `json:"definitionId"` Description string `json:"description"` Equippable bool `json:"equippable"` diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 02fa5f2..4543955 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,6 +17,10 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { + Attack *content.CombatAttack `json:"attack,omitempty"` + Mob *content.MobDefinition `json:"mob,omitempty"` + Loot *content.LootTable `json:"loot,omitempty"` + Spawn *content.MobSpawn `json:"spawn,omitempty"` GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"` Resource *content.ResourceDefinition `json:"resource,omitempty"` Biome *content.BiomeDefinition `json:"biome,omitempty"` @@ -42,7 +46,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.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.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 { @@ -106,6 +110,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) { } catalog.Gathering = b.Gathering } + if catalog.Combat == nil { + b, e := content.Load() + if e != nil { + return catalog, e + } + catalog.Combat = b.Combat + } return catalog, catalog.Validate() } func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) { @@ -135,12 +146,20 @@ func (c CatalogChange) validate() error { } valid := false count := 0 - for _, present := range []bool{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.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-attack": + valid = c.Attack != nil + case "create-mob": + valid = c.Mob != nil + case "create-loot": + valid = c.Loot != nil + case "create-spawn": + valid = c.Spawn != nil case "create-gathering-skill": valid = c.GatheringSkill != nil case "create-resource": diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index 3f8ff48..b85d266 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -35,6 +35,18 @@ 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.Attack != nil { + resolved.Attack.ID = "" + } + if resolved.Mob != nil { + resolved.Mob.ID = "" + } + if resolved.Loot != nil { + resolved.Loot.ID = "" + } + if resolved.Spawn != nil { + resolved.Spawn.ID = "" + } if resolved.GatheringSkill != nil { resolved.GatheringSkill.ID = "" } @@ -85,7 +97,48 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str } gathering := *c.Gathering c.Gathering = &gathering + if c.Combat == nil { + b, e := content.Load() + if e != nil { + return invalid(e) + } + c.Combat = b.Combat + } + combat := *c.Combat + c.Combat = &combat switch change.Op { + case "create-attack": + v := *change.Attack + if v.ID == "" { + v.ID = "attack_" + game.ID() + } + resolved.Attack = &v + c.Combat.Attacks = append(slices.Clone(c.Combat.Attacks), v) + target = v.ID + case "create-mob": + v := *change.Mob + if v.ID == "" { + v.ID = "mob_" + game.ID() + } + resolved.Mob = &v + c.Combat.Mobs = append(slices.Clone(c.Combat.Mobs), v) + target = v.ID + case "create-loot": + v := *change.Loot + if v.ID == "" { + v.ID = "loot_" + game.ID() + } + resolved.Loot = &v + c.Combat.Loot = append(slices.Clone(c.Combat.Loot), v) + target = v.ID + case "create-spawn": + v := *change.Spawn + if v.ID == "" { + v.ID = "spawn_" + game.ID() + } + resolved.Spawn = &v + c.Combat.Spawns = append(slices.Clone(c.Combat.Spawns), v) + target = v.ID case "create-gathering-skill": v := *change.GatheringSkill if v.ID == "" { diff --git a/server/internal/store/combat_catalog_test.go b/server/internal/store/combat_catalog_test.go new file mode 100644 index 0000000..7f3c737 --- /dev/null +++ b/server/internal/store/combat_catalog_test.go @@ -0,0 +1,64 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "context" + "errors" + "path/filepath" + "testing" +) + +func TestCombatCatalogReferencesAndReplay(t *testing.T) { + ctx := context.Background() + db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "combat.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + catalog, _ := db.Catalog(ctx) + publish := func(change CatalogChange) string { + t.Helper() + change.ID = game.ID() + change.ExpectedVersion = catalog.Version + change.Reason = "Combat content test" + if _, err := db.PreviewCatalog(ctx, change); err != nil { + t.Fatal(err) + } + r, err := db.PublishCatalog(ctx, "admin", change) + if err != nil { + t.Fatal(err) + } + again, err := db.PublishCatalog(ctx, "admin", change) + if err != nil || r != again { + t.Fatal("changed replay", err) + } + catalog, _ = db.Catalog(ctx) + return r.ID + } + attack := catalog.Combat.Attacks[0] + attack.ID = "" + attack.Name = "Test shot" + id := publish(CatalogChange{Op: "create-attack", Attack: &attack}) + loot := publish(CatalogChange{Op: "create-loot", Loot: &content.LootTable{Name: "Loot", Entries: []content.LootEntry{{Item: "herb", Amount: 1, Chance: 100, Weight: 1}}}}) + mob := catalog.Combat.Mobs[0] + mob.ID = "" + mob.AttackID = id + mob.LootID = loot + mid := publish(CatalogChange{Op: "create-mob", Mob: &mob}) + publish(CatalogChange{Op: "create-spawn", Spawn: &content.MobSpawn{Name: "Region", MobID: mid, Count: 2, Respawn: 60, Biomes: []string{"forest"}}}) + publish(CatalogChange{Op: "create-item", Item: &content.ItemDefinition{Name: "Bow", Slot: "weapon", Requirements: content.ItemRequirements{Level: 1}, AttackID: id}}) + attack.Duration = 2 + attack.Radius = 0 + bad := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Reason: "Invalid area test", Op: "create-attack", Attack: &attack} + if _, err := db.PublishCatalog(ctx, "admin", bad); !errors.Is(err, ErrCatalogInvalid) { + t.Fatal("invalid area accepted", err) + } + mob.AttackID = "missing" + bad.Op = "create-mob" + bad.Attack = nil + bad.Mob = &mob + if _, err := db.PublishCatalog(ctx, "admin", bad); !errors.Is(err, ErrCatalogInvalid) { + t.Fatal("missing attack reference accepted", err) + } +} diff --git a/server/internal/transport/control.go b/server/internal/transport/control.go index 8f2c32c..fe59213 100644 --- a/server/internal/transport/control.go +++ b/server/internal/transport/control.go @@ -101,6 +101,11 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) { return } switch req.Op { + case "spawn-mobs": + if _, _, _, err := game.ParseMobSpawn(req.Value); err != nil { + fail(w, 400, err.Error()) + return + } case "grant-item", "remove-item": if _, _, err := game.ParseItemChange(req.Value); err != nil { fail(w, 400, err.Error()) diff --git a/server/internal/transport/control_test.go b/server/internal/transport/control_test.go index 005e3f0..8d631d3 100644 --- a/server/internal/transport/control_test.go +++ b/server/internal/transport/control_test.go @@ -119,6 +119,41 @@ func TestControlAuthorizationAndExecution(t *testing.T) { if len(commands) != 1 || commands[0].Status != "completed" { t.Fatal("command not audited") } + spawn := `{"id":"` + game.ID() + `","worldId":"control-test","op":"spawn-mobs","target":"ash_guard","value":"2,30,30","reason":"Combat playtest"}` + before := len(w.Mobs) + for i := 0; i < 2; i++ { + if request("POST", "/api/control/commands", spawn, token, server.URL) != 202 { + t.Fatal("spawn command/retry not accepted") + } + if err = svc.controls(ctx); err != nil { + t.Fatal(err) + } + if len(w.Mobs) != before+2 { + t.Fatal("spawn retry duplicated mobs") + } + } + if err = lease.Release(ctx); err != nil { + t.Fatal(err) + } + nextLease, snapshot, err := db.Acquire(ctx, w) + if err != nil { + t.Fatal(err) + } + defer nextLease.Release(ctx) + var restarted game.World + if err = json.Unmarshal(snapshot, &restarted); err != nil { + t.Fatal(err) + } + if err = restarted.Restore(time.Now()); err != nil { + t.Fatal(err) + } + if err = NewService(&restarted, nextLease).controls(ctx); err != nil || len(restarted.Mobs) != before+2 { + t.Fatal("spawn execution was not durable/retry safe", err) + } + commands, err = db.Commands(ctx, w.ID, false) + if err != nil || len(commands) != 2 || commands[0].Status != "completed" || commands[1].Status != "completed" { + t.Fatal("spawn audit not committed with world", err) + } bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}` if request("POST", "/api/control/commands", bad, token, server.URL) != 400 { t.Fatal("destructive action without confirmation")