tiny-adventure / commits / ed75ac1
Add Three.js game client
Tabletop diorama renderer with fog of war, click-to-move, combat replay with damage numbers, HUD with portraits and abilities, inventory and journal panels, title and end screens. three.js vendored under web/vendor. Co-Authored-By: Claude Sonnet 5.5
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -0,0 +1,82 @@
1+:root { --gold: #d9b23a; --ink: #2b1b0c; --metal: #3a3530; --parch: url(/assets/ui_parchment.png); }
2+* { box-sizing: border-box; }
3+html, body { margin: 0; height: 100%; overflow: hidden; background: #150e08; font-family: Georgia, 'Palatino Linotype', serif; color: #f4e6c0; user-select: none; }
4+#stage { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }
5+[hidden] { display: none !important; }
6+button { font: inherit; cursor: pointer; color: #f4e6c0; background: linear-gradient(#5a524a, #2e2a26); border: 2px solid #1a1612; outline: 1px solid #8a7a5a; border-radius: 3px; padding: 6px 12px; }
7+button:hover { background: linear-gradient(#6e645a, #3a342e); }
8+kbd { margin-left: 6px; color: var(--gold); font-size: 11px; }
9+.metal { background: linear-gradient(#4a443e, #26221e); border: 2px solid #14110e; box-shadow: inset 0 0 0 1px #8a7a5a, 0 4px 14px #000a; }
10+
11+#topbar { position: fixed; top: 8px; left: 50%; transform: translateX(-50%); display: flex; gap: 18px; align-items: center; padding: 5px 18px; background: linear-gradient(#4a443e, #26221e); border: 2px solid #14110e; box-shadow: inset 0 0 0 1px #8a7a5a; border-radius: 4px; font-size: 14px; }
12+#objective::before { content: '❖ '; color: var(--gold); }
13+#gold { color: var(--gold); }
14+
15+#log { position: fixed; left: 8px; bottom: 124px; width: 330px; max-height: 190px; overflow-y: auto; padding: 6px 10px; font-size: 12.5px; line-height: 1.35; background: #1a1410cc; border: 1px solid #8a7a5a; border-radius: 3px; scrollbar-width: thin; }
16+#log p { margin: 2px 0; }
17+#log .head { color: var(--gold); font-weight: bold; }
18+#log .crit { color: #ffd04a; }
19+#log .kill { color: #ff7a5a; }
20+#log .reward { color: #8fe08a; }
21+#log .hint { color: #b8c8e8; font-style: italic; }
22+
23+#bottom { position: fixed; left: 0; right: 0; bottom: 0; height: 116px; display: flex; align-items: center; gap: 22px; padding: 8px 18px; background: linear-gradient(#3a342e, #1c1814); border-top: 3px solid #0e0c0a; box-shadow: inset 0 2px 0 #8a7a5a; }
24+#portraits { display: flex; gap: 8px; }
25+.portrait { width: 118px; padding: 5px; background: var(--parch) center/175% auto; color: var(--ink); border: 2px solid #14110e; outline: 1px solid #8a7a5a; border-radius: 3px; cursor: pointer; position: relative; }
26+.portrait.sel { outline: 2px solid var(--gold); }
27+.portrait.dead { filter: grayscale(1) brightness(0.6); }
28+.face { float: left; width: 38px; height: 38px; margin-right: 6px; border: 2px solid #14110e; border-radius: 50%; display: grid; place-items: center; font-weight: bold; font-size: 20px; color: #fff; position: relative; text-shadow: 0 1px 2px #000; }
29+.face b { position: absolute; right: -6px; bottom: -6px; font-size: 11px; background: #14110e; border-radius: 8px; padding: 0 4px; color: var(--gold); }
30+.c-fighter { background: #b8392e; } .c-rogue { background: #3f8a4a; } .c-mage { background: #3f62c8; } .c-cleric { background: #a89a60; }
31+.pname { font-size: 12px; font-weight: bold; line-height: 38px; height: 38px; overflow: hidden; white-space: nowrap; }
32+.bar { height: 12px; margin-top: 4px; background: #1a1010; border: 1px solid #14110e; position: relative; clear: both; }
33+.bar span { display: block; height: 100%; transition: width 0.25s; }
34+.bar.hp span { background: linear-gradient(#e0483a, #8a1c14); }
35+.bar.xp { height: 6px; } .bar.xp span { background: linear-gradient(#6ab0ff, #2a5ab0); }
36+.bar em { position: absolute; inset: 0; font-style: normal; font-size: 10px; line-height: 10px; text-align: center; color: #fff; text-shadow: 0 1px 1px #000; }
37+
38+#abilities { display: flex; gap: 6px; padding: 8px; background: #14110e; border: 2px solid #0a0806; outline: 1px solid #8a7a5a; border-radius: 3px; min-width: 150px; min-height: 76px; }
39+.ability { width: 56px; height: 56px; position: relative; border: 2px solid #8a7a5a; background: #222; }
40+.icon { display: block; width: 100%; height: 100%; background-size: 400% 400%; image-rendering: auto; }
41+.ability .key { position: absolute; left: 2px; top: 0; font-size: 10px; color: var(--gold); text-shadow: 0 0 3px #000; }
42+.ability .aname { position: absolute; left: 0; right: 0; bottom: -17px; text-align: center; font-size: 10px; white-space: nowrap; color: #f4e6c0; }
43+#menu { margin-left: auto; display: flex; flex-direction: column; gap: 6px; }
44+
45+.panel { position: fixed; top: 54px; bottom: 132px; width: 380px; padding: 14px 16px; overflow-y: auto; background: var(--parch) center/175% auto; color: var(--ink); border: 4px solid #2a2218; outline: 2px solid #8a7a5a; box-shadow: 0 8px 30px #000a; font-size: 13px; }
46+#panel-inv { right: 12px; } #panel-journal { left: 12px; width: 420px; }
47+.panel h2 { margin: 0 0 8px; font-size: 20px; border-bottom: 2px solid #6a4a2a; }
48+.panel h3, .panel h4 { margin: 8px 0 4px; } .panel .close { position: absolute; top: 8px; right: 10px; padding: 0 8px; }
49+.panel li.done { text-decoration: line-through; opacity: 0.6; }
50+.panel ol, .panel ul { padding-left: 22px; margin: 4px 0; } .panel li { list-style: none; margin: 3px 0; margin-left: -18px; }
51+.hint { margin: 4px 0; font-size: 12px; } .seed { opacity: 0.6; font-size: 11px; }
52+.tabs { display: flex; gap: 4px; flex-wrap: wrap; } .tabs button { padding: 2px 8px; font-size: 12px; } .tabs .on { outline-color: var(--gold); }
53+.hero { margin: 8px 0 4px; font-weight: bold; text-transform: capitalize; }
54+.slots { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
55+.slot, .cell { display: flex; align-items: center; gap: 6px; padding: 4px; background: #00000022; border: 1px solid #6a4a2a; cursor: pointer; font-size: 12px; text-transform: capitalize; }
56+.slot .icon, .cell .icon { width: 38px; height: 38px; flex: none; border: 1px solid #14110e; background-color: #222; }
57+.slot .ghost { opacity: 0.25; }
58+.slot:not(.filled) { cursor: default; }
59+.slot span, .cell span { background: #1a1410; padding: 1px 5px; border-radius: 2px; }
60+.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
61+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; margin-top: 8px; } .stats span { display: flex; justify-content: space-between; padding: 2px 6px; background: #00000018; } .empty { opacity: 0.6; }
62+
63+#floaters { position: fixed; inset: 0; pointer-events: none; overflow: hidden; }
64+.floater { position: absolute; transform: translate(-50%, -50%); font-size: 26px; font-weight: bold; text-shadow: 0 2px 3px #000, 0 0 6px #000; animation: rise 1.2s ease-out forwards; }
65+.floater.dmg { color: #fff; } .floater.hurt { color: #ff6a5a; } .floater.heal { color: #6aff8a; } .floater.crit { color: #ffd04a; font-size: 38px; }
66+@keyframes rise { from { opacity: 1; margin-top: 0; } to { opacity: 0; margin-top: -70px; } }
67+#toast { position: fixed; top: 60px; left: 50%; transform: translateX(-50%); padding: 8px 18px; background: #1a1410ee; border: 1px solid var(--gold); border-radius: 3px; opacity: 0; transition: opacity 0.3s; pointer-events: none; }
68+#toast.show { opacity: 1; }
69+#combat-banner { position: fixed; top: 90px; left: 50%; transform: translateX(-50%); font-size: 30px; letter-spacing: 6px; color: #ff6a4a; text-shadow: 0 2px 6px #000; opacity: 0; transition: opacity 0.4s; pointer-events: none; }
70+body.combat #combat-banner { opacity: 1; }
71+
72+#screen { position: fixed; inset: 0; display: grid; place-items: center; background: radial-gradient(#0000 20%, #000c); }
73+#screen.title { background: radial-gradient(#0000 35%, #000a); }
74+#screen.end { background: #000b; }
75+.card { width: 520px; padding: 28px 34px; text-align: center; background: var(--parch) center/175% auto; color: var(--ink); border: 5px solid #2a2218; outline: 2px solid #8a7a5a; box-shadow: 0 10px 50px #000; }
76+.card h1 { margin: 0; font-size: 44px; letter-spacing: 2px; text-shadow: 1px 1px 0 #d9b23a66; }
77+.card h2 { margin: 14px 0 4px; font-size: 22px; }
78+.sub { margin: 4px 0; font-style: italic; } .meta, .party, .help { margin: 6px 0; font-size: 13px; } .help { opacity: 0.7; font-size: 11px; }
79+.row { display: flex; gap: 12px; justify-content: center; margin: 16px 0 8px; }
80+.card button { font-size: 18px; padding: 10px 22px; }
81+.card .alt { font-size: 14px; }
82+.card table { margin: 14px auto; border-collapse: collapse; width: 80%; font-size: 16px; } .card td { padding: 4px 8px; border-bottom: 1px dotted #6a4a2a; } .card td + td { text-align: right; font-weight: bold; }
@@ -0,0 +1,29 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+<meta charset="utf-8">
5+<title>Tiny Adventure</title>
6+<meta name="viewport" content="width=device-width, initial-scale=1">
7+<link rel="icon" href="data:,">
8+<link rel="stylesheet" href="/css/style.css">
9+</head>
10+<body>
11+<canvas id="stage"></canvas>
12+<div id="hud" hidden>
13+ <div id="topbar"><span id="objective"></span><span id="gold"></span></div>
14+ <div id="log"></div>
15+ <div id="floaters"></div>
16+ <div id="toast"></div>
17+ <div id="combat-banner">⚔ COMBAT ⚔</div>
18+ <div id="bottom">
19+ <div id="portraits"></div>
20+ <div id="abilities"></div>
21+ <div id="menu"><button id="btn-inv" title="Inventory (I)">Inventory<kbd>I</kbd></button><button id="btn-journal" title="Journal (J)">Journal<kbd>J</kbd></button></div>
22+ </div>
23+ <section id="panel-inv" class="panel" hidden><h2>Inventory</h2><button class="close">×</button><div id="inv-body"></div></section>
24+ <section id="panel-journal" class="panel" hidden><h2>Quest Journal</h2><button class="close">×</button><div id="journal-body"></div></section>
25+</div>
26+<div id="screen"></div>
27+<script type="module" src="/js/main.js"></script>
28+</body>
29+</html>
@@ -0,0 +1,32 @@
1+async function call(method, url, body) {
2+ const res = await fetch(url, {
3+ method,
4+ headers: { 'Content-Type': 'application/json', 'X-Player': 'local' },
5+ body: body ? JSON.stringify(body) : undefined,
6+ });
7+ const data = await res.json();
8+ if (!res.ok) throw new Error(data.error || res.statusText);
9+ return data.campaign ? normalize(data) : data;
10+}
11+
12+function normalize(s) {
13+ const arr = (o, k) => (o[k] ||= []);
14+ arr(s, 'log');
15+ arr(s.party, 'inventory');
16+ arr(s.campaign, 'sideQuests');
17+ arr(s.campaign, 'factions');
18+ arr(s.campaign, 'systems');
19+ ['pois', 'spawns', 'loot'].forEach((k) => arr(s.map, k));
20+ s.party.units.forEach((u) => (u.gear ||= {}));
21+ s.encounter?.enemies.forEach((e) => arr(e, 'abilities'));
22+ if (s.rewards) arr(s.rewards, 'items');
23+ return s;
24+}
25+
26+export const getState = () => call('GET', '/api/state');
27+export const newGame = (seed) => call('POST', '/api/new', seed ? { seed } : {});
28+export const move = (x, y) => call('POST', '/api/move', { x, y });
29+export const interact = (id) => call('POST', '/api/interact', { id });
30+export const equip = (unit, item, unequip = false) => call('POST', '/api/equip', { unit, item, unequip });
31+export const setAbility = (unit, ability, slot) => call('POST', '/api/ability', { unit, ability, slot });
32+export const getSeed = () => call('GET', '/api/seed');
@@ -0,0 +1,65 @@
1+import * as THREE from '../vendor/three.module.js';
2+
3+export function createCamera(canvas) {
4+ const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 400);
5+ const target = new THREE.Vector3();
6+ const goal = new THREE.Vector3();
7+ let yaw = 0.35;
8+ let pitch = 0.95;
9+ let dist = 17;
10+ let goalDist = 17;
11+ let focus = null;
12+ let drag = null;
13+
14+ canvas.addEventListener('contextmenu', (e) => e.preventDefault());
15+ canvas.addEventListener('wheel', (e) => {
16+ goalDist = THREE.MathUtils.clamp(goalDist * (e.deltaY > 0 ? 1.1 : 0.9), 6, 34);
17+ e.preventDefault();
18+ }, { passive: false });
19+ canvas.addEventListener('pointerdown', (e) => {
20+ if (e.button !== 0) drag = { x: e.clientX, y: e.clientY };
21+ });
22+ addEventListener('pointermove', (e) => {
23+ if (!drag) return;
24+ yaw -= (e.clientX - drag.x) * 0.006;
25+ pitch = THREE.MathUtils.clamp(pitch + (e.clientY - drag.y) * 0.004, 0.35, 1.3);
26+ drag = { x: e.clientX, y: e.clientY };
27+ });
28+ addEventListener('pointerup', () => (drag = null));
29+ addEventListener('keydown', (e) => {
30+ if (e.key === 'q') yaw += 0.2;
31+ if (e.key === 'e') yaw -= 0.2;
32+ });
33+
34+ function resize(w, h) {
35+ camera.aspect = w / h;
36+ camera.updateProjectionMatrix();
37+ }
38+
39+ function follow(pos) {
40+ goal.copy(pos);
41+ }
42+
43+ function setFocus(pos, d) {
44+ focus = pos ? { pos, d } : null;
45+ }
46+
47+ function update(dt) {
48+ const k = 1 - Math.exp(-dt * 4);
49+ target.lerp(focus ? focus.pos : goal, k);
50+ dist += ((focus ? focus.d : goalDist) - dist) * k;
51+ camera.position.set(
52+ target.x + Math.sin(yaw) * Math.cos(pitch) * dist,
53+ target.y + Math.sin(pitch) * dist,
54+ target.z + Math.cos(yaw) * Math.cos(pitch) * dist
55+ );
56+ camera.lookAt(target);
57+ }
58+
59+ function snap(pos) {
60+ target.copy(pos);
61+ goal.copy(pos);
62+ }
63+
64+ return { camera, resize, follow, setFocus, update, snap };
65+}
@@ -0,0 +1,148 @@
1+import * as THREE from '../vendor/three.module.js';
2+import { buildFigure, classColor, hashColor, mat, part } from './props.js';
3+
4+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5+
6+export function createCombat(scene, party, cam, ui) {
7+ const anims = [];
8+ const bars = [];
9+ let enemies = [];
10+
11+ const tween = (dur, fn) => anims.push({ t: 0, dur, fn });
12+
13+ function makeBar(fig, height) {
14+ const g = new THREE.Group();
15+ const back = part(g, 'box', '#1a1010', [0, 0, 0], [0.8, 0.1, 0.04]);
16+ const fill = part(g, 'box', '#c43a2a', [0, 0, 0.03], [0.76, 0.07, 0.04]);
17+ g.position.y = height;
18+ fig.add(g);
19+ bars.push(g);
20+ return { g, fill, back };
21+ }
22+
23+ function setBar(bar, ratio) {
24+ const r = Math.max(0, ratio);
25+ bar.fill.scale.x = 0.76 * r;
26+ bar.fill.position.x = -0.38 * (1 - r);
27+ }
28+
29+ function spawnEnemies(encounter) {
30+ const base = party.pos;
31+ const n = encounter.enemies.length;
32+ return encounter.enemies.map((e, i) => {
33+ const big = encounter.boss && i === 0;
34+ const fig = buildFigure(hashColor(e.faction || e.class), { scale: big ? 1.9 : 1.1, cls: '', enemy: true });
35+ const row = i - (n - 1) / 2;
36+ fig.position.set(base.x + 2.1 + (i % 2) * 0.6, base.y, base.z + row * 0.75);
37+ fig.rotation.y = -Math.PI / 2;
38+ fig.scale.multiplyScalar(0.01);
39+ tween(0.35, (p) => fig.scale.setScalar((big ? 1.9 : 1.1) * Math.max(0.01, p)));
40+ scene.add(fig);
41+ const bar = makeBar(fig, big ? 1.9 : 1.25);
42+ return { unit: e, fig, bar, hp: e.stats.hp, max: e.stats.maxHp, home: fig.position.clone() };
43+ });
44+ }
45+
46+ function lunge(fig, toward, dur) {
47+ const home = fig.position.clone();
48+ const dir = toward.clone().sub(home).setY(0).normalize().multiplyScalar(0.7);
49+ tween(dur, (p) => fig.position.copy(home).addScaledVector(dir, Math.sin(p * Math.PI)));
50+ }
51+
52+ function flash(fig, color = '#ff3020') {
53+ const meshes = [];
54+ fig.traverse((o) => o.isMesh && o.material.emissive && meshes.push([o, o.material]));
55+ meshes.forEach(([o, m]) => {
56+ const c = m.clone();
57+ c.emissive = new THREE.Color(color);
58+ c.emissiveIntensity = 1.6;
59+ o.material = c;
60+ });
61+ setTimeout(() => meshes.forEach(([o, m]) => (o.material = m)), 160);
62+ }
63+
64+ function screenOf(fig) {
65+ const v = fig.position.clone();
66+ v.y += 1.5 * fig.scale.y;
67+ v.project(cam.camera);
68+ return [(v.x * 0.5 + 0.5) * innerWidth, (-v.y * 0.5 + 0.5) * innerHeight];
69+ }
70+
71+ async function play(state, before) {
72+ const enc = state.encounter;
73+ const log = state.log || [];
74+ ui.setCombat(true);
75+ const foes = spawnEnemies(enc);
76+ enemies = foes;
77+ const ids = new Map();
78+ const hp = new Map();
79+ const abilities = new Map();
80+ foes.forEach((f) => {
81+ ids.set(f.unit.id, f);
82+ hp.set(f.unit.id, f.hp);
83+ f.unit.abilities.forEach((a) => abilities.set(a.id, a));
84+ });
85+ const prev = Object.fromEntries(before.party.units.map((u) => [u.id, u]));
86+ state.party.units.forEach((u) => {
87+ const fig = party.figures.get(u.id);
88+ const p = prev[u.id] || u;
89+ ids.set(u.id, { unit: u, fig, ally: true, max: p.stats.maxHp });
90+ hp.set(u.id, p.stats.hp);
91+ u.abilities.forEach((a) => abilities.set(a.id, a));
92+ });
93+ const mid = party.pos.clone();
94+ mid.x += 1.0;
95+ cam.setFocus(mid, 10);
96+ ui.renderParty(state, hp);
97+ ui.logLine(`⚔ ${enc.boss ? 'Boss fight' : 'Combat'}: ${foes.map((f) => f.unit.name).join(', ')}`, 'head');
98+ await sleep(900);
99+
100+ const delay = THREE.MathUtils.clamp(9000 / Math.max(log.length, 1), 160, 520);
101+ for (const ev of log) {
102+ const a = ids.get(ev.actor);
103+ const t = ids.get(ev.target);
104+ const ab = abilities.get(ev.ability);
105+ if (a && t && a !== t) lunge(a.fig, t.fig.position, delay / 1000 * 0.8);
106+ const heal = ab && ab.kind === 'heal';
107+ if (t) {
108+ const cur = hp.get(ev.target) ?? 0;
109+ const max = t.ally ? t.max : t.max;
110+ const next = heal ? Math.min(max, cur + ev.amount) : Math.max(0, cur - ev.amount);
111+ hp.set(ev.target, next);
112+ if (!t.ally) setBar(t.bar, next / t.max);
113+ if (!heal && ev.amount > 0) flash(t.fig);
114+ else if (heal) flash(t.fig, '#40ff60');
115+ const [sx, sy] = screenOf(t.fig);
116+ ui.floater(sx, sy, heal ? `+${ev.amount}` : ev.amount > 0 ? `${ev.amount}${ev.crit ? '!' : ''}` : ab ? ab.name : '', heal ? 'heal' : ev.crit ? 'crit' : t.ally ? 'hurt' : 'dmg');
117+ if (ev.killed) {
118+ const f = t.fig;
119+ if (t.ally) tween(0.4, (p) => (f.rotation.z = p * Math.PI / 2));
120+ else tween(0.5, (p) => (f.scale.setScalar(Math.max(0.01, (1 - p) * (t.unit.class === 'boss' ? 1.9 : 1.1))), (f.position.y = t.home.y - p * 0.3)));
121+ }
122+ }
123+ ui.logLine(ev.text, ev.killed ? 'kill' : ev.crit ? 'crit' : '');
124+ ui.renderParty(state, hp);
125+ await sleep(delay);
126+ }
127+ await sleep(500);
128+ for (const u of state.party.units) party.figures.get(u.id).rotation.z = 0;
129+ for (const f of foes) scene.remove(f.fig);
130+ bars.length = 0;
131+ enemies = [];
132+ cam.setFocus(null);
133+ ui.setCombat(false);
134+ }
135+
136+ function update(dt) {
137+ for (let i = anims.length - 1; i >= 0; i--) {
138+ const a = anims[i];
139+ a.t += dt;
140+ const p = Math.min(1, a.t / a.dur);
141+ a.fn(p);
142+ if (p >= 1) anims.splice(i, 1);
143+ }
144+ for (const b of bars) b.quaternion.copy(b.parent.quaternion).invert().multiply(cam.camera.quaternion);
145+ }
146+
147+ return { play, update };
148+}
@@ -0,0 +1,198 @@
1+import * as THREE from '../vendor/three.module.js';
2+import * as api from './api.js';
3+import { loadTextures } from './textures.js';
4+import { createWorld } from './world.js';
5+import { createParty } from './party.js';
6+import { createCamera } from './camera.js';
7+import { createCombat } from './combat.js';
8+import { createUI } from './ui.js';
9+import { showTitle, showEnd } from './screens.js';
10+import { mat } from './props.js';
11+
12+const canvas = document.getElementById('stage');
13+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
14+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
15+renderer.shadowMap.enabled = true;
16+renderer.shadowMap.type = THREE.PCFSoftShadowMap;
17+renderer.toneMapping = THREE.ACESFilmicToneMapping;
18+renderer.toneMappingExposure = 1.5;
19+
20+const scene = new THREE.Scene();
21+scene.background = new THREE.Color('#150e08');
22+scene.add(new THREE.HemisphereLight('#ffe6bd', '#3a2814', 1.1));
23+const sun = new THREE.DirectionalLight('#ffd49a', 2.6);
24+sun.position.set(-16, 26, 12);
25+sun.castShadow = true;
26+sun.shadow.mapSize.set(2048, 2048);
27+Object.assign(sun.shadow.camera, { left: -34, right: 34, top: 26, bottom: -26, near: 1, far: 80 });
28+sun.shadow.bias = -0.0006;
29+scene.add(sun);
30+
31+const cam = createCamera(canvas);
32+const party = createParty(scene);
33+const marker = new THREE.Mesh(new THREE.TorusGeometry(0.4, 0.05, 6, 20), mat('#ffe08a', { emissive: '#ffb030', emissiveIntensity: 0.9 }));
34+marker.rotation.x = Math.PI / 2;
35+marker.visible = false;
36+scene.add(marker);
37+
38+const ui = createUI({
39+ onEquip: (unit, item) => mutate(() => api.equip(unit, item)),
40+ onUnequip: (unit, item) => mutate(() => api.equip(unit, item, true)),
41+});
42+const combat = createCombat(scene, party, cam, ui);
43+
44+let tex;
45+let world = null;
46+let state = null;
47+let busy = false;
48+let lastTile = '';
49+
50+async function mutate(fn) {
51+ try {
52+ state = await fn();
53+ ui.render(state);
54+ } catch (e) {
55+ ui.toast(e.message);
56+ }
57+}
58+
59+function resize() {
60+ renderer.setSize(innerWidth, innerHeight);
61+ cam.resize(innerWidth, innerHeight);
62+}
63+addEventListener('resize', resize);
64+resize();
65+
66+function load(s) {
67+ state = s;
68+ world?.dispose();
69+ world = createWorld(scene, s, tex);
70+ party.setUnits(s.party.units);
71+ const p = world.worldPos(s.party.x, s.party.y);
72+ party.place(p);
73+ cam.snap(p);
74+ lastTile = '';
75+ ui.clearLog();
76+ ui.render(s);
77+ world.refresh(s);
78+ const sp = s.map.spawns[0];
79+ if (sp) ui.logLine(sp.hint, 'hint');
80+}
81+
82+function tileOf(p) {
83+ return `${Math.round(p.x + world.width / 2 - 0.5)},${Math.round(p.z + world.height / 2 - 0.5)}`;
84+}
85+
86+function ndc(e) {
87+ return new THREE.Vector2((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
88+}
89+
90+let down = null;
91+canvas.addEventListener('pointerdown', (e) => {
92+ if (e.button === 0) down = { x: e.clientX, y: e.clientY };
93+});
94+canvas.addEventListener('pointerup', (e) => {
95+ if (e.button !== 0 || !down) return;
96+ const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5;
97+ down = null;
98+ if (!moved && !busy && world) {
99+ const t = world.pick(ndc(e), cam.camera);
100+ if (t) go(t);
101+ }
102+});
103+canvas.addEventListener('pointermove', (e) => {
104+ if (!world || busy) return;
105+ const t = world.pick(ndc(e), cam.camera);
106+ marker.visible = !!t && state.map.tiles[t.y][t.x].walkable;
107+ if (t) marker.position.copy(world.worldPos(t.x, t.y)).setY(world.worldPos(t.x, t.y).y + 0.06);
108+});
109+
110+async function go(t) {
111+ if (!state.map.tiles[t.y][t.x].walkable) return ui.toast('Impassable terrain');
112+ busy = true;
113+ marker.visible = false;
114+ const before = state;
115+ try {
116+ const next = await api.move(t.x, t.y);
117+ const poi = next.encounter && next.map.pois.find((p) => p.id === next.encounter.poi);
118+ const dest = poi || next.party;
119+ await party.walk(world.path({ x: before.party.x, y: before.party.y }, dest));
120+ if (next.encounter && next.log.length) {
121+ world.showLabels(false);
122+ await combat.play(next, before);
123+ world.showLabels(true);
124+ const r = next.rewards;
125+ if (r) ui.logLine(`Victory: +${r.xp} XP, +${r.gold} gold${r.items?.length ? ', ' + r.items.map((i) => i.name).join(', ') : ''}`, 'reward');
126+ if (next.phase === 'defeat') ui.toast('Your party was routed and fell back to the start');
127+ }
128+ state = next;
129+ world.refresh(next);
130+ ui.render(next);
131+ if (next.phase === 'defeat') {
132+ const p = world.worldPos(next.party.x, next.party.y);
133+ party.place(p);
134+ cam.snap(p);
135+ }
136+ if (next.winner || next.phase === 'victory') return showEnd(next, restart);
137+ await collectHere();
138+ const sp = state.map.spawns.find((s) => s.x === state.party.x && s.y === state.party.y);
139+ if (sp) ui.logLine(sp.hint, 'hint');
140+ } catch (e) {
141+ ui.toast(e.message);
142+ } finally {
143+ busy = false;
144+ }
145+}
146+
147+async function collectHere() {
148+ const l = state.map.loot.find((n) => !n.collected && n.x === state.party.x && n.y === state.party.y);
149+ if (!l) return;
150+ state = await api.interact(l.id);
151+ world.refresh(state);
152+ ui.render(state);
153+ ui.logLine(`Found ${l.item.name} (${l.item.rarity})`, 'reward');
154+ ui.toast(`Found ${l.item.name}`);
155+}
156+
157+async function restart() {
158+ const s = await api.newGame();
159+ load(s);
160+ showTitle(s, { onStart: begin, onNew: restart });
161+}
162+
163+function begin() {
164+ ui.show(true);
165+}
166+
167+const clock = new THREE.Clock();
168+function frame() {
169+ const dt = Math.min(clock.getDelta(), 0.1);
170+ if (world) {
171+ party.update(dt);
172+ world.update(clock.elapsedTime);
173+ const key = tileOf(party.pos);
174+ if (key !== lastTile) {
175+ lastTile = key;
176+ const [x, y] = key.split(',').map(Number);
177+ world.reveal(x, y);
178+ }
179+ cam.follow(party.pos);
180+ }
181+ combat.update(dt);
182+ cam.update(dt);
183+ renderer.render(scene, cam.camera);
184+ requestAnimationFrame(frame);
185+}
186+
187+async function boot() {
188+ tex = await loadTextures();
189+ load(await api.getState());
190+ frame();
191+ showTitle(state, { onStart: begin, onNew: restart });
192+}
193+
194+boot().catch((e) => {
195+ console.error(e);
196+ document.getElementById('screen').innerHTML = `<div class="card"><h1>Tiny Adventure</h1><p>${e.message}</p></div>`;
197+ document.getElementById('screen').hidden = false;
198+});
@@ -0,0 +1,74 @@
1+import * as THREE from '../vendor/three.module.js';
2+import { buildFigure, classColor } from './props.js';
3+
4+const OFFSETS = [[-0.28, -0.28], [0.28, -0.28], [-0.28, 0.28], [0.28, 0.28], [0, 0]];
5+const SPEED = 5;
6+
7+export function createParty(scene) {
8+ const root = new THREE.Group();
9+ scene.add(root);
10+ const figures = new Map();
11+ const pos = new THREE.Vector3();
12+ let route = [];
13+ let resolve = null;
14+ let clock = 0;
15+
16+ function setUnits(units) {
17+ for (const f of figures.values()) root.remove(f);
18+ figures.clear();
19+ units.forEach((u, i) => {
20+ const f = buildFigure(classColor(u.class), { cls: u.class, scale: 1.1 });
21+ f.userData.offset = OFFSETS[i % OFFSETS.length];
22+ figures.set(u.id, f);
23+ root.add(f);
24+ });
25+ layout();
26+ }
27+
28+ function layout() {
29+ for (const f of figures.values()) f.position.set(pos.x + f.userData.offset[0], pos.y, pos.z + f.userData.offset[1]);
30+ }
31+
32+ function place(p) {
33+ pos.copy(p);
34+ route = [];
35+ layout();
36+ }
37+
38+ function walk(points) {
39+ route = points.slice();
40+ return new Promise((r) => {
41+ if (!route.length) return r();
42+ resolve = r;
43+ });
44+ }
45+
46+ function update(dt) {
47+ clock += dt;
48+ let step = SPEED * dt;
49+ while (route.length && step > 0) {
50+ const d = pos.distanceTo(route[0]);
51+ if (d <= step) {
52+ step -= d;
53+ pos.copy(route.shift());
54+ } else {
55+ pos.lerp(route[0], step / d);
56+ step = 0;
57+ }
58+ if (!route.length && resolve) {
59+ const r = resolve;
60+ resolve = null;
61+ r();
62+ }
63+ }
64+ layout();
65+ const moving = route.length > 0;
66+ let i = 0;
67+ for (const f of figures.values()) {
68+ f.userData.body.position.y = moving ? Math.abs(Math.sin(clock * 12 + i)) * 0.08 : 0;
69+ i++;
70+ }
71+ }
72+
73+ return { root, figures, pos, setUnits, place, walk, update, moving: () => route.length > 0 };
74+}
@@ -0,0 +1,171 @@
1+import * as THREE from '../vendor/three.module.js';
2+
3+const matCache = {};
4+export const mat = (color, extra = {}) => {
5+ const k = color + JSON.stringify(extra);
6+ return (matCache[k] ||= new THREE.MeshStandardMaterial({ color, flatShading: true, roughness: 0.85, ...extra }));
7+};
8+
9+const G = {
10+ box: new THREE.BoxGeometry(1, 1, 1),
11+ cone: new THREE.ConeGeometry(0.5, 1, 6),
12+ cyl: new THREE.CylinderGeometry(0.5, 0.5, 1, 8),
13+ sph: new THREE.IcosahedronGeometry(0.5, 1),
14+};
15+
16+export function part(parent, geo, color, [x, y, z], [sx, sy, sz], extra) {
17+ const m = new THREE.Mesh(G[geo], typeof color === 'string' ? mat(color, extra) : color);
18+ m.position.set(x, y, z);
19+ m.scale.set(sx, sy, sz);
20+ m.castShadow = true;
21+ m.receiveShadow = true;
22+ parent.add(m);
23+ return m;
24+}
25+
26+export function hashColor(id) {
27+ let h = 0;
28+ for (const c of String(id)) h = (h * 31 + c.charCodeAt(0)) % 360;
29+ return new THREE.Color().setHSL(h / 360, 0.6, 0.45).getStyle();
30+}
31+
32+export function label(text, color = '#f4e6c0') {
33+ const c = document.createElement('canvas');
34+ c.width = 512;
35+ c.height = 96;
36+ const g = c.getContext('2d');
37+ g.font = 'bold 44px serif';
38+ g.textAlign = 'center';
39+ g.lineWidth = 8;
40+ g.strokeStyle = '#1b1208';
41+ g.strokeText(text, 256, 62);
42+ g.fillStyle = color;
43+ g.fillText(text, 256, 62);
44+ const t = new THREE.CanvasTexture(c);
45+ t.colorSpace = THREE.SRGBColorSpace;
46+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, transparent: true, depthTest: false }));
47+ s.scale.set(3.2, 0.6, 1);
48+ s.renderOrder = 10;
49+ return s;
50+}
51+
52+function banner(g, color, y) {
53+ part(g, 'cyl', '#4a3320', [0.45, y / 2, 0.45], [0.05, y, 0.05]);
54+ const f = part(g, 'box', color, [0.62, y - 0.18, 0.45], [0.35, 0.28, 0.03]);
55+ f.userData.flag = true;
56+}
57+
58+const POIS = {
59+ mine(g) {
60+ part(g, 'cone', '#6e6258', [0, 0.45, 0], [1.7, 0.9, 1.5]);
61+ part(g, 'box', '#120d0a', [0, 0.22, 0.55], [0.5, 0.44, 0.2]);
62+ part(g, 'box', '#6a4a2a', [-0.3, 0.26, 0.58], [0.08, 0.52, 0.1]);
63+ part(g, 'box', '#6a4a2a', [0.3, 0.26, 0.58], [0.08, 0.52, 0.1]);
64+ part(g, 'box', '#6a4a2a', [0, 0.52, 0.58], [0.7, 0.08, 0.1]);
65+ },
66+ beach(g) {
67+ part(g, 'cyl', '#8a6a3e', [0, 0.5, 0], [0.12, 1, 0.12]).rotation.z = 0.2;
68+ for (let i = 0; i < 5; i++) {
69+ const l = part(g, 'box', '#3f9a4a', [Math.cos(i * 1.26) * 0.28 + 0.1, 1.0, Math.sin(i * 1.26) * 0.28], [0.6, 0.04, 0.16]);
70+ l.rotation.y = -i * 1.26;
71+ l.rotation.z = -0.4;
72+ }
73+ part(g, 'sph', '#e8dcc0', [-0.45, 0.12, 0.4], [0.35, 0.2, 0.3]);
74+ },
75+ ruins(g) {
76+ [[-0.45, 0.4], [0.35, 0.7], [0.0, 0.3], [0.45, -0.4]].forEach(([x, h], i) => part(g, 'cyl', '#a29d8f', [x, h / 2, (i - 1.5) * 0.3], [0.22, h, 0.22]));
77+ part(g, 'box', '#8e897c', [-0.1, 0.1, 0.4], [0.9, 0.2, 0.3]);
78+ },
79+ crypt(g) {
80+ part(g, 'box', '#7f8a84', [0, 0.3, 0], [1.1, 0.6, 0.9]);
81+ part(g, 'cone', '#5d6862', [0, 0.75, 0], [1.3, 0.35, 1.1]).rotation.y = Math.PI / 4;
82+ part(g, 'box', '#d8d4c4', [0.45, 0.45, 0.55], [0.08, 0.5, 0.08]);
83+ part(g, 'box', '#d8d4c4', [0.45, 0.55, 0.55], [0.3, 0.08, 0.08]);
84+ },
85+ village(g) {
86+ [[-0.4, -0.2], [0.35, 0.15], [-0.05, 0.5]].forEach(([x, z], i) => {
87+ part(g, 'box', '#d8c49a', [x, 0.2, z], [0.5, 0.4, 0.45]);
88+ part(g, 'cone', i % 2 ? '#a8472f' : '#8a4a2a', [x, 0.55, z], [0.75, 0.4, 0.75]).rotation.y = Math.PI / 4;
89+ });
90+ },
91+ tower(g) {
92+ part(g, 'cyl', '#a9a597', [0, 0.7, 0], [0.7, 1.4, 0.7]);
93+ part(g, 'cyl', '#8e8a7c', [0, 1.45, 0], [0.9, 0.18, 0.9]);
94+ part(g, 'cone', '#5b3a7a', [0, 1.8, 0], [0.8, 0.7, 0.8]);
95+ },
96+ camp(g) {
97+ part(g, 'cone', '#a8472f', [-0.3, 0.35, 0], [0.8, 0.7, 0.8]);
98+ part(g, 'cone', '#c9a24a', [0.4, 0.28, 0.3], [0.6, 0.56, 0.6]);
99+ part(g, 'cone', '#ff8a24', [0.2, 0.12, -0.45], [0.2, 0.24, 0.2], { emissive: '#ff6a10', emissiveIntensity: 1.2 });
100+ },
101+};
102+
103+export function buildPOI(poi, color, big) {
104+ const g = new THREE.Group();
105+ (POIS[poi.kind] || POIS.camp)(g);
106+ banner(g, poi.cleared ? '#6e6e6e' : color, big ? 1.6 : 1.2);
107+ if (big) g.scale.setScalar(1.35);
108+ g.userData.poi = poi.id;
109+ return g;
110+}
111+
112+export function setCleared(g, cleared, color) {
113+ g.traverse((o) => {
114+ if (o.userData.flag) o.material = mat(cleared ? '#6e6e6e' : color);
115+ });
116+}
117+
118+const SPAWNS = {
119+ shrine: (g) => { part(g, 'box', '#bdb7a6', [0, 0.15, 0], [0.7, 0.3, 0.7]); part(g, 'box', '#d4cebb', [0, 0.55, 0], [0.3, 0.5, 0.3]); part(g, 'cone', '#ffd27a', [0, 0.95, 0], [0.25, 0.3, 0.25], { emissive: '#ff9a20' }); },
120+ 'burned inn': (g) => { part(g, 'box', '#2b2420', [0, 0.25, 0], [0.9, 0.5, 0.7]); part(g, 'box', '#1a1512', [0.2, 0.7, 0], [0.12, 0.5, 0.5]); },
121+ crossroads: (g) => { part(g, 'cyl', '#6a4a2a', [0, 0.5, 0], [0.08, 1, 0.08]); part(g, 'box', '#8a6a3e', [0.2, 0.8, 0], [0.5, 0.15, 0.04]); part(g, 'box', '#8a6a3e', [-0.2, 0.6, 0], [0.5, 0.15, 0.04]); },
122+ watchpost: (g) => { part(g, 'box', '#6a4a2a', [0, 0.6, 0], [0.6, 0.08, 0.6]); [[-1, -1], [1, -1], [-1, 1], [1, 1]].forEach(([a, b]) => part(g, 'cyl', '#5a3d22', [a * 0.25, 0.3, b * 0.25], [0.07, 0.6, 0.07])); part(g, 'cone', '#8a4a2a', [0, 0.95, 0], [0.8, 0.4, 0.8]); },
123+ wagon: (g) => { part(g, 'box', '#8a6a3e', [0, 0.3, 0], [0.9, 0.3, 0.5]); part(g, 'cyl', '#3a2a1a', [-0.3, 0.2, 0.3], [0.35, 0.06, 0.35]).rotation.x = Math.PI / 2; part(g, 'cyl', '#3a2a1a', [0.3, 0.2, 0.3], [0.35, 0.06, 0.35]).rotation.x = Math.PI / 2; part(g, 'cone', '#d8c49a', [0, 0.65, 0], [0.8, 0.4, 0.45]); },
124+};
125+
126+export function buildSpawn(sp) {
127+ const g = new THREE.Group();
128+ (SPAWNS[sp.kind] || SPAWNS.crossroads)(g);
129+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.55, 0.04, 6, 24), mat('#ffd27a', { emissive: '#ffb030', emissiveIntensity: 0.8 }));
130+ ring.rotation.x = Math.PI / 2;
131+ ring.position.y = 0.05;
132+ g.add(ring);
133+ return g;
134+}
135+
136+const RARITY = { common: '#cfc8b8', uncommon: '#5fd068', rare: '#4a9aff', epic: '#b45aff', legendary: '#ffa526' };
137+export const rarityColor = (r) => RARITY[r] || RARITY.common;
138+
139+export function buildLoot(item) {
140+ const g = new THREE.Group();
141+ part(g, 'box', '#7a4f26', [0, 0.14, 0], [0.42, 0.28, 0.3]);
142+ part(g, 'cyl', '#7a4f26', [0, 0.28, 0], [0.3, 0.42, 0.3]).rotation.z = Math.PI / 2;
143+ part(g, 'box', '#d9b23a', [0, 0.17, 0.16], [0.08, 0.1, 0.03]);
144+ const c = rarityColor(item.rarity);
145+ const gem = part(g, 'sph', c, [0, 0.7, 0], [0.18, 0.24, 0.18], { emissive: c, emissiveIntensity: 1 });
146+ g.userData.gem = gem;
147+ return g;
148+}
149+
150+const CLASS_COLORS = { fighter: '#b8392e', rogue: '#3f8a4a', mage: '#3f62c8', cleric: '#e8e0c0' };
151+export const classColor = (c) => CLASS_COLORS[c] || '#a85a9a';
152+
153+export function buildFigure(color, { scale = 1, cls = '', enemy = false } = {}) {
154+ const g = new THREE.Group();
155+ const body = new THREE.Group();
156+ g.add(body);
157+ part(body, 'cone', color, [0, 0.3, 0], [0.45, 0.6, 0.45]);
158+ part(body, 'sph', enemy ? '#9aa88a' : '#f0c8a0', [0, 0.72, 0], [0.32, 0.32, 0.32]);
159+ if (cls === 'mage') part(body, 'cone', '#2a3f8a', [0, 1.0, 0], [0.34, 0.45, 0.34]);
160+ else if (cls === 'fighter') part(body, 'box', '#c9c9d0', [0.28, 0.35, 0], [0.06, 0.32, 0.26]);
161+ else if (cls === 'cleric') part(body, 'cyl', '#d9b23a', [0.26, 0.45, 0], [0.04, 0.7, 0.04]);
162+ else if (cls === 'rogue') part(body, 'cone', '#244a2a', [0, 0.9, 0], [0.4, 0.3, 0.4]);
163+ if (enemy) {
164+ part(body, 'cone', '#e8e0c0', [-0.13, 0.95, 0], [0.08, 0.2, 0.08]);
165+ part(body, 'cone', '#e8e0c0', [0.13, 0.95, 0], [0.08, 0.2, 0.08]);
166+ part(body, 'sph', '#ff3a2a', [0, 0.74, 0.14], [0.1, 0.06, 0.06], { emissive: '#ff2a10' });
167+ }
168+ g.scale.setScalar(scale);
169+ g.userData.body = body;
170+ return g;
171+}
@@ -0,0 +1,39 @@
1+const $ = (id) => document.getElementById(id);
2+const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
3+
4+function fmtTime(s) {
5+ const m = Math.floor(s / 60);
6+ return `${m}m ${String(Math.floor(s % 60)).padStart(2, '0')}s`;
7+}
8+
9+export function showTitle(state, { onStart, onNew }) {
10+ const c = state.campaign;
11+ $('screen').className = 'title';
12+ $('screen').innerHTML = `<div class="card">
13+ <h1>Tiny Adventure</h1><p class="sub">A tabletop campaign of ${c.factions.length} factions and one dark purpose</p>
14+ <h2>${esc(c.main.name)}</h2>
15+ <p class="meta">${c.systems.map((x) => esc(x.replace('poi:', ''))).join(' · ') || 'core rules'}</p>
16+ <p class="party">${state.party.units.map((u) => `${esc(u.name)} the ${u.class}`).join(', ')}</p>
17+ <div class="row"><button id="b-start">Begin Adventure</button><button id="b-new" class="alt">New Campaign</button></div>
18+ <p class="help">Click the board to move · I inventory · J journal · Q/E and right-drag rotate · wheel zooms</p></div>`;
19+ $('screen').hidden = false;
20+ $('b-start').onclick = () => { $('screen').hidden = true; onStart(); };
21+ $('b-new').onclick = onNew;
22+}
23+
24+export function showEnd(state, onNew) {
25+ const s = state.summary;
26+ const u = state.party.units;
27+ $('screen').className = 'end';
28+ $('screen').innerHTML = `<div class="card">
29+ <h1>Victory!</h1><p class="sub">${esc(state.campaign.main.name)} is complete</p>
30+ <table>
31+ <tr><td>Battles won</td><td>${s.battles}</td></tr><tr><td>Foes slain</td><td>${s.kills}</td></tr>
32+ <tr><td>Loot found</td><td>${s.loot}</td></tr><tr><td>Steps walked</td><td>${s.steps}</td></tr>
33+ <tr><td>Time</td><td>${fmtTime(s.seconds)}</td></tr><tr><td>Gold</td><td>${state.party.gold}</td></tr>
34+ </table>
35+ <p class="party">${u.map((x) => `${esc(x.name)} (${x.class} L${x.level})`).join(' · ')}</p>
36+ <div class="row"><button id="b-again">New Game</button></div></div>`;
37+ $('screen').hidden = false;
38+ $('b-again').onclick = onNew;
39+}
@@ -0,0 +1,76 @@
1+import * as THREE from '../vendor/three.module.js';
2+
3+export const TERRAIN = {
4+ grass: { tex: 'tex_grass', color: '#5f9a3e', h: 0 },
5+ road: { tex: 'tex_dirt', color: '#b99a66', h: 0.02 },
6+ water: { tex: 'tex_water', color: '#4a7fb8', h: -0.2 },
7+ swamp: { tex: 'tex_water', color: '#5d7a45', h: -0.08 },
8+ mountain: { tex: 'tex_stone', color: '#8a8a92', h: 0.9 },
9+ forest: { tex: 'tex_grass', color: '#3f7a35', h: 0.02 },
10+ sand: { tex: 'tex_sand', color: '#e0c98a', h: 0 },
11+ rock: { tex: 'tex_stone', color: '#7b7570', h: 0.1 },
12+ ruin: { tex: 'tex_dungeon', color: '#8d8878', h: 0.05 },
13+ grave: { tex: 'tex_dungeon', color: '#6f7a70', h: 0.03 },
14+ farm: { tex: 'tex_dirt', color: '#c2a35a', h: 0 },
15+ stone: { tex: 'tex_stone', color: '#9a968c', h: 0.08 },
16+ dirt: { tex: 'tex_dirt', color: '#a8844f', h: 0 },
17+ snow: { tex: 'tex_snow', color: '#eef2f6', h: 0.02 },
18+};
19+
20+const FALLBACK = { tex: 'tex_dirt', color: '#8a7a5a', h: 0 };
21+export const terrainInfo = (t) => TERRAIN[t] || FALLBACK;
22+
23+function noiseCanvas(base) {
24+ const c = document.createElement('canvas');
25+ c.width = c.height = 128;
26+ const g = c.getContext('2d');
27+ g.fillStyle = base;
28+ g.fillRect(0, 0, 128, 128);
29+ for (let i = 0; i < 700; i++) {
30+ g.fillStyle = Math.random() < 0.5 ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.1)';
31+ g.fillRect(Math.random() * 128, Math.random() * 128, 2 + Math.random() * 5, 2 + Math.random() * 5);
32+ }
33+ return new THREE.CanvasTexture(c);
34+}
35+
36+export async function loadTextures() {
37+ let manifest = {};
38+ try {
39+ manifest = await (await fetch('/assets/manifest.json')).json();
40+ } catch {
41+ manifest = {};
42+ }
43+ const loader = new THREE.TextureLoader();
44+ const cache = {};
45+ const get = async (key, base) => {
46+ if (cache[key + base]) return cache[key + base];
47+ let t = null;
48+ const entry = manifest[key];
49+ if (entry) {
50+ try {
51+ t = await loader.loadAsync('/assets/' + entry.file);
52+ t.anisotropy = 4;
53+ } catch {
54+ t = null;
55+ }
56+ }
57+ const fromFile = !!t;
58+ t = t || noiseCanvas(base);
59+ t.colorSpace = THREE.SRGBColorSpace;
60+ t.userData.fromFile = fromFile;
61+ cache[key + base] = t;
62+ return t;
63+ };
64+ const mats = {};
65+ for (const [name, info] of Object.entries(TERRAIN)) {
66+ const map = await get(info.tex, info.color);
67+ mats[name] = new THREE.MeshStandardMaterial({
68+ map,
69+ color: map.userData.fromFile ? new THREE.Color(info.color).lerp(new THREE.Color('#ffffff'), 0.55) : '#ffffff',
70+ roughness: 0.95,
71+ flatShading: true,
72+ });
73+ }
74+ mats.fallback = new THREE.MeshStandardMaterial({ map: await get(FALLBACK.tex, FALLBACK.color), color: '#ffffff', roughness: 1 });
75+ return { mats, wood: await get('tex_wood', '#6b4a2a') };
76+}
@@ -0,0 +1,121 @@
1+import { rarityColor } from './props.js';
2+
3+const $ = (id) => document.getElementById(id);
4+const ABILITY_ICON = { strike: 6, 'power-strike': 5, backstab: 8, firebolt: 0, fireball: 0, smite: 9, heal: 1, rally: 13, cleave: 12, 'venom-bite': 4, 'dark-bolt': 11, 'doom-wave': 11, 'war-cry': 13, mend: 1 };
5+const KIND_ICON = { damage: 6, magic: 2, aoe: 12, heal: 1, buff: 13 };
6+const SLOT_ICON = { weapon: 0, armor: 6, helm: 5, trinket: 9 };
7+const SLOTS = ['weapon', 'armor', 'helm', 'trinket'];
8+const STATS = ['maxHp', 'attack', 'defense', 'magic', 'speed', 'crit'];
9+
10+const icon = (sheet, i) => `<i class="icon" style="background-image:url(/assets/${sheet}.png);background-position:${(i % 4) * 33.33}% ${Math.floor(i / 4) * 33.33}%"></i>`;
11+const itemIcon = (it) => icon('icons_items', it.key ? 12 : SLOT_ICON[it.slot] ?? 14);
12+const bonusText = (b) => Object.entries(b || {}).filter(([, v]) => v).map(([k, v]) => `${v > 0 ? '+' : ''}${v} ${k}`).join(', ');
13+const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
14+
15+export function createUI(h) {
16+ let state = null;
17+ let selected = null;
18+
19+ const panel = (id) => $(id);
20+ const toggle = (id) => {
21+ for (const p of ['panel-inv', 'panel-journal']) if (p !== id) $(p).hidden = true;
22+ $(id).hidden = !$(id).hidden;
23+ };
24+ $('btn-inv').onclick = () => toggle('panel-inv');
25+ $('btn-journal').onclick = () => toggle('panel-journal');
26+ document.querySelectorAll('.panel .close').forEach((b) => (b.onclick = () => (b.parentElement.hidden = true)));
27+ addEventListener('keydown', (e) => {
28+ if ($('hud').hidden) return;
29+ if (e.key === 'i' || e.key === 'I') toggle('panel-inv');
30+ if (e.key === 'j' || e.key === 'J') toggle('panel-journal');
31+ if (e.key === 'Escape') for (const p of ['panel-inv', 'panel-journal']) $(p).hidden = true;
32+ });
33+
34+ const unitOf = () => state.party.units.find((u) => u.id === selected) || state.party.units[0];
35+
36+ function renderParty(s, hp) {
37+ state = s;
38+ if (!selected || !s.party.units.some((u) => u.id === selected)) selected = s.party.units[0].id;
39+ $('portraits').innerHTML = s.party.units
40+ .map((u) => {
41+ const cur = hp ? hp.get(u.id) ?? u.stats.hp : u.stats.hp;
42+ const max = u.stats.maxHp;
43+ const xp = Math.min(100, (u.xp / (40 * u.level)) * 100);
44+ return `<div class="portrait ${u.id === selected ? 'sel' : ''} ${cur <= 0 ? 'dead' : ''}" data-id="${u.id}">
45+ <div class="face c-${u.class}">${u.class[0].toUpperCase()}<b>${u.level}</b></div>
46+ <div class="pname">${esc(u.name)}</div>
47+ <div class="bar hp"><span style="width:${(Math.max(0, cur) / max) * 100}%"></span><em>${Math.max(0, cur)}/${max}</em></div>
48+ <div class="bar xp"><span style="width:${xp}%"></span></div></div>`;
49+ })
50+ .join('');
51+ $('portraits').querySelectorAll('.portrait').forEach((el) => (el.onclick = () => { selected = el.dataset.id; renderParty(state, hp); renderPanels(); }));
52+ $('gold').textContent = `◉ ${s.party.gold}`;
53+ $('abilities').innerHTML = unitOf().abilities
54+ .map((a, i) => `<div class="ability" title="${esc(a.name)} — ${a.kind}, power ${a.power}, cd ${a.cooldown}">${icon('icons_abilities', ABILITY_ICON[a.id] ?? KIND_ICON[a.kind] ?? 3)}<span class="key">${i + 1}</span><span class="aname">${esc(a.name)}</span></div>`)
55+ .join('');
56+ }
57+
58+ function renderPanels() {
59+ if (!state) return;
60+ const u = unitOf();
61+ $('inv-body').innerHTML = `
62+ <div class="tabs">${state.party.units.map((x) => `<button class="${x.id === u.id ? 'on' : ''}" data-u="${x.id}">${esc(x.name)}</button>`).join('')}</div>
63+ <div class="hero">${esc(u.name)} — ${u.class} L${u.level}</div>
64+ <div class="slots">${SLOTS.map((s) => {
65+ const it = u.gear?.[s];
66+ return `<div class="slot ${it ? 'filled' : ''}" data-slot="${s}" title="${it ? esc(it.name) + ' ' + bonusText(it.bonus) + ' (click to unequip)' : s}">${it ? itemIcon(it) : icon('icons_items', SLOT_ICON[s]).replace('class="icon"', 'class="icon ghost"')}<span style="color:${it ? rarityColor(it.rarity) : '#8a7a5a'}">${it ? esc(it.name) : s}</span></div>`;
67+ }).join('')}</div>
68+ <div class="stats">${STATS.map((k) => `<span>${k}<b>${u.stats[k]}</b></span>`).join('')}</div>
69+ <div class="hero">Pack (${state.party.inventory.length})</div>
70+ <div class="grid">${state.party.inventory.map((it) => `<div class="cell" data-item="${it.id}" title="${esc(it.name)} [${it.rarity}] ${bonusText(it.bonus)}">${itemIcon(it)}<span style="color:${rarityColor(it.rarity)}">${esc(it.name)}</span></div>`).join('') || '<p class="empty">Nothing yet. Explore for loot.</p>'}</div>`;
71+ $('inv-body').querySelectorAll('[data-u]').forEach((b) => (b.onclick = () => { selected = b.dataset.u; renderParty(state); renderPanels(); }));
72+ $('inv-body').querySelectorAll('.slot.filled').forEach((el) => (el.onclick = () => h.onUnequip(u.id, u.gear[el.dataset.slot].id)));
73+ $('inv-body').querySelectorAll('.cell').forEach((el) => (el.onclick = () => h.onEquip(u.id, el.dataset.item)));
74+
75+ const c = state.campaign;
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.