Add persistent destructible world structures and building kits

This commit is contained in:
dingo
2026-09-09 22:46:06 -04:00
parent c2bef2a45f
commit e80064976a
36 changed files with 932 additions and 43 deletions
+13
View File
@@ -0,0 +1,13 @@
import type {BuildingContent, Character} from './generated';
import {api} from './portal-shared';
import {node} from './character-stats';
export function buildingPanel(character:()=>Character|undefined,start:(id:string,rotation:string,range:number)=>void,prefix:string){
const root=node('details'),summary=node('summary','Building'),list=node('div'),message=node('p');root.append(summary,node('p','Craft a structure kit, then choose a clear spot in the survival world. Placing consumes one kit. Structures can be destroyed by players and mobs.'),list,message);
root.addEventListener('toggle',()=>{if(root.open)void refresh()});
async function refresh(){try{const b=await api<BuildingContent>(prefix+'/api/building'),c=character();list.replaceChildren();
for(const d of b.definitions){const held=c?.inventory['kit_'+d.id]??0;if(!held)continue;const row=node('section'),rotation=node('select'),place=node('button','Choose placement');rotation.setAttribute('aria-label',d.name+' orientation');rotation.append(new Option('Width along east/west','0'),new Option('Width along north/south','1'));place.type='button';place.onclick=()=>start(d.id,rotation.value,b.range);row.append(node('h4',d.name+' · '+held+' kits'),node('p',`${d.width} × ${d.depth} × ${d.height}m · ${d.hp} health · ${d.profession} level ${d.level}`),rotation,place);list.append(row)}
message.textContent=list.children.length?'Click clear ground within '+b.range+'m after choosing placement. Esc cancels.':'No structure kits held. Craft one or ask an administrator for a playtest kit.';
}catch(e){message.textContent=(e as Error).message}}
return root;
}
+15 -5
View File
@@ -9,7 +9,7 @@ function craftPool(){return repeat<CraftStat>('Available crafted stats','Add pos
const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),min=number(value?.min??1,-1000000),max=number(value?.max??5,-1000000),weight=number(value?.weight??1,.01,1000),percent=node('input');percent.type='checkbox';percent.checked=value?.percent??false;
group.append(field('Stat',stat),field('Minimum roll',min),field('Maximum roll',max),field('Selection weight',weight),field('Percentage modifier',percent));
return {node:group,read:()=>({stat:stat.value,min:Number(min.value),max:Number(max.value),weight:Number(weight.value),percent:percent.checked})};},[],32);}
function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];}
function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),...(catalog.building?.definitions??[]).map(d=>({id:'kit_'+d.id,name:d.name+' kit'})),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];}
function recipeForm(initial?:CraftRecipe){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(initial),profession=contentChoice(catalog.crafting?.professions??[],initial?.profession),level=number(initial?.level??1,1,1000,'1'),xp=number(initial?.xp??20,1,1000000,'1');
@@ -41,7 +41,7 @@ const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','world
const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message');
const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms);
let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false;
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['buildings','Structures'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;}
function show(text:string){message.textContent=text;message.hidden=false;}
function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;}
@@ -104,7 +104,8 @@ function previewView(result:ContentPreview){
const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers));
if(r.item?.craftPool?.length)root.append(node('p',`${r.item.craftRolls??0} random stat rolls per crafted item`),readableDefinition(r.item.craftPool));
if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(readableDefinition(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn));
if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon));
if(r.building)root.append(readableDefinition(r.building));
if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon));
if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules));
if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),readableDefinition(r.stats));root.append(details);}
return root;
@@ -138,7 +139,8 @@ function statsForm(){
}
function render(){
version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren();
if(section==='powers'||section==='weapons'){powerList();
if(section==='buildings'){buildingList();
}else if(section==='powers'||section==='weapons'){powerList();
}else if(section.startsWith('craft-')){craftingList();
}else if(['attacks','mobs','loot','spawns'].includes(section)){combatList();
}else if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList();
@@ -166,7 +168,7 @@ function contentChoice(values:{id:string;name:string}[],initial?:string) {
}
function readableDefinition(value:unknown, context=''):HTMLElement {
const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])];
const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.building?.definitions??[]).map(d=>({id:'kit_'+d.id,name:d.name+' kit'})),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])];
const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v);
if(Array.isArray(value)) {
const list=node('ul','','catalog-values');
@@ -277,3 +279,11 @@ function powerForm(){
const fields=form('Create spell or ability','create-power',()=>{const r=stats.read(),pre=parents.read();if(new Set(r.map(v=>v.stat)).size!==r.length||new Set(pre.map(v=>v.id)).size!==pre.length)throw new Error('Requirements must not repeat.');return {power:{...values.read(),kind:kind.value,attackId:resurrection.checked?'':attack.value,targeting:resurrection.checked?'target':targeting.value,resurrection:resurrection.checked,weapon:kind.value==='ability'?weapon.value:'',weaponLevel:Number(weaponLevel.value),requirements:{level:Number(level.value),stats:Object.fromEntries(r.map(v=>[v.stat,v.minimum])),titles:checks.filter(v=>v.input.checked).map(v=>v.id)},parents:kind.value==='ability'?{}:Object.fromEntries(pre.map(v=>[v.id,v.rank])),book:kind.value==='spell'&&book.checked,mana:Number(mana.value),castSeconds:resurrection.checked?0:Number(cast.value),cooldown:Number(cooldown.value),basePower:Number(basePower.value),rankScaling:Number(scaling.value),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:kind.value==='ability'?1:Number(max.value)}}});
fields.append(values.node,field('Kind',kind),field('Combat effect profile',attack),field('Targeting',targeting),field('Corpse resurrection (instant, adjacent, consent required)',resurrection),field('Learn from a consumable spell book',book),field('Weapon type for ability',weapon),field('Weapon level required',weaponLevel),field('Character level required',level),stats.node,titles,parents.node,field('Base effect power',basePower),field('Mana cost',mana),field('Cast time (seconds)',cast),field('Cooldown (seconds)',cooldown),field('Power increase per rank (0.03 = 3%)',scaling),field('XP to rank 2',base),field('Additional XP per rank',per),field('Maximum spell rank',max),node('p','A spell without a book automatically unlocks from its predecessor requirements. Abilities require the matching equipped weapon. Existing learned powers retain their definition. Aura profiles require a melee delivery, radius, and duration.','muted'));
}
function buildingList(){
list.append(node('p','Publish a structure, then create a Builder recipe whose output is its kit. Placed structures keep their published dimensions and health.','muted'),button('Create structure',()=>{
if(editing||saving)return;const values=identity(),model=select(['wall','camp','fort']),width=number(4,.5,8),depth=number(1,.5,8),height=number(2,.5,6),hp=number(250,1,1000000),profession=contentChoice(catalog.crafting?.professions??[],'builder'),level=number(1,1,1000,'1');
const fields=form('Create structure','create-building',()=>({building:{...values.read(),model:model.value,width:Number(width.value),depth:Number(depth.value),height:Number(height.value),hp:Number(hp.value),profession:profession.value,level:Number(level.value)}}));
fields.append(values.node,field('Appearance preset',model),field('Width (m)',width),field('Depth (m)',depth),field('Height (m)',height),field('Health',hp),field('Placement profession',profession),field('Minimum profession level',level));
}));for(const d of catalog.building?.definitions??[]){const row=node('details','','catalog-definition');row.append(node('summary',d.name),readableDefinition(d));list.append(row)}
}
+39
View File
@@ -11,6 +11,7 @@ export interface Protocol {
}
export interface ContentCatalog {
building?: BuildingContent;
combat?: CombatContent;
crafting?: CraftingContent;
effectSets?: EffectSet[];
@@ -23,6 +24,27 @@ export interface ContentCatalog {
version: number;
}
export interface BuildingContent {
definitions: BuildingDefinition[];
maxSlope: number;
maxStructures: number;
protectedRadius: number;
range: number;
}
export interface BuildingDefinition {
depth: number;
description: string;
height: number;
hp: number;
id: string;
level: number;
model: string;
name: string;
profession: string;
width: number;
}
export interface CombatContent {
attacks: CombatAttack[];
loot: LootTable[];
@@ -300,6 +322,7 @@ export interface TitleEffects {
export interface ContentChange {
attack?: CombatAttackDraft;
biome?: BiomeDefinitionDraft;
building?: BuildingDraft;
consumable?: GatheringConsumableDraft;
craftMaterial?: CraftMaterialDraft;
craftProfession?: GatheringSkillDraft;
@@ -355,6 +378,19 @@ export interface BiomeDefinitionDraft {
weight: number;
}
export interface BuildingDraft {
depth: number;
description: string;
height: number;
hp: number;
id?: string;
level: number;
model: string;
name: string;
profession: string;
width: number;
}
export interface GatheringConsumableDraft {
description: string;
id?: string;
@@ -579,6 +615,8 @@ export interface Chunk {
}
export interface Entity {
depth?: number;
height?: number;
hp: number;
id: string;
kind: string;
@@ -591,6 +629,7 @@ export interface Entity {
resourceId?: string;
skillId?: string;
state: string;
width?: number;
}
export interface Vec3 {
+11 -6
View File
@@ -1,5 +1,6 @@
import './style.css';
import { showTravel } from './travel';
import { buildingPanel } from './building-panel';
import { craftingPanel } from './crafting-panel';
import { createPowerPanel, revivalPanel } from './power-panel';
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
@@ -51,6 +52,7 @@ const avoidUntil = new Map<string, number>();
let requestedClose = false;
let input: InputActions;
let powers:ReturnType<typeof createPowerPanel>;
let placement:{id:string;rotation:string;range:number}|undefined;
let view: WorldView;
const selectedWorld = new URLSearchParams(location.search).get('world');
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
@@ -69,14 +71,14 @@ function send(op: string, target = '', x = 0, z = 0, slot = '') {
}
function selection(entity?: Entity) {
view.selected = entity; visible('target', !!entity);
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} }
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'mob', 'player','structure'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} }
}
function action(op: string) {
if (!snapshot) return;
const now = Date.now();
const kinds = op === 'attack' ? (snapshot.self.attack?.effect==='heal'?['player']:['boss', 'sentinel','mob']) : ['tree', 'ore', 'herb', 'corpse'];
let target = view.selected;
if (!target || !kinds.includes(target.kind) || (avoidUntil.get(target.id) ?? 0) > now) {
if (!target || (!kinds.includes(target.kind)&&!(op==='attack'&&target.kind==='structure'&&snapshot.self.attack?.effect!=='heal')) || (avoidUntil.get(target.id) ?? 0) > now) {
const p = snapshot.self.entity.position;
target = [...snapshot.entities,...(snapshot.self.attack?.effect==='heal'?[snapshot.self.entity]:[])].filter(e => kinds.includes(e.kind) && (avoidUntil.get(e.id) ?? 0) <= now).sort((a, b) => Math.hypot(a.position.x - p.x, a.position.z - p.z) - Math.hypot(b.position.x - p.x, b.position.z - p.z))[0];
}
@@ -201,7 +203,7 @@ async function boot() {
else if(key==='inventory')$('inventory-toggle').click();
else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1);
else if(key==='cancel-cast')send('cancel-cast');
else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}}
else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse','structure'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}}
else if(key==='heal'||key==='return'||key==='jump')send(key);
});
view.start();
@@ -228,7 +230,7 @@ async function boot() {
if (walkTo) {
const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz);
const target = actionTarget;
const range = pendingAction ? pendingAction.op === 'attack' ? (snapshot.self.attack?.range??config.attackRange) + (target?.id === 'boss' ? 3 : -0.5) : config.gatherRange - 0.5 : 0.8;
const range = pendingAction ? pendingAction.op === 'attack' ? (snapshot.self.attack?.range??config.attackRange) + (target?.id === 'boss' ? 3 : target?.kind==='structure'?Math.max(target.width??0,target.depth??0)/2-.5:-0.5) : config.gatherRange - 0.5 : 0.8;
const reach = pendingAction?.op === 'attack' && target ? Math.hypot(distance, target.position.y-p.y) : distance;
if (reach <= range) {
if (!pendingAction) { walkTo = undefined; }
@@ -262,7 +264,7 @@ async function boot() {
}, 50);
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
config = loadedConfig;
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());$('recipes').after(buildingPanel(()=>snapshot?.self,(id,rotation,range)=>{placement={id,rotation,range};input.clear();walkTo=undefined;pendingAction=undefined;send('move');$('inventory-toggle').click();notice('Click clear ground to build. Esc cancels.');},worldPrefix));
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton);
travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});};
$<HTMLInputElement>('zoom').value = String(view.distance);
@@ -307,6 +309,7 @@ async function boot() {
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
window.addEventListener('keydown',e=>{if(e.code==='Escape'&&placement){placement=undefined;notice('Placement canceled.');}});
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); });
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } });
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
@@ -318,7 +321,9 @@ async function boot() {
view.canvas.addEventListener('pointerdown', event => {
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
const hit = view.pick(event.clientX, event.clientY);
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;}
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; }
});
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
+2 -1
View File
@@ -1,7 +1,7 @@
import { api, el, type RecordCharacter } from './portal-shared';
import { statLabel } from './character-stats';
type Catalog={powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]};
type Catalog={building?:{definitions:{id:string;name:string}[]};powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]};
export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){
const root=el('section','','player-content');root.append(el('h3','Manage items and titles'));
if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;}
@@ -18,6 +18,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()
const v=record.character.view;choice.replaceChildren();
switch(operation.value){
case 'grant-item':
for(const d of catalog.building?.definitions??[])choice.append(new Option(d.name+' kit','kit_'+d.id));
choice.append(new Option('Revival stone','revival_stone'));for(const p of catalog.powers?.powers??[])if(p.book)choice.append(new Option(p.name+' spell book','book_'+p.id));
for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id));
for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id));
+2 -1
View File
@@ -99,6 +99,7 @@ export class WorldView {
this.batches.set('player', peers);
const portalMesh = new T.InstancedMesh(new T.TorusGeometry(2,.22,8,40).translate(0,2.5,0),new T.MeshBasicMaterial({color:'#86ffe0'}),8);
portalMesh.count=0;portalMesh.userData.kind='portal';this.scene.add(portalMesh);this.batches.set('portal',{parts:[portalMesh],entities:[]});
const structureMesh=new T.InstancedMesh(new T.BoxGeometry(1,1,1).translate(0,.5,0),new T.MeshStandardMaterial({color:'#8c6744',roughness:1}),512);structureMesh.count=0;structureMesh.castShadow=true;structureMesh.receiveShadow=true;structureMesh.userData.kind='structure';this.scene.add(structureMesh);this.batches.set('structure',{parts:[structureMesh],entities:[]});
const corpseMesh = new T.InstancedMesh(new T.BoxGeometry(1.1, 0.45, 2.1), new T.MeshStandardMaterial({ color: '#77766d' }), 2048);
corpseMesh.count = 0; corpseMesh.userData.kind = 'corpse'; this.scene.add(corpseMesh);
this.batches.set('corpse', { parts: [corpseMesh], entities: [] });
@@ -177,7 +178,7 @@ export class WorldView {
const variation = e.id.split('').reduce((n, c) => n + c.charCodeAt(0), 0);
this.dummy.rotation.set(0, e.kind === 'tree' || e.kind === 'ore' ? variation : 0, 0);
const scale = e.kind === 'tree' ? 0.85 + (variation % 6) * 0.07 : 1;
this.dummy.scale.setScalar(e.kind==='area'?(e.radius??1):scale);if(e.kind==='area')this.dummy.rotation.x=-Math.PI/2; this.dummy.updateMatrix();
this.dummy.scale.setScalar(e.kind==='area'?(e.radius??1):scale);if(e.kind==='area')this.dummy.rotation.x=-Math.PI/2; if(e.kind==='structure')this.dummy.scale.set(e.width??1,e.height??1,e.depth??1);this.dummy.updateMatrix();
for (const mesh of batch.parts) mesh.setMatrixAt(i, this.dummy.matrix);
}
for (const mesh of batch.parts) { mesh.count = count; mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere(); }