Merge branch 'feature/t1181-local-flights'
@@ -196,6 +196,17 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou
196
196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
197
197
op het podium en daarna ga je terug naar de lobby.
198
198
199
### Vliegende blokken en mini-velden (vloeiend)
200
201
- Een blok dat je wegschiet vliegt **meteen** lokaal weg (geen wachten op de
202
server). Zodra de server antwoordt (raak/mis, doelkolom) buigt dezelfde
203
vlucht vloeiend af naar het echte doel; geen sprong, geen tweede blok.
204
- Een tegenstander ziet de vlucht vanaf jouw mini-veld vertrekken zodra het
205
serverbericht binnenkomt, als volledige boog (iets ingekort bij vertraging).
206
- Op de mini-velden van tegenstanders vallen blokken tussen de
207
serverupdates door vloeiend verder (voorspelling met hun valsnelheid).
208
Landen of lijnen wissen wordt nooit voorspeld: dat komt altijd van de server.
209
199
210
### Wat Tim moet instellen
200
211
201
212
Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
@@ -196,6 +196,17 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden196
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden197
op het podium en daarna ga je terug naar de lobby.197
op het podium en daarna ga je terug naar de lobby.198
198
199
### Vliegende blokken en mini-velden (vloeiend)200
201
- Een blok dat je wegschiet vliegt **meteen** lokaal weg (geen wachten op de202
server). Zodra de server antwoordt (raak/mis, doelkolom) buigt dezelfde203
vlucht vloeiend af naar het echte doel; geen sprong, geen tweede blok.204
- Een tegenstander ziet de vlucht vanaf jouw mini-veld vertrekken zodra het205
serverbericht binnenkomt, als volledige boog (iets ingekort bij vertraging).206
- Op de mini-velden van tegenstanders vallen blokken tussen de207
serverupdates door vloeiend verder (voorspelling met hun valsnelheid).208
Landen of lijnen wissen wordt nooit voorspeld: dat komt altijd van de server.209
199
### Wat Tim moet instellen210
### Wat Tim moet instellen200
211
201
Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo212
Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo@@ -8462,6 +8462,237 @@ if (typeof module !== 'undefined' && module.exports && typeof MiniLayout !== 'un
8462
8462
* /workspace/meteors/src/miniLayout.js
8463
8463
*/
8464
8464
8465
/*
8466
* Start File:
8467
* /workspace/meteors/src/miniPredict.js
8468
*/
8469
'use strict';
8470
8471
/**
8472
* t1182: client-side prediction for falling blocks on opponents' mini
8473
* fields. Purely visual. Between snapshots (one per poll, ~0.75 s) a
8474
* block whose authoritative state is 'falling' keeps descending at that
8475
* player's fallSpeed (13 / fallTime cells/s), with sub-cell motion. It
8476
* never goes below the first obstacle in its column, so a landing, lock
8477
* or match is never predicted — those only appear when the next
8478
* snapshot says so. When a snapshot arrives the shown position is
8479
* reconciled smoothly: a block that lags catches up a little faster, a
8480
* block that ran ahead falls more slowly until the truth catches up
8481
* (it never moves up), and a large difference snaps.
8482
*/
8483
var MiniPredict = {
8484
FIELD_HEIGHT: 13,
8485
/** Seconds over which a lagging block closes its gap (on top of fallSpeed). */
8486
RECONCILE_S: 0.16,
8487
/** Cells: further off than this → snap to the authoritative pose. */
8488
SNAP_CELLS: 1.5,
8489
/** Never extrapolate further than this past the last snapshot (s). */
8490
MAX_EXTRAP_S: 1.5,
8491
/** Share of fallSpeed used while a block that ran ahead waits for the truth. */
8492
AHEAD_SPEED_SHARE: 0.5,
8493
/** Largest frame step used for the smoothing integrator (s). */
8494
MAX_FRAME_S: 0.1
8495
};
8496
8497
/** Arrival samples kept for the sender-clock offset estimate. */
8498
MiniPredict.OFFSET_SAMPLES = 16;
8499
8500
MiniPredict.create = function ()
8501
{
8502
return { snap: null, at: 0, lastFrame: 0, shown: Object.create(null), offsets: [], sig: null };
8503
};
8504
8505
/** Cheap content signature for snapshots without a sender time. */
8506
MiniPredict.signature = function (snapshot)
8507
{
8508
if (!snapshot || !snapshot.blocks)
8509
{ return ''; }
8510
var s = String(snapshot.blocks.length);
8511
for (var i = 0; i < snapshot.blocks.length; i++)
8512
{
8513
var b = snapshot.blocks[i];
8514
s += '|' + b.id + ':' + b.y + ':' + b.state;
8515
}
8516
return s;
8517
};
8518
8519
MiniPredict.fallSpeedFor = function (planet)
8520
{
8521
var ft = planet && (planet.fallTime != null ? planet.fallTime : planet.fall_time);
8522
ft = Number(ft);
8523
if (!(ft > 0))
8524
{ ft = 3; }
8525
return this.FIELD_HEIGHT / ft;
8526
};
8527
8528
/**
8529
* Record an authoritative snapshot. A poll can repeat the same
8530
* snapshot (the opponent has not polled since); that must not restart
8531
* the extrapolation. With a sender time `t` (ms, sender clock) the
8532
* snapshot's moment is mapped to our clock via the smallest observed
8533
* arrival offset, so a late-arriving snapshot is placed at the time it
8534
* was really taken. Returns true when the snapshot is new.
8535
*/
8536
MiniPredict.update = function (st, snapshot, now)
8537
{
8538
if (snapshot === st.snap)
8539
{ return false; }
8540
if (!snapshot)
8541
{
8542
st.snap = null;
8543
st.sig = null;
8544
return false;
8545
}
8546
var hasT = snapshot.t != null && isFinite(snapshot.t);
8547
if (st.snap && hasT && st.snap.t === snapshot.t)
8548
{
8549
st.snap = snapshot;
8550
return false;
8551
}
8552
if (!hasT)
8553
{
8554
var sig = this.signature(snapshot);
8555
if (st.snap && sig === st.sig)
8556
{
8557
st.snap = snapshot;
8558
return false;
8559
}
8560
st.sig = sig;
8561
st.snap = snapshot;
8562
st.at = now;
8563
return true;
8564
}
8565
st.offsets.push(now - snapshot.t);
8566
if (st.offsets.length > this.OFFSET_SAMPLES)
8567
{ st.offsets.shift(); }
8568
var off = Math.min.apply(null, st.offsets);
8569
st.snap = snapshot;
8570
st.sig = null;
8571
// Never in the future, never older than the extrapolation cap.
8572
st.at = Math.max(now - this.MAX_EXTRAP_S * 1000, Math.min(now, snapshot.t + off));
8573
return true;
8574
};
8575
8576
/**
8577
* Predicted y for every falling block at time `now`, clamped above the
8578
* first non-falling block (or the floor) below it in its column, chaining
8579
* falling blocks in the same column bottom-up. Returns id → y.
8580
*/
8581
MiniPredict.predict = function (snapshot, sinceS, fallSpeed)
8582
{
8583
var out = Object.create(null);
8584
if (!snapshot || !snapshot.blocks)
8585
{ return out; }
8586
var dt = Math.max(0, Math.min(this.MAX_EXTRAP_S, sinceS || 0));
8587
var cols = Object.create(null);
8588
var blocks = snapshot.blocks;
8589
for (var i = 0; i < blocks.length; i++)
8590
{
8591
var b = blocks[i];
8592
(cols[b.col] = cols[b.col] || []).push(b);
8593
}
8594
for (var c in cols)
8595
{
8596
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });
8597
var floor = 0; // lowest y the next block may occupy
8598
for (var k = 0; k < list.length; k++)
8599
{
8600
var blk = list[k];
8601
if (blk.state === 'falling')
8602
{
8603
var y = Math.max(floor, blk.y - fallSpeed * dt);
8604
if (y > blk.y)
8605
{ y = blk.y; } // only ever predict downwards
8606
out[blk.id] = y;
8607
floor = y + 1;
8608
}
8609
else
8610
{ floor = Math.max(floor, blk.y + 1); }
8611
}
8612
}
8613
return out;
8614
};
8615
8616
/**
8617
* Advance the shown positions to `now` and return id → display y for
8618
* falling blocks. Non-falling blocks are not in the map (draw them at
8619
* their authoritative y).
8620
*/
8621
MiniPredict.step = function (st, now, fallSpeed)
8622
{
8623
var frame = st.lastFrame ? Math.min(this.MAX_FRAME_S, Math.max(0, (now - st.lastFrame) / 1000)) : 0;
8624
st.lastFrame = now;
8625
var target = this.predict(st.snap, (now - st.at) / 1000, fallSpeed);
8626
var shown = Object.create(null);
8627
var floors = this._floors(st.snap, target);
8628
for (var id in target)
8629
{
8630
var t = target[id];
8631
var s = st.shown[id];
8632
if (s == null || !isFinite(s) || Math.abs(s - t) > this.SNAP_CELLS)
8633
{ s = t; }
8634
else if (s > t)
8635
{
8636
// Lagging: fall at fallSpeed plus a share of the gap.
8637
s -= (fallSpeed + (s - t) / this.RECONCILE_S) * frame;
8638
if (s < t)
8639
{ s = t; }
8640
}
8641
else if (s < t)
8642
{
8643
// Ran ahead: keep falling, slower, never upwards.
8644
s -= fallSpeed * this.AHEAD_SPEED_SHARE * frame;
8645
}
8646
var fl = floors[id] != null ? floors[id] : 0;
8647
if (s < fl)
8648
{ s = fl; }
8649
shown[id] = s;
8650
}
8651
st.shown = shown;
8652
return shown;
8653
};
8654
8655
/** Floor (lowest allowed y) for each falling block given the targets. */
8656
MiniPredict._floors = function (snapshot, target)
8657
{
8658
var out = Object.create(null);
8659
if (!snapshot || !snapshot.blocks)
8660
{ return out; }
8661
var cols = Object.create(null);
8662
for (var i = 0; i < snapshot.blocks.length; i++)
8663
{
8664
var b = snapshot.blocks[i];
8665
(cols[b.col] = cols[b.col] || []).push(b);
8666
}
8667
for (var c in cols)
8668
{
8669
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });
8670
var floor = 0;
8671
for (var k = 0; k < list.length; k++)
8672
{
8673
var blk = list[k];
8674
if (blk.state === 'falling')
8675
{
8676
out[blk.id] = floor;
8677
floor = (target[blk.id] != null ? target[blk.id] : blk.y) + 1;
8678
}
8679
else
8680
{ floor = Math.max(floor, blk.y + 1); }
8681
}
8682
}
8683
return out;
8684
};
8685
8686
if (typeof globalThis !== 'undefined')
8687
{ globalThis.MiniPredict = MiniPredict; }
8688
if (typeof module !== 'undefined' && module.exports)
8689
{ module.exports = MiniPredict; }
8690
8691
/*
8692
* End File:
8693
* /workspace/meteors/src/miniPredict.js
8694
*/
8695
8465
8696
/*
8466
8697
* Start File:
8467
8698
* /workspace/meteors/src/online.js
@@ -8492,6 +8723,10 @@ var Online = {
8492
8723
error: '',
8493
8724
_timer: null,
8494
8725
_pendingShots: [],
8726
_pollInFlight: false,
8727
_flushPending: false,
8728
_lastPollAt: 0,
8729
_getPayload: null,
8495
8730
_flights: [],
8496
8731
_lastStatus: null,
8497
8732
onChange: null,
@@ -8703,8 +8938,16 @@ Online.poll = function (opts)
8703
8938
}
8704
8939
var self = this;
8705
8940
var prevStatus = this.lobby && this.lobby.status;
8941
this._pollInFlight = true;
8942
this._lastPollAt = Date.now();
8706
8943
return this.request('poll', body).then(function (data)
8707
8944
{
8945
self._pollInFlight = false;
8946
if (self._flushPending)
8947
{
8948
self._flushPending = false;
8949
self.flushShotsSoon();
8950
}
8708
8951
self._handleTransitions(prevStatus, data);
8709
8952
if (self.onChange)
8710
8953
{ self.onChange(self); }
@@ -8739,6 +8982,7 @@ Online.startPolling = function (getPayload)
8739
8982
{
8740
8983
this.stopPolling();
8741
8984
var self = this;
8985
this._getPayload = getPayload || null;
8742
8986
var tick = function ()
8743
8987
{
8744
8988
var payload = getPayload ? getPayload() : {};
@@ -8748,8 +8992,68 @@ Online.startPolling = function (getPayload)
8748
8992
this._timer = setInterval(tick, this.POLL_MS);
8749
8993
};
8750
8994
8995
/** Minimum gap between an extra shot flush and the previous poll (ms). */
8996
Online.FLUSH_MIN_GAP_MS = 120;
8997
8998
/**
8999
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the
9000
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).
9001
*/
9002
Online.flushDecision = function (state)
9003
{
9004
if (!state || !state.polling || !(state.pending > 0))
9005
{ return 'none'; }
9006
if (state.inFlight)
9007
{ return 'later'; }
9008
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))
9009
{ return 'later'; }
9010
return 'now';
9011
};
9012
9013
/**
9014
* Send freshly cleared shots on the next possible poll instead of up to
9015
* POLL_MS later, so the server's hit/miss result (and the retarget of the
9016
* local flight) arrives in about one round trip. Network cadence only;
9017
* the server still decides hits, targets and delivery (t1181).
9018
*/
9019
Online.flushShotsSoon = function ()
9020
{
9021
var self = this;
9022
var d = this.flushDecision({
9023
polling: !!this._timer,
9024
pending: this._pendingShots.length,
9025
inFlight: this._pollInFlight,
9026
sinceLast: Date.now() - (this._lastPollAt || 0)
9027
});
9028
if (d === 'none')
9029
{ return d; }
9030
if (d === 'later')
9031
{
9032
if (this._pollInFlight)
9033
{ this._flushPending = true; }
9034
else if (!this._flushTimer)
9035
{
9036
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));
9037
this._flushTimer = setTimeout(function ()
9038
{
9039
self._flushTimer = null;
9040
self.flushShotsSoon();
9041
}, wait);
9042
}
9043
return d;
9044
}
9045
this.poll(this._getPayload ? this._getPayload() : {});
9046
return d;
9047
};
9048
8751
9049
Online.stopPolling = function ()
8752
9050
{
9051
if (this._flushTimer)
9052
{
9053
clearTimeout(this._flushTimer);
9054
this._flushTimer = null;
9055
}
9056
this._flushPending = false;
8753
9057
if (this._timer)
8754
9058
{
8755
9059
clearInterval(this._timer);
@@ -8851,7 +9155,7 @@ Online.renderMinis = function (container)
8851
9155
? I18n.t('hud.miniPoints', { n: p.score || 0 })
8852
9156
: ('Points ' + (p.score || 0));
8853
9157
}
8854
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
9158
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));
8855
9159
}
8856
9160
for (var id in existing)
8857
9161
{
@@ -8872,7 +9176,28 @@ function miniColor (planet, color)
8872
9176
}
8873
9177
8874
9178
8875
Online._drawMini = function (canvas, snapshot, planet)
9179
/**
9180
* t1182: smoothed display y for an opponent's falling blocks (see
9181
* src/miniPredict.js). Returns id → y, or null without the module.
9182
*/
9183
Online._predictMini = function (p, now)
9184
{
9185
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;
9186
if (!MP || !p)
9187
{ return null; }
9188
if (!this._miniPredict)
9189
{ this._miniPredict = Object.create(null); }
9190
var st = this._miniPredict[p.id];
9191
if (!st)
9192
{ st = this._miniPredict[p.id] = MP.create(); }
9193
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());
9194
MP.update(st, p.snapshot, now);
9195
if (p.eliminated)
9196
{ return null; }
9197
return MP.step(st, now, MP.fallSpeedFor(p.planet));
9198
};
9199
9200
Online._drawMini = function (canvas, snapshot, planet, shownY)
8876
9201
{
8877
9202
if (!canvas)
8878
9203
{ return; }
@@ -8919,7 +9244,8 @@ Online._drawMini = function (canvas, snapshot, planet)
8919
9244
{
8920
9245
var b = blocks[i];
8921
9246
var x = b.col * tw;
8922
var y = canvas.height - (b.y + 1) * th;
9247
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
9248
var y = canvas.height - (by + 1) * th;
8923
9249
if (b.state === 'locked')
8924
9250
{ ctx.fillStyle = '#3a3d4a'; }
8925
9251
else if (b.color < 0)
@@ -9732,6 +10058,17 @@ Online.spawnFlights = function (results, locals)
9732
10058
{
9733
10059
var r = results[i];
9734
10060
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
10061
// Own shot already flying locally since the clear (t1181):
10062
// pick it up at its current pose and fly on to the real target.
10063
var cid = r.client_id != null ? String(r.client_id) : null;
10064
if (cid && this._previewIds[cid] && this._isOwnShot(r))
10065
{
10066
var own = this._findFlight(cid);
10067
this._flightSeen[sid] = now;
10068
if (own)
10069
{ this.retargetFlight(own, r, locals[cid] || {}, now); }
10070
continue;
10071
}
9735
10072
if (this._flightSeen[sid])
9736
10073
{
9737
10074
if (this._previewIds[sid])
@@ -9837,12 +10174,11 @@ Online.spawnFlights = function (results, locals)
9837
10174
el.style.height = full + 'px';
9838
10175
layer.appendChild(el);
9839
10176
10177
// A flight seen late (poll delay) still starts at the sender's
10178
// field and plays the whole arc, just a bit faster, so it lands
10179
// about when the server delivers it — never a mid-arc pop-in (t1181).
9840
10180
var t0 = now;
9841
if (r.age != null && isFinite(r.age) && r.age > 0)
9842
{
9843
var u0 = Math.min(0.95, (r.age * 1000) / duration);
9844
t0 = now - u0 * duration;
9845
}
10181
duration = this.lateFlightDuration(r.age, duration);
9846
10182
var height = miss
9847
10183
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
9848
10184
: this.arcHeight(start, end);
@@ -9879,6 +10215,52 @@ Online.spawnFlights = function (results, locals)
9879
10215
this._flightLocals = {};
9880
10216
};
9881
10217
10218
/** Shortest share of the normal flight a late-seen flight may get. */
10219
Online.LATE_MIN_SHARE = 0.5;
10220
10221
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */
10222
Online.lateFlightDuration = function (age, duration)
10223
{
10224
if (age == null || !isFinite(age) || age <= 0)
10225
{ return duration; }
10226
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);
10227
};
10228
10229
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */
10230
Online.retargetDuration = function (elapsedMs, duration)
10231
{
10232
if (!(elapsedMs > 0))
10233
{ return duration; }
10234
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);
10235
};
10236
10237
Online._isOwnShot = function (r)
10238
{
10239
var mine = this.me && this.me.id;
10240
var from = r.from_id || r.from_user || null;
10241
return !from || (mine != null && String(from) === String(mine));
10242
};
10243
10244
/**
10245
* Sender side (t1181): start the flight the moment the block leaves the
10246
* field, before any server round trip. It rises out of the exit cell;
10247
* the poll answer retargets it (hit → opponent mini, miss → off-screen).
10248
*/
10249
Online.startLocalShot = function (shot, start)
10250
{
10251
if (!shot || !start)
10252
{ return null; }
10253
return this.previewExit({
10254
id: shot.id,
10255
col: shot.col,
10256
y: shot.y,
10257
vy: shot.vy,
10258
color: shot.color,
10259
start: start,
10260
from_id: null
10261
});
10262
};
10263
9882
10264
Online.rememberFlightLocal = function (shot, startX, startY)
9883
10265
{
9884
10266
if (!this._flightLocals)
@@ -10045,6 +10427,7 @@ Online.previewExit = function (info)
10045
10427
});
10046
10428
this._previewIds[sid] = true;
10047
10429
this._flightSeen[sid] = now;
10430
return true;
10048
10431
};
10049
10432
10050
10433
/** True while a field sprite should stay hidden — the flight is its visual. */
@@ -10086,6 +10469,8 @@ Online.retargetFlight = function (f, r, meta, now)
10086
10469
var miss = !!r.miss;
10087
10470
var kind = this.flightKind(fromId, targetId, miss);
10088
10471
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
10472
if (f.preview)
10473
{ duration = this.retargetDuration(now - f.t0, duration); }
10089
10474
10090
10475
var landCol = null;
10091
10476
if (r.land_col != null && isFinite(r.land_col))
@@ -10202,6 +10587,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)
10202
10587
return false;
10203
10588
};
10204
10589
10590
/** How long a local preview may wait at its apex for the server (ms). */
10591
Online.PREVIEW_HOLD_MS = 2500;
10592
10205
10593
Online.tickFlights = function (now)
10206
10594
{
10207
10595
now = now || performance.now();
@@ -10210,6 +10598,8 @@ Online.tickFlights = function (now)
10210
10598
{
10211
10599
var f = this._flights[i];
10212
10600
var raw = (now - f.t0) / f.duration;
10601
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)
10602
{ raw = 0.999; }
10213
10603
if (raw >= 1)
10214
10604
{
10215
10605
if (f.el && f.el.parentNode)
@@ -10282,6 +10672,7 @@ Online.clearFlights = function ()
10282
10672
this._flightSeen = Object.create(null);
10283
10673
this._pendingLandCol = Object.create(null);
10284
10674
this._previewIds = Object.create(null);
10675
this._miniPredict = Object.create(null);
10285
10676
};
10286
10677
10287
10678
if (typeof globalThis !== 'undefined')
@@ -13715,8 +14106,14 @@ function tickOnline (dt)
13715
14106
var s = shots[i];
13716
14107
var start = fieldToViewport(s.col, s.y);
13717
14108
Online.rememberFlightLocal(s, start.x, start.y);
14109
// Draw the flight locally right away (t1181); the server
14110
// answer only retargets it.
14111
if (Online.startLocalShot)
14112
{ Online.startLocalShot(s, start); }
13718
14113
}
13719
14114
Online.queueShots(shots);
14115
if (shots.length && Online.flushShotsSoon)
14116
{ Online.flushShotsSoon(); }
13720
14117
}
13721
14118
Online.tickFlights();
13722
14119
Online.renderMinis(document.getElementById('minis'));
@@ -14168,8 +14565,12 @@ function onlinePayload ()
14168
14565
{
14169
14566
if (!app.online || !app.core)
14170
14567
{ return {}; }
14568
var snap = app.core.fieldSnapshot();
14569
// t1182: sender time (ms) so opponents can place the snapshot in
14570
// time and predict falling blocks smoothly. Visual only.
14571
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
14171
14572
return {
14172
snapshot: app.core.fieldSnapshot(),
14573
snapshot: snap,
14173
14574
score: app.core.score,
14174
14575
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
14175
14576
};
@@ -8462,6 +8462,237 @@ if (typeof module !== 'undefined' && module.exports && typeof MiniLayout !== 'un8462
* /workspace/meteors/src/miniLayout.js8462
* /workspace/meteors/src/miniLayout.js8463
*/ 8463
*/ 8464
8464
8465
/*8466
* Start File:8467
* /workspace/meteors/src/miniPredict.js8468
*/ 8469
'use strict';8470
8471
/**8472
* t1182: client-side prediction for falling blocks on opponents' mini8473
* fields. Purely visual. Between snapshots (one per poll, ~0.75 s) a8474
* block whose authoritative state is 'falling' keeps descending at that8475
* player's fallSpeed (13 / fallTime cells/s), with sub-cell motion. It8476
* never goes below the first obstacle in its column, so a landing, lock8477
* or match is never predicted — those only appear when the next8478
* snapshot says so. When a snapshot arrives the shown position is8479
* reconciled smoothly: a block that lags catches up a little faster, a8480
* block that ran ahead falls more slowly until the truth catches up8481
* (it never moves up), and a large difference snaps.8482
*/8483
var MiniPredict = {8484
FIELD_HEIGHT: 13,8485
/** Seconds over which a lagging block closes its gap (on top of fallSpeed). */8486
RECONCILE_S: 0.16,8487
/** Cells: further off than this → snap to the authoritative pose. */8488
SNAP_CELLS: 1.5,8489
/** Never extrapolate further than this past the last snapshot (s). */8490
MAX_EXTRAP_S: 1.5,8491
/** Share of fallSpeed used while a block that ran ahead waits for the truth. */8492
AHEAD_SPEED_SHARE: 0.5,8493
/** Largest frame step used for the smoothing integrator (s). */8494
MAX_FRAME_S: 0.18495
};8496
8497
/** Arrival samples kept for the sender-clock offset estimate. */8498
MiniPredict.OFFSET_SAMPLES = 16;8499
8500
MiniPredict.create = function ()8501
{8502
return { snap: null, at: 0, lastFrame: 0, shown: Object.create(null), offsets: [], sig: null };8503
};8504
8505
/** Cheap content signature for snapshots without a sender time. */8506
MiniPredict.signature = function (snapshot)8507
{8508
if (!snapshot || !snapshot.blocks)8509
{ return ''; }8510
var s = String(snapshot.blocks.length);8511
for (var i = 0; i < snapshot.blocks.length; i++)8512
{8513
var b = snapshot.blocks[i];8514
s += '|' + b.id + ':' + b.y + ':' + b.state;8515
}8516
return s;8517
};8518
8519
MiniPredict.fallSpeedFor = function (planet)8520
{8521
var ft = planet && (planet.fallTime != null ? planet.fallTime : planet.fall_time);8522
ft = Number(ft);8523
if (!(ft > 0))8524
{ ft = 3; }8525
return this.FIELD_HEIGHT / ft;8526
};8527
8528
/**8529
* Record an authoritative snapshot. A poll can repeat the same8530
* snapshot (the opponent has not polled since); that must not restart8531
* the extrapolation. With a sender time `t` (ms, sender clock) the8532
* snapshot's moment is mapped to our clock via the smallest observed8533
* arrival offset, so a late-arriving snapshot is placed at the time it8534
* was really taken. Returns true when the snapshot is new.8535
*/8536
MiniPredict.update = function (st, snapshot, now)8537
{8538
if (snapshot === st.snap)8539
{ return false; }8540
if (!snapshot)8541
{8542
st.snap = null;8543
st.sig = null;8544
return false;8545
}8546
var hasT = snapshot.t != null && isFinite(snapshot.t);8547
if (st.snap && hasT && st.snap.t === snapshot.t)8548
{8549
st.snap = snapshot;8550
return false;8551
}8552
if (!hasT)8553
{8554
var sig = this.signature(snapshot);8555
if (st.snap && sig === st.sig)8556
{8557
st.snap = snapshot;8558
return false;8559
}8560
st.sig = sig;8561
st.snap = snapshot;8562
st.at = now;8563
return true;8564
}8565
st.offsets.push(now - snapshot.t);8566
if (st.offsets.length > this.OFFSET_SAMPLES)8567
{ st.offsets.shift(); }8568
var off = Math.min.apply(null, st.offsets);8569
st.snap = snapshot;8570
st.sig = null;8571
// Never in the future, never older than the extrapolation cap.8572
st.at = Math.max(now - this.MAX_EXTRAP_S * 1000, Math.min(now, snapshot.t + off));8573
return true;8574
};8575
8576
/**8577
* Predicted y for every falling block at time `now`, clamped above the8578
* first non-falling block (or the floor) below it in its column, chaining8579
* falling blocks in the same column bottom-up. Returns id → y.8580
*/8581
MiniPredict.predict = function (snapshot, sinceS, fallSpeed)8582
{8583
var out = Object.create(null);8584
if (!snapshot || !snapshot.blocks)8585
{ return out; }8586
var dt = Math.max(0, Math.min(this.MAX_EXTRAP_S, sinceS || 0));8587
var cols = Object.create(null);8588
var blocks = snapshot.blocks;8589
for (var i = 0; i < blocks.length; i++)8590
{8591
var b = blocks[i];8592
(cols[b.col] = cols[b.col] || []).push(b);8593
}8594
for (var c in cols)8595
{8596
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });8597
var floor = 0; // lowest y the next block may occupy8598
for (var k = 0; k < list.length; k++)8599
{8600
var blk = list[k];8601
if (blk.state === 'falling')8602
{8603
var y = Math.max(floor, blk.y - fallSpeed * dt);8604
if (y > blk.y)8605
{ y = blk.y; } // only ever predict downwards8606
out[blk.id] = y;8607
floor = y + 1;8608
}8609
else8610
{ floor = Math.max(floor, blk.y + 1); }8611
}8612
}8613
return out;8614
};8615
8616
/**8617
* Advance the shown positions to `now` and return id → display y for8618
* falling blocks. Non-falling blocks are not in the map (draw them at8619
* their authoritative y).8620
*/8621
MiniPredict.step = function (st, now, fallSpeed)8622
{8623
var frame = st.lastFrame ? Math.min(this.MAX_FRAME_S, Math.max(0, (now - st.lastFrame) / 1000)) : 0;8624
st.lastFrame = now;8625
var target = this.predict(st.snap, (now - st.at) / 1000, fallSpeed);8626
var shown = Object.create(null);8627
var floors = this._floors(st.snap, target);8628
for (var id in target)8629
{8630
var t = target[id];8631
var s = st.shown[id];8632
if (s == null || !isFinite(s) || Math.abs(s - t) > this.SNAP_CELLS)8633
{ s = t; }8634
else if (s > t)8635
{8636
// Lagging: fall at fallSpeed plus a share of the gap.8637
s -= (fallSpeed + (s - t) / this.RECONCILE_S) * frame;8638
if (s < t)8639
{ s = t; }8640
}8641
else if (s < t)8642
{8643
// Ran ahead: keep falling, slower, never upwards.8644
s -= fallSpeed * this.AHEAD_SPEED_SHARE * frame;8645
}8646
var fl = floors[id] != null ? floors[id] : 0;8647
if (s < fl)8648
{ s = fl; }8649
shown[id] = s;8650
}8651
st.shown = shown;8652
return shown;8653
};8654
8655
/** Floor (lowest allowed y) for each falling block given the targets. */8656
MiniPredict._floors = function (snapshot, target)8657
{8658
var out = Object.create(null);8659
if (!snapshot || !snapshot.blocks)8660
{ return out; }8661
var cols = Object.create(null);8662
for (var i = 0; i < snapshot.blocks.length; i++)8663
{8664
var b = snapshot.blocks[i];8665
(cols[b.col] = cols[b.col] || []).push(b);8666
}8667
for (var c in cols)8668
{8669
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });8670
var floor = 0;8671
for (var k = 0; k < list.length; k++)8672
{8673
var blk = list[k];8674
if (blk.state === 'falling')8675
{8676
out[blk.id] = floor;8677
floor = (target[blk.id] != null ? target[blk.id] : blk.y) + 1;8678
}8679
else8680
{ floor = Math.max(floor, blk.y + 1); }8681
}8682
}8683
return out;8684
};8685
8686
if (typeof globalThis !== 'undefined')8687
{ globalThis.MiniPredict = MiniPredict; }8688
if (typeof module !== 'undefined' && module.exports)8689
{ module.exports = MiniPredict; }8690
8691
/*8692
* End File:8693
* /workspace/meteors/src/miniPredict.js8694
*/ 8695
8465
/*8696
/*8466
* Start File:8697
* Start File:8467
* /workspace/meteors/src/online.js8698
* /workspace/meteors/src/online.js@@ -8492,6 +8723,10 @@ var Online = {8492
error: '',8723
error: '',8493
_timer: null,8724
_timer: null,8494
_pendingShots: [],8725
_pendingShots: [],8726
_pollInFlight: false,8727
_flushPending: false,8728
_lastPollAt: 0,8729
_getPayload: null,8495
_flights: [],8730
_flights: [],8496
_lastStatus: null,8731
_lastStatus: null,8497
onChange: null,8732
onChange: null,@@ -8703,8 +8938,16 @@ Online.poll = function (opts)8703
}8938
}8704
var self = this;8939
var self = this;8705
var prevStatus = this.lobby && this.lobby.status;8940
var prevStatus = this.lobby && this.lobby.status;8941
this._pollInFlight = true;8942
this._lastPollAt = Date.now();8706
return this.request('poll', body).then(function (data)8943
return this.request('poll', body).then(function (data)8707
{8944
{8945
self._pollInFlight = false;8946
if (self._flushPending)8947
{8948
self._flushPending = false;8949
self.flushShotsSoon();8950
}8708
self._handleTransitions(prevStatus, data);8951
self._handleTransitions(prevStatus, data);8709
if (self.onChange)8952
if (self.onChange)8710
{ self.onChange(self); }8953
{ self.onChange(self); }@@ -8739,6 +8982,7 @@ Online.startPolling = function (getPayload)8739
{8982
{8740
this.stopPolling();8983
this.stopPolling();8741
var self = this;8984
var self = this;8985
this._getPayload = getPayload || null;8742
var tick = function ()8986
var tick = function ()8743
{8987
{8744
var payload = getPayload ? getPayload() : {};8988
var payload = getPayload ? getPayload() : {};@@ -8748,8 +8992,68 @@ Online.startPolling = function (getPayload)8748
this._timer = setInterval(tick, this.POLL_MS);8992
this._timer = setInterval(tick, this.POLL_MS);8749
};8993
};8750
8994
8995
/** Minimum gap between an extra shot flush and the previous poll (ms). */8996
Online.FLUSH_MIN_GAP_MS = 120;8997
8998
/**8999
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the9000
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).9001
*/9002
Online.flushDecision = function (state)9003
{9004
if (!state || !state.polling || !(state.pending > 0))9005
{ return 'none'; }9006
if (state.inFlight)9007
{ return 'later'; }9008
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))9009
{ return 'later'; }9010
return 'now';9011
};9012
9013
/**9014
* Send freshly cleared shots on the next possible poll instead of up to9015
* POLL_MS later, so the server's hit/miss result (and the retarget of the9016
* local flight) arrives in about one round trip. Network cadence only;9017
* the server still decides hits, targets and delivery (t1181).9018
*/9019
Online.flushShotsSoon = function ()9020
{9021
var self = this;9022
var d = this.flushDecision({9023
polling: !!this._timer,9024
pending: this._pendingShots.length,9025
inFlight: this._pollInFlight,9026
sinceLast: Date.now() - (this._lastPollAt || 0)9027
});9028
if (d === 'none')9029
{ return d; }9030
if (d === 'later')9031
{9032
if (this._pollInFlight)9033
{ this._flushPending = true; }9034
else if (!this._flushTimer)9035
{9036
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));9037
this._flushTimer = setTimeout(function ()9038
{9039
self._flushTimer = null;9040
self.flushShotsSoon();9041
}, wait);9042
}9043
return d;9044
}9045
this.poll(this._getPayload ? this._getPayload() : {});9046
return d;9047
};9048
8751
Online.stopPolling = function ()9049
Online.stopPolling = function ()8752
{9050
{9051
if (this._flushTimer)9052
{9053
clearTimeout(this._flushTimer);9054
this._flushTimer = null;9055
}9056
this._flushPending = false;8753
if (this._timer)9057
if (this._timer)8754
{9058
{8755
clearInterval(this._timer);9059
clearInterval(this._timer);@@ -8851,7 +9155,7 @@ Online.renderMinis = function (container)8851
? I18n.t('hud.miniPoints', { n: p.score || 0 })9155
? I18n.t('hud.miniPoints', { n: p.score || 0 })8852
: ('Points ' + (p.score || 0));9156
: ('Points ' + (p.score || 0));8853
}9157
}8854
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);9158
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));8855
}9159
}8856
for (var id in existing)9160
for (var id in existing)8857
{9161
{@@ -8872,7 +9176,28 @@ function miniColor (planet, color)8872
}9176
}8873
9177
8874
9178
8875
Online._drawMini = function (canvas, snapshot, planet)9179
/**9180
* t1182: smoothed display y for an opponent's falling blocks (see9181
* src/miniPredict.js). Returns id → y, or null without the module.9182
*/9183
Online._predictMini = function (p, now)9184
{9185
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;9186
if (!MP || !p)9187
{ return null; }9188
if (!this._miniPredict)9189
{ this._miniPredict = Object.create(null); }9190
var st = this._miniPredict[p.id];9191
if (!st)9192
{ st = this._miniPredict[p.id] = MP.create(); }9193
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());9194
MP.update(st, p.snapshot, now);9195
if (p.eliminated)9196
{ return null; }9197
return MP.step(st, now, MP.fallSpeedFor(p.planet));9198
};9199
9200
Online._drawMini = function (canvas, snapshot, planet, shownY)8876
{9201
{8877
if (!canvas)9202
if (!canvas)8878
{ return; }9203
{ return; }@@ -8919,7 +9244,8 @@ Online._drawMini = function (canvas, snapshot, planet)8919
{9244
{8920
var b = blocks[i];9245
var b = blocks[i];8921
var x = b.col * tw;9246
var x = b.col * tw;8922
var y = canvas.height - (b.y + 1) * th;9247
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;9248
var y = canvas.height - (by + 1) * th;8923
if (b.state === 'locked')9249
if (b.state === 'locked')8924
{ ctx.fillStyle = '#3a3d4a'; }9250
{ ctx.fillStyle = '#3a3d4a'; }8925
else if (b.color < 0)9251
else if (b.color < 0)@@ -9732,6 +10058,17 @@ Online.spawnFlights = function (results, locals)9732
{10058
{9733
var r = results[i];10059
var r = results[i];9734
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));10060
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));10061
// Own shot already flying locally since the clear (t1181):10062
// pick it up at its current pose and fly on to the real target.10063
var cid = r.client_id != null ? String(r.client_id) : null;10064
if (cid && this._previewIds[cid] && this._isOwnShot(r))10065
{10066
var own = this._findFlight(cid);10067
this._flightSeen[sid] = now;10068
if (own)10069
{ this.retargetFlight(own, r, locals[cid] || {}, now); }10070
continue;10071
}9735
if (this._flightSeen[sid])10072
if (this._flightSeen[sid])9736
{10073
{9737
if (this._previewIds[sid])10074
if (this._previewIds[sid])@@ -9837,12 +10174,11 @@ Online.spawnFlights = function (results, locals)9837
el.style.height = full + 'px';10174
el.style.height = full + 'px';9838
layer.appendChild(el);10175
layer.appendChild(el);9839
10176
10177
// A flight seen late (poll delay) still starts at the sender's10178
// field and plays the whole arc, just a bit faster, so it lands10179
// about when the server delivers it — never a mid-arc pop-in (t1181).9840
var t0 = now;10180
var t0 = now;9841
if (r.age != null && isFinite(r.age) && r.age > 0)10181
duration = this.lateFlightDuration(r.age, duration);9842
{9843
var u0 = Math.min(0.95, (r.age * 1000) / duration);9844
t0 = now - u0 * duration;9845
}9846
var height = miss10182
var height = miss9847
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))10183
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))9848
: this.arcHeight(start, end);10184
: this.arcHeight(start, end);@@ -9879,6 +10215,52 @@ Online.spawnFlights = function (results, locals)9879
this._flightLocals = {};10215
this._flightLocals = {};9880
};10216
};9881
10217
10218
/** Shortest share of the normal flight a late-seen flight may get. */10219
Online.LATE_MIN_SHARE = 0.5;10220
10221
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */10222
Online.lateFlightDuration = function (age, duration)10223
{10224
if (age == null || !isFinite(age) || age <= 0)10225
{ return duration; }10226
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);10227
};10228
10229
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */10230
Online.retargetDuration = function (elapsedMs, duration)10231
{10232
if (!(elapsedMs > 0))10233
{ return duration; }10234
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);10235
};10236
10237
Online._isOwnShot = function (r)10238
{10239
var mine = this.me && this.me.id;10240
var from = r.from_id || r.from_user || null;10241
return !from || (mine != null && String(from) === String(mine));10242
};10243
10244
/**10245
* Sender side (t1181): start the flight the moment the block leaves the10246
* field, before any server round trip. It rises out of the exit cell;10247
* the poll answer retargets it (hit → opponent mini, miss → off-screen).10248
*/10249
Online.startLocalShot = function (shot, start)10250
{10251
if (!shot || !start)10252
{ return null; }10253
return this.previewExit({10254
id: shot.id,10255
col: shot.col,10256
y: shot.y,10257
vy: shot.vy,10258
color: shot.color,10259
start: start,10260
from_id: null10261
});10262
};10263
9882
Online.rememberFlightLocal = function (shot, startX, startY)10264
Online.rememberFlightLocal = function (shot, startX, startY)9883
{10265
{9884
if (!this._flightLocals)10266
if (!this._flightLocals)@@ -10045,6 +10427,7 @@ Online.previewExit = function (info)10045
});10427
});10046
this._previewIds[sid] = true;10428
this._previewIds[sid] = true;10047
this._flightSeen[sid] = now;10429
this._flightSeen[sid] = now;10430
return true;10048
};10431
};10049
10432
10050
/** True while a field sprite should stay hidden — the flight is its visual. */10433
/** True while a field sprite should stay hidden — the flight is its visual. */@@ -10086,6 +10469,8 @@ Online.retargetFlight = function (f, r, meta, now)10086
var miss = !!r.miss;10469
var miss = !!r.miss;10087
var kind = this.flightKind(fromId, targetId, miss);10470
var kind = this.flightKind(fromId, targetId, miss);10088
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;10471
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;10472
if (f.preview)10473
{ duration = this.retargetDuration(now - f.t0, duration); }10089
10474
10090
var landCol = null;10475
var landCol = null;10091
if (r.land_col != null && isFinite(r.land_col))10476
if (r.land_col != null && isFinite(r.land_col))@@ -10202,6 +10587,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)10202
return false;10587
return false;10203
};10588
};10204
10589
10590
/** How long a local preview may wait at its apex for the server (ms). */10591
Online.PREVIEW_HOLD_MS = 2500;10592
10205
Online.tickFlights = function (now)10593
Online.tickFlights = function (now)10206
{10594
{10207
now = now || performance.now();10595
now = now || performance.now();@@ -10210,6 +10598,8 @@ Online.tickFlights = function (now)10210
{10598
{10211
var f = this._flights[i];10599
var f = this._flights[i];10212
var raw = (now - f.t0) / f.duration;10600
var raw = (now - f.t0) / f.duration;10601
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)10602
{ raw = 0.999; }10213
if (raw >= 1)10603
if (raw >= 1)10214
{10604
{10215
if (f.el && f.el.parentNode)10605
if (f.el && f.el.parentNode)@@ -10282,6 +10672,7 @@ Online.clearFlights = function ()10282
this._flightSeen = Object.create(null);10672
this._flightSeen = Object.create(null);10283
this._pendingLandCol = Object.create(null);10673
this._pendingLandCol = Object.create(null);10284
this._previewIds = Object.create(null);10674
this._previewIds = Object.create(null);10675
this._miniPredict = Object.create(null);10285
};10676
};10286
10677
10287
if (typeof globalThis !== 'undefined')10678
if (typeof globalThis !== 'undefined')@@ -13715,8 +14106,14 @@ function tickOnline (dt)13715
var s = shots[i];14106
var s = shots[i];13716
var start = fieldToViewport(s.col, s.y);14107
var start = fieldToViewport(s.col, s.y);13717
Online.rememberFlightLocal(s, start.x, start.y);14108
Online.rememberFlightLocal(s, start.x, start.y);14109
// Draw the flight locally right away (t1181); the server14110
// answer only retargets it.14111
if (Online.startLocalShot)14112
{ Online.startLocalShot(s, start); }13718
}14113
}13719
Online.queueShots(shots);14114
Online.queueShots(shots);14115
if (shots.length && Online.flushShotsSoon)14116
{ Online.flushShotsSoon(); }13720
}14117
}13721
Online.tickFlights();14118
Online.tickFlights();13722
Online.renderMinis(document.getElementById('minis'));14119
Online.renderMinis(document.getElementById('minis'));@@ -14168,8 +14565,12 @@ function onlinePayload ()14168
{14565
{14169
if (!app.online || !app.core)14566
if (!app.online || !app.core)14170
{ return {}; }14567
{ return {}; }14568
var snap = app.core.fieldSnapshot();14569
// t1182: sender time (ms) so opponents can place the snapshot in14570
// time and predict falling blocks smoothly. Visual only.14571
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());14171
return {14572
return {14172
snapshot: app.core.fieldSnapshot(),14573
snapshot: snap,14173
score: app.core.score,14574
score: app.core.score,14174
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported14575
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported14175
};14576
};@@ -952,3 +952,49 @@ Aanname:
952
952
achtergrondtab springt niet). Werkt op desktop en mobiel. Bij
953
953
`prefers-reduced-motion` vliegen er geen blokjes en springt de titel
954
954
zonder animatie naar boven; het getal telt in hetzelfde tempo op.
955
956
## t1181 — vliegende blokken lokaal en vloeiend
957
958
**Oorzaak van het haperen.** De vlucht van een weggeschoten blok werd pas
959
gemaakt als de poll-response met `shot_results` terugkwam. Schoten wachtten
960
op de volgende poll (`setInterval`, 750 ms) plus de round trip, terwijl
961
`cullOffTop` het blok al had weggehaald: 140–740 ms niets, daarna verscheen
962
de vlucht ineens. De lokale preview (`previewExit`) bestond wel maar werd
963
nooit aangeroepen. Ontvangers lieten late vluchten halverwege de boog
964
beginnen (terugdateren met `age`).
965
966
**Oplossing (alleen presentatie, spellogica en payload ongewijzigd).**
967
- Zender: `Online.startLocalShot` start op het lokale clear-moment direct een
968
vlucht (`previewExit`), uit `tickOnline`.
969
- `Online.flushShotsSoon` stuurt schoten meteen mee met een extra poll
970
(minstens `FLUSH_MIN_GAP_MS` = 120 ms tussen polls, nooit twee tegelijk).
971
- Serverantwoord: dezelfde vlucht wordt via `retargetFlight` vanuit de
972
huidige positie naar het echte doel gebogen, met de resterende duur.
973
- Is de server traag, dan wacht de preview bij de top
974
(`PREVIEW_HOLD_MS` = 2500 ms) in plaats van te verdwijnen.
975
- Ontvanger: altijd de hele boog vanaf het veld van de zender, duur
976
`max(50%, duur − age)` (`LATE_MIN_SHARE`).
977
- Animatie per frame met `requestAnimationFrame` op tijd (niet op poll/tick).
978
979
Tests: `test/flight-local.test.js`; browser: `test/t1181-flights-playwright.py`
980
(desktop-zender + mobiele ontvanger).
981
982
## t1182 — voorspelling op mini-velden
983
984
- `src/miniPredict.js` (`MiniPredict`): tussen twee snapshots vallen
985
blokken met `state: 'falling'` verder met de valsnelheid van die speler
986
(`13 / planet.fallTime`), met sub-cel posities.
987
- Nooit voorspeld: landen, vastzetten of lijnen wissen. Een voorspeld blok
988
stopt bovenop het eerste obstakel in zijn kolom en wacht op de server.
989
- Snapshot krijgt `t` (zendertijd, ms, alleen visueel). De ontvanger zet die
990
om naar de eigen klok met de kleinste waargenomen aankomst-offset
991
(laatste 16), zodat een laat binnenkomende snapshot op het juiste moment
992
wordt geplaatst. Dezelfde snapshot opnieuw = geen herstart.
993
- Bijsturen: achterlopend blok haalt in (`RECONCILE_S` = 0,16 s), een blok
994
dat vooruitloopt valt even langzamer (50%) — nooit omhoog. Meer dan
995
`SNAP_CELLS` = 1,5 cel verschil: direct naar de serverpositie.
996
- Extrapolatie maximaal `MAX_EXTRAP_S` = 1,5 s na de laatste snapshot.
997
998
Tests: `test/mini-predict.test.js`, plus de mini-meting in
999
`test/t1181-flights-playwright.py`.
1000
@@ -952,3 +952,49 @@ Aanname:952
achtergrondtab springt niet). Werkt op desktop en mobiel. Bij952
achtergrondtab springt niet). Werkt op desktop en mobiel. Bij953
`prefers-reduced-motion` vliegen er geen blokjes en springt de titel953
`prefers-reduced-motion` vliegen er geen blokjes en springt de titel954
zonder animatie naar boven; het getal telt in hetzelfde tempo op.954
zonder animatie naar boven; het getal telt in hetzelfde tempo op.955
956
## t1181 — vliegende blokken lokaal en vloeiend957
958
**Oorzaak van het haperen.** De vlucht van een weggeschoten blok werd pas959
gemaakt als de poll-response met `shot_results` terugkwam. Schoten wachtten960
op de volgende poll (`setInterval`, 750 ms) plus de round trip, terwijl961
`cullOffTop` het blok al had weggehaald: 140–740 ms niets, daarna verscheen962
de vlucht ineens. De lokale preview (`previewExit`) bestond wel maar werd963
nooit aangeroepen. Ontvangers lieten late vluchten halverwege de boog964
beginnen (terugdateren met `age`).965
966
**Oplossing (alleen presentatie, spellogica en payload ongewijzigd).**967
- Zender: `Online.startLocalShot` start op het lokale clear-moment direct een968
vlucht (`previewExit`), uit `tickOnline`.969
- `Online.flushShotsSoon` stuurt schoten meteen mee met een extra poll970
(minstens `FLUSH_MIN_GAP_MS` = 120 ms tussen polls, nooit twee tegelijk).971
- Serverantwoord: dezelfde vlucht wordt via `retargetFlight` vanuit de972
huidige positie naar het echte doel gebogen, met de resterende duur.973
- Is de server traag, dan wacht de preview bij de top974
(`PREVIEW_HOLD_MS` = 2500 ms) in plaats van te verdwijnen.975
- Ontvanger: altijd de hele boog vanaf het veld van de zender, duur976
`max(50%, duur − age)` (`LATE_MIN_SHARE`).977
- Animatie per frame met `requestAnimationFrame` op tijd (niet op poll/tick).978
979
Tests: `test/flight-local.test.js`; browser: `test/t1181-flights-playwright.py`980
(desktop-zender + mobiele ontvanger).981
982
## t1182 — voorspelling op mini-velden983
984
- `src/miniPredict.js` (`MiniPredict`): tussen twee snapshots vallen985
blokken met `state: 'falling'` verder met de valsnelheid van die speler986
(`13 / planet.fallTime`), met sub-cel posities.987
- Nooit voorspeld: landen, vastzetten of lijnen wissen. Een voorspeld blok988
stopt bovenop het eerste obstakel in zijn kolom en wacht op de server.989
- Snapshot krijgt `t` (zendertijd, ms, alleen visueel). De ontvanger zet die990
om naar de eigen klok met de kleinste waargenomen aankomst-offset991
(laatste 16), zodat een laat binnenkomende snapshot op het juiste moment992
wordt geplaatst. Dezelfde snapshot opnieuw = geen herstart.993
- Bijsturen: achterlopend blok haalt in (`RECONCILE_S` = 0,16 s), een blok994
dat vooruitloopt valt even langzamer (50%) — nooit omhoog. Meer dan995
`SNAP_CELLS` = 1,5 cel verschil: direct naar de serverpositie.996
- Extrapolatie maximaal `MAX_EXTRAP_S` = 1,5 s na de laatste snapshot.997
998
Tests: `test/mini-predict.test.js`, plus de mini-meting in999
`test/t1181-flights-playwright.py`.1000
@@ -20,6 +20,7 @@ FILES=(
20
20
"$SRC_DIR/easing.js"
21
21
"$SRC_DIR/gameCore.js"
22
22
"$SRC_DIR/miniLayout.js"
23
"$SRC_DIR/miniPredict.js"
23
24
"$SRC_DIR/online.js"
24
25
"$SRC_DIR/offline.js"
25
26
"$SRC_DIR/reward.js"
@@ -20,6 +20,7 @@ FILES=(20
"$SRC_DIR/easing.js"20
"$SRC_DIR/easing.js"21
"$SRC_DIR/gameCore.js"21
"$SRC_DIR/gameCore.js"22
"$SRC_DIR/miniLayout.js"22
"$SRC_DIR/miniLayout.js"23
"$SRC_DIR/miniPredict.js"23
"$SRC_DIR/online.js"24
"$SRC_DIR/online.js"24
"$SRC_DIR/offline.js"25
"$SRC_DIR/offline.js"25
"$SRC_DIR/reward.js"26
"$SRC_DIR/reward.js"@@ -1406,8 +1406,14 @@ function tickOnline (dt)
1406
1406
var s = shots[i];
1407
1407
var start = fieldToViewport(s.col, s.y);
1408
1408
Online.rememberFlightLocal(s, start.x, start.y);
1409
// Draw the flight locally right away (t1181); the server
1410
// answer only retargets it.
1411
if (Online.startLocalShot)
1412
{ Online.startLocalShot(s, start); }
1409
1413
}
1410
1414
Online.queueShots(shots);
1415
if (shots.length && Online.flushShotsSoon)
1416
{ Online.flushShotsSoon(); }
1411
1417
}
1412
1418
Online.tickFlights();
1413
1419
Online.renderMinis(document.getElementById('minis'));
@@ -1859,8 +1865,12 @@ function onlinePayload ()
1859
1865
{
1860
1866
if (!app.online || !app.core)
1861
1867
{ return {}; }
1868
var snap = app.core.fieldSnapshot();
1869
// t1182: sender time (ms) so opponents can place the snapshot in
1870
// time and predict falling blocks smoothly. Visual only.
1871
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());
1862
1872
return {
1863
snapshot: app.core.fieldSnapshot(),
1873
snapshot: snap,
1864
1874
score: app.core.score,
1865
1875
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1866
1876
};
@@ -1406,8 +1406,14 @@ function tickOnline (dt)1406
var s = shots[i];1406
var s = shots[i];1407
var start = fieldToViewport(s.col, s.y);1407
var start = fieldToViewport(s.col, s.y);1408
Online.rememberFlightLocal(s, start.x, start.y);1408
Online.rememberFlightLocal(s, start.x, start.y);1409
// Draw the flight locally right away (t1181); the server1410
// answer only retargets it.1411
if (Online.startLocalShot)1412
{ Online.startLocalShot(s, start); }1409
}1413
}1410
Online.queueShots(shots);1414
Online.queueShots(shots);1415
if (shots.length && Online.flushShotsSoon)1416
{ Online.flushShotsSoon(); }1411
}1417
}1412
Online.tickFlights();1418
Online.tickFlights();1413
Online.renderMinis(document.getElementById('minis'));1419
Online.renderMinis(document.getElementById('minis'));@@ -1859,8 +1865,12 @@ function onlinePayload ()1859
{1865
{1860
if (!app.online || !app.core)1866
if (!app.online || !app.core)1861
{ return {}; }1867
{ return {}; }1868
var snap = app.core.fieldSnapshot();1869
// t1182: sender time (ms) so opponents can place the snapshot in1870
// time and predict falling blocks smoothly. Visual only.1871
snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now());1862
return {1872
return {1863
snapshot: app.core.fieldSnapshot(),1873
snapshot: snap,1864
score: app.core.score,1874
score: app.core.score,1865
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported1875
eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported1866
};1876
};@@ -0,0 +1,221 @@
1
'use strict';
2
3
/**
4
* t1182: client-side prediction for falling blocks on opponents' mini
5
* fields. Purely visual. Between snapshots (one per poll, ~0.75 s) a
6
* block whose authoritative state is 'falling' keeps descending at that
7
* player's fallSpeed (13 / fallTime cells/s), with sub-cell motion. It
8
* never goes below the first obstacle in its column, so a landing, lock
9
* or match is never predicted — those only appear when the next
10
* snapshot says so. When a snapshot arrives the shown position is
11
* reconciled smoothly: a block that lags catches up a little faster, a
12
* block that ran ahead falls more slowly until the truth catches up
13
* (it never moves up), and a large difference snaps.
14
*/
15
var MiniPredict = {
16
FIELD_HEIGHT: 13,
17
/** Seconds over which a lagging block closes its gap (on top of fallSpeed). */
18
RECONCILE_S: 0.16,
19
/** Cells: further off than this → snap to the authoritative pose. */
20
SNAP_CELLS: 1.5,
21
/** Never extrapolate further than this past the last snapshot (s). */
22
MAX_EXTRAP_S: 1.5,
23
/** Share of fallSpeed used while a block that ran ahead waits for the truth. */
24
AHEAD_SPEED_SHARE: 0.5,
25
/** Largest frame step used for the smoothing integrator (s). */
26
MAX_FRAME_S: 0.1
27
};
28
29
/** Arrival samples kept for the sender-clock offset estimate. */
30
MiniPredict.OFFSET_SAMPLES = 16;
31
32
MiniPredict.create = function ()
33
{
34
return { snap: null, at: 0, lastFrame: 0, shown: Object.create(null), offsets: [], sig: null };
35
};
36
37
/** Cheap content signature for snapshots without a sender time. */
38
MiniPredict.signature = function (snapshot)
39
{
40
if (!snapshot || !snapshot.blocks)
41
{ return ''; }
42
var s = String(snapshot.blocks.length);
43
for (var i = 0; i < snapshot.blocks.length; i++)
44
{
45
var b = snapshot.blocks[i];
46
s += '|' + b.id + ':' + b.y + ':' + b.state;
47
}
48
return s;
49
};
50
51
MiniPredict.fallSpeedFor = function (planet)
52
{
53
var ft = planet && (planet.fallTime != null ? planet.fallTime : planet.fall_time);
54
ft = Number(ft);
55
if (!(ft > 0))
56
{ ft = 3; }
57
return this.FIELD_HEIGHT / ft;
58
};
59
60
/**
61
* Record an authoritative snapshot. A poll can repeat the same
62
* snapshot (the opponent has not polled since); that must not restart
63
* the extrapolation. With a sender time `t` (ms, sender clock) the
64
* snapshot's moment is mapped to our clock via the smallest observed
65
* arrival offset, so a late-arriving snapshot is placed at the time it
66
* was really taken. Returns true when the snapshot is new.
67
*/
68
MiniPredict.update = function (st, snapshot, now)
69
{
70
if (snapshot === st.snap)
71
{ return false; }
72
if (!snapshot)
73
{
74
st.snap = null;
75
st.sig = null;
76
return false;
77
}
78
var hasT = snapshot.t != null && isFinite(snapshot.t);
79
if (st.snap && hasT && st.snap.t === snapshot.t)
80
{
81
st.snap = snapshot;
82
return false;
83
}
84
if (!hasT)
85
{
86
var sig = this.signature(snapshot);
87
if (st.snap && sig === st.sig)
88
{
89
st.snap = snapshot;
90
return false;
91
}
92
st.sig = sig;
93
st.snap = snapshot;
94
st.at = now;
95
return true;
96
}
97
st.offsets.push(now - snapshot.t);
98
if (st.offsets.length > this.OFFSET_SAMPLES)
99
{ st.offsets.shift(); }
100
var off = Math.min.apply(null, st.offsets);
101
st.snap = snapshot;
102
st.sig = null;
103
// Never in the future, never older than the extrapolation cap.
104
st.at = Math.max(now - this.MAX_EXTRAP_S * 1000, Math.min(now, snapshot.t + off));
105
return true;
106
};
107
108
/**
109
* Predicted y for every falling block at time `now`, clamped above the
110
* first non-falling block (or the floor) below it in its column, chaining
111
* falling blocks in the same column bottom-up. Returns id → y.
112
*/
113
MiniPredict.predict = function (snapshot, sinceS, fallSpeed)
114
{
115
var out = Object.create(null);
116
if (!snapshot || !snapshot.blocks)
117
{ return out; }
118
var dt = Math.max(0, Math.min(this.MAX_EXTRAP_S, sinceS || 0));
119
var cols = Object.create(null);
120
var blocks = snapshot.blocks;
121
for (var i = 0; i < blocks.length; i++)
122
{
123
var b = blocks[i];
124
(cols[b.col] = cols[b.col] || []).push(b);
125
}
126
for (var c in cols)
127
{
128
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });
129
var floor = 0; // lowest y the next block may occupy
130
for (var k = 0; k < list.length; k++)
131
{
132
var blk = list[k];
133
if (blk.state === 'falling')
134
{
135
var y = Math.max(floor, blk.y - fallSpeed * dt);
136
if (y > blk.y)
137
{ y = blk.y; } // only ever predict downwards
138
out[blk.id] = y;
139
floor = y + 1;
140
}
141
else
142
{ floor = Math.max(floor, blk.y + 1); }
143
}
144
}
145
return out;
146
};
147
148
/**
149
* Advance the shown positions to `now` and return id → display y for
150
* falling blocks. Non-falling blocks are not in the map (draw them at
151
* their authoritative y).
152
*/
153
MiniPredict.step = function (st, now, fallSpeed)
154
{
155
var frame = st.lastFrame ? Math.min(this.MAX_FRAME_S, Math.max(0, (now - st.lastFrame) / 1000)) : 0;
156
st.lastFrame = now;
157
var target = this.predict(st.snap, (now - st.at) / 1000, fallSpeed);
158
var shown = Object.create(null);
159
var floors = this._floors(st.snap, target);
160
for (var id in target)
161
{
162
var t = target[id];
163
var s = st.shown[id];
164
if (s == null || !isFinite(s) || Math.abs(s - t) > this.SNAP_CELLS)
165
{ s = t; }
166
else if (s > t)
167
{
168
// Lagging: fall at fallSpeed plus a share of the gap.
169
s -= (fallSpeed + (s - t) / this.RECONCILE_S) * frame;
170
if (s < t)
171
{ s = t; }
172
}
173
else if (s < t)
174
{
175
// Ran ahead: keep falling, slower, never upwards.
176
s -= fallSpeed * this.AHEAD_SPEED_SHARE * frame;
177
}
178
var fl = floors[id] != null ? floors[id] : 0;
179
if (s < fl)
180
{ s = fl; }
181
shown[id] = s;
182
}
183
st.shown = shown;
184
return shown;
185
};
186
187
/** Floor (lowest allowed y) for each falling block given the targets. */
188
MiniPredict._floors = function (snapshot, target)
189
{
190
var out = Object.create(null);
191
if (!snapshot || !snapshot.blocks)
192
{ return out; }
193
var cols = Object.create(null);
194
for (var i = 0; i < snapshot.blocks.length; i++)
195
{
196
var b = snapshot.blocks[i];
197
(cols[b.col] = cols[b.col] || []).push(b);
198
}
199
for (var c in cols)
200
{
201
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });
202
var floor = 0;
203
for (var k = 0; k < list.length; k++)
204
{
205
var blk = list[k];
206
if (blk.state === 'falling')
207
{
208
out[blk.id] = floor;
209
floor = (target[blk.id] != null ? target[blk.id] : blk.y) + 1;
210
}
211
else
212
{ floor = Math.max(floor, blk.y + 1); }
213
}
214
}
215
return out;
216
};
217
218
if (typeof globalThis !== 'undefined')
219
{ globalThis.MiniPredict = MiniPredict; }
220
if (typeof module !== 'undefined' && module.exports)
221
{ module.exports = MiniPredict; }
@@ -0,0 +1,221 @@1
'use strict';2
3
/**4
* t1182: client-side prediction for falling blocks on opponents' mini5
* fields. Purely visual. Between snapshots (one per poll, ~0.75 s) a6
* block whose authoritative state is 'falling' keeps descending at that7
* player's fallSpeed (13 / fallTime cells/s), with sub-cell motion. It8
* never goes below the first obstacle in its column, so a landing, lock9
* or match is never predicted — those only appear when the next10
* snapshot says so. When a snapshot arrives the shown position is11
* reconciled smoothly: a block that lags catches up a little faster, a12
* block that ran ahead falls more slowly until the truth catches up13
* (it never moves up), and a large difference snaps.14
*/15
var MiniPredict = {16
FIELD_HEIGHT: 13,17
/** Seconds over which a lagging block closes its gap (on top of fallSpeed). */18
RECONCILE_S: 0.16,19
/** Cells: further off than this → snap to the authoritative pose. */20
SNAP_CELLS: 1.5,21
/** Never extrapolate further than this past the last snapshot (s). */22
MAX_EXTRAP_S: 1.5,23
/** Share of fallSpeed used while a block that ran ahead waits for the truth. */24
AHEAD_SPEED_SHARE: 0.5,25
/** Largest frame step used for the smoothing integrator (s). */26
MAX_FRAME_S: 0.127
};28
29
/** Arrival samples kept for the sender-clock offset estimate. */30
MiniPredict.OFFSET_SAMPLES = 16;31
32
MiniPredict.create = function ()33
{34
return { snap: null, at: 0, lastFrame: 0, shown: Object.create(null), offsets: [], sig: null };35
};36
37
/** Cheap content signature for snapshots without a sender time. */38
MiniPredict.signature = function (snapshot)39
{40
if (!snapshot || !snapshot.blocks)41
{ return ''; }42
var s = String(snapshot.blocks.length);43
for (var i = 0; i < snapshot.blocks.length; i++)44
{45
var b = snapshot.blocks[i];46
s += '|' + b.id + ':' + b.y + ':' + b.state;47
}48
return s;49
};50
51
MiniPredict.fallSpeedFor = function (planet)52
{53
var ft = planet && (planet.fallTime != null ? planet.fallTime : planet.fall_time);54
ft = Number(ft);55
if (!(ft > 0))56
{ ft = 3; }57
return this.FIELD_HEIGHT / ft;58
};59
60
/**61
* Record an authoritative snapshot. A poll can repeat the same62
* snapshot (the opponent has not polled since); that must not restart63
* the extrapolation. With a sender time `t` (ms, sender clock) the64
* snapshot's moment is mapped to our clock via the smallest observed65
* arrival offset, so a late-arriving snapshot is placed at the time it66
* was really taken. Returns true when the snapshot is new.67
*/68
MiniPredict.update = function (st, snapshot, now)69
{70
if (snapshot === st.snap)71
{ return false; }72
if (!snapshot)73
{74
st.snap = null;75
st.sig = null;76
return false;77
}78
var hasT = snapshot.t != null && isFinite(snapshot.t);79
if (st.snap && hasT && st.snap.t === snapshot.t)80
{81
st.snap = snapshot;82
return false;83
}84
if (!hasT)85
{86
var sig = this.signature(snapshot);87
if (st.snap && sig === st.sig)88
{89
st.snap = snapshot;90
return false;91
}92
st.sig = sig;93
st.snap = snapshot;94
st.at = now;95
return true;96
}97
st.offsets.push(now - snapshot.t);98
if (st.offsets.length > this.OFFSET_SAMPLES)99
{ st.offsets.shift(); }100
var off = Math.min.apply(null, st.offsets);101
st.snap = snapshot;102
st.sig = null;103
// Never in the future, never older than the extrapolation cap.104
st.at = Math.max(now - this.MAX_EXTRAP_S * 1000, Math.min(now, snapshot.t + off));105
return true;106
};107
108
/**109
* Predicted y for every falling block at time `now`, clamped above the110
* first non-falling block (or the floor) below it in its column, chaining111
* falling blocks in the same column bottom-up. Returns id → y.112
*/113
MiniPredict.predict = function (snapshot, sinceS, fallSpeed)114
{115
var out = Object.create(null);116
if (!snapshot || !snapshot.blocks)117
{ return out; }118
var dt = Math.max(0, Math.min(this.MAX_EXTRAP_S, sinceS || 0));119
var cols = Object.create(null);120
var blocks = snapshot.blocks;121
for (var i = 0; i < blocks.length; i++)122
{123
var b = blocks[i];124
(cols[b.col] = cols[b.col] || []).push(b);125
}126
for (var c in cols)127
{128
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });129
var floor = 0; // lowest y the next block may occupy130
for (var k = 0; k < list.length; k++)131
{132
var blk = list[k];133
if (blk.state === 'falling')134
{135
var y = Math.max(floor, blk.y - fallSpeed * dt);136
if (y > blk.y)137
{ y = blk.y; } // only ever predict downwards138
out[blk.id] = y;139
floor = y + 1;140
}141
else142
{ floor = Math.max(floor, blk.y + 1); }143
}144
}145
return out;146
};147
148
/**149
* Advance the shown positions to `now` and return id → display y for150
* falling blocks. Non-falling blocks are not in the map (draw them at151
* their authoritative y).152
*/153
MiniPredict.step = function (st, now, fallSpeed)154
{155
var frame = st.lastFrame ? Math.min(this.MAX_FRAME_S, Math.max(0, (now - st.lastFrame) / 1000)) : 0;156
st.lastFrame = now;157
var target = this.predict(st.snap, (now - st.at) / 1000, fallSpeed);158
var shown = Object.create(null);159
var floors = this._floors(st.snap, target);160
for (var id in target)161
{162
var t = target[id];163
var s = st.shown[id];164
if (s == null || !isFinite(s) || Math.abs(s - t) > this.SNAP_CELLS)165
{ s = t; }166
else if (s > t)167
{168
// Lagging: fall at fallSpeed plus a share of the gap.169
s -= (fallSpeed + (s - t) / this.RECONCILE_S) * frame;170
if (s < t)171
{ s = t; }172
}173
else if (s < t)174
{175
// Ran ahead: keep falling, slower, never upwards.176
s -= fallSpeed * this.AHEAD_SPEED_SHARE * frame;177
}178
var fl = floors[id] != null ? floors[id] : 0;179
if (s < fl)180
{ s = fl; }181
shown[id] = s;182
}183
st.shown = shown;184
return shown;185
};186
187
/** Floor (lowest allowed y) for each falling block given the targets. */188
MiniPredict._floors = function (snapshot, target)189
{190
var out = Object.create(null);191
if (!snapshot || !snapshot.blocks)192
{ return out; }193
var cols = Object.create(null);194
for (var i = 0; i < snapshot.blocks.length; i++)195
{196
var b = snapshot.blocks[i];197
(cols[b.col] = cols[b.col] || []).push(b);198
}199
for (var c in cols)200
{201
var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; });202
var floor = 0;203
for (var k = 0; k < list.length; k++)204
{205
var blk = list[k];206
if (blk.state === 'falling')207
{208
out[blk.id] = floor;209
floor = (target[blk.id] != null ? target[blk.id] : blk.y) + 1;210
}211
else212
{ floor = Math.max(floor, blk.y + 1); }213
}214
}215
return out;216
};217
218
if (typeof globalThis !== 'undefined')219
{ globalThis.MiniPredict = MiniPredict; }220
if (typeof module !== 'undefined' && module.exports)221
{ module.exports = MiniPredict; }@@ -24,6 +24,10 @@ var Online = {
24
24
error: '',
25
25
_timer: null,
26
26
_pendingShots: [],
27
_pollInFlight: false,
28
_flushPending: false,
29
_lastPollAt: 0,
30
_getPayload: null,
27
31
_flights: [],
28
32
_lastStatus: null,
29
33
onChange: null,
@@ -235,8 +239,16 @@ Online.poll = function (opts)
235
239
}
236
240
var self = this;
237
241
var prevStatus = this.lobby && this.lobby.status;
242
this._pollInFlight = true;
243
this._lastPollAt = Date.now();
238
244
return this.request('poll', body).then(function (data)
239
245
{
246
self._pollInFlight = false;
247
if (self._flushPending)
248
{
249
self._flushPending = false;
250
self.flushShotsSoon();
251
}
240
252
self._handleTransitions(prevStatus, data);
241
253
if (self.onChange)
242
254
{ self.onChange(self); }
@@ -271,6 +283,7 @@ Online.startPolling = function (getPayload)
271
283
{
272
284
this.stopPolling();
273
285
var self = this;
286
this._getPayload = getPayload || null;
274
287
var tick = function ()
275
288
{
276
289
var payload = getPayload ? getPayload() : {};
@@ -280,8 +293,68 @@ Online.startPolling = function (getPayload)
280
293
this._timer = setInterval(tick, this.POLL_MS);
281
294
};
282
295
296
/** Minimum gap between an extra shot flush and the previous poll (ms). */
297
Online.FLUSH_MIN_GAP_MS = 120;
298
299
/**
300
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the
301
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).
302
*/
303
Online.flushDecision = function (state)
304
{
305
if (!state || !state.polling || !(state.pending > 0))
306
{ return 'none'; }
307
if (state.inFlight)
308
{ return 'later'; }
309
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))
310
{ return 'later'; }
311
return 'now';
312
};
313
314
/**
315
* Send freshly cleared shots on the next possible poll instead of up to
316
* POLL_MS later, so the server's hit/miss result (and the retarget of the
317
* local flight) arrives in about one round trip. Network cadence only;
318
* the server still decides hits, targets and delivery (t1181).
319
*/
320
Online.flushShotsSoon = function ()
321
{
322
var self = this;
323
var d = this.flushDecision({
324
polling: !!this._timer,
325
pending: this._pendingShots.length,
326
inFlight: this._pollInFlight,
327
sinceLast: Date.now() - (this._lastPollAt || 0)
328
});
329
if (d === 'none')
330
{ return d; }
331
if (d === 'later')
332
{
333
if (this._pollInFlight)
334
{ this._flushPending = true; }
335
else if (!this._flushTimer)
336
{
337
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));
338
this._flushTimer = setTimeout(function ()
339
{
340
self._flushTimer = null;
341
self.flushShotsSoon();
342
}, wait);
343
}
344
return d;
345
}
346
this.poll(this._getPayload ? this._getPayload() : {});
347
return d;
348
};
349
283
350
Online.stopPolling = function ()
284
351
{
352
if (this._flushTimer)
353
{
354
clearTimeout(this._flushTimer);
355
this._flushTimer = null;
356
}
357
this._flushPending = false;
285
358
if (this._timer)
286
359
{
287
360
clearInterval(this._timer);
@@ -383,7 +456,7 @@ Online.renderMinis = function (container)
383
456
? I18n.t('hud.miniPoints', { n: p.score || 0 })
384
457
: ('Points ' + (p.score || 0));
385
458
}
386
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
459
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));
387
460
}
388
461
for (var id in existing)
389
462
{
@@ -404,7 +477,28 @@ function miniColor (planet, color)
404
477
}
405
478
406
479
407
Online._drawMini = function (canvas, snapshot, planet)
480
/**
481
* t1182: smoothed display y for an opponent's falling blocks (see
482
* src/miniPredict.js). Returns id → y, or null without the module.
483
*/
484
Online._predictMini = function (p, now)
485
{
486
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;
487
if (!MP || !p)
488
{ return null; }
489
if (!this._miniPredict)
490
{ this._miniPredict = Object.create(null); }
491
var st = this._miniPredict[p.id];
492
if (!st)
493
{ st = this._miniPredict[p.id] = MP.create(); }
494
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());
495
MP.update(st, p.snapshot, now);
496
if (p.eliminated)
497
{ return null; }
498
return MP.step(st, now, MP.fallSpeedFor(p.planet));
499
};
500
501
Online._drawMini = function (canvas, snapshot, planet, shownY)
408
502
{
409
503
if (!canvas)
410
504
{ return; }
@@ -451,7 +545,8 @@ Online._drawMini = function (canvas, snapshot, planet)
451
545
{
452
546
var b = blocks[i];
453
547
var x = b.col * tw;
454
var y = canvas.height - (b.y + 1) * th;
548
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
549
var y = canvas.height - (by + 1) * th;
455
550
if (b.state === 'locked')
456
551
{ ctx.fillStyle = '#3a3d4a'; }
457
552
else if (b.color < 0)
@@ -1264,6 +1359,17 @@ Online.spawnFlights = function (results, locals)
1264
1359
{
1265
1360
var r = results[i];
1266
1361
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
1362
// Own shot already flying locally since the clear (t1181):
1363
// pick it up at its current pose and fly on to the real target.
1364
var cid = r.client_id != null ? String(r.client_id) : null;
1365
if (cid && this._previewIds[cid] && this._isOwnShot(r))
1366
{
1367
var own = this._findFlight(cid);
1368
this._flightSeen[sid] = now;
1369
if (own)
1370
{ this.retargetFlight(own, r, locals[cid] || {}, now); }
1371
continue;
1372
}
1267
1373
if (this._flightSeen[sid])
1268
1374
{
1269
1375
if (this._previewIds[sid])
@@ -1369,12 +1475,11 @@ Online.spawnFlights = function (results, locals)
1369
1475
el.style.height = full + 'px';
1370
1476
layer.appendChild(el);
1371
1477
1478
// A flight seen late (poll delay) still starts at the sender's
1479
// field and plays the whole arc, just a bit faster, so it lands
1480
// about when the server delivers it — never a mid-arc pop-in (t1181).
1372
1481
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
}
1482
duration = this.lateFlightDuration(r.age, duration);
1378
1483
var height = miss
1379
1484
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
1380
1485
: this.arcHeight(start, end);
@@ -1411,6 +1516,52 @@ Online.spawnFlights = function (results, locals)
1411
1516
this._flightLocals = {};
1412
1517
};
1413
1518
1519
/** Shortest share of the normal flight a late-seen flight may get. */
1520
Online.LATE_MIN_SHARE = 0.5;
1521
1522
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */
1523
Online.lateFlightDuration = function (age, duration)
1524
{
1525
if (age == null || !isFinite(age) || age <= 0)
1526
{ return duration; }
1527
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);
1528
};
1529
1530
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */
1531
Online.retargetDuration = function (elapsedMs, duration)
1532
{
1533
if (!(elapsedMs > 0))
1534
{ return duration; }
1535
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);
1536
};
1537
1538
Online._isOwnShot = function (r)
1539
{
1540
var mine = this.me && this.me.id;
1541
var from = r.from_id || r.from_user || null;
1542
return !from || (mine != null && String(from) === String(mine));
1543
};
1544
1545
/**
1546
* Sender side (t1181): start the flight the moment the block leaves the
1547
* field, before any server round trip. It rises out of the exit cell;
1548
* the poll answer retargets it (hit → opponent mini, miss → off-screen).
1549
*/
1550
Online.startLocalShot = function (shot, start)
1551
{
1552
if (!shot || !start)
1553
{ return null; }
1554
return this.previewExit({
1555
id: shot.id,
1556
col: shot.col,
1557
y: shot.y,
1558
vy: shot.vy,
1559
color: shot.color,
1560
start: start,
1561
from_id: null
1562
});
1563
};
1564
1414
1565
Online.rememberFlightLocal = function (shot, startX, startY)
1415
1566
{
1416
1567
if (!this._flightLocals)
@@ -1577,6 +1728,7 @@ Online.previewExit = function (info)
1577
1728
});
1578
1729
this._previewIds[sid] = true;
1579
1730
this._flightSeen[sid] = now;
1731
return true;
1580
1732
};
1581
1733
1582
1734
/** True while a field sprite should stay hidden — the flight is its visual. */
@@ -1618,6 +1770,8 @@ Online.retargetFlight = function (f, r, meta, now)
1618
1770
var miss = !!r.miss;
1619
1771
var kind = this.flightKind(fromId, targetId, miss);
1620
1772
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1773
if (f.preview)
1774
{ duration = this.retargetDuration(now - f.t0, duration); }
1621
1775
1622
1776
var landCol = null;
1623
1777
if (r.land_col != null && isFinite(r.land_col))
@@ -1734,6 +1888,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)
1734
1888
return false;
1735
1889
};
1736
1890
1891
/** How long a local preview may wait at its apex for the server (ms). */
1892
Online.PREVIEW_HOLD_MS = 2500;
1893
1737
1894
Online.tickFlights = function (now)
1738
1895
{
1739
1896
now = now || performance.now();
@@ -1742,6 +1899,8 @@ Online.tickFlights = function (now)
1742
1899
{
1743
1900
var f = this._flights[i];
1744
1901
var raw = (now - f.t0) / f.duration;
1902
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)
1903
{ raw = 0.999; }
1745
1904
if (raw >= 1)
1746
1905
{
1747
1906
if (f.el && f.el.parentNode)
@@ -1814,6 +1973,7 @@ Online.clearFlights = function ()
1814
1973
this._flightSeen = Object.create(null);
1815
1974
this._pendingLandCol = Object.create(null);
1816
1975
this._previewIds = Object.create(null);
1976
this._miniPredict = Object.create(null);
1817
1977
};
1818
1978
1819
1979
if (typeof globalThis !== 'undefined')
@@ -24,6 +24,10 @@ var Online = {24
error: '',24
error: '',25
_timer: null,25
_timer: null,26
_pendingShots: [],26
_pendingShots: [],27
_pollInFlight: false,28
_flushPending: false,29
_lastPollAt: 0,30
_getPayload: null,27
_flights: [],31
_flights: [],28
_lastStatus: null,32
_lastStatus: null,29
onChange: null,33
onChange: null,@@ -235,8 +239,16 @@ Online.poll = function (opts)235
}239
}236
var self = this;240
var self = this;237
var prevStatus = this.lobby && this.lobby.status;241
var prevStatus = this.lobby && this.lobby.status;242
this._pollInFlight = true;243
this._lastPollAt = Date.now();238
return this.request('poll', body).then(function (data)244
return this.request('poll', body).then(function (data)239
{245
{246
self._pollInFlight = false;247
if (self._flushPending)248
{249
self._flushPending = false;250
self.flushShotsSoon();251
}240
self._handleTransitions(prevStatus, data);252
self._handleTransitions(prevStatus, data);241
if (self.onChange)253
if (self.onChange)242
{ self.onChange(self); }254
{ self.onChange(self); }@@ -271,6 +283,7 @@ Online.startPolling = function (getPayload)271
{283
{272
this.stopPolling();284
this.stopPolling();273
var self = this;285
var self = this;286
this._getPayload = getPayload || null;274
var tick = function ()287
var tick = function ()275
{288
{276
var payload = getPayload ? getPayload() : {};289
var payload = getPayload ? getPayload() : {};@@ -280,8 +293,68 @@ Online.startPolling = function (getPayload)280
this._timer = setInterval(tick, this.POLL_MS);293
this._timer = setInterval(tick, this.POLL_MS);281
};294
};282
295
296
/** Minimum gap between an extra shot flush and the previous poll (ms). */297
Online.FLUSH_MIN_GAP_MS = 120;298
299
/**300
* Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the301
* in-flight poll or the min gap) or 'none' (nothing to send / not polling).302
*/303
Online.flushDecision = function (state)304
{305
if (!state || !state.polling || !(state.pending > 0))306
{ return 'none'; }307
if (state.inFlight)308
{ return 'later'; }309
if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS))310
{ return 'later'; }311
return 'now';312
};313
314
/**315
* Send freshly cleared shots on the next possible poll instead of up to316
* POLL_MS later, so the server's hit/miss result (and the retarget of the317
* local flight) arrives in about one round trip. Network cadence only;318
* the server still decides hits, targets and delivery (t1181).319
*/320
Online.flushShotsSoon = function ()321
{322
var self = this;323
var d = this.flushDecision({324
polling: !!this._timer,325
pending: this._pendingShots.length,326
inFlight: this._pollInFlight,327
sinceLast: Date.now() - (this._lastPollAt || 0)328
});329
if (d === 'none')330
{ return d; }331
if (d === 'later')332
{333
if (this._pollInFlight)334
{ this._flushPending = true; }335
else if (!this._flushTimer)336
{337
var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0)));338
this._flushTimer = setTimeout(function ()339
{340
self._flushTimer = null;341
self.flushShotsSoon();342
}, wait);343
}344
return d;345
}346
this.poll(this._getPayload ? this._getPayload() : {});347
return d;348
};349
283
Online.stopPolling = function ()350
Online.stopPolling = function ()284
{351
{352
if (this._flushTimer)353
{354
clearTimeout(this._flushTimer);355
this._flushTimer = null;356
}357
this._flushPending = false;285
if (this._timer)358
if (this._timer)286
{359
{287
clearInterval(this._timer);360
clearInterval(this._timer);@@ -383,7 +456,7 @@ Online.renderMinis = function (container)383
? I18n.t('hud.miniPoints', { n: p.score || 0 })456
? I18n.t('hud.miniPoints', { n: p.score || 0 })384
: ('Points ' + (p.score || 0));457
: ('Points ' + (p.score || 0));385
}458
}386
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);459
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p));387
}460
}388
for (var id in existing)461
for (var id in existing)389
{462
{@@ -404,7 +477,28 @@ function miniColor (planet, color)404
}477
}405
478
406
479
407
Online._drawMini = function (canvas, snapshot, planet)480
/**481
* t1182: smoothed display y for an opponent's falling blocks (see482
* src/miniPredict.js). Returns id → y, or null without the module.483
*/484
Online._predictMini = function (p, now)485
{486
var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null;487
if (!MP || !p)488
{ return null; }489
if (!this._miniPredict)490
{ this._miniPredict = Object.create(null); }491
var st = this._miniPredict[p.id];492
if (!st)493
{ st = this._miniPredict[p.id] = MP.create(); }494
now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now());495
MP.update(st, p.snapshot, now);496
if (p.eliminated)497
{ return null; }498
return MP.step(st, now, MP.fallSpeedFor(p.planet));499
};500
501
Online._drawMini = function (canvas, snapshot, planet, shownY)408
{502
{409
if (!canvas)503
if (!canvas)410
{ return; }504
{ return; }@@ -451,7 +545,8 @@ Online._drawMini = function (canvas, snapshot, planet)451
{545
{452
var b = blocks[i];546
var b = blocks[i];453
var x = b.col * tw;547
var x = b.col * tw;454
var y = canvas.height - (b.y + 1) * th;548
var by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;549
var y = canvas.height - (by + 1) * th;455
if (b.state === 'locked')550
if (b.state === 'locked')456
{ ctx.fillStyle = '#3a3d4a'; }551
{ ctx.fillStyle = '#3a3d4a'; }457
else if (b.color < 0)552
else if (b.color < 0)@@ -1264,6 +1359,17 @@ Online.spawnFlights = function (results, locals)1264
{1359
{1265
var r = results[i];1360
var r = results[i];1266
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));1361
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));1362
// Own shot already flying locally since the clear (t1181):1363
// pick it up at its current pose and fly on to the real target.1364
var cid = r.client_id != null ? String(r.client_id) : null;1365
if (cid && this._previewIds[cid] && this._isOwnShot(r))1366
{1367
var own = this._findFlight(cid);1368
this._flightSeen[sid] = now;1369
if (own)1370
{ this.retargetFlight(own, r, locals[cid] || {}, now); }1371
continue;1372
}1267
if (this._flightSeen[sid])1373
if (this._flightSeen[sid])1268
{1374
{1269
if (this._previewIds[sid])1375
if (this._previewIds[sid])@@ -1369,12 +1475,11 @@ Online.spawnFlights = function (results, locals)1369
el.style.height = full + 'px';1475
el.style.height = full + 'px';1370
layer.appendChild(el);1476
layer.appendChild(el);1371
1477
1478
// A flight seen late (poll delay) still starts at the sender's1479
// field and plays the whole arc, just a bit faster, so it lands1480
// about when the server delivers it — never a mid-arc pop-in (t1181).1372
var t0 = now;1481
var t0 = now;1373
if (r.age != null && isFinite(r.age) && r.age > 0)1482
duration = this.lateFlightDuration(r.age, duration);1374
{1375
var u0 = Math.min(0.95, (r.age * 1000) / duration);1376
t0 = now - u0 * duration;1377
}1378
var height = miss1483
var height = miss1379
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))1484
? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))1380
: this.arcHeight(start, end);1485
: this.arcHeight(start, end);@@ -1411,6 +1516,52 @@ Online.spawnFlights = function (results, locals)1411
this._flightLocals = {};1516
this._flightLocals = {};1412
};1517
};1413
1518
1519
/** Shortest share of the normal flight a late-seen flight may get. */1520
Online.LATE_MIN_SHARE = 0.5;1521
1522
/** Duration (ms) for a flight first seen `age` seconds after it was fired. */1523
Online.lateFlightDuration = function (age, duration)1524
{1525
if (age == null || !isFinite(age) || age <= 0)1526
{ return duration; }1527
return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000);1528
};1529
1530
/** Remaining duration (ms) after a local preview has flown `elapsedMs`. */1531
Online.retargetDuration = function (elapsedMs, duration)1532
{1533
if (!(elapsedMs > 0))1534
{ return duration; }1535
return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs);1536
};1537
1538
Online._isOwnShot = function (r)1539
{1540
var mine = this.me && this.me.id;1541
var from = r.from_id || r.from_user || null;1542
return !from || (mine != null && String(from) === String(mine));1543
};1544
1545
/**1546
* Sender side (t1181): start the flight the moment the block leaves the1547
* field, before any server round trip. It rises out of the exit cell;1548
* the poll answer retargets it (hit → opponent mini, miss → off-screen).1549
*/1550
Online.startLocalShot = function (shot, start)1551
{1552
if (!shot || !start)1553
{ return null; }1554
return this.previewExit({1555
id: shot.id,1556
col: shot.col,1557
y: shot.y,1558
vy: shot.vy,1559
color: shot.color,1560
start: start,1561
from_id: null1562
});1563
};1564
1414
Online.rememberFlightLocal = function (shot, startX, startY)1565
Online.rememberFlightLocal = function (shot, startX, startY)1415
{1566
{1416
if (!this._flightLocals)1567
if (!this._flightLocals)@@ -1577,6 +1728,7 @@ Online.previewExit = function (info)1577
});1728
});1578
this._previewIds[sid] = true;1729
this._previewIds[sid] = true;1579
this._flightSeen[sid] = now;1730
this._flightSeen[sid] = now;1731
return true;1580
};1732
};1581
1733
1582
/** True while a field sprite should stay hidden — the flight is its visual. */1734
/** True while a field sprite should stay hidden — the flight is its visual. */@@ -1618,6 +1770,8 @@ Online.retargetFlight = function (f, r, meta, now)1618
var miss = !!r.miss;1770
var miss = !!r.miss;1619
var kind = this.flightKind(fromId, targetId, miss);1771
var kind = this.flightKind(fromId, targetId, miss);1620
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;1772
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;1773
if (f.preview)1774
{ duration = this.retargetDuration(now - f.t0, duration); }1621
1775
1622
var landCol = null;1776
var landCol = null;1623
if (r.land_col != null && isFinite(r.land_col))1777
if (r.land_col != null && isFinite(r.land_col))@@ -1734,6 +1888,9 @@ Online.pointAllowedOnArc = function (p, field, start, end, slop)1734
return false;1888
return false;1735
};1889
};1736
1890
1891
/** How long a local preview may wait at its apex for the server (ms). */1892
Online.PREVIEW_HOLD_MS = 2500;1893
1737
Online.tickFlights = function (now)1894
Online.tickFlights = function (now)1738
{1895
{1739
now = now || performance.now();1896
now = now || performance.now();@@ -1742,6 +1899,8 @@ Online.tickFlights = function (now)1742
{1899
{1743
var f = this._flights[i];1900
var f = this._flights[i];1744
var raw = (now - f.t0) / f.duration;1901
var raw = (now - f.t0) / f.duration;1902
if (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS)1903
{ raw = 0.999; }1745
if (raw >= 1)1904
if (raw >= 1)1746
{1905
{1747
if (f.el && f.el.parentNode)1906
if (f.el && f.el.parentNode)@@ -1814,6 +1973,7 @@ Online.clearFlights = function ()1814
this._flightSeen = Object.create(null);1973
this._flightSeen = Object.create(null);1815
this._pendingLandCol = Object.create(null);1974
this._pendingLandCol = Object.create(null);1816
this._previewIds = Object.create(null);1975
this._previewIds = Object.create(null);1976
this._miniPredict = Object.create(null);1817
};1977
};1818
1978
1819
if (typeof globalThis !== 'undefined')1979
if (typeof globalThis !== 'undefined')@@ -0,0 +1,145 @@
1
'use strict';
2
3
// t1181: flights are drawn locally, decoupled from the poll/server cadence.
4
5
const { describe, it, beforeEach } = require('node:test');
6
const assert = require('node:assert/strict');
7
8
function fakeEl ()
9
{
10
return {
11
style: {},
12
className: '',
13
parentNode: null,
14
children: [],
15
appendChild (c) { c.parentNode = this; this.children.push(c); return c; },
16
removeChild (c) { c.parentNode = null; this.children = this.children.filter((x) => x !== c); },
17
querySelector () { return null; },
18
getBoundingClientRect () { return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 }; }
19
};
20
}
21
22
const layers = { flights: fakeEl(), 'flights-back': fakeEl() };
23
globalThis.document = {
24
getElementById: (id) => layers[id] || null,
25
querySelector: () => null,
26
createElement: () => fakeEl()
27
};
28
globalThis.window = globalThis.window || { innerWidth: 1280, innerHeight: 800 };
29
globalThis.CSS = globalThis.CSS || { escape: (s) => String(s) };
30
globalThis.app = { fieldX: 400, fieldY: 100, fieldW: 400, fieldH: 520, tile: 40 };
31
32
const Online = require('../src/online.js');
33
34
function reset ()
35
{
36
Online.clearFlights();
37
Online._pendingShots = [];
38
Online.me = { id: 'me' };
39
layers.flights.children = [];
40
layers['flights-back'].children = [];
41
}
42
43
function poseOf (f, now)
44
{
45
Online.tickFlights(now);
46
const m = /translate\(([-\d.]+)px,([-\d.]+)px\)/.exec(f.el.style.transform || '');
47
return m ? { x: Number(m[1]), y: Number(m[2]) } : null;
48
}
49
50
describe('Local flights (t1181)', () =>
51
{
52
beforeEach(reset);
53
54
it('the sender sees its flight at once, before any server answer', () =>
55
{
56
const ok = Online.startLocalShot({ id: 41, col: 3, y: 13, vy: 6, color: 2 }, { x: 470, y: 100 });
57
assert.equal(ok, true);
58
assert.equal(Online._flights.length, 1);
59
assert.equal(layers.flights.children.length, 1, 'img element is on screen immediately');
60
const f = Online._flights[0];
61
assert.equal(f.preview, true);
62
const p = poseOf(f, f.t0 + 16);
63
assert.ok(p && Math.abs(p.x - 470) < 20 && p.y <= 100, 'starts at the exit cell going up: ' + JSON.stringify(p));
64
});
65
66
it('the poll result retargets the same flight without a jump, and only once', () =>
67
{
68
Online.startLocalShot({ id: 7, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
69
const f = Online._flights[0];
70
f.t0 = performance.now() - 300; // pretend it has been flying for 300 ms
71
const before = poseOf(f, performance.now());
72
// Server answer for the same client id (own shot, a miss so no mini is needed).
73
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0 }]);
74
assert.equal(Online._flights.length, 1, 'no second flight for the same shot');
75
assert.equal(Online._flights[0], f);
76
assert.equal(f.preview, false);
77
// Retargeting happened at performance.now(); sample the new curve at its start.
78
const after = poseOf(f, f.t0);
79
assert.ok(Math.hypot(after.x - before.x, after.y - before.y) < 2, 'continues from the current pose');
80
// The same shot later in the lobby-wide shot_flights list is ignored.
81
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0.4 }]);
82
assert.equal(Online._flights.length, 1);
83
});
84
85
it('the retarget keeps the total close to one flight duration', () =>
86
{
87
assert.equal(Online.retargetDuration(0, 1200), 1200);
88
assert.equal(Online.retargetDuration(300, 1200), 900);
89
assert.equal(Online.retargetDuration(1100, 1200), 600, 'never shorter than half a flight');
90
});
91
92
it('a preview waits at its apex for a slow server instead of vanishing', () =>
93
{
94
Online.startLocalShot({ id: 8, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
95
const f = Online._flights[0];
96
Online.tickFlights(f.t0 + f.duration + 500);
97
assert.equal(Online._flights.length, 1, 'still there while waiting');
98
Online.tickFlights(f.t0 + f.duration + Online.PREVIEW_HOLD_MS + 50);
99
assert.equal(Online._flights.length, 0, 'gives up after the hold');
100
});
101
102
it('a receiver plays a late-seen flight from the start, a bit faster (no mid-arc pop-in)', () =>
103
{
104
assert.equal(Online.lateFlightDuration(0, 1200), 1200);
105
assert.equal(Online.lateFlightDuration(null, 1200), 1200);
106
assert.equal(Online.lateFlightDuration(0.5, 1200), 700);
107
assert.equal(Online.lateFlightDuration(1.0, 1200), 600);
108
const now = performance.now();
109
Online.spawnFlights([{ id: 77, client_id: '3', from_id: 'other', miss: true, color: 0, flight_duration: 1.2, age: 0.5, col: 2, y: 13 }],
110
{ 77: { startX: 200, startY: 90 } });
111
const f = Online._flights.find((x) => x.id === '77');
112
assert.ok(f, 'flight spawned');
113
assert.ok(f.t0 >= now - 1, 't0 is now, not back-dated');
114
assert.ok(Math.abs(f.duration - 700) < 1e-6);
115
const p = poseOf(f, f.t0);
116
assert.ok(Math.hypot(p.x - 200, p.y - 90) < 2, 'starts at the sender field: ' + JSON.stringify(p));
117
});
118
119
it('interpolation depends only on time, not on how often tickFlights runs', () =>
120
{
121
Online.startLocalShot({ id: 9, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });
122
const f = Online._flights[0];
123
const t = f.t0 + 420;
124
poseOf(f, f.t0 + 100);
125
poseOf(f, f.t0 + 250);
126
const a = poseOf(f, t);
127
const b = poseOf(f, t);
128
assert.deepEqual(a, b);
129
});
130
131
it('flushDecision sends new shots right away unless a poll is in flight or just happened', () =>
132
{
133
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 500 }), 'now');
134
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: true, sinceLast: 500 }), 'later');
135
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 30 }), 'later');
136
assert.equal(Online.flushDecision({ polling: true, pending: 0, inFlight: false, sinceLast: 500 }), 'none');
137
assert.equal(Online.flushDecision({ polling: false, pending: 3, inFlight: false, sinceLast: 500 }), 'none');
138
});
139
140
it('the authoritative payload is unchanged: shots are queued exactly as before', () =>
141
{
142
Online.queueShots([{ id: 5, color: 3, col: 1, y: 13 }]);
143
assert.deepEqual(Online._pendingShots, [{ client_id: '5', color: 3, col: 1, y: 13 }]);
144
});
145
});
@@ -0,0 +1,145 @@1
'use strict';2
3
// t1181: flights are drawn locally, decoupled from the poll/server cadence.4
5
const { describe, it, beforeEach } = require('node:test');6
const assert = require('node:assert/strict');7
8
function fakeEl ()9
{10
return {11
style: {},12
className: '',13
parentNode: null,14
children: [],15
appendChild (c) { c.parentNode = this; this.children.push(c); return c; },16
removeChild (c) { c.parentNode = null; this.children = this.children.filter((x) => x !== c); },17
querySelector () { return null; },18
getBoundingClientRect () { return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 }; }19
};20
}21
22
const layers = { flights: fakeEl(), 'flights-back': fakeEl() };23
globalThis.document = {24
getElementById: (id) => layers[id] || null,25
querySelector: () => null,26
createElement: () => fakeEl()27
};28
globalThis.window = globalThis.window || { innerWidth: 1280, innerHeight: 800 };29
globalThis.CSS = globalThis.CSS || { escape: (s) => String(s) };30
globalThis.app = { fieldX: 400, fieldY: 100, fieldW: 400, fieldH: 520, tile: 40 };31
32
const Online = require('../src/online.js');33
34
function reset ()35
{36
Online.clearFlights();37
Online._pendingShots = [];38
Online.me = { id: 'me' };39
layers.flights.children = [];40
layers['flights-back'].children = [];41
}42
43
function poseOf (f, now)44
{45
Online.tickFlights(now);46
const m = /translate\(([-\d.]+)px,([-\d.]+)px\)/.exec(f.el.style.transform || '');47
return m ? { x: Number(m[1]), y: Number(m[2]) } : null;48
}49
50
describe('Local flights (t1181)', () =>51
{52
beforeEach(reset);53
54
it('the sender sees its flight at once, before any server answer', () =>55
{56
const ok = Online.startLocalShot({ id: 41, col: 3, y: 13, vy: 6, color: 2 }, { x: 470, y: 100 });57
assert.equal(ok, true);58
assert.equal(Online._flights.length, 1);59
assert.equal(layers.flights.children.length, 1, 'img element is on screen immediately');60
const f = Online._flights[0];61
assert.equal(f.preview, true);62
const p = poseOf(f, f.t0 + 16);63
assert.ok(p && Math.abs(p.x - 470) < 20 && p.y <= 100, 'starts at the exit cell going up: ' + JSON.stringify(p));64
});65
66
it('the poll result retargets the same flight without a jump, and only once', () =>67
{68
Online.startLocalShot({ id: 7, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });69
const f = Online._flights[0];70
f.t0 = performance.now() - 300; // pretend it has been flying for 300 ms71
const before = poseOf(f, performance.now());72
// Server answer for the same client id (own shot, a miss so no mini is needed).73
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0 }]);74
assert.equal(Online._flights.length, 1, 'no second flight for the same shot');75
assert.equal(Online._flights[0], f);76
assert.equal(f.preview, false);77
// Retargeting happened at performance.now(); sample the new curve at its start.78
const after = poseOf(f, f.t0);79
assert.ok(Math.hypot(after.x - before.x, after.y - before.y) < 2, 'continues from the current pose');80
// The same shot later in the lobby-wide shot_flights list is ignored.81
Online.spawnFlights([{ id: 900, client_id: '7', from_id: 'me', miss: true, color: 1, flight_duration: 1.2, age: 0.4 }]);82
assert.equal(Online._flights.length, 1);83
});84
85
it('the retarget keeps the total close to one flight duration', () =>86
{87
assert.equal(Online.retargetDuration(0, 1200), 1200);88
assert.equal(Online.retargetDuration(300, 1200), 900);89
assert.equal(Online.retargetDuration(1100, 1200), 600, 'never shorter than half a flight');90
});91
92
it('a preview waits at its apex for a slow server instead of vanishing', () =>93
{94
Online.startLocalShot({ id: 8, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });95
const f = Online._flights[0];96
Online.tickFlights(f.t0 + f.duration + 500);97
assert.equal(Online._flights.length, 1, 'still there while waiting');98
Online.tickFlights(f.t0 + f.duration + Online.PREVIEW_HOLD_MS + 50);99
assert.equal(Online._flights.length, 0, 'gives up after the hold');100
});101
102
it('a receiver plays a late-seen flight from the start, a bit faster (no mid-arc pop-in)', () =>103
{104
assert.equal(Online.lateFlightDuration(0, 1200), 1200);105
assert.equal(Online.lateFlightDuration(null, 1200), 1200);106
assert.equal(Online.lateFlightDuration(0.5, 1200), 700);107
assert.equal(Online.lateFlightDuration(1.0, 1200), 600);108
const now = performance.now();109
Online.spawnFlights([{ id: 77, client_id: '3', from_id: 'other', miss: true, color: 0, flight_duration: 1.2, age: 0.5, col: 2, y: 13 }],110
{ 77: { startX: 200, startY: 90 } });111
const f = Online._flights.find((x) => x.id === '77');112
assert.ok(f, 'flight spawned');113
assert.ok(f.t0 >= now - 1, 't0 is now, not back-dated');114
assert.ok(Math.abs(f.duration - 700) < 1e-6);115
const p = poseOf(f, f.t0);116
assert.ok(Math.hypot(p.x - 200, p.y - 90) < 2, 'starts at the sender field: ' + JSON.stringify(p));117
});118
119
it('interpolation depends only on time, not on how often tickFlights runs', () =>120
{121
Online.startLocalShot({ id: 9, col: 5, y: 13, vy: 6, color: 1 }, { x: 510, y: 100 });122
const f = Online._flights[0];123
const t = f.t0 + 420;124
poseOf(f, f.t0 + 100);125
poseOf(f, f.t0 + 250);126
const a = poseOf(f, t);127
const b = poseOf(f, t);128
assert.deepEqual(a, b);129
});130
131
it('flushDecision sends new shots right away unless a poll is in flight or just happened', () =>132
{133
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 500 }), 'now');134
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: true, sinceLast: 500 }), 'later');135
assert.equal(Online.flushDecision({ polling: true, pending: 2, inFlight: false, sinceLast: 30 }), 'later');136
assert.equal(Online.flushDecision({ polling: true, pending: 0, inFlight: false, sinceLast: 500 }), 'none');137
assert.equal(Online.flushDecision({ polling: false, pending: 3, inFlight: false, sinceLast: 500 }), 'none');138
});139
140
it('the authoritative payload is unchanged: shots are queued exactly as before', () =>141
{142
Online.queueShots([{ id: 5, color: 3, col: 1, y: 13 }]);143
assert.deepEqual(Online._pendingShots, [{ client_id: '5', color: 3, col: 1, y: 13 }]);144
});145
});@@ -0,0 +1,162 @@
1
'use strict';
2
3
// t1182: prediction / reconcile of falling blocks on opponents' minis.
4
5
const { describe, it } = require('node:test');
6
const assert = require('node:assert/strict');
7
const MP = require('../src/miniPredict.js');
8
9
const FS = 13 / 3; // fallTime 3 → 4.33 cells/s
10
11
function snap (t, blocks)
12
{
13
return { t, blocks };
14
}
15
16
function run (st, from, to, fs, stepMs)
17
{
18
let out = null;
19
for (let now = from; now <= to + 1e-9; now += stepMs || 16)
20
{ out = MP.step(st, now, fs); }
21
return out;
22
}
23
24
describe('MiniPredict (t1182)', () =>
25
{
26
it('fall speed comes from the opponent planet (13 / fallTime)', () =>
27
{
28
assert.equal(MP.fallSpeedFor({ fallTime: 2 }), 6.5);
29
assert.equal(MP.fallSpeedFor({ fallTime: 5 }), 13 / 5);
30
assert.equal(MP.fallSpeedFor(null), 13 / 3);
31
});
32
33
it('extrapolates a falling block downwards between snapshots, sub-cell', () =>
34
{
35
const st = MP.create();
36
MP.update(st, snap(1000, [{ id: 1, col: 2, y: 10, state: 'falling' }]), 5000);
37
const a = MP.step(st, 5000, FS)[1];
38
const b = MP.step(st, 5100, FS)[1];
39
const c = MP.step(st, 5300, FS)[1];
40
assert.equal(a, 10);
41
assert.ok(Math.abs(b - (10 - FS * 0.1)) < 1e-9, 'b=' + b);
42
assert.ok(Math.abs(c - (10 - FS * 0.3)) < 1e-9, 'c=' + c);
43
assert.ok(c % 1 !== 0, 'sub-cell position');
44
});
45
46
it('never predicts a landing below the stack, and leaves non-falling blocks alone', () =>
47
{
48
const st = MP.create();
49
MP.update(st, snap(0, [
50
{ id: 1, col: 4, y: 0, state: 'still' },
51
{ id: 2, col: 4, y: 1, state: 'locked' },
52
{ id: 3, col: 4, y: 4, state: 'falling' },
53
{ id: 4, col: 4, y: 5.5, state: 'falling' }
54
]), 0);
55
const out = run(st, 0, 1500, FS);
56
assert.equal(out[3], 2, 'stops on top of the stack (y=2), no lock shown');
57
assert.equal(out[4], 3, 'the block above it stops one cell higher');
58
assert.equal(out[1], undefined, 'still blocks are drawn at their own y');
59
assert.equal(out[2], undefined);
60
});
61
62
it('caps extrapolation when snapshots stop coming', () =>
63
{
64
const st = MP.create();
65
MP.update(st, snap(0, [{ id: 1, col: 0, y: 12, state: 'falling' }]), 0);
66
const out = run(st, 0, 5000, FS, 50);
67
assert.ok(Math.abs(out[1] - (12 - FS * MP.MAX_EXTRAP_S)) < 1e-6, 'y=' + out[1]);
68
});
69
70
it('a repeated snapshot (opponent has not polled) does not restart the prediction', () =>
71
{
72
const st = MP.create();
73
const s1 = snap(1000, [{ id: 1, col: 0, y: 12, state: 'falling' }]);
74
MP.update(st, s1, 0);
75
run(st, 0, 400, FS);
76
const again = snap(1000, [{ id: 1, col: 0, y: 12, state: 'falling' }]);
77
assert.equal(MP.update(st, again, 400), false);
78
const out = MP.step(st, 416, FS);
79
assert.ok(out[1] < 12 - FS * 0.4 + 0.01, 'kept falling: ' + out[1]);
80
// Same for snapshots without a sender time (content signature).
81
const st2 = MP.create();
82
MP.update(st2, { blocks: [{ id: 1, col: 0, y: 12, state: 'falling' }] }, 0);
83
assert.equal(MP.update(st2, { blocks: [{ id: 1, col: 0, y: 12, state: 'falling' }] }, 400), false);
84
});
85
86
it('a late snapshot is placed at the time it was taken (sender clock offset)', () =>
87
{
88
const st = MP.create();
89
MP.update(st, snap(10000, [{ id: 1, col: 0, y: 12, state: 'falling' }]), 50); // offset 50 ms
90
// Next snapshot taken 750 ms later but arrives 300 ms late.
91
MP.update(st, snap(10750, [{ id: 1, col: 0, y: 12 - FS * 0.75, state: 'falling' }]), 50 + 750 + 300);
92
assert.equal(st.at, 10750 + (50 - 10000));
93
const t = MP.predict(st.snap, (1100 - st.at) / 1000, FS)[1];
94
assert.ok(Math.abs(t - (12 - FS * 1.05)) < 1e-6, 'continuous with true motion: ' + t);
95
});
96
97
it('reconciles smoothly: a lagging block catches up, a leading one never moves up', () =>
98
{
99
// Lagging: shown 0.8 cell above the new truth.
100
const st = MP.create();
101
MP.update(st, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);
102
MP.step(st, 0, FS);
103
st.shown[1] = 10.8;
104
let prev = 10.8;
105
for (let now = 16; now <= 400; now += 16)
106
{
107
const y = MP.step(st, now, FS)[1];
108
assert.ok(y <= prev + 1e-9, 'monotonic down');
109
prev = y;
110
}
111
const truth = 10 - FS * 0.4;
112
assert.ok(Math.abs(prev - truth) < 0.02, 'caught up: ' + prev + ' vs ' + truth);
113
114
// Leading: shown 0.6 below the truth → keeps falling (slower), never jumps up.
115
const st2 = MP.create();
116
MP.update(st2, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);
117
MP.step(st2, 0, FS);
118
st2.shown[1] = 9.4;
119
prev = 9.4;
120
for (let now = 16; now <= 800; now += 16)
121
{
122
const y = MP.step(st2, now, FS)[1];
123
assert.ok(y <= prev + 1e-9, 'never up: ' + y + ' > ' + prev);
124
prev = y;
125
}
126
assert.ok(Math.abs(prev - (10 - FS * 0.8)) < 0.05, 'converged: ' + prev);
127
});
128
129
it('snaps when far off (e.g. block jumped / was dragged) and drops blocks that landed', () =>
130
{
131
const st = MP.create();
132
MP.update(st, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);
133
run(st, 0, 200, FS);
134
// Authoritative: block now 4 cells higher (far) → snap.
135
MP.update(st, snap(250, [{ id: 1, col: 0, y: 13.5, state: 'falling' }]), 250);
136
assert.equal(MP.step(st, 250, FS)[1], 13.5);
137
// Then it landed: not falling any more → no predicted pose.
138
MP.update(st, snap(900, [{ id: 1, col: 0, y: 0, state: 'still' }]), 900);
139
assert.equal(MP.step(st, 916, FS)[1], undefined);
140
});
141
142
it('steady 750 ms snapshots of a constant fall render as one smooth descent', () =>
143
{
144
const st = MP.create();
145
let maxStep = 0;
146
let prev = null;
147
const y0 = 12.5;
148
for (let now = 0; now <= 2200; now += 16)
149
{
150
const k = Math.floor(now / 750);
151
const taken = k * 750;
152
if (now % 750 < 16)
153
{ MP.update(st, snap(taken, [{ id: 9, col: 1, y: y0 - FS * taken / 1000, state: 'falling' }]), now + 40); }
154
const y = MP.step(st, now + 40, FS)[9];
155
if (prev != null)
156
{ maxStep = Math.max(maxStep, Math.abs(prev - y)); }
157
prev = y;
158
}
159
const perFrame = FS * 0.016;
160
assert.ok(maxStep < perFrame * 1.6, 'max per-frame move ' + maxStep.toFixed(3) + ' vs fall ' + perFrame.toFixed(3));
161
});
162
});
@@ -0,0 +1,162 @@1
'use strict';2
3
// t1182: prediction / reconcile of falling blocks on opponents' minis.4
5
const { describe, it } = require('node:test');6
const assert = require('node:assert/strict');7
const MP = require('../src/miniPredict.js');8
9
const FS = 13 / 3; // fallTime 3 → 4.33 cells/s10
11
function snap (t, blocks)12
{13
return { t, blocks };14
}15
16
function run (st, from, to, fs, stepMs)17
{18
let out = null;19
for (let now = from; now <= to + 1e-9; now += stepMs || 16)20
{ out = MP.step(st, now, fs); }21
return out;22
}23
24
describe('MiniPredict (t1182)', () =>25
{26
it('fall speed comes from the opponent planet (13 / fallTime)', () =>27
{28
assert.equal(MP.fallSpeedFor({ fallTime: 2 }), 6.5);29
assert.equal(MP.fallSpeedFor({ fallTime: 5 }), 13 / 5);30
assert.equal(MP.fallSpeedFor(null), 13 / 3);31
});32
33
it('extrapolates a falling block downwards between snapshots, sub-cell', () =>34
{35
const st = MP.create();36
MP.update(st, snap(1000, [{ id: 1, col: 2, y: 10, state: 'falling' }]), 5000);37
const a = MP.step(st, 5000, FS)[1];38
const b = MP.step(st, 5100, FS)[1];39
const c = MP.step(st, 5300, FS)[1];40
assert.equal(a, 10);41
assert.ok(Math.abs(b - (10 - FS * 0.1)) < 1e-9, 'b=' + b);42
assert.ok(Math.abs(c - (10 - FS * 0.3)) < 1e-9, 'c=' + c);43
assert.ok(c % 1 !== 0, 'sub-cell position');44
});45
46
it('never predicts a landing below the stack, and leaves non-falling blocks alone', () =>47
{48
const st = MP.create();49
MP.update(st, snap(0, [50
{ id: 1, col: 4, y: 0, state: 'still' },51
{ id: 2, col: 4, y: 1, state: 'locked' },52
{ id: 3, col: 4, y: 4, state: 'falling' },53
{ id: 4, col: 4, y: 5.5, state: 'falling' }54
]), 0);55
const out = run(st, 0, 1500, FS);56
assert.equal(out[3], 2, 'stops on top of the stack (y=2), no lock shown');57
assert.equal(out[4], 3, 'the block above it stops one cell higher');58
assert.equal(out[1], undefined, 'still blocks are drawn at their own y');59
assert.equal(out[2], undefined);60
});61
62
it('caps extrapolation when snapshots stop coming', () =>63
{64
const st = MP.create();65
MP.update(st, snap(0, [{ id: 1, col: 0, y: 12, state: 'falling' }]), 0);66
const out = run(st, 0, 5000, FS, 50);67
assert.ok(Math.abs(out[1] - (12 - FS * MP.MAX_EXTRAP_S)) < 1e-6, 'y=' + out[1]);68
});69
70
it('a repeated snapshot (opponent has not polled) does not restart the prediction', () =>71
{72
const st = MP.create();73
const s1 = snap(1000, [{ id: 1, col: 0, y: 12, state: 'falling' }]);74
MP.update(st, s1, 0);75
run(st, 0, 400, FS);76
const again = snap(1000, [{ id: 1, col: 0, y: 12, state: 'falling' }]);77
assert.equal(MP.update(st, again, 400), false);78
const out = MP.step(st, 416, FS);79
assert.ok(out[1] < 12 - FS * 0.4 + 0.01, 'kept falling: ' + out[1]);80
// Same for snapshots without a sender time (content signature).81
const st2 = MP.create();82
MP.update(st2, { blocks: [{ id: 1, col: 0, y: 12, state: 'falling' }] }, 0);83
assert.equal(MP.update(st2, { blocks: [{ id: 1, col: 0, y: 12, state: 'falling' }] }, 400), false);84
});85
86
it('a late snapshot is placed at the time it was taken (sender clock offset)', () =>87
{88
const st = MP.create();89
MP.update(st, snap(10000, [{ id: 1, col: 0, y: 12, state: 'falling' }]), 50); // offset 50 ms90
// Next snapshot taken 750 ms later but arrives 300 ms late.91
MP.update(st, snap(10750, [{ id: 1, col: 0, y: 12 - FS * 0.75, state: 'falling' }]), 50 + 750 + 300);92
assert.equal(st.at, 10750 + (50 - 10000));93
const t = MP.predict(st.snap, (1100 - st.at) / 1000, FS)[1];94
assert.ok(Math.abs(t - (12 - FS * 1.05)) < 1e-6, 'continuous with true motion: ' + t);95
});96
97
it('reconciles smoothly: a lagging block catches up, a leading one never moves up', () =>98
{99
// Lagging: shown 0.8 cell above the new truth.100
const st = MP.create();101
MP.update(st, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);102
MP.step(st, 0, FS);103
st.shown[1] = 10.8;104
let prev = 10.8;105
for (let now = 16; now <= 400; now += 16)106
{107
const y = MP.step(st, now, FS)[1];108
assert.ok(y <= prev + 1e-9, 'monotonic down');109
prev = y;110
}111
const truth = 10 - FS * 0.4;112
assert.ok(Math.abs(prev - truth) < 0.02, 'caught up: ' + prev + ' vs ' + truth);113
114
// Leading: shown 0.6 below the truth → keeps falling (slower), never jumps up.115
const st2 = MP.create();116
MP.update(st2, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);117
MP.step(st2, 0, FS);118
st2.shown[1] = 9.4;119
prev = 9.4;120
for (let now = 16; now <= 800; now += 16)121
{122
const y = MP.step(st2, now, FS)[1];123
assert.ok(y <= prev + 1e-9, 'never up: ' + y + ' > ' + prev);124
prev = y;125
}126
assert.ok(Math.abs(prev - (10 - FS * 0.8)) < 0.05, 'converged: ' + prev);127
});128
129
it('snaps when far off (e.g. block jumped / was dragged) and drops blocks that landed', () =>130
{131
const st = MP.create();132
MP.update(st, snap(0, [{ id: 1, col: 0, y: 10, state: 'falling' }]), 0);133
run(st, 0, 200, FS);134
// Authoritative: block now 4 cells higher (far) → snap.135
MP.update(st, snap(250, [{ id: 1, col: 0, y: 13.5, state: 'falling' }]), 250);136
assert.equal(MP.step(st, 250, FS)[1], 13.5);137
// Then it landed: not falling any more → no predicted pose.138
MP.update(st, snap(900, [{ id: 1, col: 0, y: 0, state: 'still' }]), 900);139
assert.equal(MP.step(st, 916, FS)[1], undefined);140
});141
142
it('steady 750 ms snapshots of a constant fall render as one smooth descent', () =>143
{144
const st = MP.create();145
let maxStep = 0;146
let prev = null;147
const y0 = 12.5;148
for (let now = 0; now <= 2200; now += 16)149
{150
const k = Math.floor(now / 750);151
const taken = k * 750;152
if (now % 750 < 16)153
{ MP.update(st, snap(taken, [{ id: 9, col: 1, y: y0 - FS * taken / 1000, state: 'falling' }]), now + 40); }154
const y = MP.step(st, now + 40, FS)[9];155
if (prev != null)156
{ maxStep = Math.max(maxStep, Math.abs(prev - y)); }157
prev = y;158
}159
const perFrame = FS * 0.016;160
assert.ok(maxStep < perFrame * 1.6, 'max per-frame move ' + maxStep.toFixed(3) + ' vs fall ' + perFrame.toFixed(3));161
});162
});@@ -0,0 +1,257 @@
1
#!/usr/bin/env python3
2
"""t1181: sender/receiver flight latency and smoothness with two real browser clients.
3
4
Usage: t1181-flights-playwright.py [ROOT] [TAG]
5
ROOT defaults to /workspace/meteors (its build/ is served by php -S).
6
Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver.
7
Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics.
8
"""
9
from __future__ import annotations
10
11
import json
12
import os
13
import socket
14
import subprocess
15
import sys
16
import tempfile
17
import time
18
from pathlib import Path
19
20
from playwright.sync_api import sync_playwright
21
22
ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors")
23
TAG = sys.argv[2] if len(sys.argv) > 2 else "after"
24
SHOTS = Path("/workspace/meteors-shots")
25
SHOTS.mkdir(parents=True, exist_ok=True)
26
PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
27
CHROME = "/usr/bin/google-chrome"
28
ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
29
FAILURES = []
30
URL = None
31
32
# Records, per frame, every flight element's on-screen centre, plus the
33
# Date.now() when each of my shots left the field (cull).
34
PROBE = """() => {
35
if (window.__probe) return;
36
const P = window.__probe = { culls: {}, tracks: {}, frames: 0 };
37
const orig = GameCore.prototype.consumeOutgoingShots;
38
GameCore.prototype.consumeOutgoingShots = function () {
39
const shots = orig.call(this);
40
if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now();
41
return shots;
42
};
43
let ids = new WeakMap(); let next = 1;
44
function f() {
45
P.frames++;
46
const now = Date.now();
47
for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) {
48
if (!ids.has(el)) ids.set(el, 'el' + (next++));
49
const k = ids.get(el);
50
const r = el.getBoundingClientRect();
51
if (!r.width) continue;
52
(P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]);
53
}
54
requestAnimationFrame(f);
55
}
56
requestAnimationFrame(f);
57
}"""
58
59
SHOOT = """(n) => {
60
const out = [];
61
for (let i = 0; i < n; i++) {
62
const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying');
63
b.vy = 6;
64
out.push(b.id);
65
}
66
return out;
67
}"""
68
69
70
def check(cond, msg):
71
print(("OK " if cond else "FAIL") + " " + msg)
72
if not cond:
73
FAILURES.append(msg)
74
return cond
75
76
77
def free_port():
78
s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port
79
80
81
def start_php(port, data):
82
env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data)
83
log = open(f"/tmp/t1181-php-{TAG}.log", "w")
84
proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
85
cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log)
86
time.sleep(0.5)
87
return proc
88
89
90
def login(page, n):
91
page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded")
92
page.wait_for_timeout(300)
93
page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded")
94
page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
95
page.locator("#online-panel").wait_for(state="visible", timeout=8000)
96
97
98
def analyse(tracks, t_ref):
99
"""First appearance (ms after t_ref), max per-frame jump (px) and path length per flight."""
100
out = []
101
for k, pts in tracks.items():
102
if len(pts) < 2:
103
continue
104
first = pts[0][0] - t_ref
105
jumps = []
106
for a, b in zip(pts, pts[1:]):
107
dt = max(1, b[0] - a[0])
108
d = ((b[1] - a[1]) ** 2 + (b[2] - a[2]) ** 2) ** 0.5
109
jumps.append(d / (dt / 16.7)) # px per 60 Hz frame
110
out.append({"id": k, "first_ms": first, "frames": len(pts), "start": [round(pts[0][1]), round(pts[0][2])],
111
"max_jump_px": round(max(jumps), 1), "median_jump_px": round(sorted(jumps)[len(jumps) // 2], 1),
112
"max_kink_px": round(max([abs(y - x) for x, y in zip(jumps, jumps[1:])] or [0]), 1),
113
"dur_ms": pts[-1][0] - pts[0][0]})
114
return sorted(out, key=lambda r: r["first_ms"])
115
116
117
def main():
118
global URL
119
port = free_port(); URL = f"http://127.0.0.1:{port}/"
120
proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1181-")))
121
metrics = {}
122
try:
123
with sync_playwright() as p:
124
b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True)
125
c1 = b.new_context(viewport={"width": 1280, "height": 800})
126
c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3)
127
p1, p2 = c1.new_page(), c2.new_page()
128
errs = []
129
for pg, tag in ((p1, "desktop"), (p2, "mobile")):
130
pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}"))
131
login(p1, 1); login(p2, 2)
132
p1.locator("#btn-create").click()
133
p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
134
code = p1.locator("#lobby-code").inner_text().strip()
135
p2.locator("#join-code").fill(code); p2.locator("#btn-join").click()
136
p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
137
p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click()
138
start = p1.locator("#btn-start")
139
for _ in range(20):
140
if start.is_visible() and start.is_enabled():
141
break
142
p1.wait_for_timeout(400)
143
start.click()
144
for pg in (p1, p2):
145
pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
146
p1.wait_for_timeout(1500)
147
for pg in (p1, p2):
148
pg.evaluate(PROBE)
149
# Several rounds so the poll phase varies.
150
rounds = []
151
for rnd in range(4):
152
for pg in (p1, p2):
153
pg.evaluate("() => { window.__probe.tracks = {}; window.__probe.culls = {}; }")
154
p1.wait_for_timeout(137 * rnd)
155
t_shot = p1.evaluate("() => Date.now()")
156
p1.evaluate(SHOOT, 3)
157
if rnd == 0:
158
p1.wait_for_timeout(120); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-120ms.png"))
159
p1.wait_for_timeout(330); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-450ms.png"))
160
p2.wait_for_timeout(500); p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-receiver.png"))
161
p1.wait_for_timeout(3200)
162
s = p1.evaluate("() => window.__probe")
163
r = p2.evaluate("() => window.__probe")
164
cull = min(s["culls"].values()) if s["culls"] else t_shot
165
rounds.append({"sender": analyse(s["tracks"], cull), "receiver": analyse(r["tracks"], cull)})
166
metrics["rounds"] = rounds
167
# t1182: falling blocks on the receiver's mini of the sender.
168
p2.evaluate("""() => {
169
const R = window.__mini = { rows: [] };
170
const orig = Online._drawMini;
171
Online._drawMini = function (canvas, snapshot, planet, shownY) {
172
if (snapshot && snapshot.blocks) {
173
for (const b of snapshot.blocks) if (b.color === 3 && b.col === 7) {
174
const y = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
175
R.rows.push([performance.now(), b.id, y, b.state]);
176
}
177
}
178
return orig.apply(this, arguments);
179
};
180
}""")
181
p1.evaluate("""() => {
182
const b = app.core.createBlock(7, 12.6, 3, 'falling');
183
b.vy = -app.planet.fallSpeed;
184
}""")
185
p2.wait_for_timeout(1400)
186
p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-mini-falling.png"))
187
p2.wait_for_timeout(2600)
188
rows = p2.evaluate("() => window.__mini.rows")
189
fall_speed = p1.evaluate("() => app.planet.fallSpeed")
190
steps = []
191
falling = [r for r in rows if r[3] == 'falling']
192
for a_, b_ in zip(falling, falling[1:]):
193
if a_[1] == b_[1]:
194
steps.append(round(a_[2] - b_[2], 4))
195
# Only judge motion until the block reaches its resting spot
196
# (prediction stops on top of the stack, it never locks).
197
last = max([i for i, s in enumerate(steps) if abs(s) > 1e-6] or [0])
198
steps = steps[:last + 1]
199
moving = [s for s in steps if abs(s) > 1e-6]
200
metrics["mini"] = {
201
"frames_falling": len(falling),
202
"frames_moving": len(moving),
203
"share_moving": round(len(moving) / max(1, len(steps)), 3),
204
"max_step_cells": max([abs(s) for s in steps] or [0]),
205
"fall_speed": fall_speed,
206
# A jump: > 0.5 cell in one frame AND far faster than the
207
# real fall (long frames from renderer stalls are not jumps).
208
"jumps_over_half_cell": sum(1 for a_, b_ in zip(falling, falling[1:])
209
if a_[1] == b_[1] and abs(a_[2] - b_[2]) > 0.5
210
and abs(a_[2] - b_[2]) / max(1e-3, (b_[0] - a_[0]) / 1000) > 2.5 * fall_speed),
211
"upward_steps": sum(1 for s in steps if s < -1e-6),
212
"landed_seen": any(r[3] != 'falling' for r in rows),
213
"big_steps": [[round(a_[0]-falling[0][0]), round(b_[0]-a_[0]), round(a_[2],3), round(b_[2],3)] for a_, b_ in zip(falling, falling[1:]) if a_[1]==b_[1] and abs(a_[2]-b_[2])>0.3],
214
"series": [[round(r[0]-falling[0][0]), round(r[2],3)] for r in falling][::6] if falling else [],
215
}
216
metrics["errors"] = errs
217
b.close()
218
finally:
219
proc.terminate()
220
# Summaries
221
# Own outgoing shots leave the top of the sender's main field; flights
222
# that start low on the screen are incoming garbage from the opponent.
223
sf = [f for r in metrics["rounds"] for f in r["sender"] if f["start"][1] < 400]
224
rf = [f for r in metrics["rounds"] for f in r["receiver"]]
225
summ = {
226
"tag": TAG,
227
"sender_flights": len(sf),
228
"sender_first_ms": [f["first_ms"] for f in sf],
229
"sender_max_jump_px": max([f["max_jump_px"] for f in sf] or [0]),
230
"receiver_flights": len(rf),
231
"receiver_first_ms": [f["first_ms"] for f in rf],
232
"receiver_max_jump_px": max([f["max_jump_px"] for f in rf] or [0]),
233
"receiver_starts": [f["start"] for f in rf][:6],
234
"sender_max_kink_px": max([f["max_kink_px"] for f in sf] or [0]),
235
"receiver_max_kink_px": max([f["max_kink_px"] for f in rf] or [0]),
236
"sender_first_ms_median": sorted(f["first_ms"] for f in sf if f["first_ms"] >= 0)[len(sf) // 2] if sf else None,
237
"receiver_first_ms_median": sorted(f["first_ms"] for f in rf if f["first_ms"] >= 0)[len(rf) // 2] if rf else None,
238
"errors": metrics["errors"],
239
"mini": metrics.get("mini"),
240
}
241
print(json.dumps(summ, indent=1))
242
Path(f"/workspace/meteors-shots/t1181-{TAG}-metrics.json").write_text(json.dumps({"summary": summ, **metrics}, indent=1))
243
return summ
244
245
246
if __name__ == "__main__":
247
s = main()
248
if TAG == "after":
249
check(s["sender_flights"] >= 12, f"sender drew a flight for every shot ({s['sender_flights']})")
250
check(max(s["sender_first_ms"] or [9999]) <= 120, f"sender flight starts within ~1-2 frames of the cull (max {max(s['sender_first_ms'] or [0])} ms)")
251
check(s["receiver_flights"] >= 12, f"receiver drew the opponent's flights ({s['receiver_flights']})")
252
check(not s["errors"], f"no page errors {s['errors'][:2]}")
253
m = s["mini"] or {}
254
check(m.get("share_moving", 0) > 0.8, f"mini: falling block moves on most frames ({m.get('share_moving')})")
255
check(m.get("jumps_over_half_cell", 99) == 0, f"mini: no jumps > 0.5 cell ({m.get('jumps_over_half_cell')})")
256
check(m.get("upward_steps", 99) == 0, f"mini: never moves up ({m.get('upward_steps')})")
257
sys.exit(1 if FAILURES else 0)
@@ -0,0 +1,257 @@1
#!/usr/bin/env python32
"""t1181: sender/receiver flight latency and smoothness with two real browser clients.3
4
Usage: t1181-flights-playwright.py [ROOT] [TAG]5
ROOT defaults to /workspace/meteors (its build/ is served by php -S).6
Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver.7
Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics.8
"""9
from __future__ import annotations10
11
import json12
import os13
import socket14
import subprocess15
import sys16
import tempfile17
import time18
from pathlib import Path19
20
from playwright.sync_api import sync_playwright21
22
ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors")23
TAG = sys.argv[2] if len(sys.argv) > 2 else "after"24
SHOTS = Path("/workspace/meteors-shots")25
SHOTS.mkdir(parents=True, exist_ok=True)26
PHP = os.environ.get("PHP", "/home/box/.local/bin/php")27
CHROME = "/usr/bin/google-chrome"28
ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]29
FAILURES = []30
URL = None31
32
# Records, per frame, every flight element's on-screen centre, plus the33
# Date.now() when each of my shots left the field (cull).34
PROBE = """() => {35
if (window.__probe) return;36
const P = window.__probe = { culls: {}, tracks: {}, frames: 0 };37
const orig = GameCore.prototype.consumeOutgoingShots;38
GameCore.prototype.consumeOutgoingShots = function () {39
const shots = orig.call(this);40
if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now();41
return shots;42
};43
let ids = new WeakMap(); let next = 1;44
function f() {45
P.frames++;46
const now = Date.now();47
for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) {48
if (!ids.has(el)) ids.set(el, 'el' + (next++));49
const k = ids.get(el);50
const r = el.getBoundingClientRect();51
if (!r.width) continue;52
(P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]);53
}54
requestAnimationFrame(f);55
}56
requestAnimationFrame(f);57
}"""58
59
SHOOT = """(n) => {60
const out = [];61
for (let i = 0; i < n; i++) {62
const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying');63
b.vy = 6;64
out.push(b.id);65
}66
return out;67
}"""68
69
70
def check(cond, msg):71
print(("OK " if cond else "FAIL") + " " + msg)72
if not cond:73
FAILURES.append(msg)74
return cond75
76
77
def free_port():78
s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port79
80
81
def start_php(port, data):82
env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data)83
log = open(f"/tmp/t1181-php-{TAG}.log", "w")84
proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],85
cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log)86
time.sleep(0.5)87
return proc88
89
90
def login(page, n):91
page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded")92
page.wait_for_timeout(300)93
page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded")94
page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)95
page.locator("#online-panel").wait_for(state="visible", timeout=8000)96
97
98
def analyse(tracks, t_ref):99
"""First appearance (ms after t_ref), max per-frame jump (px) and path length per flight."""100
out = []101
for k, pts in tracks.items():102
if len(pts) < 2:103
continue104
first = pts[0][0] - t_ref105
jumps = []106
for a, b in zip(pts, pts[1:]):107
dt = max(1, b[0] - a[0])108
d = ((b[1] - a[1]) ** 2 + (b[2] - a[2]) ** 2) ** 0.5109
jumps.append(d / (dt / 16.7)) # px per 60 Hz frame110
out.append({"id": k, "first_ms": first, "frames": len(pts), "start": [round(pts[0][1]), round(pts[0][2])],111
"max_jump_px": round(max(jumps), 1), "median_jump_px": round(sorted(jumps)[len(jumps) // 2], 1),112
"max_kink_px": round(max([abs(y - x) for x, y in zip(jumps, jumps[1:])] or [0]), 1),113
"dur_ms": pts[-1][0] - pts[0][0]})114
return sorted(out, key=lambda r: r["first_ms"])115
116
117
def main():118
global URL119
port = free_port(); URL = f"http://127.0.0.1:{port}/"120
proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1181-")))121
metrics = {}122
try:123
with sync_playwright() as p:124
b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True)125
c1 = b.new_context(viewport={"width": 1280, "height": 800})126
c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3)127
p1, p2 = c1.new_page(), c2.new_page()128
errs = []129
for pg, tag in ((p1, "desktop"), (p2, "mobile")):130
pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}"))131
login(p1, 1); login(p2, 2)132
p1.locator("#btn-create").click()133
p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)134
code = p1.locator("#lobby-code").inner_text().strip()135
p2.locator("#join-code").fill(code); p2.locator("#btn-join").click()136
p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)137
p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click()138
start = p1.locator("#btn-start")139
for _ in range(20):140
if start.is_visible() and start.is_enabled():141
break142
p1.wait_for_timeout(400)143
start.click()144
for pg in (p1, p2):145
pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)146
p1.wait_for_timeout(1500)147
for pg in (p1, p2):148
pg.evaluate(PROBE)149
# Several rounds so the poll phase varies.150
rounds = []151
for rnd in range(4):152
for pg in (p1, p2):153
pg.evaluate("() => { window.__probe.tracks = {}; window.__probe.culls = {}; }")154
p1.wait_for_timeout(137 * rnd)155
t_shot = p1.evaluate("() => Date.now()")156
p1.evaluate(SHOOT, 3)157
if rnd == 0:158
p1.wait_for_timeout(120); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-120ms.png"))159
p1.wait_for_timeout(330); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-450ms.png"))160
p2.wait_for_timeout(500); p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-receiver.png"))161
p1.wait_for_timeout(3200)162
s = p1.evaluate("() => window.__probe")163
r = p2.evaluate("() => window.__probe")164
cull = min(s["culls"].values()) if s["culls"] else t_shot165
rounds.append({"sender": analyse(s["tracks"], cull), "receiver": analyse(r["tracks"], cull)})166
metrics["rounds"] = rounds167
# t1182: falling blocks on the receiver's mini of the sender.168
p2.evaluate("""() => {169
const R = window.__mini = { rows: [] };170
const orig = Online._drawMini;171
Online._drawMini = function (canvas, snapshot, planet, shownY) {172
if (snapshot && snapshot.blocks) {173
for (const b of snapshot.blocks) if (b.color === 3 && b.col === 7) {174
const y = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;175
R.rows.push([performance.now(), b.id, y, b.state]);176
}177
}178
return orig.apply(this, arguments);179
};180
}""")181
p1.evaluate("""() => {182
const b = app.core.createBlock(7, 12.6, 3, 'falling');183
b.vy = -app.planet.fallSpeed;184
}""")185
p2.wait_for_timeout(1400)186
p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-mini-falling.png"))187
p2.wait_for_timeout(2600)188
rows = p2.evaluate("() => window.__mini.rows")189
fall_speed = p1.evaluate("() => app.planet.fallSpeed")190
steps = []191
falling = [r for r in rows if r[3] == 'falling']192
for a_, b_ in zip(falling, falling[1:]):193
if a_[1] == b_[1]:194
steps.append(round(a_[2] - b_[2], 4))195
# Only judge motion until the block reaches its resting spot196
# (prediction stops on top of the stack, it never locks).197
last = max([i for i, s in enumerate(steps) if abs(s) > 1e-6] or [0])198
steps = steps[:last + 1]199
moving = [s for s in steps if abs(s) > 1e-6]200
metrics["mini"] = {201
"frames_falling": len(falling),202
"frames_moving": len(moving),203
"share_moving": round(len(moving) / max(1, len(steps)), 3),204
"max_step_cells": max([abs(s) for s in steps] or [0]),205
"fall_speed": fall_speed,206
# A jump: > 0.5 cell in one frame AND far faster than the207
# real fall (long frames from renderer stalls are not jumps).208
"jumps_over_half_cell": sum(1 for a_, b_ in zip(falling, falling[1:])209
if a_[1] == b_[1] and abs(a_[2] - b_[2]) > 0.5210
and abs(a_[2] - b_[2]) / max(1e-3, (b_[0] - a_[0]) / 1000) > 2.5 * fall_speed),211
"upward_steps": sum(1 for s in steps if s < -1e-6),212
"landed_seen": any(r[3] != 'falling' for r in rows),213
"big_steps": [[round(a_[0]-falling[0][0]), round(b_[0]-a_[0]), round(a_[2],3), round(b_[2],3)] for a_, b_ in zip(falling, falling[1:]) if a_[1]==b_[1] and abs(a_[2]-b_[2])>0.3],214
"series": [[round(r[0]-falling[0][0]), round(r[2],3)] for r in falling][::6] if falling else [],215
}216
metrics["errors"] = errs217
b.close()218
finally:219
proc.terminate()220
# Summaries221
# Own outgoing shots leave the top of the sender's main field; flights222
# that start low on the screen are incoming garbage from the opponent.223
sf = [f for r in metrics["rounds"] for f in r["sender"] if f["start"][1] < 400]224
rf = [f for r in metrics["rounds"] for f in r["receiver"]]225
summ = {226
"tag": TAG,227
"sender_flights": len(sf),228
"sender_first_ms": [f["first_ms"] for f in sf],229
"sender_max_jump_px": max([f["max_jump_px"] for f in sf] or [0]),230
"receiver_flights": len(rf),231
"receiver_first_ms": [f["first_ms"] for f in rf],232
"receiver_max_jump_px": max([f["max_jump_px"] for f in rf] or [0]),233
"receiver_starts": [f["start"] for f in rf][:6],234
"sender_max_kink_px": max([f["max_kink_px"] for f in sf] or [0]),235
"receiver_max_kink_px": max([f["max_kink_px"] for f in rf] or [0]),236
"sender_first_ms_median": sorted(f["first_ms"] for f in sf if f["first_ms"] >= 0)[len(sf) // 2] if sf else None,237
"receiver_first_ms_median": sorted(f["first_ms"] for f in rf if f["first_ms"] >= 0)[len(rf) // 2] if rf else None,238
"errors": metrics["errors"],239
"mini": metrics.get("mini"),240
}241
print(json.dumps(summ, indent=1))242
Path(f"/workspace/meteors-shots/t1181-{TAG}-metrics.json").write_text(json.dumps({"summary": summ, **metrics}, indent=1))243
return summ244
245
246
if __name__ == "__main__":247
s = main()248
if TAG == "after":249
check(s["sender_flights"] >= 12, f"sender drew a flight for every shot ({s['sender_flights']})")250
check(max(s["sender_first_ms"] or [9999]) <= 120, f"sender flight starts within ~1-2 frames of the cull (max {max(s['sender_first_ms'] or [0])} ms)")251
check(s["receiver_flights"] >= 12, f"receiver drew the opponent's flights ({s['receiver_flights']})")252
check(not s["errors"], f"no page errors {s['errors'][:2]}")253
m = s["mini"] or {}254
check(m.get("share_moving", 0) > 0.8, f"mini: falling block moves on most frames ({m.get('share_moving')})")255
check(m.get("jumps_over_half_cell", 99) == 0, f"mini: no jumps > 0.5 cell ({m.get('jumps_over_half_cell')})")256
check(m.get("upward_steps", 99) == 0, f"mini: never moves up ({m.get('upward_steps')})")257
sys.exit(1 if FAILURES else 0)