'use strict'; /** * Online play: talks to api.php (cookie session), polls lobby and game * state, and draws opponent miniatures plus flying-block tweens. * Real-time sync is not required; a 0.75 s poll is enough. */ var Online = { POLL_MS: 750, DEFAULT_MISS_CHANCE: 0.30, FLIGHT_DURATION: 1.2, configured: false, local: false, csrf: '', me: null, lifetimePoints: 0, locale: null, blocks: [], planets: [], lobby: null, incoming: [], shotResults: [], error: '', _timer: null, _pendingShots: [], _pollInFlight: false, _flushPending: false, _lastPollAt: 0, _getPayload: null, _flights: [], _lastStatus: null, onChange: null, onGameStart: null, onIncoming: null, onFinished: null, onLobbyReturn: null }; Online._headers = function (json) { var h = { 'Accept': 'application/json' }; if (json) { h['Content-Type'] = 'application/json'; } if (this.csrf) { h['X-CSRF-Token'] = this.csrf; } return h; }; Online._apply = function (data) { if (!data) { return; } if (typeof data.configured === 'boolean') { this.configured = data.configured; } if (typeof data.local === 'boolean') { this.local = data.local; } if (data.csrf) { this.csrf = data.csrf; } if (data.me !== undefined) { this.me = data.me; } if (data.lobby !== undefined) { this.lobby = data.lobby; } if (data.incoming) { this.incoming = data.incoming; } if (data.shot_results) { this.shotResults = data.shot_results; } if (data.miss_chance_default != null) { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; } if (data.flight_duration != null) { this.FLIGHT_DURATION = data.flight_duration; } if (data.error) { this.error = data.error; } else if (data.ok) { this.error = ''; } if (data.lifetime_points != null) { this.lifetimePoints = data.lifetime_points; } if (data.locale !== undefined) { this.locale = data.locale; } if (data.last_planet !== undefined) { this.lastPlanet = data.last_planet; } if (data.blocks) { this.blocks = data.blocks; } if (data.planets) { this.planets = data.planets; if (typeof Planet !== 'undefined' && Planet.setCustomPlanets) { Planet.setCustomPlanets(data.planets); } } if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet) { for (var i = 0; i < data.lobby.players.length; i++) { if (data.lobby.players[i].planet) { Planet.rememberPlanet(data.lobby.players[i].planet); } } } }; Online.request = function (action, body) { var self = this; var isGet = action === 'me' || action === ''; var url = 'api.php?action=' + encodeURIComponent(action || 'me'); var opts = { method: isGet && !body ? 'GET' : 'POST', credentials: 'same-origin', headers: this._headers(!!body || !isGet) }; if (opts.method === 'POST') { var payload = body ? Object.assign({ action: action }, body) : { action: action }; opts.body = JSON.stringify(payload); } return fetch(url, opts).then(function (res) { return res.json().then(function (data) { data = data || {}; if (!res.ok && !data.error) { data.error = (typeof I18n !== 'undefined' ? I18n.t('error.serverStatus', { status: res.status }) : ('De server gaf ' + res.status)); data.ok = false; } self._apply(data); return data; }, function () { var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') }; self.error = fail.error; return fail; }); }).catch(function (err) { var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') }; self.error = fail.error; return fail; }); }; Online.refresh = function () { return this.request('me'); }; Online.testLogin = function (who) { return this.request('test_login', { user: who }); }; Online.createLobby = function (planetId) { return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.joinLobby = function (code, planetId) { return this.request('lobby_join', { code: code, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.setPlanet = function (planetId) { return this.request('lobby_set_planet', { planet_id: planetId }); }; Online.playBegin = function (mode) { return this.request('play_begin', { mode: mode || 'solo' }); }; Online.playFinish = function (token, score) { return this.request('play_finish', { token: token, score: score || 0 }); }; Online.savePlanet = function (planet) { return this.request('planet_save', { planet: planet }); }; Online.deletePlanet = function (id) { return this.request('planet_delete', { id: id }); }; /** Remember the last chosen planet on the profile (t1196). */ Online.setLastPlanet = function (planetId) { this.lastPlanet = planetId; return this.request('set_last_planet', { planet_id: planetId }); }; Online.setLocale = function (locale) { return this.request('set_locale', { locale: locale }); }; Online.leaveLobby = function () { return this.request('lobby_leave'); }; Online.setReady = function (ready) { return this.request('lobby_ready', { ready: !!ready }); }; Online.startGame = function () { var self = this; var prev = this.lobby && this.lobby.status; return this.request('lobby_start').then(function (data) { self._handleTransitions(prev, data); return data; }); }; Online.queueShots = function (shots) { for (var i = 0; i < shots.length; i++) { this._pendingShots.push({ client_id: String(shots[i].id), color: shots[i].color, col: shots[i].col, y: shots[i].y }); } }; Online.poll = function (opts) { opts = opts || {}; var body = {}; if (opts.snapshot) { body.snapshot = opts.snapshot; } if (opts.score != null) { body.score = opts.score; } if (opts.eliminated) { body.eliminated = true; } if (this._pendingShots.length) { body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length); } var self = this; var prevStatus = this.lobby && this.lobby.status; this._pollInFlight = true; this._lastPollAt = Date.now(); return this.request('poll', body).then(function (data) { self._pollInFlight = false; if (self._flushPending) { self._flushPending = false; self.flushShotsSoon(); } self._handleTransitions(prevStatus, data); if (self.onChange) { self.onChange(self); } return data; }); }; Online._handleTransitions = function (prevStatus, data) { var lobby = this.lobby; var status = lobby && lobby.status; if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart) { this.onGameStart(lobby); } if (data && data.incoming && data.incoming.length && this.onIncoming) { this.onIncoming(data.incoming); } // Own outgoing results (immediate) and lobby-wide recent flights // (so every client can draw opponent and enemy-to-enemy arcs, t1125). var flights = []; if (data && data.shot_results && data.shot_results.length) { flights = flights.concat(data.shot_results); } if (data && data.shot_flights && data.shot_flights.length) { flights = flights.concat(data.shot_flights); } if (flights.length) { this.spawnFlights(flights, this._flightLocals); } if (status === 'finished' && prevStatus !== 'finished' && this.onFinished) { this.onFinished(lobby); } if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn) { this.onLobbyReturn(lobby); } }; Online.startPolling = function (getPayload) { this.stopPolling(); var self = this; this._getPayload = getPayload || null; var tick = function () { var payload = getPayload ? getPayload() : {}; self.poll(payload); }; tick(); this._timer = setInterval(tick, this.POLL_MS); }; /** Minimum gap between an extra shot flush and the previous poll (ms). */ Online.FLUSH_MIN_GAP_MS = 120; /** * Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the * in-flight poll or the min gap) or 'none' (nothing to send / not polling). */ Online.flushDecision = function (state) { if (!state || !state.polling || !(state.pending > 0)) { return 'none'; } if (state.inFlight) { return 'later'; } if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS)) { return 'later'; } return 'now'; }; /** * Send freshly cleared shots on the next possible poll instead of up to * POLL_MS later, so the server's hit/miss result (and the retarget of the * local flight) arrives in about one round trip. Network cadence only; * the server still decides hits, targets and delivery (t1181). */ Online.flushShotsSoon = function () { var self = this; var d = this.flushDecision({ polling: !!this._timer, pending: this._pendingShots.length, inFlight: this._pollInFlight, sinceLast: Date.now() - (this._lastPollAt || 0) }); if (d === 'none') { return d; } if (d === 'later') { if (this._pollInFlight) { this._flushPending = true; } else if (!this._flushTimer) { var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0))); this._flushTimer = setTimeout(function () { self._flushTimer = null; self.flushShotsSoon(); }, wait); } return d; } this.poll(this._getPayload ? this._getPayload() : {}); return d; }; Online.stopPolling = function () { if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = null; } this._flushPending = false; if (this._timer) { clearInterval(this._timer); this._timer = null; } }; /** Login from the Online screen: come back to online play (t1193). */ Online.loginUrl = function () { return 'auth.php?return=online'; }; Online.logoutUrl = function () { return 'logout.php'; }; Online.opponents = function () { if (!this.lobby || !this.lobby.players) { return []; } return this.lobby.players.filter(function (p) { return !p.is_me; }); }; Online.aliveOpponents = function () { return this.opponents().filter(function (p) { return !p.eliminated; }); }; Online.mePlayer = function () { if (!this.lobby || !this.lobby.players) { return null; } for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i]; } } return null; }; /* ---------- miniatures --------------------------------------------- */ Online.renderMinis = function (container) { if (!container) { return; } var opponents = this.opponents(); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < opponents.length; i++) { var p = opponents[i]; seen[p.id] = true; var el = existing[p.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', p.id); el.innerHTML = '
' + '' + '
'; container.appendChild(el); } var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini) ? app.miniLayout.mini : { w: 80, h: 104 }; var canvas = el.querySelector('canvas'); if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h)) { canvas.width = mz.w; canvas.height = mz.h; } if (canvas) { canvas.style.width = mz.w + 'px'; canvas.style.height = mz.h + 'px'; } el.classList.toggle('eliminated', !!p.eliminated); var hostTag = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host'; el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (' + hostTag + ')' : ''); if (p.eliminated) { var out = (typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out'; if (p.place && typeof I18n !== 'undefined') { out += ' · ' + I18n.place(p.place); } else if (p.place) { out += ' · ' + p.place; } el.querySelector('.mini-meta').textContent = out; } else { el.querySelector('.mini-meta').textContent = (typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: p.score || 0 }) : ('Points ' + (p.score || 0)); } this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p)); } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } if (typeof applyMinisLayout === 'function') { applyMinisLayout(); } }; var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4']; function miniColor (planet, color) { if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex) { return planet.colors[color].hex; } return MINI_COLORS[color] || '#888'; } /** * t1182: smoothed display y for an opponent's falling blocks (see * src/miniPredict.js). Returns id → y, or null without the module. */ Online._predictMini = function (p, now) { var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null; if (!MP || !p) { return null; } if (!this._miniPredict) { this._miniPredict = Object.create(null); } var st = this._miniPredict[p.id]; if (!st) { st = this._miniPredict[p.id] = MP.create(); } now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now()); MP.update(st, p.snapshot, now); if (p.eliminated) { return null; } return MP.step(st, now, MP.fallSpeedFor(p.planet)); }; Online._drawMini = function (canvas, snapshot, planet, shownY) { if (!canvas) { return; } var ctx = canvas.getContext('2d'); var w = 10; var h = 13; var tw = canvas.width / w; var th = canvas.height / h; ctx.fillStyle = '#0c1020'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.lineWidth = 1; for (var c = 0; c <= w; c++) { ctx.beginPath(); ctx.moveTo(c * tw + 0.5, 0); ctx.lineTo(c * tw + 0.5, canvas.height); ctx.stroke(); } for (var r = 0; r <= h; r++) { ctx.beginPath(); ctx.moveTo(0, r * th + 0.5); ctx.lineTo(canvas.width, r * th + 0.5); ctx.stroke(); } if (!snapshot || !snapshot.blocks) { return; } // t1123: cheap sine pulse behind blocks of nearly-full columns. if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot) { var warns = GameCore.warnColumnsFromSnapshot(snapshot); var pulse = GameCore.columnWarnPulse(); for (var wc = 0; wc < warns.length; wc++) { if (!warns[wc]) { continue; } ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')'; ctx.fillRect(wc * tw, 0, tw, canvas.height); } } var blocks = snapshot.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; var x = b.col * tw; var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y; var y = canvas.height - (by + 1) * th; if (b.state === 'locked') { ctx.fillStyle = '#3a3d4a'; } else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } else { ctx.fillStyle = miniColor(planet, b.color); } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }; Online.miniElement = function (playerId) { return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]'); }; /* ---------- flight tweens ------------------------------------------ */ function colorSpriteUrl (color, planetId) { if (color < 0) { return 'images/block-gray.png'; } var planet = null; if (typeof Planet !== 'undefined') { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); } if (planet && planet.colors && planet.colors[color] && planet.colors[color].image) { return planet.colors[color].image; } return 'images/block-gray.png'; } /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY} in viewport pixels, filled by the view just after * consumeOutgoingShots. */ Online.playerId = function () { if (typeof app !== 'undefined' && app.offline) { return 'player'; } if (this.lobby && this.lobby.players) { for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i].id; } } } return 'player'; }; /** * Classify a shot for visual treatment (t1125). * player-to-enemy, enemy-to-player, enemy-to-enemy, * player-miss, enemy-miss. */ Online.flightKind = function (fromId, targetId, miss) { var me = this.playerId(); var fromMe = !fromId || fromId === me || fromId === 'player'; if (miss) { return fromMe ? 'player-miss' : 'enemy-miss'; } if (fromMe) { return 'player-to-enemy'; } if (targetId === me || targetId === 'player') { return 'enemy-to-player'; } return 'enemy-to-enemy'; }; /** * Parabolic arc: linear in x, a rise of `height` pixels above the * chord at mid-flight (screen y grows downward, so we subtract). */ Online.arcPoint = function (start, end, u, height) { var t = u < 0 ? 0 : (u > 1 ? 1 : u); var x = start.x + (end.x - start.x) * t; var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t); return { x: x, y: y }; }; Online.arcHeight = function (start, end) { var dx = end.x - start.x; var dy = end.y - start.y; var dist = Math.sqrt(dx * dx + dy * dy); return Math.max(48, Math.min(220, dist * 0.28)); }; Online.easeInOutCubic = function (t) { if (t < 0.5) { return 4 * t * t * t; } var u = -2 * t + 2; return 1 - (u * u * u) / 2; }; /** Bounding box of the player's field in viewport pixels. */ Online.playerFieldRect = function () { var appRef = typeof app !== 'undefined' ? app : null; var canvas = appRef && appRef.scene && appRef.scene.canvas; if (canvas && canvas.getBoundingClientRect) { return canvas.getBoundingClientRect(); } if (appRef && appRef.fieldW) { return { left: appRef.fieldX, top: appRef.fieldY, right: appRef.fieldX + appRef.fieldW, bottom: appRef.fieldY + appRef.fieldH, width: appRef.fieldW, height: appRef.fieldH }; } return null; }; /** * True if (x, y) is inside the field's interior. The top edge (a few * pixels) is not interior: launch and landing may use that band. */ Online.pointInFieldInterior = function (x, y, field, slop) { if (!field) { return false; } slop = slop == null ? 6 : slop; return x > field.left + 0.5 && x < field.right - 0.5 && y > field.top + slop && y < field.bottom - 0.5; }; /** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */ Online.cubicBezier = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; var a = u * u * u; var b = 3 * u * u * t; var c = 3 * u * t * t; var d = t * t * t; return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y }; }; /** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */ Online.cubicBezierDeriv = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; return { x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x), y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y) }; }; Online.cubicBezierDeriv2 = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; // C''(t) = 6(1−t)(P2−2P1+P0) + 6t(P3−2P2+P1) return { x: 6 * u * (p2.x - 2 * p1.x + p0.x) + 6 * t * (p3.x - 2 * p2.x + p1.x), y: 6 * u * (p2.y - 2 * p1.y + p0.y) + 6 * t * (p3.y - 2 * p2.y + p1.y) }; }; /** Degree-5 Bézier. One polynomial ⇒ C^∞ on (0, 1) (t1138). */ Online.quinticBezier = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; var u2 = u * u, u3 = u2 * u, u4 = u3 * u, u5 = u4 * u; var t2 = t * t, t3 = t2 * t, t4 = t3 * t, t5 = t4 * t; var b0 = u5, b1 = 5 * u4 * t, b2 = 10 * u3 * t2; var b3 = 10 * u2 * t3, b4 = 5 * u * t4, b5 = t5; return { x: b0 * pts[0].x + b1 * pts[1].x + b2 * pts[2].x + b3 * pts[3].x + b4 * pts[4].x + b5 * pts[5].x, y: b0 * pts[0].y + b1 * pts[1].y + b2 * pts[2].y + b3 * pts[3].y + b4 * pts[4].y + b5 * pts[5].y }; }; Online.quinticBezierDeriv = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var d = []; for (var i = 0; i < 5; i++) { d.push({ x: pts[i + 1].x - pts[i].x, y: pts[i + 1].y - pts[i].y }); } var u = 1 - t; var u2 = u * u, u3 = u2 * u, u4 = u3 * u; var t2 = t * t, t3 = t2 * t, t4 = t3 * t; var b0 = u4, b1 = 4 * u3 * t, b2 = 6 * u2 * t2, b3 = 4 * u * t3, b4 = t4; return { x: 5 * (b0 * d[0].x + b1 * d[1].x + b2 * d[2].x + b3 * d[3].x + b4 * d[4].x), y: 5 * (b0 * d[0].y + b1 * d[1].y + b2 * d[2].y + b3 * d[3].y + b4 * d[4].y) }; }; Online.quinticBezierDeriv2 = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var d2 = []; for (var i = 0; i < 4; i++) { d2.push({ x: pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x, y: pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y }); } var u = 1 - t; var u2 = u * u, u3 = u2 * u; var t2 = t * t, t3 = t2 * t; var b0 = u3, b1 = 3 * u2 * t, b2 = 3 * u * t2, b3 = t3; return { x: 20 * (b0 * d2[0].x + b1 * d2[1].x + b2 * d2[2].x + b3 * d2[3].x), y: 20 * (b0 * d2[0].y + b1 * d2[1].y + b2 * d2[2].y + b3 * d2[3].y) }; }; /** Signed curvature κ = (x'y'' − y'x'') / |r'|³ (independent of parametrisation). */ Online.curvature = function (d1, d2) { var sp = d1.x * d1.x + d1.y * d1.y; var den = Math.pow(sp, 1.5); if (den < 1e-12) { return 0; } return (d1.x * d2.y - d1.y * d2.x) / den; }; /** * de Casteljau evaluation of a Bézier of any degree, plus first * and second derivatives (t1138). A single polynomial is C^∞ on (0, 1). */ Online.bezierPoint = function (pts, t) { if (!pts || !pts.length) { return { x: 0, y: 0 }; } if (t < 0) { t = 0; } if (t > 1) { t = 1; } var tmp = []; var i, k, u = 1 - t; for (i = 0; i < pts.length; i++) { tmp.push({ x: pts[i].x, y: pts[i].y }); } for (k = 1; k < pts.length; k++) { for (i = 0; i < pts.length - k; i++) { tmp[i] = { x: u * tmp[i].x + t * tmp[i + 1].x, y: u * tmp[i].y + t * tmp[i + 1].y }; } } return tmp[0]; }; Online.bezierDeriv = function (pts, t) { var n = pts ? pts.length - 1 : 0; if (n < 1) { return { x: 0, y: 0 }; } var d = []; for (var i = 0; i < n; i++) { d.push({ x: n * (pts[i + 1].x - pts[i].x), y: n * (pts[i + 1].y - pts[i].y) }); } return this.bezierPoint(d, t); }; Online.bezierDeriv2 = function (pts, t) { var n = pts ? pts.length - 1 : 0; if (n < 2) { return { x: 0, y: 0 }; } var s = n * (n - 1); var d2 = []; for (var i = 0; i < n - 1; i++) { d2.push({ x: s * (pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x), y: s * (pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y) }); } return this.bezierPoint(d2, t); }; /** * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1. * v0=v1=1 is linear (constant speed in t, no endpoint halt). */ Online.smoothParam = function (t, v0, v1) { if (t < 0) { return 0; } if (t > 1) { return 1; } if (v0 == null) { v0 = 1; } if (v1 == null) { v1 = 1; } var b = 3 - 2 * v0 - v1; var a = v0 + v1 - 2; return ((a * t + b) * t + v0) * t; }; /** * One continuous degree-7 Bézier: a single big, round, ballistic * arch (t1138). Vertical at the exit (heading up) and at the * landing (heading down). Horizontal travel sits on the apex, * above the field — a cluster of high control points on each * side keeps the hull out of the interior, with no straight * cruise and no quarter-turn kinks. C^∞ on (0, 1). * * Incoming (low mini → high field): the first mid controls stay * on the outside so the rise clears the top before crossing. * Outgoing (high exit → low mini): mid controls sit above the * target so the dive happens outside. Enemy→enemy (no field) * is a symmetric parabola behind the field. */ Online.makeAroundCurve = function (start, end, field, opts) { opts = opts || {}; if (!start) { start = { x: 0, y: 0 }; } if (!end) { end = { x: 0, y: 0 }; } var clearance = opts.clearance || 150; if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD) { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD); } if (clearance < 150) { clearance = 150; } var apexY; var left, right, top; if (field) { top = field.top; left = field.left; right = field.right; apexY = top - clearance; if (apexY < 8) { apexY = Math.max(8, top - Math.max(28, clearance * 0.5)); } } else { apexY = Math.min(start.y, end.y) - Math.max(56, clearance * 0.6); if (apexY < 8) { apexY = Math.min(start.y, end.y) - 40; } left = right = top = null; } function outsideX (x) { if (!field) { return x; } var pad = 40; if (x < left + 8) { return Math.min(x, left - pad); } if (x > right - 8) { return Math.max(x, right + pad); } return x; } var startLow = field && start.y > top + 8; var endLow = field && end.y > top + 8; var startInside = field && start.x > left + 8 && start.x < right - 8; var endInside = field && end.x > left + 8 && end.x < right - 8; // Incoming: rise on the outside first. Outgoing: cross at // the apex, then dive outside. Otherwise a symmetric arch. var kind; if (startLow && !endLow) { kind = 'in'; } else if (!startLow && endLow) { kind = 'out'; } else if (startLow && endLow) { kind = startInside ? 'out' : (endInside ? 'in' : 'sym'); } else { kind = 'sym'; } var sx = outsideX(start.x); var ex = outsideX(end.x); var rise = Math.max(80, Math.abs(start.y - apexY) * 0.35); var P0 = { x: start.x, y: start.y }; var P1 = { x: start.x, y: start.y - rise }; var P2, P3, P4, P5; var P6 = { x: end.x, y: apexY }; var P7 = { x: end.x, y: end.y }; if (kind === 'in') { P2 = { x: sx, y: apexY }; P3 = { x: sx, y: apexY }; P4 = { x: sx + (ex - sx) * 0.5, y: apexY }; P5 = { x: sx + (ex - sx) * 0.85, y: apexY }; } else if (kind === 'out') { P2 = { x: start.x, y: apexY }; P3 = { x: sx + (ex - sx) * 0.55, y: apexY }; P4 = { x: ex, y: apexY }; P5 = { x: end.x, y: apexY }; } else { P2 = { x: sx, y: apexY }; P3 = { x: sx + (ex - sx) * 0.35, y: apexY }; P4 = { x: sx + (ex - sx) * 0.65, y: apexY }; P5 = { x: ex, y: apexY }; } var pts = [P0, P1, P2, P3, P4, P5, P6, P7]; var curve = { degree: 7, pts: pts, p0: P0, p3: P7, apexY: apexY, kind: kind, arcLength: true }; this._buildArcLut(curve); return curve; }; Online._evalPoly = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 2) { return this.bezierPoint(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, t); } if (curve && curve.segments) { var n = curve.segments.length; var at = (t < 0 ? 0 : (t > 1 ? 1 : t)) * n; var i = Math.floor(at); if (i >= n) { i = n - 1; } var s = curve.segments[i]; return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at - i); } return { x: 0, y: 0 }; }; Online._evalPolyDeriv = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 2) { return this.bezierDeriv(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezierDeriv(curve.p0, curve.p1, curve.p2, curve.p3, t); } return { x: 0, y: 0 }; }; Online._evalPolyDeriv2 = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 3) { return this.bezierDeriv2(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezierDeriv2(curve.p0, curve.p1, curve.p2, curve.p3, t); } return { x: 0, y: 0 }; }; /** Cumulative-length LUT so u is a fraction of arc length (t1138). */ Online._buildArcLut = function (curve, steps) { steps = steps || 48; var acc = [0]; var prev = this._evalPoly(curve, 0); for (var i = 1; i <= steps; i++) { var p = this._evalPoly(curve, i / steps); acc.push(acc[i - 1] + Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y))); prev = p; } curve.lutS = acc; curve.lutN = steps; curve.totalLen = Math.max(acc[steps], 1); return curve; }; /** Polynomial t whose arc length fraction is u. */ Online._arcT = function (curve, u) { if (u <= 0) { return 0; } if (u >= 1) { return 1; } if (!curve.lutS) { this._buildArcLut(curve); } var s = u * curve.totalLen; var acc = curve.lutS; var n = curve.lutN; var lo = 0; var hi = n; while (lo < hi) { var mid = (lo + hi) >> 1; if (acc[mid] < s) { lo = mid + 1; } else { hi = mid; } } var i = lo; if (i <= 0) { return 0; } var s0 = acc[i - 1]; var s1 = acc[i]; var f = (s1 > s0) ? (s - s0) / (s1 - s0) : 0; return ((i - 1) + f) / n; }; Online._measureCurve = function (curve) { if (!curve) { return curve; } if (!curve.lutS) { this._buildArcLut(curve); } return curve; }; Online._segLen = function (seg, steps) { steps = steps || 10; if (seg && seg.degree === 5) { if (!seg.lutS) { this._buildArcLut(seg, steps * 4); } return seg.totalLen; } var len = 0; var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0); for (var i = 1; i <= steps; i++) { var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps); len += Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y)); prev = p; } return Math.max(len, 1); }; /** Point at arc-length fraction u ∈ [0, 1]. */ Online.curvePoint = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); return this._evalPoly(curve, t); }; /** * dP/du under arc-length parametrisation: unit tangent × total length * (constant speed in u, direction from the polynomial). */ Online.curveDeriv = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); var d = this._evalPolyDeriv(curve, t); if (curve.arcLength !== false) { if (!curve.lutS) { this._buildArcLut(curve); } var mag = Math.sqrt(d.x * d.x + d.y * d.y); if (mag < 1e-9) { return { x: 0, y: 0 }; } var s = curve.totalLen / mag; return { x: d.x * s, y: d.y * s }; } return d; }; Online.curveDeriv2 = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); return this._evalPolyDeriv2(curve, t); }; /** Curvature at arc-length fraction u (uses polynomial t, κ is invariant). */ Online.curveCurvature = function (curve, u) { var t = curve && curve.arcLength !== false ? this._arcT(curve, u) : u; return this.curvature(this._evalPolyDeriv(curve, t), this._evalPolyDeriv2(curve, t)); }; /** * Endpoint ease rates so arrival speed ≈ fallSpeed under arc-length * parametrisation: v = (L / duration) * p'(raw). */ Online.flightEaseRates = function (curve, duration, fallPx) { if (!curve || !curve.lutS) { this._measureCurve(curve); } var L = (curve && curve.totalLen) || 400; duration = duration || this.FLIGHT_DURATION; var v1 = fallPx && L ? (fallPx * duration) / L : 0.75; if (v1 < 0.28) { v1 = 0.28; } if (v1 > 1.15) { v1 = 1.15; } var v0 = v1 + 0.2; if (v0 > 1) { v0 = 1; } if (v0 < 0.45) { v0 = 0.45; } return { v0: v0, v1: v1 }; }; Online.aroundFieldPoint = function (start, end, u, field, clearance) { var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance }; var curve = opts.curve || this.makeAroundCurve(start, end, field, opts); return this.curvePoint(curve, u); }; Online.waypointsAroundField = function (start, end, field, clearance) { var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 100 }); if (c.pts && c.pts.length) { return c.pts.slice(); } return [c.p0, c.p1, c.p2, c.p3]; }; Online.pointOnPath = function (points, u) { // Legacy polyline; new flights use cubicBezier. u = u < 0 ? 0 : (u > 1 ? 1 : u); if (!points || !points.length) { return { x: 0, y: 0 }; } if (points.length === 4 && points[0] && points[3]) { return this.cubicBezier(points[0], points[1], points[2], points[3], u); } if (points.length === 1) { return { x: points[0].x, y: points[0].y }; } var n = points.length - 1; var at = u * n; var i = Math.floor(at); if (i >= n) { i = n - 1; } var t = at - i; var a = points[i]; var b = points[i + 1]; return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; }; /** Viewport centre of a field cell (y=0 is the bottom row). */ Online.cellViewport = function (col, y, rect) { if (!rect) { var field = this.playerFieldRect(); if (!field) { return { x: 0, y: 0 }; } rect = field; } var w = rect.width != null ? rect.width : (rect.right - rect.left); var h = rect.height != null ? rect.height : (rect.bottom - rect.top); return { x: rect.left + ((col + 0.5) / 10) * w, y: rect.top + (1 - (y + 0.5) / 13) * h }; }; /** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */ Online.fieldEntry = function (col) { return this.cellViewport(col == null ? 4.5 : col, 13); }; Online.miniCellViewport = function (playerId, col, y) { var el = this.miniElement(playerId); var canvas = el && (el.querySelector ? el.querySelector('canvas') : null); var box = canvas || el; if (!box || !box.getBoundingClientRect) { return { x: window.innerWidth / 2, y: 48 }; } return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect()); }; Online._fallSpeedPx = function (field, duration) { var px = 40; if (field && field.height) { px = field.height / 13; } else if (typeof app !== 'undefined' && app.tile) { px = app.tile; } var cells = 13 / 3; if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed) { cells = app.planet.fallSpeed; } duration = duration || this.FLIGHT_DURATION; // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135). return (cells * px * duration) / 3; }; Online.rememberLandCol = function (id, col) { if (id == null || col == null || !isFinite(col)) { return; } if (!this._pendingLandCol) { this._pendingLandCol = Object.create(null); } this._pendingLandCol[String(id)] = col | 0; }; /** Resolve the landing column for an incoming shot (t1126). */ Online.takeLandCol = function (incoming) { if (!incoming) { return null; } if (incoming.land_col != null && isFinite(incoming.land_col)) { return incoming.land_col | 0; } if (!this._pendingLandCol) { return null; } var keys = []; if (incoming.id != null) { keys.push(String(incoming.id)); } if (incoming.client_id) { keys.push(String(incoming.client_id)); } for (var i = 0; i < keys.length; i++) { if (this._pendingLandCol[keys[i]] != null) { return this._pendingLandCol[keys[i]]; } } return null; }; Online._miniCellSize = function (playerId) { var el = this.miniElement(playerId); var canvas = el && el.querySelector('canvas'); if (canvas) { var r = canvas.getBoundingClientRect(); return Math.max(6, r.width / 10); } return 10; }; Online._fullTileSize = function () { if (typeof app !== 'undefined' && app.tile) { return app.tile; } return 40; }; Online._miniAnchor = function (playerId, dir) { var el = this.miniElement(playerId); var canvas = el && (el.querySelector ? el.querySelector('canvas') : null); var box = canvas || el; if (!box) { return { x: window.innerWidth / 2, y: 48 }; } var r = box.getBoundingClientRect(); if (dir === 'out') { return { x: r.left + r.width / 2, y: r.top + 4 }; } return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }; Online._fieldTop = function (col) { return this.fieldEntry(col); }; /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY, from_id} in viewport pixels. * * Visual-only: a smooth cubic that leaves the real cell, arcs around * the field, and dives into the landing column at the spawn pose * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn * behind the player's field. A late-seen flight starts mid-arc via `age`. */ Online.spawnFlights = function (results, locals) { locals = locals || this._flightLocals || {}; var front = document.getElementById('flights'); var back = document.getElementById('flights-back') || front; if (!front) { return; } if (!this._flightSeen) { this._flightSeen = Object.create(null); } if (!this._previewIds) { this._previewIds = Object.create(null); } var now = performance.now(); var full = this._fullTileSize(); for (var i = 0; i < results.length; i++) { var r = results[i]; var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i))); // Own shot already flying locally since the clear (t1181): // pick it up at its current pose and fly on to the real target. var cid = r.client_id != null ? String(r.client_id) : null; if (cid && this._previewIds[cid] && this._isOwnShot(r)) { var own = this._findFlight(cid); this._flightSeen[sid] = now; if (own) { this.retargetFlight(own, r, locals[cid] || {}, now); } continue; } if (this._flightSeen[sid]) { if (this._previewIds[sid]) { var existing = this._findFlight(sid); if (existing) { var meta0 = locals[r.client_id] || locals[sid] || {}; this.retargetFlight(existing, r, meta0, now); } } continue; } this._flightSeen[sid] = now; var meta = locals[r.client_id] || locals[sid] || {}; var fromId = r.from_id || r.from_user || meta.from_id || null; var targetId = r.target_id != null ? r.target_id : r.to_user; var miss = !!r.miss; var kind = this.flightKind(fromId, targetId, miss); var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000; if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration) { continue; } var landCol = null; if (r.land_col != null && isFinite(r.land_col)) { landCol = r.land_col | 0; } else if (meta.land_col != null && isFinite(meta.land_col)) { landCol = meta.land_col | 0; } else if (kind === 'enemy-to-player' && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn) { landCol = app.core.pickGarbageColumn(); } if (landCol != null) { this.rememberLandCol(sid, landCol); if (r.client_id) { this.rememberLandCol(r.client_id, landCol); } } var startCol = meta.col != null ? meta.col : r.col; var startY = meta.y != null ? meta.y : r.y; var start; if (meta.startX != null && isFinite(meta.startX)) { start = { x: meta.startX, y: meta.startY }; } else if (kind === 'player-to-enemy' || kind === 'player-miss') { start = this._flightStart(startCol, startY); } else if (startCol != null || startY != null) { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 13); } else { start = this._miniAnchor(fromId, 'out'); } var end; if (miss) { end = this._missEnd(start, kind === 'enemy-miss'); } else if (kind === 'enemy-to-player') { end = this.fieldEntry(landCol != null ? landCol : 4.5); } else { end = this._targetEnd(targetId, start, landCol); } // Hits are ingested as grey garbage; draw them grey (t1130). // Misses keep the sender's colour — nothing is received. var flightColor = miss ? (r.color != null ? r.color : meta.color) : -1; var startScale; var endScale; var mini = this._miniCellSize(fromId || targetId) / full; if (mini < 0.12) { mini = 0.2; } if (kind === 'player-to-enemy') { startScale = 1; endScale = mini; } else if (kind === 'enemy-to-player') { startScale = mini; endScale = 1; } else if (kind === 'enemy-to-enemy') { startScale = mini; endScale = mini; } else if (kind === 'enemy-miss') { startScale = mini; endScale = 0; } else { startScale = 1; endScale = 0; } var layer = (kind === 'enemy-to-enemy' && back) ? back : front; var el = document.createElement('img'); el.src = colorSpriteUrl(flightColor); el.alt = ''; el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : ''); el.style.width = full + 'px'; el.style.height = full + 'px'; layer.appendChild(el); // A flight seen late (poll delay) still starts at the sender's // field and plays the whole arc, just a bit faster, so it lands // about when the server delivers it — never a mid-arc pop-in (t1181). var t0 = now; duration = this.lateFlightDuration(r.age, duration); var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35)) : this.arcHeight(start, end); var field = this.playerFieldRect(); var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy'); var clearance = Math.max(150, height * 0.55); var endSpeed = this._fallSpeedPx(field, duration / 1000); var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, { clearance: clearance }); var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null; this._flights.push({ el: el, start: start, end: end, ctrl: miss ? this._missCtrl(start, end) : null, height: height, t0: t0, duration: duration, easeRates: easeRates, spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120), miss: miss, kind: kind, startScale: startScale, endScale: endScale, angle: 0, id: sid, landCol: landCol, field: field, curve: curve, color: flightColor }); } this._flightLocals = {}; }; /** Shortest share of the normal flight a late-seen flight may get. */ Online.LATE_MIN_SHARE = 0.5; /** Duration (ms) for a flight first seen `age` seconds after it was fired. */ Online.lateFlightDuration = function (age, duration) { if (age == null || !isFinite(age) || age <= 0) { return duration; } return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000); }; /** Remaining duration (ms) after a local preview has flown `elapsedMs`. */ Online.retargetDuration = function (elapsedMs, duration) { if (!(elapsedMs > 0)) { return duration; } return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs); }; Online._isOwnShot = function (r) { var mine = this.me && this.me.id; var from = r.from_id || r.from_user || null; return !from || (mine != null && String(from) === String(mine)); }; /** * Sender side (t1181): start the flight the moment the block leaves the * field, before any server round trip. It rises out of the exit cell; * the poll answer retargets it (hit → opponent mini, miss → off-screen). */ Online.startLocalShot = function (shot, start) { if (!shot || !start) { return null; } return this.previewExit({ id: shot.id, col: shot.col, y: shot.y, vy: shot.vy, color: shot.color, start: start, from_id: null }); }; Online.rememberFlightLocal = function (shot, startX, startY) { if (!this._flightLocals) { this._flightLocals = {}; } this._flightLocals[String(shot.id)] = { col: shot.col, y: shot.y, color: shot.color, startX: startX, startY: startY, from_id: shot.from_id, land_col: shot.land_col, vy: shot.vy }; }; Online._flightStart = function (col, y) { if (y == null || !isFinite(y)) { y = 13; } return this.cellViewport(col == null ? 4.5 : col, y); }; Online._targetEnd = function (targetId, start, col) { var el = targetId && this.miniElement(targetId); if (el) { // Slightly inside the mini, in the landing column (t1135). return this.miniCellViewport(targetId, col, 12); } return { x: start.x + (Math.random() - 0.5) * 80, y: 40 }; }; Online._missEnd = function (start, fromMini) { var w = window.innerWidth || 800; var outward; if (start.x < w * 0.4) { outward = -(80 + Math.random() * w * 0.25); } else if (start.x > w * 0.6) { outward = (80 + Math.random() * w * 0.25); } else { outward = (Math.random() * 2 - 1) * w * 0.35; } var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220); return { x: start.x + outward, y: start.y - lift }; }; Online._missCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160, y: Math.min(start.y, end.y) - 40 - Math.random() * 80 }; }; Online._hitCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40, y: (start.y + end.y) / 2 - 30 }; }; Online._findFlight = function (sid) { sid = String(sid); if (!this._flights) { return null; } for (var i = 0; i < this._flights.length; i++) { if (String(this._flights[i].id) === sid) { return this._flights[i]; } } return null; }; /** * True once a block has really left the field, matching cullOffTop * (y ≥ height, default 13). Used so an arc never starts for a * rocket that only peaked near the top and fell back (t1137). */ Online.EXIT_Y = 13; Online.hasLeftTheField = function (y, height) { height = height == null ? this.EXIT_Y : height; return y != null && isFinite(y) && y >= height - 1e-9; }; /** * Start a flight only at the true exit (y ≥ 13). Callers that pass * a rocket still on the field are ignored, so a fallback never * shows a phantom arc (t1137). The start pose is the exit cell, * continuing upward; retargetFlight aims it at the real target * if a preview was used in the same frame as cull. */ Online.previewExit = function (info) { if (!info || info.id == null) { return null; } if (!this.hasLeftTheField(info.y)) { return null; } var sid = String(info.id); if (!this._flights) { this._flights = []; } if (!this._flightSeen) { this._flightSeen = Object.create(null); } if (!this._previewIds) { this._previewIds = Object.create(null); } if (this._previewIds[sid] || this._flightSeen[sid]) { return; } var front = document.getElementById('flights'); if (!front || !info.start) { return; } var start = info.start; var field = this.playerFieldRect(); var clearance = 80; if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD) { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); } var apexY = (field ? field.top : start.y) - clearance; if (apexY < 8) { apexY = Math.max(8, start.y - 80); } var end = { x: start.x, y: apexY }; var duration = this.FLIGHT_DURATION * 1000; var full = this._fullTileSize(); var el = document.createElement('img'); el.src = colorSpriteUrl(info.color); el.alt = ''; el.className = 'flight'; el.style.width = full + 'px'; el.style.height = full + 'px'; front.appendChild(el); var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION); var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, { clearance: clearance }); var easeRates = this.flightEaseRates(curve, this.FLIGHT_DURATION, endSpeed); var now = performance.now(); var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1; if (mini < 0.12) { mini = 0.2; } this._flights.push({ el: el, start: start, end: end, ctrl: null, height: clearance, t0: now, duration: duration, spin: (Math.random() * 2 - 1) * 90, miss: false, kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy', startScale: mini, endScale: mini, angle: 0, id: sid, landCol: null, field: field, curve: curve, easeRates: easeRates, preview: true, color: info.color, from_id: info.from_id || null }); this._previewIds[sid] = true; this._flightSeen[sid] = now; return true; }; /** True while a field sprite should stay hidden — the flight is its visual. */ Online.hasExitVisual = function (id) { if (id == null) { return false; } var sid = String(id); if (this._previewIds && this._previewIds[sid]) { return true; } var f = this._findFlight(sid); if (!f || f.miss) { return false; } var raw = (performance.now() - f.t0) / f.duration; return raw < 0.4; }; /** * Once the shot is scored, pick up the preview at its current pose * and fly the rest of the way to the real end (no jump). */ Online.retargetFlight = function (f, r, meta, now) { now = now || performance.now(); meta = meta || {}; var raw = (now - f.t0) / f.duration; if (raw < 0) { raw = 0; } if (raw > 0.95) { raw = 0.95; } var u = this.smoothParam(raw, 0.9, 0.9); var pt = f.curve ? this.curvePoint(f.curve, u) : { x: f.start.x, y: f.start.y }; var curScale = f.startScale + (f.endScale - f.startScale) * u; var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null; var targetId = r.target_id != null ? r.target_id : r.to_user; var miss = !!r.miss; var kind = this.flightKind(fromId, targetId, miss); var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000; if (f.preview) { duration = this.retargetDuration(now - f.t0, duration); } var landCol = null; if (r.land_col != null && isFinite(r.land_col)) { landCol = r.land_col | 0; } else if (meta.land_col != null && isFinite(meta.land_col)) { landCol = meta.land_col | 0; } else if (f.landCol != null) { landCol = f.landCol; } if (landCol != null) { this.rememberLandCol(String(f.id), landCol); } var end; if (miss) { end = this._missEnd(pt, kind === 'enemy-miss'); } else if (kind === 'enemy-to-player') { end = this.fieldEntry(landCol != null ? landCol : 4.5); } else { end = this._targetEnd(targetId, pt, landCol); } var flightColor = miss ? (r.color != null ? r.color : meta.color) : -1; if (f.el && flightColor !== f.color) { f.el.src = colorSpriteUrl(flightColor); } var full = this._fullTileSize(); var mini = this._miniCellSize(fromId || targetId) / full; if (mini < 0.12) { mini = 0.2; } var endScale; if (kind === 'player-to-enemy') { endScale = mini; } else if (kind === 'enemy-to-player') { endScale = 1; } else if (kind === 'enemy-to-enemy') { endScale = mini; } else { endScale = 0; } var field = this.playerFieldRect(); var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy'); var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35)) : this.arcHeight(pt, end); var clearance = Math.max(150, height * 0.55); var endSpeed = this._fallSpeedPx(field, duration / 1000); var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, { clearance: clearance }); var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null; f.start = pt; f.end = end; f.t0 = now; f.duration = duration; f.curve = curve; f.easeRates = easeRates; f.ctrl = miss ? this._missCtrl(pt, end) : null; f.height = height; f.miss = miss; f.kind = kind; f.startScale = curScale; f.endScale = endScale; f.landCol = landCol; f.field = field; f.preview = false; f.color = flightColor; f.from_id = fromId; if (this._previewIds) { delete this._previewIds[String(f.id)]; } if (kind === 'enemy-to-enemy' && f.el) { var back = document.getElementById('flights-back'); if (back && f.el.parentNode !== back) { f.el.className = 'flight flight-behind'; back.appendChild(f.el); } } }; /** Point and (optional) derivative of a flight at parameter u. */ Online.flightPointAt = function (f, u) { if (!f) { return { x: 0, y: 0 }; } if (f.curve) { return this.curvePoint(f.curve, u); } if (f.miss && f.ctrl) { var e = u; var mt = 1 - e; return { x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x, y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y }; } return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); }; Online.pointAllowedOnArc = function (p, field, start, end, slop) { if (!this.pointInFieldInterior(p.x, p.y, field, slop)) { return true; } if (!field) { return true; } var w = (field.right - field.left) / 10; var corridor = w * 0.7; if (start && Math.abs(p.x - start.x) <= corridor) { return true; } if (end && Math.abs(p.x - end.x) <= corridor) { return true; } return false; }; /** How long a local preview may wait at its apex for the server (ms). */ Online.PREVIEW_HOLD_MS = 2500; Online.tickFlights = function (now) { now = now || performance.now(); var leftover = []; for (var i = 0; i < this._flights.length; i++) { var f = this._flights[i]; var raw = (now - f.t0) / f.duration; if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS) { raw = 0.999; } if (raw >= 1) { if (f.el && f.el.parentNode) { f.el.parentNode.removeChild(f.el); } if (this._previewIds) { delete this._previewIds[String(f.id)]; } continue; } if (raw < 0) { raw = 0; } // Non-zero endpoint speed so the handoff matches fallSpeed (t1135/t1138). var v0 = (f.easeRates && f.easeRates.v0 != null) ? f.easeRates.v0 : 0.85; var v1 = (f.easeRates && f.easeRates.v1 != null) ? f.easeRates.v1 : 0.85; var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, v0, v1); var x, y; if (f.miss && f.ctrl) { var e = raw * raw; var mt = 1 - e; x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x; y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y; } else if (f.curve) { var pt = this.curvePoint(f.curve, u); x = pt.x; y = pt.y; } else { var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); x = pt.x; y = pt.y; } var scale = f.startScale + (f.endScale - f.startScale) * u; if (f.miss) { var fadeU = raw * raw; scale = f.startScale * (1 - fadeU); } var angle = f.angle + f.spin * raw; f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate(' + angle + 'deg) scale(' + scale + ')'; f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1'; leftover.push(f); } this._flights = leftover; if (this._flightSeen) { var cutoff = now - 8000; var ids = Object.keys(this._flightSeen); for (var k = 0; k < ids.length; k++) { if (this._flightSeen[ids[k]] < cutoff) { delete this._flightSeen[ids[k]]; } } } }; Online.clearFlights = function () { for (var i = 0; i < this._flights.length; i++) { var el = this._flights[i].el; if (el && el.parentNode) { el.parentNode.removeChild(el); } } this._flights = []; this._flightLocals = {}; this._flightSeen = Object.create(null); this._pendingLandCol = Object.create(null); this._previewIds = Object.create(null); this._miniPredict = Object.create(null); }; if (typeof globalThis !== 'undefined') { globalThis.Online = Online; } if (typeof module !== 'undefined' && module.exports) { module.exports = Online; }