BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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