Add biome revisions readable content and visible projectile outcomes

This commit is contained in:
dingo
2026-09-09 08:27:32 -04:00
parent 4a7979e32f
commit 70d08b0d32
24 changed files with 703 additions and 128 deletions
+1
View File
@@ -1,3 +1,4 @@
.catalog-editor{padding:20px;min-width:0}.catalog-heading,.catalog-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px}.catalog-heading h2{font-size:20px;margin-right:auto}.catalog-tabs button[aria-pressed=true]{background:#215944;color:white}.catalog-list{display:grid;gap:12px}.catalog-list>.button{justify-self:start}.catalog-definition{padding:14px;border:1px solid var(--line);border-radius:5px;min-width:0;overflow-wrap:anywhere;font-size:12px;line-height:1.7}.catalog-definition summary{cursor:pointer;font-size:13px;font-weight:600}.catalog-definition p{margin-top:10px}.catalog-form{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);max-width:900px}.catalog-form>h3{margin-bottom:12px}.catalog-form label{display:flex;flex-direction:column;gap:8px;font-size:12px;margin:14px 0;min-width:0}.catalog-form input,.catalog-form select,.catalog-form textarea{width:100%;min-width:0}.catalog-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 14px}.catalog-fields label:has(textarea){grid-column:1/-1}.catalog-repeatable,.catalog-title-choices{padding:14px;min-width:0;border:1px solid var(--line);margin:20px 0}.catalog-repeatable legend,.catalog-title-choices legend{font-size:13px;padding:0 8px}.catalog-row{display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--line);margin-bottom:12px}.catalog-row>.catalog-fields{flex:1}.catalog-row>.button{font-size:11px;padding:8px}.catalog-title-choices{max-height:260px;overflow:auto}.catalog-title-choices label{flex-direction:row-reverse;justify-content:flex-end;align-items:center}.catalog-title-choices input{width:18px;height:18px}.catalog-form footer{display:flex;justify-content:flex-end;gap:12px;margin-top:20px}.catalog-form>.muted{line-height:1.7}.catalog-form details{margin:14px 0}.catalog-form .error{margin-top:14px}.table-tools[hidden]{display:none}@media(max-width:720px){.control-sidebar nav{grid-template-columns:repeat(4,minmax(0,1fr))}.catalog-editor{padding:12px}.catalog-fields{grid-template-columns:1fr}.catalog-row{align-items:flex-end}.catalog-tabs{gap:6px}.catalog-tabs button{padding:9px;font-size:11px}}
.player-content{padding:0 0 20px;border-bottom:1px solid var(--line)}.player-content form{display:grid;gap:12px}.player-content label{display:flex;flex-direction:column;gap:7px;font-size:12px;min-width:0}.player-content input,.player-content select,.player-content textarea{width:100%;min-width:0;max-width:100%}.player-content .muted{font-size:12px;line-height:1.7}.player-content [hidden]{display:none}.player-content .button{justify-self:start}
.catalog-preview:not(:empty){margin:18px 0;padding:16px;border:1px solid var(--line);border-radius:5px;line-height:1.7;font-size:13px}.catalog-preview h4{margin-bottom:10px}.catalog-preview pre{overflow:auto;max-height:320px;font-size:12px}.catalog-form footer{flex-wrap:wrap}.catalog-form:focus{outline:none}
.catalog-facts{display:grid;grid-template-columns:minmax(120px,1fr) minmax(0,2fr);gap:8px 18px;margin:14px 0}.catalog-facts dt{color:var(--muted);font-weight:500}.catalog-facts dd{margin:0;min-width:0}.catalog-values{padding-left:18px;display:grid;gap:8px}.catalog-facts .catalog-facts{margin:0}.catalog-definition section{padding:12px 0;border-top:1px solid var(--line)}@media(max-width:600px){.catalog-facts{grid-template-columns:1fr;gap:4px}.catalog-facts dd{margin-bottom:10px}}
+43 -13
View File
@@ -15,7 +15,7 @@ function field(label:string,input:HTMLElement){const wrap=node('label',label);wr
function text(value='',max=80){const i=node('input');i.value=value;i.maxLength=max;i.required=true;return i;}
function number(value:number,min=0,max=1000000,step='any'){const i=text(String(value));i.type='number';i.min=String(min);i.max=String(max);i.step=step;return i;}
function select(keys:string[],value=''){const i=node('select');for(const key of keys)i.append(new Option(statLabel(key),key));i.value=keys.includes(value)?value:keys[0];return i;}
function identity(){const group=node('div','','catalog-fields'),name=text(),description=node('textarea');description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p','A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};}
function identity(initial?:{name:string;description:string}){const group=node('div','','catalog-fields'),name=text(initial?.name??''),description=node('textarea');description.value=initial?.description??'';description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p',initial?'This biome keeps its identity. Publishing creates its next revision.':'A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};}
function repeat<T>(title:string,addLabel:string,make:(value?:T)=>{node:HTMLElement;read:()=>T},initial:T[]=[],max=64){
const group=node('fieldset','','catalog-repeatable'),rows=node('div'),entries:{node:HTMLElement;read:()=>T}[]=[];group.append(node('legend',title),rows);
const add=button(addLabel,()=>append());group.append(add);
@@ -44,7 +44,7 @@ function form(title:string,op:string,payload:()=>object){
reason.required=true;reason.minLength=5;reason.maxLength=240;reason.rows=2;error.setAttribute('role','alert');
const focus=registerMenu(form,()=>{editing=false;refresh.disabled=saving;forms.replaceChildren();focus.dispose()});
const save=node('button','Publish changes','button');save.type='submit';const cancel=button('Cancel',()=>focus.close()),check=button('Preview changes',()=>void previewChanges());const footer=node('footer');footer.append(cancel,check,save);
form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Published definitions and sets cannot be edited or removed.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form);
form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Biome edits publish new revisions; other definitions remain immutable.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form);
const previous=document.activeElement;queueMicrotask(()=>{if(form.isConnected)focus.opened(previous)});
form.addEventListener('input',()=>preview.replaceChildren());form.addEventListener('change',()=>preview.replaceChildren());
fields.addEventListener('click',event=>{if((event.target as HTMLElement).closest('button'))preview.replaceChildren()});
@@ -64,13 +64,13 @@ function form(title:string,op:string,payload:()=>object){
function previewView(result:ContentPreview){
const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`));
const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn;
if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p','Permanent ID assigned on publication.','muted'));
if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p',r.targetId?`Revision ${r.biome?.revision} of the existing biome`:'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||r.attack||r.mob||r.loot||r.spawn)root.append(node('pre',JSON.stringify(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn,null,2)));
if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),node('pre',JSON.stringify(r.stats,null,2)));root.append(details);}
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.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;
}
function titleForm(){
@@ -124,9 +124,34 @@ 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){
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??[])];
const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v);
if(Array.isArray(value)) {
const list=node('ul','','catalog-values');
if(!value.length)list.append(node('li','None'));
for(const entry of value){const row=node('li');row.append(readableDefinition(entry,context));list.append(row)}return list;
}
if(value!==null && typeof value==='object') {
const labels:Record<string,string>={baseXp:'XP to level 2',xpPerLevel:'Additional XP per level',maxLevel:'Maximum level',skillId:'Gathering profession',requiredLevel:'Required level',amount:'Yield / quantity',seconds:'Duration / interval (seconds)',respawnSeconds:'Respawn (seconds)',density:'Nodes per chunk',biomes:'Biomes',resources:'Resources',color:'Terrain color',weight:'Relative weight',revision:'Revision',speed:'Speed (m/s)',dexteritySpeed:'Extra m/s per Dexterity',strengthSpeed:'Extra m/s per Strength',cooldown:'Cooldown (seconds)',stamina:'Stamina cost',range:'Range (m)',radius:'Radius (m)',duration:'Area duration (seconds)',interval:'Pulse interval (seconds)',attackId:'Attack profile',lootId:'Loot table',mobId:'Mob',hp:'Base health',xp:'XP reward',aggroRange:'Detection range (m)',leashRange:'Pursuit limit (m)',scalePerDay:'World-age scaling per day',minPlayerDistance:'Minimum spawn distance (m)',respawn:'Respawn (seconds)',chance:'Chance (%)',group:'Weighted group',item:'Item',stat:'Power stat',multiplier:'Power multiplier'};
const fields=node('dl','','catalog-facts');
const record=value as Record<string,unknown>;
for(const [key,raw] of Object.entries(record)) {
if(['id','name','description'].includes(key))continue;
let item=raw;
if(key==='resources'&&item==null&&typeof record.id==='string')item=(catalog.gathering?.resources??[]).filter(r=>r.biomes.includes(record.id as string)).map(r=>r.id);
if(key==='biomes'&&'skillId' in record&&record.id) item=(catalog.gathering?.biomes??[]).filter(b=>b.resources!=null?b.resources.includes(record.id as string):(raw as string[]).includes(b.id)).map(b=>b.id);
const term=node('dt',labels[key]??statLabel(key)),detail=node('dd');detail.append(readableDefinition(item,key));fields.append(term,detail);
}return fields;
}
if(value==null||value==='')return node('span',context==='group'?'Independent':'None');
if(typeof value==='string')return node('span',context==='color'?value:reference(value));
return node('span',typeof value==='boolean'?(value?'Yes':'No'):String(value));
}
function gatheringForm(kind:string,existing?:NonNullable<Catalog['gathering']>['biomes'][number]){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(),g=catalog.gathering;
const values=identity(existing),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)}}));
@@ -139,9 +164,12 @@ function gatheringForm(kind:string){
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'));
const color=text(existing?.color??'#426044',7);color.type='color';const weight=number(existing?.weight??3,1,100,'1');
const resources=node('fieldset','','catalog-title-choices');resources.append(node('legend','Resources in this biome'));
const selected=existing?.resources??(g?.resources??[]).filter(r=>existing&&r.biomes.includes(existing.id)).map(r=>r.id);
const checks=(g?.resources??[]).map(r=>{const input=node('input');input.type='checkbox';input.checked=selected.includes(r.id);resources.append(field(`${r.name} · ${statLabel(r.model)} · level ${r.requiredLevel}`,input));return{id:r.id,input}});
const fields=form(existing?`Edit ${existing.name} · publish revision ${(existing.revision??1)+1}`:'Create biome',existing?'update-biome':'create-biome',()=>({...existing?{targetId:existing.id}:{},biome:{...values.read(),color:color.value,weight:Number(weight.value),resources:checks.filter(c=>c.input.checked).map(c=>c.id)}}));
fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),resources,node('p','Reuse any existing resource. Published biome revisions affect unexplored chunks; explored layouts remain unchanged. Adding a new resource from the resource editor also versions its selected biomes.','muted'));
}else{
const seconds=number(120,1,86400),effects=modifiers();
const fields=form('Create gathering consumable','create-consumable',()=>{const mods=effects.read();if(!mods.length||mods.some(m=>!m.stat.startsWith('gathering')))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods}}});
@@ -152,7 +180,9 @@ 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);}
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));
if(section==='biomes') { const b=v as NonNullable<Catalog['gathering']>['biomes'][number]; d.append(node('p',`Current revision ${b.revision??1}`),button('Edit biome',()=>gatheringForm('biomes',b)));const history=node('details');history.append(node('summary','Previous revisions'));for(const old of g?.biomeHistory??[])if(old.id===b.id){const revision=node('section');revision.append(node('h4',`Revision ${old.revision}`),readableDefinition(old));history.append(revision)}d.append(history); }
list.append(d);}
}
function combatForm(kind:string){
@@ -160,7 +190,7 @@ function combatForm(kind:string){
const values=identity(),c=catalog.combat;
if(kind==='attacks'){
const delivery=select(['melee','projectile']),effect=select(['damage','heal']),stat=select(['meleeDamage','rangedDamage','magicDamage']);
const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Projectile speed (m/s)',35,1,100],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const;
const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Weapon base projectile speed (m/s)',35,1,100],['dexteritySpeed','Extra m/s per Dexterity point',.1,0,5],['strengthSpeed','Extra m/s per Strength point',.05,0,5],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const;
const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max)}));
const fields=form('Create attack profile','create-attack',()=>({attack:{...values.read(),delivery:delivery.value,effect:effect.value,stat:stat.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}}));
fields.append(values.node,field('Delivery',delivery),field('Effect',effect),field('Player stat to scale',stat),...inputs.map(v=>field(v.label,v.input)),node('p','Damage targets opponents; healing targets allies. Players currently target mobs and the Harbinger, while player healing targets living players. Projectiles fly toward the selected position and can miss. Areas remain fixed at impact. Damage is sampled at attack time.','muted'));
@@ -184,5 +214,5 @@ function combatList(){
const c=catalog.combat,entries=section==='attacks'?c?.attacks:section==='mobs'?c?.mobs:section==='loot'?c?.loot:c?.spawns;
const labels:Record<string,string>={attacks:'attack profile',mobs:'mob',loot:'loot table',spawns:'mob spawn rule'};
list.append(button(`Create ${labels[section]}`,()=>combatForm(section)));
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d)}
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));list.append(d)}
}
+54 -32
View File
@@ -27,20 +27,22 @@ export interface CombatContent {
}
export interface CombatAttack {
cooldown: number;
delivery: string;
description: string;
duration: number;
effect: string;
id: string;
interval: number;
multiplier: number;
name: string;
radius: number;
range: number;
speed: number;
stamina: number;
stat: string;
cooldown: number;
delivery: string;
description: string;
dexteritySpeed?: number;
duration: number;
effect: string;
id: string;
interval: number;
multiplier: number;
name: string;
radius: number;
range: number;
speed: number;
stamina: number;
stat: string;
strengthSpeed?: number;
}
export interface LootTable {
@@ -106,10 +108,11 @@ export interface StatModifier {
}
export interface GatheringContent {
biomes: BiomeDefinition[];
consumables: GatheringConsumable[];
resources: ResourceDefinition[];
skills: GatheringSkill[];
biomeHistory?: BiomeDefinition[];
biomes: BiomeDefinition[];
consumables: GatheringConsumable[];
resources: ResourceDefinition[];
skills: GatheringSkill[];
}
export interface BiomeDefinition {
@@ -117,6 +120,8 @@ export interface BiomeDefinition {
description: string;
id: string;
name: string;
resources?: string[] | null;
revision?: number;
weight: number;
}
@@ -223,24 +228,27 @@ export interface ContentChange {
resource?: ResourceDefinitionDraft;
spawn?: MobSpawnDraft;
stats?: ContentStatsRules;
targetId?: string;
title?: TitleDraft;
}
export interface CombatAttackDraft {
cooldown: number;
delivery: string;
description: string;
duration: number;
effect: string;
id?: string;
interval: number;
multiplier: number;
name: string;
radius: number;
range: number;
speed: number;
stamina: number;
stat: string;
cooldown: number;
delivery: string;
description: string;
dexteritySpeed?: number;
duration: number;
effect: string;
id?: string;
interval: number;
multiplier: number;
name: string;
radius: number;
range: number;
speed: number;
stamina: number;
stat: string;
strengthSpeed?: number;
}
export interface BiomeDefinitionDraft {
@@ -248,6 +256,8 @@ export interface BiomeDefinitionDraft {
description: string;
id?: string;
name: string;
resources?: string[] | null;
revision?: number;
weight: number;
}
@@ -385,6 +395,7 @@ export interface Snapshot {
entities: Entity[];
gatherRisks?: { [key: string]: GatheringRisk };
message: string;
projectileVisuals?: ProjectileVisual[];
self: Character;
tick: number;
type: string;
@@ -435,6 +446,17 @@ export interface GatheringRisk {
seconds: number;
}
export interface ProjectileVisual {
at: number;
destination: Vec3;
id: string;
outcome: string;
phase: string;
position: Vec3;
projectileId: string;
speed: number;
}
export interface Character {
ack: number;
allocatedStats: { [key: string]: number };
+58
View File
@@ -0,0 +1,58 @@
import * as T from 'three';
import type { ProjectileVisual } from './generated';
type Flight = { mesh:T.Mesh; start:T.Vector3; end:T.Vector3; speed:number; born:number; impact?:ProjectileVisual };
// Animation consumes server outcomes. It never decides whether a target was hit.
// Straight flight is isolated here so future curved/seeking paths can use the
// same launch/authoritative-impact lifecycle without changing combat ownership.
export class ProjectilePresentation {
private flights = new Map<string,Flight>();
private seen = new Map<string,number>();
private flashes: {mesh:T.Mesh; until:number}[] = [];
private geometry = new T.SphereGeometry(.28,8,6);
private shotMaterial = new T.MeshBasicMaterial({color:'#fff0ad'});
private hitMaterial = new T.MeshBasicMaterial({color:'#ff794f',wireframe:true});
private missMaterial = new T.MeshBasicMaterial({color:'#b9c6ce',wireframe:true});
constructor(private scene:T.Scene) {}
has(id:string) { return this.flights.has(id); }
receive(events:ProjectileVisual[]) {
const now=performance.now()/1000;
for(const event of events) {
if(this.seen.has(event.id))continue;
this.seen.set(event.id,now);
if(event.phase==='launch') {
if(this.flights.size>=512)continue;
const start=new T.Vector3(event.position.x,event.position.y,event.position.z),end=new T.Vector3(event.destination.x,event.destination.y,event.destination.z);
const mesh=new T.Mesh(this.geometry,this.shotMaterial);mesh.position.copy(start);this.scene.add(mesh);
this.flights.set(event.projectileId,{mesh,start,end,speed:event.speed,born:now});
} else {
const flight=this.flights.get(event.projectileId);
if(flight) { flight.end.set(event.position.x,event.position.y,event.position.z);flight.impact=event; }
else this.flash(event,now);
}
}
// Event IDs are monotonic per world, and the server retains only two seconds.
// Bound deduplication memory even for long sessions.
while(this.seen.size>4096)this.seen.delete(this.seen.keys().next().value!);
}
private flash(event:ProjectileVisual,now:number) {
if(event.outcome==='cancelled'||this.flashes.length>=256)return;
const mesh=new T.Mesh(this.geometry,event.outcome==='hit'?this.hitMaterial:this.missMaterial);
mesh.position.set(event.position.x,event.position.y,event.position.z);mesh.scale.setScalar(event.outcome==='hit'?4:2);
this.scene.add(mesh);this.flashes.push({mesh,until:now+.4});
}
update() {
const now=performance.now()/1000;
for(const [id,f] of this.flights) {
const duration=Math.max(.1,f.start.distanceTo(f.end)/Math.max(1,f.speed));
const t=Math.min(1,(now-f.born)/duration);
f.mesh.position.lerpVectors(f.start,f.end,t);
if(t>=1&&(f.impact||now-f.born>duration+2)) {
if(f.impact)this.flash(f.impact,now);
this.scene.remove(f.mesh);this.flights.delete(id);
}
}
this.flashes=this.flashes.filter(f=>{if(now<f.until)return true;this.scene.remove(f.mesh);return false});
}
}
+5 -1
View File
@@ -1,11 +1,13 @@
import * as T from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { ProjectilePresentation } from './projectile-presentation';
import type { Chunk, Entity, Snapshot, Vec3 } from './generated';
type Batch = { parts: T.InstancedMesh[]; entities: Entity[] };
export class WorldView {
readonly renderer: T.WebGLRenderer;
readonly scene = new T.Scene();
readonly projectiles = new ProjectilePresentation(this.scene);
readonly camera = new T.OrthographicCamera(-60, 60, 40, -40, 0.1, 1400);
readonly chunks = new Map<string, { data: Chunk; mesh: T.Mesh }>();
readonly batches = new Map<string, Batch>();
@@ -181,12 +183,13 @@ export class WorldView {
}
update(snapshot: Snapshot) {
this.snapshot = snapshot;
this.projectiles.receive(snapshot.projectileVisuals??[]);
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));
snapshot.entities = [...snapshot.entities, ...resources];
this.updateEntities(snapshot.entities);
this.updateEntities(snapshot.entities.filter(e=>e.kind!=='projectile'||!this.projectiles.has(e.id)));
const p = snapshot.self.entity.position;
this.aim.set(p.x, p.y, p.z);
if (!this.initialized || this.position.distanceTo(this.aim) > 20) { this.position.copy(this.aim); this.focus.copy(this.aim); this.initialized = true; }
@@ -212,6 +215,7 @@ export class WorldView {
start() {
this.renderer.setAnimationLoop(() => {
const dt = Math.min(this.clock.getDelta(), 0.05);
this.projectiles.update();
// Presentation interpolation follows server positions; it never changes authoritative movement.
this.position.lerp(this.aim, 1 - Math.exp(-14 * dt));
this.focus.lerp(this.position, 1 - Math.exp(-8 * dt));