1import * as THREE from '../vendor/three.module.js'; 2import * as api from './api.js'; 3import { createWorld } from './world.js'; 4import { createParty } from './party.js'; 5import { createCamera } from './camera.js'; 6import { createCombat } from './combat.js'; 7import { createUI } from './ui.js'; 8import { createSound } from './sound.js'; 9import { mat } from './props.js'; 10import { T } from './theme.js'; 11import { hurt } from './stats.js'; 12import { installDebug, track, tickFrame } from './debug.js'; 13import { loadFonts } from './text.js'; 14import { createSky } from './sky.js'; 15import { createRoute } from './route.js'; 16import { createLevelUp } from './levelup.js'; 17 18const canvas = document.getElementById('stage'); 19const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); 20renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); 21renderer.shadowMap.enabled = true; 22renderer.shadowMap.type = THREE.PCFSoftShadowMap; 23renderer.autoClear = false; 24renderer.info.autoReset = false; 25renderer.toneMapping = THREE.ACESFilmicToneMapping; 26renderer.toneMappingExposure = 1.25; 27 28const scene = new THREE.Scene(); 29const sky = createSky(scene); 30 31const sound = createSound(); 32const cam = createCamera(canvas); 33const party = createParty(scene); 34const marker = new THREE.Mesh(new THREE.TorusGeometry(0.54, 0.035, 4, 6).rotateZ(Math.PI / 6), mat(T.accent, { emissive: T.accent, emissiveIntensity: 0.6 })); 35marker.rotation.x = Math.PI / 2; 36marker.visible = false; 37scene.add(marker); 38const goal = marker.clone(); 39scene.add(goal); 40const route = createRoute(scene); 41 42let world = null; 43let state = null; 44let busy = false; 45let lastTile = ''; 46let dest = null; 47let hoverKey = ''; 48let hoverSeq = 0; 49 50const ui = createUI(renderer, canvas, { 51 onEquip: (unit, item) => mutate(() => api.equip(unit, item), 'click'), 52 onUnequip: (unit, item) => mutate(() => api.equip(unit, item, true), 'click'), 53 onPrepare: () => { 54 track.mode = 'prepare'; 55 ui.prepare(); 56 }, 57 onResume: () => { 58 track.mode = 'threat'; 59 ui.resume(); 60 }, 61 onDrink: (unit) => mutate(() => api.drink(unit), 'heal'), 62 onRest: () => makeCamp(), 63 onBuy: (id) => mutate(() => api.buy(id), 'coin'), 64 onSell: (id) => mutate(() => api.sell(id), 'coin'), 65 onFight: () => fight(), 66 onBack: () => backOff(), 67 onClick: () => sound.play('click'), 68 onMute: () => ui.toast(sound.toggle() ? 'Sound off' : 'Sound on'), 69 onHurry: () => combat.hurry(), 70 onHalt: () => halt(), 71 onFeedback: async (text) => { 72 state = await api.feedback(text); 73 ui.render(state); 74 ui.toast('Thanks. Your note is in, with this game\'s log.'); 75 }, 76}); 77const combat = createCombat(scene, party, cam, ui, sound); 78const levelUp = createLevelUp(party, cam, ui, sound); 79 80async function mutate(fn, cue) { 81 if (busy) return; 82 try { 83 state = await fn(); 84 ui.render(state); 85 sound.play(cue); 86 } catch (e) { 87 ui.toast(e.message); 88 } 89} 90 91function resize() { 92 renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); 93 renderer.setSize(innerWidth, innerHeight); 94 cam.resize(innerWidth, innerHeight); 95 ui.resize(innerWidth, innerHeight); 96} 97addEventListener('resize', resize); 98resize(); 99 100function load(s) { 101 state = s; 102 world?.dispose(); 103 world = createWorld(scene, s); 104 party.setUnits(s.party.units); 105 const p = world.worldPos(s.party.x, s.party.y); 106 party.place(p); 107 cam.snap(p); 108 lastTile = ''; 109 preview(null); 110 ui.clearLog(); 111 ui.render(s); 112 world.refresh(s); 113 sky.setClock(s.clock, true); 114 const sp = s.map.spawns[0]; 115 if (sp) ui.logLine(sp.hint, 'hint'); 116} 117 118function tileOf(p) { 119 return world.hexAt(p).join(','); 120} 121 122function ndc(e) { 123 return new THREE.Vector2((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1); 124} 125 126let down = null; 127canvas.addEventListener('pointerdown', (e) => { 128 sound.wake(); 129 if (e.button === 0) down = { x: e.clientX, y: e.clientY }; 130}); 131canvas.addEventListener('pointerup', (e) => { 132 if (e.button !== 0 || !down) return; 133 const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5; 134 down = null; 135 if (moved || !world) return; 136 if (track.mode === 'combat') return combat.hurry(); 137 if (track.mode !== 'explore' || (busy && !dest)) return; 138 const t = world.pick(ndc(e), cam.camera); 139 if (!t) return; 140 if (dest && t.x === state.party.x && t.y === state.party.y) return halt(); 141 go(t); 142}); 143addEventListener('keydown', () => sound.wake()); 144canvas.addEventListener('pointermove', (e) => { 145 if (!world || (busy && !dest) || track.mode !== 'explore' || ui.over(e.clientX, e.clientY)) { 146 marker.visible = false; 147 preview(null); 148 return; 149 } 150 const t = world.pick(ndc(e), cam.camera); 151 marker.visible = !!t && world.walkable(t.x, t.y); 152 preview(marker.visible ? t : null); 153 if (t) marker.position.copy(world.worldPos(t.x, t.y)).setY(world.worldPos(t.x, t.y).y + 0.06); 154}); 155 156async function preview(t) { 157 const key = t ? `${t.x},${t.y}` : ''; 158 if (key === hoverKey) return; 159 hoverKey = key; 160 const seq = ++hoverSeq; 161 if (!t) return route.clear(); 162 try { 163 const r = await api.path(t.x, t.y); 164 if (seq === hoverSeq) route.show(r, world.worldPos); 165 } catch { 166 if (seq === hoverSeq) route.clear(); 167 } 168} 169 170async function act(fn) { 171 busy = true; 172 track.busy = true; 173 marker.visible = false; 174 preview(null); 175 try { 176 await fn(); 177 } catch (e) { 178 ui.toast(e.message); 179 } finally { 180 busy = false; 181 track.busy = false; 182 } 183} 184 185function settle(next) { 186 levelUp.play(state, next); 187 party.sync(next.party.units); 188 state = next; 189 world.refresh(next); 190 ui.render(next); 191 for (const n of next.notes || []) { 192 ui.logLine(n, /hp|trap|fallen/.test(n) ? 'kill' : 'hint'); 193 ui.toast(n); 194 } 195 for (const it of next.found || []) { 196 ui.logLine(`Found ${it.name} (${it.rarity})`, 'reward'); 197 ui.toast(`Found ${it.name}`); 198 sound.play('loot'); 199 } 200} 201 202function aim(t) { 203 dest = t; 204 goal.visible = !!t; 205 if (t) goal.position.copy(world.worldPos(t.x, t.y)).setY(world.worldPos(t.x, t.y).y + 0.06); 206} 207 208function halt() { 209 if (dest) aim(null); 210} 211 212function go(t) { 213 if (!world.walkable(t.x, t.y)) return ui.toast('Impassable terrain'); 214 ui.closePanel(); 215 const walking = !!dest; 216 aim(t); 217 if (walking) return; 218 return act(async () => { 219 try { 220 while (dest && (state.party.x !== dest.x || state.party.y !== dest.y)) { 221 const next = await api.move(dest.x, dest.y, 1); 222 const stuck = !next.trail?.length; 223 sky.setClock(next.clock); 224 world.moveBands(next); 225 await party.walk(world.trail(next)); 226 settle(next); 227 if (next.threat) { 228 aim(null); 229 return showThreat(next.threat); 230 } 231 if (stuck || next.phase !== 'explore') break; 232 } 233 const s = state; 234 const sp = s.map.spawns.find((q) => q.x === s.party.x && q.y === s.party.y); 235 if (sp) ui.logLine(sp.hint, 'hint'); 236 if (s.shop) ui.logLine(`A trader works here. Press T to trade.`, 'hint'); 237 } finally { 238 aim(null); 239 } 240 }); 241} 242 243const BAND_KINDS = { roam: 'on the roam', guard: 'guarding a chest', mimic: 'a chest that bites' }; 244const target = (s, threat) => { 245 const poi = s.map.pois.find((p) => p.id === threat.poi); 246 if (poi) return poi; 247 const b = s.map.bands.find((q) => q.id === threat.band); 248 return { ...b, kind: BAND_KINDS[b.kind] }; 249}; 250 251function showThreat(threat) { 252 const poi = target(state, threat); 253 const faction = state.campaign.factions.find((f) => f.id === poi.faction); 254 track.mode = 'threat'; 255 sound.play('threat'); 256 cam.setFocus(world.worldPos(poi.x, poi.y), 13); 257 ui.showThreat({ threat, poi, faction, hurt: state.party.units.some(hurt) }); 258} 259 260function backOff() { 261 ui.hideThreat(); 262 cam.setFocus(null); 263 track.mode = 'explore'; 264 sound.play('click'); 265} 266 267function fight() { 268 const poiId = state.threat?.poi || state.threat?.band; 269 ui.hideThreat(); 270 cam.setFocus(null); 271 track.mode = 'explore'; 272 return act(async () => { 273 const before = state; 274 const next = await api.interact(poiId); 275 sky.setClock(next.clock); 276 const poi = target(next, { poi: next.map.pois.some((p) => p.id === poiId) && poiId, band: poiId }); 277 world.stage(true); 278 track.mode = 'combat'; 279 await combat.play(next, before, world.worldPos(poi.x, poi.y)); 280 world.stage(false); 281 if (next.phase !== 'defeat') await party.walk([world.worldPos(next.party.x, next.party.y)]); 282 track.mode = 'explore'; 283 const r = next.rewards; 284 if (r) { 285 ui.logLine(`Victory: +${r.xp} XP, +${r.gold} gold${r.items?.length ? ', ' + r.items.map((i) => i.name).join(', ') : ''}`, 'reward'); 286 sound.play('win'); 287 } 288 settle(next); 289 if (next.phase === 'defeat') sound.play('lose'); 290 if (next.phase === 'victory' || next.phase === 'defeat') endGame(next); 291 }); 292} 293 294async function restart(seed) { 295 history.replaceState(null, '', '/'); 296 const s = await api.newGame(seed); 297 load(s); 298 ui.show(false); 299 title(s); 300} 301 302async function share(run) { 303 const url = `${location.origin}/r/${run.game}`; 304 try { 305 await navigator.clipboard.writeText(url); 306 return true; 307 } catch { 308 return false; 309 } 310} 311 312function showRun(run, own) { 313 track.mode = 'end'; 314 cam.orbit(0.06); 315 ui.showEnd(run, { own, onShare: () => share(run), onSeed: () => restart(run.seed), onNew: () => restart() }); 316} 317 318function title(s) { 319 track.mode = 'title'; 320 cam.orbit(0.06); 321 ui.showTitle(s, { onStart: begin, onNew: restart }); 322} 323 324async function endGame(s) { 325 track.mode = 'end'; 326 history.replaceState(null, '', `/r/${s.game}`); 327 showRun(await api.run(s.game), true); 328} 329 330function begin() { 331 sound.wake(); 332 cam.orbit(0); 333 track.mode = 'explore'; 334 ui.show(true); 335 if (state.shop) ui.logLine(`A trader works here. Press T to trade.`, 'hint'); 336} 337 338function makeCamp() { 339 if (busy) return; 340 return act(async () => { 341 const next = await api.rest(); 342 ui.closePanel(); 343 track.mode = 'camp'; 344 world.showLabels(false); 345 sound.play('rest'); 346 party.gather(true); 347 ui.camp(state.clock.day); 348 await sky.camp(party.pos.clone()); 349 ui.camp(null); 350 party.gather(false); 351 world.showLabels(true); 352 track.mode = 'explore'; 353 settle(next); 354 ui.logLine(`The party rests by the fire. Day ${next.clock.day} begins.`, 'reward'); 355 }); 356} 357 358const clock = new THREE.Clock(); 359function frame() { 360 const raw = clock.getDelta(); 361 tickFrame(raw * 1000); 362 const dt = Math.min(raw, 0.1); 363 if (world) { 364 party.update(dt); 365 levelUp.update(dt); 366 world.update(clock.elapsedTime, sky.dark(), party.pos); 367 const key = tileOf(party.pos); 368 if (key !== lastTile) { 369 if (lastTile && party.moving()) sound.play('step'); 370 lastTile = key; 371 const [x, y] = key.split(',').map(Number); 372 world.reveal(x, y); 373 } 374 world.shelter(party.pos, cam.camera.position); 375 cam.follow(party.pos); 376 sky.update(dt, party.pos); 377 } 378 combat.update(dt); 379 ui.night(sky.night()); 380 cam.update(dt); 381 renderer.info.reset(); 382 renderer.clear(); 383 renderer.render(scene, cam.camera); 384 ui.tick(dt); 385 ui.draw(); 386 requestAnimationFrame(frame); 387} 388 389async function boot() { 390 await loadFonts(); 391 load(await api.getState()); 392 frame(); 393 installDebug({ getState: () => state, getWorld: () => world, cam, party, renderer }); 394 window.__game.setRects(ui.rects); 395 const link = location.pathname.match(/^\/r\/([0-9a-f]{16})$/); 396 if (link && link[1] !== state.game) { 397 try { 398 return showRun(await api.run(link[1]), false); 399 } catch { 400 history.replaceState(null, '', '/'); 401 } 402 } 403 if (state.phase === 'victory' || state.phase === 'defeat') return endGame(state); 404 history.replaceState(null, '', '/'); 405 title(state); 406} 407 408boot().catch((e) => { 409 console.error(e); 410 const fatal = document.getElementById('fatal'); 411 fatal.textContent = `Tiny Adventure failed to start: ${e.message}`; 412 fatal.hidden = false; 413});