Add walkable housing interiors and cross-hub visitors
This commit is contained in:
@@ -723,6 +723,7 @@ export interface Snapshot {
|
||||
chunks: Chunk[];
|
||||
entities: Entity[];
|
||||
gatherRisks?: { [key: string]: GatheringRisk };
|
||||
house?: HouseScene;
|
||||
message: string;
|
||||
projectileVisuals?: ProjectileVisual[];
|
||||
self: Character;
|
||||
@@ -754,6 +755,25 @@ export interface GatheringRisk {
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
export interface HouseScene {
|
||||
furniture: RoomFurniture[];
|
||||
id: string;
|
||||
name: string;
|
||||
people: Entity[];
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface RoomFurniture {
|
||||
container: boolean;
|
||||
depth: number;
|
||||
height: number;
|
||||
id: string;
|
||||
name: string;
|
||||
width: number;
|
||||
x: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface ProjectileVisual {
|
||||
at: number;
|
||||
destination: Vec3;
|
||||
@@ -786,6 +806,7 @@ export interface Character {
|
||||
hasKeystone: boolean;
|
||||
healthChoices: number;
|
||||
houseId?: string;
|
||||
housePosition?: Vec3;
|
||||
inventory: { [key: string]: number };
|
||||
items: ItemInstance[];
|
||||
kills: number;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as T from 'three';
|
||||
import type {Entity, HouseScene, Snapshot} from './generated';
|
||||
|
||||
/** Indoor presentation only. Positions and furniture geometry come from Go. */
|
||||
export class HouseView {
|
||||
readonly scene=new T.Scene();
|
||||
readonly camera=new T.OrthographicCamera(-10,10,10,-10,.1,100);
|
||||
private room=new T.Group();private actors=new Map<string,{root:T.Group;target:T.Vector3;dispose:()=>void}>();
|
||||
private signature='';private active=false;private size=12;private ray=new T.Raycaster();
|
||||
private disposables:(()=>void)[]=[];
|
||||
constructor(){this.scene.background=new T.Color('#172329');this.scene.add(new T.HemisphereLight('#fff5db','#4b3930',2));const sun=new T.DirectionalLight('#ffdfaa',3);sun.position.set(2,9,6);this.scene.add(sun,this.room)}
|
||||
private box(w:number,h:number,d:number,x:number,y:number,z:number,color:string,parent:T.Object3D=this.room){const geometry=new T.BoxGeometry(w,h,d),material=new T.MeshStandardMaterial({color,roughness:.85});const mesh=new T.Mesh(geometry,material);mesh.position.set(x,y,z);parent.add(mesh);this.disposables.push(()=>{geometry.dispose();material.dispose()});return mesh}
|
||||
update(snapshot:Snapshot,model?:T.Group){
|
||||
const house=snapshot.house;if(!house){if(this.active)this.clear();return}this.active=true;this.size=house.size;
|
||||
const signature=JSON.stringify([house.id,house.size,house.furniture]);if(this.signature!==signature){this.clear();this.active=true;this.signature=signature;this.build(house)}
|
||||
const entities=[...house.people.filter(p=>p.id!==snapshot.self.entity.id),{...snapshot.self.entity,position:snapshot.self.housePosition??{x:0,y:0,z:0}}];
|
||||
const ids=new Set(entities.map(p=>p.id));for(const [id,v] of this.actors)if(!ids.has(id)){this.scene.remove(v.root);v.dispose();this.actors.delete(id)}
|
||||
for(const e of entities){let actor=this.actors.get(e.id);if(!actor){const firstDisposable=this.disposables.length,root=new T.Group();if(model)root.add(model.clone(true));else{this.box(.55,1.25,.45,0,.8,0,e.id===snapshot.self.entity.id?'#bdd1ad':'#88a9c6',root);this.box(.4,.4,.4,0,1.65,0,'#d6b49a',root)}
|
||||
const canvas=document.createElement('canvas');canvas.width=256;canvas.height=48;const ctx=canvas.getContext('2d')!;ctx.fillStyle='#13201ee6';ctx.fillRect(0,0,256,48);ctx.fillStyle='#fff5df';ctx.textAlign='center';ctx.font='24px sans-serif';ctx.fillText(e.name,128,32,248);const texture=new T.CanvasTexture(canvas),material=new T.SpriteMaterial({map:texture,depthTest:false}),name=new T.Sprite(material);name.position.y=2.2;name.scale.set(2.5,.47,1);root.add(name);this.disposables.push(()=>{texture.dispose();material.dispose()});root.position.set(e.position.x,e.position.y,e.position.z);const cleanup=this.disposables.splice(firstDisposable);actor={root,target:root.position.clone(),dispose:()=>cleanup.forEach(f=>f())};this.actors.set(e.id,actor);this.scene.add(root)
|
||||
}actor.target.set(e.position.x,e.position.y,e.position.z)
|
||||
}
|
||||
}
|
||||
private build(h:HouseScene){
|
||||
this.box(h.size,.18,h.size,0,-.09,0,'#907451');this.box(h.size,2.8,.2,0,1.4,-h.size/2,'#bab297');this.box(.2,2.8,h.size,-h.size/2,1.4,0,'#9e9986');
|
||||
for(let x=-h.size/2;x<h.size/2;x+=1)this.box(.015,.006,h.size,x,.006,0,'#77613f');
|
||||
const door=this.box(1.5,2.3,.15,0,1.15,h.size/2,'#548f81');door.userData.entity={id:'house-exit',kind:'house-exit',name:'Return to hub',position:{x:0,y:0,z:h.size/2},hp:0,maxHp:0,state:'active'} satisfies Entity;
|
||||
for(const f of h.furniture){const group=new T.Group();this.room.add(group);group.position.set(f.x,0,f.z);group.userData.entity={id:f.id,kind:'furniture',name:f.name,position:{x:f.x,y:0,z:f.z},hp:0,maxHp:0,state:'active'} satisfies Entity;
|
||||
if(f.container){this.box(f.width,f.height,f.depth,0,f.height/2,0,'#805232',group);this.box(f.width+.03,.1,f.depth+.03,0,f.height-.05,0,'#b28851',group);this.box(.12,.22,.025,0,f.height*.65,f.depth/2+.02,'#e0c06e',group)}
|
||||
else{this.box(f.width,.12,f.depth,0,f.height-.06,0,'#b39362',group);for(const x of [-1,1])for(const z of [-1,1])this.box(.12,f.height-.12,.12,x*(f.width/2-.12),(f.height-.12)/2,z*(f.depth/2-.12),'#694a31',group)}
|
||||
}
|
||||
}
|
||||
render(renderer:T.WebGLRenderer,dt:number){
|
||||
const aspect=innerWidth/innerHeight,size=(this.size*.64+1)/Math.min(1,aspect);this.camera.left=-size*aspect;this.camera.right=size*aspect;this.camera.top=size;this.camera.bottom=-size;this.camera.position.set(0,this.size*1.15,this.size*1.05);this.camera.lookAt(0,.4,0);this.camera.updateProjectionMatrix();
|
||||
for(const a of this.actors.values()){const delta=a.target.clone().sub(a.root.position);if(delta.x*delta.x+delta.z*delta.z>.002)a.root.rotation.y=Math.atan2(-delta.x,-delta.z);a.root.position.lerp(a.target,1-Math.exp(-14*dt))}renderer.render(this.scene,this.camera);
|
||||
}
|
||||
pick(canvas:HTMLCanvasElement,x:number,y:number):{entity?:Entity;point?:T.Vector3}{const r=canvas.getBoundingClientRect();this.ray.setFromCamera(new T.Vector2((x-r.left)/r.width*2-1,-(y-r.top)/r.height*2+1),this.camera);for(const hit of this.ray.intersectObject(this.room,true)){let o:T.Object3D|null=hit.object;while(o){if(o.userData.entity)return{entity:o.userData.entity as Entity};o=o.parent}if(Math.abs(hit.point.y)<.02)return{point:hit.point}}return{}}
|
||||
clear(){for(const dispose of this.disposables)dispose();this.disposables=[];this.room.clear();for(const a of this.actors.values()){this.scene.remove(a.root);a.dispose()}this.actors.clear();this.signature='';this.active=false}
|
||||
}
|
||||
@@ -12,13 +12,15 @@ const number=(value:number,min:number,max:number)=>{const n=node('input');n.type
|
||||
type InventoryView=Pick<HouseInventory,'inventory'|'items'> & {stackNames?:Record<string,string>};
|
||||
function choices(v:InventoryView):[string,string][]{return [...v.items.map(i=>[i.id,i.name] as [string,string]),...Object.entries(v.inventory).filter(([,n])=>n>0).map(([id,n])=>[id,`${v.stackNames?.[id]??id} × ${n}`] as [string,string])];}
|
||||
|
||||
export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean){
|
||||
export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean,onEnter:()=>void){
|
||||
const root=node('section'),open=button('Housing & keys',()=>{dialog.showModal();menu.opened();void refresh(true)});
|
||||
const dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close',()=>void leave());
|
||||
const dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close controls',()=>dialog.close());
|
||||
const toolbar=node('div','','house-toolbar');toolbar.hidden=true;toolbar.append(button('House controls',()=>show()),button('Return to hub',()=>void leave()));
|
||||
const retry=button('Retry pending action',()=>{if(pending)void action(pending,true)});retry.hidden=true;
|
||||
status.setAttribute('role','status');root.append(open);dialog.append(title,close,status,retry,body);document.body.append(dialog);
|
||||
let pending:HouseRequest|undefined,state:HouseState|undefined,busy=false,loading=false,signature='',lastHouse='',selected='',latest:Character|undefined;
|
||||
const menu=registerMenu(dialog,()=>void leave());dialog.addEventListener('cancel',e=>{e.preventDefault();void leave()});
|
||||
const menu=registerMenu(dialog,()=>dialog.close());dialog.addEventListener('cancel',e=>{e.preventDefault();dialog.close()});
|
||||
function show(id=''){selected=id;if(!dialog.open)dialog.showModal();menu.opened();void refresh(true)}
|
||||
async function leave(){if(busy)return;if(character()?.houseId||state?.room)await action({op:'leave'});dialog.close();signature=''}
|
||||
async function action(r:Omit<HouseRequest,'requestId'>,retrying=false){
|
||||
if(busy)return;if(pending&&!retrying){status.textContent='Resolve the pending action before making another change.';return}busy=true;dialog.classList.add('housing-busy');status.textContent='Saving…';
|
||||
@@ -35,7 +37,7 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
|
||||
}
|
||||
function render(){
|
||||
const c=latest,s=state;if(!c||!s)return;body.replaceChildren();const h=s.room;
|
||||
title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Leave house':'Close';
|
||||
title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Walk around':'Close';
|
||||
const keys=node('section');keys.append(node('h3','Carried keys'),node('p','Destroying a key takes three seconds. Death, dropping the key, leaving the world, or disconnecting cancels the action.'));
|
||||
for(const key of c.items.filter(i=>i.houseId)){const row=node('p',key.name+' ');row.append(button('Destroy key',()=>void action({op:'destroy-key',item:key.id})));keys.append(row)}
|
||||
const progress=node('p');progress.dataset.keyProgress='';keys.append(progress,button('Cancel key destruction',()=>void action({op:'cancel-key'})));body.append(keys);
|
||||
@@ -46,7 +48,7 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
|
||||
}
|
||||
body.prepend(node('p','Private house room · click the floor to choose a position, or furniture to select it. No experience is earned here.'));
|
||||
const layout=node('div','','house-layout');layout.setAttribute('aria-label','House floor plan');
|
||||
const x=number(0,-h.size/2,h.size/2),z=number(0,-h.size/2,h.size/2);
|
||||
const x=number(h.furniture[selected]?.x??0,-h.size/2,h.size/2),z=number(h.furniture[selected]?.z??0,-h.size/2,h.size/2);
|
||||
layout.onclick=e=>{if(e.target!==layout)return;const b=layout.getBoundingClientRect();x.value=String(Math.round(((e.clientX-b.left)/b.width*h.size-h.size/2)*2)/2);z.value=String(Math.round(((e.clientY-b.top)/b.height*h.size-h.size/2)*2)/2)};
|
||||
const furniture=select([['','Choose furniture'],...Object.values(h.furniture).map(f=>[f.item.id,f.item.name] as [string,string])]);furniture.value=selected;
|
||||
const choose=(id:string)=>{selected=id;furniture.value=id;const f=h.furniture[id];if(f){x.value=String(f.x);z.value=String(f.z)}showStorage()};furniture.onchange=()=>choose(furniture.value);
|
||||
@@ -76,5 +78,5 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri
|
||||
}
|
||||
}
|
||||
setInterval(()=>{if(dialog.open&&!busy)void refresh();const a=character()?.destroyKey;const p=dialog.querySelector<HTMLElement>('[data-key-progress]');if(p)p.textContent=a?`Key destruction in progress · ${Math.max(0,a.finishesAt-Date.now()/1000).toFixed(1)}s remaining (server confirmed on completion)`:'No key destruction in progress.'},1000);
|
||||
return {root,update(c:Character){latest=c;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId&&!dialog.open){dialog.showModal();menu.opened()}if(dialog.open)void refresh(true)}}};
|
||||
return {root,toolbar,open:show,leave,update(c:Character){latest=c;toolbar.hidden=!c.houseId;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId){onEnter();dialog.close()}if(dialog.open)void refresh(true)}}};
|
||||
}
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
.house-layout{position:relative;width:min(100%,540px);aspect-ratio:1;margin:16px auto;background-color:#76664b;background-image:linear-gradient(#b2a48344 1px,transparent 1px),linear-gradient(90deg,#b2a48344 1px,transparent 1px);background-size:8.333% 8.333%;border:8px solid #403c36;cursor:crosshair}
|
||||
.housing-dialog .house-piece{position:absolute;transform:translate(-50%,-50%);margin:0;padding:1px;background:#b48b54;color:#171c1b;overflow:hidden;font-size:11px;border:2px solid #463421;border-radius:3px}
|
||||
.housing-dialog .house-piece:focus{outline:3px solid #b7e2bb}
|
||||
.house-toolbar{pointer-events:auto;position:absolute;top:90px;right:24px;display:flex;gap:8px;z-index:4}.house-toolbar[hidden]{display:none}.house-toolbar button{background:#21372eef;color:#f2ecd5;padding:10px;border:1px solid #a9b994;border-radius:5px}
|
||||
|
||||
@@ -32,6 +32,7 @@ export class InputActions {
|
||||
const focused=document.activeElement as HTMLElement|null,menu=focused?.closest('.panel,dialog,form');if(!menu)return;
|
||||
const options=[...menu.querySelectorAll<HTMLElement>('button:not([disabled]),input:not([disabled]),select:not([disabled]),summary,a[href]')].filter(e=>e.getClientRects().length>0);
|
||||
if(i===12||i===13){const at=options.indexOf(focused!);options[(at+(i===13?1:options.length-1)+options.length)%options.length]?.focus();return}
|
||||
if((i===14||i===15)&&focused instanceof HTMLInputElement&&focused.type==='number'){if(i===15)focused.stepUp();else focused.stepDown();focused.dispatchEvent(new Event('change',{bubbles:true}));return}
|
||||
if((i===14||i===15)&&focused instanceof HTMLSelectElement){focused.selectedIndex=Math.max(0,Math.min(focused.options.length-1,focused.selectedIndex+(i===15?1:-1)));focused.dispatchEvent(new Event('change',{bubbles:true}));return}
|
||||
if(i===0&&focused&&!['INPUT','SELECT'].includes(focused.tagName))focused.click();
|
||||
}
|
||||
|
||||
+7
-3
@@ -141,7 +141,7 @@ function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
$<HTMLDialogElement>('ending').show();
|
||||
}
|
||||
function inventory(c: Character) {
|
||||
housing?.update(c);
|
||||
|
||||
$('earned-titles').replaceChildren(permanentTitles(c.titles));
|
||||
const parent = $('inventory-items'), panel = characterPanel(c, send);
|
||||
if (panel.parentElement !== parent) parent.replaceChildren(panel);
|
||||
@@ -164,6 +164,7 @@ function minimap(s: Snapshot) {
|
||||
}
|
||||
function updateHUD(s: Snapshot) {
|
||||
const c = s.self, w = s.world;
|
||||
housing?.update(c);
|
||||
powers?.update(c);
|
||||
visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden);
|
||||
$('character-name').textContent = c.entity.name;
|
||||
@@ -194,6 +195,7 @@ function updateHUD(s: Snapshot) {
|
||||
visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger');
|
||||
visible('dev-boss',config.development&&w.kind!=='hub');
|
||||
$<HTMLButtonElement>('attack').disabled=w.kind==='hub'||w.phase==='won';$<HTMLButtonElement>('gather').disabled=w.kind==='hub'||w.phase==='won';
|
||||
if(c.houseId){$('phase-label').textContent=s.house?.name??'HOUSE';$('season-detail').textContent='WASD / stick to walk · Jump onto furniture · I for house controls';$('coordinates').textContent=`${c.housePosition?.x.toFixed(1)??0}, ${c.housePosition?.z.toFixed(1)??0}`;}
|
||||
selection(view.selected); minimap(s);
|
||||
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
|
||||
}
|
||||
@@ -202,6 +204,7 @@ async function boot() {
|
||||
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
|
||||
view = new WorldView($<HTMLCanvasElement>('world'));
|
||||
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
||||
if(snapshot?.self.houseId){if(key==='inventory'||key==='gather'){housing.open();return}if(key==='jump'){send('jump');return}return}
|
||||
if(key==='attack'||key==='gather')action(key);
|
||||
else if(key==='inventory')$('inventory-toggle').click();
|
||||
else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1);
|
||||
@@ -219,11 +222,11 @@ async function boot() {
|
||||
inputElapsed += dt;
|
||||
input.pollController();
|
||||
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
|
||||
if(snapshot.self.houseId){input.clear();walkTo=undefined;pendingAction=undefined;return}
|
||||
if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false;
|
||||
if(inputElapsed>=0.05){send('move');inputElapsed=0;}return;
|
||||
}
|
||||
if(snapshot.self.houseId){let {x,z}=input.movement;if(x||z)walkTo=undefined;const p=snapshot.self.housePosition;if(walkTo&&p){const dx=walkTo.x-p.x,dz=walkTo.z-p.z,n=Math.hypot(dx,dz);if(n>.25){x=dx/n;z=dz/n}else walkTo=undefined}if(inputElapsed>=.05){send('move','',x,z);inputElapsed=0}return}
|
||||
let {x,z} = input.movement;
|
||||
if (x || z) { walkTo = undefined; pendingAction = undefined; }
|
||||
const actionTarget = pendingAction?.target === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === pendingAction?.target);
|
||||
@@ -268,7 +271,7 @@ async function boot() {
|
||||
}, 50);
|
||||
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
|
||||
config = loadedConfig;
|
||||
housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub');$('recipes').after(housing.root);
|
||||
housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub',()=>{input.clear();walkTo=undefined;pendingAction=undefined;placement=undefined;visible('inventory',false);selection()});$('recipes').after(housing.root);$('hud').append(housing.toolbar);
|
||||
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;}});};
|
||||
@@ -326,6 +329,7 @@ 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(snapshot.self.houseId){if(hit.entity?.kind==='house-exit')void housing.leave();else if(hit.entity)housing.open(hit.entity.id);else if(hit.point)walkTo=hit.point;return}
|
||||
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'); }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as T from 'three';
|
||||
import {HouseView} from './house-view';
|
||||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||||
import { ProjectilePresentation } from './projectile-presentation';
|
||||
import type { Chunk, Entity, Snapshot, Vec3 } from './generated';
|
||||
@@ -7,6 +8,7 @@ type Batch = { parts: T.InstancedMesh[]; entities: Entity[] };
|
||||
export class WorldView {
|
||||
readonly renderer: T.WebGLRenderer;
|
||||
readonly scene = new T.Scene();
|
||||
readonly houseView=new HouseView();
|
||||
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 }>();
|
||||
@@ -186,6 +188,7 @@ export class WorldView {
|
||||
}
|
||||
update(snapshot: Snapshot) {
|
||||
this.snapshot = snapshot;
|
||||
this.houseView.update(snapshot,this.models.get('player'));
|
||||
this.projectiles.receive(snapshot.projectileVisuals??[]);
|
||||
if (!this.initialized) this.addChunks([], []);
|
||||
this.addChunks(snapshot.chunks, snapshot.chunkKeys);
|
||||
@@ -204,6 +207,7 @@ export class WorldView {
|
||||
if (this.selected) this.selected = this.selected.id === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === this.selected!.id);
|
||||
}
|
||||
pick(clientX: number, clientY: number): { entity?: Entity; point?: T.Vector3 } {
|
||||
if(this.snapshot?.house)return this.houseView.pick(this.canvas,clientX,clientY);
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
this.ray.setFromCamera(new T.Vector2((clientX - rect.left) / rect.width * 2 - 1, -(clientY - rect.top) / rect.height * 2 + 1), this.camera);
|
||||
const objects: T.Object3D[] = [];
|
||||
@@ -218,6 +222,7 @@ export class WorldView {
|
||||
start() {
|
||||
this.renderer.setAnimationLoop(() => {
|
||||
const dt = Math.min(this.clock.getDelta(), 0.05);
|
||||
if(this.snapshot?.house){this.houseView.render(this.renderer,dt);this.frames++;return}
|
||||
this.projectiles.update();
|
||||
// Presentation interpolation follows server positions; it never changes authoritative movement.
|
||||
this.position.lerp(this.aim, 1 - Math.exp(-14 * dt));
|
||||
|
||||
Reference in New Issue
Block a user