BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

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