BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 53.8 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lifetimePoints: 0,
18 locale: null,
19 localeExplicit: false,
20 authLocale: null,
21 blocks: [],
22 planets: [],
23 lobby: null,
24 incoming: [],
25 shotResults: [],
26 error: '',
27 _timer: null,
28 _pendingShots: [],
29 _pollInFlight: false,
30 _flushPending: false,
31 _lastPollAt: 0,
32 _getPayload: null,
33 _flights: [],
34 _lastStatus: null,
35 onChange: null,
36 onGameStart: null,
37 onIncoming: null,
38 onFinished: null,
39 onLobbyReturn: null
40};
41
42Online._headers = function (json)
43{
44 var h = { 'Accept': 'application/json' };
45 if (json)
46 { h['Content-Type'] = 'application/json'; }
47 if (this.csrf)
48 { h['X-CSRF-Token'] = this.csrf; }
49 return h;
50};
51
52Online._apply = function (data)
53{
54 if (!data)
55 { return; }
56 if (typeof data.configured === 'boolean')
57 { this.configured = data.configured; }
58 if (typeof data.local === 'boolean')
59 { this.local = data.local; }
60 if (data.csrf)
61 { this.csrf = data.csrf; }
62 if (data.me !== undefined)
63 { this.me = data.me; }
64 if (data.lobby !== undefined)
65 { this.lobby = data.lobby; }
66 if (data.incoming)
67 { this.incoming = data.incoming; }
68 if (data.shot_results)
69 { this.shotResults = data.shot_results; }
70 if (data.miss_chance_default != null)
71 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
72 if (data.flight_duration != null)
73 { this.FLIGHT_DURATION = data.flight_duration; }
74 if (data.error)
75 { this.error = data.error; }
76 else if (data.ok)
77 { this.error = ''; }
78 if (data.lifetime_points != null)
79 { this.lifetimePoints = data.lifetime_points; }
80 if (data.locale !== undefined)
81 { this.locale = data.locale; }
82 if (data.locale_explicit !== undefined)
83 { this.localeExplicit = !!data.locale_explicit; }
84 if (data.auth_locale !== undefined)
85 { this.authLocale = data.auth_locale; }
86 if (data.last_planet !== undefined)
87 { this.lastPlanet = data.last_planet; }
88 if (data.blocks)
89 { this.blocks = data.blocks; }
90 if (data.planets)
91 {
92 this.planets = data.planets;
93 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
94 { Planet.setCustomPlanets(data.planets); }
95 }
96 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
97 {
98 for (var i = 0; i < data.lobby.players.length; i++)
99 {
100 if (data.lobby.players[i].planet)
101 { Planet.rememberPlanet(data.lobby.players[i].planet); }
102 }
103 }
104};
105
106Online.request = function (action, body)
107{
108 var self = this;
109 var isGet = action === 'me' || action === '';
110 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
111 var opts = {
112 method: isGet && !body ? 'GET' : 'POST',
113 credentials: 'same-origin',
114 headers: this._headers(!!body || !isGet)
115 };
116 if (opts.method === 'POST')
117 {
118 var payload = body ? Object.assign({ action: action }, body) : { action: action };
119 opts.body = JSON.stringify(payload);
120 }
121 return fetch(url, opts).then(function (res)
122 {
123 return res.json().then(function (data)
124 {
125 data = data || {};
126 if (!res.ok && !data.error)
127 { data.error = (typeof I18n !== 'undefined' ? I18n.t('error.serverStatus', { status: res.status }) : ('De server gaf ' + res.status)); data.ok = false; }
128 self._apply(data);
129 return data;
130 }, function ()
131 {
132 var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') };
133 self.error = fail.error;
134 return fail;
135 });
136 }).catch(function (err)
137 {
138 var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') };
139 self.error = fail.error;
140 return fail;
141 });
142};
143
144Online.refresh = function ()
145{
146 return this.request('me');
147};
148
149Online.testLogin = function (who)
150{
151 return this.request('test_login', { user: who });
152};
153
154Online.createLobby = function (planetId)
155{
156 return this.request('lobby_create', {
157 miss_chance: this.DEFAULT_MISS_CHANCE,
158 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
159 });
160};
161
162Online.joinLobby = function (code, planetId)
163{
164 return this.request('lobby_join', {
165 code: code,
166 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
167 });
168};
169
170Online.setPlanet = function (planetId)
171{
172 return this.request('lobby_set_planet', { planet_id: planetId });
173};
174
175Online.playBegin = function (mode)
176{
177 return this.request('play_begin', { mode: mode || 'solo' });
178};
179
180Online.playFinish = function (token, score)
181{
182 return this.request('play_finish', { token: token, score: score || 0 });
183};
184
185Online.savePlanet = function (planet)
186{
187 return this.request('planet_save', { planet: planet });
188};
189
190Online.deletePlanet = function (id)
191{
192 return this.request('planet_delete', { id: id });
193};
194
195/** Remember the last chosen planet on the profile (t1196). */
196Online.setLastPlanet = function (planetId)
197{
198 this.lastPlanet = planetId;
199 return this.request('set_last_planet', { planet_id: planetId });
200};
201
202Online.setLocale = function (locale)
203{
204 return this.request('set_locale', { locale: locale });
205};
206
207Online.leaveLobby = function ()
208{
209 return this.request('lobby_leave');
210};
211
212Online.setReady = function (ready)
213{
214 return this.request('lobby_ready', { ready: !!ready });
215};
216
217Online.startGame = function ()
218{
219 var self = this;
220 var prev = this.lobby && this.lobby.status;
221 return this.request('lobby_start').then(function (data)
222 {
223 self._handleTransitions(prev, data);
224 return data;
225 });
226};
227
228Online.queueShots = function (shots)
229{
230 for (var i = 0; i < shots.length; i++)
231 {
232 this._pendingShots.push({
233 client_id: String(shots[i].id),
234 color: shots[i].color,
235 col: shots[i].col,
236 y: shots[i].y
237 });
238 }
239};
240
241Online.poll = function (opts)
242{
243 opts = opts || {};
244 var body = {};
245 if (opts.snapshot)
246 { body.snapshot = opts.snapshot; }
247 if (opts.score != null)
248 { body.score = opts.score; }
249 if (opts.eliminated)
250 { body.eliminated = true; }
251 if (this._pendingShots.length)
252 {
253 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
254 }
255 var self = this;
256 var prevStatus = this.lobby && this.lobby.status;
257 this._pollInFlight = true;
258 this._lastPollAt = Date.now();
259 return this.request('poll', body).then(function (data)
260 {
261 self._pollInFlight = false;
262 if (self._flushPending)
263 {
264 self._flushPending = false;
265 self.flushShotsSoon();
266 }
267 self._handleTransitions(prevStatus, data);
268 if (self.onChange)
269 { self.onChange(self); }
270 return data;
271 });
272};
273
274Online._handleTransitions = function (prevStatus, data)
275{
276 var lobby = this.lobby;
277 var status = lobby && lobby.status;
278 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
279 { this.onGameStart(lobby); }
280 if (data && data.incoming && data.incoming.length && this.onIncoming)
281 { this.onIncoming(data.incoming); }
282 // Own outgoing results (immediate) and lobby-wide recent flights
283 // (so every client can draw opponent and enemy-to-enemy arcs, t1125).
284 var flights = [];
285 if (data && data.shot_results && data.shot_results.length)
286 { flights = flights.concat(data.shot_results); }
287 if (data && data.shot_flights && data.shot_flights.length)
288 { flights = flights.concat(data.shot_flights); }
289 if (flights.length)
290 { this.spawnFlights(flights, this._flightLocals); }
291 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
292 { this.onFinished(lobby); }
293 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
294 { this.onLobbyReturn(lobby); }
295};
296
297Online.startPolling = function (getPayload)
298{
299 this.stopPolling();
300 var self = this;
301 this._getPayload = getPayload || null;
302 var tick = function ()
303 {
304 var payload = getPayload ? getPayload() : {};
305 self.poll(payload);
306 };
307 tick();
308 this._timer = setInterval(tick, this.POLL_MS);
309};
310
311/** Minimum gap between an extra shot flush and the previous poll (ms). */
312Online.FLUSH_MIN_GAP_MS = 120;
313
314/**
315 * Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the
316 * in-flight poll or the min gap) or 'none' (nothing to send / not polling).
317 */
318Online.flushDecision = function (state)
319{
320 if (!state || !state.polling || !(state.pending > 0))
321 { return 'none'; }
322 if (state.inFlight)
323 { return 'later'; }
324 if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))
325 { return 'later'; }
326 return 'now';
327};
328
329/**
330 * Send freshly cleared shots on the next possible poll instead of up to
331 * POLL_MS later, so the server's hit/miss result (and the retarget of the
332 * local flight) arrives in about one round trip. Network cadence only;
333 * the server still decides hits, targets and delivery (t1181).
334 */
335Online.flushShotsSoon = function ()
336{
337 var self = this;
338 var d = this.flushDecision({
339 polling: !!this._timer,
340 pending: this._pendingShots.length,
341 inFlight: this._pollInFlight,
342 sinceLast: Date.now() - (this._lastPollAt || 0)
343 });
344 if (d === 'none')
345 { return d; }
346 if (d === 'later')
347 {
348 if (this._pollInFlight)
349 { this._flushPending = true; }
350 else if (!this._flushTimer)
351 {
352 var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));
353 this._flushTimer = setTimeout(function ()
354 {
355 self._flushTimer = null;
356 self.flushShotsSoon();
357 }, wait);
358 }
359 return d;
360 }
361 this.poll(this._getPayload ? this._getPayload() : {});
362 return d;
363};
364
365Online.stopPolling = function ()
366{
367 if (this._flushTimer)
368 {
369 clearTimeout(this._flushTimer);
370 this._flushTimer = null;
371 }
372 this._flushPending = false;
373 if (this._timer)
374 {
375 clearInterval(this._timer);
376 this._timer = null;
377 }
378};
379
380/** Login from the Online screen: come back to online play (t1193). */
381Online.loginUrl = function ()
382{
383 return 'auth.php?return=online';
384};
385
386/** t1247: global or friends leaderboard (GET, no CSRF). */
387Online.leaderboard = function (scope)
388{
389 var self = this;
390 var url = 'api.php?action=leaderboard&scope=' + encodeURIComponent(scope === 'friends' ? 'friends' : 'global');
391 return fetch(url, {
392 method: 'GET',
393 credentials: 'same-origin',
394 headers: this._headers(false)
395 }).then(function (res)
396 {
397 return res.json().then(function (data)
398 {
399 data = data || {};
400 if (!res.ok && !data.error)
401 {
402 data.error = (typeof I18n !== 'undefined'
403 ? I18n.t('error.serverStatus', { status: res.status })
404 : ('De server gaf ' + res.status));
405 data.ok = false;
406 }
407 return data;
408 }, function ()
409 {
410 return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') };
411 });
412 }).catch(function ()
413 {
414 return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') };
415 });
416};
417
418Online.logoutUrl = function ()
419{
420 return 'logout.php';
421};
422
423Online.opponents = function ()
424{
425 if (!this.lobby || !this.lobby.players)
426 { return []; }
427 return this.lobby.players.filter(function (p) { return !p.is_me; });
428};
429
430Online.aliveOpponents = function ()
431{
432 return this.opponents().filter(function (p) { return !p.eliminated; });
433};
434
435Online.mePlayer = function ()
436{
437 if (!this.lobby || !this.lobby.players)
438 { return null; }
439 for (var i = 0; i < this.lobby.players.length; i++)
440 {
441 if (this.lobby.players[i].is_me)
442 { return this.lobby.players[i]; }
443 }
444 return null;
445};
446
447/* ---------- miniatures --------------------------------------------- */
448
449Online.renderMinis = function (container)
450{
451 if (!container)
452 { return; }
453 var opponents = this.opponents();
454 var existing = {};
455 var kids = container.querySelectorAll('[data-player]');
456 for (var i = 0; i < kids.length; i++)
457 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
458
459 var seen = Object.create(null);
460 for (var i = 0; i < opponents.length; i++)
461 {
462 var p = opponents[i];
463 seen[p.id] = true;
464 var el = existing[p.id];
465 if (!el)
466 {
467 el = document.createElement('div');
468 el.className = 'mini';
469 el.setAttribute('data-player', p.id);
470 el.innerHTML = '<div class="mini-name"></div>'
471 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
472 + '<div class="mini-meta"></div>';
473 container.appendChild(el);
474 }
475 var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini)
476 ? app.miniLayout.mini
477 : { w: 80, h: 104 };
478 var canvas = el.querySelector('canvas');
479 if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h))
480 {
481 canvas.width = mz.w;
482 canvas.height = mz.h;
483 }
484 if (canvas)
485 {
486 canvas.style.width = mz.w + 'px';
487 canvas.style.height = mz.h + 'px';
488 }
489 el.classList.toggle('eliminated', !!p.eliminated);
490 var hostTag = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
491 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (' + hostTag + ')' : '');
492 if (p.eliminated)
493 {
494 var out = (typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out';
495 if (p.place && typeof I18n !== 'undefined')
496 { out += ' · ' + I18n.place(p.place); }
497 else if (p.place)
498 { out += ' · ' + p.place; }
499 el.querySelector('.mini-meta').textContent = out;
500 }
501 else
502 {
503 el.querySelector('.mini-meta').textContent = (typeof I18n !== 'undefined')
504 ? I18n.t('hud.miniPoints', { n: p.score || 0 })
505 : ('Points ' + (p.score || 0));
506 }
507 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));
508 }
509 for (var id in existing)
510 {
511 if (!seen[id])
512 { existing[id].remove(); }
513 }
514 if (typeof applyMinisLayout === 'function')
515 { applyMinisLayout(); }
516};
517
518var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
519
520function miniColor (planet, color)
521{
522 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
523 { return planet.colors[color].hex; }
524 return MINI_COLORS[color] || '#888';
525}
526
527
528/**
529 * t1182: smoothed display y for an opponent's falling blocks (see
530 * src/miniPredict.js). Returns id → y, or null without the module.
531 */
532Online._predictMini = function (p, now)
533{
534 var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;
535 if (!MP || !p)
536 { return null; }
537 if (!this._miniPredict)
538 { this._miniPredict = Object.create(null); }
539 var st = this._miniPredict[p.id];
540 if (!st)
541 { st = this._miniPredict[p.id] = MP.create(); }
542 now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());
543 MP.update(st, p.snapshot, now);
544 if (p.eliminated)
545 { return null; }
546 return MP.step(st, now, MP.fallSpeedFor(p.planet));
547};
548
549Online._drawMini = function (canvas, snapshot, planet, shownY)
550{
551 if (!canvas)
552 { return; }
553 var ctx = canvas.getContext('2d');
554 var w = 10;
555 var h = 13;
556 var tw = canvas.width / w;
557 var th = canvas.height / h;
558 ctx.fillStyle = '#0c1020';
559 ctx.fillRect(0, 0, canvas.width, canvas.height);
560 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
561 ctx.lineWidth = 1;
562 for (var c = 0; c <= w; c++)
563 {
564 ctx.beginPath();
565 ctx.moveTo(c * tw + 0.5, 0);
566 ctx.lineTo(c * tw + 0.5, canvas.height);
567 ctx.stroke();
568 }
569 for (var r = 0; r <= h; r++)
570 {
571 ctx.beginPath();
572 ctx.moveTo(0, r * th + 0.5);
573 ctx.lineTo(canvas.width, r * th + 0.5);
574 ctx.stroke();
575 }
576 if (!snapshot || !snapshot.blocks)
577 { return; }
578 // t1123: cheap sine pulse behind blocks of nearly-full columns.
579 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
580 {
581 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
582 var pulse = GameCore.columnWarnPulse();
583 for (var wc = 0; wc < warns.length; wc++)
584 {
585 if (!warns[wc])
586 { continue; }
587 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
588 ctx.fillRect(wc * tw, 0, tw, canvas.height);
589 }
590 }
591 var blocks = snapshot.blocks;
592 for (var i = 0; i < blocks.length; i++)
593 {
594 var b = blocks[i];
595 var x = b.col * tw;
596 var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
597 var y = canvas.height - (by + 1) * th;
598 if (b.state === 'locked')
599 { ctx.fillStyle = '#3a3d4a'; }
600 else if (b.color < 0)
601 { ctx.fillStyle = '#5a5d66'; }
602 else
603 { ctx.fillStyle = miniColor(planet, b.color); }
604 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
605 }
606};
607
608Online.miniElement = function (playerId)
609{
610 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
611};
612
613/* ---------- flight tweens ------------------------------------------ */
614
615function colorSpriteUrl (color, planetId)
616{
617 if (color < 0)
618 { return 'images/block-gray.png'; }
619 var planet = null;
620 if (typeof Planet !== 'undefined')
621 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
622 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
623 { return planet.colors[color].image; }
624 return 'images/block-gray.png';
625}
626
627/**
628 * Animate shot results. `locals` is a map of client_id → {col, y, color,
629 * startX, startY} in viewport pixels, filled by the view just after
630 * consumeOutgoingShots.
631 */
632Online.playerId = function ()
633{
634 if (typeof app !== 'undefined' && app.offline)
635 { return 'player'; }
636 if (this.lobby && this.lobby.players)
637 {
638 for (var i = 0; i < this.lobby.players.length; i++)
639 {
640 if (this.lobby.players[i].is_me)
641 { return this.lobby.players[i].id; }
642 }
643 }
644 return 'player';
645};
646
647/**
648 * Classify a shot for visual treatment (t1125).
649 * player-to-enemy, enemy-to-player, enemy-to-enemy,
650 * player-miss, enemy-miss.
651 */
652Online.flightKind = function (fromId, targetId, miss)
653{
654 var me = this.playerId();
655 var fromMe = !fromId || fromId === me || fromId === 'player';
656 if (miss)
657 { return fromMe ? 'player-miss' : 'enemy-miss'; }
658 if (fromMe)
659 { return 'player-to-enemy'; }
660 if (targetId === me || targetId === 'player')
661 { return 'enemy-to-player'; }
662 return 'enemy-to-enemy';
663};
664
665/**
666 * Parabolic arc: linear in x, a rise of `height` pixels above the
667 * chord at mid-flight (screen y grows downward, so we subtract).
668 */
669Online.arcPoint = function (start, end, u, height)
670{
671 var t = u < 0 ? 0 : (u > 1 ? 1 : u);
672 var x = start.x + (end.x - start.x) * t;
673 var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t);
674 return { x: x, y: y };
675};
676
677Online.arcHeight = function (start, end)
678{
679 var dx = end.x - start.x;
680 var dy = end.y - start.y;
681 var dist = Math.sqrt(dx * dx + dy * dy);
682 return Math.max(48, Math.min(220, dist * 0.28));
683};
684
685Online.easeInOutCubic = function (t)
686{
687 if (t < 0.5)
688 { return 4 * t * t * t; }
689 var u = -2 * t + 2;
690 return 1 - (u * u * u) / 2;
691};
692
693/** Bounding box of the player's field in viewport pixels. */
694Online.playerFieldRect = function ()
695{
696 var appRef = typeof app !== 'undefined' ? app : null;
697 var canvas = appRef && appRef.scene && appRef.scene.canvas;
698 if (canvas && canvas.getBoundingClientRect)
699 { return canvas.getBoundingClientRect(); }
700 if (appRef && appRef.fieldW)
701 {
702 return {
703 left: appRef.fieldX,
704 top: appRef.fieldY,
705 right: appRef.fieldX + appRef.fieldW,
706 bottom: appRef.fieldY + appRef.fieldH,
707 width: appRef.fieldW,
708 height: appRef.fieldH
709 };
710 }
711 return null;
712};
713
714/**
715 * True if (x, y) is inside the field's interior. The top edge (a few
716 * pixels) is not interior: launch and landing may use that band.
717 */
718Online.pointInFieldInterior = function (x, y, field, slop)
719{
720 if (!field)
721 { return false; }
722 slop = slop == null ? 6 : slop;
723 return x > field.left + 0.5 && x < field.right - 0.5
724 && y > field.top + slop && y < field.bottom - 0.5;
725};
726
727/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */
728Online.cubicBezier = function (p0, p1, p2, p3, t)
729{
730 if (t < 0)
731 { t = 0; }
732 if (t > 1)
733 { t = 1; }
734 var u = 1 - t;
735 var a = u * u * u;
736 var b = 3 * u * u * t;
737 var c = 3 * u * t * t;
738 var d = t * t * t;
739 return {
740 x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
741 y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
742 };
743};
744
745/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */
746Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)
747{
748 if (t < 0)
749 { t = 0; }
750 if (t > 1)
751 { t = 1; }
752 var u = 1 - t;
753 return {
754 x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
755 y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
756 };
757};
758
759Online.cubicBezierDeriv2 = function (p0, p1, p2, p3, t)
760{
761 if (t < 0)
762 { t = 0; }
763 if (t > 1)
764 { t = 1; }
765 var u = 1 - t;
766 // C''(t) = 6(1−t)(P2−2P1+P0) + 6t(P3−2P2+P1)
767 return {
768 x: 6 * u * (p2.x - 2 * p1.x + p0.x) + 6 * t * (p3.x - 2 * p2.x + p1.x),
769 y: 6 * u * (p2.y - 2 * p1.y + p0.y) + 6 * t * (p3.y - 2 * p2.y + p1.y)
770 };
771};
772
773/** Degree-5 Bézier. One polynomial ⇒ C^∞ on (0, 1) (t1138). */
774Online.quinticBezier = function (pts, t)
775{
776 if (t < 0)
777 { t = 0; }
778 if (t > 1)
779 { t = 1; }
780 var u = 1 - t;
781 var u2 = u * u, u3 = u2 * u, u4 = u3 * u, u5 = u4 * u;
782 var t2 = t * t, t3 = t2 * t, t4 = t3 * t, t5 = t4 * t;
783 var b0 = u5, b1 = 5 * u4 * t, b2 = 10 * u3 * t2;
784 var b3 = 10 * u2 * t3, b4 = 5 * u * t4, b5 = t5;
785 return {
786 x: b0 * pts[0].x + b1 * pts[1].x + b2 * pts[2].x
787 + b3 * pts[3].x + b4 * pts[4].x + b5 * pts[5].x,
788 y: b0 * pts[0].y + b1 * pts[1].y + b2 * pts[2].y
789 + b3 * pts[3].y + b4 * pts[4].y + b5 * pts[5].y
790 };
791};
792
793Online.quinticBezierDeriv = function (pts, t)
794{
795 if (t < 0)
796 { t = 0; }
797 if (t > 1)
798 { t = 1; }
799 var d = [];
800 for (var i = 0; i < 5; i++)
801 { d.push({ x: pts[i + 1].x - pts[i].x, y: pts[i + 1].y - pts[i].y }); }
802 var u = 1 - t;
803 var u2 = u * u, u3 = u2 * u, u4 = u3 * u;
804 var t2 = t * t, t3 = t2 * t, t4 = t3 * t;
805 var b0 = u4, b1 = 4 * u3 * t, b2 = 6 * u2 * t2, b3 = 4 * u * t3, b4 = t4;
806 return {
807 x: 5 * (b0 * d[0].x + b1 * d[1].x + b2 * d[2].x + b3 * d[3].x + b4 * d[4].x),
808 y: 5 * (b0 * d[0].y + b1 * d[1].y + b2 * d[2].y + b3 * d[3].y + b4 * d[4].y)
809 };
810};
811
812Online.quinticBezierDeriv2 = function (pts, t)
813{
814 if (t < 0)
815 { t = 0; }
816 if (t > 1)
817 { t = 1; }
818 var d2 = [];
819 for (var i = 0; i < 4; i++)
820 {
821 d2.push({
822 x: pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x,
823 y: pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y
824 });
825 }
826 var u = 1 - t;
827 var u2 = u * u, u3 = u2 * u;
828 var t2 = t * t, t3 = t2 * t;
829 var b0 = u3, b1 = 3 * u2 * t, b2 = 3 * u * t2, b3 = t3;
830 return {
831 x: 20 * (b0 * d2[0].x + b1 * d2[1].x + b2 * d2[2].x + b3 * d2[3].x),
832 y: 20 * (b0 * d2[0].y + b1 * d2[1].y + b2 * d2[2].y + b3 * d2[3].y)
833 };
834};
835
836/** Signed curvature κ = (x'y'' − y'x'') / |r'|³ (independent of parametrisation). */
837Online.curvature = function (d1, d2)
838{
839 var sp = d1.x * d1.x + d1.y * d1.y;
840 var den = Math.pow(sp, 1.5);
841 if (den < 1e-12)
842 { return 0; }
843 return (d1.x * d2.y - d1.y * d2.x) / den;
844};
845
846/**
847 * de Casteljau evaluation of a Bézier of any degree, plus first
848 * and second derivatives (t1138). A single polynomial is C^∞ on (0, 1).
849 */
850Online.bezierPoint = function (pts, t)
851{
852 if (!pts || !pts.length)
853 { return { x: 0, y: 0 }; }
854 if (t < 0)
855 { t = 0; }
856 if (t > 1)
857 { t = 1; }
858 var tmp = [];
859 var i, k, u = 1 - t;
860 for (i = 0; i < pts.length; i++)
861 { tmp.push({ x: pts[i].x, y: pts[i].y }); }
862 for (k = 1; k < pts.length; k++)
863 {
864 for (i = 0; i < pts.length - k; i++)
865 {
866 tmp[i] = {
867 x: u * tmp[i].x + t * tmp[i + 1].x,
868 y: u * tmp[i].y + t * tmp[i + 1].y
869 };
870 }
871 }
872 return tmp[0];
873};
874
875Online.bezierDeriv = function (pts, t)
876{
877 var n = pts ? pts.length - 1 : 0;
878 if (n < 1)
879 { return { x: 0, y: 0 }; }
880 var d = [];
881 for (var i = 0; i < n; i++)
882 {
883 d.push({
884 x: n * (pts[i + 1].x - pts[i].x),
885 y: n * (pts[i + 1].y - pts[i].y)
886 });
887 }
888 return this.bezierPoint(d, t);
889};
890
891Online.bezierDeriv2 = function (pts, t)
892{
893 var n = pts ? pts.length - 1 : 0;
894 if (n < 2)
895 { return { x: 0, y: 0 }; }
896 var s = n * (n - 1);
897 var d2 = [];
898 for (var i = 0; i < n - 1; i++)
899 {
900 d2.push({
901 x: s * (pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x),
902 y: s * (pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y)
903 });
904 }
905 return this.bezierPoint(d2, t);
906};
907
908/**
909 * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
910 * v0=v1=1 is linear (constant speed in t, no endpoint halt).
911 */
912Online.smoothParam = function (t, v0, v1)
913{
914 if (t < 0)
915 { return 0; }
916 if (t > 1)
917 { return 1; }
918 if (v0 == null)
919 { v0 = 1; }
920 if (v1 == null)
921 { v1 = 1; }
922 var b = 3 - 2 * v0 - v1;
923 var a = v0 + v1 - 2;
924 return ((a * t + b) * t + v0) * t;
925};
926
927/**
928 * One continuous degree-7 Bézier: a single big, round, ballistic
929 * arch (t1138). Vertical at the exit (heading up) and at the
930 * landing (heading down). Horizontal travel sits on the apex,
931 * above the field — a cluster of high control points on each
932 * side keeps the hull out of the interior, with no straight
933 * cruise and no quarter-turn kinks. C^∞ on (0, 1).
934 *
935 * Incoming (low mini → high field): the first mid controls stay
936 * on the outside so the rise clears the top before crossing.
937 * Outgoing (high exit → low mini): mid controls sit above the
938 * target so the dive happens outside. Enemy→enemy (no field)
939 * is a symmetric parabola behind the field.
940 */
941Online.makeAroundCurve = function (start, end, field, opts)
942{
943 opts = opts || {};
944 if (!start)
945 { start = { x: 0, y: 0 }; }
946 if (!end)
947 { end = { x: 0, y: 0 }; }
948 var clearance = opts.clearance || 150;
949 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
950 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD); }
951 if (clearance < 150)
952 { clearance = 150; }
953
954 var apexY;
955 var left, right, top;
956 if (field)
957 {
958 top = field.top;
959 left = field.left;
960 right = field.right;
961 apexY = top - clearance;
962 if (apexY < 8)
963 { apexY = Math.max(8, top - Math.max(28, clearance * 0.5)); }
964 }
965 else
966 {
967 apexY = Math.min(start.y, end.y) - Math.max(56, clearance * 0.6);
968 if (apexY < 8)
969 { apexY = Math.min(start.y, end.y) - 40; }
970 left = right = top = null;
971 }
972
973 function outsideX (x)
974 {
975 if (!field)
976 { return x; }
977 var pad = 40;
978 if (x < left + 8)
979 { return Math.min(x, left - pad); }
980 if (x > right - 8)
981 { return Math.max(x, right + pad); }
982 return x;
983 }
984
985 var startLow = field && start.y > top + 8;
986 var endLow = field && end.y > top + 8;
987 var startInside = field && start.x > left + 8 && start.x < right - 8;
988 var endInside = field && end.x > left + 8 && end.x < right - 8;
989 // Incoming: rise on the outside first. Outgoing: cross at
990 // the apex, then dive outside. Otherwise a symmetric arch.
991 var kind;
992 if (startLow && !endLow)
993 { kind = 'in'; }
994 else if (!startLow && endLow)
995 { kind = 'out'; }
996 else if (startLow && endLow)
997 { kind = startInside ? 'out' : (endInside ? 'in' : 'sym'); }
998 else
999 { kind = 'sym'; }
1000
1001 var sx = outsideX(start.x);
1002 var ex = outsideX(end.x);
1003 var rise = Math.max(80, Math.abs(start.y - apexY) * 0.35);
1004 var P0 = { x: start.x, y: start.y };
1005 var P1 = { x: start.x, y: start.y - rise };
1006 var P2, P3, P4, P5;
1007 var P6 = { x: end.x, y: apexY };
1008 var P7 = { x: end.x, y: end.y };
1009 if (kind === 'in')
1010 {
1011 P2 = { x: sx, y: apexY };
1012 P3 = { x: sx, y: apexY };
1013 P4 = { x: sx + (ex - sx) * 0.5, y: apexY };
1014 P5 = { x: sx + (ex - sx) * 0.85, y: apexY };
1015 }
1016 else if (kind === 'out')
1017 {
1018 P2 = { x: start.x, y: apexY };
1019 P3 = { x: sx + (ex - sx) * 0.55, y: apexY };
1020 P4 = { x: ex, y: apexY };
1021 P5 = { x: end.x, y: apexY };
1022 }
1023 else
1024 {
1025 P2 = { x: sx, y: apexY };
1026 P3 = { x: sx + (ex - sx) * 0.35, y: apexY };
1027 P4 = { x: sx + (ex - sx) * 0.65, y: apexY };
1028 P5 = { x: ex, y: apexY };
1029 }
1030 var pts = [P0, P1, P2, P3, P4, P5, P6, P7];
1031
1032 var curve = {
1033 degree: 7,
1034 pts: pts,
1035 p0: P0,
1036 p3: P7,
1037 apexY: apexY,
1038 kind: kind,
1039 arcLength: true
1040 };
1041 this._buildArcLut(curve);
1042 return curve;
1043};
1044
1045Online._evalPoly = function (curve, t)
1046{
1047 if (curve && curve.pts && curve.pts.length >= 2)
1048 { return this.bezierPoint(curve.pts, t); }
1049 if (curve && curve.p1)
1050 { return this.cubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1051 if (curve && curve.segments)
1052 {
1053 var n = curve.segments.length;
1054 var at = (t < 0 ? 0 : (t > 1 ? 1 : t)) * n;
1055 var i = Math.floor(at);
1056 if (i >= n)
1057 { i = n - 1; }
1058 var s = curve.segments[i];
1059 return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at - i);
1060 }
1061 return { x: 0, y: 0 };
1062};
1063
1064Online._evalPolyDeriv = function (curve, t)
1065{
1066 if (curve && curve.pts && curve.pts.length >= 2)
1067 { return this.bezierDeriv(curve.pts, t); }
1068 if (curve && curve.p1)
1069 { return this.cubicBezierDeriv(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1070 return { x: 0, y: 0 };
1071};
1072
1073Online._evalPolyDeriv2 = function (curve, t)
1074{
1075 if (curve && curve.pts && curve.pts.length >= 3)
1076 { return this.bezierDeriv2(curve.pts, t); }
1077 if (curve && curve.p1)
1078 { return this.cubicBezierDeriv2(curve.p0, curve.p1, curve.p2, curve.p3, t); }
1079 return { x: 0, y: 0 };
1080};
1081
1082/** Cumulative-length LUT so u is a fraction of arc length (t1138). */
1083Online._buildArcLut = function (curve, steps)
1084{
1085 steps = steps || 48;
1086 var acc = [0];
1087 var prev = this._evalPoly(curve, 0);
1088 for (var i = 1; i <= steps; i++)
1089 {
1090 var p = this._evalPoly(curve, i / steps);
1091 acc.push(acc[i - 1] + Math.sqrt((p.x - prev.x) * (p.x - prev.x)
1092 + (p.y - prev.y) * (p.y - prev.y)));
1093 prev = p;
1094 }
1095 curve.lutS = acc;
1096 curve.lutN = steps;
1097 curve.totalLen = Math.max(acc[steps], 1);
1098 return curve;
1099};
1100
1101/** Polynomial t whose arc length fraction is u. */
1102Online._arcT = function (curve, u)
1103{
1104 if (u <= 0)
1105 { return 0; }
1106 if (u >= 1)
1107 { return 1; }
1108 if (!curve.lutS)
1109 { this._buildArcLut(curve); }
1110 var s = u * curve.totalLen;
1111 var acc = curve.lutS;
1112 var n = curve.lutN;
1113 var lo = 0;
1114 var hi = n;
1115 while (lo < hi)
1116 {
1117 var mid = (lo + hi) >> 1;
1118 if (acc[mid] < s)
1119 { lo = mid + 1; }
1120 else
1121 { hi = mid; }
1122 }
1123 var i = lo;
1124 if (i <= 0)
1125 { return 0; }
1126 var s0 = acc[i - 1];
1127 var s1 = acc[i];
1128 var f = (s1 > s0) ? (s - s0) / (s1 - s0) : 0;
1129 return ((i - 1) + f) / n;
1130};
1131
1132Online._measureCurve = function (curve)
1133{
1134 if (!curve)
1135 { return curve; }
1136 if (!curve.lutS)
1137 { this._buildArcLut(curve); }
1138 return curve;
1139};
1140
1141Online._segLen = function (seg, steps)
1142{
1143 steps = steps || 10;
1144 if (seg && seg.degree === 5)
1145 {
1146 if (!seg.lutS)
1147 { this._buildArcLut(seg, steps * 4); }
1148 return seg.totalLen;
1149 }
1150 var len = 0;
1151 var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
1152 for (var i = 1; i <= steps; i++)
1153 {
1154 var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
1155 len += Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y));
1156 prev = p;
1157 }
1158 return Math.max(len, 1);
1159};
1160
1161/** Point at arc-length fraction u ∈ [0, 1]. */
1162Online.curvePoint = function (curve, u)
1163{
1164 if (!curve)
1165 { return { x: 0, y: 0 }; }
1166 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1167 return this._evalPoly(curve, t);
1168};
1169
1170/**
1171 * dP/du under arc-length parametrisation: unit tangent × total length
1172 * (constant speed in u, direction from the polynomial).
1173 */
1174Online.curveDeriv = function (curve, u)
1175{
1176 if (!curve)
1177 { return { x: 0, y: 0 }; }
1178 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1179 var d = this._evalPolyDeriv(curve, t);
1180 if (curve.arcLength !== false)
1181 {
1182 if (!curve.lutS)
1183 { this._buildArcLut(curve); }
1184 var mag = Math.sqrt(d.x * d.x + d.y * d.y);
1185 if (mag < 1e-9)
1186 { return { x: 0, y: 0 }; }
1187 var s = curve.totalLen / mag;
1188 return { x: d.x * s, y: d.y * s };
1189 }
1190 return d;
1191};
1192
1193Online.curveDeriv2 = function (curve, u)
1194{
1195 if (!curve)
1196 { return { x: 0, y: 0 }; }
1197 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
1198 return this._evalPolyDeriv2(curve, t);
1199};
1200
1201/** Curvature at arc-length fraction u (uses polynomial t, κ is invariant). */
1202Online.curveCurvature = function (curve, u)
1203{
1204 var t = curve && curve.arcLength !== false ? this._arcT(curve, u) : u;
1205 return this.curvature(this._evalPolyDeriv(curve, t), this._evalPolyDeriv2(curve, t));
1206};
1207
1208/**
1209 * Endpoint ease rates so arrival speed ≈ fallSpeed under arc-length
1210 * parametrisation: v = (L / duration) * p'(raw).
1211 */
1212Online.flightEaseRates = function (curve, duration, fallPx)
1213{
1214 if (!curve || !curve.lutS)
1215 { this._measureCurve(curve); }
1216 var L = (curve && curve.totalLen) || 400;
1217 duration = duration || this.FLIGHT_DURATION;
1218 var v1 = fallPx && L ? (fallPx * duration) / L : 0.75;
1219 if (v1 < 0.28)
1220 { v1 = 0.28; }
1221 if (v1 > 1.15)
1222 { v1 = 1.15; }
1223 var v0 = v1 + 0.2;
1224 if (v0 > 1)
1225 { v0 = 1; }
1226 if (v0 < 0.45)
1227 { v0 = 0.45; }
1228 return { v0: v0, v1: v1 };
1229};
1230
1231Online.aroundFieldPoint = function (start, end, u, field, clearance)
1232{
1233 var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
1234 var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
1235 return this.curvePoint(curve, u);
1236};
1237
1238Online.waypointsAroundField = function (start, end, field, clearance)
1239{
1240 var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 100 });
1241 if (c.pts && c.pts.length)
1242 { return c.pts.slice(); }
1243 return [c.p0, c.p1, c.p2, c.p3];
1244};
1245
1246Online.pointOnPath = function (points, u)
1247{
1248 // Legacy polyline; new flights use cubicBezier.
1249 u = u < 0 ? 0 : (u > 1 ? 1 : u);
1250 if (!points || !points.length)
1251 { return { x: 0, y: 0 }; }
1252 if (points.length === 4 && points[0] && points[3])
1253 { return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
1254 if (points.length === 1)
1255 { return { x: points[0].x, y: points[0].y }; }
1256 var n = points.length - 1;
1257 var at = u * n;
1258 var i = Math.floor(at);
1259 if (i >= n)
1260 { i = n - 1; }
1261 var t = at - i;
1262 var a = points[i];
1263 var b = points[i + 1];
1264 return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
1265};
1266
1267/** Viewport centre of a field cell (y=0 is the bottom row). */
1268Online.cellViewport = function (col, y, rect)
1269{
1270 if (!rect)
1271 {
1272 var field = this.playerFieldRect();
1273 if (!field)
1274 { return { x: 0, y: 0 }; }
1275 rect = field;
1276 }
1277 var w = rect.width != null ? rect.width : (rect.right - rect.left);
1278 var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
1279 return {
1280 x: rect.left + ((col + 0.5) / 10) * w,
1281 y: rect.top + (1 - (y + 0.5) / 13) * h
1282 };
1283};
1284
1285/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
1286Online.fieldEntry = function (col)
1287{
1288 return this.cellViewport(col == null ? 4.5 : col, 13);
1289};
1290
1291Online.miniCellViewport = function (playerId, col, y)
1292{
1293 var el = this.miniElement(playerId);
1294 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
1295 var box = canvas || el;
1296 if (!box || !box.getBoundingClientRect)
1297 { return { x: window.innerWidth / 2, y: 48 }; }
1298 return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
1299};
1300
1301Online._fallSpeedPx = function (field, duration)
1302{
1303 var px = 40;
1304 if (field && field.height)
1305 { px = field.height / 13; }
1306 else if (typeof app !== 'undefined' && app.tile)
1307 { px = app.tile; }
1308 var cells = 13 / 3;
1309 if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
1310 { cells = app.planet.fallSpeed; }
1311 duration = duration || this.FLIGHT_DURATION;
1312 // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
1313 return (cells * px * duration) / 3;
1314};
1315
1316Online.rememberLandCol = function (id, col)
1317{
1318 if (id == null || col == null || !isFinite(col))
1319 { return; }
1320 if (!this._pendingLandCol)
1321 { this._pendingLandCol = Object.create(null); }
1322 this._pendingLandCol[String(id)] = col | 0;
1323};
1324
1325/** Resolve the landing column for an incoming shot (t1126). */
1326Online.takeLandCol = function (incoming)
1327{
1328 if (!incoming)
1329 { return null; }
1330 if (incoming.land_col != null && isFinite(incoming.land_col))
1331 { return incoming.land_col | 0; }
1332 if (!this._pendingLandCol)
1333 { return null; }
1334 var keys = [];
1335 if (incoming.id != null)
1336 { keys.push(String(incoming.id)); }
1337 if (incoming.client_id)
1338 { keys.push(String(incoming.client_id)); }
1339 for (var i = 0; i < keys.length; i++)
1340 {
1341 if (this._pendingLandCol[keys[i]] != null)
1342 { return this._pendingLandCol[keys[i]]; }
1343 }
1344 return null;
1345};
1346
1347Online._miniCellSize = function (playerId)
1348{
1349 var el = this.miniElement(playerId);
1350 var canvas = el && el.querySelector('canvas');
1351 if (canvas)
1352 {
1353 var r = canvas.getBoundingClientRect();
1354 return Math.max(6, r.width / 10);
1355 }
1356 return 10;
1357};
1358
1359Online._fullTileSize = function ()
1360{
1361 if (typeof app !== 'undefined' && app.tile)
1362 { return app.tile; }
1363 return 40;
1364};
1365
1366Online._miniAnchor = function (playerId, dir)
1367{
1368 var el = this.miniElement(playerId);
1369 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
1370 var box = canvas || el;
1371 if (!box)
1372 { return { x: window.innerWidth / 2, y: 48 }; }
1373 var r = box.getBoundingClientRect();
1374 if (dir === 'out')
1375 { return { x: r.left + r.width / 2, y: r.top + 4 }; }
1376 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
1377};
1378
1379Online._fieldTop = function (col)
1380{
1381 return this.fieldEntry(col);
1382};
1383
1384/**
1385 * Animate shot results. `locals` is a map of client_id → {col, y, color,
1386 * startX, startY, from_id} in viewport pixels.
1387 *
1388 * Visual-only: a smooth cubic that leaves the real cell, arcs around
1389 * the field, and dives into the landing column at the spawn pose
1390 * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
1391 * behind the player's field. A late-seen flight starts mid-arc via `age`.
1392 */
1393Online.spawnFlights = function (results, locals)
1394{
1395 locals = locals || this._flightLocals || {};
1396 var front = document.getElementById('flights');
1397 var back = document.getElementById('flights-back') || front;
1398 if (!front)
1399 { return; }
1400 if (!this._flightSeen)
1401 { this._flightSeen = Object.create(null); }
1402 if (!this._previewIds)
1403 { this._previewIds = Object.create(null); }
1404 var now = performance.now();
1405 var full = this._fullTileSize();
1406 for (var i = 0; i < results.length; i++)
1407 {
1408 var r = results[i];
1409 var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
1410 // Own shot already flying locally since the clear (t1181):
1411 // pick it up at its current pose and fly on to the real target.
1412 var cid = r.client_id != null ? String(r.client_id) : null;
1413 if (cid && this._previewIds[cid] && this._isOwnShot(r))
1414 {
1415 var own = this._findFlight(cid);
1416 this._flightSeen[sid] = now;
1417 if (own)
1418 { this.retargetFlight(own, r, locals[cid] || {}, now); }
1419 continue;
1420 }
1421 if (this._flightSeen[sid])
1422 {
1423 if (this._previewIds[sid])
1424 {
1425 var existing = this._findFlight(sid);
1426 if (existing)
1427 {
1428 var meta0 = locals[r.client_id] || locals[sid] || {};
1429 this.retargetFlight(existing, r, meta0, now);
1430 }
1431 }
1432 continue;
1433 }
1434 this._flightSeen[sid] = now;
1435
1436 var meta = locals[r.client_id] || locals[sid] || {};
1437 var fromId = r.from_id || r.from_user || meta.from_id || null;
1438 var targetId = r.target_id != null ? r.target_id : r.to_user;
1439 var miss = !!r.miss;
1440 var kind = this.flightKind(fromId, targetId, miss);
1441 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1442 if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration)
1443 { continue; }
1444
1445 var landCol = null;
1446 if (r.land_col != null && isFinite(r.land_col))
1447 { landCol = r.land_col | 0; }
1448 else if (meta.land_col != null && isFinite(meta.land_col))
1449 { landCol = meta.land_col | 0; }
1450 else if (kind === 'enemy-to-player'
1451 && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn)
1452 { landCol = app.core.pickGarbageColumn(); }
1453 if (landCol != null)
1454 {
1455 this.rememberLandCol(sid, landCol);
1456 if (r.client_id)
1457 { this.rememberLandCol(r.client_id, landCol); }
1458 }
1459
1460 var startCol = meta.col != null ? meta.col : r.col;
1461 var startY = meta.y != null ? meta.y : r.y;
1462 var start;
1463 if (meta.startX != null && isFinite(meta.startX))
1464 { start = { x: meta.startX, y: meta.startY }; }
1465 else if (kind === 'player-to-enemy' || kind === 'player-miss')
1466 { start = this._flightStart(startCol, startY); }
1467 else if (startCol != null || startY != null)
1468 { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 13); }
1469 else
1470 { start = this._miniAnchor(fromId, 'out'); }
1471
1472 var end;
1473 if (miss)
1474 { end = this._missEnd(start, kind === 'enemy-miss'); }
1475 else if (kind === 'enemy-to-player')
1476 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1477 else
1478 { end = this._targetEnd(targetId, start, landCol); }
1479
1480 // Hits are ingested as grey garbage; draw them grey (t1130).
1481 // Misses keep the sender's colour — nothing is received.
1482 var flightColor = miss
1483 ? (r.color != null ? r.color : meta.color)
1484 : -1;
1485
1486 var startScale;
1487 var endScale;
1488 var mini = this._miniCellSize(fromId || targetId) / full;
1489 if (mini < 0.12)
1490 { mini = 0.2; }
1491 if (kind === 'player-to-enemy')
1492 {
1493 startScale = 1;
1494 endScale = mini;
1495 }
1496 else if (kind === 'enemy-to-player')
1497 {
1498 startScale = mini;
1499 endScale = 1;
1500 }
1501 else if (kind === 'enemy-to-enemy')
1502 {
1503 startScale = mini;
1504 endScale = mini;
1505 }
1506 else if (kind === 'enemy-miss')
1507 {
1508 startScale = mini;
1509 endScale = 0;
1510 }
1511 else
1512 {
1513 startScale = 1;
1514 endScale = 0;
1515 }
1516
1517 var layer = (kind === 'enemy-to-enemy' && back) ? back : front;
1518 var el = document.createElement('img');
1519 el.src = colorSpriteUrl(flightColor);
1520 el.alt = '';
1521 el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : '');
1522 el.style.width = full + 'px';
1523 el.style.height = full + 'px';
1524 layer.appendChild(el);
1525
1526 // A flight seen late (poll delay) still starts at the sender's
1527 // field and plays the whole arc, just a bit faster, so it lands
1528 // about when the server delivers it — never a mid-arc pop-in (t1181).
1529 var t0 = now;
1530 duration = this.lateFlightDuration(r.age, duration);
1531 var height = miss
1532 ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
1533 : this.arcHeight(start, end);
1534 var field = this.playerFieldRect();
1535 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1536 var clearance = Math.max(150, height * 0.55);
1537 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1538 var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
1539 clearance: clearance
1540 });
1541 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
1542 this._flights.push({
1543 el: el,
1544 start: start,
1545 end: end,
1546 ctrl: miss ? this._missCtrl(start, end) : null,
1547 height: height,
1548 t0: t0,
1549 duration: duration,
1550 easeRates: easeRates,
1551 spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
1552 miss: miss,
1553 kind: kind,
1554 startScale: startScale,
1555 endScale: endScale,
1556 angle: 0,
1557 id: sid,
1558 landCol: landCol,
1559 field: field,
1560 curve: curve,
1561 color: flightColor
1562 });
1563 }
1564 this._flightLocals = {};
1565};
1566
1567/** Shortest share of the normal flight a late-seen flight may get. */
1568Online.LATE_MIN_SHARE = 0.5;
1569
1570/** Duration (ms) for a flight first seen `age` seconds after it was fired. */
1571Online.lateFlightDuration = function (age, duration)
1572{
1573 if (age == null || !isFinite(age) || age <= 0)
1574 { return duration; }
1575 return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);
1576};
1577
1578/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */
1579Online.retargetDuration = function (elapsedMs, duration)
1580{
1581 if (!(elapsedMs > 0))
1582 { return duration; }
1583 return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);
1584};
1585
1586Online._isOwnShot = function (r)
1587{
1588 var mine = this.me && this.me.id;
1589 var from = r.from_id || r.from_user || null;
1590 return !from || (mine != null && String(from) === String(mine));
1591};
1592
1593/**
1594 * Sender side (t1181): start the flight the moment the block leaves the
1595 * field, before any server round trip. It rises out of the exit cell;
1596 * the poll answer retargets it (hit → opponent mini, miss → off-screen).
1597 */
1598Online.startLocalShot = function (shot, start)
1599{
1600 if (!shot || !start)
1601 { return null; }
1602 return this.previewExit({
1603 id: shot.id,
1604 col: shot.col,
1605 y: shot.y,
1606 vy: shot.vy,
1607 color: shot.color,
1608 start: start,
1609 from_id: null
1610 });
1611};
1612
1613Online.rememberFlightLocal = function (shot, startX, startY)
1614{
1615 if (!this._flightLocals)
1616 { this._flightLocals = {}; }
1617 this._flightLocals[String(shot.id)] = {
1618 col: shot.col,
1619 y: shot.y,
1620 color: shot.color,
1621 startX: startX,
1622 startY: startY,
1623 from_id: shot.from_id,
1624 land_col: shot.land_col,
1625 vy: shot.vy
1626 };
1627};
1628
1629Online._flightStart = function (col, y)
1630{
1631 if (y == null || !isFinite(y))
1632 { y = 13; }
1633 return this.cellViewport(col == null ? 4.5 : col, y);
1634};
1635
1636Online._targetEnd = function (targetId, start, col)
1637{
1638 var el = targetId && this.miniElement(targetId);
1639 if (el)
1640 {
1641 // Slightly inside the mini, in the landing column (t1135).
1642 return this.miniCellViewport(targetId, col, 12);
1643 }
1644 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
1645};
1646
1647Online._missEnd = function (start, fromMini)
1648{
1649 var w = window.innerWidth || 800;
1650 var outward;
1651 if (start.x < w * 0.4)
1652 { outward = -(80 + Math.random() * w * 0.25); }
1653 else if (start.x > w * 0.6)
1654 { outward = (80 + Math.random() * w * 0.25); }
1655 else
1656 { outward = (Math.random() * 2 - 1) * w * 0.35; }
1657 var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220);
1658 return { x: start.x + outward, y: start.y - lift };
1659};
1660
1661Online._missCtrl = function (start, end)
1662{
1663 return {
1664 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
1665 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
1666 };
1667};
1668
1669Online._hitCtrl = function (start, end)
1670{
1671 return {
1672 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
1673 y: (start.y + end.y) / 2 - 30
1674 };
1675};
1676
1677Online._findFlight = function (sid)
1678{
1679 sid = String(sid);
1680 if (!this._flights)
1681 { return null; }
1682 for (var i = 0; i < this._flights.length; i++)
1683 {
1684 if (String(this._flights[i].id) === sid)
1685 { return this._flights[i]; }
1686 }
1687 return null;
1688};
1689
1690/**
1691 * True once a block has really left the field, matching cullOffTop
1692 * (y ≥ height, default 13). Used so an arc never starts for a
1693 * rocket that only peaked near the top and fell back (t1137).
1694 */
1695Online.EXIT_Y = 13;
1696Online.hasLeftTheField = function (y, height)
1697{
1698 height = height == null ? this.EXIT_Y : height;
1699 return y != null && isFinite(y) && y >= height - 1e-9;
1700};
1701
1702/**
1703 * Start a flight only at the true exit (y ≥ 13). Callers that pass
1704 * a rocket still on the field are ignored, so a fallback never
1705 * shows a phantom arc (t1137). The start pose is the exit cell,
1706 * continuing upward; retargetFlight aims it at the real target
1707 * if a preview was used in the same frame as cull.
1708 */
1709Online.previewExit = function (info)
1710{
1711 if (!info || info.id == null)
1712 { return null; }
1713 if (!this.hasLeftTheField(info.y))
1714 { return null; }
1715 var sid = String(info.id);
1716 if (!this._flights)
1717 { this._flights = []; }
1718 if (!this._flightSeen)
1719 { this._flightSeen = Object.create(null); }
1720 if (!this._previewIds)
1721 { this._previewIds = Object.create(null); }
1722 if (this._previewIds[sid] || this._flightSeen[sid])
1723 { return; }
1724 var front = document.getElementById('flights');
1725 if (!front || !info.start)
1726 { return; }
1727 var start = info.start;
1728 var field = this.playerFieldRect();
1729 var clearance = 80;
1730 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
1731 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
1732 var apexY = (field ? field.top : start.y) - clearance;
1733 if (apexY < 8)
1734 { apexY = Math.max(8, start.y - 80); }
1735 var end = { x: start.x, y: apexY };
1736 var duration = this.FLIGHT_DURATION * 1000;
1737 var full = this._fullTileSize();
1738 var el = document.createElement('img');
1739 el.src = colorSpriteUrl(info.color);
1740 el.alt = '';
1741 el.className = 'flight';
1742 el.style.width = full + 'px';
1743 el.style.height = full + 'px';
1744 front.appendChild(el);
1745 var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
1746 var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
1747 clearance: clearance
1748 });
1749 var easeRates = this.flightEaseRates(curve, this.FLIGHT_DURATION, endSpeed);
1750 var now = performance.now();
1751 var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
1752 if (mini < 0.12)
1753 { mini = 0.2; }
1754 this._flights.push({
1755 el: el,
1756 start: start,
1757 end: end,
1758 ctrl: null,
1759 height: clearance,
1760 t0: now,
1761 duration: duration,
1762 spin: (Math.random() * 2 - 1) * 90,
1763 miss: false,
1764 kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
1765 startScale: mini,
1766 endScale: mini,
1767 angle: 0,
1768 id: sid,
1769 landCol: null,
1770 field: field,
1771 curve: curve,
1772 easeRates: easeRates,
1773 preview: true,
1774 color: info.color,
1775 from_id: info.from_id || null
1776 });
1777 this._previewIds[sid] = true;
1778 this._flightSeen[sid] = now;
1779 return true;
1780};
1781
1782/** True while a field sprite should stay hidden — the flight is its visual. */
1783Online.hasExitVisual = function (id)
1784{
1785 if (id == null)
1786 { return false; }
1787 var sid = String(id);
1788 if (this._previewIds && this._previewIds[sid])
1789 { return true; }
1790 var f = this._findFlight(sid);
1791 if (!f || f.miss)
1792 { return false; }
1793 var raw = (performance.now() - f.t0) / f.duration;
1794 return raw < 0.4;
1795};
1796
1797/**
1798 * Once the shot is scored, pick up the preview at its current pose
1799 * and fly the rest of the way to the real end (no jump).
1800 */
1801Online.retargetFlight = function (f, r, meta, now)
1802{
1803 now = now || performance.now();
1804 meta = meta || {};
1805 var raw = (now - f.t0) / f.duration;
1806 if (raw < 0)
1807 { raw = 0; }
1808 if (raw > 0.95)
1809 { raw = 0.95; }
1810 var u = this.smoothParam(raw, 0.9, 0.9);
1811 var pt = f.curve
1812 ? this.curvePoint(f.curve, u)
1813 : { x: f.start.x, y: f.start.y };
1814 var curScale = f.startScale + (f.endScale - f.startScale) * u;
1815
1816 var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
1817 var targetId = r.target_id != null ? r.target_id : r.to_user;
1818 var miss = !!r.miss;
1819 var kind = this.flightKind(fromId, targetId, miss);
1820 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1821 if (f.preview)
1822 { duration = this.retargetDuration(now - f.t0, duration); }
1823
1824 var landCol = null;
1825 if (r.land_col != null && isFinite(r.land_col))
1826 { landCol = r.land_col | 0; }
1827 else if (meta.land_col != null && isFinite(meta.land_col))
1828 { landCol = meta.land_col | 0; }
1829 else if (f.landCol != null)
1830 { landCol = f.landCol; }
1831 if (landCol != null)
1832 { this.rememberLandCol(String(f.id), landCol); }
1833
1834 var end;
1835 if (miss)
1836 { end = this._missEnd(pt, kind === 'enemy-miss'); }
1837 else if (kind === 'enemy-to-player')
1838 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1839 else
1840 { end = this._targetEnd(targetId, pt, landCol); }
1841
1842 var flightColor = miss
1843 ? (r.color != null ? r.color : meta.color)
1844 : -1;
1845 if (f.el && flightColor !== f.color)
1846 { f.el.src = colorSpriteUrl(flightColor); }
1847
1848 var full = this._fullTileSize();
1849 var mini = this._miniCellSize(fromId || targetId) / full;
1850 if (mini < 0.12)
1851 { mini = 0.2; }
1852 var endScale;
1853 if (kind === 'player-to-enemy')
1854 { endScale = mini; }
1855 else if (kind === 'enemy-to-player')
1856 { endScale = 1; }
1857 else if (kind === 'enemy-to-enemy')
1858 { endScale = mini; }
1859 else
1860 { endScale = 0; }
1861
1862 var field = this.playerFieldRect();
1863 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1864 var height = miss
1865 ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
1866 : this.arcHeight(pt, end);
1867 var clearance = Math.max(150, height * 0.55);
1868 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1869 var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
1870 clearance: clearance
1871 });
1872 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
1873
1874 f.start = pt;
1875 f.end = end;
1876 f.t0 = now;
1877 f.duration = duration;
1878 f.curve = curve;
1879 f.easeRates = easeRates;
1880 f.ctrl = miss ? this._missCtrl(pt, end) : null;
1881 f.height = height;
1882 f.miss = miss;
1883 f.kind = kind;
1884 f.startScale = curScale;
1885 f.endScale = endScale;
1886 f.landCol = landCol;
1887 f.field = field;
1888 f.preview = false;
1889 f.color = flightColor;
1890 f.from_id = fromId;
1891 if (this._previewIds)
1892 { delete this._previewIds[String(f.id)]; }
1893
1894 if (kind === 'enemy-to-enemy' && f.el)
1895 {
1896 var back = document.getElementById('flights-back');
1897 if (back && f.el.parentNode !== back)
1898 {
1899 f.el.className = 'flight flight-behind';
1900 back.appendChild(f.el);
1901 }
1902 }
1903};
1904
1905/** Point and (optional) derivative of a flight at parameter u. */
1906Online.flightPointAt = function (f, u)
1907{
1908 if (!f)
1909 { return { x: 0, y: 0 }; }
1910 if (f.curve)
1911 { return this.curvePoint(f.curve, u); }
1912 if (f.miss && f.ctrl)
1913 {
1914 var e = u;
1915 var mt = 1 - e;
1916 return {
1917 x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
1918 y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
1919 };
1920 }
1921 return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1922};
1923
1924Online.pointAllowedOnArc = function (p, field, start, end, slop)
1925{
1926 if (!this.pointInFieldInterior(p.x, p.y, field, slop))
1927 { return true; }
1928 if (!field)
1929 { return true; }
1930 var w = (field.right - field.left) / 10;
1931 var corridor = w * 0.7;
1932 if (start && Math.abs(p.x - start.x) <= corridor)
1933 { return true; }
1934 if (end && Math.abs(p.x - end.x) <= corridor)
1935 { return true; }
1936 return false;
1937};
1938
1939/** How long a local preview may wait at its apex for the server (ms). */
1940Online.PREVIEW_HOLD_MS = 2500;
1941
1942Online.tickFlights = function (now)
1943{
1944 now = now || performance.now();
1945 var leftover = [];
1946 for (var i = 0; i < this._flights.length; i++)
1947 {
1948 var f = this._flights[i];
1949 var raw = (now - f.t0) / f.duration;
1950 if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)
1951 { raw = 0.999; }
1952 if (raw >= 1)
1953 {
1954 if (f.el && f.el.parentNode)
1955 { f.el.parentNode.removeChild(f.el); }
1956 if (this._previewIds)
1957 { delete this._previewIds[String(f.id)]; }
1958 continue;
1959 }
1960 if (raw < 0)
1961 { raw = 0; }
1962 // Non-zero endpoint speed so the handoff matches fallSpeed (t1135/t1138).
1963 var v0 = (f.easeRates && f.easeRates.v0 != null) ? f.easeRates.v0 : 0.85;
1964 var v1 = (f.easeRates && f.easeRates.v1 != null) ? f.easeRates.v1 : 0.85;
1965 var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, v0, v1);
1966 var x, y;
1967 if (f.miss && f.ctrl)
1968 {
1969 var e = raw * raw;
1970 var mt = 1 - e;
1971 x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
1972 y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
1973 }
1974 else if (f.curve)
1975 {
1976 var pt = this.curvePoint(f.curve, u);
1977 x = pt.x;
1978 y = pt.y;
1979 }
1980 else
1981 {
1982 var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1983 x = pt.x;
1984 y = pt.y;
1985 }
1986 var scale = f.startScale + (f.endScale - f.startScale) * u;
1987 if (f.miss)
1988 {
1989 var fadeU = raw * raw;
1990 scale = f.startScale * (1 - fadeU);
1991 }
1992 var angle = f.angle + f.spin * raw;
1993 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
1994 + angle + 'deg) scale(' + scale + ')';
1995 f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1';
1996 leftover.push(f);
1997 }
1998 this._flights = leftover;
1999 if (this._flightSeen)
2000 {
2001 var cutoff = now - 8000;
2002 var ids = Object.keys(this._flightSeen);
2003 for (var k = 0; k < ids.length; k++)
2004 {
2005 if (this._flightSeen[ids[k]] < cutoff)
2006 { delete this._flightSeen[ids[k]]; }
2007 }
2008 }
2009};
2010
2011Online.clearFlights = function ()
2012{
2013 for (var i = 0; i < this._flights.length; i++)
2014 {
2015 var el = this._flights[i].el;
2016 if (el && el.parentNode)
2017 { el.parentNode.removeChild(el); }
2018 }
2019 this._flights = [];
2020 this._flightLocals = {};
2021 this._flightSeen = Object.create(null);
2022 this._pendingLandCol = Object.create(null);
2023 this._previewIds = Object.create(null);
2024 this._miniPredict = Object.create(null);
2025};
2026
2027if (typeof globalThis !== 'undefined')
2028{ globalThis.Online = Online; }
2029if (typeof module !== 'undefined' && module.exports)
2030{ module.exports = Online; }