BlueGit

projects-timfalken-com meteors

Files

meteors / build / game.js

game.js

game.js 144.0 KiB Download Raw
1/*
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 * Built by src/build.sh from the sources in src/.
4 */
5var PLANET_CATALOG = {
6 "planets": [
7 {
8 "id": "terra",
9 "name": "Terra",
10 "people": "Terrans",
11 "jumpsToClear": 2,
12 "fallTime": 3,
13 "riseTime": 1.5,
14 "colors": [
15 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
16 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
17 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
18 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
19 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
20 ]
21 },
22 {
23 "id": "aurel",
24 "name": "Aurel",
25 "people": "Aurelians",
26 "jumpsToClear": 1,
27 "fallTime": 5,
28 "riseTime": 3,
29 "colors": [
30 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
31 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
32 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
33 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
34 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
35 ]
36 },
37 {
38 "id": "cinder",
39 "name": "Cinder",
40 "people": "Cindari",
41 "jumpsToClear": 4,
42 "fallTime": 1,
43 "riseTime": 0.5,
44 "colors": [
45 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
46 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
47 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
48 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
49 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
50 ]
51 },
52 {
53 "id": "lunara",
54 "name": "Lunara",
55 "people": "Lunarites",
56 "jumpsToClear": 1,
57 "fallTime": 2,
58 "riseTime": 1.2,
59 "colors": [
60 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
61 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
62 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
63 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
64 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
65 ]
66 },
67 {
68 "id": "mire",
69 "name": "Mire",
70 "people": "Mirians",
71 "jumpsToClear": 2,
72 "fallTime": 5,
73 "riseTime": 2.5,
74 "colors": [
75 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
76 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
77 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
78 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
79 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
80 ]
81 },
82 {
83 "id": "galeon",
84 "name": "Galeon",
85 "people": "Galeoni",
86 "jumpsToClear": 3,
87 "fallTime": 1,
88 "riseTime": 1.8,
89 "colors": [
90 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
91 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
92 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
93 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
94 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
95 ]
96 },
97 {
98 "id": "obsid",
99 "name": "Obsid",
100 "people": "Obsidians",
101 "jumpsToClear": 4,
102 "fallTime": 3.5,
103 "riseTime": 2.2,
104 "colors": [
105 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
106 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
107 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
108 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
109 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
110 ]
111 },
112 {
113 "id": "wisp",
114 "name": "Wisp",
115 "people": "Wisplings",
116 "jumpsToClear": 2,
117 "fallTime": 3.5,
118 "riseTime": 0.5,
119 "colors": [
120 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
121 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
122 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
123 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
124 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
125 ]
126 },
127 {
128 "id": "thorn",
129 "name": "Thorn",
130 "people": "Thornfolk",
131 "jumpsToClear": 3,
132 "fallTime": 2,
133 "riseTime": 1.0,
134 "colors": [
135 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
136 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
137 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
138 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
139 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
140 ]
141 },
142 {
143 "id": "zephyr",
144 "name": "Zephyr",
145 "people": "Zephyrites",
146 "jumpsToClear": 1,
147 "fallTime": 1.2,
148 "riseTime": 2.8,
149 "colors": [
150 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
151 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
152 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
153 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
154 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
155 ]
156 },
157 {
158 "id": "frore",
159 "name": "Frore",
160 "people": "Frorians",
161 "jumpsToClear": 3,
162 "fallTime": 4.5,
163 "riseTime": 0.8,
164 "colors": [
165 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
166 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
167 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
168 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
169 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
170 ]
171 },
172 {
173 "id": "forge",
174 "name": "Forge",
175 "people": "Forgelings",
176 "jumpsToClear": 4,
177 "fallTime": 2,
178 "riseTime": 1.5,
179 "colors": [
180 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
181 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
182 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
183 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
184 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
185 ]
186 }
187 ]
188}
189;
190
191/*
192 * Start File:
193 * /workspace/meteors/src/rng.js
194 */
195'use strict';
196
197/**
198 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
199 * and (later) for multiplayer replays.
200 */
201function createRng (seed)
202{
203 var a = (seed >>> 0) || 1;
204 return function rng ()
205 {
206 a |= 0;
207 a = a + 0x6D2B79F5 | 0;
208 var t = Math.imul(a ^ a >>> 15, 1 | a);
209 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
210 return ((t ^ t >>> 14) >>> 0) / 4294967296;
211 };
212}
213
214function pickIndex (rng, count)
215{
216 var n = count | 0;
217 if (n <= 0)
218 { return 0; }
219 return Math.floor(rng() * n) % n;
220}
221
222function pickFrom (rng, list)
223{
224 if (!list || !list.length)
225 { return undefined; }
226 return list[pickIndex(rng, list.length)];
227}
228
229var Rng = {
230 create: createRng,
231 pickIndex: pickIndex,
232 pickFrom: pickFrom
233};
234
235if (typeof module !== 'undefined' && module.exports)
236{ module.exports = Rng; }
237else if (typeof globalThis !== 'undefined')
238{ globalThis.Rng = Rng; }
239
240/*
241 * End File:
242 * /workspace/meteors/src/rng.js
243 */
244
245/*
246 * Start File:
247 * /workspace/meteors/src/planet.js
248 */
249'use strict';
250
251/**
252 * Planet physics and visuals for Meteors.
253 *
254 * Stage 1 uses a single default planet. Stage 3 lets the player pick a
255 * planet; the numbers and jump-height rules are already applied here so
256 * that later planets only need new data, not new physics code.
257 *
258 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
259 * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
260 * at 1, one jump from the floor clears the field; at 4, you need four.
261 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
262 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
263 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
264 * Time to reach the apex, independent of jump height.
265 *
266 * Jump-height multipliers (never explained in the game):
267 * A vertical match of 3 is 120 % of a horizontal row of 3.
268 * Each extra block beyond 3 adds 5 %.
269 *
270 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
271 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
272 * power 0 to 5 % at power 1.
273 */
274
275var FIELD_WIDTH = 10;
276var FIELD_HEIGHT = 13;
277
278function clamp (value, lo, hi)
279{
280 return Math.max(lo, Math.min(hi, value));
281}
282
283function defaultColors ()
284{
285 return [
286 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
287 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
288 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
289 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
290 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
291 ];
292}
293
294function createPlanet (opts)
295{
296 opts = opts || {};
297 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
298 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
299 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
300 var colors = opts.colors || defaultColors();
301 var planet = {
302 id: opts.id || null,
303 name: opts.name || 'Terra',
304 people: opts.people || 'Terrans',
305 jumpsToClear: jumpsToClear,
306 fallTime: fallTime,
307 riseTime: riseTime,
308 colors: colors,
309 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
310 fallSpeed: FIELD_HEIGHT / fallTime,
311 // Time to ease from vy=0 at the apex to terminal fallSpeed.
312 // Shorter when air resistance is low (small fallTime).
313 apexEaseTime: 0.15 * fallTime,
314 fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
315 // Visual landing bounce: faster at low air resistance. Stage-3 params.
316 bounceDuration: 0.12 * fallTime,
317 bounceSquash: 0.16
318 };
319 return planet;
320}
321
322function loadCatalog ()
323{
324 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
325 { return PLANET_CATALOG; }
326 if (typeof require !== 'undefined')
327 {
328 try
329 { return require('../server/lib/planets.json'); }
330 catch (e) {}
331 }
332 return { planets: [] };
333}
334
335function planetFromData (data)
336{
337 var planet = createPlanet({
338 name: data.name,
339 people: data.people,
340 jumpsToClear: data.jumpsToClear,
341 fallTime: data.fallTime,
342 riseTime: data.riseTime,
343 colors: data.colors
344 });
345 planet.id = data.id;
346 return planet;
347}
348
349function allPlanets ()
350{
351 var raw = loadCatalog().planets || [];
352 var out = [];
353 for (var i = 0; i < raw.length; i++)
354 { out.push(planetFromData(raw[i])); }
355 if (out.length === 0)
356 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
357 return out;
358}
359
360function planetById (id)
361{
362 var all = allPlanets();
363 for (var i = 0; i < all.length; i++)
364 {
365 if (all[i].id === id)
366 { return all[i]; }
367 }
368 return defaultPlanet();
369}
370
371function defaultPlanet ()
372{
373 var all = allPlanets();
374 for (var i = 0; i < all.length; i++)
375 {
376 if (all[i].id === 'terra')
377 { return all[i]; }
378 }
379 return all[0];
380}
381
382function formatStats (planet)
383{
384 var d = displayValues(planet);
385 return 'g ' + d.gravity.toFixed(2)
386 + ' d ' + d.density.toFixed(2)
387 + ' F ' + Math.round(d.newtons) + ' N'
388 + ' Power ' + d.power + '%';
389}
390
391function spriteKey (planet, colorIndex)
392{
393 var colors = planet && planet.colors;
394 var c = colors && colors[colorIndex];
395 if (!c)
396 { return 'gray'; }
397 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
398}
399
400/**
401 * Jump height in tiles for a match line.
402 * @param {object} planet
403 * @param {number} matchLength number of blocks in the line (>= 3)
404 * @param {boolean} vertical true for a vertical line
405 */
406function jumpHeight (planet, matchLength, vertical)
407{
408 var extra = Math.max(0, (matchLength | 0) - 3);
409 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
410 return planet.baseJumpHeight * multiplier;
411}
412
413/** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
414function launchVelocity (planet, height)
415{
416 if (height <= 0)
417 { return 0; }
418 return (2 * height) / planet.riseTime;
419}
420
421/** Constant deceleration (tiles/s^2) paired with launchVelocity. */
422function launchDeceleration (planet, height)
423{
424 if (height <= 0)
425 { return 0; }
426 return (2 * height) / (planet.riseTime * planet.riseTime);
427}
428
429/**
430 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
431 * chance that a shot-off block misses the opponent).
432 */
433function power (planet)
434{
435 var gravity = (planet.jumpsToClear - 1) / 3;
436 var air = (5 - planet.fallTime) / 4;
437 var mass = (3 - planet.riseTime) / 2.5;
438 return (gravity + air + mass) / 3;
439}
440
441/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
442var MAX_MISS_CHANCE = 0.60;
443var MIN_MISS_CHANCE = 0.05;
444
445/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
446function missChance (planet)
447{
448 return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
449}
450
451/**
452 * Displayed Power, as a 0–100 percentage. This is the complement of the
453 * miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
454 * → 0% Power. The gameplay power() and missChance() formulas are unchanged.
455 */
456function displayPower (planet)
457{
458 return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
459}
460
461/**
462 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
463 * launch force (N), and displayed Power as a percentage. The numbers do
464 * not have to explain themselves.
465 */
466function displayValues (planet)
467{
468 var gravity = 9.81 * planet.jumpsToClear / 2;
469 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
470 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
471 return {
472 gravity: gravity,
473 density: density,
474 newtons: newtons,
475 power: displayPower(planet),
476 missChance: missChance(planet)
477 };
478}
479
480var Planet = {
481 FIELD_WIDTH: FIELD_WIDTH,
482 FIELD_HEIGHT: FIELD_HEIGHT,
483 COLOR_COUNT: 5,
484 SETTLE_TIME: 3,
485 SPAWN_INTERVAL: 1,
486 JUMP_VERTICAL_BONUS: 1.2,
487 JUMP_EXTRA_BLOCK: 0.05,
488 createPlanet: createPlanet,
489 defaultPlanet: defaultPlanet,
490 defaultColors: defaultColors,
491 allPlanets: allPlanets,
492 planetById: planetById,
493 planetFromData: planetFromData,
494 formatStats: formatStats,
495 spriteKey: spriteKey,
496 jumpHeight: jumpHeight,
497 launchVelocity: launchVelocity,
498 launchDeceleration: launchDeceleration,
499 MAX_MISS_CHANCE: MAX_MISS_CHANCE,
500 MIN_MISS_CHANCE: MIN_MISS_CHANCE,
501 power: power,
502 missChance: missChance,
503 displayPower: displayPower,
504 displayValues: displayValues
505};
506
507if (typeof module !== 'undefined' && module.exports)
508{ module.exports = Planet; }
509else if (typeof globalThis !== 'undefined')
510{ globalThis.Planet = Planet; }
511
512/*
513 * End File:
514 * /workspace/meteors/src/planet.js
515 */
516
517/*
518 * Start File:
519 * /workspace/meteors/src/easing.js
520 */
521'use strict';
522
523/**
524 * Easing curves matching Qt QEasingCurve defaults (the same values Tim's
525 * KWin Click Tween effect uses). Formulas and default parameters come from
526 * Qt 6's QEasingCurve and https://easings.net/.
527 *
528 * Source of the click/release defaults:
529 * /workspace/click-tween/settings.h (clickTime, releaseTime, easing names)
530 * /workspace/click-tween/clicktween.cpp (press scale 0.8, release scale 1.0)
531 * /workspace/click-tween/README.md
532 */
533
534/** Qt QEasingCurve default overshoot for InBack / OutBack / InOutBack. */
535var BACK_OVERSHOOT = 1.70158;
536
537/** Qt QEasingCurve default period and amplitude for Elastic curves. */
538var ELASTIC_PERIOD = 0.3;
539var ELASTIC_AMPLITUDE = 1.0;
540
541function clamp01 (t)
542{
543 if (t <= 0)
544 { return 0; }
545 if (t >= 1)
546 { return 1; }
547 return t;
548}
549
550/** easeOutBack: overshoots the end value, then settles. Qt / easings.net. */
551function easeOutBack (t)
552{
553 t = clamp01(t);
554 var c1 = BACK_OVERSHOOT;
555 var c3 = c1 + 1;
556 var u = t - 1;
557 return 1 + c3 * u * u * u + c1 * u * u;
558}
559
560/**
561 * easeOutElastic: decaying sine overshoot past the end value.
562 * Qt default amplitude 1, period 0.3 (equivalent to easings.net).
563 */
564function easeOutElastic (t)
565{
566 t = clamp01(t);
567 if (t === 0 || t === 1)
568 { return t; }
569 var p = ELASTIC_PERIOD;
570 var s = p / 4;
571 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
572}
573
574function tween (from, to, t, ease)
575{
576 return from + (to - from) * ease(clamp01(t));
577}
578
579/**
580 * DEFAULT settings of Tim's KWin Click Tween
581 * (git.timfalken.com/timfa/click-tween).
582 *
583 * Press: shrink to 80% in 150 ms with easeOutBack, stay at 80% while held.
584 * Release: grow back to 100% in 720 ms with easeOutElastic.
585 * Mid-animation release starts from the current scale, like QVariantAnimation.
586 */
587var CLICK_TWEEN = {
588 pressScale: 0.8,
589 releaseScale: 1.0,
590 pressDuration: 0.150,
591 releaseDuration: 0.720,
592 pressEase: easeOutBack,
593 releaseEase: easeOutElastic,
594 backOvershoot: BACK_OVERSHOOT,
595 elasticPeriod: ELASTIC_PERIOD,
596 elasticAmplitude: ELASTIC_AMPLITUDE,
597 source: 'click-tween settings.h + clicktween.cpp (Qt QEasingCurve defaults)'
598};
599
600/**
601 * Visual landing bounce, u in 0..1. Subtle squash with a slight stretch
602 * on the other axis and a tiny upward rebound (in tiles, visual only).
603 */
604function bouncePose (u, squash)
605{
606 if (u <= 0 || u >= 1)
607 { return { sx: 1, sy: 1, dy: 0 }; }
608 var wave = Math.sin(Math.PI * u);
609 return {
610 sx: 1 + squash * 0.6 * wave,
611 sy: 1 - squash * wave,
612 dy: 0.07 * wave * (1 - u)
613 };
614}
615
616var Easing = {
617 BACK_OVERSHOOT: BACK_OVERSHOOT,
618 ELASTIC_PERIOD: ELASTIC_PERIOD,
619 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
620 easeOutBack: easeOutBack,
621 easeOutElastic: easeOutElastic,
622 tween: tween,
623 CLICK_TWEEN: CLICK_TWEEN,
624 clamp01: clamp01,
625 bouncePose: bouncePose
626};
627
628if (typeof module !== 'undefined' && module.exports)
629{ module.exports = Easing; }
630else if (typeof globalThis !== 'undefined')
631{ globalThis.Easing = Easing; }
632
633/*
634 * End File:
635 * /workspace/meteors/src/easing.js
636 */
637
638/*
639 * Start File:
640 * /workspace/meteors/src/gameCore.js
641 */
642'use strict';
643
644/**
645 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
646 * The view layer reads this state and translates pointer events into
647 * beginDrag / moveDrag / endDrag.
648 */
649
650var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
651 ? require('./planet.js')
652 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
653
654var COLOR_GRAY = -1;
655
656var STATE_STILL = 'still';
657var STATE_FALLING = 'falling';
658var STATE_FLYING = 'flying';
659var STATE_SETTLING = 'settling';
660var STATE_LOCKED = 'locked';
661var STATE_MANUAL = 'manual';
662
663var ALIGN_EPS = 0.15;
664var SUBSTEP = 1 / 120;
665var DRAG_LAUNCH_SLACK = 0.65;
666// Upward pull (tiles past the press point) that launches an already-topmost block.
667var LAUNCH_PULL = 0.35;
668// Minimal accumulated vertical pointer travel (tiles) to swap one step.
669// No hold delay: the first swap fires as soon as this distance is reached.
670var SWAP_DISTANCE = 0.25;
671// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
672var SNAP_Y = 0.5;
673// Horizontal slop (tiles) for snapping to a neighbouring column on press.
674var HORIZONTAL_SLOP = 0.35;
675
676function UnionFind ()
677{
678 this.parent = Object.create(null);
679}
680
681UnionFind.prototype.add = function (id)
682{
683 if (this.parent[id] == null)
684 { this.parent[id] = id; }
685};
686
687UnionFind.prototype.find = function (id)
688{
689 if (this.parent[id] !== id)
690 { this.parent[id] = this.find(this.parent[id]); }
691 return this.parent[id];
692};
693
694UnionFind.prototype.union = function (a, b)
695{
696 this.add(a);
697 this.add(b);
698 var ra = this.find(a);
699 var rb = this.find(b);
700 if (ra !== rb)
701 { this.parent[rb] = ra; }
702};
703
704function GameCore (planet, rng)
705{
706 this.planet = planet || PlanetMod.defaultPlanet();
707 this.rng = rng || Math.random;
708 this.width = PlanetMod.FIELD_WIDTH;
709 this.height = PlanetMod.FIELD_HEIGHT;
710 this.blocks = [];
711 this.clusters = Object.create(null);
712 this.nextBlockId = 1;
713 this.nextClusterId = 1;
714 this.spawnTimer = 0;
715 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
716 this.settleTime = PlanetMod.SETTLE_TIME;
717 this.score = 0;
718 this.state = 'playing';
719 this.drag = null;
720 this.gameOverTime = 0;
721 this.outgoingShots = [];
722 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
723 this.missChance = optsMissChance(arguments);
724 // t1112: invariant checker. strictInvariants throws (tests);
725 // debugInvariants records violations for the ?debug overlay.
726 this.strictInvariants = false;
727 this.debugInvariants = false;
728 this.lastInvariantViolations = [];
729}
730
731function optsMissChance (args)
732{
733 // GameCore(planet, rng, missChance) — third arg is optional.
734 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
735 { return Math.max(0, Math.min(1, args[2])); }
736 var planet = args[0];
737 if (planet && typeof PlanetMod.missChance === 'function')
738 { return PlanetMod.missChance(planet); }
739 return GameCore.DEFAULT_MISS_CHANCE;
740}
741
742GameCore.COLOR_GRAY = COLOR_GRAY;
743GameCore.LAUNCH_PULL = LAUNCH_PULL;
744GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
745GameCore.SNAP_Y = SNAP_Y;
746GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
747GameCore.DEFAULT_MISS_CHANCE = 0.30;
748GameCore.STATE_STILL = STATE_STILL;
749GameCore.STATE_FALLING = STATE_FALLING;
750GameCore.STATE_FLYING = STATE_FLYING;
751GameCore.STATE_SETTLING = STATE_SETTLING;
752GameCore.STATE_LOCKED = STATE_LOCKED;
753GameCore.STATE_MANUAL = STATE_MANUAL;
754
755GameCore.prototype.randomColor = function ()
756{
757 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
758};
759
760GameCore.prototype.createBlock = function (col, y, color, state)
761{
762 var block = {
763 id: this.nextBlockId++,
764 col: col,
765 y: y,
766 color: color,
767 state: state || STATE_STILL,
768 vy: 0,
769 clusterId: null,
770 settleTime: 0,
771 flame: false,
772 pushedClusters: null,
773 manualTarget: 0,
774 manualDecel: 0,
775 manualPhase: null,
776 bouncing: false,
777 bounceAge: 0
778 };
779 this.blocks.push(block);
780 return block;
781};
782
783GameCore.prototype.removeBlock = function (block)
784{
785 if (block.clusterId != null)
786 { this.leaveCluster(block); }
787 var index = this.blocks.indexOf(block);
788 if (index >= 0)
789 { this.blocks.splice(index, 1); }
790};
791
792GameCore.prototype.leaveCluster = function (block)
793{
794 var id = block.clusterId;
795 block.clusterId = null;
796 block.flame = false;
797 if (id == null || !this.clusters[id])
798 { return; }
799 var still = 0;
800 for (var i = 0; i < this.blocks.length; i++)
801 {
802 if (this.blocks[i].clusterId === id)
803 { still++; }
804 }
805 if (still === 0)
806 { delete this.clusters[id]; }
807};
808
809GameCore.prototype.blocksInColumn = function (col)
810{
811 var out = [];
812 for (var i = 0; i < this.blocks.length; i++)
813 {
814 if (this.blocks[i].col === col)
815 { out.push(this.blocks[i]); }
816 }
817 out.sort(function (a, b) { return a.y - b.y; });
818 return out;
819};
820
821GameCore.prototype.isGrounded = function (block)
822{
823 return block.state === STATE_STILL
824 || block.state === STATE_SETTLING
825 || block.state === STATE_LOCKED;
826};
827
828/**
829 * Highest grounded landing surface in `col`. If `belowY` is given, only
830 * blocks strictly below that y count — a hanging still block above a
831 * gap must never pull a falling or thrown block upward through the gap.
832 */
833GameCore.prototype.stackTop = function (col, ignore, belowY)
834{
835 var top = 0;
836 for (var i = 0; i < this.blocks.length; i++)
837 {
838 var block = this.blocks[i];
839 if (block.col !== col)
840 { continue; }
841 if (ignore && ignore(block))
842 { continue; }
843 if (belowY != null && block.y + 1e-9 >= belowY)
844 { continue; }
845 if (this.isGrounded(block))
846 {
847 var surface = block.y + 1;
848 if (surface > top)
849 { top = surface; }
850 }
851 }
852 return top;
853};
854
855GameCore.prototype.isColumnLocked = function (col)
856{
857 for (var i = 0; i < this.blocks.length; i++)
858 {
859 var block = this.blocks[i];
860 if (block.col === col && block.state === STATE_LOCKED)
861 { return true; }
862 }
863 return false;
864};
865
866GameCore.prototype.isColumnStill = function (col)
867{
868 if (this.isColumnLocked(col))
869 { return false; }
870 for (var i = 0; i < this.blocks.length; i++)
871 {
872 var block = this.blocks[i];
873 if (block.col !== col)
874 { continue; }
875 if (block.state === STATE_FLYING
876 || block.state === STATE_FALLING
877 || block.state === STATE_MANUAL
878 || block.state === STATE_SETTLING)
879 { return false; }
880 }
881 return true;
882};
883
884GameCore.prototype.groundedCount = function (col)
885{
886 var n = 0;
887 for (var i = 0; i < this.blocks.length; i++)
888 {
889 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
890 { n++; }
891 }
892 return n;
893};
894
895GameCore.prototype.blockAt = function (col, row)
896{
897 for (var i = 0; i < this.blocks.length; i++)
898 {
899 var block = this.blocks[i];
900 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
901 { return block; }
902 }
903 return null;
904};
905
906GameCore.prototype.place = function (col, row, color, state)
907{
908 return this.createBlock(col, row, color, state || STATE_STILL);
909};
910
911GameCore.prototype.lockedColumnCount = function ()
912{
913 var n = 0;
914 for (var c = 0; c < this.width; c++)
915 {
916 if (this.isColumnLocked(c))
917 { n++; }
918 }
919 return n;
920};
921
922GameCore.prototype.startBounce = function (block)
923{
924 if (!block)
925 { return; }
926 block.bouncing = true;
927 block.bounceAge = 0;
928};
929
930GameCore.prototype.advanceBounces = function (dt)
931{
932 var duration = this.planet.bounceDuration;
933 for (var i = 0; i < this.blocks.length; i++)
934 {
935 var block = this.blocks[i];
936 if (!block.bouncing)
937 { continue; }
938 block.bounceAge += dt;
939 if (duration <= 0 || block.bounceAge >= duration)
940 {
941 block.bouncing = false;
942 block.bounceAge = duration;
943 }
944 }
945};
946
947/**
948 * True if `block` rests on the floor or on a solid (still / settling /
949 * locked) block immediately below it in the same column.
950 */
951GameCore.prototype.hasSupport = function (block)
952{
953 if (block.y <= 1e-9)
954 { return true; }
955 for (var i = 0; i < this.blocks.length; i++)
956 {
957 var other = this.blocks[i];
958 if (other === block || other.col !== block.col)
959 { continue; }
960 if (!this.isGrounded(other))
961 { continue; }
962 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
963 { return true; }
964 }
965 return false;
966};
967
968/** Highest flying block in this column whose top is at or below `block.y + 1`. */
969GameCore.prototype.highestFlyingBelow = function (block)
970{
971 var best = null;
972 for (var i = 0; i < this.blocks.length; i++)
973 {
974 var other = this.blocks[i];
975 if (other === block || other.col !== block.col)
976 { continue; }
977 if (other.state !== STATE_FLYING || other.clusterId == null)
978 { continue; }
979 var cluster = this.clusters[other.clusterId];
980 if (!cluster || cluster.phase === 'landed')
981 { continue; }
982 // The falling block is at or above this flyer (or already overlapping).
983 if (block.y + 1e-9 < other.y)
984 { continue; }
985 if (!best || other.y > best.y)
986 { best = other; }
987 }
988 return best;
989};
990
991GameCore.prototype.highestFallingBelow = function (block)
992{
993 var best = null;
994 for (var i = 0; i < this.blocks.length; i++)
995 {
996 var other = this.blocks[i];
997 if (other === block || other.col !== block.col)
998 { continue; }
999 if (other.state !== STATE_FALLING)
1000 { continue; }
1001 if (other.y > block.y - 1e-9)
1002 { continue; }
1003 if (!best || other.y > best.y)
1004 { best = other; }
1005 }
1006 return best;
1007};
1008
1009/**
1010 * Make an unsupported still block start falling from rest, so it eases
1011 * into fallSpeed under normal gravity. Skips the block being dragged.
1012 */
1013/**
1014 * Strip leftover launch / manual kinematics so a block that has just
1015 * become still or falling starts from rest. Used after a landed grey
1016 * cluster recolors, and whenever an unsupported still block drops.
1017 */
1018GameCore.prototype.clearFlightState = function (block)
1019{
1020 block.vy = 0;
1021 block.flame = false;
1022 block.manualPhase = null;
1023 block.manualTarget = null;
1024 block.manualDecel = 0;
1025 block.pushedClusters = null;
1026};
1027
1028GameCore.prototype.releaseUnsupported = function ()
1029{
1030 // Repeat until stable: a still sitting on a still that itself just
1031 // became falling must also drop. Two fixed passes are not enough
1032 // for a chain of hanging blocks (t1112).
1033 var guard = 0;
1034 var changed = true;
1035 while (changed && guard++ < this.height + 2)
1036 {
1037 changed = false;
1038 for (var i = 0; i < this.blocks.length; i++)
1039 {
1040 var block = this.blocks[i];
1041 if (block.state !== STATE_STILL)
1042 { continue; }
1043 if (this.drag && this.drag.blockId === block.id)
1044 { continue; }
1045 if (this.hasSupport(block))
1046 { continue; }
1047 this.leaveCluster(block);
1048 this.clearFlightState(block);
1049 block.state = STATE_FALLING;
1050 changed = true;
1051 }
1052 }
1053};
1054
1055GameCore.prototype.accelerateFall = function (block, dt)
1056{
1057 var target = -this.planet.fallSpeed;
1058 if (block.vy > target)
1059 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
1060 else
1061 { block.vy = target; }
1062};
1063
1064GameCore.prototype.landFallingBlock = function (block)
1065{
1066 block.vy = 0;
1067 block.flame = false;
1068 this.startBounce(block);
1069 if (block.color === COLOR_GRAY)
1070 {
1071 block.state = STATE_SETTLING;
1072 block.settleTime = 0;
1073 }
1074 else
1075 { block.state = STATE_STILL; }
1076};
1077
1078/**
1079 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
1080 * carry it along as cargo (no flame). Returns true if attached.
1081 */
1082GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1083{
1084 var cluster = this.clusters[flyer.clusterId];
1085 if (!cluster || cluster.phase === 'landed')
1086 { return false; }
1087 this.prepareClusterBody(cluster);
1088 var maxOff = null;
1089 var members = this.clusterMembers(cluster.id);
1090 for (var i = 0; i < members.length; i++)
1091 {
1092 if (members[i].col !== block.col)
1093 { continue; }
1094 if (maxOff == null || members[i].clusterOffset > maxOff)
1095 { maxOff = members[i].clusterOffset; }
1096 }
1097 var oldN = members.length;
1098 var fallingVy = block.vy;
1099 if (block.clusterId != null && block.clusterId !== cluster.id)
1100 { this.leaveCluster(block); }
1101 block.state = STATE_FLYING;
1102 block.clusterId = cluster.id;
1103 block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
1104 block.flame = false;
1105 block.settleTime = 0;
1106 block.manualPhase = null;
1107 block.manualTarget = null;
1108 block.manualDecel = 0;
1109 block.pushedClusters = null;
1110 // A cluster born from a thrown block averages in falling cargo
1111 // the same way two flying clusters merge (t1108). Other rockets
1112 // keep their velocity and just pick the cargo up.
1113 if (cluster.fromManual)
1114 {
1115 var newN = oldN + 1;
1116 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
1117 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1118 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1119 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1120 }
1121 this.syncClusterMembers(cluster);
1122 return true;
1123};
1124
1125GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
1126{
1127 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1128 { return; }
1129 // Snapshot falling blocks; attaching mutates state.
1130 var falling = [];
1131 for (var i = 0; i < this.blocks.length; i++)
1132 {
1133 if (this.blocks[i].state === STATE_FALLING)
1134 { falling.push(this.blocks[i]); }
1135 }
1136 for (var i = 0; i < falling.length; i++)
1137 {
1138 var block = falling[i];
1139 var flyer = null;
1140 for (var m = 0; m < members.length; m++)
1141 {
1142 var other = members[m];
1143 if (other.col !== block.col)
1144 { continue; }
1145 // Overlap or rest on this member's top.
1146 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
1147 {
1148 if (!flyer || other.y > flyer.y)
1149 { flyer = other; }
1150 }
1151 }
1152 if (flyer)
1153 { this.attachToFlyingCluster(block, flyer); }
1154 }
1155};
1156
1157GameCore.prototype.tick = function (dt)
1158{
1159 if (this.state === 'gameover')
1160 {
1161 this.gameOverTime += Math.max(0, dt);
1162 return;
1163 }
1164 if (dt <= 0)
1165 { return; }
1166 dt = Math.min(dt, 0.1);
1167
1168 this.spawnTimer += dt;
1169 while (this.spawnTimer >= this.spawnInterval)
1170 {
1171 this.spawnTimer -= this.spawnInterval;
1172 this.trySpawn();
1173 }
1174
1175 var left = dt;
1176 while (left > 1e-12)
1177 {
1178 var step = Math.min(SUBSTEP, left);
1179 this.snapshotPrevY();
1180 this.integrateFalling(step);
1181 this.resolveFlyingMatches();
1182 this.integrateClusters(step);
1183 this.mergeFlyingClusters();
1184 this.integrateManual(step);
1185 this.mergeAnyManualFallingOverlaps();
1186 this.resolveAirborneCollisions();
1187 this.cullOffTop();
1188 left -= step;
1189 }
1190
1191 this.releaseUnsupported();
1192 this.advanceSettle(dt);
1193 // After a landed grey group is released, blocks that were sitting on
1194 // hanging members are still STILL (the earlier pass ran while those
1195 // members counted as support). Drop them from rest before matching,
1196 // so they cannot form a mid-air match and shoot off the top.
1197 this.releaseUnsupported();
1198 this.advanceBounces(dt);
1199 if (!this.drag)
1200 { this.resolveMatches(); }
1201 this.checkLocks();
1202 this.checkGameOver();
1203 this.assertInvariants('tick');
1204};
1205
1206/** Step a stretch of time in fixed substeps. Useful for tests. */
1207GameCore.prototype.step = function (seconds, dt)
1208{
1209 dt = dt || SUBSTEP;
1210 var t = 0;
1211 while (t < seconds - 1e-15)
1212 {
1213 var s = Math.min(dt, seconds - t);
1214 this.tick(s);
1215 t += s;
1216 }
1217};
1218
1219GameCore.prototype.trySpawn = function ()
1220{
1221 if (this.state !== 'playing')
1222 { return null; }
1223 var eligible = [];
1224 for (var col = 0; col < this.width; col++)
1225 {
1226 if (this.isColumnLocked(col))
1227 { continue; }
1228 if (this.groundedCount(col) >= this.height)
1229 { continue; }
1230 var alreadyFalling = false;
1231 var list = this.blocksInColumn(col);
1232 for (var i = 0; i < list.length; i++)
1233 {
1234 if (list[i].state === STATE_FALLING)
1235 {
1236 alreadyFalling = true;
1237 break;
1238 }
1239 }
1240 if (!alreadyFalling)
1241 { eligible.push(col); }
1242 }
1243 if (!eligible.length)
1244 { return null; }
1245 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1246 var color = this.randomColor();
1247 var block = this.createBlock(col, this.height, color, STATE_FALLING);
1248 block.vy = -this.planet.fallSpeed;
1249 return block;
1250};
1251
1252GameCore.prototype.integrateFalling = function (dt)
1253{
1254 var falling = [];
1255 for (var i = 0; i < this.blocks.length; i++)
1256 {
1257 if (this.blocks[i].state === STATE_FALLING)
1258 { falling.push(this.blocks[i]); }
1259 }
1260 // Lowest first, so a stack of falling blocks rests on itself.
1261 falling.sort(function (a, b) { return a.y - b.y; });
1262 for (var i = 0; i < falling.length; i++)
1263 {
1264 var block = falling[i];
1265 if (block.state !== STATE_FALLING)
1266 { continue; }
1267 this.accelerateFall(block, dt);
1268 var nextY = block.y + block.vy * dt;
1269 var manual = this.manualInColumnHit(block, block.y, nextY);
1270 if (manual)
1271 {
1272 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
1273 continue;
1274 }
1275 var flyer = this.highestFlyingBelow(block);
1276 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1277 {
1278 if (this.attachToFlyingCluster(block, flyer))
1279 { continue; }
1280 }
1281 var top = this.stackTop(block.col, null, block.y);
1282 var below = this.highestFallingBelow(block);
1283 if (below && below.y + 1 > top)
1284 { top = below.y + 1; }
1285 if (nextY <= top)
1286 {
1287 block.y = top;
1288 this.landFallingBlock(block);
1289 }
1290 else
1291 { block.y = nextY; }
1292 }
1293};
1294
1295GameCore.prototype.clusterMembers = function (clusterId)
1296{
1297 var out = [];
1298 for (var i = 0; i < this.blocks.length; i++)
1299 {
1300 if (this.blocks[i].clusterId === clusterId)
1301 { out.push(this.blocks[i]); }
1302 }
1303 return out;
1304};
1305
1306
1307/**
1308 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
1309 * jump of height H peaks at exactly H after riseTime. Returns dy.
1310 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
1311 * upward deceleration. After the apex, vy eases from 0 to -fallSpeed
1312 * at planet.fallAccel, then stays at terminal fallSpeed.
1313 */
1314GameCore.prototype.advanceJump = function (body, dt)
1315{
1316 var dy = 0;
1317 var left = dt;
1318 if (body.phase === 'up')
1319 {
1320 var decel = body.decel;
1321 var vy = body.vy;
1322 var tApex = decel > 1e-12 ? vy / decel : Infinity;
1323 if (tApex <= left + 1e-15)
1324 {
1325 dy += vy * tApex - 0.5 * decel * tApex * tApex;
1326 body.vy = 0;
1327 body.phase = 'down';
1328 left -= tApex;
1329 }
1330 else
1331 {
1332 var vyNew = vy - decel * left;
1333 dy += (vy + vyNew) * 0.5 * left;
1334 body.vy = vyNew;
1335 left = 0;
1336 }
1337 }
1338 if (body.phase === 'up' && body.vy <= 1e-10)
1339 {
1340 body.vy = 0;
1341 body.phase = 'down';
1342 }
1343 if (body.phase === 'down' && left > 0)
1344 {
1345 var target = -this.planet.fallSpeed;
1346 var accel = this.planet.fallAccel;
1347 if (accel < 1e-12)
1348 {
1349 body.vy = target;
1350 dy += body.vy * left;
1351 }
1352 else if (body.vy > target + 1e-12)
1353 {
1354 var tReach = (body.vy - target) / accel;
1355 if (tReach <= left + 1e-15)
1356 {
1357 dy += (body.vy + target) * 0.5 * tReach;
1358 body.vy = target;
1359 left -= tReach;
1360 dy += body.vy * left;
1361 }
1362 else
1363 {
1364 var vyNew = body.vy - accel * left;
1365 dy += (body.vy + vyNew) * 0.5 * left;
1366 body.vy = vyNew;
1367 }
1368 }
1369 else
1370 {
1371 body.vy = target;
1372 dy += body.vy * left;
1373 }
1374 }
1375 return dy;
1376};
1377
1378GameCore.prototype.integrateClusters = function (dt)
1379{
1380 var ids = Object.keys(this.clusters);
1381 for (var n = 0; n < ids.length; n++)
1382 {
1383 var cluster = this.clusters[ids[n]];
1384 if (!cluster)
1385 { continue; }
1386 var members = this.clusterMembers(cluster.id);
1387 if (!members.length)
1388 {
1389 delete this.clusters[cluster.id];
1390 continue;
1391 }
1392 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1393 { continue; }
1394
1395 this.prepareClusterBody(cluster);
1396 var dy = this.advanceJump(cluster, dt);
1397 cluster.anchorY += dy;
1398 this.syncClusterMembers(cluster);
1399
1400 this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
1401 this.checkChainRelaunch(cluster);
1402
1403 if (cluster.phase === 'down' && this.clusters[cluster.id])
1404 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
1405 }
1406};
1407
1408
1409/**
1410 * If two or more flying clusters overlap in the same column, merge them
1411 * into one cluster. Velocity (and deceleration and jumpHeight) is the
1412 * mass-weighted average by block count. Phase is 'up' when the merged
1413 * vy is positive, otherwise 'down'. Overlapping members in a column
1414 * are packed so the higher one sits flush on the lower.
1415 */
1416GameCore.prototype.mergeFlyingClusters = function ()
1417{
1418 var flying = [];
1419 var ids = Object.keys(this.clusters);
1420 for (var n = 0; n < ids.length; n++)
1421 {
1422 var cluster = this.clusters[ids[n]];
1423 if (!cluster)
1424 { continue; }
1425 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1426 { continue; }
1427 flying.push(cluster);
1428 }
1429 if (flying.length < 2)
1430 { return; }
1431
1432 var uf = new UnionFind();
1433 for (var i = 0; i < flying.length; i++)
1434 { uf.add(flying[i].id); }
1435 for (var i = 0; i < flying.length; i++)
1436 {
1437 for (var j = i + 1; j < flying.length; j++)
1438 {
1439 if (this.flyingClustersOverlap(flying[i], flying[j]))
1440 { uf.union(flying[i].id, flying[j].id); }
1441 }
1442 }
1443
1444 var groups = Object.create(null);
1445 for (var i = 0; i < flying.length; i++)
1446 {
1447 var root = uf.find(flying[i].id);
1448 if (!groups[root])
1449 { groups[root] = []; }
1450 groups[root].push(flying[i]);
1451 }
1452 for (var root in groups)
1453 {
1454 if (groups[root].length >= 2)
1455 { this.mergeClusterGroup(groups[root]); }
1456 }
1457};
1458
1459GameCore.prototype.flyingClustersOverlap = function (a, b)
1460{
1461 var ma = this.clusterMembers(a.id);
1462 var mb = this.clusterMembers(b.id);
1463 for (var i = 0; i < ma.length; i++)
1464 {
1465 for (var j = 0; j < mb.length; j++)
1466 {
1467 if (ma[i].col !== mb[j].col)
1468 { continue; }
1469 if (this.sweptIntervalsOverlap(ma[i], mb[j]))
1470 { return true; }
1471 }
1472 }
1473 return false;
1474};
1475
1476/**
1477 * Swept [y, y+1) of two blocks this substep, using _prevY when present.
1478 * Catches pairs that crossed without sharing a cell at either endpoint.
1479 */
1480GameCore.prototype.sweptIntervalsOverlap = function (a, b)
1481{
1482 var a0 = (a._prevY != null) ? a._prevY : a.y;
1483 var a1 = a.y;
1484 var b0 = (b._prevY != null) ? b._prevY : b.y;
1485 var b1 = b.y;
1486 var aLo = Math.min(a0, a1);
1487 var aHi = Math.max(a0, a1) + 1;
1488 var bLo = Math.min(b0, b1);
1489 var bHi = Math.max(b0, b1) + 1;
1490 return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
1491};
1492
1493GameCore.prototype.mergeClusterGroup = function (clusters)
1494{
1495 clusters.sort(function (a, b) { return a.id - b.id; });
1496 var keep = clusters[0];
1497 var n = 0;
1498 var vySum = 0;
1499 var decelSum = 0;
1500 var hSum = 0;
1501 for (var c = 0; c < clusters.length; c++)
1502 {
1503 var mem = this.clusterMembers(clusters[c].id);
1504 var m = mem.length;
1505 n += m;
1506 vySum += clusters[c].vy * m;
1507 decelSum += (clusters[c].decel || 0) * m;
1508 hSum += (clusters[c].jumpHeight || 0) * m;
1509 }
1510 if (n === 0)
1511 { return; }
1512 keep.vy = vySum / n;
1513 keep.decel = decelSum / n;
1514 keep.jumpHeight = hSum / n;
1515 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1516 for (var c = 0; c < clusters.length; c++)
1517 {
1518 var mem = this.clusterMembers(clusters[c].id);
1519 for (var i = 0; i < mem.length; i++)
1520 {
1521 mem[i].clusterId = keep.id;
1522 mem[i].vy = keep.vy;
1523 mem[i].state = STATE_FLYING;
1524 }
1525 if (clusters[c] !== keep)
1526 { delete this.clusters[clusters[c].id]; }
1527 }
1528 this.prepareClusterBody(keep);
1529 this.checkChainRelaunch(keep);
1530 if (keep.phase === 'down' && this.clusters[keep.id])
1531 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1532};
1533
1534GameCore.prototype.packClusterOverlaps = function (cluster)
1535{
1536 var members = this.clusterMembers(cluster.id);
1537 var byCol = Object.create(null);
1538 for (var i = 0; i < members.length; i++)
1539 {
1540 var col = members[i].col;
1541 if (!byCol[col])
1542 { byCol[col] = []; }
1543 byCol[col].push(members[i]);
1544 }
1545 var cols = Object.keys(byCol);
1546 for (var c = 0; c < cols.length; c++)
1547 {
1548 var list = byCol[cols[c]];
1549 list.sort(function (a, b) { return a.y - b.y; });
1550 for (var i = 1; i < list.length; i++)
1551 {
1552 var minY = list[i - 1].y + 1;
1553 if (list[i].y < minY - 1e-12)
1554 { list[i].y = minY; }
1555 }
1556 }
1557};
1558
1559
1560/**
1561 * Derive integer cell offsets from current member positions and a
1562 * single anchorY, packing overlaps in each column while preserving
1563 * order (lower y stays lower; ties break on id). Then sync.
1564 * Flying clusters are one rigid body: one y, one vy, integer offsets.
1565 */
1566GameCore.prototype.prepareClusterBody = function (cluster)
1567{
1568 if (!cluster)
1569 { return; }
1570 var members = this.clusterMembers(cluster.id);
1571 if (!members.length)
1572 { return; }
1573 this.rebuildClusterOffsets(cluster, members);
1574};
1575
1576GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
1577{
1578 members = members || this.clusterMembers(cluster.id);
1579 if (!members.length)
1580 { return; }
1581 var byCol = Object.create(null);
1582 for (var i = 0; i < members.length; i++)
1583 {
1584 var col = members[i].col;
1585 if (!byCol[col])
1586 { byCol[col] = []; }
1587 byCol[col].push(members[i]);
1588 }
1589 var minY = Infinity;
1590 for (var i = 0; i < members.length; i++)
1591 {
1592 if (members[i].y < minY)
1593 { minY = members[i].y; }
1594 }
1595 if (cluster.anchorY == null || !isFinite(cluster.anchorY))
1596 { cluster.anchorY = minY; }
1597 var cols = Object.keys(byCol);
1598 for (var c = 0; c < cols.length; c++)
1599 {
1600 var list = byCol[cols[c]];
1601 list.sort(function (a, b)
1602 {
1603 if (a.y !== b.y)
1604 { return a.y - b.y; }
1605 return a.id - b.id;
1606 });
1607 var prevOff = -Infinity;
1608 for (var i = 0; i < list.length; i++)
1609 {
1610 var off = Math.round(list[i].y - cluster.anchorY);
1611 if (off <= prevOff)
1612 { off = prevOff + 1; }
1613 list[i].clusterOffset = off;
1614 prevOff = off;
1615 }
1616 }
1617 // Re-base so the lowest offset is 0, keeping relative integers.
1618 var minOff = Infinity;
1619 for (var i = 0; i < members.length; i++)
1620 {
1621 if (members[i].clusterOffset < minOff)
1622 { minOff = members[i].clusterOffset; }
1623 }
1624 if (minOff !== 0 && isFinite(minOff))
1625 {
1626 cluster.anchorY += minOff;
1627 for (var i = 0; i < members.length; i++)
1628 { members[i].clusterOffset -= minOff; }
1629 }
1630 this.syncClusterMembers(cluster);
1631};
1632
1633GameCore.prototype.syncClusterMembers = function (cluster)
1634{
1635 if (!cluster)
1636 { return; }
1637 var members = this.clusterMembers(cluster.id);
1638 if (cluster.anchorY == null)
1639 {
1640 var minY = Infinity;
1641 for (var i = 0; i < members.length; i++)
1642 {
1643 if (members[i].y < minY)
1644 { minY = members[i].y; }
1645 }
1646 cluster.anchorY = isFinite(minY) ? minY : 0;
1647 }
1648 for (var i = 0; i < members.length; i++)
1649 {
1650 var block = members[i];
1651 if (block.clusterOffset == null)
1652 { block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1653 block.y = cluster.anchorY + block.clusterOffset;
1654 if (cluster.phase !== 'landed')
1655 { block.vy = cluster.vy; }
1656 }
1657};
1658
1659GameCore.prototype.snapshotPrevY = function ()
1660{
1661 for (var i = 0; i < this.blocks.length; i++)
1662 { this.blocks[i]._prevY = this.blocks[i].y; }
1663};
1664
1665/**
1666 * Safety net after the specific integrates: any remaining mid-air
1667 * overlap or swept crossing is resolved with the same rules, then
1668 * every flying cluster is rebuilt as a rigid body. Repeats a few
1669 * times because one attach can create a new contact.
1670 */
1671GameCore.prototype.resolveAirborneCollisions = function ()
1672{
1673 var guard = 0;
1674 while (guard++ < this.height + 4)
1675 {
1676 var changed = false;
1677
1678 // Manual vs falling / cluster / manual.
1679 var manuals = [];
1680 for (var i = 0; i < this.blocks.length; i++)
1681 {
1682 if (this.blocks[i].state === STATE_MANUAL)
1683 { manuals.push(this.blocks[i]); }
1684 }
1685 manuals.sort(function (a, b) { return b.y - a.y; });
1686 for (var m = 0; m < manuals.length; m++)
1687 {
1688 var manual = manuals[m];
1689 if (manual.state !== STATE_MANUAL)
1690 { continue; }
1691 var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1692 if (this.resolveManualCollisions(manual, oldY, manual.y))
1693 { changed = true; }
1694 }
1695
1696 // Falling vs flying (sit on the roof).
1697 for (var i = 0; i < this.blocks.length; i++)
1698 {
1699 var block = this.blocks[i];
1700 if (block.state !== STATE_FALLING)
1701 { continue; }
1702 var flyer = this.highestFlyingBelow(block);
1703 if (!flyer)
1704 {
1705 // Also a flyer whose swept path crosses this falling block.
1706 flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1707 }
1708 if (flyer && this.sweptIntervalsOverlap(block, flyer))
1709 {
1710 if (this.attachToFlyingCluster(block, flyer))
1711 { changed = true; }
1712 }
1713 }
1714
1715 // Cluster vs cluster (swept, including after a column push).
1716 var before = Object.keys(this.clusters).length;
1717 this.mergeFlyingClusters();
1718 if (Object.keys(this.clusters).length !== before)
1719 { changed = true; }
1720
1721 // Rebuild every flying body so offsets stay integer and unique.
1722 var ids = Object.keys(this.clusters);
1723 for (var n = 0; n < ids.length; n++)
1724 {
1725 var cluster = this.clusters[ids[n]];
1726 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1727 { continue; }
1728 this.prepareClusterBody(cluster);
1729 }
1730
1731 if (!changed)
1732 { break; }
1733 }
1734};
1735
1736/**
1737 * Invariant checker (t1112). No two blocks occupy the same cell or
1738 * overlap their [y, y+1) intervals. Flying-cluster members are
1739 * grid-aligned to a single anchor. Returns a list of violation
1740 * strings (empty if clean).
1741 */
1742GameCore.prototype.checkInvariants = function ()
1743{
1744 var issues = [];
1745 var byCol = Object.create(null);
1746 var ids = Object.create(null);
1747 for (var i = 0; i < this.blocks.length; i++)
1748 {
1749 var block = this.blocks[i];
1750 if (ids[block.id])
1751 { issues.push('duplicate id ' + block.id); }
1752 ids[block.id] = true;
1753 if (!byCol[block.col])
1754 { byCol[block.col] = []; }
1755 byCol[block.col].push(block);
1756 if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1757 && block.color >= this.planet.colors.length))
1758 { issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1759 }
1760 var cols = Object.keys(byCol);
1761 for (var c = 0; c < cols.length; c++)
1762 {
1763 var list = byCol[cols[c]];
1764 list.sort(function (a, b)
1765 {
1766 if (a.y !== b.y)
1767 { return a.y - b.y; }
1768 return a.id - b.id;
1769 });
1770 for (var i = 0; i < list.length; i++)
1771 {
1772 var a = list[i];
1773 if (i > 0)
1774 {
1775 var prev = list[i - 1];
1776 if (a.y < prev.y + 1 - 1e-6)
1777 {
1778 issues.push('overlap col=' + a.col
1779 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1780 + ' gap=' + (a.y - prev.y));
1781 }
1782 var cellA = Math.floor(a.y + 1e-9);
1783 var cellP = Math.floor(prev.y + 1e-9);
1784 if (cellA === cellP)
1785 {
1786 issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1787 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1788 }
1789 }
1790 }
1791 }
1792 var cids = Object.keys(this.clusters);
1793 for (var n = 0; n < cids.length; n++)
1794 {
1795 var cluster = this.clusters[cids[n]];
1796 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1797 { continue; }
1798 var mem = this.clusterMembers(cluster.id);
1799 var seenOff = Object.create(null);
1800 for (var i = 0; i < mem.length; i++)
1801 {
1802 var b = mem[i];
1803 if (cluster.anchorY != null && b.clusterOffset != null)
1804 {
1805 var expected = cluster.anchorY + b.clusterOffset;
1806 if (Math.abs(b.y - expected) > 1e-6)
1807 {
1808 issues.push('cluster ' + cluster.id + ' member ' + b.id
1809 + ' y=' + b.y + ' != anchor+off ' + expected);
1810 }
1811 if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1812 {
1813 issues.push('cluster ' + cluster.id + ' member ' + b.id
1814 + ' non-integer offset ' + b.clusterOffset);
1815 }
1816 var key = b.col + ':' + b.clusterOffset;
1817 if (seenOff[key])
1818 {
1819 issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1820 }
1821 seenOff[key] = true;
1822 }
1823 }
1824 }
1825 return issues;
1826};
1827
1828GameCore.prototype._invBlock = function (b)
1829{
1830 return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1831 + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1832};
1833
1834GameCore.prototype.assertInvariants = function (label)
1835{
1836 if (!this.strictInvariants && !this.debugInvariants)
1837 { return; }
1838 var issues = this.checkInvariants();
1839 this.lastInvariantViolations = issues;
1840 if (!issues.length)
1841 { return; }
1842 var msg = 'physics invariants failed'
1843 + (label ? ' at ' + label : '')
1844 + ':\n ' + issues.join('\n ')
1845 + '\n' + (this.snapshot ? this.snapshot().picture : '');
1846 if (this.strictInvariants)
1847 { throw new Error(msg); }
1848};
1849
1850GameCore.prototype.tryLandCluster = function (cluster, members)
1851{
1852 if (!members.length)
1853 { return; }
1854 var shift = 0;
1855 var hit = false;
1856 for (var i = 0; i < members.length; i++)
1857 {
1858 var block = members[i];
1859 var top = this.stackTop(block.col, function (other)
1860 {
1861 return other.clusterId === cluster.id;
1862 }, block.y);
1863 if (block.y <= top + 1e-9)
1864 {
1865 hit = true;
1866 var need = top - block.y;
1867 if (need > shift)
1868 { shift = need; }
1869 }
1870 }
1871 if (!hit)
1872 { return; }
1873 // Lift the whole rigid body so the deepest contact sits flush.
1874 this.prepareClusterBody(cluster);
1875 cluster.anchorY += shift;
1876 this.syncClusterMembers(cluster);
1877 this.landCluster(cluster, this.clusterMembers(cluster.id));
1878};
1879
1880/**
1881 * Land as a rigid group: relative positions are kept, so part of the
1882 * cluster may hang above a gap. Grey members start the 3s settle timer;
1883 * coloured cargo stays put with them until every grey has recolored.
1884 * Members that actually rest on the floor or on another block bounce.
1885 */
1886GameCore.prototype.landCluster = function (cluster, members)
1887{
1888 for (var i = 0; i < members.length; i++)
1889 {
1890 var block = members[i];
1891 block.vy = 0;
1892 block.flame = false;
1893 block.clusterId = cluster.id;
1894 if (block.color === COLOR_GRAY)
1895 {
1896 block.state = STATE_SETTLING;
1897 block.settleTime = 0;
1898 }
1899 else
1900 {
1901 // Cargo stays in the rigid group (not matchable) until release.
1902 block.state = STATE_SETTLING;
1903 block.settleTime = 0;
1904 }
1905 if (this.hasSupport(block))
1906 { this.startBounce(block); }
1907 }
1908 cluster.phase = 'landed';
1909 cluster.vy = 0;
1910};
1911
1912/**
1913 * After every grey in a landed cluster has recolored, let the group go.
1914 * Unsupported blocks fall individually from rest; supported ones stay.
1915 */
1916GameCore.prototype.releaseLandedCluster = function (cluster)
1917{
1918 var members = this.clusterMembers(cluster.id);
1919 var releasing = Object.create(null);
1920 for (var i = 0; i < members.length; i++)
1921 { releasing[members[i].id] = true; }
1922
1923 for (var i = 0; i < members.length; i++)
1924 {
1925 var block = members[i];
1926 if (block.color === COLOR_GRAY)
1927 {
1928 block.color = this.randomColor();
1929 block.settleTime = 0;
1930 }
1931 this.leaveCluster(block);
1932 // Always drop leftover launch / manual velocity. A stale upward
1933 // vy here is what sends blocks off the top "very fast" after
1934 // a grey group recolors.
1935 this.clearFlightState(block);
1936 // Support from outside the group (floor or a foreign block). Fellow
1937 // members that will also fall do not count, so a hanging stack
1938 // drops together without the top one staying put.
1939 var supported = this.hasSupportOutside(block, releasing);
1940 block.state = supported ? STATE_STILL : STATE_FALLING;
1941 }
1942 delete this.clusters[cluster.id];
1943};
1944
1945GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
1946{
1947 if (block.y <= 1e-9)
1948 { return true; }
1949 for (var i = 0; i < this.blocks.length; i++)
1950 {
1951 var other = this.blocks[i];
1952 if (other === block || other.col !== block.col)
1953 { continue; }
1954 if (ignoreIds && ignoreIds[other.id])
1955 { continue; }
1956 if (!this.isGrounded(other))
1957 { continue; }
1958 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
1959 { return true; }
1960 }
1961 return false;
1962};
1963
1964GameCore.prototype.integrateManual = function (dt)
1965{
1966 for (var i = 0; i < this.blocks.length; i++)
1967 {
1968 var block = this.blocks[i];
1969 if (block.state !== STATE_MANUAL)
1970 { continue; }
1971
1972 if (block.manualPhase === 'up')
1973 {
1974 var oldY = block.y;
1975 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1976 var dy = this.advanceJump(proxy, dt);
1977 var nextY = oldY + dy;
1978 block.vy = proxy.vy;
1979 block.manualPhase = proxy.phase;
1980 if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
1981 { continue; }
1982 block.y = Math.min(nextY, block.manualTarget);
1983 if (block.y >= block.manualTarget - 1e-12)
1984 {
1985 block.y = block.manualTarget;
1986 block.vy = 0;
1987 block.manualPhase = 'down';
1988 }
1989 if (block.y > this.height - 1)
1990 {
1991 block.y = this.height - 1;
1992 block.vy = 0;
1993 block.manualPhase = 'down';
1994 }
1995 }
1996
1997 if (block.manualPhase === 'down')
1998 {
1999 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
2000 var dy = this.advanceJump(proxy, dt);
2001 block.vy = proxy.vy;
2002 var nextY = block.y + dy;
2003 var top = this.stackTop(block.col, null, block.y);
2004 if (nextY <= top)
2005 {
2006 block.y = top;
2007 block.state = STATE_STILL;
2008 block.vy = 0;
2009 block.manualPhase = null;
2010 block.flame = false;
2011 this.startBounce(block);
2012 }
2013 else
2014 {
2015 var downNext = Math.min(nextY, this.height - 1);
2016 if (this.resolveManualCollisions(block, block.y, downNext))
2017 { continue; }
2018 block.y = downNext;
2019 }
2020 }
2021 }
2022};
2023
2024/**
2025 * If the manual throw (or its path this step) hits falling blocks, merge
2026 * them into a flying cluster with mass-weighted velocity, the same rule
2027 * as two flying clusters colliding (t1108). Returns true if merged.
2028 */
2029GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
2030{
2031 if (!manual || manual.state !== STATE_MANUAL)
2032 { return false; }
2033 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
2034 if (!hits.length)
2035 { return false; }
2036 this.mergeManualWithFalling(manual, hits);
2037 return true;
2038};
2039
2040GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
2041{
2042 var lo = Math.min(oldY, newY);
2043 var hi = Math.max(oldY, newY) + 1;
2044 for (var i = 0; i < this.blocks.length; i++)
2045 {
2046 var other = this.blocks[i];
2047 if (other === falling || other.col !== falling.col)
2048 { continue; }
2049 if (other.state !== STATE_MANUAL)
2050 { continue; }
2051 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
2052 { return other; }
2053 }
2054 return null;
2055};
2056
2057GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
2058{
2059 var lo = Math.min(oldY, newY);
2060 var hi = Math.max(oldY, newY) + 1;
2061 var hits = [];
2062 for (var i = 0; i < this.blocks.length; i++)
2063 {
2064 var other = this.blocks[i];
2065 if (other === manual || other.col !== manual.col)
2066 { continue; }
2067 if (other.state !== STATE_FALLING)
2068 { continue; }
2069 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
2070 { hits.push(other); }
2071 }
2072 if (!hits.length)
2073 { return hits; }
2074 return this.contiguousFallingInColumn(manual.col, manual, hits);
2075};
2076
2077/**
2078 * Every falling block in `col` that overlaps `anchor` or a hit already
2079 * in `seed`, plus a contiguous falling stack sitting on them.
2080 */
2081GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
2082{
2083 var falling = [];
2084 for (var i = 0; i < this.blocks.length; i++)
2085 {
2086 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
2087 { falling.push(this.blocks[i]); }
2088 }
2089 falling.sort(function (a, b) { return a.y - b.y; });
2090 var include = Object.create(null);
2091 var queue = [];
2092 function enqueue (b)
2093 {
2094 if (!b || include[b.id])
2095 { return; }
2096 include[b.id] = true;
2097 queue.push(b);
2098 }
2099 if (seed)
2100 {
2101 for (var s = 0; s < seed.length; s++)
2102 { enqueue(seed[s]); }
2103 }
2104 // Also include falling that already overlap the anchor.
2105 if (anchor)
2106 {
2107 for (var i = 0; i < falling.length; i++)
2108 {
2109 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
2110 { enqueue(falling[i]); }
2111 }
2112 }
2113 for (var q = 0; q < queue.length; q++)
2114 {
2115 var a = queue[q];
2116 for (var i = 0; i < falling.length; i++)
2117 {
2118 var b = falling[i];
2119 if (include[b.id])
2120 { continue; }
2121 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
2122 { enqueue(b); }
2123 }
2124 }
2125 var out = [];
2126 for (var i = 0; i < falling.length; i++)
2127 {
2128 if (include[falling[i].id])
2129 { out.push(falling[i]); }
2130 }
2131 return out;
2132};
2133
2134/**
2135 * Merge a thrown (manual) block with falling blocks into one flying
2136 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
2137 * averages by block count, identical to mergeClusterGroup. The thrown
2138 * block stops being manual and the group follows normal cluster physics.
2139 * fromManual marks the cluster so later falling cargo also averages in.
2140 */
2141GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
2142{
2143 if (!manual || manual.state !== STATE_MANUAL)
2144 { return null; }
2145 var blocks = [manual];
2146 for (var i = 0; i < fallingList.length; i++)
2147 {
2148 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
2149 { blocks.push(fallingList[i]); }
2150 }
2151 if (blocks.length < 2)
2152 { return null; }
2153 var n = blocks.length;
2154 var vySum = 0;
2155 var decelSum = 0;
2156 var hSum = 0;
2157 for (var i = 0; i < n; i++)
2158 {
2159 var b = blocks[i];
2160 vySum += b.vy;
2161 if (b === manual)
2162 {
2163 decelSum += manual.manualDecel || 0;
2164 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
2165 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
2166 }
2167 }
2168 var cluster = {
2169 id: this.nextClusterId++,
2170 jumpHeight: hSum / n,
2171 vy: vySum / n,
2172 decel: decelSum / n,
2173 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
2174 fromManual: true
2175 };
2176 this.clusters[cluster.id] = cluster;
2177 for (var i = 0; i < n; i++)
2178 {
2179 var b = blocks[i];
2180 b.clusterId = cluster.id;
2181 b.state = STATE_FLYING;
2182 b.vy = cluster.vy;
2183 b.flame = b.color === COLOR_GRAY;
2184 b.manualPhase = null;
2185 b.manualTarget = null;
2186 b.manualDecel = 0;
2187 b.manualJumpHeight = 0;
2188 b.pushedClusters = null;
2189 b.settleTime = 0;
2190 }
2191 if (this.drag && this.drag.blockId === manual.id)
2192 { this.drag = null; }
2193 this.prepareClusterBody(cluster);
2194 this.checkChainRelaunch(cluster);
2195 return cluster;
2196};
2197
2198/** Safety net: any remaining manual/falling overlaps after the substep. */
2199GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
2200{
2201 var manuals = [];
2202 for (var i = 0; i < this.blocks.length; i++)
2203 {
2204 if (this.blocks[i].state === STATE_MANUAL)
2205 { manuals.push(this.blocks[i]); }
2206 }
2207 for (var m = 0; m < manuals.length; m++)
2208 {
2209 var manual = manuals[m];
2210 if (manual.state !== STATE_MANUAL)
2211 { continue; }
2212 var hits = this.contiguousFallingInColumn(manual.col, manual);
2213 if (hits.length)
2214 { this.mergeManualWithFalling(manual, hits); }
2215 }
2216};
2217
2218/**
2219 * Resolve collisions of a thrown (manual) block along [oldY, nextY].
2220 * Falling blocks merge (t1108). A flying cluster is pushed one cell up
2221 * in the hit column and the shot attaches at the bottom (t1111).
2222 * Another thrown block is promoted to a 1-block cluster and then the
2223 * same attach-at-bottom rule applies. Returns true if `manual` is no
2224 * longer in the MANUAL state.
2225 */
2226GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
2227{
2228 if (!manual || manual.state !== STATE_MANUAL)
2229 { return true; }
2230
2231 var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
2232 if (fallingHits.length)
2233 {
2234 this.mergeManualWithFalling(manual, fallingHits);
2235 return manual.state !== STATE_MANUAL;
2236 }
2237
2238 var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
2239 if (flyer)
2240 {
2241 var cluster = this.clusters[flyer.clusterId];
2242 if (cluster && cluster.phase !== 'landed')
2243 {
2244 if (nextY + 1e-12 < oldY)
2245 { this.attachToFlyingCluster(manual, flyer); }
2246 else
2247 { this.attachShotUnderCluster(manual, cluster, manual.col); }
2248 return manual.state !== STATE_MANUAL;
2249 }
2250 }
2251
2252 var other = this.manualHitOnManualPath(manual, oldY, nextY);
2253 if (other)
2254 {
2255 var host = this.promoteManualToCluster(other);
2256 if (host)
2257 {
2258 if (nextY + 1e-12 < oldY)
2259 { this.attachToFlyingCluster(manual, other); }
2260 else
2261 { this.attachShotUnderCluster(manual, host, manual.col); }
2262 return manual.state !== STATE_MANUAL;
2263 }
2264 }
2265 return false;
2266};
2267
2268/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
2269GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
2270{
2271 var lo = Math.min(oldY, nextY);
2272 var hi = Math.max(oldY, nextY) + 1;
2273 var best = null;
2274 var bestY = Infinity;
2275 for (var i = 0; i < this.blocks.length; i++)
2276 {
2277 var other = this.blocks[i];
2278 if (other === manual || other.col !== manual.col)
2279 { continue; }
2280 if (other.state !== STATE_FLYING || other.clusterId == null)
2281 { continue; }
2282 var cluster = this.clusters[other.clusterId];
2283 if (!cluster || cluster.phase === 'landed')
2284 { continue; }
2285 var o0 = (other._prevY != null) ? other._prevY : other.y;
2286 var o1 = other.y;
2287 var oLo = Math.min(o0, o1);
2288 var oHi = Math.max(o0, o1) + 1;
2289 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
2290 {
2291 if (other.y < bestY)
2292 {
2293 bestY = other.y;
2294 best = other;
2295 }
2296 }
2297 }
2298 return best;
2299};
2300
2301/** Another thrown block in the same column on the path (prefer the lower). */
2302GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
2303{
2304 var lo = Math.min(oldY, nextY);
2305 var hi = Math.max(oldY, nextY) + 1;
2306 var best = null;
2307 for (var i = 0; i < this.blocks.length; i++)
2308 {
2309 var other = this.blocks[i];
2310 if (other === manual || other.col !== manual.col)
2311 { continue; }
2312 if (other.state !== STATE_MANUAL)
2313 { continue; }
2314 var o0 = (other._prevY != null) ? other._prevY : other.y;
2315 var o1 = other.y;
2316 var oLo = Math.min(o0, o1);
2317 var oHi = Math.max(o0, o1) + 1;
2318 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
2319 {
2320 if (!best || other.y < best.y)
2321 { best = other; }
2322 }
2323 }
2324 return best;
2325};
2326
2327/**
2328 * t1111: push every member of `cluster` in `col` up by one cell, then
2329 * attach `manual` at the bottom of that column, grid-aligned, as part
2330 * of the cluster. The cluster keeps its velocity; the shot takes it.
2331 * Other columns are untouched. Same rule for every successive shot.
2332 */
2333GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
2334{
2335 if (!manual || !cluster || !this.clusters[cluster.id])
2336 { return false; }
2337 if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
2338 {
2339 // Already belonging elsewhere: leave first.
2340 if (manual.clusterId != null)
2341 { this.leaveCluster(manual); }
2342 }
2343 this.prepareClusterBody(cluster);
2344 var members = this.clusterMembers(cluster.id);
2345 var minOff = null;
2346 for (var i = 0; i < members.length; i++)
2347 {
2348 if (members[i].col !== col)
2349 { continue; }
2350 if (minOff == null || members[i].clusterOffset < minOff)
2351 { minOff = members[i].clusterOffset; }
2352 }
2353 if (minOff == null)
2354 { minOff = 0; }
2355 else
2356 {
2357 for (var i = 0; i < members.length; i++)
2358 {
2359 if (members[i].col === col)
2360 { members[i].clusterOffset += 1; }
2361 }
2362 }
2363 if (this.drag && this.drag.blockId === manual.id)
2364 { this.drag = null; }
2365 manual.clusterId = cluster.id;
2366 manual.clusterOffset = minOff;
2367 manual.state = STATE_FLYING;
2368 manual.flame = manual.color === COLOR_GRAY;
2369 manual.settleTime = 0;
2370 manual.manualPhase = null;
2371 manual.manualTarget = null;
2372 manual.manualDecel = 0;
2373 manual.manualJumpHeight = 0;
2374 manual.pushedClusters = null;
2375 this.syncClusterMembers(cluster);
2376 this.cullOffTop();
2377 if (this.clusters[cluster.id])
2378 { this.checkChainRelaunch(cluster); }
2379 return true;
2380};
2381
2382/**
2383 * Turn a lone thrown block into a 1-block flying cluster so a later
2384 * shot can use the t1111 attach-at-bottom rule. A single throw stays
2385 * MANUAL (and is capped at the top of the field) until it collides.
2386 */
2387GameCore.prototype.promoteManualToCluster = function (manual)
2388{
2389 if (!manual)
2390 { return null; }
2391 if (manual.state === STATE_FLYING && manual.clusterId != null)
2392 {
2393 var existing = this.clusters[manual.clusterId];
2394 if (existing && existing.phase !== 'landed')
2395 { return existing; }
2396 }
2397 if (manual.state !== STATE_MANUAL)
2398 { return null; }
2399 var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
2400 : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
2401 var cluster = {
2402 id: this.nextClusterId++,
2403 jumpHeight: height,
2404 vy: manual.vy,
2405 decel: manual.manualDecel || 0,
2406 phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
2407 fromManual: true,
2408 anchorY: manual.y
2409 };
2410 this.clusters[cluster.id] = cluster;
2411 manual.state = STATE_FLYING;
2412 manual.clusterId = cluster.id;
2413 manual.clusterOffset = 0;
2414 manual.flame = manual.color === COLOR_GRAY;
2415 manual.settleTime = 0;
2416 manual.manualPhase = null;
2417 manual.manualTarget = null;
2418 manual.manualDecel = 0;
2419 manual.manualJumpHeight = 0;
2420 manual.pushedClusters = null;
2421 this.syncClusterMembers(cluster);
2422 return cluster;
2423};
2424
2425/** Kept for older tests / call sites: push a cluster column by one cell. */
2426GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
2427{
2428 return this.resolveManualCollisions(manual, oldY, nextY);
2429};
2430
2431
2432/**
2433 * Push every flying block of the cluster that sits in `col` one tile up.
2434 * Other columns stay put (they remain linked). Then look for a new
2435 * same-color line of 3+ in the flying cluster; if there is one, those
2436 * blocks turn gray, join the link, and the whole cluster re-launches
2437 * with the same jump height from its current position.
2438 */
2439GameCore.prototype.pushClusterColumn = function (clusterId, col)
2440{
2441 var cluster = this.clusters[clusterId];
2442 if (!cluster)
2443 { return false; }
2444 var members = this.clusterMembers(clusterId);
2445 for (var i = 0; i < members.length; i++)
2446 {
2447 if (members[i].col === col)
2448 { members[i].y += 1; }
2449 }
2450 this.cullOffTop();
2451 if (!this.clusters[clusterId])
2452 { return true; }
2453 this.checkChainRelaunch(cluster);
2454 return true;
2455};
2456
2457/**
2458 * After a cargo attach or a cluster merge (or any other mid-air state
2459 * change), turn spontaneous lines of 3+ into rockets and give the whole
2460 * already-flying cluster an extra launch from its current position —
2461 * the same re-launch as a player push that completes a row.
2462 */
2463GameCore.prototype.resolveFlyingMatches = function ()
2464{
2465 var ids = Object.keys(this.clusters);
2466 for (var n = 0; n < ids.length; n++)
2467 {
2468 var cluster = this.clusters[ids[n]];
2469 if (!cluster || cluster.phase === 'landed')
2470 { continue; }
2471 this.checkChainRelaunch(cluster);
2472 }
2473};
2474
2475GameCore.prototype.checkChainRelaunch = function (cluster)
2476{
2477 if (!this.clusters[cluster.id])
2478 { return; }
2479 var lines = this.findFlyingMatchLines(cluster.id);
2480 if (!lines.length)
2481 { return; }
2482 var newly = [];
2483 var seen = Object.create(null);
2484 for (var i = 0; i < lines.length; i++)
2485 {
2486 for (var j = 0; j < lines[i].blocks.length; j++)
2487 {
2488 var block = lines[i].blocks[j];
2489 if (seen[block.id])
2490 { continue; }
2491 seen[block.id] = true;
2492 newly.push(block);
2493 }
2494 }
2495 for (var i = 0; i < newly.length; i++)
2496 {
2497 var block = newly[i];
2498 block.color = COLOR_GRAY;
2499 block.flame = true;
2500 block.clusterId = cluster.id;
2501 block.state = STATE_FLYING;
2502 }
2503 this.relaunchCluster(cluster, cluster.jumpHeight);
2504};
2505
2506GameCore.prototype.relaunchCluster = function (cluster, height)
2507{
2508 cluster.jumpHeight = height;
2509 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
2510 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
2511 cluster.phase = 'up';
2512 var members = this.clusterMembers(cluster.id);
2513 for (var i = 0; i < members.length; i++)
2514 {
2515 members[i].vy = cluster.vy;
2516 members[i].state = STATE_FLYING;
2517 if (members[i].color === COLOR_GRAY)
2518 { members[i].flame = true; }
2519 }
2520};
2521
2522GameCore.prototype.startManualLaunch = function (block)
2523{
2524 var target = this.height - 1;
2525 var height = Math.max(0.05, target - block.y);
2526 this.leaveCluster(block);
2527 block.state = STATE_MANUAL;
2528 block.pushedClusters = Object.create(null);
2529 block.manualTarget = target;
2530 block.manualPhase = 'up';
2531 block.manualJumpHeight = height;
2532 block.vy = PlanetMod.launchVelocity(this.planet, height);
2533 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
2534 block.flame = false;
2535 if (this.drag && this.drag.blockId === block.id)
2536 { this.drag = null; }
2537};
2538
2539GameCore.prototype.cullOffTop = function ()
2540{
2541 var gone = [];
2542 for (var i = 0; i < this.blocks.length; i++)
2543 {
2544 var block = this.blocks[i];
2545 if (block.state === STATE_MANUAL)
2546 {
2547 if (block.y > this.height - 1)
2548 { block.y = this.height - 1; }
2549 continue;
2550 }
2551 if (block.y >= this.height - 1e-9)
2552 { gone.push(block); }
2553 }
2554 for (var i = 0; i < gone.length; i++)
2555 {
2556 var block = gone[i];
2557 this.outgoingShots.push({
2558 id: block.id,
2559 color: block.color,
2560 col: block.col,
2561 y: block.y
2562 });
2563 this.score += 1;
2564 this.removeBlock(block);
2565 }
2566};
2567
2568GameCore.prototype.consumeOutgoingShots = function ()
2569{
2570 var shots = this.outgoingShots;
2571 this.outgoingShots = [];
2572 return shots;
2573};
2574
2575/**
2576 * A compact field picture for the multiplayer snapshot (miniatures).
2577 * Includes every block's col, y, color, state and flame.
2578 */
2579GameCore.prototype.fieldSnapshot = function ()
2580{
2581 var blocks = [];
2582 for (var i = 0; i < this.blocks.length; i++)
2583 {
2584 var b = this.blocks[i];
2585 blocks.push({
2586 id: b.id,
2587 col: b.col,
2588 y: Math.round(b.y * 1000) / 1000,
2589 color: b.color,
2590 state: b.state,
2591 flame: !!b.flame
2592 });
2593 }
2594 return {
2595 score: this.score,
2596 state: this.state,
2597 width: this.width,
2598 height: this.height,
2599 locked: this.lockedColumnCount(),
2600 blocks: blocks
2601 };
2602};
2603
2604/**
2605 * Incoming garbage from another player: a dark-grey block that falls
2606 * normally from the top of an open column. After landing it uses the
2607 * usual 3s settle and then a random colour (landFallingBlock).
2608 * `col` is optional; a random eligible column is used otherwise.
2609 * Returns the new block, or null if every column is locked or full.
2610 */
2611GameCore.prototype.ingestGarbage = function (col)
2612{
2613 if (this.state !== 'playing')
2614 { return null; }
2615 var chosen = null;
2616 if (col != null && col >= 0 && col < this.width
2617 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
2618 { chosen = col | 0; }
2619 else
2620 {
2621 var eligible = [];
2622 for (var c = 0; c < this.width; c++)
2623 {
2624 if (this.isColumnLocked(c))
2625 { continue; }
2626 if (this.groundedCount(c) >= this.height)
2627 { continue; }
2628 eligible.push(c);
2629 }
2630 if (!eligible.length)
2631 { return null; }
2632 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2633 }
2634 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2635 block.vy = -this.planet.fallSpeed;
2636 block.flame = false;
2637 return block;
2638};
2639
2640GameCore.prototype.advanceSettle = function (dt)
2641{
2642 for (var i = 0; i < this.blocks.length; i++)
2643 {
2644 var block = this.blocks[i];
2645 if (block.state !== STATE_SETTLING)
2646 { continue; }
2647 var inLanded = block.clusterId != null
2648 && this.clusters[block.clusterId]
2649 && this.clusters[block.clusterId].phase === 'landed';
2650 if (block.color === COLOR_GRAY)
2651 {
2652 block.settleTime += dt;
2653 if (block.settleTime >= this.settleTime)
2654 {
2655 block.color = this.randomColor();
2656 block.settleTime = 0;
2657 block.flame = false;
2658 if (inLanded)
2659 {
2660 // Stay in the rigid group; releaseLandedCluster runs below.
2661 block.state = STATE_SETTLING;
2662 }
2663 else
2664 {
2665 this.leaveCluster(block);
2666 this.clearFlightState(block);
2667 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2668 }
2669 }
2670 }
2671 else if (!inLanded)
2672 {
2673 // Coloured settling that is not in a landed cluster (shouldn't
2674 // normally happen): just become still or fall, from rest.
2675 this.leaveCluster(block);
2676 this.clearFlightState(block);
2677 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2678 }
2679 }
2680
2681 var ids = Object.keys(this.clusters);
2682 for (var n = 0; n < ids.length; n++)
2683 {
2684 var cluster = this.clusters[ids[n]];
2685 if (!cluster || cluster.phase !== 'landed')
2686 { continue; }
2687 var members = this.clusterMembers(cluster.id);
2688 var greySettling = false;
2689 for (var i = 0; i < members.length; i++)
2690 {
2691 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2692 { greySettling = true; }
2693 }
2694 if (!greySettling)
2695 { this.releaseLandedCluster(cluster); }
2696 }
2697};
2698
2699GameCore.prototype.findMatchLines = function ()
2700{
2701 var candidates = [];
2702 for (var i = 0; i < this.blocks.length; i++)
2703 {
2704 var block = this.blocks[i];
2705 // Coloured cargo in a just-landed cluster (SETTLING) can match
2706 // with already-resting blocks immediately (t1110). Greys have no
2707 // colour and wait until they recolor; after release they are STILL.
2708 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2709 && block.color >= 0)
2710 { candidates.push(block); }
2711 }
2712 return this.collectLines(candidates, true);
2713};
2714
2715GameCore.prototype.findFlyingMatchLines = function (clusterId)
2716{
2717 var candidates = [];
2718 for (var i = 0; i < this.blocks.length; i++)
2719 {
2720 var block = this.blocks[i];
2721 if (block.clusterId === clusterId && block.color >= 0
2722 && (block.state === STATE_FLYING))
2723 { candidates.push(block); }
2724 }
2725 return this.collectLines(candidates, false);
2726};
2727
2728GameCore.prototype.collectLines = function (candidates, snapInteger)
2729{
2730 var lines = [];
2731 if (!candidates.length)
2732 { return lines; }
2733
2734 var byRow = Object.create(null);
2735 for (var i = 0; i < candidates.length; i++)
2736 {
2737 var block = candidates[i];
2738 var row = Math.round(block.y);
2739 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2740 { continue; }
2741 if (!byRow[row])
2742 { byRow[row] = []; }
2743 byRow[row].push(block);
2744 }
2745 var rows = Object.keys(byRow);
2746 for (var r = 0; r < rows.length; r++)
2747 {
2748 var list = byRow[rows[r]];
2749 list.sort(function (a, b) { return a.col - b.col; });
2750 this.pushRuns(lines, list, false, function (a, b)
2751 {
2752 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2753 });
2754 }
2755
2756 var byCol = Object.create(null);
2757 for (var i = 0; i < candidates.length; i++)
2758 {
2759 var block = candidates[i];
2760 if (!byCol[block.col])
2761 { byCol[block.col] = []; }
2762 byCol[block.col].push(block);
2763 }
2764 var cols = Object.keys(byCol);
2765 for (var c = 0; c < cols.length; c++)
2766 {
2767 var list = byCol[cols[c]];
2768 list.sort(function (a, b) { return a.y - b.y; });
2769 this.pushRuns(lines, list, true, function (a, b)
2770 {
2771 return a.color === b.color && a.color >= 0
2772 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2773 });
2774 }
2775 return lines;
2776};
2777
2778GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2779{
2780 var start = 0;
2781 for (var i = 1; i <= list.length; i++)
2782 {
2783 var same = i < list.length && adjacent(list[i - 1], list[i]);
2784 if (!same)
2785 {
2786 var length = i - start;
2787 if (length >= 3)
2788 {
2789 lines.push({
2790 blocks: list.slice(start, i),
2791 length: length,
2792 vertical: vertical
2793 });
2794 }
2795 start = i;
2796 }
2797 }
2798};
2799
2800GameCore.prototype.resolveMatches = function ()
2801{
2802 if (this.state !== 'playing' || this.drag)
2803 { return []; }
2804 var lines = this.findMatchLines();
2805 if (!lines.length)
2806 { return []; }
2807
2808 var uf = new UnionFind();
2809 var blockById = Object.create(null);
2810 for (var i = 0; i < lines.length; i++)
2811 {
2812 var line = lines[i];
2813 for (var j = 0; j < line.blocks.length; j++)
2814 {
2815 uf.add(line.blocks[j].id);
2816 blockById[line.blocks[j].id] = line.blocks[j];
2817 if (j > 0)
2818 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2819 }
2820 }
2821 var matched = [];
2822 var seen = Object.create(null);
2823 for (var id in blockById)
2824 {
2825 if (!seen[id])
2826 {
2827 seen[id] = true;
2828 matched.push(blockById[id]);
2829 }
2830 }
2831 for (var i = 0; i < matched.length; i++)
2832 {
2833 for (var j = i + 1; j < matched.length; j++)
2834 {
2835 if (matched[i].col === matched[j].col)
2836 { uf.union(matched[i].id, matched[j].id); }
2837 }
2838 }
2839
2840 var groups = Object.create(null);
2841 for (var i = 0; i < matched.length; i++)
2842 {
2843 var root = uf.find(matched[i].id);
2844 if (!groups[root])
2845 { groups[root] = []; }
2846 groups[root].push(matched[i]);
2847 }
2848
2849 var launched = [];
2850 for (var root in groups)
2851 {
2852 var group = groups[root];
2853 var height = 0;
2854 for (var i = 0; i < lines.length; i++)
2855 {
2856 var line = lines[i];
2857 var overlaps = false;
2858 for (var j = 0; j < line.blocks.length; j++)
2859 {
2860 for (var k = 0; k < group.length; k++)
2861 {
2862 if (line.blocks[j].id === group[k].id)
2863 { overlaps = true; }
2864 }
2865 }
2866 if (overlaps)
2867 {
2868 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2869 if (h > height)
2870 { height = h; }
2871 }
2872 }
2873 this.launchCluster(group, height);
2874 launched.push({ blocks: group, jumpHeight: height });
2875 }
2876 return launched;
2877};
2878
2879/**
2880 * Gray the matched blocks, take everything sitting on top of them in
2881 * those columns, link them, and launch with jump height `height`.
2882 */
2883GameCore.prototype.launchCluster = function (matchedBlocks, height)
2884{
2885 var lowestInCol = Object.create(null);
2886 var matchedIds = Object.create(null);
2887 for (var i = 0; i < matchedBlocks.length; i++)
2888 {
2889 var block = matchedBlocks[i];
2890 matchedIds[block.id] = true;
2891 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
2892 { lowestInCol[block.col] = block.y; }
2893 }
2894
2895 var clusterId = this.nextClusterId++;
2896 var cluster = {
2897 id: clusterId,
2898 jumpHeight: height,
2899 vy: PlanetMod.launchVelocity(this.planet, height),
2900 decel: PlanetMod.launchDeceleration(this.planet, height),
2901 phase: 'up'
2902 };
2903 this.clusters[clusterId] = cluster;
2904
2905 var riders = [];
2906 var cols = Object.keys(lowestInCol);
2907 for (var c = 0; c < cols.length; c++)
2908 {
2909 var col = +cols[c];
2910 var lowest = lowestInCol[col];
2911 var list = this.blocksInColumn(col);
2912 for (var i = 0; i < list.length; i++)
2913 {
2914 var block = list[i];
2915 if (!this.isGrounded(block) && block.state !== STATE_STILL)
2916 {
2917 if (block.state !== STATE_SETTLING)
2918 { continue; }
2919 }
2920 if (block.y + ALIGN_EPS >= lowest)
2921 { riders.push(block); }
2922 }
2923 }
2924
2925 for (var i = 0; i < riders.length; i++)
2926 {
2927 var block = riders[i];
2928 var isMatch = !!matchedIds[block.id];
2929 if (isMatch || block.color === COLOR_GRAY)
2930 {
2931 block.color = COLOR_GRAY;
2932 block.flame = true;
2933 }
2934 else
2935 { block.flame = false; }
2936 block.state = STATE_FLYING;
2937 block.clusterId = clusterId;
2938 block.vy = cluster.vy;
2939 block.settleTime = 0;
2940 }
2941 this.prepareClusterBody(cluster);
2942 return cluster;
2943};
2944
2945GameCore.prototype.checkLocks = function ()
2946{
2947 for (var col = 0; col < this.width; col++)
2948 {
2949 if (this.isColumnLocked(col))
2950 { continue; }
2951 if (this.groundedCount(col) < this.height)
2952 { continue; }
2953 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
2954 var filled = true;
2955 for (var row = 0; row < this.height; row++)
2956 {
2957 var block = this.blockAt(col, row);
2958 if (!block || !this.isGrounded(block))
2959 {
2960 filled = false;
2961 break;
2962 }
2963 }
2964 if (!filled)
2965 { continue; }
2966 var list = this.blocksInColumn(col);
2967 for (var i = 0; i < list.length; i++)
2968 {
2969 var block = list[i];
2970 if (!this.isGrounded(block))
2971 { continue; }
2972 block.state = STATE_LOCKED;
2973 block.color = COLOR_GRAY;
2974 block.flame = false;
2975 block.vy = 0;
2976 block.settleTime = 0;
2977 if (block.clusterId != null)
2978 { this.leaveCluster(block); }
2979 }
2980 }
2981};
2982
2983GameCore.prototype.checkGameOver = function ()
2984{
2985 if (this.state !== 'playing')
2986 { return; }
2987 for (var col = 0; col < this.width; col++)
2988 {
2989 if (!this.isColumnLocked(col))
2990 { return; }
2991 }
2992 this.state = 'gameover';
2993 this.gameOverTime = 0;
2994 this.drag = null;
2995};
2996
2997/* ---------- dragging -------------------------------------------------- */
2998
2999GameCore.prototype.beginDrag = function (col, y)
3000{
3001 if (this.state !== 'playing')
3002 { return false; }
3003 var block = this.snapDragBlock(col, y);
3004 if (!block)
3005 { return false; }
3006 var top = this.columnStackTopRow(block.col);
3007 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
3008 this.drag = {
3009 blockId: block.id,
3010 pointerY: y,
3011 startY: y,
3012 accum: 0,
3013 launchIntent: false,
3014 startedAsTop: startedAsTop
3015 };
3016 return true;
3017};
3018
3019/**
3020 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
3021 * floor(col), floor(y); any press inside that cell — corners, padding,
3022 * gaps between sprites, a visually tweened or bouncing sprite — grabs
3023 * the block that occupies it. This uses simulation cells, not the drawn
3024 * sprite bounds. If no block sits in that cell (mid-animation, a block
3025 * whose y is off the integer), fall back to the nearest grabbable block
3026 * in the same column within SNAP_Y (about half a tile). A small
3027 * horizontal slop still consults a neighbouring column when the press
3028 * is near the edge and the primary cell is empty.
3029 */
3030GameCore.prototype.snapDragBlock = function (col, y)
3031{
3032 var raw = col;
3033 var c0 = Math.floor(raw + 1e-9);
3034 var row = Math.floor(y + 1e-9);
3035 var frac = raw - c0;
3036
3037 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
3038 {
3039 var exact = this.draggableInCell(c0, row);
3040 if (exact)
3041 { return exact; }
3042 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
3043 if (near)
3044 { return near; }
3045 }
3046
3047 // Primary cell empty: allow a small horizontal slop into a neighbour.
3048 var neighbours = [];
3049 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
3050 { neighbours.push(c0 - 1); }
3051 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
3052 { neighbours.push(c0 + 1); }
3053 var best = null;
3054 var bestDist = Infinity;
3055 for (var n = 0; n < neighbours.length; n++)
3056 {
3057 var cc = neighbours[n];
3058 if (!this.columnAllowsDrag(cc))
3059 { continue; }
3060 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
3061 if (!hit)
3062 { continue; }
3063 var dist = this.pointerDistToBlock(hit, raw, y);
3064 if (dist < bestDist)
3065 {
3066 bestDist = dist;
3067 best = hit;
3068 }
3069 }
3070 return best;
3071};
3072
3073/** The draggable block that occupies grid cell (col, row), if any. */
3074GameCore.prototype.draggableInCell = function (col, row)
3075{
3076 var best = null;
3077 var bestOverlap = 0;
3078 var list = this.blocksInColumn(col);
3079 for (var i = 0; i < list.length; i++)
3080 {
3081 var block = list[i];
3082 if (!this.isDraggableBlock(block))
3083 { continue; }
3084 var lo = Math.max(block.y, row);
3085 var hi = Math.min(block.y + 1, row + 1);
3086 var overlap = hi - lo;
3087 if (overlap > bestOverlap + 1e-12)
3088 {
3089 bestOverlap = overlap;
3090 best = block;
3091 }
3092 }
3093 if (best && bestOverlap > 1e-9)
3094 { return best; }
3095 return null;
3096};
3097
3098/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
3099GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
3100{
3101 var best = null;
3102 var bestDist = Infinity;
3103 var list = this.blocksInColumn(col);
3104 for (var i = 0; i < list.length; i++)
3105 {
3106 var block = list[i];
3107 if (!this.isDraggableBlock(block))
3108 { continue; }
3109 var dist = this.pointerDistToBlock(block, col + 0.5, y);
3110 if (dist < bestDist)
3111 {
3112 bestDist = dist;
3113 best = block;
3114 }
3115 }
3116 if (!best || bestDist > maxDist)
3117 { return null; }
3118 return best;
3119};
3120
3121GameCore.prototype.pointerDistToBlock = function (block, col, y)
3122{
3123 var dx;
3124 if (col >= block.col && col < block.col + 1)
3125 { dx = 0; }
3126 else if (col < block.col)
3127 { dx = block.col - col; }
3128 else
3129 { dx = col - (block.col + 1); }
3130 var dy;
3131 if (y >= block.y && y < block.y + 1)
3132 { dy = 0; }
3133 else if (y < block.y)
3134 { dy = block.y - y; }
3135 else
3136 { dy = y - (block.y + 1); }
3137 return Math.sqrt(dx * dx + dy * dy);
3138};
3139
3140GameCore.prototype.moveDrag = function (y)
3141{
3142 if (!this.drag)
3143 { return; }
3144 var block = this.blockById(this.drag.blockId);
3145 if (!block || !this.isDraggableBlock(block))
3146 {
3147 this.drag = null;
3148 return;
3149 }
3150 if (!this.columnAllowsDrag(block.col))
3151 {
3152 this.drag = null;
3153 return;
3154 }
3155 this.drag.pointerY = y;
3156 // 1:1 tracking: the target row is the one under the pointer, clamped
3157 // to the still stack. Swap step by step with each neighbour, and stop
3158 // exactly there. When the pointer stops, nothing else moves.
3159 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
3160 // used to jump a full cell on a short pull, and one large event
3161 // could walk the entire column (the "jumps all the way" bug).
3162 var top = this.columnStackTopRow(block.col);
3163 var bottom = this.columnStackBottomRow(block.col);
3164 var target = Math.floor(y + 1e-12);
3165 if (bottom < 0)
3166 { bottom = 0; }
3167 if (target < bottom)
3168 { target = bottom; }
3169 if (target > top)
3170 { target = top; }
3171 this.swapToward(block, target);
3172
3173 top = this.columnStackTopRow(block.col);
3174 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
3175 if (this.drag.startedAsTop)
3176 {
3177 // Already the topmost block: pulling upward past its own position
3178 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
3179 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
3180 }
3181 else
3182 {
3183 // Started mid-stack: swap first, and only launch once the pointer
3184 // is pulled into the empty space above the (new) top.
3185 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
3186 }
3187};
3188
3189/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
3190GameCore.prototype.swapOne = function (block, dir)
3191{
3192 var neighbor = this.blockAt(block.col, block.y + dir);
3193 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
3194 {
3195 this.swapBlocks(block, neighbor);
3196 return true;
3197 }
3198 return false;
3199};
3200
3201GameCore.prototype.endDrag = function ()
3202{
3203 if (!this.drag)
3204 { return; }
3205 var block = this.blockById(this.drag.blockId);
3206 var launch = this.drag.launchIntent;
3207 this.drag = null;
3208 if (launch && block && block.state === STATE_STILL)
3209 { this.startManualLaunch(block); }
3210 else
3211 { this.resolveMatches(); }
3212};
3213
3214GameCore.prototype.blockById = function (id)
3215{
3216 for (var i = 0; i < this.blocks.length; i++)
3217 {
3218 if (this.blocks[i].id === id)
3219 { return this.blocks[i]; }
3220 }
3221 return null;
3222};
3223
3224GameCore.prototype.columnStackTopRow = function (col)
3225{
3226 var top = -1;
3227 var list = this.blocksInColumn(col);
3228 for (var i = 0; i < list.length; i++)
3229 {
3230 if (this.isGrounded(list[i]) && list[i].y > top)
3231 { top = list[i].y; }
3232 }
3233 return top;
3234};
3235
3236GameCore.prototype.columnStackBottomRow = function (col)
3237{
3238 var bottom = Infinity;
3239 var list = this.blocksInColumn(col);
3240 for (var i = 0; i < list.length; i++)
3241 {
3242 if (this.isGrounded(list[i]) && list[i].y < bottom)
3243 { bottom = list[i].y; }
3244 }
3245 return bottom === Infinity ? 0 : bottom;
3246};
3247
3248GameCore.prototype.swapToward = function (block, targetY)
3249{
3250 var guard = 0;
3251 while (guard++ < this.height + 2)
3252 {
3253 var current = block.y;
3254 if (targetY > current + 0.5)
3255 {
3256 var above = this.blockAt(block.col, current + 1);
3257 if (above && this.isGrounded(above) && above !== block)
3258 { this.swapBlocks(block, above); }
3259 else
3260 { break; }
3261 }
3262 else if (targetY < current - 0.5)
3263 {
3264 var below = this.blockAt(block.col, current - 1);
3265 if (below && this.isGrounded(below) && below !== block)
3266 { this.swapBlocks(block, below); }
3267 else
3268 { break; }
3269 }
3270 else
3271 { break; }
3272 }
3273};
3274
3275GameCore.prototype.swapBlocks = function (a, b)
3276{
3277 var y = a.y;
3278 a.y = b.y;
3279 b.y = y;
3280 this.transferLandedMembership(a, b);
3281};
3282
3283/**
3284 * A landed cluster (grey rockets or linked cargo resting on the ground)
3285 * is a swappable part of the contiguous grounded stack. Flying, falling
3286 * and manual blocks are not. A locked column is not.
3287 */
3288GameCore.prototype.isDraggableBlock = function (block)
3289{
3290 if (!block)
3291 { return false; }
3292 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
3293 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
3294 { return false; }
3295 if (block.clusterId != null)
3296 {
3297 var cluster = this.clusters[block.clusterId];
3298 // Flying (rising / descending) clusters stay non-draggable.
3299 if (cluster && cluster.phase !== 'landed')
3300 { return false; }
3301 }
3302 return block.state === STATE_STILL || block.state === STATE_SETTLING;
3303};
3304
3305/**
3306 * The grounded contiguous stack in this column can be dragged, even if a
3307 * flying cluster or a falling spawn occupies the air above it. Only a
3308 * locked column is blocked as a whole.
3309 */
3310GameCore.prototype.columnAllowsDrag = function (col)
3311{
3312 return !this.isColumnLocked(col);
3313};
3314
3315GameCore.prototype.landedClusterId = function (block)
3316{
3317 if (!block || block.clusterId == null)
3318 { return null; }
3319 var cluster = this.clusters[block.clusterId];
3320 if (!cluster || cluster.phase !== 'landed')
3321 { return null; }
3322 return block.clusterId;
3323};
3324
3325/**
3326 * After a swap: leaving a landed cluster clears membership; joining one
3327 * makes the block part of that rigid group. Same-cluster swaps only
3328 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
3329 */
3330GameCore.prototype.transferLandedMembership = function (a, b)
3331{
3332 var ca = this.landedClusterId(a);
3333 var cb = this.landedClusterId(b);
3334 if (ca === cb)
3335 { return; }
3336 // Join first so leaveCluster does not delete a cluster that still
3337 // has the incoming member.
3338 this.applyLandedMembership(b, ca);
3339 this.applyLandedMembership(a, cb);
3340};
3341
3342GameCore.prototype.applyLandedMembership = function (block, clusterId)
3343{
3344 if (clusterId == null)
3345 {
3346 var wasGrey = block.color === COLOR_GRAY;
3347 var wasSettling = block.state === STATE_SETTLING;
3348 this.leaveCluster(block);
3349 if (wasGrey && wasSettling)
3350 {
3351 // Keep settling and recolor on its own, same remaining timer.
3352 block.state = STATE_SETTLING;
3353 }
3354 else if (wasSettling)
3355 {
3356 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
3357 }
3358 return;
3359 }
3360 if (!this.clusters[clusterId])
3361 { return; }
3362 block.clusterId = clusterId;
3363 block.flame = false;
3364 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
3365 { block.state = STATE_SETTLING; }
3366};
3367
3368/**
3369 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
3370 * Returns the moved block, or null if the column does not allow a drag.
3371 */
3372GameCore.prototype.swapTo = function (col, fromRow, toRow)
3373{
3374 if (!this.columnAllowsDrag(col))
3375 { return null; }
3376 var block = this.blockAt(col, fromRow);
3377 if (!block)
3378 { return null; }
3379 this.swapToward(block, toRow);
3380 return block;
3381};
3382
3383/**
3384 * Test helper: a compact picture of grounded/falling/flying blocks.
3385 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
3386 * L locked, f falling, m manual, . empty. Flying colored blocks use
3387 * their color with a marker in `flying`.
3388 */
3389GameCore.prototype.snapshot = function ()
3390{
3391 var grid = [];
3392 for (var r = 0; r < this.height; r++)
3393 {
3394 var row = [];
3395 for (var c = 0; c < this.width; c++)
3396 { row.push('.'); }
3397 grid.push(row);
3398 }
3399 var airborne = [];
3400 for (var i = 0; i < this.blocks.length; i++)
3401 {
3402 var block = this.blocks[i];
3403 var ch;
3404 if (block.state === STATE_LOCKED)
3405 { ch = 'L'; }
3406 else if (block.color === COLOR_GRAY)
3407 { ch = 'g'; }
3408 else
3409 { ch = String(block.color); }
3410 if (this.isGrounded(block) || block.state === STATE_FALLING)
3411 {
3412 var row = Math.round(block.y);
3413 if (row >= 0 && row < this.height)
3414 { grid[row][block.col] = ch; }
3415 }
3416 else
3417 {
3418 airborne.push({
3419 id: block.id,
3420 col: block.col,
3421 y: block.y,
3422 color: block.color,
3423 state: block.state,
3424 clusterId: block.clusterId,
3425 flame: block.flame,
3426 vy: block.vy
3427 });
3428 }
3429 }
3430 var lines = [];
3431 for (var r = this.height - 1; r >= 0; r--)
3432 { lines.push(grid[r].join('')); }
3433 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
3434};
3435
3436var GameCoreAPI = {
3437 GameCore: GameCore,
3438 COLOR_GRAY: COLOR_GRAY,
3439 STATE_STILL: STATE_STILL,
3440 STATE_FALLING: STATE_FALLING,
3441 STATE_FLYING: STATE_FLYING,
3442 STATE_SETTLING: STATE_SETTLING,
3443 STATE_LOCKED: STATE_LOCKED,
3444 STATE_MANUAL: STATE_MANUAL
3445};
3446
3447if (typeof module !== 'undefined' && module.exports)
3448{ module.exports = GameCoreAPI; }
3449else if (typeof globalThis !== 'undefined')
3450{
3451 globalThis.GameCore = GameCore;
3452 globalThis.GameCoreAPI = GameCoreAPI;
3453}
3454
3455/*
3456 * End File:
3457 * /workspace/meteors/src/gameCore.js
3458 */
3459
3460/*
3461 * Start File:
3462 * /workspace/meteors/src/online.js
3463 */
3464'use strict';
3465
3466/**
3467 * Online play: talks to api.php (cookie session), polls lobby and game
3468 * state, and draws opponent miniatures plus flying-block tweens.
3469 * Real-time sync is not required; a 0.75 s poll is enough.
3470 */
3471
3472var Online = {
3473 POLL_MS: 750,
3474 DEFAULT_MISS_CHANCE: 0.30,
3475 FLIGHT_DURATION: 1.2,
3476 configured: false,
3477 local: false,
3478 csrf: '',
3479 me: null,
3480 lobby: null,
3481 incoming: [],
3482 shotResults: [],
3483 error: '',
3484 _timer: null,
3485 _pendingShots: [],
3486 _flights: [],
3487 _lastStatus: null,
3488 onChange: null,
3489 onGameStart: null,
3490 onIncoming: null,
3491 onFinished: null,
3492 onLobbyReturn: null
3493};
3494
3495Online._headers = function (json)
3496{
3497 var h = { 'Accept': 'application/json' };
3498 if (json)
3499 { h['Content-Type'] = 'application/json'; }
3500 if (this.csrf)
3501 { h['X-CSRF-Token'] = this.csrf; }
3502 return h;
3503};
3504
3505Online._apply = function (data)
3506{
3507 if (!data)
3508 { return; }
3509 if (typeof data.configured === 'boolean')
3510 { this.configured = data.configured; }
3511 if (typeof data.local === 'boolean')
3512 { this.local = data.local; }
3513 if (data.csrf)
3514 { this.csrf = data.csrf; }
3515 if (data.me !== undefined)
3516 { this.me = data.me; }
3517 if (data.lobby !== undefined)
3518 { this.lobby = data.lobby; }
3519 if (data.incoming)
3520 { this.incoming = data.incoming; }
3521 if (data.shot_results)
3522 { this.shotResults = data.shot_results; }
3523 if (data.miss_chance_default != null)
3524 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
3525 if (data.flight_duration != null)
3526 { this.FLIGHT_DURATION = data.flight_duration; }
3527 if (data.error)
3528 { this.error = data.error; }
3529 else if (data.ok)
3530 { this.error = ''; }
3531};
3532
3533Online.request = function (action, body)
3534{
3535 var self = this;
3536 var isGet = action === 'me' || action === '';
3537 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
3538 var opts = {
3539 method: isGet && !body ? 'GET' : 'POST',
3540 credentials: 'same-origin',
3541 headers: this._headers(!!body || !isGet)
3542 };
3543 if (opts.method === 'POST')
3544 {
3545 var payload = body ? Object.assign({ action: action }, body) : { action: action };
3546 opts.body = JSON.stringify(payload);
3547 }
3548 return fetch(url, opts).then(function (res)
3549 {
3550 return res.json().then(function (data)
3551 {
3552 data = data || {};
3553 if (!res.ok && !data.error)
3554 { data.error = 'De server gaf ' + res.status; data.ok = false; }
3555 self._apply(data);
3556 return data;
3557 }, function ()
3558 {
3559 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
3560 self.error = fail.error;
3561 return fail;
3562 });
3563 }).catch(function (err)
3564 {
3565 var fail = { ok: false, error: 'Geen verbinding met de server.' };
3566 self.error = fail.error;
3567 return fail;
3568 });
3569};
3570
3571Online.refresh = function ()
3572{
3573 return this.request('me');
3574};
3575
3576Online.testLogin = function (who)
3577{
3578 return this.request('test_login', { user: who });
3579};
3580
3581Online.createLobby = function (planetId)
3582{
3583 return this.request('lobby_create', {
3584 miss_chance: this.DEFAULT_MISS_CHANCE,
3585 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3586 });
3587};
3588
3589Online.joinLobby = function (code, planetId)
3590{
3591 return this.request('lobby_join', {
3592 code: code,
3593 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3594 });
3595};
3596
3597Online.setPlanet = function (planetId)
3598{
3599 return this.request('lobby_set_planet', { planet_id: planetId });
3600};
3601
3602Online.leaveLobby = function ()
3603{
3604 return this.request('lobby_leave');
3605};
3606
3607Online.setReady = function (ready)
3608{
3609 return this.request('lobby_ready', { ready: !!ready });
3610};
3611
3612Online.startGame = function ()
3613{
3614 var self = this;
3615 var prev = this.lobby && this.lobby.status;
3616 return this.request('lobby_start').then(function (data)
3617 {
3618 self._handleTransitions(prev, data);
3619 return data;
3620 });
3621};
3622
3623Online.queueShots = function (shots)
3624{
3625 for (var i = 0; i < shots.length; i++)
3626 {
3627 this._pendingShots.push({
3628 client_id: String(shots[i].id),
3629 color: shots[i].color,
3630 col: shots[i].col,
3631 y: shots[i].y
3632 });
3633 }
3634};
3635
3636Online.poll = function (opts)
3637{
3638 opts = opts || {};
3639 var body = {};
3640 if (opts.snapshot)
3641 { body.snapshot = opts.snapshot; }
3642 if (opts.score != null)
3643 { body.score = opts.score; }
3644 if (opts.eliminated)
3645 { body.eliminated = true; }
3646 if (this._pendingShots.length)
3647 {
3648 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
3649 }
3650 var self = this;
3651 var prevStatus = this.lobby && this.lobby.status;
3652 return this.request('poll', body).then(function (data)
3653 {
3654 self._handleTransitions(prevStatus, data);
3655 if (self.onChange)
3656 { self.onChange(self); }
3657 return data;
3658 });
3659};
3660
3661Online._handleTransitions = function (prevStatus, data)
3662{
3663 var lobby = this.lobby;
3664 var status = lobby && lobby.status;
3665 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
3666 { this.onGameStart(lobby); }
3667 if (data && data.incoming && data.incoming.length && this.onIncoming)
3668 { this.onIncoming(data.incoming); }
3669 if (data && data.shot_results && data.shot_results.length)
3670 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
3671 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
3672 { this.onFinished(lobby); }
3673 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
3674 { this.onLobbyReturn(lobby); }
3675};
3676
3677Online.startPolling = function (getPayload)
3678{
3679 this.stopPolling();
3680 var self = this;
3681 var tick = function ()
3682 {
3683 var payload = getPayload ? getPayload() : {};
3684 self.poll(payload);
3685 };
3686 tick();
3687 this._timer = setInterval(tick, this.POLL_MS);
3688};
3689
3690Online.stopPolling = function ()
3691{
3692 if (this._timer)
3693 {
3694 clearInterval(this._timer);
3695 this._timer = null;
3696 }
3697};
3698
3699Online.loginUrl = function ()
3700{
3701 return 'auth.php';
3702};
3703
3704Online.logoutUrl = function ()
3705{
3706 return 'logout.php';
3707};
3708
3709Online.opponents = function ()
3710{
3711 if (!this.lobby || !this.lobby.players)
3712 { return []; }
3713 return this.lobby.players.filter(function (p) { return !p.is_me; });
3714};
3715
3716Online.aliveOpponents = function ()
3717{
3718 return this.opponents().filter(function (p) { return !p.eliminated; });
3719};
3720
3721Online.mePlayer = function ()
3722{
3723 if (!this.lobby || !this.lobby.players)
3724 { return null; }
3725 for (var i = 0; i < this.lobby.players.length; i++)
3726 {
3727 if (this.lobby.players[i].is_me)
3728 { return this.lobby.players[i]; }
3729 }
3730 return null;
3731};
3732
3733/* ---------- miniatures --------------------------------------------- */
3734
3735Online.renderMinis = function (container)
3736{
3737 if (!container)
3738 { return; }
3739 var opponents = this.opponents();
3740 var existing = {};
3741 var kids = container.querySelectorAll('[data-player]');
3742 for (var i = 0; i < kids.length; i++)
3743 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
3744
3745 var seen = Object.create(null);
3746 for (var i = 0; i < opponents.length; i++)
3747 {
3748 var p = opponents[i];
3749 seen[p.id] = true;
3750 var el = existing[p.id];
3751 if (!el)
3752 {
3753 el = document.createElement('div');
3754 el.className = 'mini';
3755 el.setAttribute('data-player', p.id);
3756 el.innerHTML = '<div class="mini-name"></div>'
3757 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
3758 + '<div class="mini-meta"></div>';
3759 container.appendChild(el);
3760 }
3761 el.classList.toggle('eliminated', !!p.eliminated);
3762 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
3763 el.querySelector('.mini-meta').textContent = p.eliminated
3764 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
3765 : ('Punten ' + (p.score || 0));
3766 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
3767 }
3768 for (var id in existing)
3769 {
3770 if (!seen[id])
3771 { existing[id].remove(); }
3772 }
3773};
3774
3775var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
3776
3777function miniColor (planet, color)
3778{
3779 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
3780 { return planet.colors[color].hex; }
3781 return MINI_COLORS[color] || '#888';
3782}
3783
3784
3785Online._drawMini = function (canvas, snapshot, planet)
3786{
3787 if (!canvas)
3788 { return; }
3789 var ctx = canvas.getContext('2d');
3790 var w = 10;
3791 var h = 13;
3792 var tw = canvas.width / w;
3793 var th = canvas.height / h;
3794 ctx.fillStyle = '#0c1020';
3795 ctx.fillRect(0, 0, canvas.width, canvas.height);
3796 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
3797 ctx.lineWidth = 1;
3798 for (var c = 0; c <= w; c++)
3799 {
3800 ctx.beginPath();
3801 ctx.moveTo(c * tw + 0.5, 0);
3802 ctx.lineTo(c * tw + 0.5, canvas.height);
3803 ctx.stroke();
3804 }
3805 for (var r = 0; r <= h; r++)
3806 {
3807 ctx.beginPath();
3808 ctx.moveTo(0, r * th + 0.5);
3809 ctx.lineTo(canvas.width, r * th + 0.5);
3810 ctx.stroke();
3811 }
3812 if (!snapshot || !snapshot.blocks)
3813 { return; }
3814 var blocks = snapshot.blocks;
3815 for (var i = 0; i < blocks.length; i++)
3816 {
3817 var b = blocks[i];
3818 var x = b.col * tw;
3819 var y = canvas.height - (b.y + 1) * th;
3820 if (b.state === 'locked')
3821 { ctx.fillStyle = '#3a3d4a'; }
3822 else if (b.color < 0)
3823 { ctx.fillStyle = '#5a5d66'; }
3824 else
3825 { ctx.fillStyle = miniColor(planet, b.color); }
3826 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
3827 }
3828};
3829
3830Online.miniElement = function (playerId)
3831{
3832 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
3833};
3834
3835/* ---------- flight tweens ------------------------------------------ */
3836
3837function colorSpriteUrl (color, planetId)
3838{
3839 if (color < 0)
3840 { return 'images/block-gray.png'; }
3841 var planet = null;
3842 if (typeof Planet !== 'undefined')
3843 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
3844 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
3845 { return planet.colors[color].image; }
3846 return 'images/block-gray.png';
3847}
3848
3849/**
3850 * Animate shot results. `locals` is a map of client_id → {col, y, color,
3851 * startX, startY} in viewport pixels, filled by the view just after
3852 * consumeOutgoingShots.
3853 */
3854Online.spawnFlights = function (results, locals)
3855{
3856 locals = locals || this._flightLocals || {};
3857 var layer = document.getElementById('flights');
3858 if (!layer)
3859 { return; }
3860 for (var i = 0; i < results.length; i++)
3861 {
3862 var r = results[i];
3863 var meta = locals[r.client_id] || {};
3864 var start = this._flightStart(meta.col);
3865 var end;
3866 var miss = !!r.miss;
3867 if (miss)
3868 { end = this._missEnd(start); }
3869 else
3870 { end = this._targetEnd(r.target_id, start); }
3871 var el = document.createElement('img');
3872 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
3873 el.alt = '';
3874 el.className = 'flight';
3875 layer.appendChild(el);
3876 var spin = (Math.random() * 2 - 1) * 720;
3877 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
3878 this._flights.push({
3879 el: el,
3880 start: start,
3881 end: end,
3882 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
3883 t0: performance.now(),
3884 duration: duration,
3885 spin: spin,
3886 miss: miss,
3887 angle: Math.random() * 360
3888 });
3889 }
3890 this._flightLocals = {};
3891};
3892
3893Online.rememberFlightLocal = function (shot, startX, startY)
3894{
3895 if (!this._flightLocals)
3896 { this._flightLocals = {}; }
3897 this._flightLocals[String(shot.id)] = {
3898 col: shot.col,
3899 y: shot.y,
3900 color: shot.color,
3901 startX: startX,
3902 startY: startY
3903 };
3904};
3905
3906Online._flightStart = function (col)
3907{
3908 var field = document.querySelector('canvas');
3909 var appRef = typeof app !== 'undefined' ? app : null;
3910 if (appRef && appRef.scene && appRef.scene.canvas)
3911 {
3912 var canvas = appRef.scene.canvas;
3913 var rect = canvas.getBoundingClientRect();
3914 var c = col == null ? 4.5 : col;
3915 return {
3916 x: rect.left + (c + 0.5) * (rect.width / 10),
3917 y: rect.top + 4
3918 };
3919 }
3920 if (field)
3921 {
3922 var rect = field.getBoundingClientRect();
3923 return { x: rect.left + rect.width / 2, y: rect.top };
3924 }
3925 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
3926};
3927
3928Online._targetEnd = function (targetId, start)
3929{
3930 var el = targetId && this.miniElement(targetId);
3931 if (el)
3932 {
3933 var r = el.getBoundingClientRect();
3934 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
3935 }
3936 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
3937};
3938
3939Online._missEnd = function (start)
3940{
3941 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
3942 return {
3943 x: start.x + dx,
3944 y: start.y - (120 + Math.random() * 220)
3945 };
3946};
3947
3948Online._missCtrl = function (start, end)
3949{
3950 return {
3951 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
3952 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
3953 };
3954};
3955
3956Online._hitCtrl = function (start, end)
3957{
3958 return {
3959 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
3960 y: (start.y + end.y) / 2 - 30
3961 };
3962};
3963
3964Online.tickFlights = function (now)
3965{
3966 now = now || performance.now();
3967 var leftover = [];
3968 for (var i = 0; i < this._flights.length; i++)
3969 {
3970 var f = this._flights[i];
3971 var u = (now - f.t0) / f.duration;
3972 if (u >= 1)
3973 {
3974 if (f.el && f.el.parentNode)
3975 { f.el.parentNode.removeChild(f.el); }
3976 continue;
3977 }
3978 // Quadratic bezier, ease-in so they feel like they recede.
3979 var e = u * u;
3980 var mt = 1 - e;
3981 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
3982 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
3983 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
3984 var angle = f.angle + f.spin * u;
3985 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
3986 + angle + 'deg) scale(' + scale + ')';
3987 f.el.style.opacity = f.miss ? String(1 - e) : '1';
3988 leftover.push(f);
3989 }
3990 this._flights = leftover;
3991};
3992
3993Online.clearFlights = function ()
3994{
3995 for (var i = 0; i < this._flights.length; i++)
3996 {
3997 var el = this._flights[i].el;
3998 if (el && el.parentNode)
3999 { el.parentNode.removeChild(el); }
4000 }
4001 this._flights = [];
4002 this._flightLocals = {};
4003};
4004
4005if (typeof globalThis !== 'undefined')
4006{ globalThis.Online = Online; }
4007if (typeof module !== 'undefined' && module.exports)
4008{ module.exports = Online; }
4009
4010/*
4011 * End File:
4012 * /workspace/meteors/src/online.js
4013 */
4014
4015/*
4016 * Start File:
4017 * /workspace/meteors/src/main.js
4018 */
4019'use strict';
4020
4021/**
4022 * View and input for Meteors. The simulation lives in GameCore; this file
4023 * only draws it, scales it to the viewport, and translates pointer events
4024 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4025 * through Online (src/online.js) and the same GameCore.
4026 */
4027
4028function planetImages ()
4029{
4030 var list = [
4031 { name: 'gray', url: 'images/block-gray.png' },
4032 { name: 'locked', url: 'images/block-locked.png' },
4033 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4034 { name: 'cell', url: 'images/cell.png' },
4035 { name: 'pixel', url: 'images/pixel.png' },
4036 // Keep the original Terra placeholders as aliases (Tim may still have them).
4037 { name: 'ember', url: 'images/block-ember.png' },
4038 { name: 'aqua', url: 'images/block-aqua.png' },
4039 { name: 'leaf', url: 'images/block-leaf.png' },
4040 { name: 'sun', url: 'images/block-sun.png' },
4041 { name: 'orchid', url: 'images/block-orchid.png' }
4042 ];
4043 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4044 for (var i = 0; i < planets.length; i++)
4045 {
4046 var pl = planets[i];
4047 for (var c = 0; c < pl.colors.length; c++)
4048 {
4049 list.push({
4050 name: Planet.spriteKey(pl, c),
4051 url: pl.colors[c].image
4052 });
4053 }
4054 }
4055 return list;
4056}
4057
4058var IMAGES = planetImages();
4059var GAME_OVER_DELAY = 2;
4060
4061var game = new Game();
4062var app = {
4063 mode: 'menu',
4064 core: null,
4065 scene: null,
4066 manager: null,
4067 planet: null,
4068 lastScore: 0,
4069 tile: 48,
4070 fieldX: 0,
4071 fieldY: 0,
4072 fieldW: 0,
4073 fieldH: 0,
4074 hudH: 56,
4075 sprites: Object.create(null),
4076 flames: Object.create(null),
4077 cells: [],
4078 pointerId: null,
4079 pointerType: null,
4080 activeTouchId: null,
4081 debugDrag: false,
4082 debugPhysics: false,
4083 gameOverShown: false,
4084 selectTween: null,
4085 online: false,
4086 eliminatedReported: false,
4087 spectating: false,
4088 miniH: 0,
4089 selectedPlanetId: 'terra',
4090 planetSelectContext: 'solo'
4091};
4092
4093window.onload = function ()
4094{
4095 app.debugDrag = isDragDebugEnabled();
4096 app.debugPhysics = isPhysicsDebugEnabled();
4097 var play = document.getElementById('btn-play');
4098 play.addEventListener('click', onPlay);
4099 play.addEventListener('pointerup', function (e)
4100 {
4101 // A touch-friendly path: some mobile browsers swallow the click
4102 // after a slightly sloppy tap. Ignore the following click.
4103 if (e.pointerType === 'touch' || e.pointerType === 'pen')
4104 {
4105 e.preventDefault();
4106 onPlay();
4107 }
4108 });
4109
4110 game.preloadImagesThenStart(IMAGES, function ()
4111 {
4112 if (game.images.flame && game.images.flame.addAnimationCycle)
4113 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
4114 });
4115
4116 bindOnlineUi();
4117 bindPlanetSelect();
4118 restoreSelectedPlanet();
4119};
4120
4121function onPlay ()
4122{
4123 if (app.mode === 'playing')
4124 { return; }
4125 openPlanetSelect('solo');
4126}
4127
4128function startPlay (opts)
4129{
4130 opts = opts || {};
4131 hideEl('menu');
4132 hideEl('game-over');
4133 hideEl('online-panel');
4134 hideEl('spectator');
4135 hideEl('podium');
4136 hideEl('planet-select');
4137 showEl('hud');
4138
4139 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
4140 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
4141 var miss = opts.missChance;
4142 if (typeof miss !== 'number' || !isFinite(miss))
4143 { miss = planetMod.missChance(app.planet); }
4144 app.core = new GameCore(app.planet, Math.random, miss);
4145 if (app.debugPhysics)
4146 { app.core.debugInvariants = true; }
4147 app.mode = 'playing';
4148 app.online = !!opts.online;
4149 app.gameOverShown = false;
4150 app.eliminatedReported = false;
4151 app.spectating = false;
4152 app.sprites = Object.create(null);
4153 app.flames = Object.create(null);
4154 app.cells = [];
4155 app.pointerId = null;
4156 app.selectTween = null;
4157
4158 layout();
4159 if (app.scene)
4160 {
4161 app.scene.destroy();
4162 app.scene = null;
4163 }
4164 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
4165 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
4166 app.scene.renderBackground = true;
4167 game.loadScene(app.scene);
4168
4169 buildCells();
4170 app.manager = app.scene.addObject(makeManager());
4171 if (!app.spectating)
4172 { bindPointer(app.scene.canvas); }
4173 refreshHud();
4174 if (app.online)
4175 { showEl('minis'); }
4176 else
4177 { hideEl('minis'); }
4178}
4179
4180function teardownPlay ()
4181{
4182 unbindPointer();
4183 if (app.scene)
4184 {
4185 app.scene.destroy();
4186 app.scene = null;
4187 }
4188 app.manager = null;
4189 app.core = null;
4190 app.sprites = Object.create(null);
4191 app.flames = Object.create(null);
4192 app.cells = [];
4193 app.selectTween = null;
4194 app.pointerId = null;
4195 app.gameOverShown = false;
4196 hideEl('hud');
4197 hideEl('game-over');
4198 hideEl('spectator');
4199 hideEl('minis');
4200 if (typeof Online !== 'undefined')
4201 { Online.clearFlights(); }
4202}
4203
4204function returnToMenu ()
4205{
4206 if (app.online && typeof Online !== 'undefined')
4207 {
4208 // Online matches do not dump you back to the solo menu:
4209 // elimination becomes spectating; a finished match shows the podium.
4210 return;
4211 }
4212 teardownPlay();
4213 app.mode = 'menu';
4214 app.online = false;
4215 hideEl('planet-select');
4216 showEl('menu');
4217 var last = document.getElementById('last-score');
4218 if (app.lastScore > 0)
4219 {
4220 last.hidden = false;
4221 last.querySelector('strong').textContent = String(app.lastScore);
4222 }
4223}
4224
4225function buildCells ()
4226{
4227 if (!app.scene)
4228 { return; }
4229 var img = game.images.cell;
4230 for (var row = 0; row < 13; row++)
4231 {
4232 for (var col = 0; col < 10; col++)
4233 {
4234 var obj = new GameObject(0, 0, img, 0);
4235 placeTile(obj, col, row);
4236 obj.renderer.alpha = 0.9;
4237 app.scene.addObject(obj);
4238 app.cells.push(obj);
4239 }
4240 }
4241}
4242
4243function placeTile (obj, col, y)
4244{
4245 var t = app.tile;
4246 obj.transform.position.x = col * t + t / 2;
4247 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
4248 obj.transform.size = { x: t, y: t };
4249}
4250
4251function layoutIfNeeded ()
4252{
4253 if (app.core && app.core.drag)
4254 { return; }
4255 var vw = window.innerWidth || 320;
4256 var vh = window.innerHeight || 480;
4257 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
4258 { return; }
4259 layout();
4260}
4261
4262function layout ()
4263{
4264 if (app.core && app.core.drag)
4265 { return; }
4266 var vw = window.innerWidth || 320;
4267 var vh = window.innerHeight || 480;
4268 app._layoutVw = vw;
4269 app._layoutVh = vh;
4270 var safeTop = 0;
4271 try
4272 {
4273 // env(safe-area) is a CSS thing; keep a conservative HUD height.
4274 safeTop = 0;
4275 }
4276 catch (e) { /* ignore */ }
4277 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
4278 app.miniH = 0;
4279 if (app.online)
4280 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
4281 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
4282 var availW = Math.max(80, vw - margin * 2);
4283 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
4284 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
4285 app.fieldW = app.tile * 10;
4286 app.fieldH = app.tile * 13;
4287 app.fieldX = Math.floor((vw - app.fieldW) / 2);
4288 var topBand = app.hudH + app.miniH;
4289 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
4290 if (app.fieldY < topBand)
4291 { app.fieldY = topBand; }
4292 var minis = document.getElementById('minis');
4293 if (minis)
4294 {
4295 minis.style.top = app.hudH + 'px';
4296 minis.style.maxHeight = app.miniH + 'px';
4297 }
4298
4299 if (app.scene)
4300 {
4301 app.scene.position.x = app.fieldX;
4302 app.scene.position.y = app.fieldY;
4303 app.scene.size.x = app.fieldW;
4304 app.scene.size.y = app.fieldH;
4305 }
4306}
4307
4308function spriteFor (block)
4309{
4310 if (block.state === 'locked')
4311 { return game.images.locked; }
4312 if (block.color < 0)
4313 { return game.images.gray; }
4314 var key = Planet.spriteKey(app.planet, block.color);
4315 return game.images[key] || game.images.gray;
4316}
4317
4318function syncSprites ()
4319{
4320 if (!app.core || !app.scene)
4321 { return; }
4322 var seen = Object.create(null);
4323 var blocks = app.core.blocks;
4324 for (var i = 0; i < blocks.length; i++)
4325 {
4326 var block = blocks[i];
4327 seen[block.id] = true;
4328 var obj = app.sprites[block.id];
4329 if (!obj)
4330 {
4331 obj = new GameObject(0, 0, spriteFor(block), 2);
4332 app.scene.addObject(obj);
4333 app.sprites[block.id] = obj;
4334 }
4335 obj.renderer.sprite = spriteFor(block);
4336 placeTile(obj, block.col, block.y);
4337 applyBlockVisual(obj, block);
4338 obj.renderer.visible = true;
4339 obj.renderer.alpha = 1;
4340
4341 if (block.flame)
4342 {
4343 var flame = app.flames[block.id];
4344 if (!flame)
4345 {
4346 flame = new GameObject(0, 0, game.images.flame, 1);
4347 flame.renderer.setAnimation('burn', 0, 0.08);
4348 app.scene.addObject(flame);
4349 app.flames[block.id] = flame;
4350 }
4351 flame.renderer.visible = true;
4352 var t = app.tile;
4353 // 3x as large (length and width, t1110). Keep the top of the
4354 // flame at the same overlap into the block so the extra length
4355 // extends downward under the rocket.
4356 var flameW = t * 0.85 * 3;
4357 var flameH = t * 0.85 * 3;
4358 var origCenter = app.fieldH - block.y * t + t * 0.15;
4359 var origTop = origCenter - (t * 0.85) / 2;
4360 flame.transform.position.x = block.col * t + t / 2;
4361 flame.transform.position.y = origTop + flameH / 2;
4362 flame.transform.size = { x: flameW, y: flameH };
4363 }
4364 else if (app.flames[block.id])
4365 { app.flames[block.id].renderer.visible = false; }
4366 }
4367
4368 var ids = Object.keys(app.sprites);
4369 for (var i = 0; i < ids.length; i++)
4370 {
4371 if (!seen[ids[i]])
4372 {
4373 app.sprites[ids[i]].destroy();
4374 delete app.sprites[ids[i]];
4375 if (app.flames[ids[i]])
4376 {
4377 app.flames[ids[i]].destroy();
4378 delete app.flames[ids[i]];
4379 }
4380 }
4381 }
4382}
4383
4384function applyBlockVisual (obj, block)
4385{
4386 var t = app.tile;
4387 var sx = 1;
4388 var sy = 1;
4389 var dy = 0;
4390 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
4391 && typeof Easing !== 'undefined' && Easing.bouncePose)
4392 {
4393 var u = block.bounceAge / app.planet.bounceDuration;
4394 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
4395 sx = pose.sx;
4396 sy = pose.sy;
4397 dy = pose.dy;
4398 }
4399 var sel = 1;
4400 var tw = app.selectTween;
4401 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
4402 { sel = tw.scale; }
4403 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
4404 if (dy)
4405 { obj.transform.position.y -= dy * t; }
4406}
4407
4408function clickTween ()
4409{
4410 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
4411}
4412
4413function startPressTween (blockId)
4414{
4415 var c = clickTween();
4416 if (!c)
4417 { return; }
4418 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
4419 app.selectTween = {
4420 blockId: blockId,
4421 from: from,
4422 to: c.pressScale,
4423 t: 0,
4424 duration: c.pressDuration,
4425 ease: c.pressEase,
4426 scale: from,
4427 phase: 'press'
4428 };
4429}
4430
4431function startReleaseTween ()
4432{
4433 var c = clickTween();
4434 var tw = app.selectTween;
4435 if (!c || !tw || tw.phase === 'idle')
4436 { return; }
4437 app.selectTween = {
4438 blockId: tw.blockId,
4439 from: tw.scale,
4440 to: c.releaseScale,
4441 t: 0,
4442 duration: c.releaseDuration,
4443 ease: c.releaseEase,
4444 scale: tw.scale,
4445 phase: 'release'
4446 };
4447}
4448
4449function updateSelectTween (dt)
4450{
4451 var tw = app.selectTween;
4452 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
4453 { return; }
4454 tw.t += dt;
4455 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
4456 if (u >= 1)
4457 {
4458 tw.scale = tw.to;
4459 tw.t = tw.duration;
4460 if (tw.phase === 'press')
4461 { tw.phase = 'hold'; }
4462 else
4463 {
4464 tw.phase = 'idle';
4465 tw.scale = 1;
4466 tw.blockId = null;
4467 }
4468 return;
4469 }
4470 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
4471 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
4472}
4473
4474function refreshHud ()
4475{
4476 if (!app.core)
4477 { return; }
4478 document.getElementById('score').textContent = String(app.core.score);
4479 var planet = app.planet;
4480 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
4481 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
4482}
4483
4484function makeManager ()
4485{
4486 var obj = new GameObject(0, 0, game.images.pixel, 0);
4487 obj.renderer.visible = false;
4488 var base = obj.update.bind(obj);
4489 obj.update = function (dt)
4490 {
4491 base(dt);
4492 tickView(dt);
4493 };
4494 return obj;
4495}
4496
4497function tickView (dt)
4498{
4499 if (app.mode !== 'playing' || !app.core)
4500 { return; }
4501
4502 // Never resize the canvas mid-drag: a URL-bar hide would move the
4503 // field under the finger and jump the target row. Also skip work
4504 // when the viewport has not actually changed.
4505 if (!(app.core && app.core.drag))
4506 { layoutIfNeeded(); }
4507 for (var i = 0; i < app.cells.length; i++)
4508 {
4509 var col = i % 10;
4510 var row = Math.floor(i / 10);
4511 placeTile(app.cells[i], col, row);
4512 }
4513
4514 app.core.tick(dt);
4515 updateSelectTween(dt);
4516 syncSprites();
4517 refreshHud();
4518 tickOnline(dt);
4519 if (app.debugPhysics)
4520 { logPhysicsDebug(); }
4521
4522 if (app.core.state === 'gameover' && !app.gameOverShown)
4523 {
4524 app.gameOverShown = true;
4525 app.lastScore = app.core.score;
4526 document.getElementById('go-score').textContent = String(app.lastScore);
4527 if (app.online)
4528 { onOnlineEliminated(); }
4529 else
4530 { showEl('game-over'); }
4531 }
4532 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
4533 { returnToMenu(); }
4534}
4535
4536/* ---------- pointer input (mouse + touch) --------------------------- */
4537/*
4538 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
4539 * on a real phone, pointer clientX/Y can disagree with the visual
4540 * finger (zoomed visual viewport, gesture takeover, capture cancel)
4541 * while changedTouches stays correct. When a touch is active, pointer
4542 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
4543 * walk the block to the top or bottom of the stack (t1106).
4544 *
4545 * After a down we also listen on the document, so a drag that leaves
4546 * the canvas (needed to launch a block at the top of a full column)
4547 * still reaches moveDrag. We do not call setPointerCapture: on mobile
4548 * that is often cancelled when the browser takes the gesture, which
4549 * would fire pointercancel mid-drag.
4550 *
4551 * A non-passive document touchstart/touchmove preventDefault during
4552 * play stops scrolling, rubber-banding and the pointercancel that
4553 * follows. pointercancel / touchcancel end the drag without launch.
4554 *
4555 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
4556 */
4557
4558var boundCanvas = null;
4559var windowListening = false;
4560var touchListening = false;
4561var lastDragDebug = null;
4562
4563function isDragDebugEnabled ()
4564{
4565 try
4566 {
4567 var q = window.location && window.location.search;
4568 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
4569 { return true; }
4570 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
4571 { return true; }
4572 }
4573 catch (err) { /* ignore */ }
4574 return false;
4575}
4576
4577/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
4578function isPhysicsDebugEnabled ()
4579{
4580 try
4581 {
4582 var q = window.location && window.location.search;
4583 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
4584 { return true; }
4585 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
4586 || window.localStorage.getItem('meteors-debug-drag') === '1'))
4587 { return true; }
4588 }
4589 catch (err) { /* ignore */ }
4590 return false;
4591}
4592
4593function eventClient (e)
4594{
4595 var t = null;
4596 if (e.changedTouches && e.changedTouches.length)
4597 { t = e.changedTouches[0]; }
4598 else if (e.touches && e.touches.length)
4599 { t = e.touches[0]; }
4600 if (t)
4601 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
4602 if (e.clientX != null && e.clientY != null)
4603 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
4604 return null;
4605}
4606
4607function addWindowPointer ()
4608{
4609 if (windowListening)
4610 { return; }
4611 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
4612 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
4613 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
4614 windowListening = true;
4615}
4616
4617function removeWindowPointer ()
4618{
4619 if (!windowListening)
4620 { return; }
4621 window.removeEventListener('pointermove', onPointerMove, { capture: true });
4622 window.removeEventListener('pointerup', onPointerUp, { capture: true });
4623 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
4624 windowListening = false;
4625}
4626
4627function addTouchListeners ()
4628{
4629 if (touchListening)
4630 { return; }
4631 var opts = { capture: true, passive: false };
4632 document.addEventListener('touchstart', onTouchStart, opts);
4633 document.addEventListener('touchmove', onTouchMove, opts);
4634 document.addEventListener('touchend', onTouchEnd, opts);
4635 document.addEventListener('touchcancel', onTouchCancel, opts);
4636 touchListening = true;
4637}
4638
4639function removeTouchListeners ()
4640{
4641 if (!touchListening)
4642 { return; }
4643 var opts = { capture: true };
4644 document.removeEventListener('touchstart', onTouchStart, opts);
4645 document.removeEventListener('touchmove', onTouchMove, opts);
4646 document.removeEventListener('touchend', onTouchEnd, opts);
4647 document.removeEventListener('touchcancel', onTouchCancel, opts);
4648 touchListening = false;
4649}
4650
4651function bindPointer (canvas)
4652{
4653 unbindPointer();
4654 boundCanvas = canvas;
4655 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
4656 canvas.style.touchAction = 'none';
4657 canvas.style.position = 'fixed';
4658 canvas.style.cursor = 'pointer';
4659 canvas.style.webkitUserSelect = 'none';
4660 canvas.style.userSelect = 'none';
4661 addTouchListeners();
4662 if (app.debugDrag)
4663 { ensureDragDebugOverlay(); }
4664}
4665
4666function unbindPointer ()
4667{
4668 removeWindowPointer();
4669 removeTouchListeners();
4670 if (boundCanvas)
4671 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
4672 boundCanvas = null;
4673 app.pointerId = null;
4674 app.pointerType = null;
4675 app.activeTouchId = null;
4676}
4677
4678function fieldFromEvent (e)
4679{
4680 var canvas = app.scene && app.scene.canvas;
4681 if (!canvas)
4682 { return null; }
4683 var rect = canvas.getBoundingClientRect();
4684 if (rect.width <= 0 || rect.height <= 0)
4685 { return null; }
4686 var pt = eventClient(e);
4687 if (!pt)
4688 { return null; }
4689 // Map through the CSS box only. Using canvas.width / app.tile would
4690 // scale the pointer by the backing-store ratio whenever that differs
4691 // from the layout size (high-DPR devices), so a short finger move
4692 // would look like a long swipe.
4693 var width = Planet.FIELD_WIDTH;
4694 var height = Planet.FIELD_HEIGHT;
4695 var col = ((pt.x - rect.left) / rect.width) * width;
4696 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
4697 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
4698}
4699
4700function playingForDrag ()
4701{
4702 return app.core && app.core.state === 'playing';
4703}
4704
4705function startDragFromEvent (e)
4706{
4707 var pos = fieldFromEvent(e);
4708 if (!pos)
4709 { return; }
4710 if (app.core.drag)
4711 {
4712 app.core.moveDrag(pos.y);
4713 logDragDebug(e, pos, 'move-already');
4714 return;
4715 }
4716 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
4717 { startPressTween(app.core.drag.blockId); }
4718 logDragDebug(e, pos, 'down');
4719}
4720
4721function moveDragFromEvent (e)
4722{
4723 if (!app.core || !app.core.drag)
4724 { return; }
4725 var pos = fieldFromEvent(e);
4726 if (pos)
4727 { app.core.moveDrag(pos.y); }
4728 logDragDebug(e, pos, 'move');
4729}
4730
4731function finishDrag (opts)
4732{
4733 opts = opts || {};
4734 app.pointerId = null;
4735 app.pointerType = null;
4736 app.activeTouchId = null;
4737 removeWindowPointer();
4738 if (boundCanvas)
4739 {
4740 try
4741 {
4742 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
4743 { boundCanvas.releasePointerCapture(opts.pointerId); }
4744 }
4745 catch (err) { /* ignore */ }
4746 }
4747 startReleaseTween();
4748 if (app.core && app.core.drag)
4749 {
4750 if (opts.noLaunch)
4751 { app.core.drag.launchIntent = false; }
4752 app.core.endDrag();
4753 }
4754 else if (app.core)
4755 { app.core.endDrag(); }
4756 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
4757}
4758
4759function onPointerDown (e)
4760{
4761 if (!playingForDrag())
4762 { return; }
4763 if (app.pointerId != null && e.pointerId !== app.pointerId)
4764 { return; }
4765 if (e.preventDefault)
4766 { e.preventDefault(); }
4767 app.pointerId = e.pointerId;
4768 app.pointerType = e.pointerType || 'mouse';
4769 addWindowPointer();
4770 // If a touch is already in charge, do not reset the grab from pointerdown.
4771 if (app.activeTouchId != null)
4772 { return; }
4773 startDragFromEvent(e);
4774}
4775
4776function onPointerMove (e)
4777{
4778 if (app.pointerId == null || e.pointerId !== app.pointerId)
4779 { return; }
4780 if (!app.core || !app.core.drag)
4781 { return; }
4782 // Touch coordinates are the authority; ignore pointer moves for a
4783 // live touch so a wrong clientY cannot walk the whole column.
4784 // Only skip when touchstart has actually arrived — some environments
4785 // deliver touch-pointer events without a TouchEvent stream.
4786 if (app.activeTouchId != null)
4787 {
4788 if (e.preventDefault)
4789 { e.preventDefault(); }
4790 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
4791 return;
4792 }
4793 if (e.preventDefault)
4794 { e.preventDefault(); }
4795 moveDragFromEvent(e);
4796}
4797
4798function onPointerUp (e)
4799{
4800 if (app.pointerId == null)
4801 { return; }
4802 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4803 { return; }
4804 if (app.activeTouchId != null)
4805 {
4806 // touchend will finish the drag.
4807 if (e && e.preventDefault)
4808 { e.preventDefault(); }
4809 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
4810 return;
4811 }
4812 if (e && e.preventDefault)
4813 { e.preventDefault(); }
4814 finishDrag({ pointerId: e && e.pointerId });
4815}
4816
4817function onPointerCancel (e)
4818{
4819 if (app.pointerId == null)
4820 { return; }
4821 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4822 { return; }
4823 if (app.activeTouchId != null)
4824 {
4825 if (e && e.preventDefault)
4826 { e.preventDefault(); }
4827 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
4828 return;
4829 }
4830 if (e && e.preventDefault)
4831 { e.preventDefault(); }
4832 // A cancelled gesture is not a launch pull.
4833 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
4834}
4835
4836function touchById (list, id)
4837{
4838 if (!list)
4839 { return null; }
4840 for (var i = 0; i < list.length; i++)
4841 {
4842 if (list[i].identifier === id)
4843 { return list[i]; }
4844 }
4845 return null;
4846}
4847
4848function onTouchStart (e)
4849{
4850 if (!playingForDrag())
4851 { return; }
4852 if (app.activeTouchId != null)
4853 {
4854 if (e.preventDefault)
4855 { e.preventDefault(); }
4856 return;
4857 }
4858 var t = e.changedTouches && e.changedTouches[0];
4859 if (!t)
4860 { return; }
4861 if (e.preventDefault)
4862 { e.preventDefault(); }
4863 app.activeTouchId = t.identifier;
4864 addWindowPointer();
4865 startDragFromEvent(e);
4866}
4867
4868function onTouchMove (e)
4869{
4870 if (app.activeTouchId == null)
4871 { return; }
4872 if (!touchById(e.changedTouches, app.activeTouchId)
4873 && !touchById(e.touches, app.activeTouchId))
4874 { return; }
4875 if (e.preventDefault)
4876 { e.preventDefault(); }
4877 moveDragFromEvent(e);
4878}
4879
4880function onTouchEnd (e)
4881{
4882 if (app.activeTouchId == null)
4883 { return; }
4884 if (!touchById(e.changedTouches, app.activeTouchId))
4885 { return; }
4886 if (e.preventDefault)
4887 { e.preventDefault(); }
4888 finishDrag({});
4889}
4890
4891function onTouchCancel (e)
4892{
4893 if (app.activeTouchId == null)
4894 { return; }
4895 if (!touchById(e.changedTouches, app.activeTouchId))
4896 { return; }
4897 if (e.preventDefault)
4898 { e.preventDefault(); }
4899 finishDrag({ noLaunch: true });
4900}
4901
4902function logPhysicsDebug ()
4903{
4904 if (!app.debugPhysics || !app.core)
4905 { return; }
4906 ensureDragDebugOverlay();
4907 var el = document.getElementById('drag-debug');
4908 if (!el)
4909 { return; }
4910 var issues = app.core.lastInvariantViolations || [];
4911 var flying = 0;
4912 var manuals = 0;
4913 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
4914 for (var i = 0; i < app.core.blocks.length; i++)
4915 {
4916 if (app.core.blocks[i].state === 'flying')
4917 { flying++; }
4918 if (app.core.blocks[i].state === 'manual')
4919 { manuals++; }
4920 }
4921 var status = issues.length
4922 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
4923 : ('physics ok blocks=' + app.core.blocks.length
4924 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
4925 // Keep any live drag line above the physics status.
4926 var dragLine = '';
4927 if (app.debugDrag && lastDragDebug)
4928 {
4929 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
4930 ? el.textContent.split('\n')[0] + '\n'
4931 : '';
4932 }
4933 el.textContent = dragLine + status;
4934 el.hidden = false;
4935 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
4936}
4937
4938function ensureDragDebugOverlay ()
4939{
4940 if (document.getElementById('drag-debug'))
4941 { return; }
4942 var el = document.createElement('div');
4943 el.id = 'drag-debug';
4944 el.setAttribute('aria-live', 'polite');
4945 document.body.appendChild(el);
4946}
4947
4948function logDragDebug (e, pos, phase)
4949{
4950 if (!app.debugDrag)
4951 { return; }
4952 ensureDragDebugOverlay();
4953 var el = document.getElementById('drag-debug');
4954 if (!el)
4955 { return; }
4956 var block = null;
4957 if (app.core && app.core.drag)
4958 { block = app.core.blockById(app.core.drag.blockId); }
4959 var pt = e ? eventClient(e) : null;
4960 var evType = e ? e.type : phase;
4961 var info = {
4962 phase: phase,
4963 ev: evType,
4964 src: pos && pos.src,
4965 fieldY: pos && Math.round(pos.y * 100) / 100,
4966 col: pos && Math.round(pos.col * 100) / 100,
4967 cy: pt && Math.round(pt.y * 10) / 10,
4968 blockY: block && Math.round(block.y * 100) / 100,
4969 target: block && Math.floor((pos && pos.y) + 1e-12),
4970 launch: app.core && app.core.drag && app.core.drag.launchIntent,
4971 touchId: app.activeTouchId,
4972 pid: app.pointerId,
4973 ptype: app.pointerType
4974 };
4975 lastDragDebug = info;
4976 el.textContent = 'drag ' + phase
4977 + ' ev=' + evType
4978 + ' src=' + (info.src || '-')
4979 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
4980 + ' → ' + (info.target != null ? info.target : '-')
4981 + ' block=' + (info.blockY != null ? info.blockY : '-')
4982 + (info.launch ? ' LAUNCH' : '')
4983 + ' tId=' + info.touchId
4984 + ' pId=' + info.pid;
4985 el.hidden = false;
4986}
4987
4988
4989function hideEl (id)
4990{
4991 document.getElementById(id).hidden = true;
4992}
4993
4994function showEl (id)
4995{
4996 document.getElementById(id).hidden = false;
4997}
4998
4999window.addEventListener('resize', function ()
5000{
5001 if (app.mode === 'playing')
5002 { layout(); }
5003});
5004
5005window.addEventListener('orientationchange', function ()
5006{
5007 setTimeout(function ()
5008 {
5009 if (app.mode === 'playing')
5010 { layout(); }
5011 }, 120);
5012});
5013
5014/* ---------- online play (stage 2) ---------------------------------- */
5015
5016function tickOnline (dt)
5017{
5018 if (!app.online || typeof Online === 'undefined')
5019 { return; }
5020 if (app.core)
5021 {
5022 var shots = app.core.consumeOutgoingShots();
5023 for (var i = 0; i < shots.length; i++)
5024 {
5025 var s = shots[i];
5026 var start = fieldToViewport(s.col, s.y + 1);
5027 Online.rememberFlightLocal(s, start.x, start.y);
5028 }
5029 Online.queueShots(shots);
5030 }
5031 Online.tickFlights();
5032 Online.renderMinis(document.getElementById('minis'));
5033}
5034
5035function fieldToViewport (col, fieldY)
5036{
5037 var canvas = app.scene && app.scene.canvas;
5038 if (!canvas)
5039 { return { x: window.innerWidth / 2, y: 40 }; }
5040 var rect = canvas.getBoundingClientRect();
5041 var x = rect.left + ((col + 0.5) / 10) * rect.width;
5042 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
5043 return { x: x, y: y };
5044}
5045
5046function onlinePayload ()
5047{
5048 if (!app.online || !app.core)
5049 { return {}; }
5050 return {
5051 snapshot: app.core.fieldSnapshot(),
5052 score: app.core.score,
5053 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
5054 };
5055}
5056
5057function onOnlineEliminated ()
5058{
5059 app.eliminatedReported = true;
5060 app.spectating = true;
5061 unbindPointer();
5062 hideEl('game-over');
5063 var lobby = typeof Online !== 'undefined' && Online.lobby;
5064 if (lobby && lobby.status === 'finished')
5065 {
5066 showPodium(lobby);
5067 return;
5068 }
5069 showEl('spectator');
5070}
5071
5072function showPodium (lobby)
5073{
5074 hideEl('spectator');
5075 hideEl('game-over');
5076 hideEl('online-panel');
5077 showEl('podium');
5078 var list = document.getElementById('podium-list');
5079 list.innerHTML = '';
5080 var ranks = (lobby && lobby.rankings) || [];
5081 for (var i = 0; i < ranks.length; i++)
5082 {
5083 var r = ranks[i];
5084 var li = document.createElement('li');
5085 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
5086 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
5087 list.appendChild(li);
5088 }
5089 var hint = document.getElementById('podium-hint');
5090 var secs = (lobby && lobby.podium_seconds) || 5;
5091 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
5092}
5093
5094function startOnlineMatch ()
5095{
5096 if (app.mode === 'playing' && app.online)
5097 { return; }
5098 var planet = Planet.planetById(selectedPlanetId());
5099 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
5100 if (me && me.planet && me.planet.id)
5101 { planet = Planet.planetById(me.planet.id); }
5102 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
5103 if (typeof Online !== 'undefined')
5104 { Online.startPolling(onlinePayload); }
5105}
5106
5107function leaveOnlineMatch (goMenu)
5108{
5109 if (typeof Online !== 'undefined')
5110 {
5111 Online.stopPolling();
5112 Online.leaveLobby();
5113 Online.clearFlights();
5114 }
5115 teardownPlay();
5116 app.online = false;
5117 if (goMenu)
5118 {
5119 app.mode = 'menu';
5120 showEl('menu');
5121 }
5122 else
5123 {
5124 app.mode = 'online';
5125 openOnlinePanel();
5126 }
5127}
5128
5129function bindOnlineUi ()
5130{
5131 var onlineBtn = document.getElementById('btn-online');
5132 if (!onlineBtn)
5133 { return; }
5134 onlineBtn.addEventListener('click', function ()
5135 { openOnlinePanel(); });
5136
5137 var backs = document.querySelectorAll('[data-back-menu]');
5138 for (var i = 0; i < backs.length; i++)
5139 {
5140 backs[i].addEventListener('click', function ()
5141 {
5142 if (typeof Online !== 'undefined')
5143 { Online.stopPolling(); }
5144 hideEl('online-panel');
5145 app.mode = 'menu';
5146 app.online = false;
5147 showEl('menu');
5148 });
5149 }
5150
5151 document.getElementById('btn-create').addEventListener('click', function ()
5152 {
5153 Online.createLobby().then(function (data)
5154 {
5155 if (data && data.ok)
5156 {
5157 renderOnline();
5158 Online.startPolling(onlinePayload);
5159 }
5160 else
5161 { renderOnline(); }
5162 });
5163 });
5164
5165 document.getElementById('join-form').addEventListener('submit', function (e)
5166 {
5167 e.preventDefault();
5168 var code = (document.getElementById('join-code').value || '').trim();
5169 if (!code)
5170 { return; }
5171 Online.joinLobby(code).then(function ()
5172 {
5173 renderOnline();
5174 if (Online.lobby)
5175 { Online.startPolling(onlinePayload); }
5176 });
5177 });
5178
5179 document.getElementById('btn-ready').addEventListener('click', function ()
5180 {
5181 var me = Online.mePlayer();
5182 Online.setReady(!(me && me.ready)).then(renderOnline);
5183 });
5184
5185 document.getElementById('btn-start').addEventListener('click', function ()
5186 {
5187 Online.startGame().then(function (data)
5188 {
5189 if (data && data.ok)
5190 { startOnlineMatch(); }
5191 else
5192 { renderOnline(); }
5193 });
5194 });
5195
5196 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
5197 {
5198 Online.leaveLobby().then(function ()
5199 {
5200 Online.stopPolling();
5201 renderOnline();
5202 });
5203 });
5204
5205 document.getElementById('btn-copy-code').addEventListener('click', function ()
5206 {
5207 var code = document.getElementById('lobby-code').textContent;
5208 if (navigator.clipboard && navigator.clipboard.writeText)
5209 { navigator.clipboard.writeText(code); }
5210 });
5211
5212 document.getElementById('btn-spectate').addEventListener('click', function ()
5213 {
5214 hideEl('spectator');
5215 app.spectating = true;
5216 });
5217
5218 document.getElementById('btn-leave-game').addEventListener('click', function ()
5219 { leaveOnlineMatch(false); });
5220
5221 if (typeof Online !== 'undefined')
5222 {
5223 Online.onChange = function ()
5224 { renderOnline(); };
5225 Online.onGameStart = function ()
5226 { startOnlineMatch(); };
5227 Online.onIncoming = function (incoming)
5228 {
5229 if (!app.core || app.core.state !== 'playing')
5230 { return; }
5231 for (var i = 0; i < incoming.length; i++)
5232 { app.core.ingestGarbage(); }
5233 };
5234 Online.onFinished = function (lobby)
5235 { showPodium(lobby); };
5236 Online.onLobbyReturn = function (lobby)
5237 {
5238 teardownPlay();
5239 app.online = false;
5240 app.mode = 'online';
5241 hideEl('podium');
5242 showEl('online-panel');
5243 renderOnline();
5244 Online.startPolling(onlinePayload);
5245 };
5246 }
5247
5248 var params = new URLSearchParams(window.location.search);
5249 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
5250 { openOnlinePanel(); }
5251}
5252
5253function openOnlinePanel ()
5254{
5255 hideEl('menu');
5256 hideEl('game-over');
5257 hideEl('podium');
5258 hideEl('spectator');
5259 hideEl('planet-select');
5260 showEl('online-panel');
5261 app.mode = 'online';
5262 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
5263 if (typeof Online === 'undefined')
5264 {
5265 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
5266 showOnly('online-unconfigured');
5267 return;
5268 }
5269 Online.refresh().then(function (data)
5270 {
5271 if (!data || data.ok === false)
5272 {
5273 var msg = (data && data.error) || 'Geen verbinding met de server.';
5274 showOnlineError(msg + ' Je kunt wel alleen spelen.');
5275 if (data && data.configured === false)
5276 { showOnly('online-unconfigured'); }
5277 else
5278 { showOnly('online-login'); }
5279 document.getElementById('btn-login').style.display = 'none';
5280 return;
5281 }
5282 renderOnline();
5283 if (Online.lobby)
5284 { Online.startPolling(onlinePayload); }
5285 });
5286}
5287
5288function setOnlineStatus (text)
5289{
5290 var el = document.getElementById('online-status');
5291 if (el)
5292 { el.textContent = text; }
5293}
5294
5295function showOnlineError (text)
5296{
5297 var el = document.getElementById('online-error');
5298 if (!el)
5299 { return; }
5300 if (!text)
5301 {
5302 el.hidden = true;
5303 el.textContent = '';
5304 return;
5305 }
5306 el.hidden = false;
5307 el.textContent = text;
5308}
5309
5310function showOnly (id)
5311{
5312 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
5313 for (var i = 0; i < ids.length; i++)
5314 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
5315}
5316
5317function renderOnline ()
5318{
5319 if (typeof Online === 'undefined')
5320 { return; }
5321 if (app.mode === 'playing' && app.online)
5322 {
5323 Online.renderMinis(document.getElementById('minis'));
5324 if (Online.lobby && Online.lobby.status === 'finished')
5325 { showPodium(Online.lobby); }
5326 return;
5327 }
5328 showOnlineError(Online.error);
5329 if (!Online.configured && !Online.me && !Online.local)
5330 {
5331 setOnlineStatus('Online spelen is nog niet ingesteld.');
5332 showOnly('online-unconfigured');
5333 return;
5334 }
5335 if (!Online.me)
5336 {
5337 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
5338 showOnly('online-login');
5339 document.getElementById('btn-login').style.display = '';
5340 document.getElementById('btn-login').href = Online.loginUrl();
5341 document.getElementById('local-login').hidden = !Online.local;
5342 return;
5343 }
5344 if (Online.lobby)
5345 {
5346 setOnlineStatus('Lobby');
5347 showOnly('online-lobby');
5348 document.getElementById('lobby-me-name').textContent = Online.me.name;
5349 document.getElementById('lobby-code').textContent = Online.lobby.code;
5350 var list = document.getElementById('lobby-players');
5351 list.innerHTML = '';
5352 var players = Online.lobby.players || [];
5353 for (var i = 0; i < players.length; i++)
5354 {
5355 var p = players[i];
5356 var li = document.createElement('li');
5357 if (p.is_me)
5358 { li.classList.add('you'); }
5359 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
5360 var state = p.ready ? 'Gereed' : 'Wacht…';
5361 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
5362 li.innerHTML = '<span>' + escapeText(label)
5363 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
5364 + '</span><span class="'
5365 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
5366 list.appendChild(li);
5367 }
5368 renderPlanetGrid('lobby-planet-grid', true);
5369 var me = Online.mePlayer();
5370 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
5371 var start = document.getElementById('btn-start');
5372 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
5373 start.disabled = !Online.lobby.can_start;
5374 var hint = document.getElementById('lobby-hint');
5375 if (Online.lobby.status === 'playing')
5376 { hint.textContent = 'Het spel start…'; }
5377 else if (players.length < 2)
5378 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
5379 else if (!Online.lobby.all_ready)
5380 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
5381 else if (Online.lobby.can_start)
5382 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
5383 else
5384 { hint.textContent = 'Wachten tot de host start.'; }
5385 return;
5386 }
5387 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
5388 showOnly('online-home');
5389 document.getElementById('me-name').textContent = Online.me.name;
5390 document.getElementById('local-login').hidden = !Online.local;
5391}
5392
5393function escapeText (s)
5394{
5395 return String(s)
5396 .replace(/&/g, '&amp;')
5397 .replace(/</g, '&lt;')
5398 .replace(/>/g, '&gt;')
5399 .replace(/"/g, '&quot;');
5400}
5401
5402
5403function selectedPlanetId ()
5404{
5405 if (app.selectedPlanetId)
5406 { return app.selectedPlanetId; }
5407 return 'terra';
5408}
5409
5410function restoreSelectedPlanet ()
5411{
5412 var id = 'terra';
5413 try
5414 { id = localStorage.getItem('meteors-planet') || 'terra'; }
5415 catch (e) {}
5416 setSelectedPlanet(id, true);
5417}
5418
5419function setSelectedPlanet (id, silent)
5420{
5421 var all = Planet.allPlanets();
5422 var found = null;
5423 for (var i = 0; i < all.length; i++)
5424 {
5425 if (all[i].id === id)
5426 { found = all[i]; break; }
5427 }
5428 if (!found)
5429 { found = Planet.defaultPlanet(); }
5430 app.selectedPlanetId = found.id;
5431 try
5432 { localStorage.setItem('meteors-planet', found.id); }
5433 catch (e) {}
5434 if (!silent)
5435 {
5436 var grid = document.getElementById('planet-grid');
5437 if (grid && !grid.hidden && grid.children.length)
5438 { renderPlanetGrid('planet-grid', false); }
5439 var lobby = document.getElementById('lobby-planet-grid');
5440 if (lobby && lobby.children.length)
5441 { renderPlanetGrid('lobby-planet-grid', true); }
5442 }
5443 return found;
5444}
5445
5446function openPlanetSelect (context)
5447{
5448 if (app.mode === 'playing')
5449 { return; }
5450 app.planetSelectContext = context || 'solo';
5451 app.mode = 'planet-select';
5452 hideEl('menu');
5453 hideEl('online-panel');
5454 hideEl('game-over');
5455 showEl('planet-select');
5456 renderPlanetGrid('planet-grid', false);
5457 var go = document.getElementById('btn-planet-go');
5458 if (go)
5459 { go.textContent = 'Spelen'; }
5460}
5461
5462function renderPlanetGrid (containerId, compact)
5463{
5464 var grid = document.getElementById(containerId);
5465 if (!grid)
5466 { return; }
5467 var current = selectedPlanetId();
5468 var all = Planet.allPlanets();
5469 grid.innerHTML = '';
5470 if (compact)
5471 { grid.classList.add('compact'); }
5472 for (var i = 0; i < all.length; i++)
5473 {
5474 var pl = all[i];
5475 var btn = document.createElement('button');
5476 btn.type = 'button';
5477 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
5478 btn.setAttribute('role', 'listitem');
5479 btn.dataset.planet = pl.id;
5480 var swatches = '';
5481 for (var c = 0; c < pl.colors.length; c++)
5482 {
5483 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
5484 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
5485 }
5486 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
5487 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
5488 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
5489 + '<div class="planet-swatches">' + swatches + '</div>';
5490 btn.addEventListener('click', (function (id, isCompact)
5491 {
5492 return function ()
5493 { onPlanetPicked(id, isCompact); };
5494 })(pl.id, !!compact));
5495 grid.appendChild(btn);
5496 }
5497}
5498
5499function onPlanetPicked (id, fromLobby)
5500{
5501 setSelectedPlanet(id);
5502 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
5503 {
5504 Online.setPlanet(id).then(function ()
5505 { renderOnline(); });
5506 }
5507 else
5508 {
5509 renderPlanetGrid('planet-grid', false);
5510 }
5511}
5512
5513function confirmPlanetSelect ()
5514{
5515 var planet = setSelectedPlanet(selectedPlanetId());
5516 hideEl('planet-select');
5517 if (app.planetSelectContext === 'online')
5518 {
5519 openOnlinePanel();
5520 return;
5521 }
5522 startPlay({ planet: planet });
5523}
5524
5525function cancelPlanetSelect ()
5526{
5527 hideEl('planet-select');
5528 app.mode = 'menu';
5529 showEl('menu');
5530}
5531
5532function bindPlanetSelect ()
5533{
5534 var go = document.getElementById('btn-planet-go');
5535 var back = document.getElementById('btn-planet-back');
5536 if (go)
5537 {
5538 go.addEventListener('click', confirmPlanetSelect);
5539 }
5540 if (back)
5541 {
5542 back.addEventListener('click', cancelPlanetSelect);
5543 }
5544}
5545
5546/*
5547 * End File:
5548 * /workspace/meteors/src/main.js
5549 */