BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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