BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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