'use strict';
/**
* View and input for Meteors. The simulation lives in GameCore; this file
* only draws it, scales it to the viewport, and translates pointer events
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
* through Online (src/online.js) and the same GameCore.
*/
function planetImages ()
{
var list = [
{ name: 'gray', url: 'images/block-gray.png' },
{ name: 'locked', url: 'images/block-locked.png' },
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
{ name: 'cell', url: 'images/cell.png' },
{ name: 'pixel', url: 'images/pixel.png' },
// Keep the original Terra placeholders as aliases (Tim may still have them).
{ name: 'ember', url: 'images/block-ember.png' },
{ name: 'aqua', url: 'images/block-aqua.png' },
{ name: 'leaf', url: 'images/block-leaf.png' },
{ name: 'sun', url: 'images/block-sun.png' },
{ name: 'orchid', url: 'images/block-orchid.png' }
];
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
for (var i = 0; i < planets.length; i++)
{
var pl = planets[i];
for (var c = 0; c < pl.colors.length; c++)
{
list.push({
name: Planet.spriteKey(pl, c),
url: pl.colors[c].image
});
}
}
return list;
}
var IMAGES = planetImages();
var GAME_OVER_DELAY = 2;
var game = new Game();
var app = {
mode: 'menu',
core: null,
scene: null,
manager: null,
planet: null,
lastScore: 0,
tile: 48,
fieldX: 0,
fieldY: 0,
fieldW: 0,
fieldH: 0,
hudH: 56,
sprites: Object.create(null),
flames: Object.create(null),
cells: [],
pointerId: null,
pointerType: null,
activeTouchId: null,
debugDrag: false,
debugPhysics: false,
gameOverShown: false,
selectTween: null,
online: false,
eliminatedReported: false,
spectating: false,
miniH: 0,
selectedPlanetId: 'terra',
planetSelectContext: 'solo'
};
window.onload = function ()
{
app.debugDrag = isDragDebugEnabled();
app.debugPhysics = isPhysicsDebugEnabled();
var play = document.getElementById('btn-play');
play.addEventListener('click', onPlay);
play.addEventListener('pointerup', function (e)
{
// A touch-friendly path: some mobile browsers swallow the click
// after a slightly sloppy tap. Ignore the following click.
if (e.pointerType === 'touch' || e.pointerType === 'pen')
{
e.preventDefault();
onPlay();
}
});
game.preloadImagesThenStart(IMAGES, function ()
{
if (game.images.flame && game.images.flame.addAnimationCycle)
{ game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
});
bindOnlineUi();
bindPlanetSelect();
restoreSelectedPlanet();
};
function onPlay ()
{
if (app.mode === 'playing')
{ return; }
openPlanetSelect('solo');
}
function startPlay (opts)
{
opts = opts || {};
hideEl('menu');
hideEl('game-over');
hideEl('online-panel');
hideEl('spectator');
hideEl('podium');
hideEl('planet-select');
showEl('hud');
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
var miss = opts.missChance;
if (typeof miss !== 'number' || !isFinite(miss))
{ miss = planetMod.missChance(app.planet); }
app.core = new GameCore(app.planet, Math.random, miss);
if (app.debugPhysics)
{ app.core.debugInvariants = true; }
app.mode = 'playing';
app.online = !!opts.online;
app.gameOverShown = false;
app.eliminatedReported = false;
app.spectating = false;
app.sprites = Object.create(null);
app.flames = Object.create(null);
app.cells = [];
app.pointerId = null;
app.selectTween = null;
layout();
if (app.scene)
{
app.scene.destroy();
app.scene = null;
}
app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
app.scene.renderBackground = true;
game.loadScene(app.scene);
buildCells();
app.manager = app.scene.addObject(makeManager());
if (!app.spectating)
{ bindPointer(app.scene.canvas); }
refreshHud();
if (app.online)
{ showEl('minis'); }
else
{ hideEl('minis'); }
}
function teardownPlay ()
{
unbindPointer();
if (app.scene)
{
app.scene.destroy();
app.scene = null;
}
app.manager = null;
app.core = null;
app.sprites = Object.create(null);
app.flames = Object.create(null);
app.cells = [];
app.selectTween = null;
app.pointerId = null;
app.gameOverShown = false;
hideEl('hud');
hideEl('game-over');
hideEl('spectator');
hideEl('minis');
if (typeof Online !== 'undefined')
{ Online.clearFlights(); }
}
function returnToMenu ()
{
if (app.online && typeof Online !== 'undefined')
{
// Online matches do not dump you back to the solo menu:
// elimination becomes spectating; a finished match shows the podium.
return;
}
teardownPlay();
app.mode = 'menu';
app.online = false;
hideEl('planet-select');
showEl('menu');
var last = document.getElementById('last-score');
if (app.lastScore > 0)
{
last.hidden = false;
last.querySelector('strong').textContent = String(app.lastScore);
}
}
function buildCells ()
{
if (!app.scene)
{ return; }
var img = game.images.cell;
for (var row = 0; row < 13; row++)
{
for (var col = 0; col < 10; col++)
{
var obj = new GameObject(0, 0, img, 0);
placeTile(obj, col, row);
obj.renderer.alpha = 0.9;
app.scene.addObject(obj);
app.cells.push(obj);
}
}
}
function placeTile (obj, col, y)
{
var t = app.tile;
obj.transform.position.x = col * t + t / 2;
obj.transform.position.y = app.fieldH - (y + 0.5) * t;
obj.transform.size = { x: t, y: t };
}
function layoutIfNeeded ()
{
if (app.core && app.core.drag)
{ return; }
var vw = window.innerWidth || 320;
var vh = window.innerHeight || 480;
if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
{ return; }
layout();
}
function layout ()
{
if (app.core && app.core.drag)
{ return; }
var vw = window.innerWidth || 320;
var vh = window.innerHeight || 480;
app._layoutVw = vw;
app._layoutVh = vh;
var safeTop = 0;
try
{
// env(safe-area) is a CSS thing; keep a conservative HUD height.
safeTop = 0;
}
catch (e) { /* ignore */ }
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
app.miniH = 0;
if (app.online)
{ app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
var availW = Math.max(80, vw - margin * 2);
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
app.fieldW = app.tile * 10;
app.fieldH = app.tile * 13;
app.fieldX = Math.floor((vw - app.fieldW) / 2);
var topBand = app.hudH + app.miniH;
app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
if (app.fieldY < topBand)
{ app.fieldY = topBand; }
var minis = document.getElementById('minis');
if (minis)
{
minis.style.top = app.hudH + 'px';
minis.style.maxHeight = app.miniH + 'px';
}
if (app.scene)
{
app.scene.position.x = app.fieldX;
app.scene.position.y = app.fieldY;
app.scene.size.x = app.fieldW;
app.scene.size.y = app.fieldH;
}
}
function spriteFor (block)
{
if (block.state === 'locked')
{ return game.images.locked; }
if (block.color < 0)
{ return game.images.gray; }
var key = Planet.spriteKey(app.planet, block.color);
return game.images[key] || game.images.gray;
}
function syncSprites ()
{
if (!app.core || !app.scene)
{ return; }
var seen = Object.create(null);
var blocks = app.core.blocks;
for (var i = 0; i < blocks.length; i++)
{
var block = blocks[i];
seen[block.id] = true;
var obj = app.sprites[block.id];
if (!obj)
{
obj = new GameObject(0, 0, spriteFor(block), 2);
app.scene.addObject(obj);
app.sprites[block.id] = obj;
}
obj.renderer.sprite = spriteFor(block);
placeTile(obj, block.col, block.y);
applyBlockVisual(obj, block);
obj.renderer.visible = true;
obj.renderer.alpha = 1;
if (block.flame)
{
var flame = app.flames[block.id];
if (!flame)
{
flame = new GameObject(0, 0, game.images.flame, 1);
flame.renderer.setAnimation('burn', 0, 0.08);
app.scene.addObject(flame);
app.flames[block.id] = flame;
}
flame.renderer.visible = true;
var t = app.tile;
// 3x as large (length and width, t1110). Keep the top of the
// flame at the same overlap into the block so the extra length
// extends downward under the rocket.
var flameW = t * 0.85 * 3;
var flameH = t * 0.85 * 3;
var origCenter = app.fieldH - block.y * t + t * 0.15;
var origTop = origCenter - (t * 0.85) / 2;
flame.transform.position.x = block.col * t + t / 2;
flame.transform.position.y = origTop + flameH / 2;
flame.transform.size = { x: flameW, y: flameH };
}
else if (app.flames[block.id])
{ app.flames[block.id].renderer.visible = false; }
}
var ids = Object.keys(app.sprites);
for (var i = 0; i < ids.length; i++)
{
if (!seen[ids[i]])
{
app.sprites[ids[i]].destroy();
delete app.sprites[ids[i]];
if (app.flames[ids[i]])
{
app.flames[ids[i]].destroy();
delete app.flames[ids[i]];
}
}
}
}
function applyBlockVisual (obj, block)
{
var t = app.tile;
var sx = 1;
var sy = 1;
var dy = 0;
if (block.bouncing && app.planet && app.planet.bounceDuration > 0
&& typeof Easing !== 'undefined' && Easing.bouncePose)
{
var u = block.bounceAge / app.planet.bounceDuration;
var pose = Easing.bouncePose(u, app.planet.bounceSquash);
sx = pose.sx;
sy = pose.sy;
dy = pose.dy;
}
var sel = 1;
var tw = app.selectTween;
if (tw && tw.blockId === block.id && tw.phase !== 'idle')
{ sel = tw.scale; }
obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
if (dy)
{ obj.transform.position.y -= dy * t; }
}
function clickTween ()
{
return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
}
function startPressTween (blockId)
{
var c = clickTween();
if (!c)
{ return; }
var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
app.selectTween = {
blockId: blockId,
from: from,
to: c.pressScale,
t: 0,
duration: c.pressDuration,
ease: c.pressEase,
scale: from,
phase: 'press'
};
}
function startReleaseTween ()
{
var c = clickTween();
var tw = app.selectTween;
if (!c || !tw || tw.phase === 'idle')
{ return; }
app.selectTween = {
blockId: tw.blockId,
from: tw.scale,
to: c.releaseScale,
t: 0,
duration: c.releaseDuration,
ease: c.releaseEase,
scale: tw.scale,
phase: 'release'
};
}
function updateSelectTween (dt)
{
var tw = app.selectTween;
if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
{ return; }
tw.t += dt;
var u = tw.duration > 0 ? tw.t / tw.duration : 1;
if (u >= 1)
{
tw.scale = tw.to;
tw.t = tw.duration;
if (tw.phase === 'press')
{ tw.phase = 'hold'; }
else
{
tw.phase = 'idle';
tw.scale = 1;
tw.blockId = null;
}
return;
}
var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
}
function refreshHud ()
{
if (!app.core)
{ return; }
document.getElementById('score').textContent = String(app.core.score);
var planet = app.planet;
document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
}
function makeManager ()
{
var obj = new GameObject(0, 0, game.images.pixel, 0);
obj.renderer.visible = false;
var base = obj.update.bind(obj);
obj.update = function (dt)
{
base(dt);
tickView(dt);
};
return obj;
}
function tickView (dt)
{
if (app.mode !== 'playing' || !app.core)
{ return; }
// Never resize the canvas mid-drag: a URL-bar hide would move the
// field under the finger and jump the target row. Also skip work
// when the viewport has not actually changed.
if (!(app.core && app.core.drag))
{ layoutIfNeeded(); }
for (var i = 0; i < app.cells.length; i++)
{
var col = i % 10;
var row = Math.floor(i / 10);
placeTile(app.cells[i], col, row);
}
app.core.tick(dt);
updateSelectTween(dt);
syncSprites();
refreshHud();
tickOnline(dt);
if (app.debugPhysics)
{ logPhysicsDebug(); }
if (app.core.state === 'gameover' && !app.gameOverShown)
{
app.gameOverShown = true;
app.lastScore = app.core.score;
document.getElementById('go-score').textContent = String(app.lastScore);
if (app.online)
{ onOnlineEliminated(); }
else
{ showEl('game-over'); }
}
if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
{ returnToMenu(); }
}
/* ---------- pointer input (mouse + touch) --------------------------- */
/*
* Mouse uses Pointer Events. Touch uses Touch Events as the authority:
* on a real phone, pointer clientX/Y can disagree with the visual
* finger (zoomed visual viewport, gesture takeover, capture cancel)
* while changedTouches stays correct. When a touch is active, pointer
* move/up/cancel are ignored so a poisoned pointer coordinate cannot
* walk the block to the top or bottom of the stack (t1106).
*
* After a down we also listen on the document, so a drag that leaves
* the canvas (needed to launch a block at the top of a full column)
* still reaches moveDrag. We do not call setPointerCapture: on mobile
* that is often cancelled when the browser takes the gesture, which
* would fire pointercancel mid-drag.
*
* A non-passive document touchstart/touchmove preventDefault during
* play stops scrolling, rubber-banding and the pointercancel that
* follows. pointercancel / touchcancel end the drag without launch.
*
* ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
*/
var boundCanvas = null;
var windowListening = false;
var touchListening = false;
var lastDragDebug = null;
function isDragDebugEnabled ()
{
try
{
var q = window.location && window.location.search;
if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
{ return true; }
if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
{ return true; }
}
catch (err) { /* ignore */ }
return false;
}
/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
function isPhysicsDebugEnabled ()
{
try
{
var q = window.location && window.location.search;
if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
{ return true; }
if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
|| window.localStorage.getItem('meteors-debug-drag') === '1'))
{ return true; }
}
catch (err) { /* ignore */ }
return false;
}
function eventClient (e)
{
var t = null;
if (e.changedTouches && e.changedTouches.length)
{ t = e.changedTouches[0]; }
else if (e.touches && e.touches.length)
{ t = e.touches[0]; }
if (t)
{ return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
if (e.clientX != null && e.clientY != null)
{ return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
return null;
}
function addWindowPointer ()
{
if (windowListening)
{ return; }
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
windowListening = true;
}
function removeWindowPointer ()
{
if (!windowListening)
{ return; }
window.removeEventListener('pointermove', onPointerMove, { capture: true });
window.removeEventListener('pointerup', onPointerUp, { capture: true });
window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
windowListening = false;
}
function addTouchListeners ()
{
if (touchListening)
{ return; }
var opts = { capture: true, passive: false };
document.addEventListener('touchstart', onTouchStart, opts);
document.addEventListener('touchmove', onTouchMove, opts);
document.addEventListener('touchend', onTouchEnd, opts);
document.addEventListener('touchcancel', onTouchCancel, opts);
touchListening = true;
}
function removeTouchListeners ()
{
if (!touchListening)
{ return; }
var opts = { capture: true };
document.removeEventListener('touchstart', onTouchStart, opts);
document.removeEventListener('touchmove', onTouchMove, opts);
document.removeEventListener('touchend', onTouchEnd, opts);
document.removeEventListener('touchcancel', onTouchCancel, opts);
touchListening = false;
}
function bindPointer (canvas)
{
unbindPointer();
boundCanvas = canvas;
canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
canvas.style.touchAction = 'none';
canvas.style.position = 'fixed';
canvas.style.cursor = 'pointer';
canvas.style.webkitUserSelect = 'none';
canvas.style.userSelect = 'none';
addTouchListeners();
if (app.debugDrag)
{ ensureDragDebugOverlay(); }
}
function unbindPointer ()
{
removeWindowPointer();
removeTouchListeners();
if (boundCanvas)
{ boundCanvas.removeEventListener('pointerdown', onPointerDown); }
boundCanvas = null;
app.pointerId = null;
app.pointerType = null;
app.activeTouchId = null;
}
function fieldFromEvent (e)
{
var canvas = app.scene && app.scene.canvas;
if (!canvas)
{ return null; }
var rect = canvas.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0)
{ return null; }
var pt = eventClient(e);
if (!pt)
{ return null; }
// Map through the CSS box only. Using canvas.width / app.tile would
// scale the pointer by the backing-store ratio whenever that differs
// from the layout size (high-DPR devices), so a short finger move
// would look like a long swipe.
var width = Planet.FIELD_WIDTH;
var height = Planet.FIELD_HEIGHT;
var col = ((pt.x - rect.left) / rect.width) * width;
var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
}
function playingForDrag ()
{
return app.core && app.core.state === 'playing';
}
function startDragFromEvent (e)
{
var pos = fieldFromEvent(e);
if (!pos)
{ return; }
if (app.core.drag)
{
app.core.moveDrag(pos.y);
logDragDebug(e, pos, 'move-already');
return;
}
if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
{ startPressTween(app.core.drag.blockId); }
logDragDebug(e, pos, 'down');
}
function moveDragFromEvent (e)
{
if (!app.core || !app.core.drag)
{ return; }
var pos = fieldFromEvent(e);
if (pos)
{ app.core.moveDrag(pos.y); }
logDragDebug(e, pos, 'move');
}
function finishDrag (opts)
{
opts = opts || {};
app.pointerId = null;
app.pointerType = null;
app.activeTouchId = null;
removeWindowPointer();
if (boundCanvas)
{
try
{
if (opts.pointerId != null && boundCanvas.releasePointerCapture)
{ boundCanvas.releasePointerCapture(opts.pointerId); }
}
catch (err) { /* ignore */ }
}
startReleaseTween();
if (app.core && app.core.drag)
{
if (opts.noLaunch)
{ app.core.drag.launchIntent = false; }
app.core.endDrag();
}
else if (app.core)
{ app.core.endDrag(); }
logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
}
function onPointerDown (e)
{
if (!playingForDrag())
{ return; }
if (app.pointerId != null && e.pointerId !== app.pointerId)
{ return; }
if (e.preventDefault)
{ e.preventDefault(); }
app.pointerId = e.pointerId;
app.pointerType = e.pointerType || 'mouse';
addWindowPointer();
// If a touch is already in charge, do not reset the grab from pointerdown.
if (app.activeTouchId != null)
{ return; }
startDragFromEvent(e);
}
function onPointerMove (e)
{
if (app.pointerId == null || e.pointerId !== app.pointerId)
{ return; }
if (!app.core || !app.core.drag)
{ return; }
// Touch coordinates are the authority; ignore pointer moves for a
// live touch so a wrong clientY cannot walk the whole column.
// Only skip when touchstart has actually arrived — some environments
// deliver touch-pointer events without a TouchEvent stream.
if (app.activeTouchId != null)
{
if (e.preventDefault)
{ e.preventDefault(); }
logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
return;
}
if (e.preventDefault)
{ e.preventDefault(); }
moveDragFromEvent(e);
}
function onPointerUp (e)
{
if (app.pointerId == null)
{ return; }
if (e && e.pointerId != null && e.pointerId !== app.pointerId)
{ return; }
if (app.activeTouchId != null)
{
// touchend will finish the drag.
if (e && e.preventDefault)
{ e.preventDefault(); }
logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
return;
}
if (e && e.preventDefault)
{ e.preventDefault(); }
finishDrag({ pointerId: e && e.pointerId });
}
function onPointerCancel (e)
{
if (app.pointerId == null)
{ return; }
if (e && e.pointerId != null && e.pointerId !== app.pointerId)
{ return; }
if (app.activeTouchId != null)
{
if (e && e.preventDefault)
{ e.preventDefault(); }
logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
return;
}
if (e && e.preventDefault)
{ e.preventDefault(); }
// A cancelled gesture is not a launch pull.
finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
}
function touchById (list, id)
{
if (!list)
{ return null; }
for (var i = 0; i < list.length; i++)
{
if (list[i].identifier === id)
{ return list[i]; }
}
return null;
}
function onTouchStart (e)
{
if (!playingForDrag())
{ return; }
if (app.activeTouchId != null)
{
if (e.preventDefault)
{ e.preventDefault(); }
return;
}
var t = e.changedTouches && e.changedTouches[0];
if (!t)
{ return; }
if (e.preventDefault)
{ e.preventDefault(); }
app.activeTouchId = t.identifier;
addWindowPointer();
startDragFromEvent(e);
}
function onTouchMove (e)
{
if (app.activeTouchId == null)
{ return; }
if (!touchById(e.changedTouches, app.activeTouchId)
&& !touchById(e.touches, app.activeTouchId))
{ return; }
if (e.preventDefault)
{ e.preventDefault(); }
moveDragFromEvent(e);
}
function onTouchEnd (e)
{
if (app.activeTouchId == null)
{ return; }
if (!touchById(e.changedTouches, app.activeTouchId))
{ return; }
if (e.preventDefault)
{ e.preventDefault(); }
finishDrag({});
}
function onTouchCancel (e)
{
if (app.activeTouchId == null)
{ return; }
if (!touchById(e.changedTouches, app.activeTouchId))
{ return; }
if (e.preventDefault)
{ e.preventDefault(); }
finishDrag({ noLaunch: true });
}
function logPhysicsDebug ()
{
if (!app.debugPhysics || !app.core)
{ return; }
ensureDragDebugOverlay();
var el = document.getElementById('drag-debug');
if (!el)
{ return; }
var issues = app.core.lastInvariantViolations || [];
var flying = 0;
var manuals = 0;
var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
for (var i = 0; i < app.core.blocks.length; i++)
{
if (app.core.blocks[i].state === 'flying')
{ flying++; }
if (app.core.blocks[i].state === 'manual')
{ manuals++; }
}
var status = issues.length
? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
: ('physics ok blocks=' + app.core.blocks.length
+ ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
// Keep any live drag line above the physics status.
var dragLine = '';
if (app.debugDrag && lastDragDebug)
{
dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
? el.textContent.split('\n')[0] + '\n'
: '';
}
el.textContent = dragLine + status;
el.hidden = false;
el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
}
function ensureDragDebugOverlay ()
{
if (document.getElementById('drag-debug'))
{ return; }
var el = document.createElement('div');
el.id = 'drag-debug';
el.setAttribute('aria-live', 'polite');
document.body.appendChild(el);
}
function logDragDebug (e, pos, phase)
{
if (!app.debugDrag)
{ return; }
ensureDragDebugOverlay();
var el = document.getElementById('drag-debug');
if (!el)
{ return; }
var block = null;
if (app.core && app.core.drag)
{ block = app.core.blockById(app.core.drag.blockId); }
var pt = e ? eventClient(e) : null;
var evType = e ? e.type : phase;
var info = {
phase: phase,
ev: evType,
src: pos && pos.src,
fieldY: pos && Math.round(pos.y * 100) / 100,
col: pos && Math.round(pos.col * 100) / 100,
cy: pt && Math.round(pt.y * 10) / 10,
blockY: block && Math.round(block.y * 100) / 100,
target: block && Math.floor((pos && pos.y) + 1e-12),
launch: app.core && app.core.drag && app.core.drag.launchIntent,
touchId: app.activeTouchId,
pid: app.pointerId,
ptype: app.pointerType
};
lastDragDebug = info;
el.textContent = 'drag ' + phase
+ ' ev=' + evType
+ ' src=' + (info.src || '-')
+ ' y=' + (info.fieldY != null ? info.fieldY : '-')
+ ' → ' + (info.target != null ? info.target : '-')
+ ' block=' + (info.blockY != null ? info.blockY : '-')
+ (info.launch ? ' LAUNCH' : '')
+ ' tId=' + info.touchId
+ ' pId=' + info.pid;
el.hidden = false;
}
function hideEl (id)
{
document.getElementById(id).hidden = true;
}
function showEl (id)
{
document.getElementById(id).hidden = false;
}
window.addEventListener('resize', function ()
{
if (app.mode === 'playing')
{ layout(); }
});
window.addEventListener('orientationchange', function ()
{
setTimeout(function ()
{
if (app.mode === 'playing')
{ layout(); }
}, 120);
});
/* ---------- online play (stage 2) ---------------------------------- */
function tickOnline (dt)
{
if (!app.online || typeof Online === 'undefined')
{ return; }
if (app.core)
{
var shots = app.core.consumeOutgoingShots();
for (var i = 0; i < shots.length; i++)
{
var s = shots[i];
var start = fieldToViewport(s.col, s.y + 1);
Online.rememberFlightLocal(s, start.x, start.y);
}
Online.queueShots(shots);
}
Online.tickFlights();
Online.renderMinis(document.getElementById('minis'));
}
function fieldToViewport (col, fieldY)
{
var canvas = app.scene && app.scene.canvas;
if (!canvas)
{ return { x: window.innerWidth / 2, y: 40 }; }
var rect = canvas.getBoundingClientRect();
var x = rect.left + ((col + 0.5) / 10) * rect.width;
var y = rect.top + (1 - (fieldY / 13)) * rect.height;
return { x: x, y: y };
}
function onlinePayload ()
{
if (!app.online || !app.core)
{ return {}; }
return {
snapshot: app.core.fieldSnapshot(),
score: app.core.score,
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
};
}
function onOnlineEliminated ()
{
app.eliminatedReported = true;
app.spectating = true;
unbindPointer();
hideEl('game-over');
var lobby = typeof Online !== 'undefined' && Online.lobby;
if (lobby && lobby.status === 'finished')
{
showPodium(lobby);
return;
}
showEl('spectator');
}
function showPodium (lobby)
{
hideEl('spectator');
hideEl('game-over');
hideEl('online-panel');
showEl('podium');
var list = document.getElementById('podium-list');
list.innerHTML = '';
var ranks = (lobby && lobby.rankings) || [];
for (var i = 0; i < ranks.length; i++)
{
var r = ranks[i];
var li = document.createElement('li');
var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
list.appendChild(li);
}
var hint = document.getElementById('podium-hint');
var secs = (lobby && lobby.podium_seconds) || 5;
hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
}
function startOnlineMatch ()
{
if (app.mode === 'playing' && app.online)
{ return; }
var planet = Planet.planetById(selectedPlanetId());
var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
if (me && me.planet && me.planet.id)
{ planet = Planet.planetById(me.planet.id); }
startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
if (typeof Online !== 'undefined')
{ Online.startPolling(onlinePayload); }
}
function leaveOnlineMatch (goMenu)
{
if (typeof Online !== 'undefined')
{
Online.stopPolling();
Online.leaveLobby();
Online.clearFlights();
}
teardownPlay();
app.online = false;
if (goMenu)
{
app.mode = 'menu';
showEl('menu');
}
else
{
app.mode = 'online';
openOnlinePanel();
}
}
function bindOnlineUi ()
{
var onlineBtn = document.getElementById('btn-online');
if (!onlineBtn)
{ return; }
onlineBtn.addEventListener('click', function ()
{ openOnlinePanel(); });
var backs = document.querySelectorAll('[data-back-menu]');
for (var i = 0; i < backs.length; i++)
{
backs[i].addEventListener('click', function ()
{
if (typeof Online !== 'undefined')
{ Online.stopPolling(); }
hideEl('online-panel');
app.mode = 'menu';
app.online = false;
showEl('menu');
});
}
document.getElementById('btn-create').addEventListener('click', function ()
{
Online.createLobby().then(function (data)
{
if (data && data.ok)
{
renderOnline();
Online.startPolling(onlinePayload);
}
else
{ renderOnline(); }
});
});
document.getElementById('join-form').addEventListener('submit', function (e)
{
e.preventDefault();
var code = (document.getElementById('join-code').value || '').trim();
if (!code)
{ return; }
Online.joinLobby(code).then(function ()
{
renderOnline();
if (Online.lobby)
{ Online.startPolling(onlinePayload); }
});
});
document.getElementById('btn-ready').addEventListener('click', function ()
{
var me = Online.mePlayer();
Online.setReady(!(me && me.ready)).then(renderOnline);
});
document.getElementById('btn-start').addEventListener('click', function ()
{
Online.startGame().then(function (data)
{
if (data && data.ok)
{ startOnlineMatch(); }
else
{ renderOnline(); }
});
});
document.getElementById('btn-leave-lobby').addEventListener('click', function ()
{
Online.leaveLobby().then(function ()
{
Online.stopPolling();
renderOnline();
});
});
document.getElementById('btn-copy-code').addEventListener('click', function ()
{
var code = document.getElementById('lobby-code').textContent;
if (navigator.clipboard && navigator.clipboard.writeText)
{ navigator.clipboard.writeText(code); }
});
document.getElementById('btn-spectate').addEventListener('click', function ()
{
hideEl('spectator');
app.spectating = true;
});
document.getElementById('btn-leave-game').addEventListener('click', function ()
{ leaveOnlineMatch(false); });
if (typeof Online !== 'undefined')
{
Online.onChange = function ()
{ renderOnline(); };
Online.onGameStart = function ()
{ startOnlineMatch(); };
Online.onIncoming = function (incoming)
{
if (!app.core || app.core.state !== 'playing')
{ return; }
for (var i = 0; i < incoming.length; i++)
{ app.core.ingestGarbage(); }
};
Online.onFinished = function (lobby)
{ showPodium(lobby); };
Online.onLobbyReturn = function (lobby)
{
teardownPlay();
app.online = false;
app.mode = 'online';
hideEl('podium');
showEl('online-panel');
renderOnline();
Online.startPolling(onlinePayload);
};
}
var params = new URLSearchParams(window.location.search);
if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
{ openOnlinePanel(); }
}
function openOnlinePanel ()
{
hideEl('menu');
hideEl('game-over');
hideEl('podium');
hideEl('spectator');
hideEl('planet-select');
showEl('online-panel');
app.mode = 'online';
setOnlineStatus('Even kijken of online spelen beschikbaar is…');
if (typeof Online === 'undefined')
{
showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
showOnly('online-unconfigured');
return;
}
Online.refresh().then(function (data)
{
if (!data || data.ok === false)
{
var msg = (data && data.error) || 'Geen verbinding met de server.';
showOnlineError(msg + ' Je kunt wel alleen spelen.');
if (data && data.configured === false)
{ showOnly('online-unconfigured'); }
else
{ showOnly('online-login'); }
document.getElementById('btn-login').style.display = 'none';
return;
}
renderOnline();
if (Online.lobby)
{ Online.startPolling(onlinePayload); }
});
}
function setOnlineStatus (text)
{
var el = document.getElementById('online-status');
if (el)
{ el.textContent = text; }
}
function showOnlineError (text)
{
var el = document.getElementById('online-error');
if (!el)
{ return; }
if (!text)
{
el.hidden = true;
el.textContent = '';
return;
}
el.hidden = false;
el.textContent = text;
}
function showOnly (id)
{
var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
for (var i = 0; i < ids.length; i++)
{ document.getElementById(ids[i]).hidden = (ids[i] !== id); }
}
function renderOnline ()
{
if (typeof Online === 'undefined')
{ return; }
if (app.mode === 'playing' && app.online)
{
Online.renderMinis(document.getElementById('minis'));
if (Online.lobby && Online.lobby.status === 'finished')
{ showPodium(Online.lobby); }
return;
}
showOnlineError(Online.error);
if (!Online.configured && !Online.me && !Online.local)
{
setOnlineStatus('Online spelen is nog niet ingesteld.');
showOnly('online-unconfigured');
return;
}
if (!Online.me)
{
setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
showOnly('online-login');
document.getElementById('btn-login').style.display = '';
document.getElementById('btn-login').href = Online.loginUrl();
document.getElementById('local-login').hidden = !Online.local;
return;
}
if (Online.lobby)
{
setOnlineStatus('Lobby');
showOnly('online-lobby');
document.getElementById('lobby-me-name').textContent = Online.me.name;
document.getElementById('lobby-code').textContent = Online.lobby.code;
var list = document.getElementById('lobby-players');
list.innerHTML = '';
var players = Online.lobby.players || [];
for (var i = 0; i < players.length; i++)
{
var p = players[i];
var li = document.createElement('li');
if (p.is_me)
{ li.classList.add('you'); }
var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
var state = p.ready ? 'Gereed' : 'Wacht…';
var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
li.innerHTML = '' + escapeText(label)
+ (world ? '' + escapeText(world) + '' : '')
+ '' + state + '';
list.appendChild(li);
}
renderPlanetGrid('lobby-planet-grid', true);
var me = Online.mePlayer();
document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
var start = document.getElementById('btn-start');
start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
start.disabled = !Online.lobby.can_start;
var hint = document.getElementById('lobby-hint');
if (Online.lobby.status === 'playing')
{ hint.textContent = 'Het spel start…'; }
else if (players.length < 2)
{ hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
else if (!Online.lobby.all_ready)
{ hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
else if (Online.lobby.can_start)
{ hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
else
{ hint.textContent = 'Wachten tot de host start.'; }
return;
}
setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
showOnly('online-home');
document.getElementById('me-name').textContent = Online.me.name;
document.getElementById('local-login').hidden = !Online.local;
}
function escapeText (s)
{
return String(s)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"');
}
function selectedPlanetId ()
{
if (app.selectedPlanetId)
{ return app.selectedPlanetId; }
return 'terra';
}
function restoreSelectedPlanet ()
{
var id = 'terra';
try
{ id = localStorage.getItem('meteors-planet') || 'terra'; }
catch (e) {}
setSelectedPlanet(id, true);
}
function setSelectedPlanet (id, silent)
{
var all = Planet.allPlanets();
var found = null;
for (var i = 0; i < all.length; i++)
{
if (all[i].id === id)
{ found = all[i]; break; }
}
if (!found)
{ found = Planet.defaultPlanet(); }
app.selectedPlanetId = found.id;
try
{ localStorage.setItem('meteors-planet', found.id); }
catch (e) {}
if (!silent)
{
var grid = document.getElementById('planet-grid');
if (grid && !grid.hidden && grid.children.length)
{ renderPlanetGrid('planet-grid', false); }
var lobby = document.getElementById('lobby-planet-grid');
if (lobby && lobby.children.length)
{ renderPlanetGrid('lobby-planet-grid', true); }
}
return found;
}
function openPlanetSelect (context)
{
if (app.mode === 'playing')
{ return; }
app.planetSelectContext = context || 'solo';
app.mode = 'planet-select';
hideEl('menu');
hideEl('online-panel');
hideEl('game-over');
showEl('planet-select');
renderPlanetGrid('planet-grid', false);
var go = document.getElementById('btn-planet-go');
if (go)
{ go.textContent = 'Spelen'; }
}
function renderPlanetGrid (containerId, compact)
{
var grid = document.getElementById(containerId);
if (!grid)
{ return; }
var current = selectedPlanetId();
var all = Planet.allPlanets();
grid.innerHTML = '';
if (compact)
{ grid.classList.add('compact'); }
for (var i = 0; i < all.length; i++)
{
var pl = all[i];
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
btn.setAttribute('role', 'listitem');
btn.dataset.planet = pl.id;
var swatches = '';
for (var c = 0; c < pl.colors.length; c++)
{
swatches += '';
}
btn.innerHTML = '