From 68d87fcae354d810bc7b0af16502b23442cb390b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:29:40 +0000 Subject: [PATCH 1/6] Windrow: first playable slice of a leaf-clearing game (not on the site yet) A new Back Room game in e63334287a3deaa3/windrow/: first-person garden with thousands of physical leaves, hands and sack, rake, blower, bins, chutes, upgrades, five gardens, journal map, touch controls and saving. Not yet linked from any page. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Cw2rMA4m89wq5xtvEXdXsk --- e63334287a3deaa3/windrow/es.js | 1 + e63334287a3deaa3/windrow/index.html | 272 ++++++++++++++ e63334287a3deaa3/windrow/js/audio.js | 57 +++ e63334287a3deaa3/windrow/js/game.js | 489 ++++++++++++++++++++++++++ e63334287a3deaa3/windrow/js/leaves.js | 317 +++++++++++++++++ e63334287a3deaa3/windrow/js/models.js | 60 ++++ e63334287a3deaa3/windrow/js/world.js | 312 ++++++++++++++++ 7 files changed, 1508 insertions(+) create mode 100644 e63334287a3deaa3/windrow/es.js create mode 100644 e63334287a3deaa3/windrow/index.html create mode 100644 e63334287a3deaa3/windrow/js/audio.js create mode 100644 e63334287a3deaa3/windrow/js/game.js create mode 100644 e63334287a3deaa3/windrow/js/leaves.js create mode 100644 e63334287a3deaa3/windrow/js/models.js create mode 100644 e63334287a3deaa3/windrow/js/world.js diff --git a/e63334287a3deaa3/windrow/es.js b/e63334287a3deaa3/windrow/es.js new file mode 100644 index 00000000..a86c306c --- /dev/null +++ b/e63334287a3deaa3/windrow/es.js @@ -0,0 +1 @@ +if (window.BackRoomLang) BackRoomLang.add({}); diff --git a/e63334287a3deaa3/windrow/index.html b/e63334287a3deaa3/windrow/index.html new file mode 100644 index 00000000..24f57c03 --- /dev/null +++ b/e63334287a3deaa3/windrow/index.html @@ -0,0 +1,272 @@ + + + + + + + +Windrow + + + + + + + + + + + +
+ + + + +
+
+

Windrow

+

The old gardens are buried in autumn. Gather, rake and blow every last leaf away, one walled garden at a time.

+
+ + + +
+

Your garden saves itself in this browser.

+
+
+ + + + + + + + +
+ + + + + + + + + + + diff --git a/e63334287a3deaa3/windrow/js/audio.js b/e63334287a3deaa3/windrow/js/audio.js new file mode 100644 index 00000000..95ff5e78 --- /dev/null +++ b/e63334287a3deaa3/windrow/js/audio.js @@ -0,0 +1,57 @@ +/* Windrow: every sound is made here in code with the Web Audio API. Nothing is downloaded. + Three sounds run all the time and are only turned up and down (leaf rustle, rake scrape, blower); the rest are + short one-off notes and thumps. Starts on the first tap or key, as browsers require. */ +(function () { + 'use strict'; + var WR = window.WR, A = WR.Audio = { vol: 0.7, ready: false }, ctx, master, noise, rustleG, scrapeG, blowG, blowOsc, blowF, windG, birdT = 3; + function noiseBuf(sec) { var b = ctx.createBuffer(1, ctx.sampleRate * sec, ctx.sampleRate), d = b.getChannelData(0), last = 0; for (var i = 0; i < d.length; i++) { var w = Math.random() * 2 - 1; last = last * 0.2 + w * 0.8; d[i] = last; } return b; } + function loop(type, freq, q) { var s = ctx.createBufferSource(); s.buffer = noise; s.loop = true; s.playbackRate.value = 0.8 + Math.random() * 0.4; var f = ctx.createBiquadFilter(); f.type = type; f.frequency.value = freq; f.Q.value = q; var g = ctx.createGain(); g.gain.value = 0; s.connect(f); f.connect(g); g.connect(master); s.start(); return { g: g, f: f }; } + A.init = function () { + if (ctx) { if (ctx.state === 'suspended') ctx.resume(); return; } + var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; + try { ctx = new AC(); } catch (e) { return; } + master = ctx.createGain(); master.gain.value = A.vol; master.connect(ctx.destination); + noise = noiseBuf(2); + rustleG = loop('bandpass', 5200, 0.7); scrapeG = loop('bandpass', 1500, 1.6); windG = loop('lowpass', 420, 0.3); + var b = loop('lowpass', 900, 0.5); blowG = b.g; blowF = b.f; + blowOsc = ctx.createOscillator(); blowOsc.type = 'sawtooth'; blowOsc.frequency.value = 78; var og = ctx.createGain(); og.gain.value = 0.16; var of = ctx.createBiquadFilter(); of.type = 'lowpass'; of.frequency.value = 520; blowOsc.connect(of); of.connect(og); og.connect(blowG); blowOsc.start(); + A.ready = true; + }; + A.setVol = function (v) { A.vol = v; if (master) master.gain.setTargetAtTime(v, ctx.currentTime, 0.05); }; + A.suspend = function (on) { if (!ctx) return; if (on) ctx.suspend(); else ctx.resume(); }; + // called every frame: how much leaf is moving, whether the rake is dragging, whether the blower is on + A.frame = function (dt, moved, scrape, blow, blowLv) { + if (!A.ready) return; var t = ctx.currentTime; + rustleG.g.gain.setTargetAtTime(Math.min(0.5, moved * 0.012), t, 0.06); + rustleG.f.frequency.setTargetAtTime(4200 + Math.min(1, moved / 60) * 2600, t, 0.1); + scrapeG.g.gain.setTargetAtTime(scrape ? 0.22 : 0, t, scrape ? 0.03 : 0.08); + blowG.gain.setTargetAtTime(blow ? 0.34 : 0, t, blow ? 0.12 : 0.2); + blowOsc.frequency.setTargetAtTime(blow ? 104 + (blowLv || 0) * 9 : 62, t, 0.25); blowF.frequency.setTargetAtTime(blow ? 1500 + (blowLv || 0) * 260 : 500, t, 0.2); + windG.g.gain.setTargetAtTime(0.05 + 0.035 * Math.sin(t * 0.23) + 0.02 * Math.sin(t * 0.71), t, 0.5); + birdT -= dt; if (birdT <= 0) { birdT = 4 + Math.random() * 9; chirp(); } + }; + function tone(type, f0, f1, dur, vol, delay) { + if (!A.ready) return; var t = ctx.currentTime + (delay || 0), o = ctx.createOscillator(), g = ctx.createGain(); o.type = type; + o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t + dur); + g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + 0.012); g.gain.exponentialRampToValueAtTime(0.0001, t + dur); + o.connect(g); g.connect(master); o.start(t); o.stop(t + dur + 0.03); + } + function burst(freq, q, dur, vol, delay) { + if (!A.ready) return; var t = ctx.currentTime + (delay || 0), s = ctx.createBufferSource(); s.buffer = noise; var f = ctx.createBiquadFilter(); f.type = 'bandpass'; f.frequency.value = freq; f.Q.value = q; var g = ctx.createGain(); + g.gain.setValueAtTime(vol, t); g.gain.exponentialRampToValueAtTime(0.0001, t + dur); s.connect(f); f.connect(g); g.connect(master); s.start(t, Math.random()); s.stop(t + dur + 0.02); + } + function chirp() { var f = 2400 + Math.random() * 1600, n = 2 + (Math.random() * 3 | 0); for (var i = 0; i < n; i++) tone('sine', f, f * (1.15 + Math.random() * .3), 0.07, 0.022, i * 0.11); } + var lastTick = 0; + A.pick = function () { if (!A.ready || ctx.currentTime - lastTick < 0.05) return; lastTick = ctx.currentTime; burst(3800 + Math.random() * 2500, 2, 0.06, 0.09); }; + A.chute = function () { if (!A.ready || ctx.currentTime - lastTick < 0.06) return; lastTick = ctx.currentTime; tone('sine', 520 + Math.random() * 160, 180, 0.12, 0.06); }; + A.bin = function () { tone('sine', 130, 55, 0.3, 0.4); burst(700, 0.8, 0.35, 0.3); burst(3000, 0.8, 0.5, 0.12, 0.05); }; + A.coin = function () { tone('triangle', 880, 880, 0.08, 0.1); tone('triangle', 1320, 1320, 0.14, 0.1, 0.07); }; + A.buy = function () { tone('triangle', 660, 660, 0.09, 0.12); tone('triangle', 880, 880, 0.09, 0.12, 0.08); tone('triangle', 1175, 1175, 0.2, 0.12, 0.16); }; + A.no = function () { tone('square', 180, 140, 0.14, 0.05); }; + A.click = function () { tone('sine', 700, 500, 0.05, 0.06); }; + A.full = function () { tone('sine', 300, 220, 0.18, 0.1); tone('sine', 300, 220, 0.18, 0.1, 0.2); }; + A.fanfare = function () { [523, 659, 784, 1047, 1319].forEach(function (f, i) { tone('triangle', f, f, 0.32, 0.13, i * 0.11); }); }; + A.gate = function () { tone('sawtooth', 90, 140, 0.7, 0.05); burst(500, 3, 0.7, 0.08); }; + A.step = function (wood) { if (wood) { tone('sine', 150, 90, 0.07, 0.07); burst(900, 1, 0.04, 0.04); } else burst(260 + Math.random() * 120, 0.9, 0.07, 0.07); }; + A.jump = function () { burst(500, 0.6, 0.12, 0.05); }; +})(); diff --git a/e63334287a3deaa3/windrow/js/game.js b/e63334287a3deaa3/windrow/js/game.js new file mode 100644 index 00000000..528586bb --- /dev/null +++ b/e63334287a3deaa3/windrow/js/game.js @@ -0,0 +1,489 @@ +/* Windrow: the game itself. The player, the three tools, bins, chutes and gates, acorns and upgrades, the HUD and + menus, saving, and the frame loop. + Everything is saved in this browser under localStorage 'windrow:v1' (see README): acorns, upgrades, which gardens + are open and finished, what is in the sack, settings, and where every leaf still on the ground is lying. */ +(function () { + 'use strict'; + var WR = window.WR, L = window.BackRoomLang, $ = function (id) { return document.getElementById(id); }; + function T(s, v) { if (L) return L.t(s, v); return String(s).replace(/\{(\w+)\}/g, function (m, n) { return v && v[n] != null ? v[n] : m; }); } + WR.T = T; + var KEY = 'windrow:v1', A = WR.AREAS, Au = WR.Audio; + + /* ---------- upgrades (the shed) ---------- */ + var UP = WR.UPGRADES = [ + { id: 'sack', name: 'Bigger sack', text: 'Carry more leaves before a trip to the bin', costs: [40, 110, 260, 600, 1300] }, + { id: 'hands', name: 'Quick hands', text: 'Gather faster and reach wider', costs: [30, 90, 220, 520] }, + { id: 'rake', name: 'Rake', text: 'Drags a whole row of leaves toward you with every stroke', costs: [60] }, + { id: 'rakeW', name: 'Wider rake', text: 'A broader head moves more leaves a stroke', costs: [120, 320, 800], needs: 'rake' }, + { id: 'blower', name: 'Leaf blower', text: 'Pushes leaves away in a cone of wind', costs: [350] }, + { id: 'power', name: 'Stronger motor', text: 'The blower pushes harder', costs: [300, 700, 1500], needs: 'blower' }, + { id: 'nozzle', name: 'Long nozzle', text: 'The wind reaches farther and spreads wider', costs: [250, 600, 1400], needs: 'blower' }, + { id: 'value', name: 'Rich compost', text: 'Every leaf pays 15% more', costs: [90, 220, 500, 1100, 2400] }, + { id: 'shoes', name: 'Light boots', text: 'Walk 10% faster', costs: [70, 190, 450] } + ]; + var SACK = [30, 55, 90, 140, 210, 320], HAND_RATE = [9, 14, 21, 30, 42], HAND_REACH = [0.95, 1.1, 1.25, 1.45, 1.7]; + var RAKE_W = [1.0, 1.4, 1.9, 2.5], BLOW_P = [15, 22, 31, 42], BLOW_R = [4.5, 5.8, 7.2, 9], BLOW_H = [0.3, 0.36, 0.42, 0.5]; + WR.sackCap = function (s) { return SACK[s.up.sack]; }; WR.rakeWidth = function (s) { return RAKE_W[s.up.rakeW]; }; + var TOOL_NAMES = ['Hands', 'Rake', 'Blower']; + + /* ---------- saved state ---------- */ + function fresh(set) { + return { v: 1, acorns: 0, earned: 0, up: { sack: 0, hands: 0, rake: 0, rakeW: 0, blower: 0, power: 0, nozzle: 0, value: 0, shoes: 0 }, + unlocked: [1, 0, 0, 0, 0], done: [0, 0, 0, 0, 0], rewards: {}, bagUnits: [0, 0, 0, 0, 0], bagFill: 0, gone: [0, 0, 0, 0, 0], tool: 0, tut: 0, pos: null, + set: set || { sens: 1, vol: 0.7, q: null, inv: false, picked: false }, leaves: null, leafMul: 0, secs: 0, binFill: 0 }; + } + var state = fresh(); + try { var raw = JSON.parse(localStorage.getItem(KEY) || 'null'); if (raw && raw.v === 1) { var f = fresh(); for (var k in f) if (raw[k] != null) state[k] = raw[k]; for (k in f.up) if (state.up[k] == null) state.up[k] = 0; for (k in f.set) if (state.set[k] == null) state.set[k] = f.set[k]; } } catch (e) {} + var touchDev = window.matchMedia && matchMedia('(pointer:coarse)').matches, touchUI = false; + if (!state.set.q) state.set.q = touchDev ? 'low' : 'medium'; + var dirty = false, saveT = 0; + function save() { + if (!leaves) return; + state.pos = { x: +p.x.toFixed(2), z: +p.z.toFixed(2), yaw: +p.yaw.toFixed(3) }; + state.leaves = leaves.serialize(); state.leafMul = leaves.mul; state.gone = A.map(function (a, i) { return +leaves.share(i).toFixed(5); }); + try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) {} + dirty = false; saveT = 0; + } + + /* ---------- scene ---------- */ + var canvas = $('view'), renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: !touchDev, powerPreference: 'high-performance' }); + renderer.autoClear = false; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; + var scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(72, 1, 0.08, 600); camera.rotation.order = 'YXZ'; + WR.buildGrid(state.unlocked); + var world = WR.buildWorld(scene), vm = WR.buildViewModels(scene, state), fx = new WR.Fx(scene, 90), leaves = null; + world.sun.shadow.autoUpdate = false; + world.gates.forEach(function (G) { if (state.unlocked[G.def.area]) { G.open = G.target = 1; } }); + var p = { x: WR.SPAWN.x, z: WR.SPAWN.z, y: 0, vy: 0, vx: 0, vz: 0, yaw: 0, pitch: -0.25, ground: true, eye: 1.62, bob: 0, stepD: 0 }; + if (state.pos && !WR.solidAt(state.pos.x, state.pos.z)) { p.x = state.pos.x; p.z = state.pos.z; p.yaw = state.pos.yaw || 0; } + function resize() { var w = canvas.clientWidth || innerWidth, h = canvas.clientHeight || innerHeight; renderer.setSize(w, h, false); camera.aspect = vm.cam.aspect = w / h; camera.fov = w < h ? 84 : 72; camera.updateProjectionMatrix(); vm.cam.updateProjectionMatrix(); needRender = true; } + var needRender = true; + function onGone(ar, w, how, idx) { + dirty = true; + if (how === 'bag') { state.bagUnits[ar] += w; state.bagFill += 1 / leaves.mul; Au.pick(); bagDirty = true; } + else { pay(w, 1); Au.chute(); var c = WR.CHUTES[idx]; if (Math.random() < .3) fx.spawn(c.x + (Math.random() - .5), .1, c.z + (Math.random() - .5), 0, 1.2, 0, .5, A[ar].pal[0], .16); if (state.tut === 4) tutNext(5); } + } + function applyQuality() { + var q = state.set.q; + renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, q === 'high' ? 2 : q === 'medium' ? 1.5 : 1)); + world.sun.castShadow = q === 'high'; world.blobs.visible = q !== 'high'; world.sun.shadow.needsUpdate = true; + if (leaves) { state.gone = A.map(function (a, i) { return leaves.share(i); }); leaves.dispose(); state.leaves = null; } + leaves = WR.leaves = new WR.Leaves(scene, state, WR.QUALITY[q]); leaves.onGone = onGone; needRender = true; + } + applyQuality(); resize(); addEventListener('resize', resize); addEventListener('orientationchange', function () { setTimeout(resize, 200); }); + + /* ---------- controls ---------- */ + var KB = Keybinds.create({ game: 'windrow', actions: [ + { id: 'fwd', label: 'Walk forward', group: 'Move', keys: ['KeyW', 'ArrowUp'] }, { id: 'back', label: 'Walk back', group: 'Move', keys: ['KeyS', 'ArrowDown'] }, + { id: 'left', label: 'Step left', group: 'Move', keys: ['KeyA', 'ArrowLeft'] }, { id: 'right', label: 'Step right', group: 'Move', keys: ['KeyD', 'ArrowRight'] }, + { id: 'jump', label: 'Jump', group: 'Move', keys: ['Space'] }, { id: 'sprint', label: 'Sprint', note: 'After you earn the running shoes', group: 'Move', keys: ['ShiftLeft'] }, + { id: 'kneel', label: 'Kneel', note: 'After you earn the knee pads', group: 'Move', keys: ['KeyC'] }, + { id: 'use', label: 'Empty sack or open a gate', group: 'Work', keys: ['KeyE'] }, { id: 'tool1', label: 'Hands', group: 'Work', keys: ['Digit1'] }, + { id: 'tool2', label: 'Rake', group: 'Work', keys: ['Digit2'] }, { id: 'tool3', label: 'Blower', group: 'Work', keys: ['Digit3'] }, + { id: 'next', label: 'Next tool', group: 'Work', keys: ['KeyQ'] }, { id: 'find', label: 'Leaf finder', group: 'Work', keys: ['KeyF'] }, + { id: 'journal', label: 'Journal and shed', group: 'Work', keys: ['Tab', 'KeyJ'] }, { id: 'pause', label: 'Pause', group: 'Work', keys: ['Escape'], fixed: true } + ], classes: { button: 'btn sm', primary: 'btn sm go' } }); + var keys = new Set(), useHeld = false, mouseUse = false, touchUse = false, stick = { x: 0, y: 0, id: -1 }, lookId = -1, lookX = 0, lookY = 0, sprintT = false, kneelT = false, wasLocked = false; + var ov = ['title'], inGame = false; + function playing() { return inGame && !ov.length; } + function setTouch() { if (touchUI) return; touchUI = true; document.body.classList.add('touch'); $('howTouch').hidden = false; hudStatic(); } + addEventListener('touchstart', setTouch, { passive: true }); + addEventListener('keydown', function (e) { + if (KB.busy()) return; + if (e.code === 'Escape') { if (ov.length && ov[0] !== 'title' || ov.length > 1) closeTop(); else if (playing()) pause(); return; } + if (!inGame) return; + if (KB.is('journal', e.code)) { e.preventDefault(); if (playing()) open('journal'); else if (ov[ov.length - 1] === 'journal') closeTop(); return; } + if (!playing()) return; + if (e.code === 'Space' || e.code.indexOf('Arrow') === 0) e.preventDefault(); + if (e.repeat) return; + keys.add(e.code); + if (KB.is('jump', e.code)) jump(); + if (KB.is('use', e.code)) interact(); + if (KB.is('tool1', e.code)) setTool(0); if (KB.is('tool2', e.code)) setTool(1); if (KB.is('tool3', e.code)) setTool(2); + if (KB.is('next', e.code)) nextTool(1); + if (KB.is('find', e.code)) toggleFinder(); + }); + addEventListener('keyup', function (e) { keys.delete(e.code); }); + addEventListener('blur', function () { keys.clear(); mouseUse = false; }); + canvas.addEventListener('mousedown', function (e) { + if (!playing() || touchUI) return; Au.init(); + if (document.pointerLockElement !== canvas) { lock(); if (e.button === 0) mouseUse = true; return; } + if (e.button === 0) mouseUse = true; + }); + addEventListener('mouseup', function (e) { if (e.button === 0) mouseUse = false; }); + addEventListener('mousemove', function (e) { + if (!playing() || document.pointerLockElement !== canvas) return; + look(e.movementX * 0.0022, e.movementY * 0.0022); + }); + canvas.addEventListener('wheel', function (e) { if (playing()) nextTool(e.deltaY > 0 ? 1 : -1); }, { passive: true }); + function look(dx, dy) { var s = state.set.sens; p.yaw -= dx * s; p.pitch -= dy * s * (state.set.inv ? -1 : 1); if (p.pitch > 1.45) p.pitch = 1.45; if (p.pitch < -1.45) p.pitch = -1.45; } + function lock() { if (touchUI || !canvas.requestPointerLock) return; try { var r = canvas.requestPointerLock(); if (r && r.catch) r.catch(function () {}); } catch (e) {} } + document.addEventListener('pointerlockchange', function () { + if (document.pointerLockElement === canvas) wasLocked = true; + else if (wasLocked && playing() && !touchUI) { wasLocked = false; pause(); } + }); + // touch: left stick walks, a drag anywhere else looks, Use is held (and still looks while held) + function bindHold(el, down, up, moveLook) { + var id = -1, lx = 0, ly = 0; + el.addEventListener('pointerdown', function (e) { e.preventDefault(); id = e.pointerId; lx = e.clientX; ly = e.clientY; try { el.setPointerCapture(id); } catch (x) {} el.classList.add('down'); Au.init(); down && down(e); }); + el.addEventListener('pointermove', function (e) { if (e.pointerId !== id || !moveLook) return; look((e.clientX - lx) * 0.0052, (e.clientY - ly) * 0.0052); lx = e.clientX; ly = e.clientY; }); + function end(e) { if (e.pointerId !== id) return; id = -1; el.classList.remove('down'); up && up(e); } + el.addEventListener('pointerup', end); el.addEventListener('pointercancel', end); + } + (function () { + var st = $('tStick'), nub = st.firstElementChild; + function mv(e) { var r = st.getBoundingClientRect(), dx = e.clientX - (r.left + r.width / 2), dy = e.clientY - (r.top + r.height / 2), m = r.width * 0.4, d = Math.hypot(dx, dy); if (d > m) { dx *= m / d; dy *= m / d; } stick.x = dx / m; stick.y = dy / m; nub.style.transform = 'translate(' + dx + 'px,' + dy + 'px)'; } + st.addEventListener('pointerdown', function (e) { e.preventDefault(); stick.id = e.pointerId; try { st.setPointerCapture(e.pointerId); } catch (x) {} mv(e); Au.init(); }); + st.addEventListener('pointermove', function (e) { if (e.pointerId === stick.id) mv(e); }); + function end(e) { if (e.pointerId !== stick.id) return; stick.id = -1; stick.x = stick.y = 0; nub.style.transform = ''; } + st.addEventListener('pointerup', end); st.addEventListener('pointercancel', end); + canvas.addEventListener('pointerdown', function (e) { if (e.pointerType === 'mouse' || !playing()) return; setTouch(); lookId = e.pointerId; lookX = e.clientX; lookY = e.clientY; try { canvas.setPointerCapture(e.pointerId); } catch (x) {} Au.init(); }); + canvas.addEventListener('pointermove', function (e) { if (e.pointerId !== lookId) return; look((e.clientX - lookX) * 0.0052, (e.clientY - lookY) * 0.0052); lookX = e.clientX; lookY = e.clientY; }); + function lend(e) { if (e.pointerId === lookId) lookId = -1; } + canvas.addEventListener('pointerup', lend); canvas.addEventListener('pointercancel', lend); + bindHold($('tUse'), function () { touchUse = true; }, function () { touchUse = false; }, true); + bindHold($('tJump'), function () { jump(); }, null, true); + bindHold($('tSprint'), function () { sprintT = !sprintT; if (sprintT) kneelT = false; touchToggles(); }); + bindHold($('tKneel'), function () { kneelT = !kneelT; if (kneelT) sprintT = false; touchToggles(); }); + bindHold($('tAct'), function () { interact(); }); + bindHold($('tFind'), function () { toggleFinder(); }); + bindHold($('tJournal'), function () { open('journal'); }); + bindHold($('tPause'), function () { pause(); }); + Array.prototype.forEach.call(document.querySelectorAll('.slot'), function (b) { b.addEventListener('click', function () { setTool(+b.dataset.tool); b.blur(); }); }); + })(); + function touchToggles() { $('tSprint').classList.toggle('on', sprintT); $('tKneel').classList.toggle('on', kneelT); } + + /* ---------- player ---------- */ + function jump() { if (!playing() || !p.ground) return; p.vy = state.rewards.spring ? 5.65 : 4.6; p.ground = false; Au.jump(); } + var kneeling = false, speedNow = 0; + function movePlayer(dt) { + var f = (KB.held('fwd', keys) ? 1 : 0) - (KB.held('back', keys) ? 1 : 0) - stick.y, s = (KB.held('right', keys) ? 1 : 0) - (KB.held('left', keys) ? 1 : 0) + stick.x; + var m = Math.hypot(f, s); if (m > 1) { f /= m; s /= m; m = 1; } + kneeling = !!state.rewards.crouch && (KB.held('kneel', keys) || kneelT); + var sprint = !!state.rewards.sprint && !kneeling && (KB.held('sprint', keys) || sprintT) && f > 0.2; + var sp = 4.1 * (1 + 0.1 * state.up.shoes) * (kneeling ? 0.45 : sprint ? 1.6 : 1); + var sy = Math.sin(p.yaw), cy = Math.cos(p.yaw), tx = (-sy * f + cy * s) * sp, tz = (-cy * f - sy * s) * sp, k = Math.min(1, dt * (p.ground ? 12 : 3)); + p.vx += (tx - p.vx) * k; p.vz += (tz - p.vz) * k; + var ox = p.x, oz = p.z; p.x += p.vx * dt; p.z += p.vz * dt; WR.collide(p, 0.34); + if (!p.ground) { p.vy -= 13 * dt; p.y += p.vy * dt; if (p.y <= 0) { p.y = 0; p.vy = 0; p.ground = true; Au.step(WR.gtype[WR.cellOf(p.x, p.z)] === 2); leaves.kick(p.x, p.z, 0.7, 0, 0); } } + var moved = Math.hypot(p.x - ox, p.z - oz); speedNow = moved / Math.max(dt, 1e-4); + if (p.ground && moved > 0.001) { + p.stepD += moved; p.bob += moved * 3.3; + if (p.stepD > (sprint ? 2.6 : 2.0)) { p.stepD = 0; Au.step(WR.gtype[WR.cellOf(p.x, p.z)] === 2); } + if (speedNow > 0.8) leaves.kick(p.x, p.z, 0.42, p.vx, p.vz); + if (state.tut === 0) { tutMove += moved; if (tutMove > 4) tutNext(1); } + } + var eyeT = kneeling ? 0.95 : 1.62; p.eye += (eyeT - p.eye) * Math.min(1, dt * 9); + camera.position.set(p.x, p.y + p.eye + Math.sin(p.bob) * 0.022 * Math.min(1, speedNow / 3), p.z); camera.rotation.set(p.pitch, p.yaw, 0); + } + var tutMove = 0; + + /* ---------- tools ---------- */ + var tool = state.tool || 0, toolT = 0, rakeT = 0, rakeHead = { x: 0, z: 0, has: false }, handAcc = 0, handAnim = 0, blowAnim = 0, scraping = false, blowing = false, fullT = 0, bagDirty = true; + var bagPos = new THREE.Vector3(), fwd = new THREE.Vector3(), tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(); + function owns(t) { return t === 0 || (t === 1 && state.up.rake) || (t === 2 && state.up.blower); } + function setTool(t) { if (!owns(t)) { toast(T(t === 1 ? 'Buy the rake in the shed first' : 'Buy the blower in the shed first')); Au.no(); return; } if (tool !== t) { tool = state.tool = t; toolT = 0; Au.click(); hudStatic(); } } + function nextTool(d) { for (var i = 1; i <= 3; i++) { var t = (tool + d * i + 9) % 3; if (owns(t)) { setTool(t); return; } } } + function useTools(dt) { + var using = (mouseUse || touchUse) && playing(); toolT += dt; scraping = false; blowing = false; + camera.getWorldDirection(fwd); + var sy = Math.sin(p.yaw), cy = Math.cos(p.yaw), fx2 = -sy, fz2 = -cy, rx = cy, rz = -sy, cap = SACK[state.up.sack]; + bagPos.set(p.x - rx * 0.3 + fx2 * 0.3, p.y + p.eye - 0.5, p.z - rz * 0.3 + fz2 * 0.3); + vm.hands.visible = tool === 0; vm.blower.visible = tool === 2; vm.rake.visible = vm.handle.visible = tool === 1; vm.ring.visible = false; vm.air.visible = false; + var raise = Math.min(1, toolT * 5); + if (tool === 0) { + // where the hands reach: where you are looking on the ground, no farther than an arm and a bit + var reach = HAND_REACH[state.up.hands], maxD = 2.3 + reach * 0.4, d = maxD; + if (fwd.y < -0.05) d = Math.min(maxD, Math.max(0.5, (p.y + p.eye) / -fwd.y * Math.hypot(fwd.x, fwd.z))); + var tx = p.x + fx2 * d, tz = p.z + fz2 * d; + vm.ring.visible = true; vm.ring.position.set(tx, 0.035, tz); vm.ring.scale.setScalar(reach); + var room = Math.floor((cap - state.bagFill) * leaves.mul + 1e-6); + if (using) { + if (room <= 0) { fullT -= dt; if (fullT <= 0) { fullT = 2.5; toast(T('Sack full. Empty it at a bin with a red flag')); Au.full(); } } + else { + handAcc += HAND_RATE[state.up.hands] * leaves.mul * (kneeling ? 2 : 1) * dt * 1.15; var n = Math.floor(handAcc); + if (n > 0) { handAcc -= n; var took = leaves.scoop(tx, tz, reach, Math.min(n, room), p.x, p.z); if (took) { handAnim = 1; tutPicked += took / leaves.mul; if (state.tut === 1 && tutPicked >= 12) tutNext(2); } } + } + } else handAcc = 0; + handAnim = Math.max(0, handAnim - dt * 3); + var sw = using ? Math.sin(toolT * 13) : 0; + vm.rh.position.set(0.25 - handAnim * 0.06, -0.24 - (using ? 0.05 : 0) + sw * 0.03 + (raise - 1) * 0.3, -0.5 - (using ? 0.12 : 0) - sw * 0.04); + vm.ring.material.opacity = using ? 0.8 : 0.4; + } else if (tool === 1) { + // a stroke: reach out with the head lifted, drop it, drag it back along the ground + var W = RAKE_W[state.up.rakeW], near = 0.95, far = 2.75, dist, lift, pulling = false; + if (using) { rakeT += dt; var ph = rakeT % 0.8; if (ph < 0.28) { var u = ph / 0.28; dist = near + (far - near) * u; lift = 0.3 * Math.sin(u * Math.PI) + 0.04; } else { var u2 = (ph - 0.28) / 0.52; dist = far - (far - near) * (1 - (1 - u2) * (1 - u2)); lift = 0; pulling = true; } } + else { rakeT = 0; dist = 1.5; lift = 0.1; } + var free = leaves.freeDist(p.x, p.z, fx2, fz2, dist + 0.2) - 0.2; if (dist > free) dist = Math.max(0.5, free); + var hx = p.x + fx2 * dist, hz = p.z + fz2 * dist; + if (pulling && rakeHead.has && dt > 0) { + var hvx = (hx - rakeHead.x) / dt, hvz = (hz - rakeHead.z) / dt, hs = Math.hypot(hvx, hvz); if (hs > 9) { hvx *= 9 / hs; hvz *= 9 / hs; } + var hit = leaves.rake(hx - rx * W / 2, hz - rz * W / 2, hx + rx * W / 2, hz + rz * W / 2, 0.24, hvx, hvz); scraping = hit > 0; + } + rakeHead.x = hx; rakeHead.z = hz; rakeHead.has = pulling; + vm.rake.position.set(hx, lift, hz); vm.rake.rotation.y = p.yaw; + tmp.set(p.x + rx * 0.26 + fx2 * 0.2, p.y + p.eye - 0.42 - (1 - raise) * 0.4, p.z + rz * 0.26 + fz2 * 0.2); tmp2.set(hx, lift + 0.16, hz); + vm.handle.position.copy(tmp); vm.handle.lookAt(tmp2); vm.handle.scale.z = tmp.distanceTo(tmp2); + } else { + var lv = state.up.nozzle, range = BLOW_R[lv], half = BLOW_H[lv]; + if (using) { + blowing = true; var dy = Math.max(-0.5, Math.min(0.12, fwd.y)), hl = Math.hypot(fwd.x, fwd.z) || 1, k = Math.sqrt(1 - dy * dy), dx = fwd.x / hl * k, dz = fwd.z / hl * k; + var ox = p.x + fx2 * 0.35, oz = p.z + fz2 * 0.35, oy = 0.42; + leaves.blow(ox, oy, oz, dx, dy * 0.5, dz, range, half, BLOW_P[state.up.power], dt); + vm.air.visible = true; vm.air.position.set(ox + rx * 0.2, p.y + p.eye - 0.5, oz + rz * 0.2); tmp.set(ox + dx * range, 0.3, oz + dz * range); vm.air.lookAt(tmp); + var rad = Math.tan(half) * range; vm.air.scale.set(rad, rad * 0.5, range); vm.air.material.opacity = 0.05 + 0.03 * Math.sin(toolT * 40); + if (state.tut === 4) tutBlow += dt; + } + blowAnim += ((using ? 1 : 0) - blowAnim) * Math.min(1, dt * 10); + vm.blower.position.set(0.3 + Math.sin(toolT * 47) * 0.004 * blowAnim, -0.3 + (raise - 1) * 0.3 + Math.sin(toolT * 61) * 0.004 * blowAnim, -0.42 + blowAnim * 0.02); + } + vm.hands.position.y = tool === 0 ? Math.sin(p.bob) * 0.008 : 0; + } + var tutPicked = 0, tutBlow = 0; + + /* ---------- bins, gates, money ---------- */ + var gainAcc = 0, gainT = 0, prompt = null; + function pay(units, mult) { var amt = units * (1 + 0.15 * state.up.value) * mult; state.acorns += amt; state.earned += amt; gainAcc += amt; gainT = 1.6; dirty = true; acDirty = true; return amt; } + var acDirty = true; + function findPrompt() { + var best = null, i, d; + if (state.bagFill > 0.01) for (i = 0; i < WR.BINS.length; i++) { var b = WR.BINS[i]; d = Math.hypot(b.x - p.x, b.z - p.z); if (d < 2.6 && (!best || d < best.d)) best = { type: 'bin', i: i, d: d, ok: true, text: T('Empty your sack') }; } + for (i = 0; i < WR.GATES.length; i++) { var g = WR.GATES[i], a = A[g.area]; if (state.unlocked[g.area]) continue; d = Math.hypot(g.x - p.x, g.z - p.z); if (d > 3.6 || (best && best.d < d)) continue; + var need = a.need && leaves.share(a.need[0]) < a.need[1]; + best = need ? { type: 'gate', d: d, ok: false, text: T('Clear half of {a} to open this gate', { a: T(A[a.need[0]].name) }) } + : state.acorns < a.cost ? { type: 'gate', d: d, ok: false, text: T('{a}: opens for {n} acorns', { a: T(a.name), n: a.cost }) } + : { type: 'gate', area: g.area, d: d, ok: true, text: T('Open {a} for {n} acorns', { a: T(a.name), n: a.cost }) }; } + return best; + } + function interact() { + if (!playing() || !prompt || !prompt.ok) return; + if (prompt.type === 'bin') emptyBag(prompt.i); else unlock(prompt.area); + } + function emptyBag(bi) { + var units = 0, cap = SACK[state.up.sack], full = state.bagFill >= cap * 0.95, b = WR.BINS[bi]; + for (var i = 0; i < 5; i++) { units += state.bagUnits[i]; state.bagUnits[i] = 0; } + var n = Math.min(40, Math.round(state.bagFill / 3) + 6); + for (i = 0; i < n; i++) fx.spawn(b.x + (Math.random() - .5) * .8, 1.5 + Math.random() * .8, b.z + (Math.random() - .5) * .8, (Math.random() - .5), -0.5 - Math.random(), (Math.random() - .5), 1.1 + Math.random() * .5, A[(Math.random() * 5) | 0].pal[(Math.random() * 5) | 0], .22, 0.5); + state.binFill = Math.min(1, (state.binFill || 0) + state.bagFill / 2500); world.bins.forEach(function (B) { B.heap.scale.y = 0.3 + state.binFill * 0.9; }); + state.bagFill = 0; bagDirty = true; var amt = pay(units, full ? 1.2 : 1); Au.bin(); Au.coin(); + toast(T('+{n} acorns', { n: Math.round(amt) }) + (full ? ' · ' + T('full sack bonus') : '')); + if (state.tut === 2) tutNext(3); + vm.refresh(); checkDone(); save(); + } + function unlock(ai) { + var a = A[ai]; if (state.unlocked[ai] || state.acorns < a.cost) { Au.no(); return false; } + if (a.need && leaves.share(a.need[0]) < a.need[1]) { Au.no(); return false; } + state.acorns -= a.cost; state.unlocked[ai] = 1; WR.openGate(ai); world.gates.forEach(function (G) { if (G.def.area === ai) G.target = 1; }); world.refreshSigns(state); + Au.gate(); Au.buy(); toast(T('{a} is open', { a: T(a.name) }), true); acDirty = true; save(); return true; + } + function buy(id) { + var u = UP.filter(function (x) { return x.id === id; })[0], lv = state.up[id]; if (!u || lv >= u.costs.length) return; + if (u.needs && !state.up[u.needs]) return; var c = u.costs[lv]; if (state.acorns < c) { Au.no(); return; } + state.acorns -= c; state.up[id]++; Au.buy(); acDirty = bagDirty = true; vm.refresh(); hudStatic(); + if (id === 'rake') { tool = state.tool = 1; toast(T('Rake bought. Hold to pull leaves toward you')); } if (id === 'blower') { tool = state.tool = 2; toast(T('Blower bought. Hold to push leaves away')); } + if (state.tut === 3) tutNext(4); + save(); renderJournal(); + } + function checkDone() { + for (var i = 0; i < 5; i++) { + if (!state.unlocked[i] || state.done[i]) continue; + if (leaves.alive[i] > 0 || state.bagUnits[i] > 1e-6) continue; + state.done[i] = 1; var a = A[i]; state.acorns += a.bonus; state.earned += a.bonus; state.rewards[a.reward] = 1; acDirty = true; + toast(T('{a} is clear!', { a: T(a.name) }) + '' + T('+{n} acorns', { n: a.bonus }) + ' · ' + T(a.rewardName) + ': ' + T(rewardText(a)) + '', true, 7); + Au.fanfare(); vm.refresh(); hudStatic(); save(); + for (var k = 0; k < 40; k++) fx.spawn(p.x + (Math.random() - .5) * 5, 2.5 + Math.random() * 2, p.z + (Math.random() - .5) * 5, 0, 0, 0, 3, a.pal[k % 5], .26, 0.02); + } + } + function rewardText(a) { if (touchUI) { if (a.reward === 'sprint') return 'Tap Run to sprint'; if (a.reward === 'crouch') return 'Tap Kneel: hands gather twice as fast'; } return a.rewardText; } + + /* ---------- leaf finder ---------- */ + var finder = false, findT = 0, near = [], curArea = 0; + function toggleFinder() { finder = !finder; $('tFind').classList.toggle('on', finder); toast(T(finder ? 'Leaf finder on: lights mark the nearest leaves' : 'Leaf finder off')); findT = 0; } + function updateFinder(dt) { + findT -= dt; if (findT > 0) return; findT = 0.4; + var auto = leaves.alive[curArea] > 0 && leaves.alive[curArea] <= Math.max(6, leaves.counts[curArea] * 0.03), on = (finder || auto) && state.unlocked[curArea]; + if (on) leaves.nearest(p.x, p.z, curArea, 8, near); else near.length = 0; + for (var i = 0; i < 8; i++) { var b = vm.beacons[i]; if (i * 3 < near.length) { b.visible = true; b.position.set(near[i * 3], 0, near[i * 3 + 1]); } else b.visible = false; } + } + + /* ---------- HUD ---------- */ + var hudT = 0; + function toast(html, big, secs) { var d = document.createElement('div'); d.className = 'toast' + (big ? ' big' : ''); d.setAttribute('data-noi18n', ''); d.innerHTML = html; var box = $('toasts'); while (box.children.length > 2) box.removeChild(box.firstChild); box.appendChild(d); setTimeout(function () { if (d.parentNode) d.parentNode.removeChild(d); }, (secs || (big ? 4.5 : 2.6)) * 1000); } + function hudStatic() { + Array.prototype.forEach.call(document.querySelectorAll('.slot'), function (b) { var t = +b.dataset.tool; b.classList.toggle('on', t === tool); b.classList.toggle('locked', !owns(t)); }); + $('hKeys').innerHTML = '' + KB.short('journal') + ' ' + T('Journal') + '
' + KB.short('find') + ' ' + T('Leaf finder') + '
Esc ' + T('Pause'); + $('tSprint').hidden = !state.rewards.sprint; $('tKneel').hidden = !state.rewards.crouch; + $('howKeys').textContent = T('{m} to walk, mouse to look, hold the left button to work, {j} to jump. {a} to switch tools, {e} at a bin or gate, {t} for the journal.', { m: KB.label(['fwd', 'left', 'back', 'right'], ' ', '', 1), j: KB.short('jump'), a: '1 2 3', e: KB.short('use'), t: KB.short('journal') }); + tutShow(); + } + KB.onChange(hudStatic); + function hud(dt) { + hudT -= dt; gainT -= dt; + if (acDirty) { acDirty = false; var el = $('acN'); el.textContent = Math.floor(state.acorns); el.classList.remove('pop'); void el.offsetWidth; el.classList.add('pop'); } + if (bagDirty) { bagDirty = false; var cap = SACK[state.up.sack], f = Math.min(1, state.bagFill / cap); $('bagBar').style.width = (f * 100) + '%'; $('bagN').textContent = Math.min(cap, Math.round(state.bagFill)) + '/' + cap; $('hBag').classList.toggle('full', f >= 0.999); vm.refresh(); } + var g = $('gain'); if (gainT > 0) { g.textContent = '+' + (gainAcc < 10 ? gainAcc.toFixed(1) : Math.round(gainAcc)); g.classList.add('on'); } else if (gainAcc) { gainAcc = 0; g.classList.remove('on'); } + if (hudT > 0) return; hudT = 0.2; + var c = WR.areaOf[WR.cellOf(p.x, p.z)]; if (c >= 0) curArea = c; + var sh = leaves.share(curArea), left = leaves.alive[curArea]; + $('arName').textContent = T(A[curArea].name); $('arBar').style.width = (sh * 100) + '%'; $('arPct').textContent = (sh >= 1 ? 100 : Math.min(99, Math.floor(sh * 100))) + '%'; + var al = $('arLeft'), show = !state.done[curArea] && left <= 60; + al.hidden = !show; if (show) al.textContent = left > 0 ? T(left === 1 ? '1 leaf left' : '{n} leaves left', { n: left }) : T('The last leaves are in your sack'); + prompt = findPrompt(); + var hp = $('hPrompt'), ta = $('tAct'); + if (prompt) { hp.hidden = false; hp.classList.toggle('act', !!prompt.ok); hp.innerHTML = (prompt.ok ? '' + KB.short('use') + '' : '') + prompt.text; ta.hidden = !prompt.ok; if (prompt.ok) ta.textContent = prompt.text; } + else { hp.hidden = true; ta.hidden = true; } + checkDone(); + if (state.tut === 4 && tutBlow > 1.5) tutNext(5); + } + /* ---------- tutorial ---------- */ + function tutText() { + var t = touchUI; + return [ + t ? 'Left thumb walks. Drag anywhere else to look around.' : T('Click to look around. Walk with {k}.', { k: KB.label(['fwd', 'left', 'back', 'right'], ' ', '', 1) }), + t ? 'Look down at some leaves and hold Use to gather them into your sack.' : 'Look down at some leaves and hold the left mouse button to gather them into your sack.', + t ? 'Carry them to the compost bin with the red flag and tap Empty your sack.' : T('Carry them to the compost bin with the red flag and press {k}.', { k: KB.short('use') }), + t ? 'Tap the book, open the Shed and buy something with your acorns.' : T('Press {k}, open the Shed and buy something with your acorns.', { k: KB.short('journal') }), + 'Leaves that reach a yellow grate are paid for at once. Rake or blow them onto it.' + ][state.tut]; + } + function tutShow() { var s = tutText(); $('hTut').hidden = !s; if (s) $('tutText').textContent = T(s); } + function tutNext(n) { if (state.tut >= n) return; state.tut = n; dirty = true; tutShow(); if (n < 5) Au.click(); } + $('tutSkip').addEventListener('click', function () { tutNext(5); }); + + /* ---------- menus ---------- */ + function showOv() { ['title', 'pause', 'journal', 'settings', 'how'].forEach(function (id) { $(id).hidden = ov[ov.length - 1] !== id; }); $('hud').hidden = !inGame || ov.length > 0; } + function open(id) { + if (playing()) { save(); keys.clear(); mouseUse = touchUse = false; if (document.pointerLockElement) { wasLocked = false; document.exitPointerLock(); } } + ov.push(id); showOv(); Au.click(); + if (id === 'journal') renderJournal(); if (id === 'settings') fillSettings(); + Au.frame && Au.ready && Au.frame(0.016, 0, false, false, 0); + } + function closeTop() { + var id = ov.pop(); if (id === 'title' && !inGame) { ov.push('title'); return; } + showOv(); Au.click(); if (!ov.length) resume(); + } + function pause() { if (!playing()) return; open('pause'); } + function resume() { ov.length = 0; inGame = true; showOv(); Au.init(); lock(); last = performance.now(); hudStatic(); acDirty = bagDirty = true; hudT = 0; } + $('playBtn').addEventListener('click', function () { world.refreshSigns(state); resume(); }); + $('resumeBtn').addEventListener('click', function () { closeTop(); }); + $('howBtn').addEventListener('click', function () { open('how'); }); $('pHow').addEventListener('click', function () { open('how'); }); + $('setBtn').addEventListener('click', function () { open('settings'); }); $('pSet').addEventListener('click', function () { open('settings'); }); + $('pJournal').addEventListener('click', function () { open('journal'); }); + $('pTitle').addEventListener('click', function () { save(); inGame = false; ov = ['title']; showOv(); titleText(); }); + $('jClose').addEventListener('click', closeTop); $('sClose').addEventListener('click', closeTop); $('hClose').addEventListener('click', closeTop); + function titleText() { $('playBtn').textContent = T(state.earned > 0 || state.tut > 0 ? 'Carry on sweeping' : 'Start sweeping'); } + // settings + function fillSettings() { $('sSens').value = state.set.sens; $('sVol').value = state.set.vol; $('sQ').value = state.set.q; $('sInv').checked = !!state.set.inv; } + $('sSens').addEventListener('input', function () { state.set.sens = +this.value; dirty = true; }); + $('sVol').addEventListener('input', function () { state.set.vol = +this.value; Au.init(); Au.setVol(state.set.vol); Au.click(); dirty = true; }); + $('sInv').addEventListener('change', function () { state.set.inv = this.checked; dirty = true; }); + $('sQ').addEventListener('change', function () { state.set.q = this.value; state.set.picked = true; applyQuality(); save(); }); + $('sFull').addEventListener('click', function () { var el = document.documentElement; if (document.fullscreenElement) document.exitFullscreen(); else if (el.requestFullscreen) el.requestFullscreen().catch(function () {}); else toast(T('Full screen is not available in this browser')); }); + $('sKeys').addEventListener('click', function () { KB.open(); }); + $('sReset').addEventListener('click', function () { + if (!confirm(T('Start over? Every garden fills with leaves again and your acorns and tools are gone.'))) return; + var set = state.set; state = fresh(set); dirty = false; leaves = null; + try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) {} + location.reload(); + }); + // journal: the map, the gardens and the shed + var tab = 'areas'; + Array.prototype.forEach.call(document.querySelectorAll('.tabs .btn'), function (b) { b.addEventListener('click', function () { tab = b.dataset.tab; renderJournal(); Au.click(); }); }); + function pips(lv, max) { var s = ''; for (var i = 0; i < max; i++) s += ''; return s + ''; } + function renderJournal() { + if (ov[ov.length - 1] !== 'journal') return; + Array.prototype.forEach.call(document.querySelectorAll('.tabs .btn'), function (b) { b.classList.toggle('on', b.dataset.tab === tab); }); + $('jPurse').textContent = Math.floor(state.acorns) + ' ' + T('acorns'); + var h = '', side = $('jSide'); side.setAttribute('data-noi18n', ''); + if (tab === 'areas') { + A.forEach(function (a, i) { + var sh = leaves.share(i), un = state.unlocked[i], need = a.need && leaves.share(a.need[0]) < a.need[1]; + h += '
' + T(a.name) + (un ? ' · ' + (sh >= 1 ? 100 : Math.floor(sh * 100)) + '%' : '') + ''; + if (state.done[i]) h += '✓ ' + T('Clear') + ' · ' + T(a.rewardName) + ''; + else if (un) h += '' + T('Clear it all: +{n} acorns and {r}', { n: a.bonus, r: T(a.rewardName) }) + ''; + else h += '' + (need ? T('First clear half of {a}', { a: T(A[a.need[0]].name) }) : T('Reward for clearing: {r}', { r: T(a.rewardName) })) + ''; + h += '
' + (un ? '' : '') + '
'; + }); + } else { + UP.forEach(function (u) { + var lv = state.up[u.id], max = u.costs.length, lockd = u.needs && !state.up[u.needs]; + h += '
' + T(u.name) + (max > 1 ? pips(lv, max) : '') + '' + T(u.text) + '
'; + h += lv >= max ? '✓ ' + T(max > 1 ? 'Best' : 'Owned') + '' : ''; + h += '
'; + }); + } + side.innerHTML = h; + Array.prototype.forEach.call(side.querySelectorAll('[data-buy]'), function (b) { b.addEventListener('click', function () { buy(b.dataset.buy); }); }); + Array.prototype.forEach.call(side.querySelectorAll('[data-unlock]'), function (b) { b.addEventListener('click', function () { if (unlock(+b.dataset.unlock)) renderJournal(); }); }); + drawMap(); + } + function drawMap() { + var c = $('map'), g = c.getContext('2d'), S = 10; function X(x) { return (x + 40) * S; } function Z(z) { return (z + 30) * S; } + g.fillStyle = '#8c6a4a'; g.fillRect(0, 0, c.width, c.height); + var gc = ['#86a85c', '#c9c2b0', '#c79a62', '#d6c8a4']; + A.forEach(function (a, i) { g.fillStyle = gc[a.ground]; g.fillRect(X(a.x0) + 3, Z(a.z0) + 3, (a.x1 - a.x0) * S - 6, (a.z1 - a.z0) * S - 6); }); + g.fillStyle = '#5f93a0'; g.beginPath(); g.arc(X(24), Z(10), 38, 0, 7); g.fill(); g.beginPath(); g.arc(X(0), Z(9), 21, 0, 7); g.fill(); + g.fillStyle = 'rgba(207,233,238,.9)'; g.fillRect(X(15.5), Z(-25), 60, 160); g.fillRect(X(26.5), Z(-25), 60, 160); + g.fillStyle = '#3c6a36'; [[-34, -18, -21, -20], [-34, -33, -20, -6], [-28, -12.25, -9, -8], [-22, -21, -8, 6], [-40, -28, 4, 5], [-21, -16, 5, 6], [-30, -29, 10, 20], [-16, -15, -2, 14]].forEach(function (h) { g.fillRect(X(h[0]), Z(h[2]), (h[1] - h[0]) * S, (h[3] - h[2]) * S); }); + g.fillStyle = 'rgba(190,110,40,.55)'; WR.TREES.forEach(function (t) { g.beginPath(); g.arc(X(t[0]), Z(t[1]), 13 * t[2], 0, 7); g.fill(); }); + g.fillStyle = '#6b3d1c'; leaves.eachAlive(function (x, z, ar) { if (state.unlocked[ar]) g.fillRect(X(x) - 1, Z(z) - 1, 2.4, 2.4); }); + WR.CHUTES.forEach(function (ch) { g.fillStyle = '#e0b53a'; g.fillRect(X(ch.x) - 8, Z(ch.z) - 8, 16, 16); g.fillStyle = '#17130f'; g.fillRect(X(ch.x) - 5, Z(ch.z) - 5, 10, 10); }); + WR.BINS.forEach(function (b) { g.fillStyle = '#6f4a2a'; g.fillRect(X(b.x) - 7, Z(b.z) - 7, 14, 14); g.fillStyle = '#e2572f'; g.beginPath(); g.moveTo(X(b.x), Z(b.z) - 20); g.lineTo(X(b.x) + 13, Z(b.z) - 14); g.lineTo(X(b.x), Z(b.z) - 8); g.fill(); g.fillRect(X(b.x) - 1, Z(b.z) - 20, 2, 16); }); + g.textAlign = 'center'; g.font = '800 17px Nunito, sans-serif'; + A.forEach(function (a, i) { + var cx = X((a.x0 + a.x1) / 2), cz = Z((a.z0 + a.z1) / 2); + if (!state.unlocked[i]) { g.fillStyle = 'rgba(40,32,20,.55)'; g.fillRect(X(a.x0) + 3, Z(a.z0) + 3, (a.x1 - a.x0) * S - 6, (a.z1 - a.z0) * S - 6); } + var label = T(a.name), sub = state.unlocked[i] ? (state.done[i] ? '✓ 100%' : Math.floor(leaves.share(i) * 100) + '%') : T('Locked') + ' · ' + a.cost, w = Math.max(g.measureText(label).width, g.measureText(sub).width) + 16; + g.fillStyle = 'rgba(246,236,212,.9)'; g.fillRect(cx - w / 2, cz - 24, w, 46); g.fillStyle = '#2e2416'; g.fillText(label, cx, cz - 5); g.fillStyle = state.done[i] ? '#3f6b52' : '#c4552d'; g.fillText(sub, cx, cz + 15); + }); + g.save(); g.translate(X(p.x), Z(p.z)); g.rotate(-p.yaw); g.fillStyle = '#fff'; g.strokeStyle = '#1d3b6a'; g.lineWidth = 3; g.beginPath(); g.moveTo(0, -13); g.lineTo(9, 10); g.lineTo(0, 5); g.lineTo(-9, 10); g.closePath(); g.fill(); g.stroke(); g.restore(); + } + document.addEventListener('backroom:lang', function () { world.refreshSigns(state); hudStatic(); titleText(); renderJournal(); hudT = 0; }); + + /* ---------- the frame ---------- */ + var last = performance.now(), frameN = 0, slowT = 0, avgMs = 16, magT = 0; + var autoDrive = false; + function update(dt) { + if (autoDrive) { p.yaw += dt * 0.9; keys.add('KeyW'); mouseUse = true; } + movePlayer(dt); useTools(dt); + if (state.rewards.magnet) { magT += dt; var n = WR.CHUTES.length, ch = WR.CHUTES[frameN % n]; if (Math.abs(ch.x - p.x) < 30 && Math.abs(ch.z - p.z) < 30) leaves.pull(ch.x, ch.z, 2.6, 5, dt * n); } + leaves.step(dt, bagPos); fx.step(dt); updateFinder(dt); hud(dt); + world.gates.forEach(function (G) { if (G.open !== G.target) { G.open += Math.sign(G.target - G.open) * dt * 0.9; if (Math.abs(G.open - G.target) < 0.02) G.open = G.target; world.sun.shadow.needsUpdate = true; } G.leaves.forEach(function (lf) { lf.piv.rotation.y = lf.side * G.open * 1.75; }); }); + Au.frame(dt, leaves.moved, scraping, blowing, state.up.power); + state.secs += dt; saveT += dt; if (dirty && saveT > 8) save(); + // a few leaves drifting off the trees, only for show + if (frameN % 50 === 0 && state.set.q !== 'low') { var t = WR.TREES[(Math.random() * WR.TREES.length) | 0]; if (Math.abs(t[0] - p.x) < 25 && Math.abs(t[1] - p.z) < 25) fx.spawn(t[0] + (Math.random() - .5) * 3, 3.5 + Math.random() * 1.5, t[1] + (Math.random() - .5) * 3, (Math.random() - .5) * .6, 0, (Math.random() - .5) * .6, 3.2, '#d98a2b', .22, 0.03); } + } + function draw() { + renderer.clear(); renderer.render(scene, camera); + if (playing() && tool !== 1) { renderer.clearDepth(); renderer.render(vm.scene, vm.cam); } + } + function frame(now) { + requestAnimationFrame(frame); + var ms = now - last, dt = Math.min(0.05, ms / 1000); last = now; frameN++; + if (document.hidden || dt <= 0) return; + if (playing()) { + update(dt); draw(); + avgMs += (ms - avgMs) * 0.03; + // still slow after the resolution has already dropped, and the player never chose: use fewer leaves + if (avgMs > 36 && (!window.AutoRes || AutoRes.scale <= 0.5) && !state.set.picked && state.set.q !== 'low') { slowT += dt; if (slowT > 8) { slowT = 0; avgMs = 16; state.set.q = state.set.q === 'high' ? 'medium' : 'low'; applyQuality(); toast(T('Fewer leaves drawn to keep things smooth. You can change this in Settings')); save(); } } else slowT = 0; + } else if (!inGame) { + if (frameN % 2 === 0) { var a = now * 0.00004; camera.position.set(Math.sin(a) * 4.5, 7.4, 14.5 + Math.cos(a) * 3); camera.lookAt(0, 0.6, 5); vm.ring.visible = vm.rake.visible = vm.handle.visible = vm.air.visible = false; draw(); } + } else if (needRender) { draw(); } + needRender = false; + } + document.addEventListener('visibilitychange', function () { if (document.hidden) { if (dirty || playing()) save(); Au.suspend(true); if (playing()) pause(); } else Au.suspend(false); }); + addEventListener('pagehide', function () { if (inGame) save(); }); + Au.vol = state.set.vol; world.bins.forEach(function (B) { B.heap.scale.y = 0.3 + (state.binFill || 0) * 0.9; }); + hudStatic(); titleText(); showOv(); world.refreshSigns(state); + if (document.fonts && document.fonts.ready) document.fonts.ready.then(function () { world.refreshSigns(state); }); + requestAnimationFrame(frame); + + // for the test scripts only (nothing in the game calls these) + WR.test = { state: function () { return state; }, p: p, start: function () { resume(); }, hold: function (on) { mouseUse = !!on; }, key: function (c, on) { if (on) keys.add(c); else keys.delete(c); }, + mul: function (m) { WR.QUALITY.bench = m; state.set.q = 'bench'; applyQuality(); }, auto: function (on) { autoDrive = on; }, + bench: function (steps) { var t0 = performance.now(), mx = 0, sum = 0; for (var i = 0; i < steps; i++) { update(1 / 60); var a = leaves.awakeCount(); sum += a; if (a > mx) mx = a; } return { ms: (performance.now() - t0) / steps, maxAwake: mx, avgAwake: Math.round(sum / steps), n: leaves.N }; }, + refresh: function () { hudStatic(); }, + step: function (n) { for (var i = 0; i < n; i++) update(1 / 60); }, + tool: setTool, give: function (n) { state.acorns += n; acDirty = true; }, buy: buy, unlock: unlock, interact: interact, open: open, close: closeTop, save: save, touch: setTouch, + info: function () { return { awake: leaves.awakeCount(), n: leaves.N, alive: leaves.alive.slice(), acorns: state.acorns, bag: state.bagFill, playing: playing(), prompt: prompt && prompt.text }; } }; +})(); diff --git a/e63334287a3deaa3/windrow/js/leaves.js b/e63334287a3deaa3/windrow/js/leaves.js new file mode 100644 index 00000000..eff9da76 --- /dev/null +++ b/e63334287a3deaa3/windrow/js/leaves.js @@ -0,0 +1,317 @@ +/* Windrow: the leaves. Every leaf is a real thing with a place, a speed and a tumble; nothing is deleted by pointing. + To stay cheap with thousands of them: + - leaves that have come to rest are "asleep" and cost nothing until a tool, a foot or a neighbour wakes them; + - each leaf lives in one 0.25 m grid cell (a linked list per cell), so tools only look at the cells they reach; + - leaves do not collide with each other one by one. A cell holds a stack: the more leaves in it, the higher the next + one rests, a full cell turns sliding leaves away, and a leaf on a tall stack slides off onto a lower neighbour. + That is what makes heaps against walls and windrows in front of the rake. + They are drawn as instanced meshes: one per area and leaf shape, so a whole area is four draw calls. */ +(function () { + 'use strict'; + var WR = window.WR, CELL = WR.CELL, GW = WR.GW, GH = WR.GH, X0 = WR.X0, Z0 = WR.Z0; + var CAP = 16, HARD = 34, LH = 0.014, BASE = 0.014; + var DEAD = 0, SLEEP = 1, AWAKE = 2, TOBAG = 3, SINK = 4; + var SHAPES = [ + { pts: [[0, -.5], [.22, -.15], [.2, .25]], big: 1 }, // oval, 6 triangles + { pts: [[0, -.55], [.09, -.05]], big: .95 }, // long and narrow, 4 + { pts: [[0, -.5], [.12, -.28], [.38, -.28], [.24, -.02], [.4, .16]], big: 1.2 }, // five points, 10 + { pts: [[0, -.5], [.15, -.3], [.1, -.12], [.24, .04], [.16, .3]], big: 1.1 } // lobed, 10 + ]; + function leafGeo(sh) { + var out = sh.pts.slice(), i; for (i = sh.pts.length - 1; i >= 1; i--) out.push([-sh.pts[i][0], sh.pts[i][1]]); + out.splice(sh.pts.length, 0, [0, .47]); + var p = [], c = [], n = out.length; + function y(x, z) { return 0.5 * x * x * 1.6 + 0.12 * z * z + 0.02; } + for (i = 0; i < n; i++) { var a = out[i], b = out[(i + 1) % n]; + p.push(0, .012, 0, b[0], y(b[0], b[1]), b[1], a[0], y(a[0], a[1]), a[1]); c.push(.72, .7, .66, 1, 1, 1, 1, 1, 1); } + var g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(c, 3)); g.computeVertexNormals(); return g; + } + + function Leaves(scene, state, mul) { + var self = this, A = WR.AREAS, counts = A.map(function (a) { return Math.max(40, Math.round(a.leaves * mul)); }), N = counts.reduce(function (s, v) { return s + v; }, 0); + this.N = N; this.counts = counts; this.mul = mul; this.scene = scene; + this.w = A.map(function (a, i) { return a.units / counts[i]; }); + this.alive = A.map(function () { return 0; }); + var px = this.px = new Float32Array(N), py = this.py = new Float32Array(N), pz = this.pz = new Float32Array(N); + var vx = new Float32Array(N), vy = new Float32Array(N), vz = new Float32Array(N); + var yaw = new Float32Array(N), pit = new Float32Array(N), rol = new Float32Array(N), spin = new Float32Array(N), rp = new Float32Array(N), rr = new Float32Array(N); + var scl = new Float32Array(N), off = new Float32Array(N), idle = new Float32Array(N), tmr = new Float32Array(N); + var st = this.st = new Uint8Array(N), area = this.area = new Uint8Array(N), rank = new Uint8Array(N), aux = new Int16Array(N); + var lcell = new Int32Array(N), next = new Int32Array(N), prev = new Int32Array(N), aidx = new Int32Array(N).fill(-1); + var meshOf = new Uint8Array(N), slot = new Uint16Array(N); + var head = new Int32Array(GW * GH).fill(-1), cnt = this.cnt = new Uint8Array(GW * GH); + var solid = WR.solid, gtype = WR.gtype, inlet = WR.inlet, FR = WR.GROUND_FRICTION; + var awake = new Int32Array(N), awakeN = 0; + this.awakeCount = function () { return awakeN; }; + var meshes = this.meshes = [], dirty = []; + var mat = new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.DoubleSide }); + var geos = SHAPES.map(leafGeo); + + // which shape, size, colour and mesh slot each leaf has (the same every visit: seeded by its number) + var r = WR.rng(4242), i = 0, perMesh = [], col = new THREE.Color(), cols = []; + A.forEach(function (a, ai) { + var base = meshes.length; for (var s = 0; s < 4; s++) perMesh.push(0); + for (var k = 0; k < counts[ai]; k++, i++) { + var q = r(), s2 = q < .34 ? 0 : q < .6 ? 1 : q < .8 ? 2 : 3; + area[i] = ai; meshOf[i] = base + s2; slot[i] = perMesh[base + s2]++; + scl[i] = (0.2 + r() * 0.12) * SHAPES[s2].big; off[i] = r() * 0.012; rp[i] = (r() - .5) * .5; rr[i] = (r() - .5) * .5; + col.set(a.pal[(r() * a.pal.length) | 0]); var b = 0.8 + r() * 0.35; cols.push(col.r * b, col.g * b, col.b * b); + } + for (s = 0; s < 4; s++) { + var m = new THREE.InstancedMesh(geos[s], mat, Math.max(1, perMesh[base + s])); m.instanceMatrix.setUsage(THREE.DynamicDrawUsage); + m.frustumCulled = true; m.receiveShadow = true; m.matrixAutoUpdate = false; + m.boundingSphere = new THREE.Sphere(new THREE.Vector3((a.x0 + a.x1) / 2, 0, (a.z0 + a.z1) / 2), Math.hypot(a.x1 - a.x0, a.z1 - a.z0) / 2 + 9); + m.instanceMatrix.array.fill(0); + meshes.push(m); dirty.push(true); scene.add(m); + } + }); + for (i = 0; i < N; i++) { col.setRGB(cols[i * 3], cols[i * 3 + 1], cols[i * 3 + 2]); meshes[meshOf[i]].setColorAt(slot[i], col); } + meshes.forEach(function (m) { if (m.instanceColor) m.instanceColor.needsUpdate = true; }); + + function cellOf(x, z) { var ci = Math.floor((x - X0) / CELL), cj = Math.floor((z - Z0) / CELL); return (ci < 0 || cj < 0 || ci >= GW || cj >= GH) ? -1 : ci + cj * GW; } + function write(i, s) { + var m = meshOf[i], a = meshes[m].instanceMatrix.array, o = slot[i] * 16; dirty[m] = true; + if (s === 0) { a[o] = a[o + 5] = a[o + 10] = 0; a[o + 1] = a[o + 2] = a[o + 4] = a[o + 6] = a[o + 8] = a[o + 9] = 0; a[o + 13] = -50; return; } + var k = scl[i] * (s || 1), cy = Math.cos(yaw[i]), sy = Math.sin(yaw[i]), cp = Math.cos(pit[i]), sp = Math.sin(pit[i]), cr = Math.cos(rol[i]), sr = Math.sin(rol[i]); + a[o] = (cy * cr + sy * sp * sr) * k; a[o + 1] = cp * sr * k; a[o + 2] = (-sy * cr + cy * sp * sr) * k; a[o + 3] = 0; + a[o + 4] = (-cy * sr + sy * sp * cr) * k; a[o + 5] = cp * cr * k; a[o + 6] = (sy * sr + cy * sp * cr) * k; a[o + 7] = 0; + a[o + 8] = sy * cp * k; a[o + 9] = -sp * k; a[o + 10] = cy * cp * k; a[o + 11] = 0; + a[o + 12] = px[i]; a[o + 13] = py[i]; a[o + 14] = pz[i]; a[o + 15] = 1; + } + function link(i, c) { lcell[i] = c; next[i] = head[c]; prev[i] = -1; if (head[c] >= 0) prev[head[c]] = i; head[c] = i; rank[i] = cnt[c]; cnt[c]++; } + function unlink(i) { + var c = lcell[i], rk = rank[i]; if (c < 0) return; + if (prev[i] >= 0) next[prev[i]] = next[i]; else head[c] = next[i]; + if (next[i] >= 0) prev[next[i]] = prev[i]; + cnt[c]--; lcell[i] = -1; + for (var j = head[c]; j >= 0; j = next[j]) if (rank[j] > rk) { rank[j]--; if (st[j] === SLEEP) { py[j] -= LH; write(j); } } + } + function wake(i) { if (st[i] !== SLEEP) return; st[i] = AWAKE; idle[i] = 0; aidx[i] = awakeN; awake[awakeN++] = i; } + function unawake(i) { var k = aidx[i]; if (k < 0) return; var last = awake[--awakeN]; awake[k] = last; aidx[last] = k; aidx[i] = -1; } + function kill(i) { if (st[i] === DEAD) return; unawake(i); if (lcell[i] >= 0) unlink(i); st[i] = DEAD; self.alive[area[i]]--; write(i, 0); } + function rest(i) { return BASE + rank[i] * LH + off[i]; } + this.wake = wake; + + function place(i, x, z) { px[i] = x; pz[i] = z; link(i, cellOf(x, z)); py[i] = rest(i); pit[i] = rp[i]; rol[i] = rr[i]; st[i] = SLEEP; self.alive[area[i]]++; write(i); } + // scatter an area: drifts under trees and along the edges, a thinner layer everywhere else + function scatter(ai, keepShare) { + var a = A[ai], rr2 = WR.rng(900 + ai * 31 + counts[ai]), spots = [], k, first = 0; + for (k = 0; k < ai; k++) first += counts[k]; + WR.TREES.forEach(function (t) { if (t[0] > a.x0 && t[0] < a.x1 && t[1] > a.z0 && t[1] < a.z1) { spots.push([t[0], t[1], 2.4]); spots.push([t[0], t[1], 1.4]); } }); + var extra = 6 + Math.round((a.x1 - a.x0) * (a.z1 - a.z0) / 60); + for (k = 0; k < extra; k++) { var e = rr2(), ex = a.x0 + 1 + rr2() * (a.x1 - a.x0 - 2), ez = a.z0 + 1 + rr2() * (a.z1 - a.z0 - 2); + if (e < .5) { if (rr2() < .5) ex = rr2() < .5 ? a.x0 + .9 : a.x1 - .9; else ez = rr2() < .5 ? a.z0 + .9 : a.z1 - .9; } + spots.push([ex, ez, 1.1 + rr2() * 1.6]); } + for (k = 0; k < counts[ai]; k++) { + var id = first + k, keep = rr2() < keepShare, tries = 0, x, z, c; + do { + if (rr2() < .62) { var s = spots[(rr2() * spots.length) | 0], g = Math.sqrt(-2 * Math.log(1 - rr2() * .999)) * s[2] * .6, th = rr2() * 6.283; x = s[0] + Math.cos(th) * g; z = s[1] + Math.sin(th) * g; } + else { x = a.x0 + .4 + rr2() * (a.x1 - a.x0 - .8); z = a.z0 + .4 + rr2() * (a.z1 - a.z0 - .8); } + c = cellOf(x, z); tries++; + } while (tries < 30 && (c < 0 || solid[c] || inlet[c] >= 0 || WR.areaOf[c] !== ai || cnt[c] >= 7)); + yaw[id] = rr2() * 6.283; + if (keep && tries < 30) place(id, x, z); else { st[id] = DEAD; lcell[id] = -1; write(id, 0); } + } + } + // saved places: two 16-bit numbers a leaf (centimetres from the corner of the garden), 65535 for a leaf that is gone + function b64(u8) { var s = ''; for (var k = 0; k < u8.length; k += 8192) s += String.fromCharCode.apply(null, u8.subarray(k, k + 8192)); return btoa(s); } + function unb64(s) { var b = atob(s), u = new Uint8Array(b.length); for (var k = 0; k < b.length; k++) u[k] = b.charCodeAt(k); return u; } + this.serialize = function () { + var out = [], first = 0; + A.forEach(function (a, ai) { + if (self.alive[ai] === counts[ai] && !self.touched[ai]) { out.push(''); first += counts[ai]; return; } + var u = new Uint16Array(counts[ai] * 2); + for (var k = 0; k < counts[ai]; k++) { var id = first + k; if (st[id] === DEAD || st[id] === SINK) { u[k * 2] = u[k * 2 + 1] = 65535; } else if (st[id] === TOBAG) { u[k * 2] = u[k * 2 + 1] = 65535; } else { u[k * 2] = Math.round((px[id] - X0) * 100); u[k * 2 + 1] = Math.round((pz[id] - Z0) * 100); } } + out.push(b64(new Uint8Array(u.buffer))); first += counts[ai]; + }); + return out; + }; + this.touched = A.map(function () { return false; }); + (function init() { + var saved = state.leaves && state.leafMul === mul ? state.leaves : null, first = 0; + A.forEach(function (a, ai) { + var s = saved && saved[ai], done = (state.bagUnits[ai] || 0) / a.units + (state.gone[ai] || 0); + if (s) { + try { + var u = new Uint16Array(unb64(s).buffer); if (u.length !== counts[ai] * 2) throw 0; + for (var k = 0; k < counts[ai]; k++) { var id = first + k; yaw[id] = (id * 2.399) % 6.283; + if (u[k * 2] === 65535) { st[id] = DEAD; lcell[id] = -1; write(id, 0); continue; } + var x = X0 + u[k * 2] / 100, z = Z0 + u[k * 2 + 1] / 100, c = cellOf(x, z); + if (c < 0 || solid[c]) { st[id] = DEAD; lcell[id] = -1; write(id, 0); continue; } + place(id, x, z); } + self.touched[ai] = true; + } catch (e) { scatter(ai, 1 - done); self.touched[ai] = done > 0; } + } else { scatter(ai, Math.max(0, 1 - done)); self.touched[ai] = done > 0; } + first += counts[ai]; + }); + })(); + // share of an area's leaves that are out of the garden for good (not on the ground, not in the sack) + this.share = function (ai) { return Math.max(0, Math.min(1, 1 - (this.alive[ai] * this.w[ai] + (state.bagUnits[ai] || 0)) / A[ai].units)); }; + + /* ---------- one step ---------- */ + var time = 0; this.onGone = null; this.moved = 0; + this.step = function (dt, bag) { + time += dt; var moved = 0; + for (var n = awakeN - 1; n >= 0; n--) { + var i = awake[n], s = st[i]; + if (s === TOBAG) { + tmr[i] += dt; var k = Math.min(1, dt * 14); + px[i] += (bag.x - px[i]) * k; py[i] += (bag.y - py[i]) * k; pz[i] += (bag.z - pz[i]) * k; pit[i] += dt * 9; yaw[i] += dt * 7; + if (tmr[i] > 0.24) { var ar = area[i]; kill(i); if (self.onGone) self.onGone(ar, self.w[ar], 'bag', i); } else write(i, 1 - tmr[i] * 2.4); + continue; + } + if (s === SINK) { + tmr[i] += dt; py[i] -= dt * 1.1; yaw[i] += dt * 8; var ch = WR.CHUTES[aux[i]]; px[i] += (ch.x - px[i]) * dt * 5; pz[i] += (ch.z - pz[i]) * dt * 5; + if (tmr[i] > 0.32) { var ar2 = area[i]; kill(i); if (self.onGone) self.onGone(ar2, self.w[ar2], 'chute', aux[i]); } else write(i, 1 - tmr[i] * 2.6); + continue; + } + var c = lcell[i], ry = rest(i), ground = py[i] <= ry + 0.004, f; + if (ground) { + py[i] = ry; if (vy[i] < 0) vy[i] = 0; + f = 1 / (1 + FR[gtype[c]] * dt); vx[i] *= f; vz[i] *= f; spin[i] *= f; + var kk = Math.min(1, dt * 9); pit[i] += (rp[i] - pit[i]) * kk; rol[i] += (rr[i] - rol[i]) * kk; + } else { + vy[i] -= 4.6 * dt; f = 1 / (1 + 1.5 * dt); vx[i] *= f; vz[i] *= f; vy[i] *= 1 / (1 + 2.4 * dt); + var ph = time * 5.3 + i; vx[i] += Math.sin(ph) * 0.7 * dt; vz[i] += Math.cos(ph * 1.3) * 0.7 * dt; + pit[i] += (spin[i] * .9 + 1.5) * dt; rol[i] += spin[i] * .6 * dt; + } + yaw[i] += spin[i] * dt; + var sp2 = vx[i] * vx[i] + vz[i] * vz[i]; + if (sp2 > 1e-5 || !ground) { + var nx = px[i] + vx[i] * dt, nz = pz[i] + vz[i] * dt, c1 = cellOf(nx, pz[i]); + if (c1 < 0 || solid[c1]) { vx[i] *= -0.12; nx = px[i]; } + var c2 = cellOf(nx, nz); + if (c2 < 0 || solid[c2]) { vz[i] *= -0.12; nz = pz[i]; c2 = cellOf(nx, nz); } + py[i] += vy[i] * dt; + if (c2 !== c) { + var full = cnt[c2] >= HARD || ((ground || py[i] < BASE + cnt[c2] * LH) && cnt[c2] >= CAP && cnt[c2] >= cnt[c]); + if (full) { var t = vx[i]; vx[i] = vz[i] * (i & 1 ? .5 : -.5); vz[i] = t * (i & 1 ? -.5 : .5); nx = px[i]; nz = pz[i]; } + else { unlink(i); link(i, c2); c = c2; } + } + px[i] = nx; pz[i] = nz; ry = rest(i); if (py[i] < ry) py[i] = ry; + moved += Math.sqrt(sp2); + if (inlet[c] >= 0 && py[i] < 0.22) { st[i] = SINK; tmr[i] = 0; aux[i] = inlet[c]; unlink(i); self.touched[area[i]] = true; continue; } + } + if (ground && sp2 < 0.004) { + idle[i] += dt; + if (idle[i] > 0.3) { + // too high on the heap? slide off onto the lowest neighbour + var low = -1, lc = cnt[c] - 4; + if (rank[i] >= cnt[c] - 2 && cnt[c] > 5) { var nb = [c - 1, c + 1, c - GW, c + GW]; for (var q = 0; q < 4; q++) { var d = nb[(q + i) & 3]; if (d >= 0 && d < solid.length && !solid[d] && cnt[d] < lc) { lc = cnt[d]; low = d; } } } + if (low >= 0) { var dd = low - c; vx[i] = dd === 1 ? 1.1 : dd === -1 ? -1.1 : 0; vz[i] = dd === GW ? 1.1 : dd === -GW ? -1.1 : 0; idle[i] = 0; } + else { st[i] = SLEEP; vx[i] = vz[i] = vy[i] = spin[i] = 0; pit[i] = rp[i]; rol[i] = rr[i]; unawake(i); } + } + } else idle[i] = 0; + write(i); + } + this.moved = moved; + for (var m = 0; m < meshes.length; m++) if (dirty[m]) { meshes[m].instanceMatrix.needsUpdate = true; dirty[m] = false; } + }; + + /* ---------- what tools do to leaves ---------- */ + function eachIn(x0, z0, x1, z1, fn) { + var i0 = Math.max(0, Math.floor((x0 - X0) / CELL)), i1 = Math.min(GW - 1, Math.floor((x1 - X0) / CELL)), j0 = Math.max(0, Math.floor((z0 - Z0) / CELL)), j1 = Math.min(GH - 1, Math.floor((z1 - Z0) / CELL)); + for (var j = j0; j <= j1; j++) for (var ii = i0; ii <= i1; ii++) { var c = ii + j * GW; if (!cnt[c]) continue; for (var l = head[c]; l >= 0;) { var nl = next[l]; fn(l); l = nl; } } + } + function freeDist(ox, oz, dx, dz, max) { for (var d = 0.2; d < max; d += 0.2) { var c = cellOf(ox + dx * d, oz + dz * d); if (c < 0 || solid[c]) return d; } return max; } + this.freeDist = freeDist; + // blower: a cone from (ox,oy,oz) along (dx,dy,dz). Force fades with distance and with angle off the middle; walls stop it. + var BINS_N = 13, reach = new Float32Array(BINS_N); + this.blow = function (ox, oy, oz, dx, dy, dz, range, half, power, dt) { + var hl = Math.hypot(dx, dz) || 1, hx = dx / hl, hz = dz / hl, base = Math.atan2(hz, hx), cosH = Math.cos(half), b, hit = 0; + for (b = 0; b < BINS_N; b++) { var an = base + (b / (BINS_N - 1) * 2 - 1) * half; reach[b] = freeDist(ox, oz, Math.cos(an), Math.sin(an), range) + 0.2; } + var ex = ox + dx * range, ez = oz + dz * range, pad = Math.sin(half) * range + .3; + eachIn(Math.min(ox, ex) - pad, Math.min(oz, ez) - pad, Math.max(ox, ex) + pad, Math.max(oz, ez) + pad, function (l) { + if (st[l] > AWAKE) return; + var lx = px[l] - ox, ly = py[l] - oy, lz = pz[l] - oz, d = Math.sqrt(lx * lx + ly * ly + lz * lz); if (d > range || d < 0.05) return; + var ca = (lx * dx + ly * dy + lz * dz) / d; if (ca < cosH) return; + var ang = Math.atan2(lz, lx) - base; if (ang > Math.PI) ang -= 6.283; else if (ang < -Math.PI) ang += 6.283; + var bi = Math.round((ang / half * .5 + .5) * (BINS_N - 1)); if (bi < 0) bi = 0; else if (bi >= BINS_N) bi = BINS_N - 1; + if (Math.hypot(lx, lz) > reach[bi]) return; + var fd = 1 - d / range, fa = (ca - cosH) / (1 - cosH), f = power * Math.pow(fd, 1.25) * (0.25 + 0.75 * fa) * dt, hd = Math.hypot(lx, lz) || 1; + // leaves low in a heap are sheltered by the ones on top + var cov = cnt[lcell[l]] - 1 - rank[l]; if (cov > 2) f *= 2 / cov; + wake(l); vx[l] += (hx * .72 + lx / hd * .28) * f; vz[l] += (hz * .72 + lz / hd * .28) * f; + vy[l] += f * (0.16 + ((l * 7919) % 13) / 13 * 0.3); spin[l] += (((l * 31) % 17) / 8.5 - 1) * f * 2.2; hit++; + self.touched[area[l]] = true; + }); + return hit; + }; + // rake: leaves under the head (a line from a to b, `rad` thick) are carried along with it at (hvx,hvz) + this.rake = function (ax, az, bx, bz, rad, hvx, hvz) { + var ex = bx - ax, ez = bz - az, el = ex * ex + ez * ez || 1, hit = 0; + eachIn(Math.min(ax, bx) - rad, Math.min(az, bz) - rad, Math.max(ax, bx) + rad, Math.max(az, bz) + rad, function (l) { + if (st[l] > AWAKE) return; + var t = ((px[l] - ax) * ex + (pz[l] - az) * ez) / el; t = t < 0 ? 0 : t > 1 ? 1 : t; + var qx = px[l] - (ax + ex * t), qz = pz[l] - (az + ez * t); if (qx * qx + qz * qz > rad * rad) return; + if (py[l] > 0.5) return; + wake(l); var j = ((l * 131) % 11) / 11 - .5; vx[l] = hvx * (1 + j * .12) ; vz[l] = hvz * (1 + j * .12); spin[l] += j * 3; if (vy[l] < .3 && (l & 7) === 0) vy[l] += .5; hit++; + self.touched[area[l]] = true; + }); + return hit; + }; + // hands: the nearest leaves inside the circle fly to the sack. Returns how many were taken. + var cand = []; + this.scoop = function (cx, cz, rad, max, ex, ez) { + cand.length = 0; + eachIn(cx - rad, cz - rad, cx + rad, cz + rad, function (l) { if (st[l] > AWAKE) return; var d = (px[l] - cx) * (px[l] - cx) + (pz[l] - cz) * (pz[l] - cz); if (d < rad * rad) cand.push(l, d); }); + var took = 0; + while (took < max && cand.length) { + var best = 1, k; for (k = 3; k < cand.length; k += 2) if (cand[k] < cand[best]) best = k; + var l = cand[best - 1]; cand[best - 1] = cand[cand.length - 2]; cand[best] = cand[cand.length - 1]; cand.length -= 2; + var dx = px[l] - ex, dz = pz[l] - ez, d = Math.hypot(dx, dz) || 1; if (freeDist(ex, ez, dx / d, dz / d, d) < d - 0.05) continue; + if (st[l] === SLEEP) { st[l] = AWAKE; aidx[l] = awakeN; awake[awakeN++] = l; } + unlink(l); st[l] = TOBAG; tmr[l] = 0; took++; self.touched[area[l]] = true; + } + return took; + }; + // walking through leaves kicks them along + this.kick = function (x, z, rad, kx, kz) { + eachIn(x - rad, z - rad, x + rad, z + rad, function (l) { + if (st[l] > AWAKE) return; var qx = px[l] - x, qz = pz[l] - z, d2 = qx * qx + qz * qz; if (d2 > rad * rad) return; + if (cnt[lcell[l]] - 1 - rank[l] > 3) return; + wake(l); var d = Math.sqrt(d2) || 1; vx[l] += kx * .55 + qx / d * .5; vz[l] += kz * .55 + qz / d * .5; if (py[l] < .1) vy[l] += .35 + ((l * 13) % 7) * .05; spin[l] += ((l % 5) - 2) * 1.2; + self.touched[area[l]] = true; + }); + }; + // chutes with the Draught grates reward draw nearby leaves in + this.pull = function (x, z, rad, power, dt) { + eachIn(x - rad, z - rad, x + rad, z + rad, function (l) { + if (st[l] > AWAKE) return; var qx = x - px[l], qz = z - pz[l], d = Math.hypot(qx, qz); if (d > rad || d < .01) return; + wake(l); var f = power * (1 - d / rad * .6) * dt / d; vx[l] += qx * f; vz[l] += qz * f; + }); + }; + // the nearest few leaves that belong to an area and are still on the ground: for the leaf finder + this.nearest = function (x, z, ai, n, out) { + out.length = 0; var first = 0, k; for (k = 0; k < ai; k++) first += counts[k]; + for (k = first; k < first + counts[ai]; k++) { if (st[k] !== SLEEP && st[k] !== AWAKE) continue; var d = (px[k] - x) * (px[k] - x) + (pz[k] - z) * (pz[k] - z); + if (out.length < n * 3) out.push(px[k], pz[k], d); else { var worst = 2; for (var q = 5; q < out.length; q += 3) if (out[q] > out[worst]) worst = q; if (d < out[worst]) { out[worst - 2] = px[k]; out[worst - 1] = pz[k]; out[worst] = d; } } } + return out; + }; + this.eachAlive = function (fn) { for (var k = 0; k < N; k++) if (st[k] === SLEEP || st[k] === AWAKE) fn(px[k], pz[k], area[k]); }; + this.countIn = function (x, z, rad) { var n = 0; eachIn(x - rad, z - rad, x + rad, z + rad, function (l) { if (st[l] <= AWAKE && (px[l] - x) * (px[l] - x) + (pz[l] - z) * (pz[l] - z) < rad * rad) n++; }); return n; }; + this.dispose = function () { meshes.forEach(function (m) { scene.remove(m); m.dispose && m.dispose(); }); geos.forEach(function (g) { g.dispose(); }); mat.dispose(); }; + } + WR.Leaves = Leaves; + + /* Loose leaves that are only for show: the ones poured out of the sack, puffs at a chute, a few drifting off the trees. */ + function Fx(scene, max) { + var geo = leafGeo(SHAPES[0]), mesh = new THREE.InstancedMesh(geo, new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.DoubleSide }), max); + mesh.frustumCulled = false; mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage); scene.add(mesh); + var P = [], m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), v = new THREE.Vector3(), sc = new THREE.Vector3(), col = new THREE.Color(), nextSlot = 0; + for (var i = 0; i < max; i++) { P.push({ life: 0 }); m4.makeScale(0, 0, 0); mesh.setMatrixAt(i, m4); mesh.setColorAt(i, col.set('#c8822c')); } + this.spawn = function (x, y, z, vx, vy, vz, life, color, size, floorY) { + var p = P[nextSlot]; p.x = x; p.y = y; p.z = z; p.vx = vx; p.vy = vy; p.vz = vz; p.life = p.max = life; p.s = size || .24; p.a = Math.random() * 6; p.b = Math.random() * 6; p.fl = floorY == null ? -1 : floorY; + mesh.setColorAt(nextSlot, col.set(color)); mesh.instanceColor.needsUpdate = true; nextSlot = (nextSlot + 1) % max; + }; + this.step = function (dt) { + var any = false; + for (var i = 0; i < max; i++) { var p = P[i]; if (p.life <= 0) continue; any = true; p.life -= dt; + p.vy -= 4.5 * dt; p.vx *= 1 - dt; p.vz *= 1 - dt; p.vy *= 1 - 1.8 * dt; p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt; p.a += dt * 5; p.b += dt * 3.3; + if (p.y < p.fl) { p.y = p.fl; p.vx = p.vz = 0; } + var k = p.life <= 0 ? 0 : Math.min(1, p.life * 5) * p.s; e.set(p.a, p.b, p.a * .5); q.setFromEuler(e); v.set(p.x, p.y, p.z); sc.set(k, k, k); m4.compose(v, q, sc); mesh.setMatrixAt(i, m4); } + if (any) mesh.instanceMatrix.needsUpdate = true; + }; + } + WR.Fx = Fx; +})(); diff --git a/e63334287a3deaa3/windrow/js/models.js b/e63334287a3deaa3/windrow/js/models.js new file mode 100644 index 00000000..4bb7dd81 --- /dev/null +++ b/e63334287a3deaa3/windrow/js/models.js @@ -0,0 +1,60 @@ +/* Windrow: what you see of yourself. The gloves, sack and blower are drawn in a small scene of their own on top of + the garden (so they never poke through a wall); the rake is a real object in the garden, because its head is out + on the ground where the leaves are. Upgrades change these models: the sack swells, the rake head widens, the + blower's pipe grows. */ +(function () { + 'use strict'; + var WR = window.WR, Builder = WR.Builder; + WR.buildViewModels = function (scene, state) { + var vm = { scene: new THREE.Scene(), cam: new THREE.PerspectiveCamera(58, 1, 0.02, 5) }; + vm.scene.add(new THREE.HemisphereLight(0xdfe8ee, 0x8a7a5a, 0.75)); var d = new THREE.DirectionalLight(0xffe6c0, 0.7); d.position.set(-1, 2, 1.5); vm.scene.add(d); + + // hands and sack + var hands = vm.hands = new THREE.Group(); + function glove(side) { var b = new Builder(); b.blob(0, 0, 0, .075, '#d8b27c', .8, 5); b.box(0, -.01, .1, .1, .09, .1, '#c4552d'); b.box(side * -.06, .0, -.03, .04, .04, .08, '#d8b27c'); b.cyl(0, -.01, .22, .045, .05, .16, "#6b7a55", 8); var m = b.mesh(); return m; } + var rh = vm.rh = glove(1); rh.position.set(.25, -.24, -.5); rh.rotation.set(-.3, .25, -.2); rh.scale.setScalar(.8); hands.add(rh); + var lh = glove(-1); lh.position.set(-.27, -.27, -.5); lh.rotation.set(-.2, -.3, .2); lh.scale.setScalar(.8); hands.add(lh); + var sackB = new Builder(); sackB.blob(0, 0, 0, .16, '#b99a66', 1.15, 9); sackB.cyl(0, .17, 0, .1, .12, .06, '#8f7447', 10); sackB.cyl(0, .2, 0, .085, .085, .01, '#3a2a18', 10); + var sack = vm.sack = sackB.mesh(); sack.position.set(-.33, -.46, -.6); hands.add(sack); + var fillB = new Builder(); fillB.blob(0, 0, 0, .09, '#c8822c', .6, 21); var fill = vm.sackFill = fillB.mesh(); fill.position.set(0, .2, 0); sack.add(fill); + vm.scene.add(hands); + + // blower + var blower = vm.blower = new THREE.Group(), bb = new Builder(); + bb.box(0, 0, .05, .15, .17, .26, '#e0782a'); bb.box(0, .12, .05, .04, .05, .2, '#2f2f33'); bb.box(0, .0, .2, .13, .13, .06, '#2f2f33'); bb.cyl(.08, 0, .05, .06, .06, .02, '#3b3b40', 10); + var body = bb.mesh(); blower.add(body); + var pipe = vm.pipe = new THREE.Mesh(new THREE.CylinderGeometry(.036, .05, 1, 10), new THREE.MeshLambertMaterial({ color: 0x3b3b40 })); pipe.geometry.rotateX(-Math.PI / 2); pipe.geometry.translate(0, 0, -.5); pipe.position.set(0, -.02, -.07); blower.add(pipe); + var tip = vm.tip = new THREE.Mesh(new THREE.CylinderGeometry(.045, .04, .05, 10), new THREE.MeshLambertMaterial({ color: 0xe0b53a })); tip.geometry.rotateX(-Math.PI / 2); blower.add(tip); + blower.position.set(.3, -.3, -.42); blower.rotation.set(-.12, .16, 0); vm.scene.add(blower); + // a faint cone of moving air in the garden, so you can see where the blower reaches + var airG = new THREE.ConeGeometry(1, 1, 14, 1, true); airG.translate(0, -.5, 0); airG.rotateX(-Math.PI / 2); + var air = vm.air = new THREE.Mesh(airG, new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: .07, side: THREE.DoubleSide, depthWrite: false, fog: false })); air.visible = false; scene.add(air); + + // rake (in the garden itself) + var rake = vm.rake = new THREE.Group(); rake.visible = false; scene.add(rake); + var handle = vm.handle = new THREE.Mesh(new THREE.CylinderGeometry(.017, .02, 1, 7), new THREE.MeshLambertMaterial({ color: 0xb98a4e })); handle.geometry.rotateX(Math.PI / 2); handle.geometry.translate(0, 0, .5); scene.add(handle); handle.visible = false; + var headMesh = null; + vm.setRakeWidth = function (w, gold) { + if (headMesh) { rake.remove(headMesh); headMesh.geometry.dispose(); } + var b = new Builder(), n = Math.round(w / .1), metal = gold ? '#e0b53a' : '#6f7479'; + b.box(0, .13, 0, w, .035, .05, metal); for (var i = 0; i <= n; i++) b.box(-w / 2 + i * w / n, .06, .02, .014, .13, .014, gold ? '#f0cf6a' : '#8a9096'); b.box(0, .16, -.05, .05, .05, .14, '#b98a4e'); + headMesh = b.mesh(); headMesh.castShadow = false; rake.add(headMesh); + }; + // the ring that shows where the hands reach + var ring = vm.ring = new THREE.Mesh(new THREE.RingGeometry(.94, 1, 40), new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: .55, depthWrite: false, fog: false })); ring.rotation.x = -Math.PI / 2; ring.visible = false; scene.add(ring); + // finder beacons + vm.beacons = []; var bg = new THREE.CylinderGeometry(.05, .05, 7, 6, 1, true); bg.translate(0, 3.5, 0); var bm = new THREE.MeshBasicMaterial({ color: 0xffe27a, transparent: true, opacity: .5, depthWrite: false, fog: false }); + for (var i = 0; i < 8; i++) { var be = new THREE.Mesh(bg, bm); be.visible = false; scene.add(be); vm.beacons.push(be); } + + vm.refresh = function () { + var up = state.up, fill = Math.min(1, state.bagFill / WR.sackCap(state)); + var s = 1 + up.sack * 0.13; sack.scale.set(s * (0.8 + fill * .35), s * (0.75 + fill * .4), s * (0.8 + fill * .35)); + vm.sackFill.visible = fill > 0.02; vm.sackFill.scale.setScalar(0.6 + fill * 0.7); + var len = 0.42 + up.nozzle * 0.11; pipe.scale.set(1 + up.nozzle * .08, 1 + up.nozzle * .08, len); tip.position.set(0, -.02, -.07 - len); + body.material.color.setHex([0xffffff, 0xfff0d0, 0xffd9a0, 0xffc070][up.power] || 0xffffff); + vm.setRakeWidth(WR.rakeWidth(state), state.rewards.crown); + }; + vm.refresh(); + return vm; + }; +})(); diff --git a/e63334287a3deaa3/windrow/js/world.js b/e63334287a3deaa3/windrow/js/world.js new file mode 100644 index 00000000..710ac772 --- /dev/null +++ b/e63334287a3deaa3/windrow/js/world.js @@ -0,0 +1,312 @@ +/* Windrow: the garden. Areas, the collision grid, and everything that stands still (ground, walls, hedges, trees, + bins, chutes, gates). All shapes and textures are made here in code; nothing is downloaded. + The whole garden is flat and sits on one grid of 0.25 m cells (WR.CELL): `solid` blocks the player and the leaves, + `gtype` says what the ground is (how far a leaf slides on it), `inlet` marks the cells of a mulch chute. */ +(function () { + 'use strict'; + var WR = window.WR = window.WR || {}; + var CELL = WR.CELL = 0.25, X0 = WR.X0 = -41, Z0 = WR.Z0 = -31, GW = WR.GW = 312, GH = WR.GH = 208; + var LAWN = 0, PAVE = 1, DECK = 2, GRAVEL = 3; + WR.GROUND_FRICTION = [7.5, 3.2, 4.2, 6.0]; + + /* The five areas. `units` is what all of an area's leaves are worth together before upgrades, however many leaves + the quality setting draws; `leaves` is the count before the quality setting multiplies it (WR.QUALITY). `need` = [area, share cleared] to be allowed to unlock. */ + WR.AREAS = [ + { id: 'court', name: 'Gatehouse Court', x0: -12, x1: 12, z0: 0, z1: 20, ground: PAVE, leaves: 1500, units: 500, cost: 0, need: null, bonus: 100, + reward: 'sprint', rewardName: 'Running shoes', rewardText: 'Hold Shift to sprint', pal: ['#d9a23a', '#c9822c', '#b8692a', '#e3bd55', '#8f5a2a'] }, + { id: 'orchard', name: 'Orchard Walk', x0: -12, x1: 12, z0: -30, z1: 0, ground: LAWN, leaves: 2200, units: 1200, cost: 150, need: [0, 0.5], bonus: 250, + reward: 'crouch', rewardName: 'Knee pads', rewardText: 'Hold C to kneel: hands gather twice as fast', pal: ['#c8452a', '#d96a2b', '#b5301f', '#e08a32', '#9c3a22'] }, + { id: 'terrace', name: 'Lily Terrace', x0: 12, x1: 36, z0: 0, z1: 20, ground: DECK, leaves: 2000, units: 2200, cost: 450, need: [0, 0.5], bonus: 500, + reward: 'spring', rewardName: 'Spring heels', rewardText: 'Jump half as high again', pal: ['#e6c84a', '#d4b13a', '#b9c248', '#e9d77a', '#a89a3c'] }, + { id: 'glass', name: 'Glasshouse Row', x0: 12, x1: 36, z0: -30, z1: 0, ground: PAVE, leaves: 2200, units: 4200, cost: 1200, need: [1, 0.5], bonus: 900, + reward: 'magnet', rewardName: 'Draught grates', rewardText: 'Chutes pull in leaves from farther away', pal: ['#b07a3c', '#96602c', '#c79a52', '#7d5630', '#d4ae6a'] }, + { id: 'maze', name: 'Maze Lawn', x0: -40, x1: -12, z0: -30, z1: 20, ground: LAWN, leaves: 3600, units: 9000, cost: 2800, need: [1, 0.5], bonus: 2000, + reward: 'crown', rewardName: 'Keeper of Windrow', rewardText: 'The gardens are open again', pal: ['#8e2f3a', '#a8402c', '#6f2a3a', '#c25a2e', '#7a3a24'] } + ]; + WR.QUALITY = { low: 0.6, medium: 1.4, high: 2.8 }; // times each area's `leaves`: 6,900 / 16,100 / 32,200 in all + + // gates: the gap in a wall that opens when `area` is unlocked. axis 'x' = the gap runs along x. + WR.GATES = [ + { area: 1, axis: 'x', x: 0, z: 0 }, + { area: 2, axis: 'z', x: 12, z: 10 }, + { area: 3, axis: 'z', x: 12, z: -15 }, + { area: 4, axis: 'z', x: -12, z: -15 } + ]; + WR.BINS = [ + { area: 0, x: -9.5, z: 17.6 }, { area: 1, x: 9.6, z: -2.6 }, { area: 2, x: 33.6, z: 17.6 }, + { area: 3, x: 14.4, z: -2.6 }, { area: 4, x: -14.4, z: -18.2 }, { area: 4, x: -37.6, z: 17.6 } + ]; + WR.CHUTES = [ + { area: 0, x: 8, z: 4 }, { area: 1, x: -8.5, z: -24 }, { area: 1, x: 9, z: -12 }, { area: 2, x: 15, z: 3 }, + { area: 2, x: 31, z: 11 }, { area: 3, x: 24, z: -27.5 }, { area: 3, x: 24, z: -4 }, + { area: 4, x: -37, z: -11 }, { area: 4, x: -25.5, z: 1 }, { area: 4, x: -37, z: -27 }, { area: 4, x: -19, z: 17 } + ]; + WR.CHUTE_HALF = 0.75; + var TREES = [ + [-7.5, 5, 1.0], [7.5, 12, 1.1], [-10.2, 14.5, 0.8], + [-7.5, -27, 1], [-7.5, -21, 1.1], [-7.5, -9, 1], [-7.5, -3.2, .9], [7.5, -27, 1.05], [7.5, -21, .95], [7.5, -16.5, 1], [7.5, -7, 1.1], [-4, -15, .8], [4.2, -24.5, .85], + [15, 17.5, .8], [33.5, 2.5, .85], [14.2, 8, .7], + [14, -28, .75], [34.6, -5.5, .8], [24, -16, .7], + [-37, -25, 1.1], [-25, -25.5, 1], [-37, 12, 1.05], [-25, 14, 1], [-18.5, 0, .9], [-26.5, -2.5, .95], [-13.6, 17.5, .8], [-37.5, -2, 1], [-19, -14.5, .85] + ]; + WR.TREES = TREES; + var HEDGES = [[-34, -18, -21, -20], [-34, -33, -20, -6], [-28, -12.25, -9, -8], [-22, -21, -8, 6], [-40, -28, 4, 5], [-21, -16, 5, 6], [-30, -29, 10, 20], [-16, -15, -2, 14]]; + var LAWNS = [[-10.5, -5, 2, 8], [5, 10.5, 9, 15.5], [-10.8, -8.6, 12, 17]]; + var GRAVELS = [[-1.6, 1.6, -30, 0], [-12, 12, -16.2, -13.8]]; + var FOUNTAIN = { x: 0, z: 9, r: 2.1 }, POND = { x: 24, z: 10, r: 3.8 }; + var GLASS = [[15.5, 21.5, -25, -9], [26.5, 32.5, -25, -9]]; + var BENCHES = [[4, 1.1, 0], [-3.6, 18.9, 0], [18, 1.1, 0], [35, 8, 1], [-11, 9.5, 1], [-0.0, -29, 0], [13, -22, 1], [-39, 8, 1], [-24.5, -29, 0]]; + WR.SPAWN = { x: 0, z: 16.5, yaw: 0 }; + + var solid = WR.solid = new Uint8Array(GW * GH), gtype = WR.gtype = new Uint8Array(GW * GH); + var inlet = WR.inlet = new Int8Array(GW * GH).fill(-1), areaOf = WR.areaOf = new Int8Array(GW * GH).fill(-1); + function ci(x) { return Math.floor((x - X0) / CELL); } + function cj(z) { return Math.floor((z - Z0) / CELL); } + WR.cellOf = function (x, z) { var i = ci(x), j = cj(z); return (i < 0 || j < 0 || i >= GW || j >= GH) ? -1 : i + j * GW; }; + WR.solidAt = function (x, z) { var c = WR.cellOf(x, z); return c < 0 || solid[c] === 1; }; + function rect(arr, x0, x1, z0, z1, v) { + var i0 = Math.max(0, ci(x0 + 1e-6)), i1 = Math.min(GW - 1, ci(x1 - 1e-6)), j0 = Math.max(0, cj(z0 + 1e-6)), j1 = Math.min(GH - 1, cj(z1 - 1e-6)); + for (var j = j0; j <= j1; j++) for (var i = i0; i <= i1; i++) arr[i + j * GW] = v; + } + function disc(arr, x, z, r, v) { + for (var j = cj(z - r); j <= cj(z + r); j++) for (var i = ci(x - r); i <= ci(x + r); i++) { + var cx = X0 + (i + .5) * CELL - x, cz = Z0 + (j + .5) * CELL - z; + if (cx * cx + cz * cz <= r * r && i >= 0 && j >= 0 && i < GW && j < GH) arr[i + j * GW] = v; + } + } + var WALLS = []; // [x0,x1,z0,z1] + function wallX(z, xa, xb, gaps) { segs(xa, xb, gaps).forEach(function (s) { WALLS.push([s[0], s[1], z - .25, z + .25]); }); } + function wallZ(x, za, zb, gaps) { segs(za, zb, gaps).forEach(function (s) { WALLS.push([x - .25, x + .25, s[0], s[1]]); }); } + function segs(a, b, gaps) { + var out = [], at = a; (gaps || []).sort(function (p, q) { return p - q; }).forEach(function (g) { out.push([at, g - 1.5]); at = g + 1.5; }); + out.push([at, b]); return out; + } + function gateBox(g) { return g.axis === 'x' ? [g.x - 1.5, g.x + 1.5, g.z - .25, g.z + .25] : [g.x - .25, g.x + .25, g.z - 1.5, g.z + 1.5]; } + + WR.buildGrid = function (unlocked) { + solid.fill(1); inlet.fill(-1); areaOf.fill(-1); + WR.AREAS.forEach(function (a, n) { rect(solid, a.x0, a.x1, a.z0, a.z1, 0); rect(gtype, a.x0, a.x1, a.z0, a.z1, a.ground); rect(areaOf, a.x0, a.x1, a.z0, a.z1, n); }); + LAWNS.forEach(function (r) { rect(gtype, r[0], r[1], r[2], r[3], LAWN); }); + GRAVELS.forEach(function (r) { rect(gtype, r[0], r[1], r[2], r[3], GRAVEL); }); + WALLS.length = 0; + wallX(-30, -40.25, 36.25); wallX(20, -40.25, 36.25); wallZ(-40, -30, 20); wallZ(36, -30, 20); + wallZ(-12, -30, 20, [-15]); wallZ(12, -30, 20, [-15, 10]); wallX(0, -12, 12, [0]); wallX(0, 12, 36); + WALLS.forEach(function (w) { rect(solid, w[0], w[1], w[2], w[3], 1); }); + WR.GATES.forEach(function (g) { var b = gateBox(g); rect(solid, b[0], b[1], b[2], b[3], unlocked && unlocked[g.area] ? 0 : 1); rect(gtype, b[0], b[1], b[2], b[3], GRAVEL); }); + HEDGES.forEach(function (h) { rect(solid, h[0], h[1], h[2], h[3], 1); }); + GLASS.forEach(function (h) { rect(solid, h[0], h[1], h[2], h[3], 1); }); + TREES.forEach(function (t) { disc(solid, t[0], t[1], 0.38 * t[2], 1); }); + disc(solid, FOUNTAIN.x, FOUNTAIN.z, FOUNTAIN.r, 1); disc(solid, POND.x, POND.z, POND.r, 1); + BENCHES.forEach(function (b) { if (b[2]) rect(solid, b[0] - .3, b[0] + .3, b[1] - .9, b[1] + .9, 1); else rect(solid, b[0] - .9, b[0] + .9, b[1] - .3, b[1] + .3, 1); }); + rect(solid, 8.2, 11.7, 17.6, 19.7, 1); // potting shed + WR.BINS.forEach(function (b) { rect(solid, b.x - .7, b.x + .7, b.z - .7, b.z + .7, 1); }); + WR.CHUTES.forEach(function (c, n) { rect(inlet, c.x - WR.CHUTE_HALF, c.x + WR.CHUTE_HALF, c.z - WR.CHUTE_HALF, c.z + WR.CHUTE_HALF, n); }); + }; + WR.openGate = function (area) { + WR.GATES.forEach(function (g) { if (g.area === area) { var b = gateBox(g); rect(solid, b[0], b[1], b[2], b[3], 0); g.open = true; } }); + }; + // push a circle (the player) out of solid cells; returns true if it touched anything + WR.collide = function (p, r) { + var hit = false; + for (var it = 0; it < 2; it++) { + var i0 = ci(p.x - r), i1 = ci(p.x + r), j0 = cj(p.z - r), j1 = cj(p.z + r); + for (var j = j0; j <= j1; j++) for (var i = i0; i <= i1; i++) { + if (i >= 0 && j >= 0 && i < GW && j < GH && !solid[i + j * GW]) continue; + var bx = X0 + i * CELL, bz = Z0 + j * CELL, qx = Math.max(bx, Math.min(p.x, bx + CELL)), qz = Math.max(bz, Math.min(p.z, bz + CELL)); + var dx = p.x - qx, dz = p.z - qz, d2 = dx * dx + dz * dz; + if (d2 >= r * r) continue; + hit = true; + if (d2 > 1e-8) { var d = Math.sqrt(d2), k = (r - d) / d; p.x += dx * k; p.z += dz * k; } + else { var cx = bx + CELL / 2, cz = bz + CELL / 2; if (Math.abs(p.x - cx) > Math.abs(p.z - cz)) p.x = cx + (p.x > cx ? 1 : -1) * (CELL / 2 + r); else p.z = cz + (p.z > cz ? 1 : -1) * (CELL / 2 + r); } + } + } + return hit; + }; + + /* ---------- small helpers for making things ---------- */ + function rng(seed) { var s = seed >>> 0; return function () { s = (s + 0x6D2B79F5) | 0; var t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } + WR.rng = rng; + function canvas(n, fn) { var c = document.createElement('canvas'); c.width = c.height = n; fn(c.getContext('2d'), n); return c; } + function tex(c, rep) { var t = new THREE.CanvasTexture(c); t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = 4; if (rep) t.repeat.set(rep, rep); return t; } + function speckle(g, n, count, cols, min, max, r) { for (var i = 0; i < count; i++) { g.fillStyle = cols[(r() * cols.length) | 0]; var s = min + r() * (max - min); g.fillRect(r() * n, r() * n, s, s); } } + function texLawn() { var r = rng(11); return canvas(256, function (g, n) { + g.fillStyle = '#5f8f3c'; g.fillRect(0, 0, n, n); speckle(g, n, 2600, ['#56853a', '#6a9a44', '#4f7c34', '#74a34b'], 2, 7, r); + g.lineWidth = 1.2; for (var i = 0; i < 1500; i++) { var x = r() * n, y = r() * n; g.strokeStyle = r() < .5 ? 'rgba(130,175,80,.55)' : 'rgba(50,90,35,.5)'; g.beginPath(); g.moveTo(x, y); g.lineTo(x + (r() - .5) * 5, y - 3 - r() * 6); g.stroke(); } + }); } + function texPave() { var r = rng(12); return canvas(256, function (g, n) { + g.fillStyle = '#8e8a80'; g.fillRect(0, 0, n, n); + var rows = [[0, 128, 128], [128, 256, 0]]; + for (var y = 0; y < 4; y++) for (var x = -1; x < 3; x++) { var ox = (y % 2) * 64 + x * 128, sh = 150 + (r() * 34 | 0); g.fillStyle = 'rgb(' + (sh + 8) + ',' + (sh + 2) + ',' + (sh - 10) + ')'; g.fillRect(ox + 2, y * 64 + 2, 124, 60); if (ox + 128 > n) g.fillRect(ox - n + 2, y * 64 + 2, 124, 60); } + speckle(g, n, 1800, ['rgba(0,0,0,.06)', 'rgba(255,255,255,.07)', 'rgba(90,70,40,.08)'], 1, 4, r); + }); } + function texDeck() { var r = rng(13); return canvas(256, function (g, n) { + for (var p = 0; p < 4; p++) { var sh = r(); g.fillStyle = 'rgb(' + (150 + sh * 26 | 0) + ',' + (104 + sh * 20 | 0) + ',' + (62 + sh * 14 | 0) + ')'; g.fillRect(0, p * 64, n, 64); + g.strokeStyle = 'rgba(80,48,22,.22)'; g.lineWidth = 1; for (var k = 0; k < 9; k++) { var y = p * 64 + 5 + r() * 54; g.beginPath(); g.moveTo(0, y); g.bezierCurveTo(80, y + r() * 6 - 3, 170, y + r() * 6 - 3, n, y); g.stroke(); } + g.fillStyle = '#4c311a'; g.fillRect(0, p * 64, n, 3); var jx = r() * n; g.fillRect(jx, p * 64, 2, 64); g.fillStyle = '#3a2513'; g.fillRect(jx + 6, p * 64 + 14, 3, 3); g.fillRect(jx + 6, p * 64 + 46, 3, 3); } + }); } + function texGravel() { var r = rng(14); return canvas(256, function (g, n) { g.fillStyle = '#b9a987'; g.fillRect(0, 0, n, n); speckle(g, n, 5200, ['#a59373', '#cbbd9c', '#948264', '#d8ccae', '#857456'], 2, 5, r); }); } + function texBrick() { var r = rng(15); return canvas(256, function (g, n) { + g.fillStyle = '#b9ae9c'; g.fillRect(0, 0, n, n); + for (var y = 0; y < 8; y++) for (var x = -1; x < 4; x++) { var ox = x * 64 + (y % 2) * 32, t = r(); g.fillStyle = 'rgb(' + (150 + t * 40 | 0) + ',' + (84 + t * 26 | 0) + ',' + (62 + t * 20 | 0) + ')'; g.fillRect(ox + 2, y * 32 + 2, 60, 28); } + speckle(g, n, 1200, ['rgba(0,0,0,.07)', 'rgba(255,240,220,.08)'], 1, 4, r); + }); } + function texHedge() { var r = rng(16); return canvas(256, function (g, n) { + g.fillStyle = '#2f5a2c'; g.fillRect(0, 0, n, n); + for (var i = 0; i < 2600; i++) { g.fillStyle = ['#356a31', '#28502a', '#417a38', '#234724', '#4d8a3e'][(r() * 5) | 0]; g.beginPath(); g.ellipse(r() * n, r() * n, 2 + r() * 4, 1.5 + r() * 2.5, r() * 3.14, 0, 6.3); g.fill(); } + }); } + + // a pile of boxes, cylinders and blobs with a colour each, drawn as one mesh + function Builder() { this.p = []; this.n = []; this.c = []; } + Builder.prototype.add = function (geo, color, x, y, z, ry, jitter) { + var g = geo.index ? geo.toNonIndexed() : geo, m = new THREE.Matrix4().makeRotationY(ry || 0); m.setPosition(x, y, z); g.applyMatrix4(m); + var P = g.attributes.position.array, N = g.attributes.normal.array, col = new THREE.Color(color), j = jitter || 0; + for (var i = 0; i < P.length; i += 9) { var k = 1 + (Math.sin(i * 12.9898 + x * 7.1) * 43758.5453 % 1) * j; + for (var v = 0; v < 9; v += 3) { this.p.push(P[i + v], P[i + v + 1], P[i + v + 2]); this.n.push(N[i + v], N[i + v + 1], N[i + v + 2]); this.c.push(col.r * k, col.g * k, col.b * k); } } + g.dispose(); return this; + }; + Builder.prototype.box = function (x, y, z, w, h, d, color, ry) { return this.add(new THREE.BoxGeometry(w, h, d), color, x, y, z, ry); }; + Builder.prototype.cyl = function (x, y, z, rt, rb, h, color, seg) { return this.add(new THREE.CylinderGeometry(rt, rb, h, seg || 10), color, x, y, z); }; + Builder.prototype.blob = function (x, y, z, r, color, sy, seed) { + var g = new THREE.IcosahedronGeometry(r, 1), P = g.attributes.position.array, rr = rng((seed || 1) * 977 + 5), cache = {}; + for (var i = 0; i < P.length; i += 3) { var key = P[i].toFixed(2) + P[i + 1].toFixed(2) + P[i + 2].toFixed(2), k = cache[key] || (cache[key] = 0.82 + rr() * 0.36); P[i] *= k; P[i + 1] *= k * (sy || 1); P[i + 2] *= k; } + g.computeVertexNormals(); return this.add(g, color, x, y, z, 0, 0.16); + }; + Builder.prototype.mesh = function (mat) { + var g = new THREE.BufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute(this.p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(this.n, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(this.c, 3)); + return new THREE.Mesh(g, mat || new THREE.MeshLambertMaterial({ vertexColors: true })); + }; + WR.Builder = Builder; + // boxes sharing one repeating texture, with texture coordinates taken from where each face is in the world + function texBoxes(list, h, y0, scale) { + var p = [], n = [], uv = []; + list.forEach(function (b) { + var g = new THREE.BoxGeometry(b[1] - b[0], h, b[3] - b[2]).toNonIndexed(); g.translate((b[0] + b[1]) / 2, y0 + h / 2, (b[2] + b[3]) / 2); + var P = g.attributes.position.array, N = g.attributes.normal.array; + for (var i = 0; i < P.length; i += 3) { p.push(P[i], P[i + 1], P[i + 2]); n.push(N[i], N[i + 1], N[i + 2]); + if (Math.abs(N[i + 1]) > .5) uv.push(P[i] * scale, P[i + 2] * scale); else if (Math.abs(N[i]) > .5) uv.push(P[i + 2] * scale, P[i + 1] * scale); else uv.push(P[i] * scale, P[i + 1] * scale); } + }); + var G = new THREE.BufferGeometry(); G.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); G.setAttribute('normal', new THREE.Float32BufferAttribute(n, 3)); G.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); return G; + } + function groundGeo(list, y, scale) { + var p = [], n = [], uv = []; + list.forEach(function (b) { [[0, 2], [0, 3], [1, 2], [1, 2], [0, 3], [1, 3]].forEach(function (v) { p.push(b[v[0]], y, b[v[1]]); n.push(0, 1, 0); uv.push(b[v[0]] * scale, b[v[1]] * scale); }); }); + var G = new THREE.BufferGeometry(); G.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); G.setAttribute('normal', new THREE.Float32BufferAttribute(n, 3)); G.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); return G; + } + function signTexture(lines) { + return new THREE.CanvasTexture(canvas(256, function (g) { + g.fillStyle = '#6b4526'; g.fillRect(0, 64, 256, 128); g.fillStyle = '#f3e3bd'; g.fillRect(6, 70, 244, 116); + g.fillStyle = '#3b2613'; g.textAlign = 'center'; g.font = '700 30px Fraunces, Georgia, serif'; g.fillText(lines[0], 128, 116, 232); + g.font = '600 24px Nunito, system-ui, sans-serif'; g.fillStyle = '#7a4a1e'; g.fillText(lines[1] || '', 128, 160, 232); + })); + } + + WR.buildWorld = function (scene) { + var T = WR.T || function (s) { return s; }; + var out = { gates: [], bins: [], shadowCasters: [] }; + // sky and far ground + var sg = new THREE.SphereGeometry(400, 24, 12), sc = [], sp = sg.attributes.position.array, c0 = new THREE.Color('#f6d9a8'), c1 = new THREE.Color('#9cc3e0'), c2 = new THREE.Color('#5f93c9'), tc = new THREE.Color(); + for (var i = 0; i < sp.length; i += 3) { var h = Math.max(0, sp[i + 1] / 400); if (h < .25) tc.copy(c0).lerp(c1, h / .25); else tc.copy(c1).lerp(c2, Math.min(1, (h - .25) / .6)); sc.push(tc.r, tc.g, tc.b); } + sg.setAttribute('color', new THREE.Float32BufferAttribute(sc, 3)); + var sky = new THREE.Mesh(sg, new THREE.MeshBasicMaterial({ vertexColors: true, side: THREE.BackSide, fog: false, depthWrite: false })); sky.renderOrder = -10; scene.add(sky); + var sun = new THREE.Mesh(new THREE.CircleGeometry(26, 24), new THREE.MeshBasicMaterial({ color: 0xfff1cf, fog: false, transparent: true, opacity: .9, depthWrite: false })); + sun.position.set(-190, 150, 200); sun.lookAt(0, 0, 0); sun.renderOrder = -9; scene.add(sun); + scene.fog = new THREE.Fog(0xead6b2, 45, 210); + var far = new THREE.Mesh(new THREE.PlaneGeometry(900, 900), new THREE.MeshLambertMaterial({ color: 0x6f8a45 })); far.rotation.x = -Math.PI / 2; far.position.y = -0.03; scene.add(far); + + // ground, one mesh per surface + var mats = [texLawn(), texPave(), texDeck(), texGravel()].map(function (c, i) { return new THREE.MeshLambertMaterial({ map: tex(c) }); }); + var scales = [0.5, 0.5, 0.8, 0.6], lists = [[], [], [], []]; + WR.AREAS.forEach(function (a) { lists[a.ground].push([a.x0, a.x1, a.z0, a.z1]); }); + lists.forEach(function (l, i) { if (!l.length) return; var m = new THREE.Mesh(groundGeo(l, 0, scales[i]), mats[i]); m.receiveShadow = true; scene.add(m); }); + var over = new THREE.Mesh(groundGeo(LAWNS, 0.012, scales[0]), mats[0]); over.receiveShadow = true; scene.add(over); + var gl = GRAVELS.concat(WR.GATES.map(gateBox)); + var gv = new THREE.Mesh(groundGeo(gl, 0.008, scales[3]), mats[3]); gv.receiveShadow = true; scene.add(gv); + // walls and hedges + var wall = new THREE.Mesh(texBoxes(WALLS, 2.6, 0, 0.42), new THREE.MeshLambertMaterial({ map: tex(texBrick()) })); wall.castShadow = wall.receiveShadow = true; scene.add(wall); + var cap = new THREE.Mesh(texBoxes(WALLS.map(function (w) { return [w[0] - .08, w[1] + .08, w[2] - .08, w[3] + .08]; }), 0.14, 2.6, 0.3), new THREE.MeshLambertMaterial({ color: 0xcfc6b4 })); scene.add(cap); + var hedge = new THREE.Mesh(texBoxes(HEDGES, 1.9, 0, 0.5), new THREE.MeshLambertMaterial({ map: tex(texHedge()) })); hedge.castShadow = hedge.receiveShadow = true; scene.add(hedge); + + // props, all one mesh + var B = new Builder(), r = rng(77); + var canopy = ['#d98a2b', '#c8502a', '#e2b53c', '#b83e25', '#d9a13a', '#9fae3d', '#cf6f2a']; + TREES.forEach(function (t, n) { + var s = t[2], x = t[0], z = t[1], hgt = 3.4 * s; + B.cyl(x, hgt / 2, z, 0.2 * s, 0.34 * s, hgt, '#5d4330', 7); + B.blob(x, hgt + 0.9 * s, z, 2.1 * s, canopy[n % canopy.length], 0.8, n + 1); + B.blob(x + 1.3 * s, hgt + 0.3 * s, z + 0.5 * s, 1.4 * s, canopy[(n + 2) % canopy.length], 0.8, n + 31); + B.blob(x - 1.1 * s, hgt + 0.5 * s, z - 0.8 * s, 1.5 * s, canopy[(n + 4) % canopy.length], 0.8, n + 61); + }); + // beyond the walls: a ring of trees so the horizon is not empty + for (var k = 0; k < 46; k++) { var ang = k / 46 * 6.283 + r() * .1, rad = 62 + r() * 30, tx = -2 + Math.cos(ang) * rad * 1.15, tz = -5 + Math.sin(ang) * rad * .9, ss = 2.2 + r() * 1.6; + B.cyl(tx, 2 * ss, tz, .25 * ss, .4 * ss, 4 * ss, '#5a4634', 5); B.blob(tx, 5.2 * ss, tz, 2.6 * ss, canopy[k % canopy.length], .9, k + 200); } + BENCHES.forEach(function (b) { var ry = b[2] ? Math.PI / 2 : 0; B.box(b[0], .42, b[1], 1.8, .08, .5, '#8a5a34', ry); B.box(b[0], .2, b[1], 1.5, .4, .1, '#3d3a36', ry); + var ox = b[2] ? .24 : 0, oz = b[2] ? 0 : .24; B.box(b[0] + ox, .72, b[1] + oz, 1.8, .34, .07, '#8a5a34', ry); }); + // fountain and pond + B.cyl(FOUNTAIN.x, .28, FOUNTAIN.z, FOUNTAIN.r, FOUNTAIN.r + .1, .56, '#bdb5a4', 20); B.cyl(FOUNTAIN.x, .9, FOUNTAIN.z, .22, .34, 1.3, '#aaa293', 10); B.cyl(FOUNTAIN.x, 1.55, FOUNTAIN.z, .8, .3, .16, '#bdb5a4', 14); + B.cyl(POND.x, .16, POND.z, POND.r, POND.r + .12, .32, '#a9a294', 26); + var water = new THREE.MeshLambertMaterial({ color: 0x3f7f8c, emissive: 0x16323a }); + var w1 = new THREE.Mesh(new THREE.CircleGeometry(FOUNTAIN.r - .22, 20), water); w1.rotation.x = -Math.PI / 2; w1.position.set(FOUNTAIN.x, .5, FOUNTAIN.z); scene.add(w1); + var w2 = new THREE.Mesh(new THREE.CircleGeometry(POND.r - .25, 26), water); w2.rotation.x = -Math.PI / 2; w2.position.set(POND.x, .27, POND.z); scene.add(w2); + for (k = 0; k < 14; k++) { var pa = r() * 6.28, pr = r() * (POND.r - .9); B.cyl(POND.x + Math.cos(pa) * pr, .285, POND.z + Math.sin(pa) * pr, .28 + r() * .2, .28, .02, '#4f8a3a', 9); if (k % 3 === 0) B.blob(POND.x + Math.cos(pa) * pr, .36, POND.z + Math.sin(pa) * pr, .13, '#f0a8c0', 1, k + 9); } + // glasshouses: white frames, plants inside, glass as a second mesh + var glassB = new Builder(); + GLASS.forEach(function (g, n) { + var cx = (g[0] + g[1]) / 2, cz = (g[2] + g[3]) / 2, w = g[1] - g[0], d = g[3] - g[2]; + B.box(cx, .3, cz, w, .6, d, '#9a6a4a'); + for (var zz = g[2]; zz <= g[3] + .01; zz += d / 4) { B.box(g[0] + .06, 1.5, zz, .12, 1.9, .12, '#f1efe6'); B.box(g[1] - .06, 1.5, zz, .12, 1.9, .12, '#f1efe6'); B.box(cx, 3.35, zz, .1, .1, .1, '#f1efe6'); } + B.box(cx, 3.42, cz, .14, .14, d, '#f1efe6'); B.box(g[0] + .06, 2.45, cz, .12, .12, d, '#f1efe6'); B.box(g[1] - .06, 2.45, cz, .12, .12, d, '#f1efe6'); + glassB.box(cx, 1.5, cz, w - .1, 1.9, d - .1, '#cfe9ee'); + var rl = Math.sqrt(w * w / 4 + 1), ra = Math.atan2(1, w / 2), g1 = new THREE.BoxGeometry(rl, .04, d); g1.rotateZ(ra); glassB.add(g1, '#cfe9ee', cx - w / 4, 2.95, cz); + var g2 = new THREE.BoxGeometry(rl, .04, d); g2.rotateZ(-ra); glassB.add(g2, '#cfe9ee', cx + w / 4, 2.95, cz); + for (var q = 0; q < 9; q++) B.blob(g[0] + 1 + r() * (w - 2), .9 + r() * .5, g[2] + 1 + r() * (d - 2), .5 + r() * .5, ['#3f7d3a', '#5a9a45', '#2f6a3a', '#7fae4a'][q % 4], 1.2, q + n * 20 + 300); + }); + var glass = glassB.mesh(new THREE.MeshLambertMaterial({ vertexColors: true, transparent: true, opacity: .26, depthWrite: false })); scene.add(glass); + // potting shed by the start + B.box(9.95, 1.15, 18.65, 3.5, 2.3, 2.1, '#7c8f6a'); B.box(9.95, 2.45, 18.65, 3.9, .22, 2.6, '#4b3a2c'); B.box(9.2, 1.0, 17.58, .9, 1.9, .06, '#5a4532'); B.box(10.8, 1.5, 17.58, .9, .7, .05, '#d9ecf0'); + // lamp posts + [[-11, 1], [11, 1], [-2.6, -1.2], [2.6, -1.2], [13.2, 12.6], [13.2, -12.6], [-13.2, -12.4], [35, 19], [35, -29], [-39, -29], [-39, 19], [-11, -29], [11, -29]].forEach(function (l) { + B.cyl(l[0], 1.5, l[1], .05, .08, 3, '#2f2f33', 6); B.blob(l[0], 3.1, l[1], .2, '#fff1c4', 1, 3); + }); + // chutes: a dark grate with a painted border + WR.CHUTES.forEach(function (c) { + var hh = WR.CHUTE_HALF; B.box(c.x, .006, c.z, hh * 2, .012, hh * 2, '#17130f'); + for (var q = -3; q <= 3; q++) B.box(c.x + q * .21, .024, c.z, .05, .024, hh * 2, '#4c4a46'); + [[0, -1], [0, 1], [-1, 0], [1, 0]].forEach(function (s) { B.box(c.x + s[0] * (hh + .07), .016, c.z + s[1] * (hh + .07), s[0] ? .14 : hh * 2 + .28, .03, s[0] ? hh * 2 + .28 : .14, '#e0b53a'); }); + }); + // bins: a slatted compost crate with a flag; the leaf heap inside is its own mesh so it can grow + WR.BINS.forEach(function (b, n) { + [[-.66, 0, .08, 1.4], [.66, 0, .08, 1.4], [0, -.66, 1.4, .08], [0, .66, 1.4, .08]].forEach(function (s) { for (var q = 0; q < 3; q++) B.box(b.x + s[0], .2 + q * .34, b.z + s[1], s[2], .26, s[3], q % 2 ? '#a9743f' : '#96653a'); }); + [[-.66, -.66], [.66, -.66], [-.66, .66], [.66, .66]].forEach(function (s) { B.box(b.x + s[0], .58, b.z + s[1], .12, 1.16, .12, '#6f4a2a'); }); + B.cyl(b.x + .66, 1.9, b.z + .66, .03, .03, 1.6, '#6f4a2a', 5); B.box(b.x + .66 + .25, 2.5, b.z + .66, .5, .3, .03, '#e2572f'); + var heap = new Builder().blob(0, 0, 0, .62, '#a8672b', .7, n + 40).mesh(); heap.position.set(b.x, .2, b.z); heap.scale.y = .3; scene.add(heap); + out.bins.push({ def: b, heap: heap }); + }); + var props = B.mesh(); props.castShadow = props.receiveShadow = true; scene.add(props); + // tree blob shadows, shown when real shadows are off + var blobG = new THREE.CircleGeometry(1, 16), blobM = new THREE.MeshBasicMaterial({ color: 0x1c1a10, transparent: true, opacity: .28, depthWrite: false }); + out.blobs = new THREE.Group(); TREES.forEach(function (t) { var m = new THREE.Mesh(blobG, blobM); m.rotation.x = -Math.PI / 2; m.position.set(t[0] + .8, .02, t[1] - .5); m.scale.set(3 * t[2], 2.4 * t[2], 1); out.blobs.add(m); }); scene.add(out.blobs); + // gates: two slatted leaves that swing open, and a sign over each + WR.GATES.forEach(function (g) { + var grp = new THREE.Group(), leaves = []; + [-1, 1].forEach(function (side) { + var gb = new Builder(); for (var q = 0; q < 5; q++) gb.box(side * -(0.16 + q * .29), 1.0, 0, .2, 1.9 + (q === 4 ? .2 : 0), .07, q % 2 ? '#3f6b52' : '#386049'); gb.box(side * -.72, .5, .05, 1.4, .1, .05, '#2c4a3a'); gb.box(side * -.72, 1.6, .05, 1.4, .1, .05, '#2c4a3a'); + var m = gb.mesh(); m.castShadow = true; var piv = new THREE.Group(); piv.position.x = side * 1.5; piv.add(m); grp.add(piv); leaves.push({ piv: piv, side: side }); + }); + var a = WR.AREAS[g.area], sign = new THREE.Mesh(new THREE.PlaneGeometry(2.2, 2.2), new THREE.MeshBasicMaterial({ transparent: true, side: THREE.DoubleSide })); sign.position.y = 2.75; grp.add(sign); + grp.position.set(g.x, 0, g.z); if (g.axis === 'z') grp.rotation.y = Math.PI / 2; scene.add(grp); + out.gates.push({ def: g, leaves: leaves, sign: sign, open: 0, target: 0 }); + }); + out.refreshSigns = function (state) { + out.gates.forEach(function (G) { var a = WR.AREAS[G.def.area], un = state && state.unlocked[G.def.area]; + if (G.sign.material.map) G.sign.material.map.dispose(); + G.sign.material.map = signTexture([T(a.name), un ? '' : T('Locked') + ' · ' + a.cost]); G.sign.material.needsUpdate = true; }); + }; + // light: a low warm sun, soft sky fill + var hemi = new THREE.HemisphereLight(0xcfe0ee, 0x7a6a48, 0.62); scene.add(hemi); + var dir = new THREE.DirectionalLight(0xffe0b0, 0.78); dir.position.set(-38, 46, 44); dir.target.position.set(-2, 0, -5); scene.add(dir); scene.add(dir.target); + var cam = dir.shadow.camera; cam.left = -52; cam.right = 52; cam.top = 46; cam.bottom = -46; cam.near = 5; cam.far = 150; dir.shadow.mapSize.set(2048, 2048); dir.shadow.bias = -0.0012; + out.sun = dir; out.sunDir = dir.position.clone().sub(dir.target.position).normalize(); + return out; + }; +})(); From 8ff19b465b2ebb003488e09f173869c2dbb8133b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:35:27 +0000 Subject: [PATCH 2/6] Windrow: leaf litter layer, denser leaf tiers, rake and layout fixes Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Cw2rMA4m89wq5xtvEXdXsk --- e63334287a3deaa3/windrow/js/game.js | 4 +-- e63334287a3deaa3/windrow/js/leaves.js | 37 ++++++++++++++++++++++----- e63334287a3deaa3/windrow/js/world.js | 2 +- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/e63334287a3deaa3/windrow/js/game.js b/e63334287a3deaa3/windrow/js/game.js index 528586bb..832c7ef6 100644 --- a/e63334287a3deaa3/windrow/js/game.js +++ b/e63334287a3deaa3/windrow/js/game.js @@ -22,7 +22,7 @@ { id: 'shoes', name: 'Light boots', text: 'Walk 10% faster', costs: [70, 190, 450] } ]; var SACK = [30, 55, 90, 140, 210, 320], HAND_RATE = [9, 14, 21, 30, 42], HAND_REACH = [0.95, 1.1, 1.25, 1.45, 1.7]; - var RAKE_W = [1.0, 1.4, 1.9, 2.5], BLOW_P = [15, 22, 31, 42], BLOW_R = [4.5, 5.8, 7.2, 9], BLOW_H = [0.3, 0.36, 0.42, 0.5]; + var RAKE_W = [1.0, 1.4, 1.9, 2.5], BLOW_P = [20, 28, 38, 50], BLOW_R = [4.5, 5.8, 7.2, 9], BLOW_H = [0.3, 0.36, 0.42, 0.5]; WR.sackCap = function (s) { return SACK[s.up.sack]; }; WR.rakeWidth = function (s) { return RAKE_W[s.up.rakeW]; }; var TOOL_NAMES = ['Hands', 'Rake', 'Blower']; @@ -482,7 +482,7 @@ WR.test = { state: function () { return state; }, p: p, start: function () { resume(); }, hold: function (on) { mouseUse = !!on; }, key: function (c, on) { if (on) keys.add(c); else keys.delete(c); }, mul: function (m) { WR.QUALITY.bench = m; state.set.q = 'bench'; applyQuality(); }, auto: function (on) { autoDrive = on; }, bench: function (steps) { var t0 = performance.now(), mx = 0, sum = 0; for (var i = 0; i < steps; i++) { update(1 / 60); var a = leaves.awakeCount(); sum += a; if (a > mx) mx = a; } return { ms: (performance.now() - t0) / steps, maxAwake: mx, avgAwake: Math.round(sum / steps), n: leaves.N }; }, - refresh: function () { hudStatic(); }, + refresh: function () { hudStatic(); }, beacons: function () { return vm.beacons.filter(function (b) { return b.visible; }).length; }, step: function (n) { for (var i = 0; i < n; i++) update(1 / 60); }, tool: setTool, give: function (n) { state.acorns += n; acDirty = true; }, buy: buy, unlock: unlock, interact: interact, open: open, close: closeTop, save: save, touch: setTouch, info: function () { return { awake: leaves.awakeCount(), n: leaves.N, alive: leaves.alive.slice(), acorns: state.acorns, bag: state.bagFill, playing: playing(), prompt: prompt && prompt.text }; } }; diff --git a/e63334287a3deaa3/windrow/js/leaves.js b/e63334287a3deaa3/windrow/js/leaves.js index eff9da76..a1b5a9cf 100644 --- a/e63334287a3deaa3/windrow/js/leaves.js +++ b/e63334287a3deaa3/windrow/js/leaves.js @@ -9,7 +9,7 @@ (function () { 'use strict'; var WR = window.WR, CELL = WR.CELL, GW = WR.GW, GH = WR.GH, X0 = WR.X0, Z0 = WR.Z0; - var CAP = 16, HARD = 34, LH = 0.014, BASE = 0.014; + var CAP = 16, HARD = 34, LH = 0.014, BASE = 0.024; var DEAD = 0, SLEEP = 1, AWAKE = 2, TOBAG = 3, SINK = 4; var SHAPES = [ { pts: [[0, -.5], [.22, -.15], [.2, .25]], big: 1 }, // oval, 6 triangles @@ -54,7 +54,7 @@ for (var k = 0; k < counts[ai]; k++, i++) { var q = r(), s2 = q < .34 ? 0 : q < .6 ? 1 : q < .8 ? 2 : 3; area[i] = ai; meshOf[i] = base + s2; slot[i] = perMesh[base + s2]++; - scl[i] = (0.2 + r() * 0.12) * SHAPES[s2].big; off[i] = r() * 0.012; rp[i] = (r() - .5) * .5; rr[i] = (r() - .5) * .5; + scl[i] = (0.2 + r() * 0.12) * SHAPES[s2].big * (mul < 1 ? 1.15 : 1); off[i] = r() * 0.012; rp[i] = (r() - .5) * .5; rr[i] = (r() - .5) * .5; col.set(a.pal[(r() * a.pal.length) | 0]); var b = 0.8 + r() * 0.35; cols.push(col.r * b, col.g * b, col.b * b); } for (s = 0; s < 4; s++) { @@ -68,6 +68,28 @@ for (i = 0; i < N; i++) { col.setRGB(cols[i * 3], cols[i * 3 + 1], cols[i * 3 + 2]); meshes[meshOf[i]].setColorAt(slot[i], col); } meshes.forEach(function (m) { if (m.instanceColor) m.instanceColor.needsUpdate = true; }); + /* Leaf litter: the crumbs and dust that lie wherever leaves do. One see-through sheet over the whole garden whose + opacity comes from a small texture with one pixel per grid cell (how many leaves are in it). It fades out about a + second after a cell is emptied, which is what shows the clean lawn, paving and decking coming back. */ + var litterDirty = true, litterT = 0, lit = new Uint8Array(GW * GH * 4), litTex = new THREE.DataTexture(lit, GW, GH, THREE.RGBAFormat); + litTex.magFilter = litTex.minFilter = THREE.LinearFilter; litTex.needsUpdate = true; + var litC = document.createElement('canvas'); litC.width = litC.height = 256; + (function (g) { var q = WR.rng(5150), cols = ['#8a5a2a', '#a06a2e', '#6f4a26', '#b9822f', '#7a4a22', '#c08a3a', '#5e4126']; + for (var k = 0; k < 1500; k++) { g.fillStyle = cols[(q() * cols.length) | 0]; g.globalAlpha = 0.6 + q() * 0.4; g.beginPath(); g.ellipse(q() * 256, q() * 256, 1.5 + q() * 5, 1 + q() * 2.6, q() * 3.14, 0, 6.3); g.fill(); } + g.globalAlpha = 0.7; g.strokeStyle = '#5a4026'; g.lineWidth = 1; for (k = 0; k < 60; k++) { var x = q() * 256, y = q() * 256; g.beginPath(); g.moveTo(x, y); g.lineTo(x + (q() - .5) * 16, y + (q() - .5) * 16); g.stroke(); } })(litC.getContext('2d')); + var litMap = new THREE.CanvasTexture(litC); litMap.wrapS = litMap.wrapT = THREE.RepeatWrapping; litMap.repeat.set(GW * CELL / 1.7, GH * CELL / 1.7); litMap.anisotropy = 4; + var litGeo = new THREE.PlaneGeometry(GW * CELL, GH * CELL); litGeo.rotateX(-Math.PI / 2); + (function (uv) { for (var k = 0; k < uv.count; k++) uv.setY(k, 1 - uv.getY(k)); })(litGeo.attributes.uv); + var litter = new THREE.Mesh(litGeo, new THREE.MeshLambertMaterial({ map: litMap, alphaMap: litTex, transparent: true, depthWrite: false })); + litter.position.set(X0 + GW * CELL / 2, 0.016, Z0 + GH * CELL / 2); litter.receiveShadow = true; litter.renderOrder = 1; scene.add(litter); + function litterUpdate(dt, all) { + litterT += dt; if (!all && (!litterDirty || litterT < 0.12)) return; litterT = 0; + var moving = false; + for (var c = GW, o = GW * 4 + 1, end = cnt.length - GW; c < end; c++, o += 4) { var want = (cnt[c] * 2 + cnt[c - 1] + cnt[c + 1] + cnt[c - GW] + cnt[c + GW]) * 70; if (want > 255) want = 255; var have = lit[o]; if (have === want) continue; + if (all) have = want; else if (have < want) have = Math.min(want, have + 70); else { have = Math.max(want, have - 30); } lit[o] = have; if (have !== want) moving = true; } + litterDirty = moving; litTex.needsUpdate = true; + } + function cellOf(x, z) { var ci = Math.floor((x - X0) / CELL), cj = Math.floor((z - Z0) / CELL); return (ci < 0 || cj < 0 || ci >= GW || cj >= GH) ? -1 : ci + cj * GW; } function write(i, s) { var m = meshOf[i], a = meshes[m].instanceMatrix.array, o = slot[i] * 16; dirty[m] = true; @@ -78,12 +100,12 @@ a[o + 8] = sy * cp * k; a[o + 9] = -sp * k; a[o + 10] = cy * cp * k; a[o + 11] = 0; a[o + 12] = px[i]; a[o + 13] = py[i]; a[o + 14] = pz[i]; a[o + 15] = 1; } - function link(i, c) { lcell[i] = c; next[i] = head[c]; prev[i] = -1; if (head[c] >= 0) prev[head[c]] = i; head[c] = i; rank[i] = cnt[c]; cnt[c]++; } + function link(i, c) { lcell[i] = c; next[i] = head[c]; prev[i] = -1; if (head[c] >= 0) prev[head[c]] = i; head[c] = i; rank[i] = cnt[c]; cnt[c]++; litterDirty = true; } function unlink(i) { var c = lcell[i], rk = rank[i]; if (c < 0) return; if (prev[i] >= 0) next[prev[i]] = next[i]; else head[c] = next[i]; if (next[i] >= 0) prev[next[i]] = prev[i]; - cnt[c]--; lcell[i] = -1; + cnt[c]--; lcell[i] = -1; litterDirty = true; for (var j = head[c]; j >= 0; j = next[j]) if (rank[j] > rk) { rank[j]--; if (st[j] === SLEEP) { py[j] -= LH; write(j); } } } function wake(i) { if (st[i] !== SLEEP) return; st[i] = AWAKE; idle[i] = 0; aidx[i] = awakeN; awake[awakeN++] = i; } @@ -144,6 +166,7 @@ } else { scatter(ai, Math.max(0, 1 - done)); self.touched[ai] = done > 0; } first += counts[ai]; }); + litterUpdate(0, true); })(); // share of an area's leaves that are out of the garden for good (not on the ground, not in the sack) this.share = function (ai) { return Math.max(0, Math.min(1, 1 - (this.alive[ai] * this.w[ai] + (state.bagUnits[ai] || 0)) / A[ai].units)); }; @@ -204,7 +227,7 @@ } else idle[i] = 0; write(i); } - this.moved = moved; + this.moved = moved; litterUpdate(dt); for (var m = 0; m < meshes.length; m++) if (dirty[m]) { meshes[m].instanceMatrix.needsUpdate = true; dirty[m] = false; } }; @@ -290,7 +313,9 @@ }; this.eachAlive = function (fn) { for (var k = 0; k < N; k++) if (st[k] === SLEEP || st[k] === AWAKE) fn(px[k], pz[k], area[k]); }; this.countIn = function (x, z, rad) { var n = 0; eachIn(x - rad, z - rad, x + rad, z + rad, function (l) { if (st[l] <= AWAKE && (px[l] - x) * (px[l] - x) + (pz[l] - z) * (pz[l] - z) < rad * rad) n++; }); return n; }; - this.dispose = function () { meshes.forEach(function (m) { scene.remove(m); m.dispose && m.dispose(); }); geos.forEach(function (g) { g.dispose(); }); mat.dispose(); }; + // test scripts only: take every leaf of an area off the ground except `keep` of them + this._testClear = function (ai, keep) { var first = 0, k, left = 0; for (k = 0; k < ai; k++) first += counts[k]; for (k = first; k < first + counts[ai]; k++) if (st[k] === SLEEP || st[k] === AWAKE) { if (left < keep) left++; else kill(k); } self.touched[ai] = true; dirty.fill(true); }; + this.dispose = function () { scene.remove(litter); litGeo.dispose(); litTex.dispose(); litMap.dispose(); litter.material.dispose(); meshes.forEach(function (m) { scene.remove(m); m.dispose && m.dispose(); }); geos.forEach(function (g) { g.dispose(); }); mat.dispose(); }; } WR.Leaves = Leaves; diff --git a/e63334287a3deaa3/windrow/js/world.js b/e63334287a3deaa3/windrow/js/world.js index 710ac772..f487aaf8 100644 --- a/e63334287a3deaa3/windrow/js/world.js +++ b/e63334287a3deaa3/windrow/js/world.js @@ -23,7 +23,7 @@ { id: 'maze', name: 'Maze Lawn', x0: -40, x1: -12, z0: -30, z1: 20, ground: LAWN, leaves: 3600, units: 9000, cost: 2800, need: [1, 0.5], bonus: 2000, reward: 'crown', rewardName: 'Keeper of Windrow', rewardText: 'The gardens are open again', pal: ['#8e2f3a', '#a8402c', '#6f2a3a', '#c25a2e', '#7a3a24'] } ]; - WR.QUALITY = { low: 0.6, medium: 1.4, high: 2.8 }; // times each area's `leaves`: 6,900 / 16,100 / 32,200 in all + WR.QUALITY = { low: 0.8, medium: 1.4, high: 2.8 }; // times each area's `leaves`: 9,200 / 16,100 / 32,200 in all // gates: the gap in a wall that opens when `area` is unlocked. axis 'x' = the gap runs along x. WR.GATES = [ From 4fb85a219c94dd422295f1e8cfee5d2fe8865eb3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:39:35 +0000 Subject: [PATCH 3/6] Windrow: Spanish, Back Room card, phone page row, README, What's new entry, agent Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Cw2rMA4m89wq5xtvEXdXsk --- .claude/agents/windrow.md | 45 +++++++++++ .claude/scripts/gen_game_agents.py | 1 + README.md | 1 + e63334287a3deaa3/es.js | 12 +++ e63334287a3deaa3/index.html | 32 +++++++- e63334287a3deaa3/m/index.html | 1 + e63334287a3deaa3/m/thumbs/windrow.jpg | Bin 0 -> 44270 bytes .../news/ngcoding10-leaf-game.json | 27 +++++++ e63334287a3deaa3/windrow/es.js | 75 +++++++++++++++++- e63334287a3deaa3/windrow/preview.jpg | Bin 0 -> 343351 bytes 10 files changed, 191 insertions(+), 3 deletions(-) create mode 100644 .claude/agents/windrow.md create mode 100644 e63334287a3deaa3/m/thumbs/windrow.jpg create mode 100644 e63334287a3deaa3/news/ngcoding10-leaf-game.json create mode 100644 e63334287a3deaa3/windrow/preview.jpg diff --git a/.claude/agents/windrow.md b/.claude/agents/windrow.md new file mode 100644 index 00000000..a40d6341 --- /dev/null +++ b/.claude/agents/windrow.md @@ -0,0 +1,45 @@ +--- +name: windrow +description: Specialist for Windrow (e63334287a3deaa3/windrow/). Use for any change to Windrow: bug fixes, new features, balance, graphics, performance, phone/touch controls. Knows its files, storage keys and the repo rules that apply to it. +--- + +You are the specialist for **Windrow**, a game on Arjun's site (ascoding11.github.io). You make changes to this one game and leave the rest of the repo alone. + +## What it is + +Windrow (Back Room), a calm single-player first-person game about clearing autumn leaves out of five walled gardens (three.js: the site's own r187 build, `/lib/three/r187/three.min.js` with its r128 layer, then `../autores.js`; no Firebase and no rooms, except `stats.js` for play time; no ads). The name is the word for the long row of leaves a rake leaves behind. The page is `index.html` (markup, styles, HUD and menus) plus five plain scripts in `js/`, loaded in this order: `world.js` (the areas, the collision grid and everything that stands still), `leaves.js` (the leaf simulation and its drawing), `audio.js` (every sound, made in code), `models.js` (gloves, sack, rake, blower, finder beams) and `game.js` (player, tools, money, HUD, menus, saving, the frame loop); `es.js` is its Spanish. Everything is drawn and textured in code; nothing is downloaded. + +## Where it lives + +- Folder: `e63334287a3deaa3/windrow/`: `es.js`, `index.html`, `js/`, `preview.jpg` +- Docs: the bullet for `e63334287a3deaa3/windrow/` in `README.md` (and the indented points under it). This is the source of truth for how the game works and stores data; read it in full before changing anything, and update it when you change behaviour, storage or file layout. +- Phone page: a row in `GROUPS` in `e63334287a3deaa3/m/index.html` and thumbnail `e63334287a3deaa3/m/thumbs/windrow.jpg`. + +## What it uses (detected from the code) + +- three.js (global r128 build from cdnjs, not ES modules) +- `../autores.js` loaded straight after three.min.js (automatic resolution) +- `../stats.js` for play time / Leaderboards +- `../keybinds.js` rebindable controls (keep its `keybinds:` storage key) + +## Must stay true + +- Keep every storage path, room prefix, localStorage key, stats/leaderboard id and saved-data format working exactly as it is, so players' saved progress, settings, ratings and invite links carry over. Old names mentioned above (folder, keys, ids) are kept on purpose: never "tidy" them. +- Don't change Firebase security rules or the Firebase config, and don't create a new Firebase project. If a change needs storage the rules don't allow, stop and say so instead. +- Keep the keyboard-and-mouse version unchanged on computers, and keep the touch controls working: shown only on touch screens, nothing overlapping in portrait or with the phone sideways. +- This is a Back Room page: keep ``, keep it out of `sitemap.xml`, and never link to it from the public pages. +- Write all game text, questions and prompts in your own words; no copyrighted text. No new outside scripts, trackers or ads. + +## How to work + +1. Read `CLAUDE.md`, then this game's README entry, then the code you are about to change. Follow the code where the docs and the code disagree, and fix the docs. +2. Make the smallest change that does the job. One feature or fix per pull request; leave unrelated code alone. +3. Any change players can notice gets an entry at the top of `NEWS` in `e63334287a3deaa3/news.js` (follow the how-to at the top of that file: date, next version, `kind`, short title, bullets written for players) and the Spanish for each new line in `e63334287a3deaa3/news-es.js`. +4. Test by serving the repo (`python3 -m http.server` from the repo root) and opening `/e63334287a3deaa3/windrow/` with Playwright (pre-installed; `require('playwright')`, `chromium.launch()`): a laptop size such as 1366×768, a phone in portrait (390×844) and sideways (844×390) with touch on. Check the console for errors. +5. Commit and push only when asked; never open a pull request unless asked. When you do, start the description with plain-English bullets of what changed and which pages it affects, and call out anything risky. + +## Skills to use + +Load the ones that fit the task with the Skill tool: `game-graphics` (looks), `game-performance` (frame rate, load time), `threejs-materials-lighting` and `threejs-scene-setup` (they target r187 ES modules: translate to this game's r128 global build), `physics-tuning`, `game-feel`, `audio-design`. General skills often show Godot or Unity code; translate the idea to plain JavaScript, and where they disagree with `CLAUDE.md` or the repo's own skills, those win. + +When you finish, report what you changed (files and why), how you tested it, and anything you could not do or that Arjun needs to decide. diff --git a/.claude/scripts/gen_game_agents.py b/.claude/scripts/gen_game_agents.py index 9069bbb6..37c242cb 100644 --- a/.claude/scripts/gen_game_agents.py +++ b/.claude/scripts/gen_game_agents.py @@ -76,6 +76,7 @@ 'patchwork-tower': ['create-game-assets', 'game-feel'], 'flickerwood': ['game-ai', 'level-design', 'create-game-assets'], 'lanternhold': ['tower-defense', 'game-ai'], + 'windrow': ['physics-tuning', 'game-feel', 'audio-design'], 'ninefold': ['puzzle'], 'quartets': ['puzzle'], 'crosslet': ['puzzle'], 'sleight': ['puzzle'], 'poopdle': ['puzzle'], 'back-four': ['puzzle'], 'starhop': ['game-feel'], 'quarry': ['survival-crafting', 'procedural-gen'], diff --git a/README.md b/README.md index 01b6b92a..f8fa622a 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - `e63334287a3deaa3/patchwork-tower/`: Patchwork Tower (Back Room), a one-screen fix-it arcade game in pixel art for one player (one file, one canvas, Web Audio, no libraries, no Firebase except stats.js). It took the place of Hivefix; `e63334287a3deaa3/hivefix/index.html` is now only a redirect to it, so old links and bookmarks still work (`m/thumbs/hivefix.jpg` stays for the old What's new entry). Rivet, a repair bot with a wrench, hops between the windows of a brick tower at night (5 across, 4 down) and fixes each broken one until it glows; cracked windows take one fix, dark ones two, and fixing roots the bot to the spot. A gargoyle walks along the roof, stops over a column (more often than not the bot's), winds up (eyes red, a red arrow under the roof ledge on every column about to be hit) and kicks a brick straight down it. Clearing every window ends the floor (500 plus 10 for each second left of 60) and the next one starts with a new layout. **Rules** live between `// ==RULES==` and `// ==END RULES==`: no page, clock, sound or `Math.random` in there, so the same seed and presses always give the same game (`create(seed)`, `step(g, 1/120)`, `press(g, k)` for a tap and `hold(g, k, on)` while a key or button is down, with k one of up, down, left, right, fix; what should be heard goes into `g.ev` as words the page plays). `g.win[r][c]` is 0 fixed / 1 cracked / 2 dark; `g.blockV[r][c]` is a planter under the sill of (r, c), which blocks climbing between rows r and r+1; `g.blockH[r][c]` is an open shutter between (r, c) and (r, c+1), which blocks stepping sideways. **Tuning** is the constants at the top of the rules: a hop takes 0.12 s (`HOP`), a fix 0.26 s (`FIX`; 0.08 s with cocoa), a press made during a hop or fix is remembered for 0.3 s (`BUF`), a held direction or FIX repeats after 0.22 s (`REPEAT`), the wind-up is 0.4 s (`TELE`) plus 0.3 s on floor 1 shrinking to nothing by floor 4 (`TELE_EARLY`), 3 lives, a hit freezes the world for 1 s and restarts the bot at the door with 2 s of blinking. Per floor: 7 + 2 × floor windows broken (all 20 from floor 7), the chance one is dark is 0.15 + 0.1 × floor up to 0.75, one more planter or shutter each floor up to four (each on its own edge, redrawn until every window can be reached), the gargoyle walks at 55 + 9 × floor pixels a second, bricks fall at 65 + 11 × floor, and its rest between kicks is 1.5 − 0.13 × floor seconds, never under 0.35; the speeds stop rising at floor 12 (`TOP_LEVEL`). From floor 2, bats cross a row (an arrow blinks at that edge of the row for 0.8 s first, `BAT_WARN`); from floor 3 a kick sometimes (35%) sends a second brick down a neighbouring column 0.18 s later, chosen at the start of the wind-up so its arrow shows too. Cocoa appears on a sill now and then for 7 s: 6 s safe from everything, the first 4 with one-tap repairs, +300. The hit boxes are narrower than the sprites (9 pixels either side for bricks and bats). **Drawing**: the game is a 240 × 320 picture. `layout()` shows it at a whole number of device pixels per game pixel (the canvas is sized in device pixels and scaled back by 1/devicePixelRatio, its corner snapped to a device pixel), so pixels stay square and sharp on any screen; never size the canvas with CSS percentages or `vh`. The sky, skyline and brickwork are drawn once (`back`), the windows, planters and shutters are redrawn only when one changes (`g.winDirty`), and words use a 5 × 5 pixel alphabet drawn in code (`FONT`, capitals, digits and `+ - : ! .` only), not a web font. The loop runs the rules in fixed steps of 1/120 s and draws between steps, so it plays at the same speed on 60, 120 and 144 Hz screens. The game pauses when the tab is hidden or the window loses focus. **Saved in the browser only**: `patchwork-best`, `patchwork-mute` (in try/catch), keys under `keybinds:patchwork-tower`. Stats hook: `max('score', score)` and `max('floor', floor reached)` when a floor is cleared and at game over (the Leaderboards show best score). Controls: arrows or WASD hop (hold to keep hopping), Space, Z or X fix (hold to keep fixing), P, Enter or Esc pause, M sound, all rebindable under KEYS. On touch screens (`body.touch`): a d-pad (slide a thumb between arrows) and a round FIX button under the screen, or either side of it when the phone is sideways. How to play sits beside the screen when there is room, otherwise behind the ? button. A test hook (`window.__pt`) exists only when `navigator.webdriver` is set. It has Spanish: its words are in `patchwork-tower/es.js` (lang.js), with a Language switch in How to play; the canvas words are chosen to need no accents, since the 5×5 pixel font has none. **The Wardrobe** (captains only for now, like the other games' hidden cosmetics): 29 looks for Rivet in `patchwork-tower/wardrobe.js`, listed in `cosmetics.js` under `GAMES['patchwork-tower']` (15 paint jobs, 7 hats, 3 face pieces and 4 hop trails: sports kits, tin and chrome robots, pirates, suits and more). The page fetches `wardrobe.js` and `../cosmetics.js` only when `wardrobeOn()` is true (`PATCHWORK_PUBLIC`, the one line that opens it to everyone; a site captain through `captains.js`; or `?wardrobe=1` on localhost or in an automated browser), and then a hanger button appears in the top bar; for everyone else `WR` stays null and the bot is drawn exactly as before. Looks only: a paint job recolours the bot's own rectangles (cocoa still turns it gold, the blinking after a hit is unchanged), every paint stands out from the bricks at least 3.5 times (`MIN_CR`; factory teal is 4.1) and none is brick-orange or bat-lilac, hats sit on the head (some in place of the antenna), face pieces go on the visor, and hop trails are drawn under the bricks, bats and bot and fade within half a second. Opening it pauses a game in progress. What is worn is saved in this browser as `patchwork-look` (`{p, h, f, t}`, item numbers, 0 for none); nothing is sent anywhere. The words are in `es.js`. - `e63334287a3deaa3/flickerwood/`: Flickerwood (Back Room), an 8-bit maze chase for one player (one file, one canvas, Web Audio, no libraries, no Firebase except stats.js). Glim, a firefly, gathers every speck of pollen in a moonlit hedge maze (a glade) while four night critters come out of the hollow stump in the middle and chase its light. It is our own take on the maze-chase genre: the name, theme, characters, mazes, art, sounds, words and numbers are all ours, and only the genre's ideas are used. **The four critters** never find a path: at the middle of every tile each one picks the open way (never straight back) whose next tile is nearest, in a straight line, to the tile it wants (`target()`), and all of its character is in that tile. Swoop the bat wants Glim's tile; Gulp the frog wants the tile 3 ahead of the way Glim faces (`AHEAD`); Tangle the spider wants the point on the far side of Glim from Swoop (twice Glim's tile minus Swoop's); Dither the moth wants Glim while more than 5 tiles away (`NEAR`) and its own corner once closer. They take turns at two moods on a clock: **roost** (each heads for its own corner: Swoop top right, Gulp top left, Tangle bottom right, Dither bottom left) and **hunt**; every time the mood changes they all turn straight round, which is the tell. Glim is faster than they are in an empty corridor and a little slower while eating, turns can be pressed early and are remembered until the next gap, a turn started up to 4 pixels before the middle of a tile cuts the corner and gains those pixels (`CUT`; up to 3 pixels late it is still taken, `LATE`), and a reverse is taken anywhere. A **moonbloom** (four a glade) dazzles the critters: they turn round, go pale, slow to 60% and mostly run away, and touching one sends it home as a puff of dust for 100, 250, 500 then 1000 (`CATCH`); they flicker for the last 2 seconds, and a caught one rests 1.2 s in the stump and comes back out as itself. **Tunnels** at the edges (`~` tiles) wrap round and slow critters to 55%. A **find** (dewdrop, acorn, clover, toadstool, bluebell, feather, snail shell, moonstone, one kind a glade) shows under the stump for 9 s when 35% and again when 70% of the glade is eaten, worth 200 plus 100 a glade up to 1000. Our own twists: **Dash** (0.32 s at 2.1 times speed, then 6 s to recharge, shown as a meter) and the **chain** (each speck eaten within 1 s of the last carries it on; every 12 raises the multiplier on specks, up to 5 times). Specks are 5, moonblooms 30, clearing a glade 100 times its number up to 1000 plus 300 if no life was lost in it; 3 lives, one more at 6,000 and every 15,000 after, 5 at most. **Rules** live between `// ==RULES==` and `// ==END RULES==`: no page, clock, sound or `Math.random` in there, so the same seed and presses always give the same game (`create(seed)`, `startGame(g)`, `step(g, 1/120)`, `turn(g, d)` with d 0 right, 1 down, 2 left, 3 up, and `dash(g)`; what should be heard or shown goes into `g.ev` as words, and eaten tiles into `g.gone`). Positions in the rules are maze pixels; the page adds the score bar above. Glim and the critters are a tile, a direction and how far along it they are (`c, r, dir, off`), so they can never leave a path; they touch when both gaps are under 7 pixels (`HIT`, smaller than the sprites). **Glades** are the five `MAZES` at the top of the rules, drawn by hand as 23 rows of 21 letters (12-pixel tiles): `#` hedge, `.` pollen, `o` moonbloom, `-` path, `~` tunnel, `HHH` the stump with `G` its gate above the middle, `P` Glim's start, `B` the find, space outside the glade. Hedge Court is a full rectangle with a tunnel across the middle, Lily Pond has its corners cut off and tunnels top to bottom, Bramble Wheel is not mirrored (its bottom half is its top half turned half round) and has two tunnels, Mossy Ruin has tunnels both ways through the middle of each edge, and Moth Hollow is an hourglass with none; glade 6 is Hedge Court again, quicker. A new or changed glade must stay: every path one tile wide (no open 2 × 2), no dead ends, all joined up, a border tile that is a path matched on the opposite border, the start at least 8 steps from the gate with a way left and right (Glim sets off left), one moonbloom in each quarter, nothing but hedge next to the outside. A script checked all of that for the five glades when they were made (it is not in the repo), so check again by hand if you change one. **Tuning** is `tune(level)` and the constants at the top of the rules: Glim 66 pixels a second plus 1.3 a glade; critters 70% of that plus 3 points a glade (97% at glade 10); the dazzle 8 s less 0.67 s a glade, never under 2; roosts of 7, 7, 5 and 4 s (less 0.55 s a glade, never under 1.5) between hunts of 13, 15 and 18 s (plus 1.2 s a glade), then hunting for good; Gulp leaves the stump after 3 s, Tangle after 12 s or 30 specks, Dither after 28 s or 90 specks, all sooner glade by glade; from glade 3 Swoop speeds up 6% when 20% of the pollen is left and 12% under 8%, and keeps hunting through roosts; nothing tightens after glade 10 (`TOP_LEVEL`). Glade 1 is meant to be cleared by a first-time player: a test bot that only heads for the nearest pollen and runs when something is three tiles away clears it nearly every time. **Drawing**: the game is a 252 × 300 picture (a 14-pixel score bar, the 252 × 276 maze, a 10-pixel strip for spare lives, the dash meter and finds). `layout()` shows it at a whole number of device pixels per game pixel, so pixels stay square and sharp, and tries three places for it, biggest picture first: under the top bar with the key hint, under the bar without the hint, and between the bar's title and buttons (so a 1366 × 768 laptop with a short browser window still gets 2 ×); only when a whole number would be 1 is it drawn at 2 and shrunk smoothly to fit. Never size the canvas with CSS percentages or `vh`. Sprites are rows of letters turned into small canvases once (`bake`; Glim is drawn facing right and turned for the other three ways; two frames each; the dazzled look is the same shapes in two pale tones); the hedges, stump and tunnel marks are drawn once per glade (`mazeL`, and a lit copy `flashL` for the blink when a glade is cleared), the pollen sits on its own layer and each speck is wiped from it as it is eaten, the score bar is redrawn only when something on it changes, and words use a 5 × 5 pixel alphabet drawn in code (capitals, digits and `+ - : ! .` only). The loop runs the rules in fixed steps of 1/120 s and draws between steps. It pauses when the tab is hidden or the window loses focus. **Sound** is made in the page: square, triangle and noise blips in `SFX`, and a 16-bar tune of our own in A minor in `TUNE` (notes as numbers), booked a tenth of a second ahead on the audio clock; while a moonbloom is on, a quicker bright figure plays instead. Nobody has listened to it yet, so the loudness and the tune want a check by ear. **Saved in the browser only**: `flickerwood-best` (score), `flickerwood-glade` (furthest glade), `flickerwood-mute` (in try/catch), keys under `keybinds:flickerwood`. Stats hook: `max('score', score)` and `max('glade', glade reached)` when a glade is cleared and at game over (the Leaderboards show best score). Controls: arrows or WASD turn, Space or Shift dashes, P, Enter or Esc pause, M sound, all rebindable under KEYS. On touch screens (`body.touch`): swipe anywhere to turn (keep sliding to turn again without lifting), tap the screen to dash, or use the d-pad with a DASH button either side of it under the screen (pad on the left and DASH on the right when the phone is sideways). How to play, with a picture of each character, sits beside the screen when there is room, otherwise behind the ? button. A test hook (`window.__fw`) exists only when `navigator.webdriver` is set. It has Spanish: its words are in `flickerwood/es.js` (lang.js), with a Language switch in How to play; the canvas words are chosen to need no accents (the 5×5 pixel font has none), and glade and critter names stay English. **The Wardrobe** (captains only for now, like the other games' hidden cosmetics): 28 looks for Glim in `flickerwood/wardrobe.js`, listed in `cosmetics.js` under `GAMES.flickerwood` (14 kits, 7 hats, 2 face pieces and 5 trails: sports kits, a tin firefly, pirates, suits and more, all seen from above). The page fetches `wardrobe.js` and `../cosmetics.js` only when `wardrobeOn()` is true (`FLICKERWOOD_PUBLIC`, the one line that opens it to everyone; a site captain through `captains.js`; or `?wardrobe=1` on localhost or in an automated browser), and then a hanger button appears in the top bar; for everyone else `WR` stays null and Glim is drawn exactly as before. Looks only: a look swaps `SP.glim` for pictures of the same 16 × 16 size (so the spare Glims on the score bar wear it too), no kit recolours the glowing yellow tail or the halo (what tells Glim from the critters), and trails are drawn under the critters and Glim, fade in 0.4 s and are never small yellow dots that could pass for pollen. Opening it pauses a game in progress. What is worn is saved in this browser as `flickerwood-look` (`{k, h, f, t}`, item numbers, 0 for none); nothing is sent anywhere. The words are in `es.js`. - `e63334287a3deaa3/lanternhold/`: Lanternhold (Back Room), a co-op tower defense game for 1 to 4 players (one file, three.js r128 with `../autores.js`, `../netsmooth.js` for teammates' pointers, Web Audio, Firebase Realtime Database rooms under `rooms/lh-`, same project and rules as Rumble Karts; invite links go through the home page as `#lh-`; no Quick match, rooms hold up to 4). The name, the Gloom, the towers, the maps, the art and the sounds are all our own. The Gloom walks a road across a floating island (a 20 × 12 grid of 2 m tiles, `GW`/`GH`/`T`) to the lantern; each one that gets there costs lives (`lv` in `EN`: 1, 2 for Shellbacks and Splitblobs, 15 for the boss). Towers go on grass tiles only (not road, scenery or the lantern). **Rules** are plain data and pure functions near the top of the script, the same in every browser, so a client can work out wave previews and enemy health without asking: `MAPS` (Meadow Bend, one long road; Twin Fords, two roads that meet; Whorl Garden, a spiral, whose flyers come from their own pink gate, `fly`, so they don't skip almost the whole map), `DIFFS` (Easy, Normal, Hard: health factor, lives 30/20/12, starting gold 720/620/540, bounty factor and seconds between waves), `EN` (Gloomling; Skitter, fast; Shellback, armour 7 taken off every hit, at least a quarter always goes through; Duskmoth, flies straight at the lantern; Splitblob, splits into three Bloblets; Mender, heals the Gloom near it 5% a second; Gloomwarden, the boss on every 10th wave, armoured, slow, and calls two Skitters every 5 s), `TW` (Bolt Spire, quick single shots, two at once at level 3; Thumper, lobbed blasts that hurt groups, ground only; Frost Bell, rings out to slow and chip everything near it, bosses half as much; Spark Coil, lightning that jumps between enemies; Sky Lance, flyers only, splash on nearby flyers; Sun Lens, a long beam that ignores armour), each with three levels (`lv`: range, damage, seconds between shots and the upgrade's cost) and a target mode (First, Last, Strong, Close). Selling gives back 70% of what went into the tower (`SELL`). `waveDef(w, map)` builds wave w from a seeded random pool (new kinds join at waves 2, 4, 5, 6 and 8, and the wave a kind first appears always has a group of it), `hpScale` makes them tougher each wave and faster still after wave 30. Survive 30 waves (`CAMPAIGN`) to win; then Keep going is endless mode. Gold: every kill's bounty and every wave's bonus (25 + 5 a wave) is split evenly between the players (`income`), each player spends their own share, and the team list has +50 to give gold to a teammate. Sending a wave before its countdown ends pays 2 gold per second left. Speed 1×, 2× or 3× (`sp`, anyone can change it). Only whoever built a tower can sell it (anyone can once they've left); anyone can upgrade or retarget it. `simStep(S, dt)` runs the game at a fixed 30 steps a second in solo, behind the menu (a demo game, `attract`) and on the online host; `act(S, uid, a)` applies one action (`b` build, `u` upgrade, `s` sell, `m` target mode, `w` send the wave, `f` speed, `g` give gold, `c` continue into endless) and returns '' or what went wrong. **Online:** each player writes only their own node `rooms/lh-/players/`: `n` name, `c` colour, `x`/`z` where their pointer is on the board (drawn on the others' screens as a ring and a name tag from a short history, NetSmooth), `h` (always 0), `ts` (server time), `j` (when they joined), and `ac`, their last 10 actions as JSON, each with a rising number `i` and the game number `g`. The host is whoever has the highest `he` with a published state, else whoever joined first (`Net.elect`); it runs the game, takes each player's new actions (`takeActs`, at most once each, by `i`, and only for the current game), and publishes the whole state as JSON in its own node's `rs` about 5 times a second (`encodeRS`: phase, wave, lives, gold per player, towers, enemies, Thumper shells in the air and the last shots, so clients can draw them). Clients rebuild the game from it (`decodeRS`, which checks every value) and move the Gloom on between snapshots from its speed, easing towards the host's numbers. If the host leaves, the next player picks up the last snapshot and carries on (`he` goes up by one), and a tab in the background keeps the host's game running once a second. The host picks the map and difficulty in the room's lobby and presses Start; anyone joining later gets a share of gold (the average, at most 250). Nodes are removed on leave and onDisconnect. **Saved in this browser** (localStorage, all `lanternhold:`): `name`, `color`, `map`, `diff`, `gfx` (Pretty, with shadows, or Fast; Fast is the default on touch screens), `sound`, `room` (the last room code) and `best::`, the best wave held. **stats.js:** `max('wave', waves held)` and `add('bosses', n)`; the Leaderboards show Most waves held and Gloomwardens beaten. **Touch:** shown only on touch screens (`body.touch`): tap a tower button, tap a tile to see the tower there, tap it again to build; drag to move the board, pinch to zoom. The camera fits the board into the space the HUD leaves (`fitCam`, `measureHud`), and on an upright phone the wave box becomes a row under the top bar and the dock gets compact. **Drawing:** the island, scenery and lantern are merged meshes with vertex colours; enemies, health bars, shots and rings are instanced meshes (their colour buffers are made at full size in `whiteColors`, because three r128's `setColorAt` sizes the buffer from the mesh's current count); particles are one Points draw. Automated browsers get a test hook, `window.__lh`. It has Spanish: its words, tower names and descriptions are in `lanternhold/es.js` (lang.js), with a Language switch on the menu and the pause screen; map names and the Gloom's names stay English, and nothing translated is sent to the room. **Wardrobe (hidden: captains only for now).** `LH_PUBLIC = false` and `wardOn()` (captains.js's `may(false, 'wardrobe', 'lh-wardrobe')`; `?wardrobe=1` for tests on localhost or in an automated browser) decide whether the menu shows a Wardrobe button under the colour swatches; for everyone else `lanternhold/wardrobe.js` is never fetched and the game is exactly as before, unless a teammate wears something, in which case it is fetched to draw them. It has 30 items in four slots, numbered as in `../cosmetics.js` (`lh-…`): 12 tower banners (a small flag on a pole at the back-left of every tower that player builds, seen by the whole team: sports pennants, a gear, a pirate flag with an eye-patched skull, a ship's wheel, pinstripes, a crown; baked into the tower's base mesh through `towerParts`' new `ban` argument, so a tower is still the same draw calls and its shape, owner band and level gems are untouched), 9 lanterns (the lantern's stand and cage on the captain's own screen only: `lanternGeo()` is the usual one, and `world.core.body`'s geometry is swapped; the flame, halo and light stay where they are and the same size), 5 flame colours (the flame's and halo's colour on the captain's own screen only; the point light is not recoloured, the low-lives flicker and the red flash are kept) and 4 build bursts (in place of the usual puff in `fxBuild` when that player builds or upgrades, seen by everyone, from the same particle pool). Saved in this browser as `lanternhold:wardrobe` (`'banner.lantern.flame.burst'`); online, a player's own node carries `cz: 'banner.burst'` (written with `Net.upd`) only while one of those is worn. Older pages ignore `cz`, `rs` and the actions are unchanged, and a page draws the usual look for numbers it doesn't know. The test hook `window.__lh` adds `WD` (with `wear(slot, n)`), `wardOn`, `wdLoad`, `wearOf`, `towerViews`, `towerMesh`, `wx`, `wz` and `world`. Its words and item names are in `lanternhold/es.js`. +- `e63334287a3deaa3/windrow/`: Windrow (Back Room), a calm single-player first-person game about clearing autumn leaves out of five walled gardens (three.js: the site's own r187 build, `/lib/three/r187/three.min.js` with its r128 layer, then `../autores.js`; no Firebase and no rooms, except `stats.js` for play time; no ads). The name is the word for the long row of leaves a rake leaves behind. The page is `index.html` (markup, styles, HUD and menus) plus five plain scripts in `js/`, loaded in this order: `world.js` (the areas, the collision grid and everything that stands still), `leaves.js` (the leaf simulation and its drawing), `audio.js` (every sound, made in code), `models.js` (gloves, sack, rake, blower, finder beams) and `game.js` (player, tools, money, HUD, menus, saving, the frame loop); `es.js` is its Spanish. Everything is drawn and textured in code; nothing is downloaded. **The garden** is flat, 76 x 50 m, on one grid of 0.25 m cells (`WR.CELL`, 312 x 208): `solid` blocks the player and the leaves, `gtype` is the surface (lawn, paving, decking, gravel: how far a leaf slides), `inlet` marks mulch-chute cells, `areaOf` says which garden a cell belongs to. The five gardens are `WR.AREAS` in `world.js` (Gatehouse Court, Orchard Walk, Lily Terrace, Glasshouse Row, Maze Lawn) with their gate cost, the garden that must be half cleared first, the bonus and the reward for finishing (sprint, kneel, higher jump, chutes that draw leaves in, a gold rake); bins, chutes, gates, trees, hedges and benches are lists just under it, and `WR.buildGrid` turns them into the grid, so moving a prop means editing its list only. **Leaves** are real objects, never removed by pointing: each has a place, a speed and a tumble, and leaves the garden only by being carried to a compost bin in the sack or by reaching a mulch chute. To stay cheap, resting leaves are asleep and cost nothing; each leaf sits in one grid cell (a linked list per cell), so a tool only visits the cells it reaches; and leaves do not collide one with another: a cell is a stack (each extra leaf rests 1.4 cm higher), a cell with 16 leaves turns sliding leaves away (34 for falling ones) and a leaf near the top of a stack 5 taller than a neighbour slides off onto it. That is what makes heaps against walls and rows in front of the rake. `Leaves.blow` is the blower (a cone; force falls with distance and with angle off the middle, 13 rays stop it at walls, leaves low in a heap are sheltered), `rake` carries the leaves under the head along with it, `scoop` sends the nearest leaves in a ring to the sack (they need a clear line from the player), `kick` is walking through them and `pull` the Draught grates reward. They are drawn as instanced meshes, one per garden and leaf shape (20 draw calls; four shapes of 4 to 10 triangles), plus one see-through 'litter' sheet whose opacity comes from a texture with one pixel per cell, so cleared ground looks clean about a second after its leaves go. **How many leaves** is the quality setting (`WR.QUALITY` times each area's `leaves`): Low 9,200, Medium 16,100, High 32,200 in the whole garden; High also turns on a real shadow map, drawn once (nothing that casts a shadow moves, except a gate opening). Phones start on Low, computers on Medium. Measured: the simulation costs under 1 ms a step with 34,500 leaves and a fully upgraded blower at 4x CPU slowdown, so the limit is triangles (about 87k / 137k / 255k with every garden in view). `autores.js` lowers the resolution first; if frames stay slow for 8 s after that and the player never chose a setting, the game drops one leaf tier itself and says so. An area's leaves are worth the same in total at every tier (`units`; fewer leaves are each worth more), and the sack and the hands are measured in the same quality-free units, so progress and prices do not depend on the setting. Changing the setting scatters the leaves that are left again and keeps each garden's percent. **Tools and money.** Hands and sack, a rake (a stroke reaches out lifted, then drags back along the ground, so it pulls) and a blower (it pushes). Acorns come from leaves: at a bin when the sack is emptied (20% more for a full sack) or at once at a chute. `UP` in `game.js` is the shed (nine upgrades and their prices) and the arrays under it are what each level does; the models in `models.js` change with them. The leaf finder (F, or by itself when under 3% of a garden is left) lights the 8 nearest leaves of the garden you are standing in, and the journal map draws a dot for every leaf on the ground. **Saved data:** one localStorage key, `windrow:v1` (JSON): `acorns`, `earned`, `up` (upgrade levels), `unlocked` and `done` (per garden), `rewards`, `bagUnits` (what is in the sack, per garden) and `bagFill`, `gone` (share of each garden cleared), `tool`, `tut` (tutorial step), `pos`, `secs`, `binFill`, `set` (look speed, volume, quality, flipped look, whether the player chose the quality), and `leaves` with `leafMul`: for each garden that has been touched, a base64 string of two 16-bit numbers a leaf (centimetres from the corner of the garden; 65535 = gone), about 85 KB at Medium and 170 KB at High once every garden has been disturbed. An untouched garden saves nothing and is scattered again from its seed. It saves 8 s after a change, on pause, and when the tab is hidden or closed. Keys are rebindable (`keybinds:windrow`); `autores.js` keeps its own scale. It is not in `account-nudge.js`'s KEYS, so it does not follow a Google account to another device, and it has no row in `leaderboard.js` or `miles.js`. **Touch:** `body.touch` is set on the first touch and shows `#touch` (left stick, Use, Jump, Run and Kneel once earned, a context button for bins and gates, and finder, journal and pause top right); the three tool slots at the bottom are tappable on any device. Portrait and landscape have their own positions in the style block; a drag on the view or on the Use button looks around. `WR.test` at the bottom of `game.js` is only for test scripts (start without a click, step the simulation, hold the tool, a simulation benchmark); nothing in the game calls it. - `e63334287a3deaa3/daily/`: Daily Puzzles (Back Room), the dashboard for every daily puzzle. No libraries, no network except stats.js. `DAILY_GAMES` at the top of the script lists every daily game (`slug` = folder = storage key `daily:`, name, icon, `cat`: word, geo, logic, est (Estimation) or soccer, a one-line blurb, `ready`), plus `EXTRA` link cards under Play together (Puffer Party, `chip` in place of a daily status). Tiles only show for `ready:true` games, and "Coming soon" ones are listed under each category; flip `ready` when a game's folder lands. For each game it reads the shared record `daily:` (written by the game when a daily ends: `{ v:1, days:{YYYYMMDD:{done,win,score,tries,time}}, played, wins, streak, maxStreak, last, dist }`) and shows today's status (Not played, Solved in N / in m:ss, Done, or Missed) and the game's 🔥 streak (only while its last win was today or yesterday). Deepword is read from its own `deepword:` keys. The summary counts today's finished puzzles, the overall streak (days in a row, ending today or yesterday, with at least one daily done, worked out from every game's `days`), and counts down to local midnight; when every ready game is done it shows an "All done today" banner. stats.js (`data-game="daily"`): `max('streak', overall)` and `add('done', 1)` once per game per day (remembered in `daily-hub:counted`). It re-reads storage when the tab comes back into view or another tab writes, so finishing a puzzle in another tab updates it. Test hook: `window.__dh` under webdriver (`setToday`, `render`, `streakOverall`). A game whose win shouldn't read "Solved in " gives a `show` template (`{tries}`, `{score}`, `{time}`; `{score|hint}` adds the word, plural unless the number is 1, and `zero` is the text used when the number is 0): Crosslet shows its time, Ninefold puzzles solved of 3, Crossbar squares, Stat Duel calls right, Top Bins entries found, Quartets mistakes (Perfect for none), Sleight hints, Poopdle moves, Mainstream its points, Yardstick its total out of 500 and Thereabouts its average miss (`{score|x100}`: a score saved as a hundred times a decimal, so 137 reads "1.37×"). A missed puzzle's tile has the finished look but no ✓. Poopdle and Thereabouts are under Logic. `RETIRED`, under `DAILY_GAMES`, holds the daily puzzles taken off the list on 18 Nov 2026 (the least played; see the Back Room page above): they have no tile and aren't in today's total, but their records still count toward the overall streak, so taking a puzzle off never shortens anyone's streak, and a category with nothing listed (Soccer, for now) isn't shown. To bring one back, move its line back into `DAILY_GAMES`. The daily games don't have Back Room or phone-page cards of their own: the Daily Puzzles card and tile are the way in (the phone thumbnails in `m/thumbs/` are kept for if they ever do). - `e63334287a3deaa3/hunch/`: Hunch (Back Room, a daily puzzle on the Daily Puzzles page), a five-letter word guess in six tries, like Wordle. No libraries, no network: `words.js` holds `window.WORDS5 = { ANSWERS, GUESSES }` as space-separated strings, 2,019 answers (common, school-safe, no plurals) and 6,334 more allowed guesses (8,353 in all), written for the site and checked by a script (five letters a–z, no repeats, every answer also a guess, a blocklist for rude words). `ANSWERS` is already in daily order (a fixed seeded shuffle): day n after 1 November 2026 (puzzle #n+1, from the player's local date) uses `ANSWERS[n % length]`, so new answers must be **appended** to keep past days unchanged. Scoring marks greens first, then yellows only for as many copies as the answer has left. Hard mode (Settings, only before a game's first guess) makes every green stay put and every found letter be reused; High contrast swaps green/yellow for orange/blue. Unlimited mode picks random answers and never touches daily stats. Storage: the shared daily record `daily:hunch` (`{ v:1, days:{YYYYMMDD:{done,win,score,tries,time,hard?}}, played, wins, streak, maxStreak, last, dist }`, 60 days kept; the Daily Puzzles page reads it), the day in progress `hunch:day` (`{ d, g:[guesses], hard, t0 }`), Unlimited `hunch:free`, settings `hunch:settings`, `hunch:seen` (how-to shown) and `hunch:mode`. stats.js (`data-game="hunch"`): `add('wins')`, `max('streak')`, `min('fewest')`. The page is generated from the same engine as Fourcast (`CFG` at the top of the script: boards, rows, offset); keep the two in step when fixing the engine. Tile size is worked out in `fit()` (bigger of the layouts that fit); on a sideways phone the keyboard sits right of the board. Test hooks: `window.__wg` under webdriver (`setToday('YYYYMMDD')`, `type(word)`, `score`, …). Thanksgiving Day 2026 (`TG_DAY`) has its own answer, FEAST, set in `answersFor` for Hunch only; every other day and Fourcast are unchanged. **Spanish:** `es.js` has its words (lang.js), with a language switch in Settings; the words are English by design and tagged "En inglés". - `e63334287a3deaa3/fourcast/`: Fourcast (Back Room, a daily puzzle), four five-letter words at once in nine guesses, like Quordle. The same engine as Hunch with `boards: 4, rows: 9, offset: 777`, and the same word lists (it loads `/e63334287a3deaa3/hunch/words.js`, so don't move that file). Each guess goes on every unsolved board; a solved board stops. Day n uses `ANSWERS[(777 + 4n + k) % length]` for boards k = 0–3, so appending answers keeps past days. Each keyboard key shows four corner colours, one per board in reading order (top left = board 1). Tiles may be up to 1.45× wider than tall, and `fit()` picks a 1 × 4 or 2 × 2 layout, whichever gives bigger tiles; on a sideways phone the keyboard stays underneath in short rows. Win = all four within nine; the share card shows the guess each board fell on (🟥 for missed). Storage: `daily:fourcast` (same contract; each day also has `boards`, how many were solved), `fourcast:day`, `fourcast:free`, `fourcast:settings`, `fourcast:seen`, `fourcast:mode`. stats.js: `add('wins')`, `max('streak')`, `min('fewest')`. **Spanish:** `es.js` has its words (lang.js), with a language switch in Settings; the words are English by design and tagged "En inglés". diff --git a/e63334287a3deaa3/es.js b/e63334287a3deaa3/es.js index a02aa60a..d7db25e6 100644 --- a/e63334287a3deaa3/es.js +++ b/e63334287a3deaa3/es.js @@ -435,6 +435,18 @@ "Build towers together and keep the lantern lit.": "Construyan torres juntos y mantengan encendida la linterna.", "Online co-op · up to 4": "Cooperativo en línea · hasta 4", "New · Tower defense": "Nuevo · Defensa de torres", + "Open Windrow": "Abrir Windrow", "More about Windrow": "Más sobre Windrow", + "Garden sim": "Jardín", "New · Garden sim": "Nuevo · Simulador de jardín", "Relaxing": "Relajante", "Saves itself": "Se guarda solo", + "Gather, rake and blow thousands of real leaves out of five walled gardens.": "Junta, rastrilla y sopla miles de hojas de verdad en cinco jardines amurallados.", + "Windrow in play, first person, in a walled brick courtyard under autumn trees: a rake with a wooden handle reaches out over grey paving that has just been cleared, with orange, gold and brown leaves and their litter still lying beyond it, a lawn square with a tree and a bench on the left, a stone fountain on the right and a green gate with a sign reading Orchard Walk, locked, 150. The acorn count and sack meter are top left, the garden name and percent cleared top centre, and the hands, rake and blower slots at the bottom.": "Windrow en juego, en primera persona, en un patio de ladrillo amurallado bajo árboles de otoño: un rastrillo con mango de madera se extiende sobre un pavimento gris recién limpiado, con hojas naranjas, doradas y marrones y sus restos más allá, un cuadro de césped con un árbol y un banco a la izquierda, una fuente de piedra a la derecha y un portón verde con un cartel que dice Orchard Walk, cerrado, 150. La cuenta de bellotas y el medidor del saco están arriba a la izquierda, el nombre del jardín y el porcentaje limpiado arriba al centro, y las casillas de manos, rastrillo y sopladora abajo.", + "A calm first-person game about clearing autumn leaves. Every leaf is a real object: it slides, tumbles, lifts on the wind and heaps up against walls, and it only leaves the garden through a compost bin or a mulch chute. Earn acorns, buy better tools and open the next gate.": "Un juego tranquilo en primera persona sobre limpiar hojas de otoño. Cada hoja es un objeto de verdad: resbala, da vueltas, se levanta con el viento y se amontona contra los muros, y solo sale del jardín por una compostera o una rejilla de mantillo. Gana bellotas, compra mejores herramientas y abre el siguiente portón.", + "Three tools: hands and a sack, a rake that drags rows of leaves toward you, and a blower that pushes them away in a cone of wind": "Tres herramientas: manos y un saco, un rastrillo que arrastra hileras de hojas hacia ti y una sopladora que las empuja con un cono de viento", + "Five gardens (a paved court, an orchard, a decked lily terrace, a row of glasshouses and a hedge maze), each with its own percent cleared and a reward for finishing it": "Cinco jardines (un patio pavimentado, un huerto, una terraza de madera con nenúfares, una calle de invernaderos y un laberinto de setos), cada uno con su porcentaje limpiado y un premio por terminarlo", + "Nine upgrades in the shed, from a bigger sack to a longer blower nozzle, and you can see each one on the tool": "Nueve mejoras en el cobertizo, desde un saco más grande hasta una boquilla más larga para la sopladora, y cada una se ve en la herramienta", + "A journal map that shows every leaf still on the ground, and a leaf finder for the last few": "Un mapa en el diario que muestra cada hoja que sigue en el suelo, y un buscador de hojas para las últimas", + "Your gardens save themselves in this browser, leaf by leaf": "Tus jardines se guardan solos en este navegador, hoja por hoja", + "Keyboard and mouse (rebindable keys), or touch on a phone: left thumb walks, drag to look, hold Use to work. Works either way up. Pick Low, Medium or High leaves in Settings.": "Teclado y mouse (teclas configurables), o táctil en un teléfono: el pulgar izquierdo camina, arrastra para mirar y mantén Usar para trabajar. Funciona en vertical u horizontal. Elige hojas en Bajo, Medio o Alto en Ajustes.", + "Quick games with a joystick feel: snakes, sword duels, platformers, a maze chase, co-op tower defense and a garden to sweep.": "Juegos rápidos con sensación de joystick: serpientes, duelos de espadas, plataformas, una persecución en laberinto, defensa de torres cooperativa y un jardín para barrer.", "Horror obby": "Obby de terror", "New · Horror obby": "Nuevo · Obby de terror", "Cross the flooded pool halls without a splash. It hears you.": "Cruza los pasillos de piscinas inundados sin salpicar. Te oye.", diff --git a/e63334287a3deaa3/index.html b/e63334287a3deaa3/index.html index 77503f26..a548a18d 100644 --- a/e63334287a3deaa3/index.html +++ b/e63334287a3deaa3/index.html @@ -914,8 +914,8 @@

Gridpop

-

Arcade

Quick games with a joystick feel: snakes, sword duels, platformers, a maze chase and co-op tower defense.

- 7 games +

Arcade

Quick games with a joystick feel: snakes, sword duels, platformers, a maze chase, co-op tower defense and a garden to sweep.

+ 8 games
@@ -1117,6 +1117,34 @@

Lanternhold

+
+ + Windrow in play, first person, in a walled brick courtyard under autumn trees: a rake with a wooden handle reaches out over grey paving that has just been cleared, with orange, gold and brown leaves and their litter still lying beyond it, a lawn square with a tree and a bench on the left, a stone fountain on the right and a green gate with a sign reading Orchard Walk, locked, 150. The acorn count and sack meter are top left, the garden name and percent cleared top centre, and the hands, rake and blower slots at the bottom. + NewGarden sim + +
+

Windrow

+

Gather, rake and blow thousands of real leaves out of five walled gardens.

+
  • Solo
  • Relaxing
  • Saves itself
+
+ +
+

A calm first-person game about clearing autumn leaves. Every leaf is a real object: it slides, tumbles, lifts on the wind and heaps up against walls, and it only leaves the garden through a compost bin or a mulch chute. Earn acorns, buy better tools and open the next gate.

+
    +
  • Three tools: hands and a sack, a rake that drags rows of leaves toward you, and a blower that pushes them away in a cone of wind
  • +
  • Five gardens (a paved court, an orchard, a decked lily terrace, a row of glasshouses and a hedge maze), each with its own percent cleared and a reward for finishing it
  • +
  • Nine upgrades in the shed, from a bigger sack to a longer blower nozzle, and you can see each one on the tool
  • +
  • A journal map that shows every leaf still on the ground, and a leaf finder for the last few
  • +
  • Your gardens save themselves in this browser, leaf by leaf
  • +
+

Keyboard and mouse (rebindable keys), or touch on a phone: left thumb walks, drag to look, hold Use to work. Works either way up. Pick Low, Medium or High leaves in Settings.

+
+
+
+ ▶ Play +
+
+