Add terrain biomes jumping and extensible gathering professions

This commit is contained in:
dingo
2026-09-08 21:54:23 -04:00
parent 141cb9e6b2
commit df7b245ca7
34 changed files with 1895 additions and 184 deletions
+2 -2
View File
@@ -17,13 +17,13 @@
</header>
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="18" max="100" value="30" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items"></div><h3>Permanent titles</h3><div id="earned-titles"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
<div id="notice" role="status" class="notice" hidden></div>
<footer class="bottom" id="game-controls" hidden>
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div><div class="progression-line"><strong id="character-level">Level 1</strong><span id="character-experience">0 XP</span></div><progress id="experience-meter" class="experience-meter" aria-label="Level experience" max="1" value="0"></progress><div class="progression-bank"><span id="stat-point-bank">0 stat points saved</span><span id="title-count">0 titles</span></div></section>
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
<nav class="actions" aria-label="Actions"><button id="jump" title="Jump (Space)" aria-label="Jump">↑</button><button id="attack" title="Attack (F)" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
</footer>
<nav id="movement" class="movement" aria-label="Movement" hidden><button data-move="up" aria-label="Move north"><i data-lucide="chevron-up"></i></button><button data-move="left" aria-label="Move west"><i data-lucide="chevron-left"></i></button><button data-move="down" aria-label="Move south"><i data-lucide="chevron-down"></i></button><button data-move="right" aria-label="Move east"><i data-lucide="chevron-right"></i></button></nav>
+2 -2
View File
@@ -11,7 +11,7 @@ function button(label:string,key:string,fn:()=>void,disabled=false){const b=node
function request(op:string,target:string,slot=''){sendIntent(op,target,0,0,slot);}
function render(){
for(const b of nav.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===selected));
const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.carryWeight]);
const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.carryWeight,latest.gathering,latest.gatheringEffects,latest.consumables]);
if(next===signature)return;signature=next;
const focus=root.contains(document.activeElement)?(document.activeElement as HTMLElement).dataset.focusKey:undefined;
const opened=new Set(Array.from(body.querySelectorAll<HTMLDetailsElement>('details[open]')).map(d=>d.dataset.key));body.replaceChildren();
@@ -32,7 +32,7 @@ function render(){
if(slot==='ring'){const label=node('label','Ring slot'),select=node('select');select.dataset.focusKey=`ring-${item.id}`;select.setAttribute('aria-label',`Ring slot for ${item.name}`);for(let n=1;n<=8;n++)select.append(new Option(`Ring ${n}${c.equipment?.[`ring${n}`]?' · Occupied':' · Empty'}`,`ring${n}`));select.value=rings.get(item.id)??equipmentSlots.find(s=>s.startsWith('ring')&&!c.equipment?.[s])??'ring1';slot=select.value;select.onchange=()=>{slot=select.value;rings.set(item.id,slot)};label.append(select);actions.append(label);}
actions.append(button('Equip',`equip-${item.id}`,()=>request('equip',item.id,slot),!active()||!item.equippable),button('Drop',`drop-${item.id}`,()=>request('drop',item.id),!active()));card.append(actions);grid.append(card);
}
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));grid.append(card);}
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${c.stackNames?.[key]??statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));const consumable=c.consumables?.find(v=>v.id===key);if(consumable)card.append(node('p',`${consumable.description} · ${consumable.seconds}s`),modifiersView(consumable.modifiers),button('Use',`consume-${key}`,()=>request('consume',key),!active()));grid.append(card);}
if(!grid.children.length)grid.append(node('p','Your bag is empty.'));body.append(grid);
}
for(const d of body.querySelectorAll<HTMLDetailsElement>('details'))d.open=opened.has(d.dataset.key);
+6 -2
View File
@@ -12,7 +12,7 @@ export const signed = (value:number) => `${value>0?'+':''}${numberText(value)}`;
export function node<K extends keyof HTMLElementTagNameMap>(tag:K,text='',className='') { const e=document.createElement(tag);e.textContent=text;e.className=className;return e; }
export function modifiersView(modifiers:StatModifier[] = []) {
const list=node('div','','title-effects');
for(const m of modifiers??[]) for(const [value,suffix] of [[m.flat,''],[m.percent,'%']] as const) if(value) list.append(node('span',`${signed(value)}${suffix} ${statLabel(m.stat)}`,value>0?'effect-positive':'effect-negative'));
for(const m of modifiers??[]) for(const [value,suffix] of [[m.flat,''],[m.percent,'%']] as const) if(value) list.append(node('span',`${signed(value)}${suffix} ${statLabel(m.stat)}${m.skill?` (${statLabel(m.skill)})`:m.stat.startsWith("gathering")?" (all gathering skills)":""}`,value>0?'effect-positive':'effect-negative'));
return list;
}
export function statsBreakdown(c:Character) {
@@ -21,7 +21,11 @@ export function statsBreakdown(c:Character) {
for(const label of ['Stat','Base','Flat','%','Final']) { const th=node('th',label);th.scope='col';head.append(th); }
const body=table.createTBody();
for(const key of [...primaryStats,...derivedStats]) { const v=c.stats?.[key];if(!v)continue;const row=body.insertRow(),heading=node('th',statLabel(key));heading.scope='row';row.append(heading);for(const text of [numberText(v.base),signed(v.flat),`${signed(v.percent)}%`,numberText(v.final)])row.insertCell().textContent=text; }
wrapper.append(table);return wrapper;
for(const g of Object.values(c.gathering??{})){
const row=body.insertRow();const th=node('th',`${g.name}: level ${g.level}, effective ${g.effectiveLevel} · ${g.xp} XP · ${g.xpToNextLevel} to next`);th.colSpan=5;row.append(th);
for(const [name,v] of [['Level',g.levelValue],['Yield %',g.yield],['Speed %',g.speed],['XP %',g.experience]] as const){const row=body.insertRow();row.append(node('th',name));for(const text of [numberText(v.base),signed(v.flat),`${signed(v.percent)}%`,numberText(v.final)])row.insertCell().textContent=text;}
}
wrapper.append(table);for(const effect of c.gatheringEffects??[]){wrapper.append(node('p',`${effect.name} · expires ${new Date(effect.expiresAt*1000).toLocaleTimeString()}`),modifiersView(effect.modifiers));}return wrapper;
}
export function itemDetails(item:ItemInstance,c:Character) {
const card=node('article','','gear-card');
+42 -6
View File
@@ -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'],['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'],['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;}
@@ -22,7 +22,7 @@ function repeat<T>(title:string,addLabel:string,make:(value?:T)=>{node:HTMLEleme
function append(value?:T){if(entries.length>=max)return;const entry=make(value),row=node('div','','catalog-row');entries.push(entry);row.append(entry.node,button('Remove',()=>{entries.splice(entries.indexOf(entry),1);row.remove();add.disabled=false}));rows.append(row);add.disabled=entries.length>=max;}
for(const value of initial)append(value);return {node:group,read:()=>entries.map(e=>e.read())};
}
function modifiers(){return repeat<StatModifier>('Modifiers','Add modifier',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),flat=number(value?.flat??0,-1000000),percent=number(value?.percent??0,-100,10000);group.append(field('Stat',stat),field('Flat change',flat),field('Percent change (%)',percent));return {node:group,read:()=>({stat:stat.value,flat:Number(flat.value),percent:Number(percent.value)})}});}
function modifiers(){return repeat<StatModifier>('Modifiers','Add modifier',value=>{const group=node('div','','catalog-fields'),stat=select([...statKeys,'gatheringLevel','gatheringYield','gatheringSpeed','gatheringXP'],value?.stat),flat=number(value?.flat??0,-1000000),percent=number(value?.percent??0,-100,10000);const skill=node('select');skill.append(new Option('All gathering skills',''));for(const s of catalog.gathering?.skills??[])skill.append(new Option(s.name,s.id));skill.value=value?.skill??'';const scope=field('Gathering skill scope',skill);const update=()=>{scope.hidden=!stat.value.startsWith('gathering');if(scope.hidden)skill.value=''};stat.onchange=update;update();group.append(field('Stat',stat),field('Flat change',flat),field('Percent change (%)',percent),scope);return {node:group,read:()=>({stat:stat.value,flat:Number(flat.value),percent:Number(percent.value),...(skill.value?{skill:skill.value}:{})})}});}
function requirementRows(initial:Requirement[]=[]){return repeat<Requirement>('Requirements','Add requirement',value=>{const group=node('div','','catalog-fields'),metric=select(metrics,value?.metric),minimum=number(value?.atLeast??1,1,1000000000,'1');group.append(field('Metric',metric),field('At least',minimum));return {node:group,read:()=>({metric:metric.value,atLeast:Number(minimum.value)})}},initial,8);}
function setChoices(equipment=false){
const group=node('div'),req=node('fieldset','','catalog-title-choices'),effects=node('fieldset','','catalog-title-choices');req.append(node('legend','Reusable requirement sets'));effects.append(node('legend','Reusable effect sets'));
@@ -36,7 +36,7 @@ function setForm(kind:'requirements'|'effects'){
if(editing||saving){show('Finish the open draft or pending request first.');return;}
const values=identity(),rows=kind==='requirements'?requirementRows([{metric:'level',atLeast:2}]):modifiers();
const fields=form(kind==='requirements'?'Create requirement set':'Create effect set',kind==='requirements'?'create-requirement-set':'create-effect-set',()=>kind==='requirements'?{requirementSet:{...values.read(),requirements:rows.read()}}:{effectSet:{...values.read(),modifiers:rows.read()}});
fields.append(values.node,rows.node,node('p','Reusable sets are immutable. Publish a new ID for a variation. Effects currently support flat and percentage stat modifiers.','muted'));
fields.append(values.node,rows.node,node('p','Reusable sets are immutable. Publish a new definition for a variation. Effects currently support flat and percentage stat modifiers.','muted'));
}
function form(title:string,op:string,payload:()=>object){
editing=true;refresh.disabled=true;const expectedVersion=catalog.version,form=node('form','','catalog-form'),error=node('p','','error'),fields=node('div'),reason=node('textarea'),preview=node('section','','catalog-preview');
@@ -63,12 +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;
const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable;
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.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;
}
@@ -83,7 +84,7 @@ function titleForm(){
function itemForm(){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(),slot=select(itemSlots,'weapon'),weight=number(1,0,10000),drop=number(0,0,100),level=number(1,1,10000,'1'),effects=modifiers();
const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,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 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()}}});
@@ -98,7 +99,8 @@ function statsForm(){
}
function render(){
version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren();
if(section==='titles'){
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'){
list.append(button('Create equipment',itemForm));for(const i of catalog.items??[]){const d=node('details','','catalog-definition');d.append(node('summary',i.name),node('p',`${i.id} · ${statLabel(i.slot)} · Weight ${i.weight} · Drop chance ${i.dropChance??0}%`),node('p',i.description),node('p',`Requires level ${i.requirements.level}; ${Object.entries(i.requirements.stats??{}).map(([k,v])=>`${statLabel(k)} ${v}`).join(', ')} ${(i.requirements.titles??[]).map(id=>`Title: ${catalog.titles.find(t=>t.id===id)?.name??id}`).join(', ')}`),modifiersView(i.modifiers));list.append(d);}
@@ -116,3 +118,37 @@ function render(){
async function load(){if(loading||editing)return;loading=true;refresh.disabled=true;try{const data=await api<{catalog:Catalog;changes:Audit[]}>('/api/control/catalog');catalog=data.catalog;changes=data.changes;render();}catch(e){show((e as Error).message)}finally{loading=false;refresh.disabled=editing;}}
export function showCatalog(parent:HTMLElement){if(root.parentElement!==parent)parent.replaceChildren(root);if(!catalog&&!loading)void load();}
export function hasCatalogDraft(){return editing;}
function contentChoice(values:{id:string;name:string}[]) {
const input=node('select');input.required=true;for(const v of values)input.append(new Option(v.name,v.id));return input;
}
function gatheringForm(kind:string){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(),g=catalog.gathering;
if(kind==='gathering'){
const base=number(20,1,1000000,'1'),step=number(10,0,1000000,'1'),max=number(1000,2,10000,'1');
const fields=form('Create gathering skill','create-gathering-skill',()=>({gatheringSkill:{...values.read(),baseXp:Number(base.value),xpPerLevel:Number(step.value),maxLevel:Number(max.value)}}));
fields.append(values.node,field('XP from level 1 to 2',base),field('Extra XP cost per level',step),field('Maximum earned level',max),node('p','Earned XP belongs to the character. Temporary level bonuses affect gathering difficulty without granting XP or permanent levels.','muted'));
}else if(kind==='resources'){
const skill=contentChoice(g?.skills??[]),model=select(['tree','ore','herb']),output=select(['wood','ore','herb','self']),level=number(1,1,10000,'1'),amount=number(1,1,1000,'1'),xp=number(2,0,1000000,'1'),seconds=number(1,0.1,3600),respawn=number(120,1,604800),density=number(4,0,32,'1');
output.options[3].text='New material named after this resource';
const biomeFields=node('fieldset','','catalog-title-choices');biomeFields.append(node('legend','Spawn biomes'));
const checks=(g?.biomes??[]).map(b=>{const i=node('input');i.type='checkbox';biomeFields.append(field(b.name,i));return{id:b.id,input:i}});
const fields=form('Create resource','create-resource',()=>{const biomes=checks.filter(v=>v.input.checked).map(v=>v.id);if(!biomes.length)throw new Error('Choose at least one biome.');return{resource:{...values.read(),skillId:skill.value,model:model.value,output:output.value,requiredLevel:Number(level.value),amount:Number(amount.value),xp:Number(xp.value),seconds:Number(seconds.value),respawnSeconds:Number(respawn.value),density:Number(density.value),biomes}}});
fields.append(values.node,field('Gathering skill',skill),field('Model preset',model),field('Gathered material',output),field('Required effective skill level',level),field('Base amount per success',amount),field('Base profession XP per success',xp),field('Gathering interval (seconds)',seconds),field('Respawn interval (seconds)',respawn),field('Nodes per matching chunk (before forest density bonus)',density),biomeFields,node('p','Players may risk attempts up to 20 levels below this requirement. Failures can destroy the node until respawn and inflict damage/fatigue. New definitions appear in unexplored chunks of new-generation worlds; explored layouts stay fixed. Models use existing placeholders until milestone 4.5.','muted'));
}else if(kind==='biomes'){
const color=text('#426044',7);color.type='color';const weight=number(3,1,100,'1');
const fields=form('Create biome','create-biome',()=>({biome:{...values.read(),color:color.value,weight:Number(weight.value)}}));
fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),node('p','Applies to unexplored chunks. Publish resource definitions referencing this biome to populate it. Mob populations arrive in milestone 4.','muted'));
}else{
const seconds=number(120,1,86400),effects=modifiers();
const fields=form('Create gathering consumable','create-consumable',()=>{const mods=effects.read();if(!mods.length||mods.some(m=>!m.stat.startsWith('gathering')))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods}}});
fields.append(values.node,field('Duration (seconds)',seconds),effects.node,node('p','Grant this item from Characters → Manage items and titles. Players use it from their bag. Reuse refreshes this consumable’s duration; distinct sources combine. Expiry uses real time, including time offline.','muted'));
}
}
function gatheringList(){
const labels:Record<string,string>={gathering:'gathering skill',resources:'resource',biomes:'biome',consumables:'gathering consumable'};
list.append(button(`Create ${labels[section]}`,()=>gatheringForm(section)));
const g=catalog.gathering;const entries=section==='gathering'?g?.skills:section==='resources'?g?.resources:section==='biomes'?g?.biomes:g?.consumables;
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d);}
}
+147 -14
View File
@@ -10,6 +10,7 @@ export interface Protocol {
export interface ContentCatalog {
effectSets?: EffectSet[];
gathering?: GatheringContent;
items: ItemDefinition[];
requirementSets?: RequirementSet[];
stats: ContentStatsRules;
@@ -27,9 +28,58 @@ export interface EffectSet {
export interface StatModifier {
flat: number;
percent: number;
skill?: string;
stat: string;
}
export interface GatheringContent {
biomes: BiomeDefinition[];
consumables: GatheringConsumable[];
resources: ResourceDefinition[];
skills: GatheringSkill[];
}
export interface BiomeDefinition {
color: string;
description: string;
id: string;
name: string;
weight: number;
}
export interface GatheringConsumable {
description: string;
id: string;
modifiers: StatModifier[];
name: string;
seconds: number;
}
export interface ResourceDefinition {
amount: number;
biomes: string[];
density: number;
description: string;
id: string;
model: string;
name: string;
output: string;
requiredLevel: number;
respawnSeconds: number;
seconds: number;
skillId: string;
xp: number;
}
export interface GatheringSkill {
baseXp: number;
description: string;
id: string;
maxLevel: number;
name: string;
xpPerLevel: number;
}
export interface ItemDefinition {
description: string;
dropChance: number;
@@ -81,19 +131,39 @@ export interface TitleEffects {
}
export interface ContentChange {
biome?: BiomeDefinitionDraft;
consumable?: GatheringConsumableDraft;
effectSet?: EffectSetDraft;
effectSetIds?: string[];
expectedVersion: number;
gatheringSkill?: GatheringSkillDraft;
id: string;
item?: ItemDraft;
op: string;
reason: string;
requirementSet?: RequirementSetDraft;
requirementSetIds?: string[];
resource?: ResourceDefinitionDraft;
stats?: ContentStatsRules;
title?: TitleDraft;
}
export interface BiomeDefinitionDraft {
color: string;
description: string;
id?: string;
name: string;
weight: number;
}
export interface GatheringConsumableDraft {
description: string;
id?: string;
modifiers: StatModifier[];
name: string;
seconds: number;
}
export interface EffectSetDraft {
description: string;
id?: string;
@@ -101,6 +171,15 @@ export interface EffectSetDraft {
name: string;
}
export interface GatheringSkillDraft {
baseXp: number;
description: string;
id?: string;
maxLevel: number;
name: string;
xpPerLevel: number;
}
export interface ItemDraft {
description: string;
dropChance: number;
@@ -119,6 +198,22 @@ export interface RequirementSetDraft {
requirements: ContentRequirement[];
}
export interface ResourceDefinitionDraft {
amount: number;
biomes: string[];
density: number;
description: string;
id?: string;
model: string;
name: string;
output: string;
requiredLevel: number;
respawnSeconds: number;
seconds: number;
skillId: string;
xp: number;
}
export interface TitleDraft {
description: string;
effects: TitleEffects;
@@ -152,6 +247,7 @@ export interface Snapshot {
chunkKeys: string[];
chunks: Chunk[];
entities: Entity[];
gatherRisks?: { [key: string]: GatheringRisk };
message: string;
self: Character;
tick: number;
@@ -163,6 +259,7 @@ export interface Snapshot {
export interface Chunk {
biome: string;
color?: string;
heights: number[];
key: string;
resolution: number;
@@ -173,13 +270,16 @@ export interface Chunk {
}
export interface Entity {
hp: number;
id: string;
kind: string;
maxHp: number;
name: string;
position: Vec3;
state: string;
hp: number;
id: string;
kind: string;
maxHp: number;
name: string;
position: Vec3;
requiredLevel?: number;
resourceId?: string;
skillId?: string;
state: string;
}
export interface Vec3 {
@@ -188,14 +288,27 @@ export interface Vec3 {
z: number;
}
export interface GatheringRisk {
allowed: boolean;
damage: number;
destruction: number;
failure: number;
negative: number;
seconds: number;
}
export interface Character {
ack: number;
allocatedStats: { [key: string]: number };
carryWeight: number;
consumables?: GatheringConsumable[];
entity: Entity;
equipment: { [key: string]: string };
experience: number;
experienceToNextLevel: number;
gatherAttempt: number;
gathering?: { [key: string]: SkillProgress };
gatheringEffects?: TimedGatheringEffect[];
hasKeystone: boolean;
healthChoices: number;
inventory: { [key: string]: number };
@@ -208,12 +321,39 @@ export interface Character {
playedSeconds: number;
remainingSeconds: number;
skills: { [key: string]: number };
stackNames?: { [key: string]: string };
stamina: number;
statPoints: number;
stats: { [key: string]: StatValue };
titles: TitleAward[];
}
export interface SkillProgress {
effectiveLevel: number;
experience: StatValue;
level: number;
levelValue: StatValue;
name: string;
speed: StatValue;
xp: number;
xpToNextLevel: number;
yield: StatValue;
}
export interface StatValue {
base: number;
final: number;
flat: number;
percent: number;
}
export interface TimedGatheringEffect {
expiresAt: number;
modifiers: StatModifier[];
name: string;
source: string;
}
export interface ItemInstance {
definitionId: string;
description: string;
@@ -227,13 +367,6 @@ export interface ItemInstance {
weight: number;
}
export interface StatValue {
base: number;
final: number;
flat: number;
percent: number;
}
export interface TitleAward {
description: string;
earnedAt: string;
+2 -2
View File
@@ -1,7 +1,7 @@
export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return';
export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return' | 'jump';
const bindings: Readonly<Record<string, InputAction>> = {
KeyW:'north', ArrowUp:'north', KeyS:'south', ArrowDown:'south', KeyA:'west', ArrowLeft:'west',
KeyD:'east', ArrowRight:'east', Space:'attack', KeyE:'gather', KeyI:'inventory'
KeyD:'east', ArrowRight:'east', Space:'jump', KeyF:'attack', KeyE:'gather', KeyI:'inventory'
};
export function isEditing(target: EventTarget | null) {
return target instanceof HTMLElement && !!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');
+18 -7
View File
@@ -23,6 +23,7 @@ let inputElapsed = 0;
let walkTo: { x: number; z: number } | undefined;
let pendingAction: { op: string; target: string } | undefined;
let actionElapsed = 0;
let riskyArmed = "", gatherSent = 0;
// A gather target can stay legitimately, persistently unreachable for a long time (a
// depleted resource waits out a real respawn timer measured in minutes, not a stray
// frame) -- retrying it forever would starve everything else. But a *working* attack is
@@ -64,7 +65,7 @@ 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); }
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'}`;} }
}
function action(op: string) {
if (!snapshot) return;
@@ -77,6 +78,13 @@ function action(op: string) {
}
if (!target) { notice('No target nearby.'); return; }
selection(target);
const risk=snapshot.gatherRisks?.[target.resourceId??target.kind];
if(op==='gather'&&risk){
walkTo=undefined;pendingAction=undefined;
if(!risk.allowed){notice('This resource is more than 20 levels above your effective gathering level.');return;}
if(risk.failure>0&&riskyArmed!==target.id){riskyArmed=target.id;notice(`Dangerous attempt: ${risk.failure.toFixed(0)}% failure. Inspect the target risks, then press Gather again to attempt.`);return;}
}
riskyArmed='';gatherSent=0;
pendingAction = { op: target.kind === 'corpse' ? 'loot' : op, target: target.id };
walkTo = target.position;
lastProgress = undefined; lastProgressAt = Date.now();
@@ -89,6 +97,8 @@ function connect() {
ws.onmessage = event => {
const value = JSON.parse(event.data) as Snapshot;
if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; }
if(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;walkTo=undefined;gatherSent=0;}
if(gatherSent && value.self.ack>=gatherSent)gatherSent=0;
snapshot = value; view.update(value); updateHUD(value);
const state = value.self.entity.state;
if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false);
@@ -130,7 +140,8 @@ function inventory(c: Character) {
row.append(label, button); recipes.append(row);
}
const skills = $('skills'); skills.replaceChildren();
for (const skill of ['gathering', 'crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); }
for(const g of Object.values(c.gathering??{})){const label=document.createElement('span');label.textContent=`${g.name} · Level ${g.level} (effective ${g.effectiveLevel})`;const amount=document.createElement('b');amount.textContent=`${g.xp} XP · ${g.xpToNextLevel} to next`;label.append(amount);skills.append(label);}
for (const skill of ['crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); }
}
function minimap(s: Snapshot) {
const canvas = $<HTMLCanvasElement>('minimap'), ctx = canvas.getContext('2d')!;
@@ -180,7 +191,7 @@ async function boot() {
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
if(key==='attack'||key==='gather')action(key);
else if(key==='inventory')$('inventory-toggle').click();
else if(key==='heal'||key==='return')send(key);
else if(key==='heal'||key==='return'||key==='jump')send(key);
});
view.start(dt => {
inputElapsed += dt;
@@ -211,12 +222,12 @@ async function boot() {
actionElapsed = 0;
const sig = progressSignature();
if (sig !== undefined && sig !== lastProgress) { lastProgress = sig; lastProgressAt = Date.now(); }
if (Date.now() - lastProgressAt > 5000) {
if (Date.now() - lastProgressAt > Math.max(5000,((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;
action(retryOp);
} else { send(pendingAction.op, pendingAction.target); }
if(retryOp!=='gather')action(retryOp);else notice('Gathering stopped. Select a resource 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; }
@@ -265,7 +276,7 @@ async function boot() {
};
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
}
$('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
$('jump').onclick = () => input.trigger('jump'); $('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
$('reconnect').onclick = () => location.reload();
+4 -2
View File
@@ -1,7 +1,7 @@
import { api, el, type RecordCharacter } from './portal-shared';
import { statLabel } from './character-stats';
type Catalog={items:{id:string;name:string}[];titles:{id:string;name:string}[]};
type Catalog={gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]};
export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){
const root=el('section','','player-content');root.append(el('h3','Manage items and titles'));
if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;}
@@ -19,11 +19,13 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()
switch(operation.value){
case 'grant-item':
for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id));
for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id));
for(const i of catalog.gathering?.consumables??[])choice.append(new Option(i.name,i.id));
for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage'])choice.append(new Option(statLabel(id),id));
notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break;
case 'remove-item':
for(const i of v.items??[]){const slot=Object.entries(v.equipment??{}).find(([,id])=>id===i.id)?.[0];choice.append(new Option(`${i.name}${slot?` [${statLabel(slot)}]`:''} · ${i.id}`,i.id));}
for(const [id,n] of Object.entries(v.inventory??{}))if(n>0)choice.append(new Option(`${statLabel(id)} · ${n} held`,id));
for(const [id,n] of Object.entries(v.inventory??{}))if(n>0)choice.append(new Option(`${v.stackNames?.[id]??statLabel(id)} · ${n} held`,id));
notice.textContent='Removes the selected instance or stack quantity. Equipped items are unequipped automatically.';break;
case 'grant-title':
for(const t of catalog.titles)choice.append(new Option(`${t.name} (${t.id})`,t.id));
+2
View File
@@ -9,3 +9,5 @@
@media(min-height:521px){.inventory{bottom:195px}}
@media(max-width:800px) and (min-height:521px){.movement:not([hidden]){bottom:255px}.inventory{bottom:258px;max-height:calc(100dvh - 350px)}.notice{bottom:375px}}
@media(max-height:520px){.movement:not([hidden]){bottom:178px}}
#target-health{white-space:normal;line-height:1.5;max-width:min(550px,80vw)}
+3 -2
View File
@@ -20,7 +20,7 @@ export class WorldView {
player?: T.Group;
snapshot?: Snapshot;
selected?: Entity;
distance = 46;
distance = 30;
frames = 0;
moving = false;
private highQuality = true;
@@ -124,7 +124,7 @@ export class WorldView {
if (this.chunks.has(chunk.key)) continue;
const n = chunk.resolution, step = chunk.size / n;
const positions: number[] = [], colors: number[] = [], indices: number[] = [];
const green = new T.Color('#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092');
const green = new T.Color(chunk.color || '#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092');
for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) {
const wx = chunk.x * chunk.size + x * step, wz = chunk.z * chunk.size + z * step;
const h = chunk.heights[z * (n + 1) + x];
@@ -177,6 +177,7 @@ export class WorldView {
}
update(snapshot: Snapshot) {
this.snapshot = snapshot;
if (!this.initialized) this.addChunks([], []);
this.addChunks(snapshot.chunks, snapshot.chunkKeys);
const unavailable = new Set(snapshot.unavailableResources);
const resources = [...this.chunks.values()].flatMap(c => c.data.resources).filter(r => !unavailable.has(r.id));
+11
View File
@@ -48,6 +48,17 @@ range, cooldown, inventory changes, damage, death, play-time, and passage eligib
Movement is interpolated on the client; full prediction/reconciliation is deferred.
No rigid-body physics is claimed: this is heightfield movement in open terrain.
Milestone 3 adds authoritative vertical jump velocity and gravity over that
heightfield. Generator 2 increases terrain depth and chooses weighted biomes;
generator 1 remains supported with unchanged heights/resource identities.
Explored resource layouts are persisted separately from evictable terrain meshes.
New catalog resources affect unexplored chunks in generator-2 worlds. Skill IDs
are content references, not gameplay enums: one progression/modifier/risk path
handles all gathering professions. Character snapshots retain skill XP, cooldowns,
and copied timed gathering effects with absolute expiry. Server snapshots publish
personalized risk per resource definition, avoiding a repeated payload per node.
See [milestone 3](MILESTONE-3.md) for tuning, bounds, compatibility, and manual tests.
The simulation ticks at 20 Hz; snapshots are sent at 5 Hz. Coordinates use X/Z
chunk indices and Y height. Terrain has a vertical coordinate but is a 2.5D
heightfield, **not** a volumetric 128x128x128 voxel world. Overhangs, caves, stacked
+136
View File
@@ -0,0 +1,136 @@
# Milestone 3: terrain, movement, and gathering
Implemented for manual playtesting. Model rigs, equipment attachments, animation,
sound, and arbitrary model uploads remain in milestone 4.5. Combat/mob editors
remain milestone 4. Required build and Go checks remain; Playwright runs are deferred.
## Terrain and movement
New worlds use generator 2: deeper hills/valleys and weighted forest, meadow, and
highland regions. Meshes and authoritative movement use the same triangle heights.
Forest resources provide denser tree cover. Resource models use the existing tree,
ore, and herb presets. Caves, mountains, stacked spaces, collision against trees,
fall damage, and animated jumping are not part of this slice.
Existing generator-1 worlds keep their heights, resource coordinates, and depleted
IDs. **Create a new world in Control to test the new terrain and resource spawning.**
An explored chunk's biome and resource layout are saved and kept across eviction,
restart, and catalog publication. New definitions affect unexplored chunks in
generator-2 worlds. Publishing content never relocates an already known node.
The camera starts closer (30). Space jumps, F attacks, E gathers, I opens inventory;
movement remains WASD/arrows and mobile direction buttons. There is also a Jump
button. Go owns jump velocity, gravity, and landing. Menus continue to block input.
## Reusable gathering design
Control → Content now contains Gathering, Resources, Biomes, and Consumables tabs.
Each follows the existing server-assigned IDs, preview, version check, audited
publication, and retry-safe transaction path. Definitions are append-only.
Skills contain name, XP curve, and maximum level. Lumberjack, herbalist, and miner
are initial definitions; adding a fourth profession needs no new gameplay branch.
Resources select a skill, required level, yield, XP, gathering interval, respawn,
model preset, density, and allowed biomes. They can yield wood/ore/herb or a new
material named after the resource. Maximum generated nodes per chunk is 128
(plus the three arrival nodes). Selection order is bounded; a saturated chunk can
omit later resource definitions. Density 0 disables procedural spawning.
Skill XP belongs to the character. The cost of each next level is
`baseXp + (currentLevel - 1) × xpPerLevel`. Travel preserves earned XP; replacement
starts at level 1 with zero XP. Legacy shared gathering XP stays available to
existing title requirements; it is not copied into all three new professions.
Four modifier channels use the same flat-then-percent calculation as existing stats:
| Modifier | Base and use |
| --- | --- |
| Gathering level | Earned skill level; floor/clamp the result to effective level 1–10,000 |
| Gathering yield | Existing final gather-rate stat, normally 100%; scales resource amount |
| Gathering speed | 100%; final range 10–1,000%; interval = base seconds × 100 / final speed |
| Gathering XP | Existing final XP-gain stat, normally 100%; scales profession XP |
Modifiers can apply to every gathering skill or one selected skill. Equipment,
earned titles, reusable effect sets, and consumables share these modifier channels.
Earned levels and XP never change when a level bonus is equipped, used, or expired.
Negative modifiers are supported. Yield retains the existing per-action cap and
fractional roll; profession XP rounds down and grants nothing on failure. Character
XP still uses its existing separate gathering reward and general XP-gain modifier.
Gathering currently resolves one attempt immediately when its server cooldown is
ready; speed changes the interval between attempts. There is no hold-to-channel
animation. Starting another node or changing gear cannot bypass the prior cooldown.
Control's full-stat inspection and the player's Character → Inspect all stats
show base, flat, percent, final values, earned/effective levels, and effect expiry.
Inventory also shows profession XP and remaining XP to the next level.
## Risky gathering
The hard attempt ceiling is **20 levels above effective gathering level**, including
temporary level bonuses. Larger gaps are rejected without consuming an attempt or
changing the node. Meeting the required level has no random failure in this pass.
For an under-level gap `g` from 1 through 20, initial balance.yaml tuning is:
| Outcome | Chance / consequence |
| --- | --- |
| Failure | min(98%, 70% + 1.4% × g) |
| Node destruction, conditional on failure | min(100%, 75% + 1% × g) |
| Negative effect, conditional on failure | 65% |
| Negative consequence | 2 × g direct health damage and 20 seconds of −40% gathering speed for that skill |
At +20 this is 98% failure, with a 95% destruction chance on failure. Damage can
kill and uses the existing permanent-death/corpse path. Failure grants no materials
or XP. Destroyed nodes return after their configured respawn period; they are not
deleted from the world's definition or moved elsewhere. All numbers except the
20-level ceiling are provisional tuning, not final balancing decisions.
Select a node to see authoritative risk and interval. A dangerous attempt first
shows the risks and requires Gather again. Each completed attempt stops, including
a failure that leaves the resource intact. No automatic repeated risky attempts.
## Consumables and persistence
Control can create gathering consumables and grant them through Characters →
Manage items and titles. A starter Gatherer's tonic gives +5 effective levels,
+20% speed, and +20% profession XP to all skills for 120 seconds.
Players use a consumable from their bag. One stack item is consumed; same-source
reuse refreshes duration instead of stacking another copy. Different sources combine.
Effect values and absolute expiry are copied into the character, persisted with
inventory consumption, and preserved on travel. Time offline still counts.
Fatigue refreshes per skill. Active bonuses do not transfer to replacement lives.
Corpse loot retains unused consumable items through the existing inventory path.
The future hub/housing XP policy and resurrection activation remain in their
planned milestones. This slice does not enable either system or alter title-ledger
ownership. No tested-capacity claim is increased.
## Manual playtest
1. Create a new world. Check hills/valleys, forest density, the closer camera,
Space/mobile Jump, F attack, and movement across a chunk edge. Open a menu:
jumping/movement should stop accepting input; Esc should close the focused menu.
2. Gather the three arrival resources. Check that only the corresponding profession
gains XP, the node disappears, and it returns after respawn. No second reward
should come from a depleted node.
3. In Control, create a gathering skill and resource with low difficulty, 2-second
interval, short respawn, and a matching biome. Choose its own material output.
Explore previously unvisited chunks of a new-generation world to find it.
4. Create equipment with skill-specific level/yield/speed/XP modifiers; grant and
equip it. Inspect base/final values in Control. Unequip: effective bonuses should
disappear while earned XP and levels remain unchanged.
5. Grant and use a tonic. Check its consumption, expiry, same-source refresh,
persistence after reconnect, and that only owned consumables have a Use button.
6. With a disposable test character, inspect a level-15 resource at low skill.
Check the second-press risk flow, failure messages, damage/fatigue, and depletion.
Create a level-22 resource: effective level 1 must be rejected. A +1 level bonus
should make that +20 gap attemptable. A lethal failure must leave one corpse.
7. Restart a world after depleting a node and consuming a tonic. Check unchanged
node locations, depletion deadline, remaining items, skill XP, and effect expiry.
Survive/travel to another world: skill XP stays; replacing a dead character resets it.
Server coverage includes new-definition publication/replay, invalid scope rejection,
scoped bonuses, consumption/expiry, risk limits, lethal failure, replacement, daily
cap, survivor import, jump landing, and layout persistence/legacy terrain.
+2
View File
@@ -10,6 +10,8 @@ automation. These are future tasks, not completion gates for the current milesto
- [ ] Content editors: validation, version conflicts, permissions, and previews.
- [ ] Esc closes only the focused menu and restores focus without gameplay input.
- [ ] Terrain/jumping/camera, gathering requirements, yields, and profession panels.
- [ ] 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.
- [ ] Equipment attachments, animation transitions, and sound settings/event playback.
- [ ] Hub-instance switching, admission limits, escape items, and victory portals.
+5 -1
View File
@@ -522,7 +522,11 @@ activate future gameplay or change existing saves.
Milestone 2 implementation and manual handoff:
[Content and input foundations](../docs/MILESTONE-2.md). Reusable requirement/effect
sets, server preview, and focused-menu/input actions are ready for manual testing.
Milestone 3 has not started.
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.
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
+8
View File
@@ -170,6 +170,14 @@ Tracked across:
- Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning?
## Backlog
- 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
XP globally or per skill. Effective level allows attempts up to 20 levels above
it, with high failure/destruction odds and possible damage/fatigue. Probabilities
and consequences are provisional tuning; see `docs/MILESTONE-3.md`.
- New worlds have deeper hills/valleys and biome-specific resources; existing
worlds retain their terrain. Space jumps, F attacks, and the camera starts closer.
- Follow the agreed milestone order and handoff in the systems roadmap. Model rigs,
equipment attachments, animations, and sound hooks are milestone 4.5. Commit and
push after each milestone, then hand off for the user's manual playtest before
+226 -25
View File
@@ -56,19 +56,34 @@
"ContentCatalog": {
"type": "object", "additionalProperties": false,
"properties": {
"version": {"type": "integer"}, "titles": {"type": "array", "items": {"$ref": "#/definitions/TitleDefinition"}},
"items": {"type": "array", "items": {"$ref": "#/definitions/ItemDefinition"}}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSets": {"type": "array", "items": {"$ref": "#/definitions/RequirementSet"}}, "effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}}
"version": {"type": "integer"},
"titles": {"type": "array", "items": {"$ref": "#/definitions/TitleDefinition"}},
"items": {"type": "array", "items": {"$ref": "#/definitions/ItemDefinition"}},
"stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSets": {"type": "array", "items": {"$ref": "#/definitions/RequirementSet"}},
"effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}},
"gathering": {"$ref": "#/definitions/GatheringContent"}
},
"required": ["version", "titles", "items", "stats"]
},
"ContentChange": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "expectedVersion": {"type": "integer"}, "op": {"type": "string"}, "reason": {"type": "string"},
"title": {"$ref": "#/definitions/TitleDraft"}, "item": {"$ref": "#/definitions/ItemDraft"}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSet": {"$ref": "#/definitions/RequirementSetDraft"}, "effectSet": {"$ref": "#/definitions/EffectSetDraft"},
"requirementSetIds": {"type": "array", "items": {"type": "string"}}, "effectSetIds": {"type": "array", "items": {"type": "string"}}
"id": {"type": "string"},
"expectedVersion": {"type": "integer"},
"op": {"type": "string"},
"reason": {"type": "string"},
"title": {"$ref": "#/definitions/TitleDraft"},
"item": {"$ref": "#/definitions/ItemDraft"},
"stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSet": {"$ref": "#/definitions/RequirementSetDraft"},
"effectSet": {"$ref": "#/definitions/EffectSetDraft"},
"requirementSetIds": {"type": "array", "items": {"type": "string"}},
"effectSetIds": {"type": "array", "items": {"type": "string"}},
"gatheringSkill": {"$ref": "#/definitions/GatheringSkillDraft"},
"resource": {"$ref": "#/definitions/ResourceDefinitionDraft"},
"biome": {"$ref": "#/definitions/BiomeDefinitionDraft"},
"consumable": {"$ref": "#/definitions/GatheringConsumableDraft"}
},
"required": ["id", "expectedVersion", "op", "reason"]
},
@@ -125,10 +140,16 @@
"Entity": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "kind": {"type": "string"}, "name": {"type": "string"},
"id": {"type": "string"},
"kind": {"type": "string"},
"name": {"type": "string"},
"position": {"$ref": "#/definitions/Vec3"},
"hp": {"type": "number"}, "maxHp": {"type": "number"},
"state": {"type": "string"}
"hp": {"type": "number"},
"maxHp": {"type": "number"},
"state": {"type": "string"},
"resourceId": {"type": "string"},
"skillId": {"type": "string"},
"requiredLevel": {"type": "integer"}
},
"required": ["id", "kind", "name", "position", "hp", "maxHp", "state"]
},
@@ -138,20 +159,33 @@
"entity": {"$ref": "#/definitions/Entity"},
"inventory": {"type": "object", "additionalProperties": {"type": "integer"}},
"skills": {"type": "object", "additionalProperties": {"type": "integer"}},
"level": {"type": "integer"}, "experience": {"type": "integer"},
"experienceToNextLevel": {"type": "integer"}, "statPoints": {"type": "integer"},
"level": {"type": "integer"},
"experience": {"type": "integer"},
"experienceToNextLevel": {"type": "integer"},
"statPoints": {"type": "integer"},
"titles": {"type": "array", "items": {"$ref": "#/definitions/TitleAward"}},
"allocatedStats": {"type": "object", "additionalProperties": {"type": "integer"}},
"stats": {"type": "object", "additionalProperties": {"$ref": "#/definitions/StatValue"}},
"mana": {"type": "number"}, "stamina": {"type": "number"}, "carryWeight": {"type": "number"},
"pendingVitalChoices": {"type": "integer"}, "healthChoices": {"type": "integer"}, "manaChoices": {"type": "integer"},
"mana": {"type": "number"},
"stamina": {"type": "number"},
"carryWeight": {"type": "number"},
"pendingVitalChoices": {"type": "integer"},
"healthChoices": {"type": "integer"},
"manaChoices": {"type": "integer"},
"items": {"type": "array", "items": {"$ref": "#/definitions/ItemInstance"}},
"equipment": {"type": "object", "additionalProperties": {"type": "string"}},
"playedSeconds": {"type": "number"}, "remainingSeconds": {"type": "number"},
"kills": {"type": "integer"}, "ack": {"type": "integer"},
"hasKeystone": {"type": "boolean"}
"playedSeconds": {"type": "number"},
"remainingSeconds": {"type": "number"},
"kills": {"type": "integer"},
"ack": {"type": "integer"},
"hasKeystone": {"type": "boolean"},
"gathering": {"type": "object", "additionalProperties": {"$ref": "#/definitions/SkillProgress"}},
"gatheringEffects": {"type": "array", "items": {"$ref": "#/definitions/TimedGatheringEffect"}},
"gatherAttempt": {"type": "integer"},
"consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}},
"stackNames": {"type": "object", "additionalProperties": {"type": "string"}}
},
"required": ["entity", "inventory", "skills", "level", "experience", "experienceToNextLevel", "statPoints", "titles", "allocatedStats", "stats", "mana", "stamina", "carryWeight", "pendingVitalChoices", "healthChoices", "manaChoices", "items", "equipment", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone"]
"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"]
},
"TitleEffects": {
"type": "object", "additionalProperties": false,
@@ -160,7 +194,12 @@
},
"StatModifier": {
"type": "object", "additionalProperties": false,
"properties": {"stat": {"type": "string"}, "flat": {"type": "number"}, "percent": {"type": "number"}},
"properties": {
"stat": {"type": "string"},
"flat": {"type": "number"},
"percent": {"type": "number"},
"skill": {"type": "string"}
},
"required": ["stat", "flat", "percent"]
},
"StatValue": {
@@ -194,10 +233,15 @@
"Chunk": {
"type": "object", "additionalProperties": false,
"properties": {
"key": {"type": "string"}, "x": {"type": "integer"}, "z": {"type": "integer"},
"size": {"type": "number"}, "resolution": {"type": "integer"},
"key": {"type": "string"},
"x": {"type": "integer"},
"z": {"type": "integer"},
"size": {"type": "number"},
"resolution": {"type": "integer"},
"heights": {"type": "array", "items": {"type": "number"}},
"biome": {"type": "string"}, "resources": {"type": "array", "items": {"$ref": "#/definitions/Entity"}}
"biome": {"type": "string"},
"resources": {"type": "array", "items": {"$ref": "#/definitions/Entity"}},
"color": {"type": "string"}
},
"required": ["key", "x", "z", "size", "resolution", "heights", "biome", "resources"]
},
@@ -215,15 +259,172 @@
"Snapshot": {
"type": "object", "additionalProperties": false,
"properties": {
"type": {"type": "string"}, "version": {"type": "integer"}, "tick": {"type": "integer"},
"world": {"$ref": "#/definitions/WorldInfo"}, "self": {"$ref": "#/definitions/Character"},
"type": {"type": "string"},
"version": {"type": "integer"},
"tick": {"type": "integer"},
"world": {"$ref": "#/definitions/WorldInfo"},
"self": {"$ref": "#/definitions/Character"},
"entities": {"type": "array", "items": {"$ref": "#/definitions/Entity"}},
"chunks": {"type": "array", "items": {"$ref": "#/definitions/Chunk"}},
"chunkKeys": {"type": "array", "items": {"type": "string"}},
"unavailableResources": {"type": "array", "items": {"type": "string"}},
"message": {"type": "string"}
"message": {"type": "string"},
"gatherRisks": {"type": "object", "additionalProperties": {"$ref": "#/definitions/GatheringRisk"}}
},
"required": ["type", "version", "tick", "world", "self", "entities", "chunks", "chunkKeys", "unavailableResources", "message"]
},
"GatheringSkill": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"baseXp": {"type": "integer"},
"xpPerLevel": {"type": "integer"},
"maxLevel": {"type": "integer"}
},
"required": ["id", "name", "description", "baseXp", "xpPerLevel", "maxLevel"]
},
"GatheringSkillDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"baseXp": {"type": "integer"},
"xpPerLevel": {"type": "integer"},
"maxLevel": {"type": "integer"}
},
"required": ["name", "description", "baseXp", "xpPerLevel", "maxLevel"]
},
"ResourceDefinition": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"skillId": {"type": "string"},
"model": {"type": "string"},
"output": {"type": "string"},
"requiredLevel": {"type": "integer"},
"amount": {"type": "integer"},
"xp": {"type": "integer"},
"seconds": {"type": "number"},
"respawnSeconds": {"type": "number"},
"density": {"type": "integer"},
"biomes": {"type": "array", "items": {"type": "string"}}
},
"required": ["id", "name", "description", "skillId", "model", "output", "requiredLevel", "amount", "xp", "seconds", "respawnSeconds", "density", "biomes"]
},
"ResourceDefinitionDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"skillId": {"type": "string"},
"model": {"type": "string"},
"output": {"type": "string"},
"requiredLevel": {"type": "integer"},
"amount": {"type": "integer"},
"xp": {"type": "integer"},
"seconds": {"type": "number"},
"respawnSeconds": {"type": "number"},
"density": {"type": "integer"},
"biomes": {"type": "array", "items": {"type": "string"}}
},
"required": ["name", "description", "skillId", "model", "output", "requiredLevel", "amount", "xp", "seconds", "respawnSeconds", "density", "biomes"]
},
"BiomeDefinition": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"color": {"type": "string"},
"weight": {"type": "integer"}
},
"required": ["id", "name", "description", "color", "weight"]
},
"BiomeDefinitionDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"color": {"type": "string"},
"weight": {"type": "integer"}
},
"required": ["name", "description", "color", "weight"]
},
"GatheringConsumable": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"seconds": {"type": "number"},
"modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}
},
"required": ["id", "name", "description", "seconds", "modifiers"]
},
"GatheringConsumableDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"description": {"type": "string"},
"seconds": {"type": "number"},
"modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}
},
"required": ["name", "description", "seconds", "modifiers"]
},
"GatheringContent": {
"type": "object", "additionalProperties": false,
"properties": {
"skills": {"type": "array", "items": {"$ref": "#/definitions/GatheringSkill"}},
"resources": {"type": "array", "items": {"$ref": "#/definitions/ResourceDefinition"}},
"biomes": {"type": "array", "items": {"$ref": "#/definitions/BiomeDefinition"}},
"consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}}
},
"required": ["skills", "resources", "biomes", "consumables"]
},
"SkillProgress": {
"type": "object", "additionalProperties": false,
"properties": {
"name": {"type": "string"},
"xp": {"type": "integer"},
"level": {"type": "integer"},
"xpToNextLevel": {"type": "integer"},
"effectiveLevel": {"type": "integer"},
"yield": {"$ref": "#/definitions/StatValue"},
"speed": {"$ref": "#/definitions/StatValue"},
"experience": {"$ref": "#/definitions/StatValue"},
"levelValue": {"$ref": "#/definitions/StatValue"}
},
"required": ["name", "xp", "level", "xpToNextLevel", "effectiveLevel", "yield", "speed", "experience", "levelValue"]
},
"TimedGatheringEffect": {
"type": "object", "additionalProperties": false,
"properties": {
"source": {"type": "string"},
"name": {"type": "string"},
"expiresAt": {"type": "number"},
"modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}
},
"required": ["source", "name", "expiresAt", "modifiers"]
},
"GatheringRisk": {
"type": "object", "additionalProperties": false,
"properties": {
"failure": {"type": "number"},
"destruction": {"type": "number"},
"negative": {"type": "number"},
"damage": {"type": "number"},
"seconds": {"type": "number"},
"allowed": {"type": "boolean"}
},
"required": ["failure", "destruction", "negative", "damage", "seconds", "allowed"]
}
}
}
+40
View File
@@ -1,4 +1,44 @@
version: 1
# Provisional milestone 3 tuning. The +20 attempt ceiling is a gameplay rule.
gatheringRules:
failureBase: 70
failurePerLevel: 1.4
failureMax: 98
destroyBase: 75
destroyPerLevel: 1
negativeChance: 65
damagePerLevel: 2
fatigueSeconds: 20
fatiguePercent: 40
jumpSpeed: 10
gravity: 24
hillHeight: 42
detailHeight: 6
gathering:
skills:
- { id: lumberjack, name: Lumberjack, description: Harvest wood., baseXp: 20, xpPerLevel: 10, maxLevel: 1000 }
- { id: herbalist, name: Herbalist, description: Harvest herbs., baseXp: 20, xpPerLevel: 10, maxLevel: 1000 }
- { id: miner, name: Miner, description: Harvest ore., baseXp: 20, xpPerLevel: 10, maxLevel: 1000 }
biomes:
- { id: forest, name: Forest, description: Wooded rolling hills., color: '#355c3a', weight: 4 }
- { id: meadow, name: Meadow, description: Open grassy valleys., color: '#65784c', weight: 3 }
- { id: highlands, name: Highlands, description: Rocky uplands., color: '#727d68', weight: 3 }
resources:
- { id: tree, name: Young tree, description: Common timber., skillId: lumberjack, model: tree, output: wood, requiredLevel: 1, amount: 1, xp: 2, seconds: 0.6, respawnSeconds: 120, density: 16, biomes: [forest, meadow, highlands] }
- { id: herb, name: Wild herbs, description: Common medicinal herbs., skillId: herbalist, model: herb, output: herb, requiredLevel: 1, amount: 1, xp: 2, seconds: 0.6, respawnSeconds: 120, density: 12, biomes: [forest, meadow, highlands] }
- { id: ore, name: Iron outcrop, description: Common ore., skillId: miner, model: ore, output: ore, requiredLevel: 1, amount: 1, xp: 2, seconds: 0.6, respawnSeconds: 120, density: 12, biomes: [forest, meadow, highlands] }
- { id: ancient_tree, name: Ancient hardwood, description: Difficult timber. Inspect the risk before gathering., skillId: lumberjack, model: tree, output: wood, requiredLevel: 15, amount: 5, xp: 12, seconds: 2, respawnSeconds: 240, density: 4, biomes: [forest] }
- { id: bitter_herb, name: Bitterroot, description: Dangerous herbs., skillId: herbalist, model: herb, output: herb, requiredLevel: 15, amount: 5, xp: 12, seconds: 2, respawnSeconds: 240, density: 4, biomes: [meadow] }
- { id: deep_ore, name: Dense iron, description: A difficult mineral seam., skillId: miner, model: ore, output: ore, requiredLevel: 15, amount: 5, xp: 12, seconds: 2, respawnSeconds: 240, density: 4, biomes: [highlands] }
consumables:
- id: gathering_tonic
name: Gatherer's tonic
description: Temporarily improves every gathering profession. Reuse refreshes duration.
seconds: 120
modifiers:
- { stat: gatheringLevel, flat: 5, percent: 0 }
- { stat: gatheringSpeed, flat: 0, percent: 20 }
- { stat: gatheringXP, flat: 0, percent: 20 }
tickHz: 20
snapshotHz: 5
chunkSize: 128
+12
View File
@@ -19,6 +19,8 @@ type Recipe struct {
}
type Balance struct {
Gathering *GatheringContent `yaml:"gathering"`
GatheringRules *GatheringRules `yaml:"gatheringRules"`
Version int `yaml:"version"`
TickHz int `yaml:"tickHz"`
SnapshotHz int `yaml:"snapshotHz"`
@@ -76,6 +78,16 @@ func Parse(data []byte) (Balance, error) {
return b, b.Validate()
}
func (b Balance) Validate() error {
if b.Gathering != nil {
if err := b.Gathering.Validate(); err != nil {
return err
}
}
if b.GatheringRules != nil {
if err := b.GatheringRules.Validate(); err != nil {
return err
}
}
if b.Stats == nil {
return fmt.Errorf("stats rules are required")
}
+150
View File
@@ -0,0 +1,150 @@
package content
import (
"fmt"
"math"
"slices"
)
// A skill is data, not an enum. All gathering professions share this curve.
type GatheringSkill struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
BaseXP int64 `json:"baseXp" yaml:"baseXp"`
XPPerLevel int64 `json:"xpPerLevel" yaml:"xpPerLevel"`
MaxLevel int64 `json:"maxLevel" yaml:"maxLevel"`
}
type ResourceDefinition struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
SkillID string `json:"skillId" yaml:"skillId"`
Model string `json:"model" yaml:"model"`
Output string `json:"output" yaml:"output"`
RequiredLevel int64 `json:"requiredLevel" yaml:"requiredLevel"`
Amount int64 `json:"amount" yaml:"amount"`
XP int64 `json:"xp" yaml:"xp"`
Seconds float64 `json:"seconds" yaml:"seconds"`
RespawnSeconds float64 `json:"respawnSeconds" yaml:"respawnSeconds"`
Density int64 `json:"density" yaml:"density"`
Biomes []string `json:"biomes" yaml:"biomes"`
}
type BiomeDefinition struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Color string `json:"color" yaml:"color"`
Weight int64 `json:"weight" yaml:"weight"`
}
type GatheringConsumable struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Seconds float64 `json:"seconds" yaml:"seconds"`
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
}
type GatheringContent struct {
Skills []GatheringSkill `json:"skills" yaml:"skills"`
Resources []ResourceDefinition `json:"resources" yaml:"resources"`
Biomes []BiomeDefinition `json:"biomes" yaml:"biomes"`
Consumables []GatheringConsumable `json:"consumables" yaml:"consumables"`
}
type GatheringRules struct {
FailureBase float64 `json:"failureBase" yaml:"failureBase"`
FailurePerLevel float64 `json:"failurePerLevel" yaml:"failurePerLevel"`
FailureMax float64 `json:"failureMax" yaml:"failureMax"`
DestroyBase float64 `json:"destroyBase" yaml:"destroyBase"`
DestroyPerLevel float64 `json:"destroyPerLevel" yaml:"destroyPerLevel"`
NegativeChance float64 `json:"negativeChance" yaml:"negativeChance"`
DamagePerLevel float64 `json:"damagePerLevel" yaml:"damagePerLevel"`
FatigueSeconds float64 `json:"fatigueSeconds" yaml:"fatigueSeconds"`
FatiguePercent float64 `json:"fatiguePercent" yaml:"fatiguePercent"`
JumpSpeed float64 `json:"jumpSpeed" yaml:"jumpSpeed"`
Gravity float64 `json:"gravity" yaml:"gravity"`
HillHeight float64 `json:"hillHeight" yaml:"hillHeight"`
DetailHeight float64 `json:"detailHeight" yaml:"detailHeight"`
}
var GatheringStats = []string{"gatheringLevel", "gatheringYield", "gatheringSpeed", "gatheringXP"}
func GatheringStat(key string) bool { return slices.Contains(GatheringStats, key) }
func finiteRange(v, low, high float64) bool {
return !math.IsNaN(v) && !math.IsInf(v, 0) && v >= low && v <= high
}
func (r GatheringRules) Validate() error {
for _, v := range []float64{r.FailureBase, r.FailurePerLevel, r.FailureMax, r.DestroyBase, r.DestroyPerLevel, r.NegativeChance, r.FatiguePercent} {
if !finiteRange(v, 0, 100) {
return fmt.Errorf("invalid gathering probability or fatigue")
}
}
if r.FailureMax < r.FailureBase || !finiteRange(r.DamagePerLevel, 0, 100) || !finiteRange(r.FatigueSeconds, 1, 3600) || !finiteRange(r.JumpSpeed, 1, 30) || !finiteRange(r.Gravity, 1, 100) || !finiteRange(r.HillHeight, 1, 100) || !finiteRange(r.DetailHeight, 0, 20) {
return fmt.Errorf("invalid gathering/movement rules")
}
return nil
}
func (g GatheringContent) Validate() error {
if len(g.Skills) < 1 || len(g.Skills) > 64 || len(g.Resources) > 256 || len(g.Biomes) < 1 || len(g.Biomes) > 32 || len(g.Consumables) > 256 {
return fmt.Errorf("invalid gathering content counts")
}
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
}
skills, biomes := map[string]bool{}, map[string]bool{}
for _, s := range g.Skills {
if !identity(s.ID, s.Name, s.Description) || s.BaseXP < 1 || s.BaseXP > 1000000 || s.XPPerLevel < 0 || s.XPPerLevel > 1000000 || s.MaxLevel < 2 || s.MaxLevel > 10000 {
return fmt.Errorf("invalid gathering skill %q", s.ID)
}
skills[s.ID] = true
}
for _, b := range g.Biomes {
if !identity(b.ID, b.Name, b.Description) || b.Weight < 1 || b.Weight > 100 || len(b.Color) != 7 || b.Color[0] != '#' {
return fmt.Errorf("invalid biome %q", b.ID)
}
for _, c := range b.Color[1:] {
if !slices.Contains([]rune("0123456789abcdefABCDEF"), c) {
return fmt.Errorf("invalid biome color")
}
}
biomes[b.ID] = true
}
for _, r := range g.Resources {
if !identity(r.ID, r.Name, r.Description) || !skills[r.SkillID] || !slices.Contains([]string{"tree", "ore", "herb"}, r.Model) || !slices.Contains([]string{"wood", "ore", "herb", "self"}, r.Output) || r.RequiredLevel < 1 || r.RequiredLevel > 10000 || r.Amount < 1 || r.Amount > 1000 || r.XP < 0 || r.XP > 1000000 || !finiteRange(r.Seconds, 0.1, 3600) || !finiteRange(r.RespawnSeconds, 1, 604800) || r.Density < 0 || r.Density > 32 || len(r.Biomes) < 1 || len(r.Biomes) > 32 {
return fmt.Errorf("invalid resource %q", r.ID)
}
seen := map[string]bool{}
for _, id := range r.Biomes {
if !biomes[id] || seen[id] {
return fmt.Errorf("unknown/duplicate resource biome %q", id)
}
seen[id] = true
}
}
for _, c := range g.Consumables {
if !identity(c.ID, c.Name, c.Description) || !finiteRange(c.Seconds, 1, 86400) || len(c.Modifiers) < 1 {
return fmt.Errorf("invalid consumable %q", c.ID)
}
if err := ValidateModifiers(c.Modifiers); err != nil {
return err
}
for _, m := range c.Modifiers {
if !GatheringStat(m.Stat) {
return fmt.Errorf("gathering consumables require gathering modifiers")
}
}
}
return nil
}
func (g GatheringContent) ValidateScopes(mods []StatModifier) error {
for _, m := range mods {
if m.Skill != "" && !slices.ContainsFunc(g.Skills, func(s GatheringSkill) bool { return s.ID == m.Skill }) {
return fmt.Errorf("unknown gathering skill %q", m.Skill)
}
}
return nil
}
+39 -8
View File
@@ -19,6 +19,7 @@ var StatLinks = map[string][]string{
}
type StatModifier struct {
Skill string `json:"skill,omitempty" yaml:"skill"`
Stat string `json:"stat" yaml:"stat"`
Flat float64 `json:"flat" yaml:"flat"`
Percent float64 `json:"percent" yaml:"percent"`
@@ -44,12 +45,13 @@ type ItemDefinition struct {
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
}
type Catalog struct {
Version int64 `json:"version"`
Titles []Title `json:"titles"`
Items []ItemDefinition `json:"items"`
Stats StatsRules `json:"stats"`
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
EffectSets []EffectSet `json:"effectSets,omitempty"`
Gathering *GatheringContent `json:"gathering,omitempty"`
Version int64 `json:"version"`
Titles []Title `json:"titles"`
Items []ItemDefinition `json:"items"`
Stats StatsRules `json:"stats"`
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
EffectSets []EffectSet `json:"effectSets,omitempty"`
}
func KnownStat(stat string) bool {
@@ -85,7 +87,7 @@ func ValidateModifiers(modifiers []StatModifier) error {
return fmt.Errorf("too many modifiers")
}
for _, m := range modifiers {
if !KnownStat(m.Stat) || math.IsNaN(m.Flat) || math.IsInf(m.Flat, 0) || math.Abs(m.Flat) > 1000000 || math.IsNaN(m.Percent) || math.IsInf(m.Percent, 0) || m.Percent < -100 || m.Percent > 10000 {
if (!KnownStat(m.Stat) && !GatheringStat(m.Stat)) || (m.Skill != "" && (!GatheringStat(m.Stat) || !titleID.MatchString(m.Skill))) || math.IsNaN(m.Flat) || math.IsInf(m.Flat, 0) || math.Abs(m.Flat) > 1000000 || math.IsNaN(m.Percent) || math.IsInf(m.Percent, 0) || m.Percent < -100 || m.Percent > 10000 {
return fmt.Errorf("invalid modifier for %q", m.Stat)
}
}
@@ -122,6 +124,35 @@ func (item ItemDefinition) Validate() error {
return ValidateModifiers(item.Modifiers)
}
func (c Catalog) Validate() error {
if c.Gathering != nil {
if err := c.Gathering.Validate(); err != nil {
return err
}
mods := []StatModifier{}
for _, i := range c.Items {
mods = append(mods, i.Modifiers...)
}
for _, t := range c.Titles {
mods = append(mods, t.Effects.Modifiers...)
}
for _, e := range c.EffectSets {
mods = append(mods, e.Modifiers...)
}
for _, v := range c.Gathering.Consumables {
mods = append(mods, v.Modifiers...)
}
if err := c.Gathering.ValidateScopes(mods); err != nil {
return err
}
for _, v := range c.Gathering.Consumables {
for _, i := range c.Items {
if v.ID == i.ID {
return fmt.Errorf("consumable/equipment identity collision")
}
}
}
}
if err := c.validateLibrary(); err != nil {
return err
}
@@ -165,5 +196,5 @@ func DefaultCatalog() (Catalog, error) {
if err != nil {
return Catalog{}, err
}
return Catalog{Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
return Catalog{Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
}
+12
View File
@@ -30,6 +30,18 @@ func (w *World) AdminItems(c *Character, op, value string) error {
}
if op == "grant-item" {
known := false
if w.Balance.Gathering != nil {
for _, r := range w.Balance.Gathering.Resources {
if r.Output == "self" && r.ID == id {
known = true
}
}
for _, v := range w.Balance.Gathering.Consumables {
if v.ID == id {
known = true
}
}
}
for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} {
if key == id {
known = true
+84
View File
@@ -0,0 +1,84 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"fmt"
"hash/fnv"
"math"
"math/rand/v2"
"slices"
)
// Read-only arrival preview uses the world's generator and any explored layout.
func (w *World) PreviewChunk(x, z int) p.Chunk {
c := w.terrain.Chunk(x, z)
if layout, ok := w.ResourceLayouts[c.Key]; ok {
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
}
return c
}
func (t *Terrain) biome(x, z int) content.BiomeDefinition {
list := t.B.Gathering.Biomes
total := int64(0)
for _, b := range list {
total += b.Weight
}
// Low-frequency noise creates contiguous biome regions; no per-frame randomness.
n := (t.noise.Eval2((float64(x)+0.5)/3, (float64(z)+0.5)/3) + 1) / 2
choice := int64(n * float64(total))
for _, b := range list {
choice -= b.Weight
if choice < 0 {
return b
}
}
return list[len(list)-1]
}
func (t *Terrain) Chunk(x, z int) p.Chunk {
c := t.legacyChunk(x, z)
if t.B.Gathering == nil {
return c
}
biome := t.biome(x, z)
c.Biome = biome.Name
c.Color = &biome.Color
if t.Version == 1 {
for i := range c.Resources {
e := &c.Resources[i]
e.ResourceID = stringPtr(e.Kind)
}
return c // Legacy coordinates and depleted IDs are never regenerated under new rules.
}
c.Resources = []p.Entity{}
for _, r := range t.B.Gathering.Resources {
if !slices.Contains(r.Biomes, biome.ID) {
continue
}
hash := fnv.New64a()
fmt.Fprintf(hash, "%d:%d:%d:%s", t.Seed, x, z, r.ID)
rng := rand.New(rand.NewPCG(hash.Sum64(), uint64(t.Seed)))
count := r.Density
if biome.ID == "forest" && r.Model == "tree" {
count = min(int64(32), count*2)
}
for i := int64(0); i < count && len(c.Resources) < 128; i++ {
px, pz := (float64(x)+.08+rng.Float64()*.84)*c.Size, (float64(z)+.08+rng.Float64()*.84)*c.Size
if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 25 {
continue
}
c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%s:%d", x, z, r.ID, i), Kind: r.Model, Name: r.Name, ResourceID: stringPtr(r.ID), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"})
}
}
if x == 0 && z == 0 {
for i, id := range []string{"tree", "ore", "herb"} {
for _, r := range t.B.Gathering.Resources {
if r.ID == id {
c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + id, Kind: r.Model, Name: r.Name, ResourceID: stringPtr(id), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"})
}
}
}
}
return c
}
+1 -1
View File
@@ -62,7 +62,7 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn
item.Requirements.Stats[stat] = value
}
for _, modifier := range definition.Modifiers {
item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
item.Modifiers = append(item.Modifiers, p.StatModifier{Skill: stringPtr(modifier.Skill), Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
}
created = append(created, item)
}
+298
View File
@@ -0,0 +1,298 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"errors"
"fmt"
"math"
"slices"
)
func stringPtr(s string) *string {
if s == "" {
return nil
}
return &s
}
func stringValue(s *string) string {
if s == nil {
return ""
}
return *s
}
func (w *World) restoreGathering(c *Character) error {
for _, xp := range c.View.Skills {
if xp < 0 || xp > 1000000000000 {
return errors.New("invalid persisted skill XP")
}
}
if math.IsNaN(c.JumpVelocity) || math.IsInf(c.JumpVelocity, 0) || math.IsNaN(c.GatherReadyAt) || math.IsInf(c.GatherReadyAt, 0) || c.GatherReadyAt < 0 || len(c.View.GatheringEffects) > 128 {
return errors.New("invalid persisted gathering/movement state")
}
seen := map[string]bool{}
live := []p.TimedGatheringEffect{}
for _, e := range c.View.GatheringEffects {
if e.Source == "" || len(e.Source) > 100 || seen[e.Source] || len(e.Name) > 160 || math.IsNaN(e.ExpiresAt) || math.IsInf(e.ExpiresAt, 0) || e.ExpiresAt < 0 {
return errors.New("invalid persisted gathering effect")
}
seen[e.Source] = true
mods := []content.StatModifier{}
for _, m := range e.Modifiers {
if !content.GatheringStat(m.Stat) {
return errors.New("unsupported timed gathering modifier")
}
mods = append(mods, content.StatModifier{Stat: m.Stat, Skill: stringValue(m.Skill), Flat: m.Flat, Percent: m.Percent})
}
if err := content.ValidateModifiers(mods); err != nil {
return err
}
if e.ExpiresAt > float64(w.now.UnixMilli())/1000 {
live = append(live, e)
}
}
if len(live) != len(c.View.GatheringEffects) {
w.dirty = true
}
c.View.GatheringEffects = live
return nil
}
func (w *World) gatheringModifiers(c *Character) []p.StatModifier {
mods := []p.StatModifier{}
seen := map[string]bool{}
for _, t := range c.View.Titles {
if !seen[t.ID] {
mods = append(mods, t.Effects.Modifiers...)
seen[t.ID] = true
}
}
equipped := map[string]bool{}
for _, id := range c.View.Equipment {
equipped[id] = true
}
for _, i := range c.View.Items {
if equipped[i.ID] {
mods = append(mods, i.Modifiers...)
}
}
now := float64(w.now.UnixMilli()) / 1000
for _, e := range c.View.GatheringEffects {
if e.ExpiresAt > now {
mods = append(mods, e.Modifiers...)
}
}
return mods
}
func (w *World) refreshGathering(c *Character) {
if w.Balance.Gathering == nil {
return
}
if c.View.Skills == nil {
c.View.Skills = map[string]int64{}
}
c.View.Gathering = map[string]p.SkillProgress{}
mods := w.gatheringModifiers(c)
value := func(skill, key string, base, min, max float64) p.StatValue {
v := p.StatValue{Base: base}
for _, m := range mods {
if m.Stat == key && (stringValue(m.Skill) == "" || stringValue(m.Skill) == skill) {
v.Flat += m.Flat
v.Percent += m.Percent
}
}
v.Final = math.Max(min, math.Min(max, (v.Base+v.Flat)*math.Max(0, 1+v.Percent/100)))
return v
}
for _, s := range w.Balance.Gathering.Skills {
xp := max(0, c.View.Skills[s.ID])
remaining := xp
level := int64(1)
for level < s.MaxLevel {
cost := s.BaseXP + (level-1)*s.XPPerLevel
if remaining < cost {
break
}
remaining -= cost
level++
}
next := s.BaseXP + (level-1)*s.XPPerLevel - remaining
if level == s.MaxLevel {
next = 0
}
lv := value(s.ID, "gatheringLevel", float64(level), 1, 10000)
c.View.Gathering[s.ID] = p.SkillProgress{Name: s.Name, XP: xp, Level: level, XPToNextLevel: next, EffectiveLevel: int64(math.Floor(lv.Final)), LevelValue: lv, Yield: value(s.ID, "gatheringYield", c.View.Stats["gatherRate"].Final, 0, 100000), Speed: value(s.ID, "gatheringSpeed", 100, 10, 1000), Experience: value(s.ID, "gatheringXP", c.View.Stats["xpGain"].Final, 0, 100000)}
}
c.View.StackNames = map[string]string{}
for _, r := range w.Balance.Gathering.Resources {
if r.Output == "self" && c.View.Inventory[r.ID] > 0 {
c.View.StackNames[r.ID] = r.Name
}
}
c.View.Consumables = []p.GatheringConsumable{}
for _, v := range w.Balance.Gathering.Consumables {
if c.View.Inventory[v.ID] > 0 {
c.View.StackNames[v.ID] = v.Name
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
}
}
}
func (w *World) resource(id string) *content.ResourceDefinition {
for i := range w.Balance.Gathering.Resources {
if w.Balance.Gathering.Resources[i].ID == id {
return &w.Balance.Gathering.Resources[i]
}
}
return nil
}
func (w *World) gatherRisk(c *Character, r content.ResourceDefinition) p.GatheringRisk {
s := c.View.Gathering[r.SkillID]
gap := max(int64(0), r.RequiredLevel-s.EffectiveLevel)
rules := w.Balance.GatheringRules
risk := p.GatheringRisk{Allowed: gap <= 20, Seconds: r.Seconds * 100 / math.Max(10, s.Speed.Final)}
if gap > 0 {
risk.Failure = math.Min(rules.FailureMax, rules.FailureBase+float64(gap)*rules.FailurePerLevel)
risk.Destruction = math.Min(100, rules.DestroyBase+float64(gap)*rules.DestroyPerLevel)
risk.Negative = rules.NegativeChance
risk.Damage = float64(gap) * rules.DamagePerLevel
}
return risk
}
func (w *World) gather(c *Character, target string) error {
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
w.refreshGathering(c)
for _, ch := range w.neighbors(c.View.Entity.Position) {
for _, e := range ch.Resources {
if e.ID != target {
continue
}
if distance(c.View.Entity.Position, e.Position) > w.Balance.GatherRange || math.Abs(c.View.Entity.Position.Y-e.Position.Y) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
id := stringValue(e.ResourceID)
if id == "" {
id = e.Kind
}
r := w.resource(id)
if r == nil {
return errors.New("not gatherable")
}
risk := w.gatherRisk(c, *r)
if !risk.Allowed {
return errors.New("resource requires more than 20 levels above your effective gathering level")
}
if w.Age() < c.GatherReadyAt || w.Age()-c.LastGather < risk.Seconds {
return errors.New("gathering cooldown")
}
c.LastGather = w.Age()
c.GatherReadyAt = w.Age() + risk.Seconds
c.View.GatherAttempt++
w.dirty = true
if w.roll(risk.Failure) {
destroyed := w.roll(risk.Destruction)
if destroyed {
w.Depleted[target] = w.Age() + r.RespawnSeconds
}
negative := w.roll(risk.Negative)
if negative {
c.View.Entity.HP = math.Max(0, c.View.Entity.HP-risk.Damage)
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: "fatigue:" + r.SkillID, Name: "Gathering fatigue: " + c.View.Gathering[r.SkillID].Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + w.Balance.GatheringRules.FatigueSeconds, Modifiers: []p.StatModifier{{Stat: "gatheringSpeed", Skill: stringPtr(r.SkillID), Percent: -w.Balance.GatheringRules.FatiguePercent}}})
}
c.Message = "Gathering failed"
if destroyed {
c.Message += "; resource destroyed until respawn"
}
if negative {
c.Message += fmt.Sprintf("; %.0f damage and gathering fatigue", risk.Damage)
}
if c.View.Entity.HP <= 0 {
w.kill(c, "A dangerous gathering attempt ended this character's journey.")
}
w.RefreshStats(c)
return nil
}
output := r.Output
if output == "self" {
output = r.ID
}
n := w.yieldAmount(float64(r.Amount) * c.View.Gathering[r.SkillID].Yield.Final)
if n > 0 {
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, output, n); err != nil {
return err
}
}
xp := int64(math.Min(1000000000, float64(r.XP)*c.View.Gathering[r.SkillID].Experience.Final/100))
c.View.Skills[r.SkillID] = min(int64(1000000000000), c.View.Skills[r.SkillID]+xp)
// Keep the legacy aggregate for existing title predicates, never as a level.
c.View.Skills["gathering"] = min(int64(1000000000000), c.View.Skills["gathering"]+w.Balance.SkillXpPerAction)
w.Depleted[target] = w.Age() + r.RespawnSeconds
label := output
if r.Output == "self" {
label = r.Name
}
c.Message = fmt.Sprintf("Gathered %d %s; +%d %s XP", n, label, xp, c.View.Gathering[r.SkillID].Name)
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) applyGatheringEffect(c *Character, e p.TimedGatheringEffect) {
c.View.GatheringEffects = slices.DeleteFunc(c.View.GatheringEffects, func(v p.TimedGatheringEffect) bool {
return v.Source == e.Source || v.ExpiresAt <= float64(w.now.UnixMilli())/1000
})
c.View.GatheringEffects = append(c.View.GatheringEffects, e)
}
func (w *World) consumeGathering(c *Character, id string) error {
if c.View.Inventory[id] < 1 {
return errors.New("consumable not in inventory")
}
for _, v := range w.Balance.Gathering.Consumables {
if v.ID == id {
if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) {
return errors.New("too many active gathering effects")
}
c.View.Inventory[id]--
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: id, Name: v.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
w.RefreshStats(c)
c.Message = "Used " + v.Name
w.dirty = true
return nil
}
}
return errors.New("unknown gathering consumable")
}
func (w *World) jump(c *Character) error {
ground := w.terrain.Height(c.View.Entity.Position.X, c.View.Entity.Position.Z)
if c.JumpVelocity != 0 || c.View.Entity.Position.Y > ground+0.05 {
return errors.New("already airborne")
}
c.JumpVelocity = w.Balance.GatheringRules.JumpSpeed
w.dirty = true
return nil
}
func (w *World) moveCharacter(c *Character, dt float64) {
pos := c.View.Entity.Position
speed := w.playerSpeed(c)
x, z := pos.X+c.MoveX*speed*dt, pos.Z+c.MoveZ*speed*dt
if math.Hypot(x, z) >= w.Balance.WorldRadius {
x, z = pos.X, pos.Z
}
ground := w.terrain.Height(x, z)
if c.JumpVelocity != 0 || pos.Y > w.terrain.Height(pos.X, pos.Z)+0.05 {
y := pos.Y + c.JumpVelocity*dt - w.Balance.GatheringRules.Gravity*dt*dt/2
c.JumpVelocity -= w.Balance.GatheringRules.Gravity * dt
if y <= ground {
y = ground
c.JumpVelocity = 0
}
c.View.Entity.Position = p.Vec3{X: x, Y: y, Z: z}
} else {
c.View.Entity.Position = w.terrain.Position(x, z)
}
}
+211
View File
@@ -0,0 +1,211 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"math"
"reflect"
"testing"
"time"
)
func gatheringArrival(t *testing.T, w *World, c *Character) {
t.Helper()
w.now = w.CreatedAt.Add(time.Minute)
c.View.Entity.Position = w.terrain.Position(12, 12)
}
func TestGatheringSkillsModifiersAndConsumables(t *testing.T) {
w, c := fixture(t)
gatheringArrival(t, w, c)
// A scoped item changes effective level, yield, speed and XP through one path.
mods := []p.StatModifier{{Stat: "gatheringLevel", Skill: stringPtr("lumberjack"), Flat: 5}, {Stat: "gatheringYield", Skill: stringPtr("lumberjack"), Percent: 100}, {Stat: "gatheringSpeed", Skill: stringPtr("lumberjack"), Percent: 100}, {Stat: "gatheringXP", Skill: stringPtr("lumberjack"), Percent: 100}}
c.View.Items = append(c.View.Items, p.ItemInstance{ID: "test-ring", DefinitionID: "test-ring", Name: "Test ring", Slot: "ring", Requirements: p.ItemRequirements{Level: 1}, Modifiers: mods})
c.View.Equipment["ring1"] = "test-ring"
w.RefreshStats(c)
if c.View.Gathering["lumberjack"].Level != 1 || c.View.Gathering["lumberjack"].EffectiveLevel != 6 || c.View.Gathering["miner"].EffectiveLevel != 1 {
t.Fatal("level bonus leaked or granted earned levels")
}
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Inventory["wood"] != 2 || c.View.Skills["lumberjack"] != 4 || c.View.Skills["miner"] != 0 {
t.Fatal("wrong scoped yield or XP", c.View.Inventory, c.View.Skills)
}
if err := w.gather(c, "arrival:tree"); err == nil {
t.Fatal("depleted node rewarded twice")
}
delete(w.Depleted, "arrival:tree")
w.now = w.now.Add(200 * time.Millisecond)
if err := w.gather(c, "arrival:tree"); err == nil {
t.Fatal("gather speed bypassed cooldown")
}
w.now = w.now.Add(200 * time.Millisecond)
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if err := w.unequip(c, "ring1"); err != nil {
t.Fatal(err)
}
if c.View.Gathering["lumberjack"].EffectiveLevel != 1 || c.View.Skills["lumberjack"] != 8 {
t.Fatal("unequip changed earned XP")
}
c.View.Inventory["gathering_tonic"] = 2
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
first := c.View.GatheringEffects[0].ExpiresAt
w.now = w.now.Add(time.Second)
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
if len(c.View.GatheringEffects) != 1 || c.View.GatheringEffects[0].ExpiresAt <= first || c.View.Gathering["miner"].EffectiveLevel != 6 || c.View.Inventory["gathering_tonic"] != 0 {
t.Fatal("consumption did not refresh one source")
}
if err := w.consumeGathering(c, "gathering_tonic"); err == nil {
t.Fatal("used missing consumable")
}
raw, _ := json.Marshal(w)
var restored World
if err := json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err := restored.Restore(w.now.Add(121 * time.Second)); err != nil {
t.Fatal(err)
}
rc := restored.Characters[c.View.Entity.ID]
if rc.View.Gathering["miner"].EffectiveLevel != 1 || rc.View.Skills["lumberjack"] != 8 {
t.Fatal("restart renewed expired bonus or lost progression")
}
}
func TestGatheringRiskCeilingFailureDeathAndReplacement(t *testing.T) {
w, c := fixture(t)
gatheringArrival(t, w, c)
r := w.resource("tree")
r.RequiredLevel = 22
before := c.View.GatherAttempt
if err := w.gather(c, "arrival:tree"); err == nil || c.View.GatherAttempt != before || len(w.Depleted) != 0 {
t.Fatal("accepted +21 or mutated rejection")
}
r.RequiredLevel = 21
risk := w.gatherRisk(c, *r)
if !risk.Allowed || risk.Failure < 95 || risk.Destruction < 90 || risk.Negative == 0 {
t.Fatal("+20 should be allowed but extremely risky", risk)
}
// Force each probabilistic outcome independently for deterministic lifecycle coverage.
rules := w.Balance.GatheringRules
rules.FailureBase = 100
rules.FailureMax = 100
rules.DestroyBase = 100
rules.NegativeChance = 100
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Skills["lumberjack"] != 0 || c.View.Inventory["wood"] != 0 || w.Depleted["arrival:tree"] <= w.Age() || len(c.View.GatheringEffects) != 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
t.Fatal("failure gave rewards or omitted consequences")
}
c.View.Entity.HP = 1
delete(w.Depleted, "arrival:tree")
w.now = w.now.Add(time.Minute)
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Entity.State != "dead" || len(w.Corpses) != 1 {
t.Fatal("lethal failure did not use permanent-death path")
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "gather", Seq: 1, Target: "arrival:tree"}); err == nil {
t.Fatal("dead character gathered")
}
replacement, err := w.Join(c.Account, "Replacement")
if err != nil {
t.Fatal(err)
}
if replacement.View.Gathering["lumberjack"].Level != 1 || len(replacement.View.GatheringEffects) != 0 {
t.Fatal("replacement inherited progress or effects")
}
}
func TestGatheringProgressAndEffectsTravel(t *testing.T) {
w, c := fixture(t)
c.View.Skills["miner"] = 90
c.View.Inventory["gathering_tonic"] = 1
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
c.DailySeconds = 123
c.View.Entity.State = "eligible"
expiry := c.View.GatheringEffects[0].ExpiresAt
b, _ := content.Load()
dest := New("next", 42, w.now, b)
if err := dest.Import(c); err != nil {
t.Fatal(err)
}
if c.View.Skills["miner"] != 90 || c.View.Gathering["miner"].Level != 4 || c.View.Gathering["miner"].EffectiveLevel != 9 || c.DailySeconds != 123 || c.View.GatheringEffects[0].ExpiresAt != expiry {
t.Fatal("travel reset XP, usage, or renewed effects")
}
if err := dest.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
c.DailySeconds = b.DailyPlaySeconds
dest.Advance(w.now.Add(time.Second), 1)
if c.Online || !c.Sheltered {
t.Fatal("daily cap bypassed")
}
if err := dest.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 1}); err == nil {
t.Fatal("capped player acted")
}
}
func TestJumpAndPersistedResourceLayouts(t *testing.T) {
w, c := fixture(t)
ground := c.View.Entity.Position.Y
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 1}); err != nil {
t.Fatal(err)
}
w.Advance(w.now.Add(100*time.Millisecond), .1)
if c.View.Entity.Position.Y <= ground {
t.Fatal("jump did not rise")
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 2}); err == nil {
t.Fatal("air jump accepted")
}
for i := 0; i < 30; i++ {
w.Advance(w.now.Add(50*time.Millisecond), .05)
}
if math.Abs(c.View.Entity.Position.Y-ground) > 1e-8 || c.JumpVelocity != 0 {
t.Fatal("jump did not land on authoritative terrain")
}
ch := w.chunk(0, 0)
depleted := ch.Resources[0].ID
w.Depleted[depleted] = w.Age() + 100
w.Balance.Gathering.Resources = append(w.Balance.Gathering.Resources, content.ResourceDefinition{ID: "added", Name: "Added", SkillID: "miner", Model: "ore", Output: "ore", RequiredLevel: 1, Amount: 1, Seconds: 1, RespawnSeconds: 60, Density: 32, Biomes: []string{"forest", "meadow", "highlands"}})
raw, _ := json.Marshal(w)
var restored World
_ = json.Unmarshal(raw, &restored)
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ch, restored.chunk(0, 0)) || restored.Depleted[depleted] != w.Depleted[depleted] {
t.Fatal("catalog/restart rerolled explored nodes or depletion")
}
found := false
for _, r := range restored.chunk(5, 0).Resources {
if stringValue(r.ResourceID) == "added" {
found = true
}
}
if !found {
t.Fatal("new resource missing from unexplored chunk")
}
old := NewTerrain(w.Seed, w.Balance)
old.Version = 1
restored.Version = 1
restored.ResourceLayouts = nil
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if restored.terrain.Height(130, 75) != old.Height(130, 75) {
t.Fatal("legacy terrain changed")
}
if math.Abs(old.Height(130, 75)-w.terrain.Height(130, 75)) < .01 {
t.Fatal("new terrain is not deeper")
}
}
+6 -1
View File
@@ -15,7 +15,7 @@ import (
func protocolModifiers(in []content.StatModifier) []p.StatModifier {
out := make([]p.StatModifier, 0, len(in))
for _, m := range in {
out = append(out, p.StatModifier{Stat: m.Stat, Flat: m.Flat, Percent: m.Percent})
out = append(out, p.StatModifier{Skill: stringPtr(m.Skill), Stat: m.Stat, Flat: m.Flat, Percent: m.Percent})
}
return out
}
@@ -88,6 +88,7 @@ func (w *World) RefreshStats(c *Character) {
}
w.revalidateEquipment(c)
c.View.Stats = w.statValues(c, true)
w.refreshGathering(c)
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))
@@ -161,6 +162,10 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error {
if err := catalog.Validate(); err != nil {
return err
}
if catalog.Gathering != nil {
w.Balance.Gathering = catalog.Gathering
w.terrain.B.Gathering = catalog.Gathering
}
w.Balance.Titles = catalog.Titles
w.Balance.Items = catalog.Items
w.Balance.Stats = &catalog.Stats
+10 -6
View File
@@ -10,20 +10,24 @@ import (
"github.com/ojrac/opensimplex-go"
)
const GeneratorVersion = 1
const GeneratorVersion = 2
type Terrain struct {
Seed int64
B content.Balance
noise opensimplex.Noise
Version int
Seed int64
B content.Balance
noise opensimplex.Noise
}
func NewTerrain(seed int64, b content.Balance) *Terrain {
return &Terrain{seed, b, opensimplex.New(seed)}
return &Terrain{Version: GeneratorVersion, Seed: seed, B: b, noise: opensimplex.New(seed)}
}
func (t *Terrain) rawHeight(x, z float64) float64 {
// A low, flat arrival clearing blends into broad hills and fine detail.
d := math.Min(1, math.Hypot(x, z)/55)
if t.Version >= 2 {
return (t.noise.Eval2(x/220, z/220)*t.B.GatheringRules.HillHeight + t.noise.Eval2(x/55, z/55)*t.B.GatheringRules.DetailHeight) * d
}
return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d
}
func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) }
@@ -42,7 +46,7 @@ func (t *Terrain) Height(x, z float64) float64 {
return d + (c-d)*(1-fx) + (b-d)*(1-fz)
}
func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} }
func (t *Terrain) Chunk(x, z int) p.Chunk {
func (t *Terrain) legacyChunk(x, z int) p.Chunk {
c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}}
for iz := 0; iz <= t.B.TerrainResolution; iz++ {
for ix := 0; ix <= t.B.TerrainResolution; ix++ {
+94 -40
View File
@@ -15,6 +15,9 @@ import (
)
type Character struct {
JumpVelocity float64 `json:"jumpVelocity"`
GatherReadyAt float64 `json:"gatherReadyAt"`
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
@@ -49,7 +52,14 @@ type Mob struct {
LastAttack float64 `json:"lastAttack"`
RespawnAt float64 `json:"respawnAt"`
}
type ResourceLayout struct {
Biome string `json:"biome"`
Color *string `json:"color"`
Resources []p.Entity `json:"resources"`
}
type World struct {
ResourceLayouts map[string]ResourceLayout `json:"resourceLayouts,omitempty"`
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
@@ -87,7 +97,7 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World {
return w
}
func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
if w.Version != 1 && w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
// Snapshots predating progression receive the YAML defaults once. Existing
@@ -133,6 +143,22 @@ func (w *World) Restore(now time.Time) error {
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction
w.dirty = true
}
if w.Balance.Gathering == nil || w.Balance.GatheringRules == nil {
b, err := content.Load()
if err != nil {
return err
}
if w.Balance.Gathering == nil {
w.Balance.Gathering = b.Gathering
}
if w.Balance.GatheringRules == nil {
w.Balance.GatheringRules = b.GatheringRules
}
w.dirty = true
}
if w.ResourceLayouts == nil {
w.ResourceLayouts = map[string]ResourceLayout{}
}
if err := w.Balance.Validate(); err != nil {
return err
}
@@ -140,6 +166,7 @@ func (w *World) Restore(now time.Time) error {
return errors.New("invalid world snapshot")
}
w.terrain = NewTerrain(w.Seed, w.Balance)
w.terrain.Version = w.Version
w.chunks = map[string]p.Chunk{}
w.now = now
w.PendingTitles = nil
@@ -150,6 +177,9 @@ func (w *World) Restore(now time.Time) error {
if err := w.restoreEquipment(c); err != nil {
return err
}
if err := w.restoreGathering(c); err != nil {
return err
}
if err := w.initializeStats(c); err != nil {
return err
}
@@ -249,6 +279,9 @@ func (w *World) Join(account, name string) (*Character, error) {
if err := w.restoreEquipment(c); err != nil {
return nil, err
}
if err := w.restoreGathering(c); err != nil {
return nil, err
}
if err := w.initializeStats(c); err != nil {
return nil, err
}
@@ -274,6 +307,9 @@ func (w *World) Import(c *Character) error {
if err := w.checkImportedEquipment(c); err != nil {
return err
}
if err := w.restoreGathering(c); err != nil {
return err
}
if err := w.initializeStats(c); err != nil {
return err
}
@@ -289,6 +325,8 @@ func (w *World) Import(c *Character) error {
c.View.ACK = 0
c.LastAttack = 0
c.LastGather = 0
c.GatherReadyAt = 0
c.JumpVelocity = 0
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
@@ -342,6 +380,12 @@ func (w *World) chunk(x, z int) p.Chunk {
return c
}
c := w.terrain.Chunk(x, z)
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.dirty = true
}
w.chunks[key] = c
return c
}
@@ -388,6 +432,10 @@ func (w *World) Intent(id string, i p.Intent) error {
c.MoveZ = i.Z / n
c.LastMove = w.now
return nil
case "jump":
return w.jump(c)
case "consume":
return w.consumeGathering(c, i.Target)
case "gather":
return w.gather(c, i.Target)
case "craft":
@@ -409,6 +457,7 @@ func (w *World) Intent(id string, i p.Intent) error {
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
return errors.New("keystone destination has been destroyed")
}
c.JumpVelocity = 0
c.View.Entity.Position = *c.ReturnPosition
c.ReturnPosition = nil
c.View.HasKeystone = false
@@ -420,39 +469,6 @@ func (w *World) Intent(id string, i p.Intent) error {
}
return nil
}
func (w *World) gather(c *Character, target string) error {
if w.Age()-c.LastGather < w.Balance.GatherCooldown {
return errors.New("gathering cooldown")
}
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
for _, chunk := range w.neighbors(c.View.Entity.Position) {
for _, r := range chunk.Resources {
if r.ID != target {
continue
}
if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind]
if item == "" {
return errors.New("not gatherable")
}
c.View.Inventory[item] += w.yieldAmount(c.View.Stats["gatherRate"].Final)
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
c.LastGather = w.Age()
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) craft(c *Character, name string) error {
r, ok := w.Balance.Recipes[name]
if !ok {
@@ -551,6 +567,8 @@ func (w *World) kill(c *Character, reason string) {
return
}
e := c.View.Entity
e.Position = w.terrain.Position(e.Position.X, e.Position.Z)
c.View.Entity.Position = e.Position
e.ID = "corpse:" + e.ID
e.Kind = "corpse"
e.State = "dead"
@@ -561,6 +579,7 @@ func (w *World) kill(c *Character, reason string) {
c.View.Equipment = map[string]string{}
c.View.CarryWeight = 0
c.View.Entity.HP = 0
c.JumpVelocity = 0
c.View.Entity.State = "dead"
c.MoveX = 0
c.MoveZ = 0
@@ -608,6 +627,7 @@ func (w *World) Control(op, target, value, reason string) error {
case "heal":
c.View.Entity.HP = c.View.Entity.MaxHP
case "unstuck":
c.JumpVelocity = 0
c.View.Entity.Position = w.terrain.Position(0, 0)
c.MoveX, c.MoveZ = 0, 0
case "retire":
@@ -638,6 +658,18 @@ func (w *World) Advance(now time.Time, dt float64) {
continue
}
w.resetDay(c)
nowSeconds := float64(w.now.UnixMilli()) / 1000
effects := c.View.GatheringEffects[:0]
for _, e := range c.View.GatheringEffects {
if e.ExpiresAt > nowSeconds {
effects = append(effects, e)
}
}
if len(effects) != len(c.View.GatheringEffects) {
c.View.GatheringEffects = effects
w.RefreshStats(c)
w.dirty = true
}
if c.Online {
midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds())
@@ -648,6 +680,7 @@ func (w *World) Advance(now time.Time, dt float64) {
c.ReturnPosition = &pos
c.Sheltered = true
c.View.HasKeystone = true
c.JumpVelocity = 0
c.View.Entity.Position = w.terrain.Position(0, 0)
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP))
c.Online = false
@@ -670,12 +703,7 @@ func (w *World) Advance(now time.Time, dt float64) {
c.MoveX = 0
c.MoveZ = 0
}
pos := c.View.Entity.Position
speed := w.playerSpeed(c)
nx, nz := pos.X+c.MoveX*speed*dt, pos.Z+c.MoveZ*speed*dt
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
c.View.Entity.Position = w.terrain.Position(nx, nz)
}
w.moveCharacter(c, dt)
for _, ch := range w.neighbors(c.View.Entity.Position) {
active[ch.Key] = true
w.ensureMob(ch)
@@ -804,14 +832,40 @@ func (w *World) updateMobs(active map[string]bool, dt float64) {
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{}}
s.GatherRisks = map[string]p.GatheringRisk{}
allowed := map[string]bool{}
for _, ch := range w.neighbors(c.View.Entity.Position) {
allowed[ch.Key] = true
s.ChunkKeys = append(s.ChunkKeys, ch.Key)
if !known[ch.Key] {
ch.Resources = append([]p.Entity{}, ch.Resources...)
for index := range ch.Resources {
e := &ch.Resources[index]
id := stringValue(e.ResourceID)
if id == "" {
id = e.Kind
}
if r := w.resource(id); r != nil {
e.ResourceID = stringPtr(r.ID)
e.SkillID = stringPtr(r.SkillID)
e.RequiredLevel = &r.RequiredLevel
e.Name = r.Name
}
}
s.Chunks = append(s.Chunks, ch)
}
for _, r := range ch.Resources {
if w.Depleted[r.ID] <= w.Age() {
id := stringValue(r.ResourceID)
if id == "" {
id = r.Kind
}
if def := w.resource(id); def != nil {
if _, ok := s.GatherRisks[def.ID]; !ok {
s.GatherRisks[def.ID] = w.gatherRisk(c, *def)
}
}
}
if w.Depleted[r.ID] > w.Age() {
s.UnavailableResources = append(s.UnavailableResources, r.ID)
}
+191 -58
View File
@@ -12,6 +12,7 @@ type Protocol struct {
type ContentCatalog struct {
EffectSets []EffectSet `json:"effectSets,omitempty"`
Gathering *GatheringContent `json:"gathering,omitempty"`
Items []ItemDefinition `json:"items"`
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
Stats ContentStatsRules `json:"stats"`
@@ -29,9 +30,58 @@ type EffectSet struct {
type StatModifier struct {
Flat float64 `json:"flat"`
Percent float64 `json:"percent"`
Skill *string `json:"skill,omitempty"`
Stat string `json:"stat"`
}
type GatheringContent struct {
Biomes []BiomeDefinition `json:"biomes"`
Consumables []GatheringConsumable `json:"consumables"`
Resources []ResourceDefinition `json:"resources"`
Skills []GatheringSkill `json:"skills"`
}
type BiomeDefinition struct {
Color string `json:"color"`
Description string `json:"description"`
ID string `json:"id"`
Name string `json:"name"`
Weight int64 `json:"weight"`
}
type GatheringConsumable struct {
Description string `json:"description"`
ID string `json:"id"`
Modifiers []StatModifier `json:"modifiers"`
Name string `json:"name"`
Seconds float64 `json:"seconds"`
}
type ResourceDefinition struct {
Amount int64 `json:"amount"`
Biomes []string `json:"biomes"`
Density int64 `json:"density"`
Description string `json:"description"`
ID string `json:"id"`
Model string `json:"model"`
Name string `json:"name"`
Output string `json:"output"`
RequiredLevel int64 `json:"requiredLevel"`
RespawnSeconds float64 `json:"respawnSeconds"`
Seconds float64 `json:"seconds"`
SkillID string `json:"skillId"`
XP int64 `json:"xp"`
}
type GatheringSkill struct {
BaseXP int64 `json:"baseXp"`
Description string `json:"description"`
ID string `json:"id"`
MaxLevel int64 `json:"maxLevel"`
Name string `json:"name"`
XPPerLevel int64 `json:"xpPerLevel"`
}
type ItemDefinition struct {
Description string `json:"description"`
DropChance float64 `json:"dropChance"`
@@ -83,17 +133,37 @@ type TitleEffects struct {
}
type ContentChange struct {
EffectSet *EffectSetDraft `json:"effectSet,omitempty"`
EffectSetIDS []string `json:"effectSetIds,omitempty"`
ExpectedVersion int64 `json:"expectedVersion"`
ID string `json:"id"`
Item *ItemDraft `json:"item,omitempty"`
Op string `json:"op"`
Reason string `json:"reason"`
RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"`
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
Stats *ContentStatsRules `json:"stats,omitempty"`
Title *TitleDraft `json:"title,omitempty"`
Biome *BiomeDefinitionDraft `json:"biome,omitempty"`
Consumable *GatheringConsumableDraft `json:"consumable,omitempty"`
EffectSet *EffectSetDraft `json:"effectSet,omitempty"`
EffectSetIDS []string `json:"effectSetIds,omitempty"`
ExpectedVersion int64 `json:"expectedVersion"`
GatheringSkill *GatheringSkillDraft `json:"gatheringSkill,omitempty"`
ID string `json:"id"`
Item *ItemDraft `json:"item,omitempty"`
Op string `json:"op"`
Reason string `json:"reason"`
RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"`
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
Resource *ResourceDefinitionDraft `json:"resource,omitempty"`
Stats *ContentStatsRules `json:"stats,omitempty"`
Title *TitleDraft `json:"title,omitempty"`
}
type BiomeDefinitionDraft struct {
Color string `json:"color"`
Description string `json:"description"`
ID *string `json:"id,omitempty"`
Name string `json:"name"`
Weight int64 `json:"weight"`
}
type GatheringConsumableDraft struct {
Description string `json:"description"`
ID *string `json:"id,omitempty"`
Modifiers []StatModifier `json:"modifiers"`
Name string `json:"name"`
Seconds float64 `json:"seconds"`
}
type EffectSetDraft struct {
@@ -103,6 +173,15 @@ type EffectSetDraft struct {
Name string `json:"name"`
}
type GatheringSkillDraft struct {
BaseXP int64 `json:"baseXp"`
Description string `json:"description"`
ID *string `json:"id,omitempty"`
MaxLevel int64 `json:"maxLevel"`
Name string `json:"name"`
XPPerLevel int64 `json:"xpPerLevel"`
}
type ItemDraft struct {
Description string `json:"description"`
DropChance float64 `json:"dropChance"`
@@ -121,6 +200,22 @@ type RequirementSetDraft struct {
Requirements []ContentRequirement `json:"requirements"`
}
type ResourceDefinitionDraft struct {
Amount int64 `json:"amount"`
Biomes []string `json:"biomes"`
Density int64 `json:"density"`
Description string `json:"description"`
ID *string `json:"id,omitempty"`
Model string `json:"model"`
Name string `json:"name"`
Output string `json:"output"`
RequiredLevel int64 `json:"requiredLevel"`
RespawnSeconds float64 `json:"respawnSeconds"`
Seconds float64 `json:"seconds"`
SkillID string `json:"skillId"`
XP int64 `json:"xp"`
}
type TitleDraft struct {
Description string `json:"description"`
Effects TitleEffects `json:"effects"`
@@ -151,20 +246,22 @@ type Intent struct {
}
type Snapshot struct {
ChunkKeys []string `json:"chunkKeys"`
Chunks []Chunk `json:"chunks"`
Entities []Entity `json:"entities"`
Message string `json:"message"`
Self Character `json:"self"`
Tick int64 `json:"tick"`
Type string `json:"type"`
UnavailableResources []string `json:"unavailableResources"`
Version int64 `json:"version"`
World WorldInfo `json:"world"`
ChunkKeys []string `json:"chunkKeys"`
Chunks []Chunk `json:"chunks"`
Entities []Entity `json:"entities"`
GatherRisks map[string]GatheringRisk `json:"gatherRisks,omitempty"`
Message string `json:"message"`
Self Character `json:"self"`
Tick int64 `json:"tick"`
Type string `json:"type"`
UnavailableResources []string `json:"unavailableResources"`
Version int64 `json:"version"`
World WorldInfo `json:"world"`
}
type Chunk struct {
Biome string `json:"biome"`
Color *string `json:"color,omitempty"`
Heights []float64 `json:"heights"`
Key string `json:"key"`
Resolution int64 `json:"resolution"`
@@ -175,13 +272,16 @@ 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"`
State string `json:"state"`
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"`
}
type Vec3 struct {
@@ -190,30 +290,70 @@ type Vec3 struct {
Z float64 `json:"z"`
}
type GatheringRisk struct {
Allowed bool `json:"allowed"`
Damage float64 `json:"damage"`
Destruction float64 `json:"destruction"`
Failure float64 `json:"failure"`
Negative float64 `json:"negative"`
Seconds float64 `json:"seconds"`
}
type Character struct {
ACK int64 `json:"ack"`
AllocatedStats map[string]int64 `json:"allocatedStats"`
CarryWeight float64 `json:"carryWeight"`
Entity Entity `json:"entity"`
Equipment map[string]string `json:"equipment"`
Experience int64 `json:"experience"`
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
HasKeystone bool `json:"hasKeystone"`
HealthChoices int64 `json:"healthChoices"`
Inventory map[string]int64 `json:"inventory"`
Items []ItemInstance `json:"items"`
Kills int64 `json:"kills"`
Level int64 `json:"level"`
Mana float64 `json:"mana"`
ManaChoices int64 `json:"manaChoices"`
PendingVitalChoices int64 `json:"pendingVitalChoices"`
PlayedSeconds float64 `json:"playedSeconds"`
RemainingSeconds float64 `json:"remainingSeconds"`
Skills map[string]int64 `json:"skills"`
Stamina float64 `json:"stamina"`
StatPoints int64 `json:"statPoints"`
Stats map[string]StatValue `json:"stats"`
Titles []TitleAward `json:"titles"`
ACK int64 `json:"ack"`
AllocatedStats map[string]int64 `json:"allocatedStats"`
CarryWeight float64 `json:"carryWeight"`
Consumables []GatheringConsumable `json:"consumables,omitempty"`
Entity Entity `json:"entity"`
Equipment map[string]string `json:"equipment"`
Experience int64 `json:"experience"`
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
GatherAttempt int64 `json:"gatherAttempt"`
Gathering map[string]SkillProgress `json:"gathering,omitempty"`
GatheringEffects []TimedGatheringEffect `json:"gatheringEffects,omitempty"`
HasKeystone bool `json:"hasKeystone"`
HealthChoices int64 `json:"healthChoices"`
Inventory map[string]int64 `json:"inventory"`
Items []ItemInstance `json:"items"`
Kills int64 `json:"kills"`
Level int64 `json:"level"`
Mana float64 `json:"mana"`
ManaChoices int64 `json:"manaChoices"`
PendingVitalChoices int64 `json:"pendingVitalChoices"`
PlayedSeconds float64 `json:"playedSeconds"`
RemainingSeconds float64 `json:"remainingSeconds"`
Skills map[string]int64 `json:"skills"`
StackNames map[string]string `json:"stackNames,omitempty"`
Stamina float64 `json:"stamina"`
StatPoints int64 `json:"statPoints"`
Stats map[string]StatValue `json:"stats"`
Titles []TitleAward `json:"titles"`
}
type SkillProgress struct {
EffectiveLevel int64 `json:"effectiveLevel"`
Experience StatValue `json:"experience"`
Level int64 `json:"level"`
LevelValue StatValue `json:"levelValue"`
Name string `json:"name"`
Speed StatValue `json:"speed"`
XP int64 `json:"xp"`
XPToNextLevel int64 `json:"xpToNextLevel"`
Yield StatValue `json:"yield"`
}
type StatValue struct {
Base float64 `json:"base"`
Final float64 `json:"final"`
Flat float64 `json:"flat"`
Percent float64 `json:"percent"`
}
type TimedGatheringEffect struct {
ExpiresAt float64 `json:"expiresAt"`
Modifiers []StatModifier `json:"modifiers"`
Name string `json:"name"`
Source string `json:"source"`
}
type ItemInstance struct {
@@ -229,13 +369,6 @@ type ItemInstance struct {
Weight float64 `json:"weight"`
}
type StatValue struct {
Base float64 `json:"base"`
Final float64 `json:"final"`
Flat float64 `json:"flat"`
Percent float64 `json:"percent"`
}
type TitleAward struct {
Description string `json:"description"`
EarnedAt string `json:"earnedAt"`
+22 -2
View File
@@ -17,6 +17,11 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
type CatalogChange struct {
GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"`
Resource *content.ResourceDefinition `json:"resource,omitempty"`
Biome *content.BiomeDefinition `json:"biome,omitempty"`
Consumable *content.GatheringConsumable `json:"consumable,omitempty"`
ID string `json:"id"`
ExpectedVersion int64 `json:"expectedVersion"`
Op string `json:"op"`
@@ -37,7 +42,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.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.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 {
@@ -94,6 +99,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
if catalog.Version != version {
return catalog, errors.New("catalog version mismatch")
}
if catalog.Gathering == nil {
b, err := content.Load()
if err != nil {
return catalog, err
}
catalog.Gathering = b.Gathering
}
return catalog, catalog.Validate()
}
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
@@ -123,12 +135,20 @@ func (c CatalogChange) validate() error {
}
valid := false
count := 0
for _, present := range []bool{c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
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} {
if present {
count++
}
}
switch c.Op {
case "create-gathering-skill":
valid = c.GatheringSkill != nil
case "create-resource":
valid = c.Resource != nil
case "create-biome":
valid = c.Biome != nil
case "create-consumable":
valid = c.Consumable != nil
case "create-title":
valid = c.Title != nil && c.Item == nil && c.Stats == nil
case "create-item":
+53
View File
@@ -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.GatheringSkill != nil {
resolved.GatheringSkill.ID = ""
}
if resolved.Resource != nil {
resolved.Resource.ID = ""
}
if resolved.Biome != nil {
resolved.Biome.ID = ""
}
if resolved.Consumable != nil {
resolved.Consumable.ID = ""
}
if resolved.Title != nil {
resolved.Title.ID = ""
}
@@ -64,7 +76,48 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
resolved.RequirementSetIDs = nil
resolved.EffectSetIDs = nil
target := "stats"
if c.Gathering == nil {
b, e := content.Load()
if e != nil {
return invalid(e)
}
c.Gathering = b.Gathering
}
gathering := *c.Gathering
c.Gathering = &gathering
switch change.Op {
case "create-gathering-skill":
v := *change.GatheringSkill
if v.ID == "" {
v.ID = "skill_" + game.ID()
}
resolved.GatheringSkill = &v
c.Gathering.Skills = append(slices.Clone(c.Gathering.Skills), v)
target = v.ID
case "create-resource":
v := *change.Resource
if v.ID == "" {
v.ID = "resource_" + game.ID()
}
resolved.Resource = &v
c.Gathering.Resources = append(slices.Clone(c.Gathering.Resources), v)
target = v.ID
case "create-biome":
v := *change.Biome
if v.ID == "" {
v.ID = "biome_" + game.ID()
}
resolved.Biome = &v
c.Gathering.Biomes = append(slices.Clone(c.Gathering.Biomes), v)
target = v.ID
case "create-consumable":
v := *change.Consumable
if v.ID == "" {
v.ID = "consumable_" + game.ID()
}
resolved.Consumable = &v
c.Gathering.Consumables = append(slices.Clone(c.Gathering.Consumables), v)
target = v.ID
case "create-title":
title := *change.Title
if title.ID == "" {
@@ -0,0 +1,54 @@
package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
"context"
"errors"
"path/filepath"
"testing"
)
func TestReusableGatheringCatalogPublication(t *testing.T) {
ctx := context.Background()
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "gathering.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
c, _ := db.Catalog(ctx)
publish := func(change CatalogChange) string {
t.Helper()
change.ID = game.ID()
change.ExpectedVersion = c.Version
change.Reason = "Gathering content test"
if _, err := db.PreviewCatalog(ctx, change); err != nil {
t.Fatal(err)
}
result, err := db.PublishCatalog(ctx, "admin", change)
if err != nil {
t.Fatal(err)
}
replay, err := db.PublishCatalog(ctx, "admin", change)
if err != nil || replay != result {
t.Fatal("publication replay changed identity", err)
}
c, err = db.Catalog(ctx)
if err != nil {
t.Fatal(err)
}
return result.ID
}
skill := publish(CatalogChange{Op: "create-gathering-skill", GatheringSkill: &content.GatheringSkill{Name: "Forager", BaseXP: 20, XPPerLevel: 10, MaxLevel: 1000}})
biome := publish(CatalogChange{Op: "create-biome", Biome: &content.BiomeDefinition{Name: "Wetlands", Color: "#445566", Weight: 1}})
publish(CatalogChange{Op: "create-resource", Resource: &content.ResourceDefinition{Name: "Reeds", SkillID: skill, Model: "herb", Output: "self", RequiredLevel: 2, Amount: 2, XP: 5, Seconds: 1, RespawnSeconds: 30, Density: 4, Biomes: []string{biome}}})
publish(CatalogChange{Op: "create-consumable", Consumable: &content.GatheringConsumable{Name: "Forager tonic", Seconds: 60, Modifiers: []content.StatModifier{{Stat: "gatheringLevel", Skill: skill, Flat: 5}}}})
bad := CatalogChange{ID: game.ID(), ExpectedVersion: c.Version, Reason: "Invalid skill scope", Op: "create-effect-set", EffectSet: &content.EffectSet{Name: "Bad scope", Modifiers: []content.StatModifier{{Stat: "gatheringXP", Skill: "missing", Percent: 50}}}}
if _, err := db.PublishCatalog(ctx, "admin", bad); !errors.Is(err, ErrCatalogInvalid) {
t.Fatal("unknown skill reference accepted", err)
}
after, _ := db.Catalog(ctx)
if after.Version != c.Version {
t.Fatal("invalid publication mutated version")
}
}
+1 -2
View File
@@ -153,11 +153,10 @@ func (h *HTTP) Handler() http.Handler {
mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) {
h.s.mu.Lock()
defer h.s.mu.Unlock()
t := game.NewTerrain(h.s.world.Seed, h.s.world.Balance)
chunks := []p.Chunk{}
for z := -1; z <= 1; z++ {
for x := -1; x <= 1; x++ {
chunks = append(chunks, t.Chunk(x, z))
chunks = append(chunks, h.s.world.PreviewChunk(x, z))
}
}
respond(w, 200, chunks)
+1 -1
View File
@@ -5,7 +5,7 @@ test('progression and signed permanent titles render in game, account, and admin
const errors: string[] = []; page.on('pageerror', error => errors.push(error.message));
const character: Character = {
entity: { id: 'progression-fixture', kind: 'player', name: 'Title bearer', state: 'alive', hp: 100, maxHp: 100, position: { x: 0, y: 0, z: 0 } },
inventory: { wood: 1 }, skills: { combat: 2 }, kills: 2, ack: 0, hasKeystone: false,
inventory: { wood: 1 }, skills: { combat: 2 }, kills: 2, ack: 0, gatherAttempt: 0, hasKeystone: false,
allocatedStats: {}, pendingVitalChoices: 1, healthChoices: 0, manaChoices: 0, mana: 50, stamina: 105, carryWeight: 3,
stats: { strength: { base: 2, flat: 2, percent: 50, final: 6 }, healthPoints: { base: 100, flat: 0, percent: 0, final: 100 }, manaPoints: { base: 50, flat: 0, percent: 0, final: 50 }, stamina: { base: 105, flat: 0, percent: 0, final: 105 }, carryCapacity: { base: 130, flat: 0, percent: 0, final: 130 } },
equipment: {}, items: [{ id: 'ring-fixture', definitionId: 'ring-trial', name: 'Trial Ring', description: 'An earned tool.', slot: 'ring', weight: 2, requirements: { level: 1, stats: {}, titles: [] }, modifiers: [{ stat: 'luck', flat: 2, percent: -5 }], equippable: true, requirementMessage: '' }],