BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 40.4 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 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
554/**
555 * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
556 * v0=v1=1 is linear (constant speed in t, no endpoint halt).
557 */
558Online.smoothParam = function (t, v0, v1)
559{
560 if (t < 0)
561 { return 0; }
562 if (t > 1)
563 { return 1; }
564 if (v0 == null)
565 { v0 = 1; }
566 if (v1 == null)
567 { v1 = 1; }
568 var b = 3 - 2 * v0 - v1;
569 var a = v0 + v1 - 2;
570 return ((a * t + b) * t + v0) * t;
571};
572
573/**
574 * A simple up-and-over cubic, used when there is no field to route
575 * around (enemy→enemy) or both ends already sit above the apex.
576 */
577Online._singleCubic = function (start, end, apexY, opts)
578{
579 opts = opts || {};
580 var rise = Math.max(40, Math.abs(start.y - apexY) * 0.9);
581 if (opts.startSpeedPx)
582 { rise = Math.max(rise, opts.startSpeedPx); }
583 var fall = Math.max(40, Math.abs(end.y - apexY) * 0.9);
584 if (opts.endSpeedPx)
585 { fall = Math.max(40, opts.endSpeedPx); }
586 var p1 = { x: start.x, y: Math.min(start.y - rise, apexY) };
587 var p2 = { x: end.x, y: Math.min(end.y - fall, apexY) };
588 return { p0: start, p1: p1, p2: p2, p3: end, apexY: apexY };
589};
590
591/**
592 * Smooth C¹ path: rise up (launch column or outside), cruise above
593 * the field, dive into the landing column (t1134 / t1135). Joints
594 * are quarter-turn cubics with matching tangents, so there are no
595 * corners and no speed jerks. The curve may use the launch and
596 * landing corridors but does not cut across the field interior.
597 */
598Online.makeAroundCurve = function (start, end, field, opts)
599{
600 opts = opts || {};
601 if (!start)
602 { start = { x: 0, y: 0 }; }
603 if (!end)
604 { end = { x: 0, y: 0 }; }
605 var clearance = opts.clearance || 80;
606 if (!field)
607 {
608 var looseApex = Math.min(start.y, end.y) - Math.max(40, clearance * 0.5);
609 if (looseApex < 8)
610 { looseApex = Math.min(start.y, end.y) - 24; }
611 return this._singleCubic(start, end, looseApex, opts);
612 }
613 var top = field.top;
614 var left = field.left;
615 var right = field.right;
616 var apexY = top - clearance;
617 if (apexY < 8)
618 { apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }
619
620 if (start.y <= apexY + 8 && end.y <= apexY + 8)
621 { return this._singleCubic(start, end, apexY, opts); }
622
623 var pad = 14;
624 var dir = end.x >= start.x ? 1 : -1;
625 var span = Math.abs(end.x - start.x);
626 var horiz = Math.max(28, Math.min(80, span * 0.15 + 8));
627 function outsideX (x)
628 {
629 if (x < left + 8)
630 { return Math.min(x, left - pad); }
631 if (x > right - 8)
632 { return Math.max(x, right + pad); }
633 return x;
634 }
635 var riseX = outsideX(start.x);
636 var diveX = outsideX(end.x);
637 var segments = [];
638
639 // Rise ends already turned toward the cruise, at apex.
640 var riseEnd = { x: riseX + dir * horiz, y: apexY };
641 if (start.y > apexY + 4)
642 {
643 var p1 = { x: start.x, y: apexY };
644 var p2 = { x: riseX, y: apexY };
645 segments.push({ p0: start, p1: p1, p2: p2, p3: riseEnd });
646 }
647 else
648 { riseEnd = { x: start.x, y: Math.min(start.y, apexY) }; }
649
650 // Cruise stays on the apex line (convex hull is above the field).
651 var diveStart = { x: diveX - dir * horiz, y: apexY };
652 if (Math.abs(riseEnd.x - diveStart.x) > 4 || Math.abs(riseEnd.y - diveStart.y) > 4)
653 {
654 // Keep the cruise direction consistent; if the two joints
655 // would cross, just connect them directly.
656 var cdir = diveStart.x >= riseEnd.x ? 1 : -1;
657 var c1 = { x: riseEnd.x + cdir * horiz, y: riseEnd.y };
658 if (c1.y > apexY)
659 { c1.y = apexY; }
660 var c2 = { x: diveStart.x - cdir * horiz, y: diveStart.y };
661 segments.push({ p0: { x: riseEnd.x, y: riseEnd.y }, p1: c1, p2: c2, p3: diveStart });
662 }
663
664 if (end.y > apexY + 4 || Math.abs(end.x - (diveStart.x + dir * horiz)) > 2)
665 {
666 var u0 = (Math.abs(riseEnd.x - diveStart.x) > 4 || segments.length === 0)
667 ? diveStart
668 : riseEnd;
669 if (segments.length && segments[segments.length - 1].p3.x === u0.x
670 && segments[segments.length - 1].p3.y === u0.y)
671 { /* already joined */ }
672 else if (segments.length === 0)
673 { u0 = riseEnd; }
674 var u1 = { x: u0.x + dir * horiz, y: u0.y };
675 var fall = Math.max(24, Math.abs(end.y - apexY) * 0.45);
676 if (opts.endSpeedPx)
677 {
678 // |P3-P2| so arrival ≈ fallSpeed after equal-param scaling.
679 // velocity = 3*|P3-P2|*n*v1/duration; endSpeedPx is
680 // (cells*px*duration)/3, so |P3-P2| = endSpeedPx/(n*v1).
681 var nEst = Math.max(1, segments.length + 1);
682 fall = Math.max(20, opts.endSpeedPx / (nEst * 0.85));
683 }
684 var u2 = { x: end.x, y: end.y - fall };
685 // P2 may sit between the apex and the end (slower arrival);
686 // only clamp if it would pass the end or fly far past the apex.
687 if (u2.y < apexY - 240)
688 { u2.y = apexY - 240; }
689 if (u2.y > end.y - 8)
690 { u2.y = end.y - 8; }
691 segments.push({ p0: u0, p1: u1, p2: u2, p3: end });
692 }
693
694 if (segments.length === 0)
695 { return this._singleCubic(start, end, apexY, opts); }
696 if (segments.length === 1 && !segments[0].p0)
697 { return this._singleCubic(start, end, apexY, opts); }
698
699 return { segments: segments, apexY: apexY, p0: start, p3: end };
700};
701
702Online._measureCurve = function (curve)
703{
704 if (!curve.segments)
705 { return curve; }
706 var lens = [];
707 var total = 0;
708 for (var i = 0; i < curve.segments.length; i++)
709 {
710 var L = this._segLen(curve.segments[i]);
711 lens.push(L);
712 total += L;
713 }
714 curve.lens = lens;
715 curve.totalLen = Math.max(total, 1);
716 return curve;
717};
718
719Online._segLen = function (seg, steps)
720{
721 steps = steps || 10;
722 var len = 0;
723 var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
724 for (var i = 1; i <= steps; i++)
725 {
726 var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
727 var dx = p.x - prev.x;
728 var dy = p.y - prev.y;
729 len += Math.sqrt(dx * dx + dy * dy);
730 prev = p;
731 }
732 return Math.max(len, 1);
733};
734
735/**
736 * Equal-parameter split across segments so matching local C'(t)
737 * at joints also matches dP/du (no speed jerk).
738 */
739Online._curveSegmentAt = function (curve, u)
740{
741 if (!curve)
742 { return null; }
743 if (!curve.segments)
744 {
745 return { seg: curve, t: u < 0 ? 0 : (u > 1 ? 1 : u), scale: 1 };
746 }
747 var segs = curve.segments;
748 var n = segs.length;
749 if (u <= 0)
750 { return { seg: segs[0], t: 0, scale: n }; }
751 if (u >= 1)
752 { return { seg: segs[n - 1], t: 1, scale: n }; }
753 var at = u * n;
754 var i = Math.floor(at);
755 if (i >= n)
756 { i = n - 1; }
757 var t = at - i;
758 return { seg: segs[i], t: t, scale: n };
759};
760
761/** Point on a (possibly multi-segment C¹) curve at u ∈ [0, 1]. */
762Online.curvePoint = function (curve, u)
763{
764 var at = this._curveSegmentAt(curve, u);
765 if (!at)
766 { return { x: 0, y: 0 }; }
767 var s = at.seg;
768 if (s && s.p1)
769 { return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at.t); }
770 if (s && s.p0)
771 { return { x: s.p0.x, y: s.p0.y }; }
772 return { x: 0, y: 0 };
773};
774
775/** dP/du of the curve (C¹ across joints). */
776Online.curveDeriv = function (curve, u)
777{
778 var at = this._curveSegmentAt(curve, u);
779 if (!at || !at.seg || !at.seg.p1)
780 { return { x: 0, y: 0 }; }
781 var s = at.seg;
782 var d = this.cubicBezierDeriv(s.p0, s.p1, s.p2, s.p3, at.t);
783 return { x: d.x * at.scale, y: d.y * at.scale };
784};
785
786/**
787 * Sample the smooth around-field curve at u ∈ [0, 1] (t1134).
788 * `clearance` may be a number or an options object.
789 */
790Online.aroundFieldPoint = function (start, end, u, field, clearance)
791{
792 var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
793 var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
794 return this.curvePoint(curve, u);
795};
796
797/** Guide points (start, joints, end) for older tests. */
798Online.waypointsAroundField = function (start, end, field, clearance)
799{
800 var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 64 });
801 if (c.segments && c.segments.length)
802 {
803 var pts = [{ x: c.segments[0].p0.x, y: c.segments[0].p0.y }];
804 for (var i = 0; i < c.segments.length; i++)
805 { pts.push({ x: c.segments[i].p3.x, y: c.segments[i].p3.y }); }
806 return pts;
807 }
808 return [c.p0, c.p1, c.p2, c.p3];
809};
810
811Online.pointOnPath = function (points, u)
812{
813 // Legacy polyline; new flights use cubicBezier.
814 u = u < 0 ? 0 : (u > 1 ? 1 : u);
815 if (!points || !points.length)
816 { return { x: 0, y: 0 }; }
817 if (points.length === 4 && points[0] && points[3])
818 { return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
819 if (points.length === 1)
820 { return { x: points[0].x, y: points[0].y }; }
821 var n = points.length - 1;
822 var at = u * n;
823 var i = Math.floor(at);
824 if (i >= n)
825 { i = n - 1; }
826 var t = at - i;
827 var a = points[i];
828 var b = points[i + 1];
829 return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
830};
831
832/** Viewport centre of a field cell (y=0 is the bottom row). */
833Online.cellViewport = function (col, y, rect)
834{
835 if (!rect)
836 {
837 var field = this.playerFieldRect();
838 if (!field)
839 { return { x: 0, y: 0 }; }
840 rect = field;
841 }
842 var w = rect.width != null ? rect.width : (rect.right - rect.left);
843 var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
844 return {
845 x: rect.left + ((col + 0.5) / 10) * w,
846 y: rect.top + (1 - (y + 0.5) / 13) * h
847 };
848};
849
850/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
851Online.fieldEntry = function (col)
852{
853 return this.cellViewport(col == null ? 4.5 : col, 13);
854};
855
856Online.miniCellViewport = function (playerId, col, y)
857{
858 var el = this.miniElement(playerId);
859 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
860 var box = canvas || el;
861 if (!box || !box.getBoundingClientRect)
862 { return { x: window.innerWidth / 2, y: 48 }; }
863 return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
864};
865
866Online._fallSpeedPx = function (field, duration)
867{
868 var px = 40;
869 if (field && field.height)
870 { px = field.height / 13; }
871 else if (typeof app !== 'undefined' && app.tile)
872 { px = app.tile; }
873 var cells = 13 / 3;
874 if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
875 { cells = app.planet.fallSpeed; }
876 duration = duration || this.FLIGHT_DURATION;
877 // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
878 return (cells * px * duration) / 3;
879};
880
881Online.rememberLandCol = function (id, col)
882{
883 if (id == null || col == null || !isFinite(col))
884 { return; }
885 if (!this._pendingLandCol)
886 { this._pendingLandCol = Object.create(null); }
887 this._pendingLandCol[String(id)] = col | 0;
888};
889
890/** Resolve the landing column for an incoming shot (t1126). */
891Online.takeLandCol = function (incoming)
892{
893 if (!incoming)
894 { return null; }
895 if (incoming.land_col != null && isFinite(incoming.land_col))
896 { return incoming.land_col | 0; }
897 if (!this._pendingLandCol)
898 { return null; }
899 var keys = [];
900 if (incoming.id != null)
901 { keys.push(String(incoming.id)); }
902 if (incoming.client_id)
903 { keys.push(String(incoming.client_id)); }
904 for (var i = 0; i < keys.length; i++)
905 {
906 if (this._pendingLandCol[keys[i]] != null)
907 { return this._pendingLandCol[keys[i]]; }
908 }
909 return null;
910};
911
912Online._miniCellSize = function (playerId)
913{
914 var el = this.miniElement(playerId);
915 var canvas = el && el.querySelector('canvas');
916 if (canvas)
917 {
918 var r = canvas.getBoundingClientRect();
919 return Math.max(6, r.width / 10);
920 }
921 return 10;
922};
923
924Online._fullTileSize = function ()
925{
926 if (typeof app !== 'undefined' && app.tile)
927 { return app.tile; }
928 return 40;
929};
930
931Online._miniAnchor = function (playerId, dir)
932{
933 var el = this.miniElement(playerId);
934 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
935 var box = canvas || el;
936 if (!box)
937 { return { x: window.innerWidth / 2, y: 48 }; }
938 var r = box.getBoundingClientRect();
939 if (dir === 'out')
940 { return { x: r.left + r.width / 2, y: r.top + 4 }; }
941 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
942};
943
944Online._fieldTop = function (col)
945{
946 return this.fieldEntry(col);
947};
948
949/**
950 * Animate shot results. `locals` is a map of client_id → {col, y, color,
951 * startX, startY, from_id} in viewport pixels.
952 *
953 * Visual-only: a smooth cubic that leaves the real cell, arcs around
954 * the field, and dives into the landing column at the spawn pose
955 * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
956 * behind the player's field. A late-seen flight starts mid-arc via `age`.
957 */
958Online.spawnFlights = function (results, locals)
959{
960 locals = locals || this._flightLocals || {};
961 var front = document.getElementById('flights');
962 var back = document.getElementById('flights-back') || front;
963 if (!front)
964 { return; }
965 if (!this._flightSeen)
966 { this._flightSeen = Object.create(null); }
967 if (!this._previewIds)
968 { this._previewIds = Object.create(null); }
969 var now = performance.now();
970 var full = this._fullTileSize();
971 for (var i = 0; i < results.length; i++)
972 {
973 var r = results[i];
974 var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
975 if (this._flightSeen[sid])
976 {
977 if (this._previewIds[sid])
978 {
979 var existing = this._findFlight(sid);
980 if (existing)
981 {
982 var meta0 = locals[r.client_id] || locals[sid] || {};
983 this.retargetFlight(existing, r, meta0, now);
984 }
985 }
986 continue;
987 }
988 this._flightSeen[sid] = now;
989
990 var meta = locals[r.client_id] || locals[sid] || {};
991 var fromId = r.from_id || r.from_user || meta.from_id || null;
992 var targetId = r.target_id != null ? r.target_id : r.to_user;
993 var miss = !!r.miss;
994 var kind = this.flightKind(fromId, targetId, miss);
995 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
996 if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration)
997 { continue; }
998
999 var landCol = null;
1000 if (r.land_col != null && isFinite(r.land_col))
1001 { landCol = r.land_col | 0; }
1002 else if (meta.land_col != null && isFinite(meta.land_col))
1003 { landCol = meta.land_col | 0; }
1004 else if (kind === 'enemy-to-player'
1005 && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn)
1006 { landCol = app.core.pickGarbageColumn(); }
1007 if (landCol != null)
1008 {
1009 this.rememberLandCol(sid, landCol);
1010 if (r.client_id)
1011 { this.rememberLandCol(r.client_id, landCol); }
1012 }
1013
1014 var startCol = meta.col != null ? meta.col : r.col;
1015 var startY = meta.y != null ? meta.y : r.y;
1016 var start;
1017 if (meta.startX != null && isFinite(meta.startX))
1018 { start = { x: meta.startX, y: meta.startY }; }
1019 else if (kind === 'player-to-enemy' || kind === 'player-miss')
1020 { start = this._flightStart(startCol, startY); }
1021 else if (startCol != null || startY != null)
1022 { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 12); }
1023 else
1024 { start = this._miniAnchor(fromId, 'out'); }
1025
1026 var end;
1027 if (miss)
1028 { end = this._missEnd(start, kind === 'enemy-miss'); }
1029 else if (kind === 'enemy-to-player')
1030 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1031 else
1032 { end = this._targetEnd(targetId, start, landCol); }
1033
1034 // Hits are ingested as grey garbage; draw them grey (t1130).
1035 // Misses keep the sender's colour — nothing is received.
1036 var flightColor = miss
1037 ? (r.color != null ? r.color : meta.color)
1038 : -1;
1039
1040 var startScale;
1041 var endScale;
1042 var mini = this._miniCellSize(fromId || targetId) / full;
1043 if (mini < 0.12)
1044 { mini = 0.2; }
1045 if (kind === 'player-to-enemy')
1046 {
1047 startScale = 1;
1048 endScale = mini;
1049 }
1050 else if (kind === 'enemy-to-player')
1051 {
1052 startScale = mini;
1053 endScale = 1;
1054 }
1055 else if (kind === 'enemy-to-enemy')
1056 {
1057 startScale = mini;
1058 endScale = mini;
1059 }
1060 else if (kind === 'enemy-miss')
1061 {
1062 startScale = mini;
1063 endScale = 0;
1064 }
1065 else
1066 {
1067 startScale = 1;
1068 endScale = 0;
1069 }
1070
1071 var layer = (kind === 'enemy-to-enemy' && back) ? back : front;
1072 var el = document.createElement('img');
1073 el.src = colorSpriteUrl(flightColor);
1074 el.alt = '';
1075 el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : '');
1076 el.style.width = full + 'px';
1077 el.style.height = full + 'px';
1078 layer.appendChild(el);
1079
1080 var t0 = now;
1081 if (r.age != null && isFinite(r.age) && r.age > 0)
1082 {
1083 var u0 = Math.min(0.95, (r.age * 1000) / duration);
1084 t0 = now - u0 * duration;
1085 }
1086 var height = miss
1087 ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
1088 : this.arcHeight(start, end);
1089 var field = this.playerFieldRect();
1090 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1091 var clearance = Math.max(64, height * 0.45);
1092 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1093 var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
1094 clearance: clearance,
1095 startSpeedPx: endSpeed,
1096 endSpeedPx: endSpeed,
1097 duration: duration / 1000
1098 });
1099 this._flights.push({
1100 el: el,
1101 start: start,
1102 end: end,
1103 ctrl: miss ? this._missCtrl(start, end) : null,
1104 height: height,
1105 t0: t0,
1106 duration: duration,
1107 spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
1108 miss: miss,
1109 kind: kind,
1110 startScale: startScale,
1111 endScale: endScale,
1112 angle: 0,
1113 id: sid,
1114 landCol: landCol,
1115 field: field,
1116 curve: curve,
1117 color: flightColor
1118 });
1119 }
1120 this._flightLocals = {};
1121};
1122
1123Online.rememberFlightLocal = function (shot, startX, startY)
1124{
1125 if (!this._flightLocals)
1126 { this._flightLocals = {}; }
1127 this._flightLocals[String(shot.id)] = {
1128 col: shot.col,
1129 y: shot.y,
1130 color: shot.color,
1131 startX: startX,
1132 startY: startY,
1133 from_id: shot.from_id,
1134 land_col: shot.land_col,
1135 vy: shot.vy
1136 };
1137};
1138
1139Online._flightStart = function (col, y)
1140{
1141 if (y == null || !isFinite(y))
1142 { y = 12; }
1143 return this.cellViewport(col == null ? 4.5 : col, y);
1144};
1145
1146Online._targetEnd = function (targetId, start, col)
1147{
1148 var el = targetId && this.miniElement(targetId);
1149 if (el)
1150 {
1151 // Slightly inside the mini, in the landing column (t1135).
1152 return this.miniCellViewport(targetId, col, 12);
1153 }
1154 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
1155};
1156
1157Online._missEnd = function (start, fromMini)
1158{
1159 var w = window.innerWidth || 800;
1160 var outward;
1161 if (start.x < w * 0.4)
1162 { outward = -(80 + Math.random() * w * 0.25); }
1163 else if (start.x > w * 0.6)
1164 { outward = (80 + Math.random() * w * 0.25); }
1165 else
1166 { outward = (Math.random() * 2 - 1) * w * 0.35; }
1167 var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220);
1168 return { x: start.x + outward, y: start.y - lift };
1169};
1170
1171Online._missCtrl = function (start, end)
1172{
1173 return {
1174 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
1175 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
1176 };
1177};
1178
1179Online._hitCtrl = function (start, end)
1180{
1181 return {
1182 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
1183 y: (start.y + end.y) / 2 - 30
1184 };
1185};
1186
1187Online._findFlight = function (sid)
1188{
1189 sid = String(sid);
1190 if (!this._flights)
1191 { return null; }
1192 for (var i = 0; i < this._flights.length; i++)
1193 {
1194 if (String(this._flights[i].id) === sid)
1195 { return this._flights[i]; }
1196 }
1197 return null;
1198};
1199
1200/**
1201 * Early visual takeover: a flying rocket near the top of a field
1202 * becomes a flight sprite at its exact cell, so it is seen flying
1203 * *out* rather than popping in above the canvas (t1134). When the
1204 * shot is later dispatched, `retargetFlight` picks up from the
1205 * current pose and aims at the real landing column.
1206 */
1207Online.previewExit = function (info)
1208{
1209 if (!info || info.id == null)
1210 { return; }
1211 var sid = String(info.id);
1212 if (!this._flights)
1213 { this._flights = []; }
1214 if (!this._flightSeen)
1215 { this._flightSeen = Object.create(null); }
1216 if (!this._previewIds)
1217 { this._previewIds = Object.create(null); }
1218 if (this._previewIds[sid] || this._flightSeen[sid])
1219 { return; }
1220 var front = document.getElementById('flights');
1221 if (!front || !info.start)
1222 { return; }
1223 var start = info.start;
1224 var field = this.playerFieldRect();
1225 var clearance = 80;
1226 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
1227 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
1228 var apexY = (field ? field.top : start.y) - clearance;
1229 if (apexY < 8)
1230 { apexY = Math.max(8, start.y - 80); }
1231 var end = { x: start.x, y: apexY };
1232 var duration = this.FLIGHT_DURATION * 1000;
1233 var full = this._fullTileSize();
1234 var el = document.createElement('img');
1235 el.src = colorSpriteUrl(info.color);
1236 el.alt = '';
1237 el.className = 'flight';
1238 el.style.width = full + 'px';
1239 el.style.height = full + 'px';
1240 front.appendChild(el);
1241 var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
1242 var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
1243 clearance: clearance,
1244 startSpeedPx: endSpeed,
1245 endSpeedPx: endSpeed
1246 });
1247 var now = performance.now();
1248 var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
1249 if (mini < 0.12)
1250 { mini = 0.2; }
1251 this._flights.push({
1252 el: el,
1253 start: start,
1254 end: end,
1255 ctrl: null,
1256 height: clearance,
1257 t0: now,
1258 duration: duration,
1259 spin: (Math.random() * 2 - 1) * 90,
1260 miss: false,
1261 kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
1262 startScale: mini,
1263 endScale: mini,
1264 angle: 0,
1265 id: sid,
1266 landCol: null,
1267 field: field,
1268 curve: curve,
1269 preview: true,
1270 color: info.color,
1271 from_id: info.from_id || null
1272 });
1273 this._previewIds[sid] = true;
1274 this._flightSeen[sid] = now;
1275};
1276
1277/** True while a field sprite should stay hidden — the flight is its visual. */
1278Online.hasExitVisual = function (id)
1279{
1280 if (id == null)
1281 { return false; }
1282 var sid = String(id);
1283 if (this._previewIds && this._previewIds[sid])
1284 { return true; }
1285 var f = this._findFlight(sid);
1286 if (!f || f.miss)
1287 { return false; }
1288 var raw = (performance.now() - f.t0) / f.duration;
1289 return raw < 0.4;
1290};
1291
1292/**
1293 * Once the shot is scored, pick up the preview at its current pose
1294 * and fly the rest of the way to the real end (no jump).
1295 */
1296Online.retargetFlight = function (f, r, meta, now)
1297{
1298 now = now || performance.now();
1299 meta = meta || {};
1300 var raw = (now - f.t0) / f.duration;
1301 if (raw < 0)
1302 { raw = 0; }
1303 if (raw > 0.95)
1304 { raw = 0.95; }
1305 var u = this.smoothParam(raw, 0.9, 0.9);
1306 var pt = f.curve
1307 ? this.curvePoint(f.curve, u)
1308 : { x: f.start.x, y: f.start.y };
1309 var curScale = f.startScale + (f.endScale - f.startScale) * u;
1310
1311 var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
1312 var targetId = r.target_id != null ? r.target_id : r.to_user;
1313 var miss = !!r.miss;
1314 var kind = this.flightKind(fromId, targetId, miss);
1315 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1316
1317 var landCol = null;
1318 if (r.land_col != null && isFinite(r.land_col))
1319 { landCol = r.land_col | 0; }
1320 else if (meta.land_col != null && isFinite(meta.land_col))
1321 { landCol = meta.land_col | 0; }
1322 else if (f.landCol != null)
1323 { landCol = f.landCol; }
1324 if (landCol != null)
1325 { this.rememberLandCol(String(f.id), landCol); }
1326
1327 var end;
1328 if (miss)
1329 { end = this._missEnd(pt, kind === 'enemy-miss'); }
1330 else if (kind === 'enemy-to-player')
1331 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1332 else
1333 { end = this._targetEnd(targetId, pt, landCol); }
1334
1335 var flightColor = miss
1336 ? (r.color != null ? r.color : meta.color)
1337 : -1;
1338 if (f.el && flightColor !== f.color)
1339 { f.el.src = colorSpriteUrl(flightColor); }
1340
1341 var full = this._fullTileSize();
1342 var mini = this._miniCellSize(fromId || targetId) / full;
1343 if (mini < 0.12)
1344 { mini = 0.2; }
1345 var endScale;
1346 if (kind === 'player-to-enemy')
1347 { endScale = mini; }
1348 else if (kind === 'enemy-to-player')
1349 { endScale = 1; }
1350 else if (kind === 'enemy-to-enemy')
1351 { endScale = mini; }
1352 else
1353 { endScale = 0; }
1354
1355 var field = this.playerFieldRect();
1356 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1357 var height = miss
1358 ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
1359 : this.arcHeight(pt, end);
1360 var clearance = Math.max(64, height * 0.45);
1361 var endSpeed = this._fallSpeedPx(field, duration / 1000);
1362 var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
1363 clearance: clearance,
1364 startSpeedPx: endSpeed,
1365 endSpeedPx: endSpeed
1366 });
1367
1368 f.start = pt;
1369 f.end = end;
1370 f.t0 = now;
1371 f.duration = duration;
1372 f.curve = curve;
1373 f.ctrl = miss ? this._missCtrl(pt, end) : null;
1374 f.height = height;
1375 f.miss = miss;
1376 f.kind = kind;
1377 f.startScale = curScale;
1378 f.endScale = endScale;
1379 f.landCol = landCol;
1380 f.field = field;
1381 f.preview = false;
1382 f.color = flightColor;
1383 f.from_id = fromId;
1384 if (this._previewIds)
1385 { delete this._previewIds[String(f.id)]; }
1386
1387 if (kind === 'enemy-to-enemy' && f.el)
1388 {
1389 var back = document.getElementById('flights-back');
1390 if (back && f.el.parentNode !== back)
1391 {
1392 f.el.className = 'flight flight-behind';
1393 back.appendChild(f.el);
1394 }
1395 }
1396};
1397
1398/** Point and (optional) derivative of a flight at parameter u. */
1399Online.flightPointAt = function (f, u)
1400{
1401 if (!f)
1402 { return { x: 0, y: 0 }; }
1403 if (f.curve)
1404 { return this.curvePoint(f.curve, u); }
1405 if (f.miss && f.ctrl)
1406 {
1407 var e = u;
1408 var mt = 1 - e;
1409 return {
1410 x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
1411 y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
1412 };
1413 }
1414 return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1415};
1416
1417Online.pointAllowedOnArc = function (p, field, start, end, slop)
1418{
1419 if (!this.pointInFieldInterior(p.x, p.y, field, slop))
1420 { return true; }
1421 if (!field)
1422 { return true; }
1423 var w = (field.right - field.left) / 10;
1424 var corridor = w * 0.7;
1425 if (start && Math.abs(p.x - start.x) <= corridor)
1426 { return true; }
1427 if (end && Math.abs(p.x - end.x) <= corridor)
1428 { return true; }
1429 return false;
1430};
1431
1432Online.tickFlights = function (now)
1433{
1434 now = now || performance.now();
1435 var leftover = [];
1436 for (var i = 0; i < this._flights.length; i++)
1437 {
1438 var f = this._flights[i];
1439 var raw = (now - f.t0) / f.duration;
1440 if (raw >= 1)
1441 {
1442 if (f.el && f.el.parentNode)
1443 { f.el.parentNode.removeChild(f.el); }
1444 if (this._previewIds)
1445 { delete this._previewIds[String(f.id)]; }
1446 continue;
1447 }
1448 if (raw < 0)
1449 { raw = 0; }
1450 // Non-zero endpoint speed so the handoff matches fallSpeed (t1135).
1451 var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, 0.85, 0.85);
1452 var x, y;
1453 if (f.miss && f.ctrl)
1454 {
1455 var e = raw * raw;
1456 var mt = 1 - e;
1457 x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
1458 y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
1459 }
1460 else if (f.curve)
1461 {
1462 var pt = this.curvePoint(f.curve, u);
1463 x = pt.x;
1464 y = pt.y;
1465 }
1466 else
1467 {
1468 var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1469 x = pt.x;
1470 y = pt.y;
1471 }
1472 var scale = f.startScale + (f.endScale - f.startScale) * u;
1473 if (f.miss)
1474 {
1475 var fadeU = raw * raw;
1476 scale = f.startScale * (1 - fadeU);
1477 }
1478 var angle = f.angle + f.spin * raw;
1479 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
1480 + angle + 'deg) scale(' + scale + ')';
1481 f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1';
1482 leftover.push(f);
1483 }
1484 this._flights = leftover;
1485 if (this._flightSeen)
1486 {
1487 var cutoff = now - 8000;
1488 var ids = Object.keys(this._flightSeen);
1489 for (var k = 0; k < ids.length; k++)
1490 {
1491 if (this._flightSeen[ids[k]] < cutoff)
1492 { delete this._flightSeen[ids[k]]; }
1493 }
1494 }
1495};
1496
1497Online.clearFlights = function ()
1498{
1499 for (var i = 0; i < this._flights.length; i++)
1500 {
1501 var el = this._flights[i].el;
1502 if (el && el.parentNode)
1503 { el.parentNode.removeChild(el); }
1504 }
1505 this._flights = [];
1506 this._flightLocals = {};
1507 this._flightSeen = Object.create(null);
1508 this._pendingLandCol = Object.create(null);
1509 this._previewIds = Object.create(null);
1510};
1511
1512if (typeof globalThis !== 'undefined')
1513{ globalThis.Online = Online; }
1514if (typeof module !== 'undefined' && module.exports)
1515{ module.exports = Online; }