Merge branch 'feature/t1134-smooth-arcs'
@@ -2695,7 +2695,8 @@ GameCore.prototype.cullOffTop = function ()
2695
2695
id: block.id,
2696
2696
color: block.color,
2697
2697
col: block.col,
2698
y: block.y
2698
y: block.y,
2699
vy: block.vy
2699
2700
});
2700
2701
this.score += 1;
2701
2702
this.removeBlock(block);
@@ -4567,7 +4568,7 @@ Online.playerFieldRect = function ()
4567
4568
4568
4569
/**
4569
4570
* True if (x, y) is inside the field's interior. The top edge (a few
4570
* pixels) is not interior: that is where arcs may land (t1128).
4571
* pixels) is not interior: launch and landing may use that band.
4571
4572
*/
4572
4573
Online.pointInFieldInterior = function (x, y, field, slop)
4573
4574
{
@@ -4578,107 +4579,363 @@ Online.pointInFieldInterior = function (x, y, field, slop)
4578
4579
&& y > field.top + slop && y < field.bottom - 0.5;
4579
4580
};
4580
4581
4582
/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */
4583
Online.cubicBezier = function (p0, p1, p2, p3, t)
4584
{
4585
if (t < 0)
4586
{ t = 0; }
4587
if (t > 1)
4588
{ t = 1; }
4589
var u = 1 - t;
4590
var a = u * u * u;
4591
var b = 3 * u * u * t;
4592
var c = 3 * u * t * t;
4593
var d = t * t * t;
4594
return {
4595
x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
4596
y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
4597
};
4598
};
4599
4600
/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */
4601
Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)
4602
{
4603
if (t < 0)
4604
{ t = 0; }
4605
if (t > 1)
4606
{ t = 1; }
4607
var u = 1 - t;
4608
return {
4609
x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
4610
y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
4611
};
4612
};
4613
4581
4614
/**
4582
* Waypoints that route a player↔enemy arc around the field, never
4583
* through its interior: up the outside, across above the top edge,
4584
* then into the target (t1128). If both ends already sit at or above
4585
* the top, a simple two-point path is enough.
4615
* Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
4616
* v0=v1=1 is linear (constant speed in t, no endpoint halt).
4586
4617
*/
4587
Online.waypointsAroundField = function (start, end, field, clearance)
4618
Online.smoothParam = function (t, v0, v1)
4619
{
4620
if (t < 0)
4621
{ return 0; }
4622
if (t > 1)
4623
{ return 1; }
4624
if (v0 == null)
4625
{ v0 = 1; }
4626
if (v1 == null)
4627
{ v1 = 1; }
4628
var b = 3 - 2 * v0 - v1;
4629
var a = v0 + v1 - 2;
4630
return ((a * t + b) * t + v0) * t;
4631
};
4632
4633
/**
4634
* A simple up-and-over cubic, used when there is no field to route
4635
* around (enemy→enemy) or both ends already sit above the apex.
4636
*/
4637
Online._singleCubic = function (start, end, apexY, opts)
4638
{
4639
opts = opts || {};
4640
var rise = Math.max(40, Math.abs(start.y - apexY) * 0.9);
4641
if (opts.startSpeedPx)
4642
{ rise = Math.max(rise, opts.startSpeedPx); }
4643
var fall = Math.max(40, Math.abs(end.y - apexY) * 0.9);
4644
if (opts.endSpeedPx)
4645
{ fall = Math.max(40, opts.endSpeedPx); }
4646
var p1 = { x: start.x, y: Math.min(start.y - rise, apexY) };
4647
var p2 = { x: end.x, y: Math.min(end.y - fall, apexY) };
4648
return { p0: start, p1: p1, p2: p2, p3: end, apexY: apexY };
4649
};
4650
4651
/**
4652
* Smooth C¹ path: rise up (launch column or outside), cruise above
4653
* the field, dive into the landing column (t1134 / t1135). Joints
4654
* are quarter-turn cubics with matching tangents, so there are no
4655
* corners and no speed jerks. The curve may use the launch and
4656
* landing corridors but does not cut across the field interior.
4657
*/
4658
Online.makeAroundCurve = function (start, end, field, opts)
4588
4659
{
4589
if (!start || !end)
4590
{ return [start || { x: 0, y: 0 }, end || { x: 0, y: 0 }]; }
4660
opts = opts || {};
4661
if (!start)
4662
{ start = { x: 0, y: 0 }; }
4663
if (!end)
4664
{ end = { x: 0, y: 0 }; }
4665
var clearance = opts.clearance || 80;
4591
4666
if (!field)
4592
{ return [start, end]; }
4593
clearance = clearance || 64;
4667
{
4668
var looseApex = Math.min(start.y, end.y) - Math.max(40, clearance * 0.5);
4669
if (looseApex < 8)
4670
{ looseApex = Math.min(start.y, end.y) - 24; }
4671
return this._singleCubic(start, end, looseApex, opts);
4672
}
4594
4673
var top = field.top;
4595
4674
var left = field.left;
4596
4675
var right = field.right;
4597
var pad = 10;
4598
var apexY = Math.min(start.y, end.y, top) - clearance;
4676
var apexY = top - clearance;
4599
4677
if (apexY < 8)
4600
4678
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }
4601
4679
4602
if (start.y <= top + 6 && end.y <= top + 6)
4603
{ return [start, end]; }
4680
if (start.y <= apexY + 8 && end.y <= apexY + 8)
4681
{ return this._singleCubic(start, end, apexY, opts); }
4604
4682
4605
var w1x = start.x;
4606
var w2x = end.x;
4607
if (start.x < left)
4608
{ w1x = Math.min(start.x, left - pad); }
4609
else if (start.x > right)
4610
{ w1x = Math.max(start.x, right + pad); }
4611
if (end.x < left)
4612
{ w2x = Math.min(end.x, left - pad); }
4613
else if (end.x > right)
4614
{ w2x = Math.max(end.x, right + pad); }
4683
var pad = 14;
4684
var dir = end.x >= start.x ? 1 : -1;
4685
var span = Math.abs(end.x - start.x);
4686
var horiz = Math.max(28, Math.min(80, span * 0.15 + 8));
4687
function outsideX (x)
4688
{
4689
if (x < left + 8)
4690
{ return Math.min(x, left - pad); }
4691
if (x > right - 8)
4692
{ return Math.max(x, right + pad); }
4693
return x;
4694
}
4695
var riseX = outsideX(start.x);
4696
var diveX = outsideX(end.x);
4697
var segments = [];
4615
4698
4616
return [
4617
start,
4618
{ x: w1x, y: apexY },
4619
{ x: w2x, y: apexY },
4620
end
4621
];
4699
// Rise ends already turned toward the cruise, at apex.
4700
var riseEnd = { x: riseX + dir * horiz, y: apexY };
4701
if (start.y > apexY + 4)
4702
{
4703
var p1 = { x: start.x, y: apexY };
4704
var p2 = { x: riseX, y: apexY };
4705
segments.push({ p0: start, p1: p1, p2: p2, p3: riseEnd });
4706
}
4707
else
4708
{ riseEnd = { x: start.x, y: Math.min(start.y, apexY) }; }
4709
4710
// Cruise stays on the apex line (convex hull is above the field).
4711
var diveStart = { x: diveX - dir * horiz, y: apexY };
4712
if (Math.abs(riseEnd.x - diveStart.x) > 4 || Math.abs(riseEnd.y - diveStart.y) > 4)
4713
{
4714
// Keep the cruise direction consistent; if the two joints
4715
// would cross, just connect them directly.
4716
var cdir = diveStart.x >= riseEnd.x ? 1 : -1;
4717
var c1 = { x: riseEnd.x + cdir * horiz, y: riseEnd.y };
4718
if (c1.y > apexY)
4719
{ c1.y = apexY; }
4720
var c2 = { x: diveStart.x - cdir * horiz, y: diveStart.y };
4721
segments.push({ p0: { x: riseEnd.x, y: riseEnd.y }, p1: c1, p2: c2, p3: diveStart });
4722
}
4723
4724
if (end.y > apexY + 4 || Math.abs(end.x - (diveStart.x + dir * horiz)) > 2)
4725
{
4726
var u0 = (Math.abs(riseEnd.x - diveStart.x) > 4 || segments.length === 0)
4727
? diveStart
4728
: riseEnd;
4729
if (segments.length && segments[segments.length - 1].p3.x === u0.x
4730
&& segments[segments.length - 1].p3.y === u0.y)
4731
{ /* already joined */ }
4732
else if (segments.length === 0)
4733
{ u0 = riseEnd; }
4734
var u1 = { x: u0.x + dir * horiz, y: u0.y };
4735
var fall = Math.max(24, Math.abs(end.y - apexY) * 0.45);
4736
if (opts.endSpeedPx)
4737
{
4738
// |P3-P2| so arrival ≈ fallSpeed after equal-param scaling.
4739
// velocity = 3*|P3-P2|*n*v1/duration; endSpeedPx is
4740
// (cells*px*duration)/3, so |P3-P2| = endSpeedPx/(n*v1).
4741
var nEst = Math.max(1, segments.length + 1);
4742
fall = Math.max(20, opts.endSpeedPx / (nEst * 0.85));
4743
}
4744
var u2 = { x: end.x, y: end.y - fall };
4745
// P2 may sit between the apex and the end (slower arrival);
4746
// only clamp if it would pass the end or fly far past the apex.
4747
if (u2.y < apexY - 240)
4748
{ u2.y = apexY - 240; }
4749
if (u2.y > end.y - 8)
4750
{ u2.y = end.y - 8; }
4751
segments.push({ p0: u0, p1: u1, p2: u2, p3: end });
4752
}
4753
4754
if (segments.length === 0)
4755
{ return this._singleCubic(start, end, apexY, opts); }
4756
if (segments.length === 1 && !segments[0].p0)
4757
{ return this._singleCubic(start, end, apexY, opts); }
4758
4759
return { segments: segments, apexY: apexY, p0: start, p3: end };
4622
4760
};
4623
4761
4624
/**
4625
* Point at parameter u ∈ [0, 1] along a polyline, with a small upward
4626
* bulge on each segment so the path reads as a "boogje".
4627
*/
4628
Online.pointOnPath = function (points, u)
4762
Online._measureCurve = function (curve)
4629
4763
{
4630
u = u < 0 ? 0 : (u > 1 ? 1 : u);
4631
if (!points || !points.length)
4632
{ return { x: 0, y: 0 }; }
4633
if (points.length === 1)
4634
{ return { x: points[0].x, y: points[0].y }; }
4764
if (!curve.segments)
4765
{ return curve; }
4635
4766
var lens = [];
4636
4767
var total = 0;
4637
for (var i = 1; i < points.length; i++)
4768
for (var i = 0; i < curve.segments.length; i++)
4638
4769
{
4639
var dx = points[i].x - points[i - 1].x;
4640
var dy = points[i].y - points[i - 1].y;
4641
var L = Math.sqrt(dx * dx + dy * dy);
4642
if (L < 1)
4643
{ L = 1; }
4770
var L = this._segLen(curve.segments[i]);
4644
4771
lens.push(L);
4645
4772
total += L;
4646
4773
}
4647
var dist = u * total;
4648
var acc = 0;
4649
for (var i = 0; i < lens.length; i++)
4774
curve.lens = lens;
4775
curve.totalLen = Math.max(total, 1);
4776
return curve;
4777
};
4778
4779
Online._segLen = function (seg, steps)
4780
{
4781
steps = steps || 10;
4782
var len = 0;
4783
var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
4784
for (var i = 1; i <= steps; i++)
4650
4785
{
4651
if (acc + lens[i] >= dist || i === lens.length - 1)
4652
{
4653
var t = (dist - acc) / lens[i];
4654
if (t < 0)
4655
{ t = 0; }
4656
if (t > 1)
4657
{ t = 1; }
4658
var a = points[i];
4659
var b = points[i + 1];
4660
var bump = 4 * 16 * t * (1 - t);
4661
return {
4662
x: a.x + (b.x - a.x) * t,
4663
y: a.y + (b.y - a.y) * t - bump
4664
};
4665
}
4666
acc += lens[i];
4786
var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
4787
var dx = p.x - prev.x;
4788
var dy = p.y - prev.y;
4789
len += Math.sqrt(dx * dx + dy * dy);
4790
prev = p;
4791
}
4792
return Math.max(len, 1);
4793
};
4794
4795
/**
4796
* Equal-parameter split across segments so matching local C'(t)
4797
* at joints also matches dP/du (no speed jerk).
4798
*/
4799
Online._curveSegmentAt = function (curve, u)
4800
{
4801
if (!curve)
4802
{ return null; }
4803
if (!curve.segments)
4804
{
4805
return { seg: curve, t: u < 0 ? 0 : (u > 1 ? 1 : u), scale: 1 };
4667
4806
}
4668
var last = points[points.length - 1];
4669
return { x: last.x, y: last.y };
4807
var segs = curve.segments;
4808
var n = segs.length;
4809
if (u <= 0)
4810
{ return { seg: segs[0], t: 0, scale: n }; }
4811
if (u >= 1)
4812
{ return { seg: segs[n - 1], t: 1, scale: n }; }
4813
var at = u * n;
4814
var i = Math.floor(at);
4815
if (i >= n)
4816
{ i = n - 1; }
4817
var t = at - i;
4818
return { seg: segs[i], t: t, scale: n };
4819
};
4820
4821
/** Point on a (possibly multi-segment C¹) curve at u ∈ [0, 1]. */
4822
Online.curvePoint = function (curve, u)
4823
{
4824
var at = this._curveSegmentAt(curve, u);
4825
if (!at)
4826
{ return { x: 0, y: 0 }; }
4827
var s = at.seg;
4828
if (s && s.p1)
4829
{ return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at.t); }
4830
if (s && s.p0)
4831
{ return { x: s.p0.x, y: s.p0.y }; }
4832
return { x: 0, y: 0 };
4833
};
4834
4835
/** dP/du of the curve (C¹ across joints). */
4836
Online.curveDeriv = function (curve, u)
4837
{
4838
var at = this._curveSegmentAt(curve, u);
4839
if (!at || !at.seg || !at.seg.p1)
4840
{ return { x: 0, y: 0 }; }
4841
var s = at.seg;
4842
var d = this.cubicBezierDeriv(s.p0, s.p1, s.p2, s.p3, at.t);
4843
return { x: d.x * at.scale, y: d.y * at.scale };
4670
4844
};
4671
4845
4672
/** Sample a player↔enemy path; used by tests and the ticker. */
4846
/**
4847
* Sample the smooth around-field curve at u ∈ [0, 1] (t1134).
4848
* `clearance` may be a number or an options object.
4849
*/
4673
4850
Online.aroundFieldPoint = function (start, end, u, field, clearance)
4674
4851
{
4675
var pts = this.waypointsAroundField(start, end, field, clearance);
4676
if (pts.length === 2)
4852
var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
4853
var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
4854
return this.curvePoint(curve, u);
4855
};
4856
4857
/** Guide points (start, joints, end) for older tests. */
4858
Online.waypointsAroundField = function (start, end, field, clearance)
4859
{
4860
var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 64 });
4861
if (c.segments && c.segments.length)
4862
{
4863
var pts = [{ x: c.segments[0].p0.x, y: c.segments[0].p0.y }];
4864
for (var i = 0; i < c.segments.length; i++)
4865
{ pts.push({ x: c.segments[i].p3.x, y: c.segments[i].p3.y }); }
4866
return pts;
4867
}
4868
return [c.p0, c.p1, c.p2, c.p3];
4869
};
4870
4871
Online.pointOnPath = function (points, u)
4872
{
4873
// Legacy polyline; new flights use cubicBezier.
4874
u = u < 0 ? 0 : (u > 1 ? 1 : u);
4875
if (!points || !points.length)
4876
{ return { x: 0, y: 0 }; }
4877
if (points.length === 4 && points[0] && points[3])
4878
{ return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
4879
if (points.length === 1)
4880
{ return { x: points[0].x, y: points[0].y }; }
4881
var n = points.length - 1;
4882
var at = u * n;
4883
var i = Math.floor(at);
4884
if (i >= n)
4885
{ i = n - 1; }
4886
var t = at - i;
4887
var a = points[i];
4888
var b = points[i + 1];
4889
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
4890
};
4891
4892
/** Viewport centre of a field cell (y=0 is the bottom row). */
4893
Online.cellViewport = function (col, y, rect)
4894
{
4895
if (!rect)
4677
4896
{
4678
var h = this.arcHeight(start, end);
4679
return this.arcPoint(start, end, u, h);
4897
var field = this.playerFieldRect();
4898
if (!field)
4899
{ return { x: 0, y: 0 }; }
4900
rect = field;
4680
4901
}
4681
return this.pointOnPath(pts, u);
4902
var w = rect.width != null ? rect.width : (rect.right - rect.left);
4903
var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
4904
return {
4905
x: rect.left + ((col + 0.5) / 10) * w,
4906
y: rect.top + (1 - (y + 0.5) / 13) * h
4907
};
4908
};
4909
4910
/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
4911
Online.fieldEntry = function (col)
4912
{
4913
return this.cellViewport(col == null ? 4.5 : col, 13);
4914
};
4915
4916
Online.miniCellViewport = function (playerId, col, y)
4917
{
4918
var el = this.miniElement(playerId);
4919
var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
4920
var box = canvas || el;
4921
if (!box || !box.getBoundingClientRect)
4922
{ return { x: window.innerWidth / 2, y: 48 }; }
4923
return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
4924
};
4925
4926
Online._fallSpeedPx = function (field, duration)
4927
{
4928
var px = 40;
4929
if (field && field.height)
4930
{ px = field.height / 13; }
4931
else if (typeof app !== 'undefined' && app.tile)
4932
{ px = app.tile; }
4933
var cells = 13 / 3;
4934
if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
4935
{ cells = app.planet.fallSpeed; }
4936
duration = duration || this.FLIGHT_DURATION;
4937
// Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
4938
return (cells * px * duration) / 3;
4682
4939
};
4683
4940
4684
4941
Online.rememberLandCol = function (id, col)
@@ -4746,17 +5003,17 @@ Online._miniAnchor = function (playerId, dir)
4746
5003
4747
5004
Online._fieldTop = function (col)
4748
5005
{
4749
return this._flightStart(col);
5006
return this.fieldEntry(col);
4750
5007
};
4751
5008
4752
5009
/**
4753
5010
* Animate shot results. `locals` is a map of client_id → {col, y, color,
4754
5011
* startX, startY, from_id} in viewport pixels.
4755
5012
*
4756
* Visual-only (t1125): a parabolic arc whose scale goes from mini-cell
4757
* to full tile (or the reverse). Enemy-to-enemy arcs stay small and
4758
* are drawn behind the player's field. Delivery timing is unchanged;
4759
* a late-seen flight starts mid-arc via `age`.
5013
* Visual-only: a smooth cubic that leaves the real cell, arcs around
5014
* the field, and dives into the landing column at the spawn pose
5015
* (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
5016
* behind the player's field. A late-seen flight starts mid-arc via `age`.
4760
5017
*/
4761
5018
Online.spawnFlights = function (results, locals)
4762
5019
{
@@ -4767,6 +5024,8 @@ Online.spawnFlights = function (results, locals)
4767
5024
{ return; }
4768
5025
if (!this._flightSeen)
4769
5026
{ this._flightSeen = Object.create(null); }
5027
if (!this._previewIds)
5028
{ this._previewIds = Object.create(null); }
4770
5029
var now = performance.now();
4771
5030
var full = this._fullTileSize();
4772
5031
for (var i = 0; i < results.length; i++)
@@ -4774,7 +5033,18 @@ Online.spawnFlights = function (results, locals)
4774
5033
var r = results[i];
4775
5034
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
4776
5035
if (this._flightSeen[sid])
4777
{ continue; }
5036
{
5037
if (this._previewIds[sid])
5038
{
5039
var existing = this._findFlight(sid);
5040
if (existing)
5041
{
5042
var meta0 = locals[r.client_id] || locals[sid] || {};
5043
this.retargetFlight(existing, r, meta0, now);
5044
}
5045
}
5046
continue;
5047
}
4778
5048
this._flightSeen[sid] = now;
4779
5049
4780
5050
var meta = locals[r.client_id] || locals[sid] || {};
@@ -4801,11 +5071,15 @@ Online.spawnFlights = function (results, locals)
4801
5071
{ this.rememberLandCol(r.client_id, landCol); }
4802
5072
}
4803
5073
5074
var startCol = meta.col != null ? meta.col : r.col;
5075
var startY = meta.y != null ? meta.y : r.y;
4804
5076
var start;
4805
5077
if (meta.startX != null && isFinite(meta.startX))
4806
5078
{ start = { x: meta.startX, y: meta.startY }; }
4807
5079
else if (kind === 'player-to-enemy' || kind === 'player-miss')
4808
{ start = this._flightStart(meta.col != null ? meta.col : r.col); }
5080
{ start = this._flightStart(startCol, startY); }
5081
else if (startCol != null || startY != null)
5082
{ start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 12); }
4809
5083
else
4810
5084
{ start = this._miniAnchor(fromId, 'out'); }
4811
5085
@@ -4813,7 +5087,7 @@ Online.spawnFlights = function (results, locals)
4813
5087
if (miss)
4814
5088
{ end = this._missEnd(start, kind === 'enemy-miss'); }
4815
5089
else if (kind === 'enemy-to-player')
4816
{ end = this._fieldTop(landCol != null ? landCol : 4.5); }
5090
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }
4817
5091
else
4818
5092
{ end = this._targetEnd(targetId, start, landCol); }
4819
5093
@@ -4874,7 +5148,14 @@ Online.spawnFlights = function (results, locals)
4874
5148
: this.arcHeight(start, end);
4875
5149
var field = this.playerFieldRect();
4876
5150
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
4877
var waypoints = around ? this.waypointsAroundField(start, end, field, height * 0.45) : null;
5151
var clearance = Math.max(64, height * 0.45);
5152
var endSpeed = this._fallSpeedPx(field, duration / 1000);
5153
var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
5154
clearance: clearance,
5155
startSpeedPx: endSpeed,
5156
endSpeedPx: endSpeed,
5157
duration: duration / 1000
5158
});
4878
5159
this._flights.push({
4879
5160
el: el,
4880
5161
start: start,
@@ -4883,16 +5164,16 @@ Online.spawnFlights = function (results, locals)
4883
5164
height: height,
4884
5165
t0: t0,
4885
5166
duration: duration,
4886
spin: (Math.random() * 2 - 1) * 720,
5167
spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
4887
5168
miss: miss,
4888
5169
kind: kind,
4889
5170
startScale: startScale,
4890
5171
endScale: endScale,
4891
angle: Math.random() * 360,
5172
angle: 0,
4892
5173
id: sid,
4893
5174
landCol: landCol,
4894
5175
field: field,
4895
waypoints: waypoints,
5176
curve: curve,
4896
5177
color: flightColor
4897
5178
});
4898
5179
}
@@ -4909,30 +5190,17 @@ Online.rememberFlightLocal = function (shot, startX, startY)
4909
5190
color: shot.color,
4910
5191
startX: startX,
4911
5192
startY: startY,
4912
from_id: shot.from_id
5193
from_id: shot.from_id,
5194
land_col: shot.land_col,
5195
vy: shot.vy
4913
5196
};
4914
5197
};
4915
5198
4916
Online._flightStart = function (col)
5199
Online._flightStart = function (col, y)
4917
5200
{
4918
var appRef = typeof app !== 'undefined' ? app : null;
4919
if (appRef && appRef.scene && appRef.scene.canvas)
4920
{
4921
var canvas = appRef.scene.canvas;
4922
var rect = canvas.getBoundingClientRect();
4923
var c = col == null ? 4.5 : col;
4924
return {
4925
x: rect.left + (c + 0.5) * (rect.width / 10),
4926
y: rect.top + 4
4927
};
4928
}
4929
var field = document.querySelector('canvas');
4930
if (field)
4931
{
4932
var rect = field.getBoundingClientRect();
4933
return { x: rect.left + rect.width / 2, y: rect.top };
4934
}
4935
return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
5201
if (y == null || !isFinite(y))
5202
{ y = 12; }
5203
return this.cellViewport(col == null ? 4.5 : col, y);
4936
5204
};
4937
5205
4938
5206
Online._targetEnd = function (targetId, start, col)
@@ -4940,12 +5208,8 @@ Online._targetEnd = function (targetId, start, col)
4940
5208
var el = targetId && this.miniElement(targetId);
4941
5209
if (el)
4942
5210
{
4943
var canvas = el.querySelector('canvas') || el;
4944
var r = canvas.getBoundingClientRect();
4945
var x = r.left + r.width / 2;
4946
if (col != null && isFinite(col))
4947
{ x = r.left + ((col + 0.5) / 10) * r.width; }
4948
return { x: x, y: r.top + 4 };
5211
// Slightly inside the mini, in the landing column (t1135).
5212
return this.miniCellViewport(targetId, col, 12);
4949
5213
}
4950
5214
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
4951
5215
};
@@ -4980,6 +5244,251 @@ Online._hitCtrl = function (start, end)
4980
5244
};
4981
5245
};
4982
5246
5247
Online._findFlight = function (sid)
5248
{
5249
sid = String(sid);
5250
if (!this._flights)
5251
{ return null; }
5252
for (var i = 0; i < this._flights.length; i++)
5253
{
5254
if (String(this._flights[i].id) === sid)
5255
{ return this._flights[i]; }
5256
}
5257
return null;
5258
};
5259
5260
/**
5261
* Early visual takeover: a flying rocket near the top of a field
5262
* becomes a flight sprite at its exact cell, so it is seen flying
5263
* *out* rather than popping in above the canvas (t1134). When the
5264
* shot is later dispatched, `retargetFlight` picks up from the
5265
* current pose and aims at the real landing column.
5266
*/
5267
Online.previewExit = function (info)
5268
{
5269
if (!info || info.id == null)
5270
{ return; }
5271
var sid = String(info.id);
5272
if (!this._flights)
5273
{ this._flights = []; }
5274
if (!this._flightSeen)
5275
{ this._flightSeen = Object.create(null); }
5276
if (!this._previewIds)
5277
{ this._previewIds = Object.create(null); }
5278
if (this._previewIds[sid] || this._flightSeen[sid])
5279
{ return; }
5280
var front = document.getElementById('flights');
5281
if (!front || !info.start)
5282
{ return; }
5283
var start = info.start;
5284
var field = this.playerFieldRect();
5285
var clearance = 80;
5286
if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
5287
{ clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
5288
var apexY = (field ? field.top : start.y) - clearance;
5289
if (apexY < 8)
5290
{ apexY = Math.max(8, start.y - 80); }
5291
var end = { x: start.x, y: apexY };
5292
var duration = this.FLIGHT_DURATION * 1000;
5293
var full = this._fullTileSize();
5294
var el = document.createElement('img');
5295
el.src = colorSpriteUrl(info.color);
5296
el.alt = '';
5297
el.className = 'flight';
5298
el.style.width = full + 'px';
5299
el.style.height = full + 'px';
5300
front.appendChild(el);
5301
var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
5302
var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
5303
clearance: clearance,
5304
startSpeedPx: endSpeed,
5305
endSpeedPx: endSpeed
5306
});
5307
var now = performance.now();
5308
var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
5309
if (mini < 0.12)
5310
{ mini = 0.2; }
5311
this._flights.push({
5312
el: el,
5313
start: start,
5314
end: end,
5315
ctrl: null,
5316
height: clearance,
5317
t0: now,
5318
duration: duration,
5319
spin: (Math.random() * 2 - 1) * 90,
5320
miss: false,
5321
kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
5322
startScale: mini,
5323
endScale: mini,
5324
angle: 0,
5325
id: sid,
5326
landCol: null,
5327
field: field,
5328
curve: curve,
5329
preview: true,
5330
color: info.color,
5331
from_id: info.from_id || null
5332
});
5333
this._previewIds[sid] = true;
5334
this._flightSeen[sid] = now;
5335
};
5336
5337
/** True while a field sprite should stay hidden — the flight is its visual. */
5338
Online.hasExitVisual = function (id)
5339
{
5340
if (id == null)
5341
{ return false; }
5342
var sid = String(id);
5343
if (this._previewIds && this._previewIds[sid])
5344
{ return true; }
5345
var f = this._findFlight(sid);
5346
if (!f || f.miss)
5347
{ return false; }
5348
var raw = (performance.now() - f.t0) / f.duration;
5349
return raw < 0.4;
5350
};
5351
5352
/**
5353
* Once the shot is scored, pick up the preview at its current pose
5354
* and fly the rest of the way to the real end (no jump).
5355
*/
5356
Online.retargetFlight = function (f, r, meta, now)
5357
{
5358
now = now || performance.now();
5359
meta = meta || {};
5360
var raw = (now - f.t0) / f.duration;
5361
if (raw < 0)
5362
{ raw = 0; }
5363
if (raw > 0.95)
5364
{ raw = 0.95; }
5365
var u = this.smoothParam(raw, 0.9, 0.9);
5366
var pt = f.curve
5367
? this.curvePoint(f.curve, u)
5368
: { x: f.start.x, y: f.start.y };
5369
var curScale = f.startScale + (f.endScale - f.startScale) * u;
5370
5371
var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
5372
var targetId = r.target_id != null ? r.target_id : r.to_user;
5373
var miss = !!r.miss;
5374
var kind = this.flightKind(fromId, targetId, miss);
5375
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
5376
5377
var landCol = null;
5378
if (r.land_col != null && isFinite(r.land_col))
5379
{ landCol = r.land_col | 0; }
5380
else if (meta.land_col != null && isFinite(meta.land_col))
5381
{ landCol = meta.land_col | 0; }
5382
else if (f.landCol != null)
5383
{ landCol = f.landCol; }
5384
if (landCol != null)
5385
{ this.rememberLandCol(String(f.id), landCol); }
5386
5387
var end;
5388
if (miss)
5389
{ end = this._missEnd(pt, kind === 'enemy-miss'); }
5390
else if (kind === 'enemy-to-player')
5391
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }
5392
else
5393
{ end = this._targetEnd(targetId, pt, landCol); }
5394
5395
var flightColor = miss
5396
? (r.color != null ? r.color : meta.color)
5397
: -1;
5398
if (f.el && flightColor !== f.color)
5399
{ f.el.src = colorSpriteUrl(flightColor); }
5400
5401
var full = this._fullTileSize();
5402
var mini = this._miniCellSize(fromId || targetId) / full;
5403
if (mini < 0.12)
5404
{ mini = 0.2; }
5405
var endScale;
5406
if (kind === 'player-to-enemy')
5407
{ endScale = mini; }
5408
else if (kind === 'enemy-to-player')
5409
{ endScale = 1; }
5410
else if (kind === 'enemy-to-enemy')
5411
{ endScale = mini; }
5412
else
5413
{ endScale = 0; }
5414
5415
var field = this.playerFieldRect();
5416
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
5417
var height = miss
5418
? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
5419
: this.arcHeight(pt, end);
5420
var clearance = Math.max(64, height * 0.45);
5421
var endSpeed = this._fallSpeedPx(field, duration / 1000);
5422
var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
5423
clearance: clearance,
5424
startSpeedPx: endSpeed,
5425
endSpeedPx: endSpeed
5426
});
5427
5428
f.start = pt;
5429
f.end = end;
5430
f.t0 = now;
5431
f.duration = duration;
5432
f.curve = curve;
5433
f.ctrl = miss ? this._missCtrl(pt, end) : null;
5434
f.height = height;
5435
f.miss = miss;
5436
f.kind = kind;
5437
f.startScale = curScale;
5438
f.endScale = endScale;
5439
f.landCol = landCol;
5440
f.field = field;
5441
f.preview = false;
5442
f.color = flightColor;
5443
f.from_id = fromId;
5444
if (this._previewIds)
5445
{ delete this._previewIds[String(f.id)]; }
5446
5447
if (kind === 'enemy-to-enemy' && f.el)
5448
{
5449
var back = document.getElementById('flights-back');
5450
if (back && f.el.parentNode !== back)
5451
{
5452
f.el.className = 'flight flight-behind';
5453
back.appendChild(f.el);
5454
}
5455
}
5456
};
5457
5458
/** Point and (optional) derivative of a flight at parameter u. */
5459
Online.flightPointAt = function (f, u)
5460
{
5461
if (!f)
5462
{ return { x: 0, y: 0 }; }
5463
if (f.curve)
5464
{ return this.curvePoint(f.curve, u); }
5465
if (f.miss && f.ctrl)
5466
{
5467
var e = u;
5468
var mt = 1 - e;
5469
return {
5470
x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
5471
y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
5472
};
5473
}
5474
return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
5475
};
5476
5477
Online.pointAllowedOnArc = function (p, field, start, end, slop)
5478
{
5479
if (!this.pointInFieldInterior(p.x, p.y, field, slop))
5480
{ return true; }
5481
if (!field)
5482
{ return true; }
5483
var w = (field.right - field.left) / 10;
5484
var corridor = w * 0.7;
5485
if (start && Math.abs(p.x - start.x) <= corridor)
5486
{ return true; }
5487
if (end && Math.abs(p.x - end.x) <= corridor)
5488
{ return true; }
5489
return false;
5490
};
5491
4983
5492
Online.tickFlights = function (now)
4984
5493
{
4985
5494
now = now || performance.now();
@@ -4992,11 +5501,14 @@ Online.tickFlights = function (now)
4992
5501
{
4993
5502
if (f.el && f.el.parentNode)
4994
5503
{ f.el.parentNode.removeChild(f.el); }
5504
if (this._previewIds)
5505
{ delete this._previewIds[String(f.id)]; }
4995
5506
continue;
4996
5507
}
4997
5508
if (raw < 0)
4998
5509
{ raw = 0; }
4999
var u = this.easeInOutCubic(raw);
5510
// Non-zero endpoint speed so the handoff matches fallSpeed (t1135).
5511
var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, 0.85, 0.85);
5000
5512
var x, y;
5001
5513
if (f.miss && f.ctrl)
5002
5514
{
@@ -5005,21 +5517,15 @@ Online.tickFlights = function (now)
5005
5517
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
5006
5518
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
5007
5519
}
5008
else if (f.waypoints && f.waypoints.length > 2)
5009
{
5010
var pt = this.pointOnPath(f.waypoints, u);
5011
x = pt.x;
5012
y = pt.y;
5013
}
5014
else if (f.waypoints && f.field)
5520
else if (f.curve)
5015
5521
{
5016
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
5522
var pt = this.curvePoint(f.curve, u);
5017
5523
x = pt.x;
5018
5524
y = pt.y;
5019
5525
}
5020
5526
else
5021
5527
{
5022
var pt = this.arcPoint(f.start, f.end, u, f.height || 80);
5528
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
5023
5529
x = pt.x;
5024
5530
y = pt.y;
5025
5531
}
@@ -5060,6 +5566,7 @@ Online.clearFlights = function ()
5060
5566
this._flightLocals = {};
5061
5567
this._flightSeen = Object.create(null);
5062
5568
this._pendingLandCol = Object.create(null);
5569
this._previewIds = Object.create(null);
5063
5570
};
5064
5571
5065
5572
if (typeof globalThis !== 'undefined')
@@ -6187,6 +6694,11 @@ function syncSprites (dt)
6187
6694
applyBlockVisual(obj, block);
6188
6695
obj.renderer.visible = true;
6189
6696
obj.renderer.alpha = 1;
6697
if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))
6698
{
6699
obj.renderer.visible = false;
6700
obj.renderer.alpha = 0;
6701
}
6190
6702
6191
6703
if (block.flame)
6192
6704
{
@@ -6213,6 +6725,10 @@ function syncSprites (dt)
6213
6725
}
6214
6726
else if (app.flames[block.id])
6215
6727
{ app.flames[block.id].renderer.visible = false; }
6728
if (block.flame && app.flames[block.id]
6729
&& typeof Online !== 'undefined' && Online.hasExitVisual
6730
&& Online.hasExitVisual(block.id))
6731
{ app.flames[block.id].renderer.visible = false; }
6216
6732
}
6217
6733
6218
6734
var ids = Object.keys(app.sprites);
@@ -6450,6 +6966,7 @@ function tickView (dt)
6450
6966
placeTile(app.cells[i], col, row);
6451
6967
}
6452
6968
6969
previewOutgoingFlights();
6453
6970
app.core.tick(dt);
6454
6971
if (app.offline && app.battle)
6455
6972
{ tickOffline(dt); }
@@ -6970,7 +7487,7 @@ function tickOnline (dt)
6970
7487
for (var i = 0; i < shots.length; i++)
6971
7488
{
6972
7489
var s = shots[i];
6973
var start = fieldToViewport(s.col, s.y + 1);
7490
var start = fieldToViewport(s.col, s.y);
6974
7491
Online.rememberFlightLocal(s, start.x, start.y);
6975
7492
}
6976
7493
Online.queueShots(shots);
@@ -7048,7 +7565,9 @@ function tickOffline (dt)
7048
7565
var s = list[i];
7049
7566
var start;
7050
7567
if (s.from_id === 'player')
7051
{ start = fieldToViewport(s.col, s.y + 1); }
7568
{ start = fieldToViewport(s.col, s.y); }
7569
else if (typeof Online !== 'undefined' && Online.miniCellViewport)
7570
{ start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
7052
7571
else
7053
7572
{ start = miniViewportCenter(s.from_id); }
7054
7573
locals[s.client_id] = {
@@ -7292,6 +7811,58 @@ function updateColumnWarn (dt)
7292
7811
}
7293
7812
}
7294
7813
7814
/**
7815
* Take over a rocket that is about to leave the top of a field (the
7816
* player's, or a bot's) so the flight starts at the real cell and
7817
* continues its upward motion (t1134). Shared by offline and online.
7818
*/
7819
function previewOutgoingFlights ()
7820
{
7821
if (typeof Online === 'undefined' || !Online.previewExit)
7822
{ return; }
7823
if (app.core)
7824
{ previewCoreExits(app.core, null); }
7825
if (app.offline && app.battle && app.battle.bots)
7826
{
7827
var bots = app.battle.bots;
7828
for (var i = 0; i < bots.length; i++)
7829
{
7830
var bot = bots[i];
7831
if (bot && bot.core && !bot.eliminated)
7832
{ previewCoreExits(bot.core, bot.id); }
7833
}
7834
}
7835
}
7836
7837
function previewCoreExits (core, fromId)
7838
{
7839
if (!core || !core.blocks)
7840
{ return; }
7841
var blocks = core.blocks;
7842
for (var i = 0; i < blocks.length; i++)
7843
{
7844
var b = blocks[i];
7845
if (b.y < 11.6)
7846
{ continue; }
7847
if (!(b.vy > 0))
7848
{ continue; }
7849
var start = fromId
7850
? (Online.miniCellViewport
7851
? Online.miniCellViewport(fromId, b.col, b.y)
7852
: miniViewportCenter(fromId))
7853
: fieldToViewport(b.col, b.y);
7854
Online.previewExit({
7855
id: b.id,
7856
col: b.col,
7857
y: b.y,
7858
vy: b.vy,
7859
color: b.color,
7860
start: start,
7861
from_id: fromId || null
7862
});
7863
}
7864
}
7865
7295
7866
function fieldToViewport (col, fieldY)
7296
7867
{
7297
7868
var canvas = app.scene && app.scene.canvas;
@@ -7299,7 +7870,8 @@ function fieldToViewport (col, fieldY)
7299
7870
{ return { x: window.innerWidth / 2, y: 40 }; }
7300
7871
var rect = canvas.getBoundingClientRect();
7301
7872
var x = rect.left + ((col + 0.5) / 10) * rect.width;
7302
var y = rect.top + (1 - (fieldY / 13)) * rect.height;
7873
// Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
7874
var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
7303
7875
return { x: x, y: y };
7304
7876
}
7305
7877
@@ -2695,7 +2695,8 @@ GameCore.prototype.cullOffTop = function ()2695
id: block.id,2695
id: block.id,2696
color: block.color,2696
color: block.color,2697
col: block.col,2697
col: block.col,2698
y: block.y2698
y: block.y,2699
vy: block.vy2699
});2700
});2700
this.score += 1;2701
this.score += 1;2701
this.removeBlock(block);2702
this.removeBlock(block);@@ -4567,7 +4568,7 @@ Online.playerFieldRect = function ()4567
4568
4568
/**4569
/**4569
* True if (x, y) is inside the field's interior. The top edge (a few4570
* True if (x, y) is inside the field's interior. The top edge (a few4570
* pixels) is not interior: that is where arcs may land (t1128).4571
* pixels) is not interior: launch and landing may use that band.4571
*/4572
*/4572
Online.pointInFieldInterior = function (x, y, field, slop)4573
Online.pointInFieldInterior = function (x, y, field, slop)4573
{4574
{@@ -4578,107 +4579,363 @@ Online.pointInFieldInterior = function (x, y, field, slop)4578
&& y > field.top + slop && y < field.bottom - 0.5;4579
&& y > field.top + slop && y < field.bottom - 0.5;4579
};4580
};4580
4581
4582
/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */4583
Online.cubicBezier = function (p0, p1, p2, p3, t)4584
{4585
if (t < 0)4586
{ t = 0; }4587
if (t > 1)4588
{ t = 1; }4589
var u = 1 - t;4590
var a = u * u * u;4591
var b = 3 * u * u * t;4592
var c = 3 * u * t * t;4593
var d = t * t * t;4594
return {4595
x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,4596
y: a * p0.y + b * p1.y + c * p2.y + d * p3.y4597
};4598
};4599
4600
/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */4601
Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)4602
{4603
if (t < 0)4604
{ t = 0; }4605
if (t > 1)4606
{ t = 1; }4607
var u = 1 - t;4608
return {4609
x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),4610
y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)4611
};4612
};4613
4581
/**4614
/**4582
* Waypoints that route a player↔enemy arc around the field, never4615
* Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.4583
* through its interior: up the outside, across above the top edge,4616
* v0=v1=1 is linear (constant speed in t, no endpoint halt).4584
* then into the target (t1128). If both ends already sit at or above4585
* the top, a simple two-point path is enough.4586
*/4617
*/4587
Online.waypointsAroundField = function (start, end, field, clearance)4618
Online.smoothParam = function (t, v0, v1)4619
{4620
if (t < 0)4621
{ return 0; }4622
if (t > 1)4623
{ return 1; }4624
if (v0 == null)4625
{ v0 = 1; }4626
if (v1 == null)4627
{ v1 = 1; }4628
var b = 3 - 2 * v0 - v1;4629
var a = v0 + v1 - 2;4630
return ((a * t + b) * t + v0) * t;4631
};4632
4633
/**4634
* A simple up-and-over cubic, used when there is no field to route4635
* around (enemy→enemy) or both ends already sit above the apex.4636
*/4637
Online._singleCubic = function (start, end, apexY, opts)4638
{4639
opts = opts || {};4640
var rise = Math.max(40, Math.abs(start.y - apexY) * 0.9);4641
if (opts.startSpeedPx)4642
{ rise = Math.max(rise, opts.startSpeedPx); }4643
var fall = Math.max(40, Math.abs(end.y - apexY) * 0.9);4644
if (opts.endSpeedPx)4645
{ fall = Math.max(40, opts.endSpeedPx); }4646
var p1 = { x: start.x, y: Math.min(start.y - rise, apexY) };4647
var p2 = { x: end.x, y: Math.min(end.y - fall, apexY) };4648
return { p0: start, p1: p1, p2: p2, p3: end, apexY: apexY };4649
};4650
4651
/**4652
* Smooth C¹ path: rise up (launch column or outside), cruise above4653
* the field, dive into the landing column (t1134 / t1135). Joints4654
* are quarter-turn cubics with matching tangents, so there are no4655
* corners and no speed jerks. The curve may use the launch and4656
* landing corridors but does not cut across the field interior.4657
*/4658
Online.makeAroundCurve = function (start, end, field, opts)4588
{4659
{4589
if (!start || !end)4660
opts = opts || {};4590
{ return [start || { x: 0, y: 0 }, end || { x: 0, y: 0 }]; }4661
if (!start)4662
{ start = { x: 0, y: 0 }; }4663
if (!end)4664
{ end = { x: 0, y: 0 }; }4665
var clearance = opts.clearance || 80;4591
if (!field)4666
if (!field)4592
{ return [start, end]; }4667
{4593
clearance = clearance || 64;4668
var looseApex = Math.min(start.y, end.y) - Math.max(40, clearance * 0.5);4669
if (looseApex < 8)4670
{ looseApex = Math.min(start.y, end.y) - 24; }4671
return this._singleCubic(start, end, looseApex, opts);4672
}4594
var top = field.top;4673
var top = field.top;4595
var left = field.left;4674
var left = field.left;4596
var right = field.right;4675
var right = field.right;4597
var pad = 10;4676
var apexY = top - clearance;4598
var apexY = Math.min(start.y, end.y, top) - clearance;4599
if (apexY < 8)4677
if (apexY < 8)4600
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }4678
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }4601
4679
4602
if (start.y <= top + 6 && end.y <= top + 6)4680
if (start.y <= apexY + 8 && end.y <= apexY + 8)4603
{ return [start, end]; }4681
{ return this._singleCubic(start, end, apexY, opts); }4604
4682
4605
var w1x = start.x;4683
var pad = 14;4606
var w2x = end.x;4684
var dir = end.x >= start.x ? 1 : -1;4607
if (start.x < left)4685
var span = Math.abs(end.x - start.x);4608
{ w1x = Math.min(start.x, left - pad); }4686
var horiz = Math.max(28, Math.min(80, span * 0.15 + 8));4609
else if (start.x > right)4687
function outsideX (x)4610
{ w1x = Math.max(start.x, right + pad); }4688
{4611
if (end.x < left)4689
if (x < left + 8)4612
{ w2x = Math.min(end.x, left - pad); }4690
{ return Math.min(x, left - pad); }4613
else if (end.x > right)4691
if (x > right - 8)4614
{ w2x = Math.max(end.x, right + pad); }4692
{ return Math.max(x, right + pad); }4693
return x;4694
}4695
var riseX = outsideX(start.x);4696
var diveX = outsideX(end.x);4697
var segments = [];4615
4698
4616
return [4699
// Rise ends already turned toward the cruise, at apex.4617
start,4700
var riseEnd = { x: riseX + dir * horiz, y: apexY };4618
{ x: w1x, y: apexY },4701
if (start.y > apexY + 4)4619
{ x: w2x, y: apexY },4702
{4620
end4703
var p1 = { x: start.x, y: apexY };4621
];4704
var p2 = { x: riseX, y: apexY };4705
segments.push({ p0: start, p1: p1, p2: p2, p3: riseEnd });4706
}4707
else4708
{ riseEnd = { x: start.x, y: Math.min(start.y, apexY) }; }4709
4710
// Cruise stays on the apex line (convex hull is above the field).4711
var diveStart = { x: diveX - dir * horiz, y: apexY };4712
if (Math.abs(riseEnd.x - diveStart.x) > 4 || Math.abs(riseEnd.y - diveStart.y) > 4)4713
{4714
// Keep the cruise direction consistent; if the two joints4715
// would cross, just connect them directly.4716
var cdir = diveStart.x >= riseEnd.x ? 1 : -1;4717
var c1 = { x: riseEnd.x + cdir * horiz, y: riseEnd.y };4718
if (c1.y > apexY)4719
{ c1.y = apexY; }4720
var c2 = { x: diveStart.x - cdir * horiz, y: diveStart.y };4721
segments.push({ p0: { x: riseEnd.x, y: riseEnd.y }, p1: c1, p2: c2, p3: diveStart });4722
}4723
4724
if (end.y > apexY + 4 || Math.abs(end.x - (diveStart.x + dir * horiz)) > 2)4725
{4726
var u0 = (Math.abs(riseEnd.x - diveStart.x) > 4 || segments.length === 0)4727
? diveStart4728
: riseEnd;4729
if (segments.length && segments[segments.length - 1].p3.x === u0.x4730
&& segments[segments.length - 1].p3.y === u0.y)4731
{ /* already joined */ }4732
else if (segments.length === 0)4733
{ u0 = riseEnd; }4734
var u1 = { x: u0.x + dir * horiz, y: u0.y };4735
var fall = Math.max(24, Math.abs(end.y - apexY) * 0.45);4736
if (opts.endSpeedPx)4737
{4738
// |P3-P2| so arrival ≈ fallSpeed after equal-param scaling.4739
// velocity = 3*|P3-P2|*n*v1/duration; endSpeedPx is4740
// (cells*px*duration)/3, so |P3-P2| = endSpeedPx/(n*v1).4741
var nEst = Math.max(1, segments.length + 1);4742
fall = Math.max(20, opts.endSpeedPx / (nEst * 0.85));4743
}4744
var u2 = { x: end.x, y: end.y - fall };4745
// P2 may sit between the apex and the end (slower arrival);4746
// only clamp if it would pass the end or fly far past the apex.4747
if (u2.y < apexY - 240)4748
{ u2.y = apexY - 240; }4749
if (u2.y > end.y - 8)4750
{ u2.y = end.y - 8; }4751
segments.push({ p0: u0, p1: u1, p2: u2, p3: end });4752
}4753
4754
if (segments.length === 0)4755
{ return this._singleCubic(start, end, apexY, opts); }4756
if (segments.length === 1 && !segments[0].p0)4757
{ return this._singleCubic(start, end, apexY, opts); }4758
4759
return { segments: segments, apexY: apexY, p0: start, p3: end };4622
};4760
};4623
4761
4624
/**4762
Online._measureCurve = function (curve)4625
* Point at parameter u ∈ [0, 1] along a polyline, with a small upward4626
* bulge on each segment so the path reads as a "boogje".4627
*/4628
Online.pointOnPath = function (points, u)4629
{4763
{4630
u = u < 0 ? 0 : (u > 1 ? 1 : u);4764
if (!curve.segments)4631
if (!points || !points.length)4765
{ return curve; }4632
{ return { x: 0, y: 0 }; }4633
if (points.length === 1)4634
{ return { x: points[0].x, y: points[0].y }; }4635
var lens = [];4766
var lens = [];4636
var total = 0;4767
var total = 0;4637
for (var i = 1; i < points.length; i++)4768
for (var i = 0; i < curve.segments.length; i++)4638
{4769
{4639
var dx = points[i].x - points[i - 1].x;4770
var L = this._segLen(curve.segments[i]);4640
var dy = points[i].y - points[i - 1].y;4641
var L = Math.sqrt(dx * dx + dy * dy);4642
if (L < 1)4643
{ L = 1; }4644
lens.push(L);4771
lens.push(L);4645
total += L;4772
total += L;4646
}4773
}4647
var dist = u * total;4774
curve.lens = lens;4648
var acc = 0;4775
curve.totalLen = Math.max(total, 1);4649
for (var i = 0; i < lens.length; i++)4776
return curve;4777
};4778
4779
Online._segLen = function (seg, steps)4780
{4781
steps = steps || 10;4782
var len = 0;4783
var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);4784
for (var i = 1; i <= steps; i++)4650
{4785
{4651
if (acc + lens[i] >= dist || i === lens.length - 1)4786
var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);4652
{4787
var dx = p.x - prev.x;4653
var t = (dist - acc) / lens[i];4788
var dy = p.y - prev.y;4654
if (t < 0)4789
len += Math.sqrt(dx * dx + dy * dy);4655
{ t = 0; }4790
prev = p;4656
if (t > 1)4791
}4657
{ t = 1; }4792
return Math.max(len, 1);4658
var a = points[i];4793
};4659
var b = points[i + 1];4794
4660
var bump = 4 * 16 * t * (1 - t);4795
/**4661
return {4796
* Equal-parameter split across segments so matching local C'(t)4662
x: a.x + (b.x - a.x) * t,4797
* at joints also matches dP/du (no speed jerk).4663
y: a.y + (b.y - a.y) * t - bump4798
*/4664
};4799
Online._curveSegmentAt = function (curve, u)4665
}4800
{4666
acc += lens[i];4801
if (!curve)4802
{ return null; }4803
if (!curve.segments)4804
{4805
return { seg: curve, t: u < 0 ? 0 : (u > 1 ? 1 : u), scale: 1 };4667
}4806
}4668
var last = points[points.length - 1];4807
var segs = curve.segments;4669
return { x: last.x, y: last.y };4808
var n = segs.length;4809
if (u <= 0)4810
{ return { seg: segs[0], t: 0, scale: n }; }4811
if (u >= 1)4812
{ return { seg: segs[n - 1], t: 1, scale: n }; }4813
var at = u * n;4814
var i = Math.floor(at);4815
if (i >= n)4816
{ i = n - 1; }4817
var t = at - i;4818
return { seg: segs[i], t: t, scale: n };4819
};4820
4821
/** Point on a (possibly multi-segment C¹) curve at u ∈ [0, 1]. */4822
Online.curvePoint = function (curve, u)4823
{4824
var at = this._curveSegmentAt(curve, u);4825
if (!at)4826
{ return { x: 0, y: 0 }; }4827
var s = at.seg;4828
if (s && s.p1)4829
{ return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at.t); }4830
if (s && s.p0)4831
{ return { x: s.p0.x, y: s.p0.y }; }4832
return { x: 0, y: 0 };4833
};4834
4835
/** dP/du of the curve (C¹ across joints). */4836
Online.curveDeriv = function (curve, u)4837
{4838
var at = this._curveSegmentAt(curve, u);4839
if (!at || !at.seg || !at.seg.p1)4840
{ return { x: 0, y: 0 }; }4841
var s = at.seg;4842
var d = this.cubicBezierDeriv(s.p0, s.p1, s.p2, s.p3, at.t);4843
return { x: d.x * at.scale, y: d.y * at.scale };4670
};4844
};4671
4845
4672
/** Sample a player↔enemy path; used by tests and the ticker. */4846
/**4847
* Sample the smooth around-field curve at u ∈ [0, 1] (t1134).4848
* `clearance` may be a number or an options object.4849
*/4673
Online.aroundFieldPoint = function (start, end, u, field, clearance)4850
Online.aroundFieldPoint = function (start, end, u, field, clearance)4674
{4851
{4675
var pts = this.waypointsAroundField(start, end, field, clearance);4852
var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };4676
if (pts.length === 2)4853
var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);4854
return this.curvePoint(curve, u);4855
};4856
4857
/** Guide points (start, joints, end) for older tests. */4858
Online.waypointsAroundField = function (start, end, field, clearance)4859
{4860
var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 64 });4861
if (c.segments && c.segments.length)4862
{4863
var pts = [{ x: c.segments[0].p0.x, y: c.segments[0].p0.y }];4864
for (var i = 0; i < c.segments.length; i++)4865
{ pts.push({ x: c.segments[i].p3.x, y: c.segments[i].p3.y }); }4866
return pts;4867
}4868
return [c.p0, c.p1, c.p2, c.p3];4869
};4870
4871
Online.pointOnPath = function (points, u)4872
{4873
// Legacy polyline; new flights use cubicBezier.4874
u = u < 0 ? 0 : (u > 1 ? 1 : u);4875
if (!points || !points.length)4876
{ return { x: 0, y: 0 }; }4877
if (points.length === 4 && points[0] && points[3])4878
{ return this.cubicBezier(points[0], points[1], points[2], points[3], u); }4879
if (points.length === 1)4880
{ return { x: points[0].x, y: points[0].y }; }4881
var n = points.length - 1;4882
var at = u * n;4883
var i = Math.floor(at);4884
if (i >= n)4885
{ i = n - 1; }4886
var t = at - i;4887
var a = points[i];4888
var b = points[i + 1];4889
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };4890
};4891
4892
/** Viewport centre of a field cell (y=0 is the bottom row). */4893
Online.cellViewport = function (col, y, rect)4894
{4895
if (!rect)4677
{4896
{4678
var h = this.arcHeight(start, end);4897
var field = this.playerFieldRect();4679
return this.arcPoint(start, end, u, h);4898
if (!field)4899
{ return { x: 0, y: 0 }; }4900
rect = field;4680
}4901
}4681
return this.pointOnPath(pts, u);4902
var w = rect.width != null ? rect.width : (rect.right - rect.left);4903
var h = rect.height != null ? rect.height : (rect.bottom - rect.top);4904
return {4905
x: rect.left + ((col + 0.5) / 10) * w,4906
y: rect.top + (1 - (y + 0.5) / 13) * h4907
};4908
};4909
4910
/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */4911
Online.fieldEntry = function (col)4912
{4913
return this.cellViewport(col == null ? 4.5 : col, 13);4914
};4915
4916
Online.miniCellViewport = function (playerId, col, y)4917
{4918
var el = this.miniElement(playerId);4919
var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);4920
var box = canvas || el;4921
if (!box || !box.getBoundingClientRect)4922
{ return { x: window.innerWidth / 2, y: 48 }; }4923
return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());4924
};4925
4926
Online._fallSpeedPx = function (field, duration)4927
{4928
var px = 40;4929
if (field && field.height)4930
{ px = field.height / 13; }4931
else if (typeof app !== 'undefined' && app.tile)4932
{ px = app.tile; }4933
var cells = 13 / 3;4934
if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)4935
{ cells = app.planet.fallSpeed; }4936
duration = duration || this.FLIGHT_DURATION;4937
// Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).4938
return (cells * px * duration) / 3;4682
};4939
};4683
4940
4684
Online.rememberLandCol = function (id, col)4941
Online.rememberLandCol = function (id, col)@@ -4746,17 +5003,17 @@ Online._miniAnchor = function (playerId, dir)4746
5003
4747
Online._fieldTop = function (col)5004
Online._fieldTop = function (col)4748
{5005
{4749
return this._flightStart(col);5006
return this.fieldEntry(col);4750
};5007
};4751
5008
4752
/**5009
/**4753
* Animate shot results. `locals` is a map of client_id → {col, y, color,5010
* Animate shot results. `locals` is a map of client_id → {col, y, color,4754
* startX, startY, from_id} in viewport pixels.5011
* startX, startY, from_id} in viewport pixels.4755
*5012
*4756
* Visual-only (t1125): a parabolic arc whose scale goes from mini-cell5013
* Visual-only: a smooth cubic that leaves the real cell, arcs around4757
* to full tile (or the reverse). Enemy-to-enemy arcs stay small and5014
* the field, and dives into the landing column at the spawn pose4758
* are drawn behind the player's field. Delivery timing is unchanged;5015
* (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn4759
* a late-seen flight starts mid-arc via `age`.5016
* behind the player's field. A late-seen flight starts mid-arc via `age`.4760
*/5017
*/4761
Online.spawnFlights = function (results, locals)5018
Online.spawnFlights = function (results, locals)4762
{5019
{@@ -4767,6 +5024,8 @@ Online.spawnFlights = function (results, locals)4767
{ return; }5024
{ return; }4768
if (!this._flightSeen)5025
if (!this._flightSeen)4769
{ this._flightSeen = Object.create(null); }5026
{ this._flightSeen = Object.create(null); }5027
if (!this._previewIds)5028
{ this._previewIds = Object.create(null); }4770
var now = performance.now();5029
var now = performance.now();4771
var full = this._fullTileSize();5030
var full = this._fullTileSize();4772
for (var i = 0; i < results.length; i++)5031
for (var i = 0; i < results.length; i++)@@ -4774,7 +5033,18 @@ Online.spawnFlights = function (results, locals)4774
var r = results[i];5033
var r = results[i];4775
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));5034
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));4776
if (this._flightSeen[sid])5035
if (this._flightSeen[sid])4777
{ continue; }5036
{5037
if (this._previewIds[sid])5038
{5039
var existing = this._findFlight(sid);5040
if (existing)5041
{5042
var meta0 = locals[r.client_id] || locals[sid] || {};5043
this.retargetFlight(existing, r, meta0, now);5044
}5045
}5046
continue;5047
}4778
this._flightSeen[sid] = now;5048
this._flightSeen[sid] = now;4779
5049
4780
var meta = locals[r.client_id] || locals[sid] || {};5050
var meta = locals[r.client_id] || locals[sid] || {};@@ -4801,11 +5071,15 @@ Online.spawnFlights = function (results, locals)4801
{ this.rememberLandCol(r.client_id, landCol); }5071
{ this.rememberLandCol(r.client_id, landCol); }4802
}5072
}4803
5073
5074
var startCol = meta.col != null ? meta.col : r.col;5075
var startY = meta.y != null ? meta.y : r.y;4804
var start;5076
var start;4805
if (meta.startX != null && isFinite(meta.startX))5077
if (meta.startX != null && isFinite(meta.startX))4806
{ start = { x: meta.startX, y: meta.startY }; }5078
{ start = { x: meta.startX, y: meta.startY }; }4807
else if (kind === 'player-to-enemy' || kind === 'player-miss')5079
else if (kind === 'player-to-enemy' || kind === 'player-miss')4808
{ start = this._flightStart(meta.col != null ? meta.col : r.col); }5080
{ start = this._flightStart(startCol, startY); }5081
else if (startCol != null || startY != null)5082
{ start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 12); }4809
else5083
else4810
{ start = this._miniAnchor(fromId, 'out'); }5084
{ start = this._miniAnchor(fromId, 'out'); }4811
5085
@@ -4813,7 +5087,7 @@ Online.spawnFlights = function (results, locals)4813
if (miss)5087
if (miss)4814
{ end = this._missEnd(start, kind === 'enemy-miss'); }5088
{ end = this._missEnd(start, kind === 'enemy-miss'); }4815
else if (kind === 'enemy-to-player')5089
else if (kind === 'enemy-to-player')4816
{ end = this._fieldTop(landCol != null ? landCol : 4.5); }5090
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }4817
else5091
else4818
{ end = this._targetEnd(targetId, start, landCol); }5092
{ end = this._targetEnd(targetId, start, landCol); }4819
5093
@@ -4874,7 +5148,14 @@ Online.spawnFlights = function (results, locals)4874
: this.arcHeight(start, end);5148
: this.arcHeight(start, end);4875
var field = this.playerFieldRect();5149
var field = this.playerFieldRect();4876
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');5150
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');4877
var waypoints = around ? this.waypointsAroundField(start, end, field, height * 0.45) : null;5151
var clearance = Math.max(64, height * 0.45);5152
var endSpeed = this._fallSpeedPx(field, duration / 1000);5153
var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {5154
clearance: clearance,5155
startSpeedPx: endSpeed,5156
endSpeedPx: endSpeed,5157
duration: duration / 10005158
});4878
this._flights.push({5159
this._flights.push({4879
el: el,5160
el: el,4880
start: start,5161
start: start,@@ -4883,16 +5164,16 @@ Online.spawnFlights = function (results, locals)4883
height: height,5164
height: height,4884
t0: t0,5165
t0: t0,4885
duration: duration,5166
duration: duration,4886
spin: (Math.random() * 2 - 1) * 720,5167
spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),4887
miss: miss,5168
miss: miss,4888
kind: kind,5169
kind: kind,4889
startScale: startScale,5170
startScale: startScale,4890
endScale: endScale,5171
endScale: endScale,4891
angle: Math.random() * 360,5172
angle: 0,4892
id: sid,5173
id: sid,4893
landCol: landCol,5174
landCol: landCol,4894
field: field,5175
field: field,4895
waypoints: waypoints,5176
curve: curve,4896
color: flightColor5177
color: flightColor4897
});5178
});4898
}5179
}@@ -4909,30 +5190,17 @@ Online.rememberFlightLocal = function (shot, startX, startY)4909
color: shot.color,5190
color: shot.color,4910
startX: startX,5191
startX: startX,4911
startY: startY,5192
startY: startY,4912
from_id: shot.from_id5193
from_id: shot.from_id,5194
land_col: shot.land_col,5195
vy: shot.vy4913
};5196
};4914
};5197
};4915
5198
4916
Online._flightStart = function (col)5199
Online._flightStart = function (col, y)4917
{5200
{4918
var appRef = typeof app !== 'undefined' ? app : null;5201
if (y == null || !isFinite(y))4919
if (appRef && appRef.scene && appRef.scene.canvas)5202
{ y = 12; }4920
{5203
return this.cellViewport(col == null ? 4.5 : col, y);4921
var canvas = appRef.scene.canvas;4922
var rect = canvas.getBoundingClientRect();4923
var c = col == null ? 4.5 : col;4924
return {4925
x: rect.left + (c + 0.5) * (rect.width / 10),4926
y: rect.top + 44927
};4928
}4929
var field = document.querySelector('canvas');4930
if (field)4931
{4932
var rect = field.getBoundingClientRect();4933
return { x: rect.left + rect.width / 2, y: rect.top };4934
}4935
return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };4936
};5204
};4937
5205
4938
Online._targetEnd = function (targetId, start, col)5206
Online._targetEnd = function (targetId, start, col)@@ -4940,12 +5208,8 @@ Online._targetEnd = function (targetId, start, col)4940
var el = targetId && this.miniElement(targetId);5208
var el = targetId && this.miniElement(targetId);4941
if (el)5209
if (el)4942
{5210
{4943
var canvas = el.querySelector('canvas') || el;5211
// Slightly inside the mini, in the landing column (t1135).4944
var r = canvas.getBoundingClientRect();5212
return this.miniCellViewport(targetId, col, 12);4945
var x = r.left + r.width / 2;4946
if (col != null && isFinite(col))4947
{ x = r.left + ((col + 0.5) / 10) * r.width; }4948
return { x: x, y: r.top + 4 };4949
}5213
}4950
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };5214
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };4951
};5215
};@@ -4980,6 +5244,251 @@ Online._hitCtrl = function (start, end)4980
};5244
};4981
};5245
};4982
5246
5247
Online._findFlight = function (sid)5248
{5249
sid = String(sid);5250
if (!this._flights)5251
{ return null; }5252
for (var i = 0; i < this._flights.length; i++)5253
{5254
if (String(this._flights[i].id) === sid)5255
{ return this._flights[i]; }5256
}5257
return null;5258
};5259
5260
/**5261
* Early visual takeover: a flying rocket near the top of a field5262
* becomes a flight sprite at its exact cell, so it is seen flying5263
* *out* rather than popping in above the canvas (t1134). When the5264
* shot is later dispatched, `retargetFlight` picks up from the5265
* current pose and aims at the real landing column.5266
*/5267
Online.previewExit = function (info)5268
{5269
if (!info || info.id == null)5270
{ return; }5271
var sid = String(info.id);5272
if (!this._flights)5273
{ this._flights = []; }5274
if (!this._flightSeen)5275
{ this._flightSeen = Object.create(null); }5276
if (!this._previewIds)5277
{ this._previewIds = Object.create(null); }5278
if (this._previewIds[sid] || this._flightSeen[sid])5279
{ return; }5280
var front = document.getElementById('flights');5281
if (!front || !info.start)5282
{ return; }5283
var start = info.start;5284
var field = this.playerFieldRect();5285
var clearance = 80;5286
if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)5287
{ clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }5288
var apexY = (field ? field.top : start.y) - clearance;5289
if (apexY < 8)5290
{ apexY = Math.max(8, start.y - 80); }5291
var end = { x: start.x, y: apexY };5292
var duration = this.FLIGHT_DURATION * 1000;5293
var full = this._fullTileSize();5294
var el = document.createElement('img');5295
el.src = colorSpriteUrl(info.color);5296
el.alt = '';5297
el.className = 'flight';5298
el.style.width = full + 'px';5299
el.style.height = full + 'px';5300
front.appendChild(el);5301
var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);5302
var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {5303
clearance: clearance,5304
startSpeedPx: endSpeed,5305
endSpeedPx: endSpeed5306
});5307
var now = performance.now();5308
var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;5309
if (mini < 0.12)5310
{ mini = 0.2; }5311
this._flights.push({5312
el: el,5313
start: start,5314
end: end,5315
ctrl: null,5316
height: clearance,5317
t0: now,5318
duration: duration,5319
spin: (Math.random() * 2 - 1) * 90,5320
miss: false,5321
kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',5322
startScale: mini,5323
endScale: mini,5324
angle: 0,5325
id: sid,5326
landCol: null,5327
field: field,5328
curve: curve,5329
preview: true,5330
color: info.color,5331
from_id: info.from_id || null5332
});5333
this._previewIds[sid] = true;5334
this._flightSeen[sid] = now;5335
};5336
5337
/** True while a field sprite should stay hidden — the flight is its visual. */5338
Online.hasExitVisual = function (id)5339
{5340
if (id == null)5341
{ return false; }5342
var sid = String(id);5343
if (this._previewIds && this._previewIds[sid])5344
{ return true; }5345
var f = this._findFlight(sid);5346
if (!f || f.miss)5347
{ return false; }5348
var raw = (performance.now() - f.t0) / f.duration;5349
return raw < 0.4;5350
};5351
5352
/**5353
* Once the shot is scored, pick up the preview at its current pose5354
* and fly the rest of the way to the real end (no jump).5355
*/5356
Online.retargetFlight = function (f, r, meta, now)5357
{5358
now = now || performance.now();5359
meta = meta || {};5360
var raw = (now - f.t0) / f.duration;5361
if (raw < 0)5362
{ raw = 0; }5363
if (raw > 0.95)5364
{ raw = 0.95; }5365
var u = this.smoothParam(raw, 0.9, 0.9);5366
var pt = f.curve5367
? this.curvePoint(f.curve, u)5368
: { x: f.start.x, y: f.start.y };5369
var curScale = f.startScale + (f.endScale - f.startScale) * u;5370
5371
var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;5372
var targetId = r.target_id != null ? r.target_id : r.to_user;5373
var miss = !!r.miss;5374
var kind = this.flightKind(fromId, targetId, miss);5375
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;5376
5377
var landCol = null;5378
if (r.land_col != null && isFinite(r.land_col))5379
{ landCol = r.land_col | 0; }5380
else if (meta.land_col != null && isFinite(meta.land_col))5381
{ landCol = meta.land_col | 0; }5382
else if (f.landCol != null)5383
{ landCol = f.landCol; }5384
if (landCol != null)5385
{ this.rememberLandCol(String(f.id), landCol); }5386
5387
var end;5388
if (miss)5389
{ end = this._missEnd(pt, kind === 'enemy-miss'); }5390
else if (kind === 'enemy-to-player')5391
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }5392
else5393
{ end = this._targetEnd(targetId, pt, landCol); }5394
5395
var flightColor = miss5396
? (r.color != null ? r.color : meta.color)5397
: -1;5398
if (f.el && flightColor !== f.color)5399
{ f.el.src = colorSpriteUrl(flightColor); }5400
5401
var full = this._fullTileSize();5402
var mini = this._miniCellSize(fromId || targetId) / full;5403
if (mini < 0.12)5404
{ mini = 0.2; }5405
var endScale;5406
if (kind === 'player-to-enemy')5407
{ endScale = mini; }5408
else if (kind === 'enemy-to-player')5409
{ endScale = 1; }5410
else if (kind === 'enemy-to-enemy')5411
{ endScale = mini; }5412
else5413
{ endScale = 0; }5414
5415
var field = this.playerFieldRect();5416
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');5417
var height = miss5418
? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))5419
: this.arcHeight(pt, end);5420
var clearance = Math.max(64, height * 0.45);5421
var endSpeed = this._fallSpeedPx(field, duration / 1000);5422
var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {5423
clearance: clearance,5424
startSpeedPx: endSpeed,5425
endSpeedPx: endSpeed5426
});5427
5428
f.start = pt;5429
f.end = end;5430
f.t0 = now;5431
f.duration = duration;5432
f.curve = curve;5433
f.ctrl = miss ? this._missCtrl(pt, end) : null;5434
f.height = height;5435
f.miss = miss;5436
f.kind = kind;5437
f.startScale = curScale;5438
f.endScale = endScale;5439
f.landCol = landCol;5440
f.field = field;5441
f.preview = false;5442
f.color = flightColor;5443
f.from_id = fromId;5444
if (this._previewIds)5445
{ delete this._previewIds[String(f.id)]; }5446
5447
if (kind === 'enemy-to-enemy' && f.el)5448
{5449
var back = document.getElementById('flights-back');5450
if (back && f.el.parentNode !== back)5451
{5452
f.el.className = 'flight flight-behind';5453
back.appendChild(f.el);5454
}5455
}5456
};5457
5458
/** Point and (optional) derivative of a flight at parameter u. */5459
Online.flightPointAt = function (f, u)5460
{5461
if (!f)5462
{ return { x: 0, y: 0 }; }5463
if (f.curve)5464
{ return this.curvePoint(f.curve, u); }5465
if (f.miss && f.ctrl)5466
{5467
var e = u;5468
var mt = 1 - e;5469
return {5470
x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,5471
y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y5472
};5473
}5474
return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);5475
};5476
5477
Online.pointAllowedOnArc = function (p, field, start, end, slop)5478
{5479
if (!this.pointInFieldInterior(p.x, p.y, field, slop))5480
{ return true; }5481
if (!field)5482
{ return true; }5483
var w = (field.right - field.left) / 10;5484
var corridor = w * 0.7;5485
if (start && Math.abs(p.x - start.x) <= corridor)5486
{ return true; }5487
if (end && Math.abs(p.x - end.x) <= corridor)5488
{ return true; }5489
return false;5490
};5491
4983
Online.tickFlights = function (now)5492
Online.tickFlights = function (now)4984
{5493
{4985
now = now || performance.now();5494
now = now || performance.now();@@ -4992,11 +5501,14 @@ Online.tickFlights = function (now)4992
{5501
{4993
if (f.el && f.el.parentNode)5502
if (f.el && f.el.parentNode)4994
{ f.el.parentNode.removeChild(f.el); }5503
{ f.el.parentNode.removeChild(f.el); }5504
if (this._previewIds)5505
{ delete this._previewIds[String(f.id)]; }4995
continue;5506
continue;4996
}5507
}4997
if (raw < 0)5508
if (raw < 0)4998
{ raw = 0; }5509
{ raw = 0; }4999
var u = this.easeInOutCubic(raw);5510
// Non-zero endpoint speed so the handoff matches fallSpeed (t1135).5511
var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, 0.85, 0.85);5000
var x, y;5512
var x, y;5001
if (f.miss && f.ctrl)5513
if (f.miss && f.ctrl)5002
{5514
{@@ -5005,21 +5517,15 @@ Online.tickFlights = function (now)5005
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;5517
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;5006
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;5518
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;5007
}5519
}5008
else if (f.waypoints && f.waypoints.length > 2)5520
else if (f.curve)5009
{5010
var pt = this.pointOnPath(f.waypoints, u);5011
x = pt.x;5012
y = pt.y;5013
}5014
else if (f.waypoints && f.field)5015
{5521
{5016
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);5522
var pt = this.curvePoint(f.curve, u);5017
x = pt.x;5523
x = pt.x;5018
y = pt.y;5524
y = pt.y;5019
}5525
}5020
else5526
else5021
{5527
{5022
var pt = this.arcPoint(f.start, f.end, u, f.height || 80);5528
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);5023
x = pt.x;5529
x = pt.x;5024
y = pt.y;5530
y = pt.y;5025
}5531
}@@ -5060,6 +5566,7 @@ Online.clearFlights = function ()5060
this._flightLocals = {};5566
this._flightLocals = {};5061
this._flightSeen = Object.create(null);5567
this._flightSeen = Object.create(null);5062
this._pendingLandCol = Object.create(null);5568
this._pendingLandCol = Object.create(null);5569
this._previewIds = Object.create(null);5063
};5570
};5064
5571
5065
if (typeof globalThis !== 'undefined')5572
if (typeof globalThis !== 'undefined')@@ -6187,6 +6694,11 @@ function syncSprites (dt)6187
applyBlockVisual(obj, block);6694
applyBlockVisual(obj, block);6188
obj.renderer.visible = true;6695
obj.renderer.visible = true;6189
obj.renderer.alpha = 1;6696
obj.renderer.alpha = 1;6697
if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))6698
{6699
obj.renderer.visible = false;6700
obj.renderer.alpha = 0;6701
}6190
6702
6191
if (block.flame)6703
if (block.flame)6192
{6704
{@@ -6213,6 +6725,10 @@ function syncSprites (dt)6213
}6725
}6214
else if (app.flames[block.id])6726
else if (app.flames[block.id])6215
{ app.flames[block.id].renderer.visible = false; }6727
{ app.flames[block.id].renderer.visible = false; }6728
if (block.flame && app.flames[block.id]6729
&& typeof Online !== 'undefined' && Online.hasExitVisual6730
&& Online.hasExitVisual(block.id))6731
{ app.flames[block.id].renderer.visible = false; }6216
}6732
}6217
6733
6218
var ids = Object.keys(app.sprites);6734
var ids = Object.keys(app.sprites);@@ -6450,6 +6966,7 @@ function tickView (dt)6450
placeTile(app.cells[i], col, row);6966
placeTile(app.cells[i], col, row);6451
}6967
}6452
6968
6969
previewOutgoingFlights();6453
app.core.tick(dt);6970
app.core.tick(dt);6454
if (app.offline && app.battle)6971
if (app.offline && app.battle)6455
{ tickOffline(dt); }6972
{ tickOffline(dt); }@@ -6970,7 +7487,7 @@ function tickOnline (dt)6970
for (var i = 0; i < shots.length; i++)7487
for (var i = 0; i < shots.length; i++)6971
{7488
{6972
var s = shots[i];7489
var s = shots[i];6973
var start = fieldToViewport(s.col, s.y + 1);7490
var start = fieldToViewport(s.col, s.y);6974
Online.rememberFlightLocal(s, start.x, start.y);7491
Online.rememberFlightLocal(s, start.x, start.y);6975
}7492
}6976
Online.queueShots(shots);7493
Online.queueShots(shots);@@ -7048,7 +7565,9 @@ function tickOffline (dt)7048
var s = list[i];7565
var s = list[i];7049
var start;7566
var start;7050
if (s.from_id === 'player')7567
if (s.from_id === 'player')7051
{ start = fieldToViewport(s.col, s.y + 1); }7568
{ start = fieldToViewport(s.col, s.y); }7569
else if (typeof Online !== 'undefined' && Online.miniCellViewport)7570
{ start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }7052
else7571
else7053
{ start = miniViewportCenter(s.from_id); }7572
{ start = miniViewportCenter(s.from_id); }7054
locals[s.client_id] = {7573
locals[s.client_id] = {@@ -7292,6 +7811,58 @@ function updateColumnWarn (dt)7292
}7811
}7293
}7812
}7294
7813
7814
/**7815
* Take over a rocket that is about to leave the top of a field (the7816
* player's, or a bot's) so the flight starts at the real cell and7817
* continues its upward motion (t1134). Shared by offline and online.7818
*/7819
function previewOutgoingFlights ()7820
{7821
if (typeof Online === 'undefined' || !Online.previewExit)7822
{ return; }7823
if (app.core)7824
{ previewCoreExits(app.core, null); }7825
if (app.offline && app.battle && app.battle.bots)7826
{7827
var bots = app.battle.bots;7828
for (var i = 0; i < bots.length; i++)7829
{7830
var bot = bots[i];7831
if (bot && bot.core && !bot.eliminated)7832
{ previewCoreExits(bot.core, bot.id); }7833
}7834
}7835
}7836
7837
function previewCoreExits (core, fromId)7838
{7839
if (!core || !core.blocks)7840
{ return; }7841
var blocks = core.blocks;7842
for (var i = 0; i < blocks.length; i++)7843
{7844
var b = blocks[i];7845
if (b.y < 11.6)7846
{ continue; }7847
if (!(b.vy > 0))7848
{ continue; }7849
var start = fromId7850
? (Online.miniCellViewport7851
? Online.miniCellViewport(fromId, b.col, b.y)7852
: miniViewportCenter(fromId))7853
: fieldToViewport(b.col, b.y);7854
Online.previewExit({7855
id: b.id,7856
col: b.col,7857
y: b.y,7858
vy: b.vy,7859
color: b.color,7860
start: start,7861
from_id: fromId || null7862
});7863
}7864
}7865
7295
function fieldToViewport (col, fieldY)7866
function fieldToViewport (col, fieldY)7296
{7867
{7297
var canvas = app.scene && app.scene.canvas;7868
var canvas = app.scene && app.scene.canvas;@@ -7299,7 +7870,8 @@ function fieldToViewport (col, fieldY)7299
{ return { x: window.innerWidth / 2, y: 40 }; }7870
{ return { x: window.innerWidth / 2, y: 40 }; }7300
var rect = canvas.getBoundingClientRect();7871
var rect = canvas.getBoundingClientRect();7301
var x = rect.left + ((col + 0.5) / 10) * rect.width;7872
var x = rect.left + ((col + 0.5) / 10) * rect.width;7302
var y = rect.top + (1 - (fieldY / 13)) * rect.height;7873
// Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).7874
var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;7303
return { x: x, y: y };7875
return { x: x, y: y };7304
}7876
}7305
7877
@@ -665,3 +665,60 @@ Aanname:
665
665
vanaf de **bovenkant** van de mini, gaan omhoog en in een ruime
666
666
boog over de bovenrand naar de landingskolom, niet over de mini's
667
667
of over het binnenveld.
668
669
## t1134 — soepele boogjes, en écht uit het veld vliegen
670
671
- De oude polyline met hoekpunten (omhoog, horizontaal, omlaag) is
672
vervangen door een **C¹-ketting van kubische Béziers**: omhoog
673
uit de lanceerkolom (of langs de buitenkant), een vloeiende
674
kwart-draai, een rechte kruising boven het veld, en een vloeiende
675
duik de landingskolom in. Raaklijnen en snelheid sluiten aan de
676
gewrichten naadloos aan — geen zichtbare hoeken, geen ruk in het
677
tempo. `easeInOutCubic` (snelheid 0 aan begin en eind) is voor
678
raak-schoten verdwenen; `smoothParam` houdt aan de uiteinden een
679
niet-nul snelheid.
680
- Speler↔vijand gaat nog steeds om het veld heen en mag alleen de
681
**lanceer- en landingskolom** gebruiken, niet het binnenveld.
682
Vijand→vijand blijft een kleine soepele boog achter het veld.
683
- Een uitgaand schot start op de **echte cel** van de raket (zelfde
684
positie en formaat als de sprite, `fieldToViewport` met het
685
+0,5-tegel-midden). Zodra een vliegende raket bij de bovenste
686
rij komt (`y ≳ 11,6`, `vy > 0`) neemt een vlucht-sprite het
687
visueel over (de veld-sprite verdwijnt) en vliegt omhoog verder;
688
bij het echte schot wordt de boog vanaf de huidige pose op het
689
echte doel gericht, zonder sprong. Zo ontstaan blokjes niet meer
690
„erbovenop” het veld.
691
692
## t1135 — soepel het veld invliegen, naadloze overdracht
693
694
- De boog duikt **de landingskolom in** en eindigt op de
695
spawn-pose van `ingestGarbage`: `y = 13` (een halve tegel boven
696
de canvasrand), volle tegelgrootte, raaklijn recht naar beneden.
697
De eindsnelheid is afgestemd op `fallSpeed` van de planeet, zodat
698
het vallende grijze blok dezelfde positie, grootte en snelheid
699
overneemt — geen pop-in aan de bovenkant. Offline levert
700
`battle.tick` het blok eerst af en verwijdert daarna de vlucht
701
(één frame overlap op dezelfde pose).
702
- Aankomst bij een vijand-mini gaat het blokje iets **de mini in**
703
(`y = 12` in de landingskolom, op mini-formaat). Er is geen live
704
vallende sprite op de mini; het volgende snapshot toont het cel.
705
706
## t1136 — multiplayer ziet er hetzelfde uit als Offline Strijd
707
708
- Online en offline delen dezelfde presentatie: `MiniLayout`
709
(buitenrand, horizontaal eerst, onder uitgelijnd, `ARC_TOP_PAD`),
710
`Online.spawnFlights` / `tickFlights` (C¹-bogen om het veld,
711
`land_col`, grijze raak-schoten, uitvliegen vanuit de cel,
712
invliegen naar de spawn-pose, vijand→vijand achter het veld) en
713
`previewOutgoingFlights` voor de lokale raket.
714
- De server bewaart nu ook de **lanceercel** (`from_col`, `from_y`)
715
en stuurt die mee op `shot_results` en `shot_flights`, zodat een
716
andere client het blokje uit de juiste cel van de mini ziet
717
vertrekken (niet vanaf een vast punt boven de mini). Zonder
718
lokale `startX` (typisch voor een remote poll) gebruikt
719
`spawnFlights` die `col`/`y`.
720
- Geverifieerd met Playwright: lokale PHP-server, test-auth,
721
twee Playwright-clients in een echte lobby (lokale PHP-server met test-auth), daarna `shot_flights` via
722
`Online._handleTransitions` (het echte poll-pad) op 1920×1080
723
en 1024×532, plus dezelfde bogen in Offline Strijd (early/mid/
724
late en een korte webm).
@@ -665,3 +665,60 @@ Aanname:665
vanaf de **bovenkant** van de mini, gaan omhoog en in een ruime665
vanaf de **bovenkant** van de mini, gaan omhoog en in een ruime666
boog over de bovenrand naar de landingskolom, niet over de mini's666
boog over de bovenrand naar de landingskolom, niet over de mini's667
of over het binnenveld.667
of over het binnenveld.668
669
## t1134 — soepele boogjes, en écht uit het veld vliegen670
671
- De oude polyline met hoekpunten (omhoog, horizontaal, omlaag) is672
vervangen door een **C¹-ketting van kubische Béziers**: omhoog673
uit de lanceerkolom (of langs de buitenkant), een vloeiende674
kwart-draai, een rechte kruising boven het veld, en een vloeiende675
duik de landingskolom in. Raaklijnen en snelheid sluiten aan de676
gewrichten naadloos aan — geen zichtbare hoeken, geen ruk in het677
tempo. `easeInOutCubic` (snelheid 0 aan begin en eind) is voor678
raak-schoten verdwenen; `smoothParam` houdt aan de uiteinden een679
niet-nul snelheid.680
- Speler↔vijand gaat nog steeds om het veld heen en mag alleen de681
**lanceer- en landingskolom** gebruiken, niet het binnenveld.682
Vijand→vijand blijft een kleine soepele boog achter het veld.683
- Een uitgaand schot start op de **echte cel** van de raket (zelfde684
positie en formaat als de sprite, `fieldToViewport` met het685
+0,5-tegel-midden). Zodra een vliegende raket bij de bovenste686
rij komt (`y ≳ 11,6`, `vy > 0`) neemt een vlucht-sprite het687
visueel over (de veld-sprite verdwijnt) en vliegt omhoog verder;688
bij het echte schot wordt de boog vanaf de huidige pose op het689
echte doel gericht, zonder sprong. Zo ontstaan blokjes niet meer690
„erbovenop” het veld.691
692
## t1135 — soepel het veld invliegen, naadloze overdracht693
694
- De boog duikt **de landingskolom in** en eindigt op de695
spawn-pose van `ingestGarbage`: `y = 13` (een halve tegel boven696
de canvasrand), volle tegelgrootte, raaklijn recht naar beneden.697
De eindsnelheid is afgestemd op `fallSpeed` van de planeet, zodat698
het vallende grijze blok dezelfde positie, grootte en snelheid699
overneemt — geen pop-in aan de bovenkant. Offline levert700
`battle.tick` het blok eerst af en verwijdert daarna de vlucht701
(één frame overlap op dezelfde pose).702
- Aankomst bij een vijand-mini gaat het blokje iets **de mini in**703
(`y = 12` in de landingskolom, op mini-formaat). Er is geen live704
vallende sprite op de mini; het volgende snapshot toont het cel.705
706
## t1136 — multiplayer ziet er hetzelfde uit als Offline Strijd707
708
- Online en offline delen dezelfde presentatie: `MiniLayout`709
(buitenrand, horizontaal eerst, onder uitgelijnd, `ARC_TOP_PAD`),710
`Online.spawnFlights` / `tickFlights` (C¹-bogen om het veld,711
`land_col`, grijze raak-schoten, uitvliegen vanuit de cel,712
invliegen naar de spawn-pose, vijand→vijand achter het veld) en713
`previewOutgoingFlights` voor de lokale raket.714
- De server bewaart nu ook de **lanceercel** (`from_col`, `from_y`)715
en stuurt die mee op `shot_results` en `shot_flights`, zodat een716
andere client het blokje uit de juiste cel van de mini ziet717
vertrekken (niet vanaf een vast punt boven de mini). Zonder718
lokale `startX` (typisch voor een remote poll) gebruikt719
`spawnFlights` die `col`/`y`.720
- Geverifieerd met Playwright: lokale PHP-server, test-auth,721
twee Playwright-clients in een echte lobby (lokale PHP-server met test-auth), daarna `shot_flights` via722
`Online._handleTransitions` (het echte poll-pad) op 1920×1080723
en 1024×532, plus dezelfde bogen in Offline Strijd (early/mid/724
late en een korte webm).@@ -75,6 +75,8 @@ CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered,
75
75
SQL);
76
76
$this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77
77
$this->ensureColumn('shots', 'land_col', 'INTEGER');
78
$this->ensureColumn('shots', 'from_col', 'INTEGER');
79
$this->ensureColumn('shots', 'from_y', 'REAL');
78
80
}
79
81
80
82
private function ensureColumn(string $table, string $column, string $ddl): void
@@ -395,12 +397,14 @@ SQL);
395
397
$flight = (float) $lobby['flight_duration'];
396
398
$now = $this->nowf();
397
399
$ins = $this->pdo->prepare(
398
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col)
399
VALUES (?,?,?,?,?,?,?,0,?)'
400
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y)
401
VALUES (?,?,?,?,?,?,?,0,?,?,?)'
400
402
);
401
403
foreach ($shots as $shot) {
402
404
$color = isset($shot['color']) ? (int) $shot['color'] : -1;
403
405
$clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
406
$fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null;
407
$fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null;
404
408
$miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
405
409
$to = null;
406
410
$toName = null;
@@ -412,7 +416,7 @@ SQL);
412
416
$landCol = random_int(0, 9);
413
417
}
414
418
$deliver = $now + $flight;
415
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol]);
419
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]);
416
420
$results[] = [
417
421
'id' => (int) $this->pdo->lastInsertId(),
418
422
'client_id' => $clientId,
@@ -426,6 +430,8 @@ SQL);
426
430
'flight_duration' => $flight,
427
431
'age' => 0.0,
428
432
'land_col' => $landCol,
433
'col' => $fromCol,
434
'y' => $fromY,
429
435
];
430
436
}
431
437
return $results;
@@ -457,6 +463,8 @@ SQL);
457
463
'from_user' => $r['from_user'],
458
464
'client_id' => $r['client_id'],
459
465
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
466
'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
467
'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
460
468
];
461
469
}
462
470
return $incoming;
@@ -609,6 +617,8 @@ SQL);
609
617
'age' => $now - (float) $r['created'],
610
618
'deliver_at' => (float) $r['deliver_at'],
611
619
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
620
'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
621
'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
612
622
];
613
623
}
614
624
return $out;
@@ -75,6 +75,8 @@ CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered,75
SQL);75
SQL);76
$this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");76
$this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");77
$this->ensureColumn('shots', 'land_col', 'INTEGER');77
$this->ensureColumn('shots', 'land_col', 'INTEGER');78
$this->ensureColumn('shots', 'from_col', 'INTEGER');79
$this->ensureColumn('shots', 'from_y', 'REAL');78
}80
}79
81
80
private function ensureColumn(string $table, string $column, string $ddl): void82
private function ensureColumn(string $table, string $column, string $ddl): void@@ -395,12 +397,14 @@ SQL);395
$flight = (float) $lobby['flight_duration'];397
$flight = (float) $lobby['flight_duration'];396
$now = $this->nowf();398
$now = $this->nowf();397
$ins = $this->pdo->prepare(399
$ins = $this->pdo->prepare(398
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col)400
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y)399
VALUES (?,?,?,?,?,?,?,0,?)'401
VALUES (?,?,?,?,?,?,?,0,?,?,?)'400
);402
);401
foreach ($shots as $shot) {403
foreach ($shots as $shot) {402
$color = isset($shot['color']) ? (int) $shot['color'] : -1;404
$color = isset($shot['color']) ? (int) $shot['color'] : -1;403
$clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');405
$clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');406
$fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null;407
$fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null;404
$miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;408
$miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;405
$to = null;409
$to = null;406
$toName = null;410
$toName = null;@@ -412,7 +416,7 @@ SQL);412
$landCol = random_int(0, 9);416
$landCol = random_int(0, 9);413
}417
}414
$deliver = $now + $flight;418
$deliver = $now + $flight;415
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol]);419
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]);416
$results[] = [420
$results[] = [417
'id' => (int) $this->pdo->lastInsertId(),421
'id' => (int) $this->pdo->lastInsertId(),418
'client_id' => $clientId,422
'client_id' => $clientId,@@ -426,6 +430,8 @@ SQL);426
'flight_duration' => $flight,430
'flight_duration' => $flight,427
'age' => 0.0,431
'age' => 0.0,428
'land_col' => $landCol,432
'land_col' => $landCol,433
'col' => $fromCol,434
'y' => $fromY,429
];435
];430
}436
}431
return $results;437
return $results;@@ -457,6 +463,8 @@ SQL);457
'from_user' => $r['from_user'],463
'from_user' => $r['from_user'],458
'client_id' => $r['client_id'],464
'client_id' => $r['client_id'],459
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,465
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,466
'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,467
'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,460
];468
];461
}469
}462
return $incoming;470
return $incoming;@@ -609,6 +617,8 @@ SQL);609
'age' => $now - (float) $r['created'],617
'age' => $now - (float) $r['created'],610
'deliver_at' => (float) $r['deliver_at'],618
'deliver_at' => (float) $r['deliver_at'],611
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,619
'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,620
'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,621
'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,612
];622
];613
}623
}614
return $out;624
return $out;@@ -245,7 +245,7 @@ $store->setReady('local:test_user_3', true);
245
245
$store->startGame('local:test_user_1');
246
246
$store->testMissOverride = 0.0;
247
247
$shots = $store->recordShots('local:test_user_1', [
248
['client_id' => 'f1', 'color' => 2],
248
['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],
249
249
]);
250
250
$store->testMissOverride = null;
251
251
expect(count($shots) === 1, 'one recorded shot');
@@ -270,6 +270,10 @@ if ($found) {
270
270
expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
271
271
expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');
272
272
expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');
273
expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');
274
expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');
275
expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');
276
expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');
273
277
}
274
278
// Incoming carries the same land_col (t1126).
275
279
$targetId = $found['target_id'] ?? $shots[0]['target_id'];
@@ -245,7 +245,7 @@ $store->setReady('local:test_user_3', true);245
$store->startGame('local:test_user_1');245
$store->startGame('local:test_user_1');246
$store->testMissOverride = 0.0;246
$store->testMissOverride = 0.0;247
$shots = $store->recordShots('local:test_user_1', [247
$shots = $store->recordShots('local:test_user_1', [248
['client_id' => 'f1', 'color' => 2],248
['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],249
]);249
]);250
$store->testMissOverride = null;250
$store->testMissOverride = null;251
expect(count($shots) === 1, 'one recorded shot');251
expect(count($shots) === 1, 'one recorded shot');@@ -270,6 +270,10 @@ if ($found) {270
expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');270
expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');271
expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');271
expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');272
expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');272
expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');273
expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');274
expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');275
expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');276
expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');273
}277
}274
// Incoming carries the same land_col (t1126).278
// Incoming carries the same land_col (t1126).275
$targetId = $found['target_id'] ?? $shots[0]['target_id'];279
$targetId = $found['target_id'] ?? $shots[0]['target_id'];@@ -2011,7 +2011,8 @@ GameCore.prototype.cullOffTop = function ()
2011
2011
id: block.id,
2012
2012
color: block.color,
2013
2013
col: block.col,
2014
y: block.y
2014
y: block.y,
2015
vy: block.vy
2015
2016
});
2016
2017
this.score += 1;
2017
2018
this.removeBlock(block);
@@ -2011,7 +2011,8 @@ GameCore.prototype.cullOffTop = function ()2011
id: block.id,2011
id: block.id,2012
color: block.color,2012
color: block.color,2013
col: block.col,2013
col: block.col,2014
y: block.y2014
y: block.y,2015
vy: block.vy2015
});2016
});2016
this.score += 1;2017
this.score += 1;2017
this.removeBlock(block);2018
this.removeBlock(block);@@ -489,6 +489,11 @@ function syncSprites (dt)
489
489
applyBlockVisual(obj, block);
490
490
obj.renderer.visible = true;
491
491
obj.renderer.alpha = 1;
492
if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))
493
{
494
obj.renderer.visible = false;
495
obj.renderer.alpha = 0;
496
}
492
497
493
498
if (block.flame)
494
499
{
@@ -515,6 +520,10 @@ function syncSprites (dt)
515
520
}
516
521
else if (app.flames[block.id])
517
522
{ app.flames[block.id].renderer.visible = false; }
523
if (block.flame && app.flames[block.id]
524
&& typeof Online !== 'undefined' && Online.hasExitVisual
525
&& Online.hasExitVisual(block.id))
526
{ app.flames[block.id].renderer.visible = false; }
518
527
}
519
528
520
529
var ids = Object.keys(app.sprites);
@@ -752,6 +761,7 @@ function tickView (dt)
752
761
placeTile(app.cells[i], col, row);
753
762
}
754
763
764
previewOutgoingFlights();
755
765
app.core.tick(dt);
756
766
if (app.offline && app.battle)
757
767
{ tickOffline(dt); }
@@ -1272,7 +1282,7 @@ function tickOnline (dt)
1272
1282
for (var i = 0; i < shots.length; i++)
1273
1283
{
1274
1284
var s = shots[i];
1275
var start = fieldToViewport(s.col, s.y + 1);
1285
var start = fieldToViewport(s.col, s.y);
1276
1286
Online.rememberFlightLocal(s, start.x, start.y);
1277
1287
}
1278
1288
Online.queueShots(shots);
@@ -1350,7 +1360,9 @@ function tickOffline (dt)
1350
1360
var s = list[i];
1351
1361
var start;
1352
1362
if (s.from_id === 'player')
1353
{ start = fieldToViewport(s.col, s.y + 1); }
1363
{ start = fieldToViewport(s.col, s.y); }
1364
else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1365
{ start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1354
1366
else
1355
1367
{ start = miniViewportCenter(s.from_id); }
1356
1368
locals[s.client_id] = {
@@ -1594,6 +1606,58 @@ function updateColumnWarn (dt)
1594
1606
}
1595
1607
}
1596
1608
1609
/**
1610
* Take over a rocket that is about to leave the top of a field (the
1611
* player's, or a bot's) so the flight starts at the real cell and
1612
* continues its upward motion (t1134). Shared by offline and online.
1613
*/
1614
function previewOutgoingFlights ()
1615
{
1616
if (typeof Online === 'undefined' || !Online.previewExit)
1617
{ return; }
1618
if (app.core)
1619
{ previewCoreExits(app.core, null); }
1620
if (app.offline && app.battle && app.battle.bots)
1621
{
1622
var bots = app.battle.bots;
1623
for (var i = 0; i < bots.length; i++)
1624
{
1625
var bot = bots[i];
1626
if (bot && bot.core && !bot.eliminated)
1627
{ previewCoreExits(bot.core, bot.id); }
1628
}
1629
}
1630
}
1631
1632
function previewCoreExits (core, fromId)
1633
{
1634
if (!core || !core.blocks)
1635
{ return; }
1636
var blocks = core.blocks;
1637
for (var i = 0; i < blocks.length; i++)
1638
{
1639
var b = blocks[i];
1640
if (b.y < 11.6)
1641
{ continue; }
1642
if (!(b.vy > 0))
1643
{ continue; }
1644
var start = fromId
1645
? (Online.miniCellViewport
1646
? Online.miniCellViewport(fromId, b.col, b.y)
1647
: miniViewportCenter(fromId))
1648
: fieldToViewport(b.col, b.y);
1649
Online.previewExit({
1650
id: b.id,
1651
col: b.col,
1652
y: b.y,
1653
vy: b.vy,
1654
color: b.color,
1655
start: start,
1656
from_id: fromId || null
1657
});
1658
}
1659
}
1660
1597
1661
function fieldToViewport (col, fieldY)
1598
1662
{
1599
1663
var canvas = app.scene && app.scene.canvas;
@@ -1601,7 +1665,8 @@ function fieldToViewport (col, fieldY)
1601
1665
{ return { x: window.innerWidth / 2, y: 40 }; }
1602
1666
var rect = canvas.getBoundingClientRect();
1603
1667
var x = rect.left + ((col + 0.5) / 10) * rect.width;
1604
var y = rect.top + (1 - (fieldY / 13)) * rect.height;
1668
// Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1669
var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1605
1670
return { x: x, y: y };
1606
1671
}
1607
1672
@@ -489,6 +489,11 @@ function syncSprites (dt)489
applyBlockVisual(obj, block);489
applyBlockVisual(obj, block);490
obj.renderer.visible = true;490
obj.renderer.visible = true;491
obj.renderer.alpha = 1;491
obj.renderer.alpha = 1;492
if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))493
{494
obj.renderer.visible = false;495
obj.renderer.alpha = 0;496
}492
497
493
if (block.flame)498
if (block.flame)494
{499
{@@ -515,6 +520,10 @@ function syncSprites (dt)515
}520
}516
else if (app.flames[block.id])521
else if (app.flames[block.id])517
{ app.flames[block.id].renderer.visible = false; }522
{ app.flames[block.id].renderer.visible = false; }523
if (block.flame && app.flames[block.id]524
&& typeof Online !== 'undefined' && Online.hasExitVisual525
&& Online.hasExitVisual(block.id))526
{ app.flames[block.id].renderer.visible = false; }518
}527
}519
528
520
var ids = Object.keys(app.sprites);529
var ids = Object.keys(app.sprites);@@ -752,6 +761,7 @@ function tickView (dt)752
placeTile(app.cells[i], col, row);761
placeTile(app.cells[i], col, row);753
}762
}754
763
764
previewOutgoingFlights();755
app.core.tick(dt);765
app.core.tick(dt);756
if (app.offline && app.battle)766
if (app.offline && app.battle)757
{ tickOffline(dt); }767
{ tickOffline(dt); }@@ -1272,7 +1282,7 @@ function tickOnline (dt)1272
for (var i = 0; i < shots.length; i++)1282
for (var i = 0; i < shots.length; i++)1273
{1283
{1274
var s = shots[i];1284
var s = shots[i];1275
var start = fieldToViewport(s.col, s.y + 1);1285
var start = fieldToViewport(s.col, s.y);1276
Online.rememberFlightLocal(s, start.x, start.y);1286
Online.rememberFlightLocal(s, start.x, start.y);1277
}1287
}1278
Online.queueShots(shots);1288
Online.queueShots(shots);@@ -1350,7 +1360,9 @@ function tickOffline (dt)1350
var s = list[i];1360
var s = list[i];1351
var start;1361
var start;1352
if (s.from_id === 'player')1362
if (s.from_id === 'player')1353
{ start = fieldToViewport(s.col, s.y + 1); }1363
{ start = fieldToViewport(s.col, s.y); }1364
else if (typeof Online !== 'undefined' && Online.miniCellViewport)1365
{ start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }1354
else1366
else1355
{ start = miniViewportCenter(s.from_id); }1367
{ start = miniViewportCenter(s.from_id); }1356
locals[s.client_id] = {1368
locals[s.client_id] = {@@ -1594,6 +1606,58 @@ function updateColumnWarn (dt)1594
}1606
}1595
}1607
}1596
1608
1609
/**1610
* Take over a rocket that is about to leave the top of a field (the1611
* player's, or a bot's) so the flight starts at the real cell and1612
* continues its upward motion (t1134). Shared by offline and online.1613
*/1614
function previewOutgoingFlights ()1615
{1616
if (typeof Online === 'undefined' || !Online.previewExit)1617
{ return; }1618
if (app.core)1619
{ previewCoreExits(app.core, null); }1620
if (app.offline && app.battle && app.battle.bots)1621
{1622
var bots = app.battle.bots;1623
for (var i = 0; i < bots.length; i++)1624
{1625
var bot = bots[i];1626
if (bot && bot.core && !bot.eliminated)1627
{ previewCoreExits(bot.core, bot.id); }1628
}1629
}1630
}1631
1632
function previewCoreExits (core, fromId)1633
{1634
if (!core || !core.blocks)1635
{ return; }1636
var blocks = core.blocks;1637
for (var i = 0; i < blocks.length; i++)1638
{1639
var b = blocks[i];1640
if (b.y < 11.6)1641
{ continue; }1642
if (!(b.vy > 0))1643
{ continue; }1644
var start = fromId1645
? (Online.miniCellViewport1646
? Online.miniCellViewport(fromId, b.col, b.y)1647
: miniViewportCenter(fromId))1648
: fieldToViewport(b.col, b.y);1649
Online.previewExit({1650
id: b.id,1651
col: b.col,1652
y: b.y,1653
vy: b.vy,1654
color: b.color,1655
start: start,1656
from_id: fromId || null1657
});1658
}1659
}1660
1597
function fieldToViewport (col, fieldY)1661
function fieldToViewport (col, fieldY)1598
{1662
{1599
var canvas = app.scene && app.scene.canvas;1663
var canvas = app.scene && app.scene.canvas;@@ -1601,7 +1665,8 @@ function fieldToViewport (col, fieldY)1601
{ return { x: window.innerWidth / 2, y: 40 }; }1665
{ return { x: window.innerWidth / 2, y: 40 }; }1602
var rect = canvas.getBoundingClientRect();1666
var rect = canvas.getBoundingClientRect();1603
var x = rect.left + ((col + 0.5) / 10) * rect.width;1667
var x = rect.left + ((col + 0.5) / 10) * rect.width;1604
var y = rect.top + (1 - (fieldY / 13)) * rect.height;1668
// Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).1669
var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;1605
return { x: x, y: y };1670
return { x: x, y: y };1606
}1671
}1607
1672
@@ -508,7 +508,7 @@ Online.playerFieldRect = function ()
508
508
509
509
/**
510
510
* True if (x, y) is inside the field's interior. The top edge (a few
511
* pixels) is not interior: that is where arcs may land (t1128).
511
* pixels) is not interior: launch and landing may use that band.
512
512
*/
513
513
Online.pointInFieldInterior = function (x, y, field, slop)
514
514
{
@@ -519,107 +519,363 @@ Online.pointInFieldInterior = function (x, y, field, slop)
519
519
&& y > field.top + slop && y < field.bottom - 0.5;
520
520
};
521
521
522
/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */
523
Online.cubicBezier = function (p0, p1, p2, p3, t)
524
{
525
if (t < 0)
526
{ t = 0; }
527
if (t > 1)
528
{ t = 1; }
529
var u = 1 - t;
530
var a = u * u * u;
531
var b = 3 * u * u * t;
532
var c = 3 * u * t * t;
533
var d = t * t * t;
534
return {
535
x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
536
y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
537
};
538
};
539
540
/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */
541
Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)
542
{
543
if (t < 0)
544
{ t = 0; }
545
if (t > 1)
546
{ t = 1; }
547
var u = 1 - t;
548
return {
549
x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
550
y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
551
};
552
};
553
522
554
/**
523
* Waypoints that route a player↔enemy arc around the field, never
524
* through its interior: up the outside, across above the top edge,
525
* then into the target (t1128). If both ends already sit at or above
526
* the top, a simple two-point path is enough.
555
* Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
556
* v0=v1=1 is linear (constant speed in t, no endpoint halt).
527
557
*/
528
Online.waypointsAroundField = function (start, end, field, clearance)
558
Online.smoothParam = function (t, v0, v1)
529
559
{
530
if (!start || !end)
531
{ return [start || { x: 0, y: 0 }, end || { x: 0, y: 0 }]; }
560
if (t < 0)
561
{ return 0; }
562
if (t > 1)
563
{ return 1; }
564
if (v0 == null)
565
{ v0 = 1; }
566
if (v1 == null)
567
{ v1 = 1; }
568
var b = 3 - 2 * v0 - v1;
569
var a = v0 + v1 - 2;
570
return ((a * t + b) * t + v0) * t;
571
};
572
573
/**
574
* A simple up-and-over cubic, used when there is no field to route
575
* around (enemy→enemy) or both ends already sit above the apex.
576
*/
577
Online._singleCubic = function (start, end, apexY, opts)
578
{
579
opts = opts || {};
580
var rise = Math.max(40, Math.abs(start.y - apexY) * 0.9);
581
if (opts.startSpeedPx)
582
{ rise = Math.max(rise, opts.startSpeedPx); }
583
var fall = Math.max(40, Math.abs(end.y - apexY) * 0.9);
584
if (opts.endSpeedPx)
585
{ fall = Math.max(40, opts.endSpeedPx); }
586
var p1 = { x: start.x, y: Math.min(start.y - rise, apexY) };
587
var p2 = { x: end.x, y: Math.min(end.y - fall, apexY) };
588
return { p0: start, p1: p1, p2: p2, p3: end, apexY: apexY };
589
};
590
591
/**
592
* Smooth C¹ path: rise up (launch column or outside), cruise above
593
* the field, dive into the landing column (t1134 / t1135). Joints
594
* are quarter-turn cubics with matching tangents, so there are no
595
* corners and no speed jerks. The curve may use the launch and
596
* landing corridors but does not cut across the field interior.
597
*/
598
Online.makeAroundCurve = function (start, end, field, opts)
599
{
600
opts = opts || {};
601
if (!start)
602
{ start = { x: 0, y: 0 }; }
603
if (!end)
604
{ end = { x: 0, y: 0 }; }
605
var clearance = opts.clearance || 80;
532
606
if (!field)
533
{ return [start, end]; }
534
clearance = clearance || 64;
607
{
608
var looseApex = Math.min(start.y, end.y) - Math.max(40, clearance * 0.5);
609
if (looseApex < 8)
610
{ looseApex = Math.min(start.y, end.y) - 24; }
611
return this._singleCubic(start, end, looseApex, opts);
612
}
535
613
var top = field.top;
536
614
var left = field.left;
537
615
var right = field.right;
538
var pad = 10;
539
var apexY = Math.min(start.y, end.y, top) - clearance;
616
var apexY = top - clearance;
540
617
if (apexY < 8)
541
618
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }
542
619
543
if (start.y <= top + 6 && end.y <= top + 6)
544
{ return [start, end]; }
620
if (start.y <= apexY + 8 && end.y <= apexY + 8)
621
{ return this._singleCubic(start, end, apexY, opts); }
622
623
var pad = 14;
624
var dir = end.x >= start.x ? 1 : -1;
625
var span = Math.abs(end.x - start.x);
626
var horiz = Math.max(28, Math.min(80, span * 0.15 + 8));
627
function outsideX (x)
628
{
629
if (x < left + 8)
630
{ return Math.min(x, left - pad); }
631
if (x > right - 8)
632
{ return Math.max(x, right + pad); }
633
return x;
634
}
635
var riseX = outsideX(start.x);
636
var diveX = outsideX(end.x);
637
var segments = [];
638
639
// Rise ends already turned toward the cruise, at apex.
640
var riseEnd = { x: riseX + dir * horiz, y: apexY };
641
if (start.y > apexY + 4)
642
{
643
var p1 = { x: start.x, y: apexY };
644
var p2 = { x: riseX, y: apexY };
645
segments.push({ p0: start, p1: p1, p2: p2, p3: riseEnd });
646
}
647
else
648
{ riseEnd = { x: start.x, y: Math.min(start.y, apexY) }; }
545
649
546
var w1x = start.x;
547
var w2x = end.x;
548
if (start.x < left)
549
{ w1x = Math.min(start.x, left - pad); }
550
else if (start.x > right)
551
{ w1x = Math.max(start.x, right + pad); }
552
if (end.x < left)
553
{ w2x = Math.min(end.x, left - pad); }
554
else if (end.x > right)
555
{ w2x = Math.max(end.x, right + pad); }
650
// Cruise stays on the apex line (convex hull is above the field).
651
var diveStart = { x: diveX - dir * horiz, y: apexY };
652
if (Math.abs(riseEnd.x - diveStart.x) > 4 || Math.abs(riseEnd.y - diveStart.y) > 4)
653
{
654
// Keep the cruise direction consistent; if the two joints
655
// would cross, just connect them directly.
656
var cdir = diveStart.x >= riseEnd.x ? 1 : -1;
657
var c1 = { x: riseEnd.x + cdir * horiz, y: riseEnd.y };
658
if (c1.y > apexY)
659
{ c1.y = apexY; }
660
var c2 = { x: diveStart.x - cdir * horiz, y: diveStart.y };
661
segments.push({ p0: { x: riseEnd.x, y: riseEnd.y }, p1: c1, p2: c2, p3: diveStart });
662
}
556
663
557
return [
558
start,
559
{ x: w1x, y: apexY },
560
{ x: w2x, y: apexY },
561
end
562
];
664
if (end.y > apexY + 4 || Math.abs(end.x - (diveStart.x + dir * horiz)) > 2)
665
{
666
var u0 = (Math.abs(riseEnd.x - diveStart.x) > 4 || segments.length === 0)
667
? diveStart
668
: riseEnd;
669
if (segments.length && segments[segments.length - 1].p3.x === u0.x
670
&& segments[segments.length - 1].p3.y === u0.y)
671
{ /* already joined */ }
672
else if (segments.length === 0)
673
{ u0 = riseEnd; }
674
var u1 = { x: u0.x + dir * horiz, y: u0.y };
675
var fall = Math.max(24, Math.abs(end.y - apexY) * 0.45);
676
if (opts.endSpeedPx)
677
{
678
// |P3-P2| so arrival ≈ fallSpeed after equal-param scaling.
679
// velocity = 3*|P3-P2|*n*v1/duration; endSpeedPx is
680
// (cells*px*duration)/3, so |P3-P2| = endSpeedPx/(n*v1).
681
var nEst = Math.max(1, segments.length + 1);
682
fall = Math.max(20, opts.endSpeedPx / (nEst * 0.85));
683
}
684
var u2 = { x: end.x, y: end.y - fall };
685
// P2 may sit between the apex and the end (slower arrival);
686
// only clamp if it would pass the end or fly far past the apex.
687
if (u2.y < apexY - 240)
688
{ u2.y = apexY - 240; }
689
if (u2.y > end.y - 8)
690
{ u2.y = end.y - 8; }
691
segments.push({ p0: u0, p1: u1, p2: u2, p3: end });
692
}
693
694
if (segments.length === 0)
695
{ return this._singleCubic(start, end, apexY, opts); }
696
if (segments.length === 1 && !segments[0].p0)
697
{ return this._singleCubic(start, end, apexY, opts); }
698
699
return { segments: segments, apexY: apexY, p0: start, p3: end };
563
700
};
564
701
565
/**
566
* Point at parameter u ∈ [0, 1] along a polyline, with a small upward
567
* bulge on each segment so the path reads as a "boogje".
568
*/
569
Online.pointOnPath = function (points, u)
702
Online._measureCurve = function (curve)
570
703
{
571
u = u < 0 ? 0 : (u > 1 ? 1 : u);
572
if (!points || !points.length)
573
{ return { x: 0, y: 0 }; }
574
if (points.length === 1)
575
{ return { x: points[0].x, y: points[0].y }; }
704
if (!curve.segments)
705
{ return curve; }
576
706
var lens = [];
577
707
var total = 0;
578
for (var i = 1; i < points.length; i++)
708
for (var i = 0; i < curve.segments.length; i++)
579
709
{
580
var dx = points[i].x - points[i - 1].x;
581
var dy = points[i].y - points[i - 1].y;
582
var L = Math.sqrt(dx * dx + dy * dy);
583
if (L < 1)
584
{ L = 1; }
710
var L = this._segLen(curve.segments[i]);
585
711
lens.push(L);
586
712
total += L;
587
713
}
588
var dist = u * total;
589
var acc = 0;
590
for (var i = 0; i < lens.length; i++)
714
curve.lens = lens;
715
curve.totalLen = Math.max(total, 1);
716
return curve;
717
};
718
719
Online._segLen = function (seg, steps)
720
{
721
steps = steps || 10;
722
var len = 0;
723
var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
724
for (var i = 1; i <= steps; i++)
591
725
{
592
if (acc + lens[i] >= dist || i === lens.length - 1)
593
{
594
var t = (dist - acc) / lens[i];
595
if (t < 0)
596
{ t = 0; }
597
if (t > 1)
598
{ t = 1; }
599
var a = points[i];
600
var b = points[i + 1];
601
var bump = 4 * 16 * t * (1 - t);
602
return {
603
x: a.x + (b.x - a.x) * t,
604
y: a.y + (b.y - a.y) * t - bump
605
};
606
}
607
acc += lens[i];
726
var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
727
var dx = p.x - prev.x;
728
var dy = p.y - prev.y;
729
len += Math.sqrt(dx * dx + dy * dy);
730
prev = p;
608
731
}
609
var last = points[points.length - 1];
610
return { x: last.x, y: last.y };
732
return Math.max(len, 1);
733
};
734
735
/**
736
* Equal-parameter split across segments so matching local C'(t)
737
* at joints also matches dP/du (no speed jerk).
738
*/
739
Online._curveSegmentAt = function (curve, u)
740
{
741
if (!curve)
742
{ return null; }
743
if (!curve.segments)
744
{
745
return { seg: curve, t: u < 0 ? 0 : (u > 1 ? 1 : u), scale: 1 };
746
}
747
var segs = curve.segments;
748
var n = segs.length;
749
if (u <= 0)
750
{ return { seg: segs[0], t: 0, scale: n }; }
751
if (u >= 1)
752
{ return { seg: segs[n - 1], t: 1, scale: n }; }
753
var at = u * n;
754
var i = Math.floor(at);
755
if (i >= n)
756
{ i = n - 1; }
757
var t = at - i;
758
return { seg: segs[i], t: t, scale: n };
759
};
760
761
/** Point on a (possibly multi-segment C¹) curve at u ∈ [0, 1]. */
762
Online.curvePoint = function (curve, u)
763
{
764
var at = this._curveSegmentAt(curve, u);
765
if (!at)
766
{ return { x: 0, y: 0 }; }
767
var s = at.seg;
768
if (s && s.p1)
769
{ return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at.t); }
770
if (s && s.p0)
771
{ return { x: s.p0.x, y: s.p0.y }; }
772
return { x: 0, y: 0 };
773
};
774
775
/** dP/du of the curve (C¹ across joints). */
776
Online.curveDeriv = function (curve, u)
777
{
778
var at = this._curveSegmentAt(curve, u);
779
if (!at || !at.seg || !at.seg.p1)
780
{ return { x: 0, y: 0 }; }
781
var s = at.seg;
782
var d = this.cubicBezierDeriv(s.p0, s.p1, s.p2, s.p3, at.t);
783
return { x: d.x * at.scale, y: d.y * at.scale };
611
784
};
612
785
613
/** Sample a player↔enemy path; used by tests and the ticker. */
786
/**
787
* Sample the smooth around-field curve at u ∈ [0, 1] (t1134).
788
* `clearance` may be a number or an options object.
789
*/
614
790
Online.aroundFieldPoint = function (start, end, u, field, clearance)
615
791
{
616
var pts = this.waypointsAroundField(start, end, field, clearance);
617
if (pts.length === 2)
792
var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
793
var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
794
return this.curvePoint(curve, u);
795
};
796
797
/** Guide points (start, joints, end) for older tests. */
798
Online.waypointsAroundField = function (start, end, field, clearance)
799
{
800
var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 64 });
801
if (c.segments && c.segments.length)
618
802
{
619
var h = this.arcHeight(start, end);
620
return this.arcPoint(start, end, u, h);
803
var pts = [{ x: c.segments[0].p0.x, y: c.segments[0].p0.y }];
804
for (var i = 0; i < c.segments.length; i++)
805
{ pts.push({ x: c.segments[i].p3.x, y: c.segments[i].p3.y }); }
806
return pts;
621
807
}
622
return this.pointOnPath(pts, u);
808
return [c.p0, c.p1, c.p2, c.p3];
809
};
810
811
Online.pointOnPath = function (points, u)
812
{
813
// Legacy polyline; new flights use cubicBezier.
814
u = u < 0 ? 0 : (u > 1 ? 1 : u);
815
if (!points || !points.length)
816
{ return { x: 0, y: 0 }; }
817
if (points.length === 4 && points[0] && points[3])
818
{ return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
819
if (points.length === 1)
820
{ return { x: points[0].x, y: points[0].y }; }
821
var n = points.length - 1;
822
var at = u * n;
823
var i = Math.floor(at);
824
if (i >= n)
825
{ i = n - 1; }
826
var t = at - i;
827
var a = points[i];
828
var b = points[i + 1];
829
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
830
};
831
832
/** Viewport centre of a field cell (y=0 is the bottom row). */
833
Online.cellViewport = function (col, y, rect)
834
{
835
if (!rect)
836
{
837
var field = this.playerFieldRect();
838
if (!field)
839
{ return { x: 0, y: 0 }; }
840
rect = field;
841
}
842
var w = rect.width != null ? rect.width : (rect.right - rect.left);
843
var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
844
return {
845
x: rect.left + ((col + 0.5) / 10) * w,
846
y: rect.top + (1 - (y + 0.5) / 13) * h
847
};
848
};
849
850
/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
851
Online.fieldEntry = function (col)
852
{
853
return this.cellViewport(col == null ? 4.5 : col, 13);
854
};
855
856
Online.miniCellViewport = function (playerId, col, y)
857
{
858
var el = this.miniElement(playerId);
859
var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
860
var box = canvas || el;
861
if (!box || !box.getBoundingClientRect)
862
{ return { x: window.innerWidth / 2, y: 48 }; }
863
return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
864
};
865
866
Online._fallSpeedPx = function (field, duration)
867
{
868
var px = 40;
869
if (field && field.height)
870
{ px = field.height / 13; }
871
else if (typeof app !== 'undefined' && app.tile)
872
{ px = app.tile; }
873
var cells = 13 / 3;
874
if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
875
{ cells = app.planet.fallSpeed; }
876
duration = duration || this.FLIGHT_DURATION;
877
// Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
878
return (cells * px * duration) / 3;
623
879
};
624
880
625
881
Online.rememberLandCol = function (id, col)
@@ -687,17 +943,17 @@ Online._miniAnchor = function (playerId, dir)
687
943
688
944
Online._fieldTop = function (col)
689
945
{
690
return this._flightStart(col);
946
return this.fieldEntry(col);
691
947
};
692
948
693
949
/**
694
950
* Animate shot results. `locals` is a map of client_id → {col, y, color,
695
951
* startX, startY, from_id} in viewport pixels.
696
952
*
697
* Visual-only (t1125): a parabolic arc whose scale goes from mini-cell
698
* to full tile (or the reverse). Enemy-to-enemy arcs stay small and
699
* are drawn behind the player's field. Delivery timing is unchanged;
700
* a late-seen flight starts mid-arc via `age`.
953
* Visual-only: a smooth cubic that leaves the real cell, arcs around
954
* the field, and dives into the landing column at the spawn pose
955
* (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
956
* behind the player's field. A late-seen flight starts mid-arc via `age`.
701
957
*/
702
958
Online.spawnFlights = function (results, locals)
703
959
{
@@ -708,6 +964,8 @@ Online.spawnFlights = function (results, locals)
708
964
{ return; }
709
965
if (!this._flightSeen)
710
966
{ this._flightSeen = Object.create(null); }
967
if (!this._previewIds)
968
{ this._previewIds = Object.create(null); }
711
969
var now = performance.now();
712
970
var full = this._fullTileSize();
713
971
for (var i = 0; i < results.length; i++)
@@ -715,7 +973,18 @@ Online.spawnFlights = function (results, locals)
715
973
var r = results[i];
716
974
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
717
975
if (this._flightSeen[sid])
718
{ continue; }
976
{
977
if (this._previewIds[sid])
978
{
979
var existing = this._findFlight(sid);
980
if (existing)
981
{
982
var meta0 = locals[r.client_id] || locals[sid] || {};
983
this.retargetFlight(existing, r, meta0, now);
984
}
985
}
986
continue;
987
}
719
988
this._flightSeen[sid] = now;
720
989
721
990
var meta = locals[r.client_id] || locals[sid] || {};
@@ -742,11 +1011,15 @@ Online.spawnFlights = function (results, locals)
742
1011
{ this.rememberLandCol(r.client_id, landCol); }
743
1012
}
744
1013
1014
var startCol = meta.col != null ? meta.col : r.col;
1015
var startY = meta.y != null ? meta.y : r.y;
745
1016
var start;
746
1017
if (meta.startX != null && isFinite(meta.startX))
747
1018
{ start = { x: meta.startX, y: meta.startY }; }
748
1019
else if (kind === 'player-to-enemy' || kind === 'player-miss')
749
{ start = this._flightStart(meta.col != null ? meta.col : r.col); }
1020
{ start = this._flightStart(startCol, startY); }
1021
else if (startCol != null || startY != null)
1022
{ start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 12); }
750
1023
else
751
1024
{ start = this._miniAnchor(fromId, 'out'); }
752
1025
@@ -754,7 +1027,7 @@ Online.spawnFlights = function (results, locals)
754
1027
if (miss)
755
1028
{ end = this._missEnd(start, kind === 'enemy-miss'); }
756
1029
else if (kind === 'enemy-to-player')
757
{ end = this._fieldTop(landCol != null ? landCol : 4.5); }
1030
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }
758
1031
else
759
1032
{ end = this._targetEnd(targetId, start, landCol); }
760
1033
@@ -815,7 +1088,14 @@ Online.spawnFlights = function (results, locals)
815
1088
: this.arcHeight(start, end);
816
1089
var field = this.playerFieldRect();
817
1090
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
818
var waypoints = around ? this.waypointsAroundField(start, end, field, height * 0.45) : null;
1091
var clearance = Math.max(64, height * 0.45);
1092
var endSpeed = this._fallSpeedPx(field, duration / 1000);
1093
var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
1094
clearance: clearance,
1095
startSpeedPx: endSpeed,
1096
endSpeedPx: endSpeed,
1097
duration: duration / 1000
1098
});
819
1099
this._flights.push({
820
1100
el: el,
821
1101
start: start,
@@ -824,16 +1104,16 @@ Online.spawnFlights = function (results, locals)
824
1104
height: height,
825
1105
t0: t0,
826
1106
duration: duration,
827
spin: (Math.random() * 2 - 1) * 720,
1107
spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
828
1108
miss: miss,
829
1109
kind: kind,
830
1110
startScale: startScale,
831
1111
endScale: endScale,
832
angle: Math.random() * 360,
1112
angle: 0,
833
1113
id: sid,
834
1114
landCol: landCol,
835
1115
field: field,
836
waypoints: waypoints,
1116
curve: curve,
837
1117
color: flightColor
838
1118
});
839
1119
}
@@ -850,30 +1130,17 @@ Online.rememberFlightLocal = function (shot, startX, startY)
850
1130
color: shot.color,
851
1131
startX: startX,
852
1132
startY: startY,
853
from_id: shot.from_id
1133
from_id: shot.from_id,
1134
land_col: shot.land_col,
1135
vy: shot.vy
854
1136
};
855
1137
};
856
1138
857
Online._flightStart = function (col)
1139
Online._flightStart = function (col, y)
858
1140
{
859
var appRef = typeof app !== 'undefined' ? app : null;
860
if (appRef && appRef.scene && appRef.scene.canvas)
861
{
862
var canvas = appRef.scene.canvas;
863
var rect = canvas.getBoundingClientRect();
864
var c = col == null ? 4.5 : col;
865
return {
866
x: rect.left + (c + 0.5) * (rect.width / 10),
867
y: rect.top + 4
868
};
869
}
870
var field = document.querySelector('canvas');
871
if (field)
872
{
873
var rect = field.getBoundingClientRect();
874
return { x: rect.left + rect.width / 2, y: rect.top };
875
}
876
return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
1141
if (y == null || !isFinite(y))
1142
{ y = 12; }
1143
return this.cellViewport(col == null ? 4.5 : col, y);
877
1144
};
878
1145
879
1146
Online._targetEnd = function (targetId, start, col)
@@ -881,12 +1148,8 @@ Online._targetEnd = function (targetId, start, col)
881
1148
var el = targetId && this.miniElement(targetId);
882
1149
if (el)
883
1150
{
884
var canvas = el.querySelector('canvas') || el;
885
var r = canvas.getBoundingClientRect();
886
var x = r.left + r.width / 2;
887
if (col != null && isFinite(col))
888
{ x = r.left + ((col + 0.5) / 10) * r.width; }
889
return { x: x, y: r.top + 4 };
1151
// Slightly inside the mini, in the landing column (t1135).
1152
return this.miniCellViewport(targetId, col, 12);
890
1153
}
891
1154
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
892
1155
};
@@ -921,6 +1184,251 @@ Online._hitCtrl = function (start, end)
921
1184
};
922
1185
};
923
1186
1187
Online._findFlight = function (sid)
1188
{
1189
sid = String(sid);
1190
if (!this._flights)
1191
{ return null; }
1192
for (var i = 0; i < this._flights.length; i++)
1193
{
1194
if (String(this._flights[i].id) === sid)
1195
{ return this._flights[i]; }
1196
}
1197
return null;
1198
};
1199
1200
/**
1201
* Early visual takeover: a flying rocket near the top of a field
1202
* becomes a flight sprite at its exact cell, so it is seen flying
1203
* *out* rather than popping in above the canvas (t1134). When the
1204
* shot is later dispatched, `retargetFlight` picks up from the
1205
* current pose and aims at the real landing column.
1206
*/
1207
Online.previewExit = function (info)
1208
{
1209
if (!info || info.id == null)
1210
{ return; }
1211
var sid = String(info.id);
1212
if (!this._flights)
1213
{ this._flights = []; }
1214
if (!this._flightSeen)
1215
{ this._flightSeen = Object.create(null); }
1216
if (!this._previewIds)
1217
{ this._previewIds = Object.create(null); }
1218
if (this._previewIds[sid] || this._flightSeen[sid])
1219
{ return; }
1220
var front = document.getElementById('flights');
1221
if (!front || !info.start)
1222
{ return; }
1223
var start = info.start;
1224
var field = this.playerFieldRect();
1225
var clearance = 80;
1226
if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
1227
{ clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
1228
var apexY = (field ? field.top : start.y) - clearance;
1229
if (apexY < 8)
1230
{ apexY = Math.max(8, start.y - 80); }
1231
var end = { x: start.x, y: apexY };
1232
var duration = this.FLIGHT_DURATION * 1000;
1233
var full = this._fullTileSize();
1234
var el = document.createElement('img');
1235
el.src = colorSpriteUrl(info.color);
1236
el.alt = '';
1237
el.className = 'flight';
1238
el.style.width = full + 'px';
1239
el.style.height = full + 'px';
1240
front.appendChild(el);
1241
var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
1242
var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
1243
clearance: clearance,
1244
startSpeedPx: endSpeed,
1245
endSpeedPx: endSpeed
1246
});
1247
var now = performance.now();
1248
var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
1249
if (mini < 0.12)
1250
{ mini = 0.2; }
1251
this._flights.push({
1252
el: el,
1253
start: start,
1254
end: end,
1255
ctrl: null,
1256
height: clearance,
1257
t0: now,
1258
duration: duration,
1259
spin: (Math.random() * 2 - 1) * 90,
1260
miss: false,
1261
kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
1262
startScale: mini,
1263
endScale: mini,
1264
angle: 0,
1265
id: sid,
1266
landCol: null,
1267
field: field,
1268
curve: curve,
1269
preview: true,
1270
color: info.color,
1271
from_id: info.from_id || null
1272
});
1273
this._previewIds[sid] = true;
1274
this._flightSeen[sid] = now;
1275
};
1276
1277
/** True while a field sprite should stay hidden — the flight is its visual. */
1278
Online.hasExitVisual = function (id)
1279
{
1280
if (id == null)
1281
{ return false; }
1282
var sid = String(id);
1283
if (this._previewIds && this._previewIds[sid])
1284
{ return true; }
1285
var f = this._findFlight(sid);
1286
if (!f || f.miss)
1287
{ return false; }
1288
var raw = (performance.now() - f.t0) / f.duration;
1289
return raw < 0.4;
1290
};
1291
1292
/**
1293
* Once the shot is scored, pick up the preview at its current pose
1294
* and fly the rest of the way to the real end (no jump).
1295
*/
1296
Online.retargetFlight = function (f, r, meta, now)
1297
{
1298
now = now || performance.now();
1299
meta = meta || {};
1300
var raw = (now - f.t0) / f.duration;
1301
if (raw < 0)
1302
{ raw = 0; }
1303
if (raw > 0.95)
1304
{ raw = 0.95; }
1305
var u = this.smoothParam(raw, 0.9, 0.9);
1306
var pt = f.curve
1307
? this.curvePoint(f.curve, u)
1308
: { x: f.start.x, y: f.start.y };
1309
var curScale = f.startScale + (f.endScale - f.startScale) * u;
1310
1311
var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
1312
var targetId = r.target_id != null ? r.target_id : r.to_user;
1313
var miss = !!r.miss;
1314
var kind = this.flightKind(fromId, targetId, miss);
1315
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
1316
1317
var landCol = null;
1318
if (r.land_col != null && isFinite(r.land_col))
1319
{ landCol = r.land_col | 0; }
1320
else if (meta.land_col != null && isFinite(meta.land_col))
1321
{ landCol = meta.land_col | 0; }
1322
else if (f.landCol != null)
1323
{ landCol = f.landCol; }
1324
if (landCol != null)
1325
{ this.rememberLandCol(String(f.id), landCol); }
1326
1327
var end;
1328
if (miss)
1329
{ end = this._missEnd(pt, kind === 'enemy-miss'); }
1330
else if (kind === 'enemy-to-player')
1331
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }
1332
else
1333
{ end = this._targetEnd(targetId, pt, landCol); }
1334
1335
var flightColor = miss
1336
? (r.color != null ? r.color : meta.color)
1337
: -1;
1338
if (f.el && flightColor !== f.color)
1339
{ f.el.src = colorSpriteUrl(flightColor); }
1340
1341
var full = this._fullTileSize();
1342
var mini = this._miniCellSize(fromId || targetId) / full;
1343
if (mini < 0.12)
1344
{ mini = 0.2; }
1345
var endScale;
1346
if (kind === 'player-to-enemy')
1347
{ endScale = mini; }
1348
else if (kind === 'enemy-to-player')
1349
{ endScale = 1; }
1350
else if (kind === 'enemy-to-enemy')
1351
{ endScale = mini; }
1352
else
1353
{ endScale = 0; }
1354
1355
var field = this.playerFieldRect();
1356
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
1357
var height = miss
1358
? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
1359
: this.arcHeight(pt, end);
1360
var clearance = Math.max(64, height * 0.45);
1361
var endSpeed = this._fallSpeedPx(field, duration / 1000);
1362
var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
1363
clearance: clearance,
1364
startSpeedPx: endSpeed,
1365
endSpeedPx: endSpeed
1366
});
1367
1368
f.start = pt;
1369
f.end = end;
1370
f.t0 = now;
1371
f.duration = duration;
1372
f.curve = curve;
1373
f.ctrl = miss ? this._missCtrl(pt, end) : null;
1374
f.height = height;
1375
f.miss = miss;
1376
f.kind = kind;
1377
f.startScale = curScale;
1378
f.endScale = endScale;
1379
f.landCol = landCol;
1380
f.field = field;
1381
f.preview = false;
1382
f.color = flightColor;
1383
f.from_id = fromId;
1384
if (this._previewIds)
1385
{ delete this._previewIds[String(f.id)]; }
1386
1387
if (kind === 'enemy-to-enemy' && f.el)
1388
{
1389
var back = document.getElementById('flights-back');
1390
if (back && f.el.parentNode !== back)
1391
{
1392
f.el.className = 'flight flight-behind';
1393
back.appendChild(f.el);
1394
}
1395
}
1396
};
1397
1398
/** Point and (optional) derivative of a flight at parameter u. */
1399
Online.flightPointAt = function (f, u)
1400
{
1401
if (!f)
1402
{ return { x: 0, y: 0 }; }
1403
if (f.curve)
1404
{ return this.curvePoint(f.curve, u); }
1405
if (f.miss && f.ctrl)
1406
{
1407
var e = u;
1408
var mt = 1 - e;
1409
return {
1410
x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
1411
y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
1412
};
1413
}
1414
return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1415
};
1416
1417
Online.pointAllowedOnArc = function (p, field, start, end, slop)
1418
{
1419
if (!this.pointInFieldInterior(p.x, p.y, field, slop))
1420
{ return true; }
1421
if (!field)
1422
{ return true; }
1423
var w = (field.right - field.left) / 10;
1424
var corridor = w * 0.7;
1425
if (start && Math.abs(p.x - start.x) <= corridor)
1426
{ return true; }
1427
if (end && Math.abs(p.x - end.x) <= corridor)
1428
{ return true; }
1429
return false;
1430
};
1431
924
1432
Online.tickFlights = function (now)
925
1433
{
926
1434
now = now || performance.now();
@@ -933,11 +1441,14 @@ Online.tickFlights = function (now)
933
1441
{
934
1442
if (f.el && f.el.parentNode)
935
1443
{ f.el.parentNode.removeChild(f.el); }
1444
if (this._previewIds)
1445
{ delete this._previewIds[String(f.id)]; }
936
1446
continue;
937
1447
}
938
1448
if (raw < 0)
939
1449
{ raw = 0; }
940
var u = this.easeInOutCubic(raw);
1450
// Non-zero endpoint speed so the handoff matches fallSpeed (t1135).
1451
var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, 0.85, 0.85);
941
1452
var x, y;
942
1453
if (f.miss && f.ctrl)
943
1454
{
@@ -946,21 +1457,15 @@ Online.tickFlights = function (now)
946
1457
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
947
1458
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
948
1459
}
949
else if (f.waypoints && f.waypoints.length > 2)
1460
else if (f.curve)
950
1461
{
951
var pt = this.pointOnPath(f.waypoints, u);
952
x = pt.x;
953
y = pt.y;
954
}
955
else if (f.waypoints && f.field)
956
{
957
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
1462
var pt = this.curvePoint(f.curve, u);
958
1463
x = pt.x;
959
1464
y = pt.y;
960
1465
}
961
1466
else
962
1467
{
963
var pt = this.arcPoint(f.start, f.end, u, f.height || 80);
1468
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
964
1469
x = pt.x;
965
1470
y = pt.y;
966
1471
}
@@ -1001,6 +1506,7 @@ Online.clearFlights = function ()
1001
1506
this._flightLocals = {};
1002
1507
this._flightSeen = Object.create(null);
1003
1508
this._pendingLandCol = Object.create(null);
1509
this._previewIds = Object.create(null);
1004
1510
};
1005
1511
1006
1512
if (typeof globalThis !== 'undefined')
@@ -508,7 +508,7 @@ Online.playerFieldRect = function ()508
508
509
/**509
/**510
* True if (x, y) is inside the field's interior. The top edge (a few510
* True if (x, y) is inside the field's interior. The top edge (a few511
* pixels) is not interior: that is where arcs may land (t1128).511
* pixels) is not interior: launch and landing may use that band.512
*/512
*/513
Online.pointInFieldInterior = function (x, y, field, slop)513
Online.pointInFieldInterior = function (x, y, field, slop)514
{514
{@@ -519,107 +519,363 @@ Online.pointInFieldInterior = function (x, y, field, slop)519
&& y > field.top + slop && y < field.bottom - 0.5;519
&& y > field.top + slop && y < field.bottom - 0.5;520
};520
};521
521
522
/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */523
Online.cubicBezier = function (p0, p1, p2, p3, t)524
{525
if (t < 0)526
{ t = 0; }527
if (t > 1)528
{ t = 1; }529
var u = 1 - t;530
var a = u * u * u;531
var b = 3 * u * u * t;532
var c = 3 * u * t * t;533
var d = t * t * t;534
return {535
x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,536
y: a * p0.y + b * p1.y + c * p2.y + d * p3.y537
};538
};539
540
/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */541
Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)542
{543
if (t < 0)544
{ t = 0; }545
if (t > 1)546
{ t = 1; }547
var u = 1 - t;548
return {549
x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),550
y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)551
};552
};553
522
/**554
/**523
* Waypoints that route a player↔enemy arc around the field, never555
* Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.524
* through its interior: up the outside, across above the top edge,556
* v0=v1=1 is linear (constant speed in t, no endpoint halt).525
* then into the target (t1128). If both ends already sit at or above526
* the top, a simple two-point path is enough.527
*/557
*/528
Online.waypointsAroundField = function (start, end, field, clearance)558
Online.smoothParam = function (t, v0, v1)529
{559
{530
if (!start || !end)560
if (t < 0)531
{ return [start || { x: 0, y: 0 }, end || { x: 0, y: 0 }]; }561
{ return 0; }562
if (t > 1)563
{ return 1; }564
if (v0 == null)565
{ v0 = 1; }566
if (v1 == null)567
{ v1 = 1; }568
var b = 3 - 2 * v0 - v1;569
var a = v0 + v1 - 2;570
return ((a * t + b) * t + v0) * t;571
};572
573
/**574
* A simple up-and-over cubic, used when there is no field to route575
* around (enemy→enemy) or both ends already sit above the apex.576
*/577
Online._singleCubic = function (start, end, apexY, opts)578
{579
opts = opts || {};580
var rise = Math.max(40, Math.abs(start.y - apexY) * 0.9);581
if (opts.startSpeedPx)582
{ rise = Math.max(rise, opts.startSpeedPx); }583
var fall = Math.max(40, Math.abs(end.y - apexY) * 0.9);584
if (opts.endSpeedPx)585
{ fall = Math.max(40, opts.endSpeedPx); }586
var p1 = { x: start.x, y: Math.min(start.y - rise, apexY) };587
var p2 = { x: end.x, y: Math.min(end.y - fall, apexY) };588
return { p0: start, p1: p1, p2: p2, p3: end, apexY: apexY };589
};590
591
/**592
* Smooth C¹ path: rise up (launch column or outside), cruise above593
* the field, dive into the landing column (t1134 / t1135). Joints594
* are quarter-turn cubics with matching tangents, so there are no595
* corners and no speed jerks. The curve may use the launch and596
* landing corridors but does not cut across the field interior.597
*/598
Online.makeAroundCurve = function (start, end, field, opts)599
{600
opts = opts || {};601
if (!start)602
{ start = { x: 0, y: 0 }; }603
if (!end)604
{ end = { x: 0, y: 0 }; }605
var clearance = opts.clearance || 80;532
if (!field)606
if (!field)533
{ return [start, end]; }607
{534
clearance = clearance || 64;608
var looseApex = Math.min(start.y, end.y) - Math.max(40, clearance * 0.5);609
if (looseApex < 8)610
{ looseApex = Math.min(start.y, end.y) - 24; }611
return this._singleCubic(start, end, looseApex, opts);612
}535
var top = field.top;613
var top = field.top;536
var left = field.left;614
var left = field.left;537
var right = field.right;615
var right = field.right;538
var pad = 10;616
var apexY = top - clearance;539
var apexY = Math.min(start.y, end.y, top) - clearance;540
if (apexY < 8)617
if (apexY < 8)541
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }618
{ apexY = Math.max(8, top - Math.max(24, clearance * 0.5)); }542
619
543
if (start.y <= top + 6 && end.y <= top + 6)620
if (start.y <= apexY + 8 && end.y <= apexY + 8)544
{ return [start, end]; }621
{ return this._singleCubic(start, end, apexY, opts); }622
623
var pad = 14;624
var dir = end.x >= start.x ? 1 : -1;625
var span = Math.abs(end.x - start.x);626
var horiz = Math.max(28, Math.min(80, span * 0.15 + 8));627
function outsideX (x)628
{629
if (x < left + 8)630
{ return Math.min(x, left - pad); }631
if (x > right - 8)632
{ return Math.max(x, right + pad); }633
return x;634
}635
var riseX = outsideX(start.x);636
var diveX = outsideX(end.x);637
var segments = [];638
639
// Rise ends already turned toward the cruise, at apex.640
var riseEnd = { x: riseX + dir * horiz, y: apexY };641
if (start.y > apexY + 4)642
{643
var p1 = { x: start.x, y: apexY };644
var p2 = { x: riseX, y: apexY };645
segments.push({ p0: start, p1: p1, p2: p2, p3: riseEnd });646
}647
else648
{ riseEnd = { x: start.x, y: Math.min(start.y, apexY) }; }545
649
546
var w1x = start.x;650
// Cruise stays on the apex line (convex hull is above the field).547
var w2x = end.x;651
var diveStart = { x: diveX - dir * horiz, y: apexY };548
if (start.x < left)652
if (Math.abs(riseEnd.x - diveStart.x) > 4 || Math.abs(riseEnd.y - diveStart.y) > 4)549
{ w1x = Math.min(start.x, left - pad); }653
{550
else if (start.x > right)654
// Keep the cruise direction consistent; if the two joints551
{ w1x = Math.max(start.x, right + pad); }655
// would cross, just connect them directly.552
if (end.x < left)656
var cdir = diveStart.x >= riseEnd.x ? 1 : -1;553
{ w2x = Math.min(end.x, left - pad); }657
var c1 = { x: riseEnd.x + cdir * horiz, y: riseEnd.y };554
else if (end.x > right)658
if (c1.y > apexY)555
{ w2x = Math.max(end.x, right + pad); }659
{ c1.y = apexY; }660
var c2 = { x: diveStart.x - cdir * horiz, y: diveStart.y };661
segments.push({ p0: { x: riseEnd.x, y: riseEnd.y }, p1: c1, p2: c2, p3: diveStart });662
}556
663
557
return [664
if (end.y > apexY + 4 || Math.abs(end.x - (diveStart.x + dir * horiz)) > 2)558
start,665
{559
{ x: w1x, y: apexY },666
var u0 = (Math.abs(riseEnd.x - diveStart.x) > 4 || segments.length === 0)560
{ x: w2x, y: apexY },667
? diveStart561
end668
: riseEnd;562
];669
if (segments.length && segments[segments.length - 1].p3.x === u0.x670
&& segments[segments.length - 1].p3.y === u0.y)671
{ /* already joined */ }672
else if (segments.length === 0)673
{ u0 = riseEnd; }674
var u1 = { x: u0.x + dir * horiz, y: u0.y };675
var fall = Math.max(24, Math.abs(end.y - apexY) * 0.45);676
if (opts.endSpeedPx)677
{678
// |P3-P2| so arrival ≈ fallSpeed after equal-param scaling.679
// velocity = 3*|P3-P2|*n*v1/duration; endSpeedPx is680
// (cells*px*duration)/3, so |P3-P2| = endSpeedPx/(n*v1).681
var nEst = Math.max(1, segments.length + 1);682
fall = Math.max(20, opts.endSpeedPx / (nEst * 0.85));683
}684
var u2 = { x: end.x, y: end.y - fall };685
// P2 may sit between the apex and the end (slower arrival);686
// only clamp if it would pass the end or fly far past the apex.687
if (u2.y < apexY - 240)688
{ u2.y = apexY - 240; }689
if (u2.y > end.y - 8)690
{ u2.y = end.y - 8; }691
segments.push({ p0: u0, p1: u1, p2: u2, p3: end });692
}693
694
if (segments.length === 0)695
{ return this._singleCubic(start, end, apexY, opts); }696
if (segments.length === 1 && !segments[0].p0)697
{ return this._singleCubic(start, end, apexY, opts); }698
699
return { segments: segments, apexY: apexY, p0: start, p3: end };563
};700
};564
701
565
/**702
Online._measureCurve = function (curve)566
* Point at parameter u ∈ [0, 1] along a polyline, with a small upward567
* bulge on each segment so the path reads as a "boogje".568
*/569
Online.pointOnPath = function (points, u)570
{703
{571
u = u < 0 ? 0 : (u > 1 ? 1 : u);704
if (!curve.segments)572
if (!points || !points.length)705
{ return curve; }573
{ return { x: 0, y: 0 }; }574
if (points.length === 1)575
{ return { x: points[0].x, y: points[0].y }; }576
var lens = [];706
var lens = [];577
var total = 0;707
var total = 0;578
for (var i = 1; i < points.length; i++)708
for (var i = 0; i < curve.segments.length; i++)579
{709
{580
var dx = points[i].x - points[i - 1].x;710
var L = this._segLen(curve.segments[i]);581
var dy = points[i].y - points[i - 1].y;582
var L = Math.sqrt(dx * dx + dy * dy);583
if (L < 1)584
{ L = 1; }585
lens.push(L);711
lens.push(L);586
total += L;712
total += L;587
}713
}588
var dist = u * total;714
curve.lens = lens;589
var acc = 0;715
curve.totalLen = Math.max(total, 1);590
for (var i = 0; i < lens.length; i++)716
return curve;717
};718
719
Online._segLen = function (seg, steps)720
{721
steps = steps || 10;722
var len = 0;723
var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);724
for (var i = 1; i <= steps; i++)591
{725
{592
if (acc + lens[i] >= dist || i === lens.length - 1)726
var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);593
{727
var dx = p.x - prev.x;594
var t = (dist - acc) / lens[i];728
var dy = p.y - prev.y;595
if (t < 0)729
len += Math.sqrt(dx * dx + dy * dy);596
{ t = 0; }730
prev = p;597
if (t > 1)598
{ t = 1; }599
var a = points[i];600
var b = points[i + 1];601
var bump = 4 * 16 * t * (1 - t);602
return {603
x: a.x + (b.x - a.x) * t,604
y: a.y + (b.y - a.y) * t - bump605
};606
}607
acc += lens[i];608
}731
}609
var last = points[points.length - 1];732
return Math.max(len, 1);610
return { x: last.x, y: last.y };733
};734
735
/**736
* Equal-parameter split across segments so matching local C'(t)737
* at joints also matches dP/du (no speed jerk).738
*/739
Online._curveSegmentAt = function (curve, u)740
{741
if (!curve)742
{ return null; }743
if (!curve.segments)744
{745
return { seg: curve, t: u < 0 ? 0 : (u > 1 ? 1 : u), scale: 1 };746
}747
var segs = curve.segments;748
var n = segs.length;749
if (u <= 0)750
{ return { seg: segs[0], t: 0, scale: n }; }751
if (u >= 1)752
{ return { seg: segs[n - 1], t: 1, scale: n }; }753
var at = u * n;754
var i = Math.floor(at);755
if (i >= n)756
{ i = n - 1; }757
var t = at - i;758
return { seg: segs[i], t: t, scale: n };759
};760
761
/** Point on a (possibly multi-segment C¹) curve at u ∈ [0, 1]. */762
Online.curvePoint = function (curve, u)763
{764
var at = this._curveSegmentAt(curve, u);765
if (!at)766
{ return { x: 0, y: 0 }; }767
var s = at.seg;768
if (s && s.p1)769
{ return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at.t); }770
if (s && s.p0)771
{ return { x: s.p0.x, y: s.p0.y }; }772
return { x: 0, y: 0 };773
};774
775
/** dP/du of the curve (C¹ across joints). */776
Online.curveDeriv = function (curve, u)777
{778
var at = this._curveSegmentAt(curve, u);779
if (!at || !at.seg || !at.seg.p1)780
{ return { x: 0, y: 0 }; }781
var s = at.seg;782
var d = this.cubicBezierDeriv(s.p0, s.p1, s.p2, s.p3, at.t);783
return { x: d.x * at.scale, y: d.y * at.scale };611
};784
};612
785
613
/** Sample a player↔enemy path; used by tests and the ticker. */786
/**787
* Sample the smooth around-field curve at u ∈ [0, 1] (t1134).788
* `clearance` may be a number or an options object.789
*/614
Online.aroundFieldPoint = function (start, end, u, field, clearance)790
Online.aroundFieldPoint = function (start, end, u, field, clearance)615
{791
{616
var pts = this.waypointsAroundField(start, end, field, clearance);792
var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };617
if (pts.length === 2)793
var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);794
return this.curvePoint(curve, u);795
};796
797
/** Guide points (start, joints, end) for older tests. */798
Online.waypointsAroundField = function (start, end, field, clearance)799
{800
var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 64 });801
if (c.segments && c.segments.length)618
{802
{619
var h = this.arcHeight(start, end);803
var pts = [{ x: c.segments[0].p0.x, y: c.segments[0].p0.y }];620
return this.arcPoint(start, end, u, h);804
for (var i = 0; i < c.segments.length; i++)805
{ pts.push({ x: c.segments[i].p3.x, y: c.segments[i].p3.y }); }806
return pts;621
}807
}622
return this.pointOnPath(pts, u);808
return [c.p0, c.p1, c.p2, c.p3];809
};810
811
Online.pointOnPath = function (points, u)812
{813
// Legacy polyline; new flights use cubicBezier.814
u = u < 0 ? 0 : (u > 1 ? 1 : u);815
if (!points || !points.length)816
{ return { x: 0, y: 0 }; }817
if (points.length === 4 && points[0] && points[3])818
{ return this.cubicBezier(points[0], points[1], points[2], points[3], u); }819
if (points.length === 1)820
{ return { x: points[0].x, y: points[0].y }; }821
var n = points.length - 1;822
var at = u * n;823
var i = Math.floor(at);824
if (i >= n)825
{ i = n - 1; }826
var t = at - i;827
var a = points[i];828
var b = points[i + 1];829
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };830
};831
832
/** Viewport centre of a field cell (y=0 is the bottom row). */833
Online.cellViewport = function (col, y, rect)834
{835
if (!rect)836
{837
var field = this.playerFieldRect();838
if (!field)839
{ return { x: 0, y: 0 }; }840
rect = field;841
}842
var w = rect.width != null ? rect.width : (rect.right - rect.left);843
var h = rect.height != null ? rect.height : (rect.bottom - rect.top);844
return {845
x: rect.left + ((col + 0.5) / 10) * w,846
y: rect.top + (1 - (y + 0.5) / 13) * h847
};848
};849
850
/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */851
Online.fieldEntry = function (col)852
{853
return this.cellViewport(col == null ? 4.5 : col, 13);854
};855
856
Online.miniCellViewport = function (playerId, col, y)857
{858
var el = this.miniElement(playerId);859
var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);860
var box = canvas || el;861
if (!box || !box.getBoundingClientRect)862
{ return { x: window.innerWidth / 2, y: 48 }; }863
return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());864
};865
866
Online._fallSpeedPx = function (field, duration)867
{868
var px = 40;869
if (field && field.height)870
{ px = field.height / 13; }871
else if (typeof app !== 'undefined' && app.tile)872
{ px = app.tile; }873
var cells = 13 / 3;874
if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)875
{ cells = app.planet.fallSpeed; }876
duration = duration || this.FLIGHT_DURATION;877
// Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).878
return (cells * px * duration) / 3;623
};879
};624
880
625
Online.rememberLandCol = function (id, col)881
Online.rememberLandCol = function (id, col)@@ -687,17 +943,17 @@ Online._miniAnchor = function (playerId, dir)687
943
688
Online._fieldTop = function (col)944
Online._fieldTop = function (col)689
{945
{690
return this._flightStart(col);946
return this.fieldEntry(col);691
};947
};692
948
693
/**949
/**694
* Animate shot results. `locals` is a map of client_id → {col, y, color,950
* Animate shot results. `locals` is a map of client_id → {col, y, color,695
* startX, startY, from_id} in viewport pixels.951
* startX, startY, from_id} in viewport pixels.696
*952
*697
* Visual-only (t1125): a parabolic arc whose scale goes from mini-cell953
* Visual-only: a smooth cubic that leaves the real cell, arcs around698
* to full tile (or the reverse). Enemy-to-enemy arcs stay small and954
* the field, and dives into the landing column at the spawn pose699
* are drawn behind the player's field. Delivery timing is unchanged;955
* (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn700
* a late-seen flight starts mid-arc via `age`.956
* behind the player's field. A late-seen flight starts mid-arc via `age`.701
*/957
*/702
Online.spawnFlights = function (results, locals)958
Online.spawnFlights = function (results, locals)703
{959
{@@ -708,6 +964,8 @@ Online.spawnFlights = function (results, locals)708
{ return; }964
{ return; }709
if (!this._flightSeen)965
if (!this._flightSeen)710
{ this._flightSeen = Object.create(null); }966
{ this._flightSeen = Object.create(null); }967
if (!this._previewIds)968
{ this._previewIds = Object.create(null); }711
var now = performance.now();969
var now = performance.now();712
var full = this._fullTileSize();970
var full = this._fullTileSize();713
for (var i = 0; i < results.length; i++)971
for (var i = 0; i < results.length; i++)@@ -715,7 +973,18 @@ Online.spawnFlights = function (results, locals)715
var r = results[i];973
var r = results[i];716
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));974
var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));717
if (this._flightSeen[sid])975
if (this._flightSeen[sid])718
{ continue; }976
{977
if (this._previewIds[sid])978
{979
var existing = this._findFlight(sid);980
if (existing)981
{982
var meta0 = locals[r.client_id] || locals[sid] || {};983
this.retargetFlight(existing, r, meta0, now);984
}985
}986
continue;987
}719
this._flightSeen[sid] = now;988
this._flightSeen[sid] = now;720
989
721
var meta = locals[r.client_id] || locals[sid] || {};990
var meta = locals[r.client_id] || locals[sid] || {};@@ -742,11 +1011,15 @@ Online.spawnFlights = function (results, locals)742
{ this.rememberLandCol(r.client_id, landCol); }1011
{ this.rememberLandCol(r.client_id, landCol); }743
}1012
}744
1013
1014
var startCol = meta.col != null ? meta.col : r.col;1015
var startY = meta.y != null ? meta.y : r.y;745
var start;1016
var start;746
if (meta.startX != null && isFinite(meta.startX))1017
if (meta.startX != null && isFinite(meta.startX))747
{ start = { x: meta.startX, y: meta.startY }; }1018
{ start = { x: meta.startX, y: meta.startY }; }748
else if (kind === 'player-to-enemy' || kind === 'player-miss')1019
else if (kind === 'player-to-enemy' || kind === 'player-miss')749
{ start = this._flightStart(meta.col != null ? meta.col : r.col); }1020
{ start = this._flightStart(startCol, startY); }1021
else if (startCol != null || startY != null)1022
{ start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 12); }750
else1023
else751
{ start = this._miniAnchor(fromId, 'out'); }1024
{ start = this._miniAnchor(fromId, 'out'); }752
1025
@@ -754,7 +1027,7 @@ Online.spawnFlights = function (results, locals)754
if (miss)1027
if (miss)755
{ end = this._missEnd(start, kind === 'enemy-miss'); }1028
{ end = this._missEnd(start, kind === 'enemy-miss'); }756
else if (kind === 'enemy-to-player')1029
else if (kind === 'enemy-to-player')757
{ end = this._fieldTop(landCol != null ? landCol : 4.5); }1030
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }758
else1031
else759
{ end = this._targetEnd(targetId, start, landCol); }1032
{ end = this._targetEnd(targetId, start, landCol); }760
1033
@@ -815,7 +1088,14 @@ Online.spawnFlights = function (results, locals)815
: this.arcHeight(start, end);1088
: this.arcHeight(start, end);816
var field = this.playerFieldRect();1089
var field = this.playerFieldRect();817
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');1090
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');818
var waypoints = around ? this.waypointsAroundField(start, end, field, height * 0.45) : null;1091
var clearance = Math.max(64, height * 0.45);1092
var endSpeed = this._fallSpeedPx(field, duration / 1000);1093
var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {1094
clearance: clearance,1095
startSpeedPx: endSpeed,1096
endSpeedPx: endSpeed,1097
duration: duration / 10001098
});819
this._flights.push({1099
this._flights.push({820
el: el,1100
el: el,821
start: start,1101
start: start,@@ -824,16 +1104,16 @@ Online.spawnFlights = function (results, locals)824
height: height,1104
height: height,825
t0: t0,1105
t0: t0,826
duration: duration,1106
duration: duration,827
spin: (Math.random() * 2 - 1) * 720,1107
spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),828
miss: miss,1108
miss: miss,829
kind: kind,1109
kind: kind,830
startScale: startScale,1110
startScale: startScale,831
endScale: endScale,1111
endScale: endScale,832
angle: Math.random() * 360,1112
angle: 0,833
id: sid,1113
id: sid,834
landCol: landCol,1114
landCol: landCol,835
field: field,1115
field: field,836
waypoints: waypoints,1116
curve: curve,837
color: flightColor1117
color: flightColor838
});1118
});839
}1119
}@@ -850,30 +1130,17 @@ Online.rememberFlightLocal = function (shot, startX, startY)850
color: shot.color,1130
color: shot.color,851
startX: startX,1131
startX: startX,852
startY: startY,1132
startY: startY,853
from_id: shot.from_id1133
from_id: shot.from_id,1134
land_col: shot.land_col,1135
vy: shot.vy854
};1136
};855
};1137
};856
1138
857
Online._flightStart = function (col)1139
Online._flightStart = function (col, y)858
{1140
{859
var appRef = typeof app !== 'undefined' ? app : null;1141
if (y == null || !isFinite(y))860
if (appRef && appRef.scene && appRef.scene.canvas)1142
{ y = 12; }861
{1143
return this.cellViewport(col == null ? 4.5 : col, y);862
var canvas = appRef.scene.canvas;863
var rect = canvas.getBoundingClientRect();864
var c = col == null ? 4.5 : col;865
return {866
x: rect.left + (c + 0.5) * (rect.width / 10),867
y: rect.top + 4868
};869
}870
var field = document.querySelector('canvas');871
if (field)872
{873
var rect = field.getBoundingClientRect();874
return { x: rect.left + rect.width / 2, y: rect.top };875
}876
return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };877
};1144
};878
1145
879
Online._targetEnd = function (targetId, start, col)1146
Online._targetEnd = function (targetId, start, col)@@ -881,12 +1148,8 @@ Online._targetEnd = function (targetId, start, col)881
var el = targetId && this.miniElement(targetId);1148
var el = targetId && this.miniElement(targetId);882
if (el)1149
if (el)883
{1150
{884
var canvas = el.querySelector('canvas') || el;1151
// Slightly inside the mini, in the landing column (t1135).885
var r = canvas.getBoundingClientRect();1152
return this.miniCellViewport(targetId, col, 12);886
var x = r.left + r.width / 2;887
if (col != null && isFinite(col))888
{ x = r.left + ((col + 0.5) / 10) * r.width; }889
return { x: x, y: r.top + 4 };890
}1153
}891
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };1154
return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };892
};1155
};@@ -921,6 +1184,251 @@ Online._hitCtrl = function (start, end)921
};1184
};922
};1185
};923
1186
1187
Online._findFlight = function (sid)1188
{1189
sid = String(sid);1190
if (!this._flights)1191
{ return null; }1192
for (var i = 0; i < this._flights.length; i++)1193
{1194
if (String(this._flights[i].id) === sid)1195
{ return this._flights[i]; }1196
}1197
return null;1198
};1199
1200
/**1201
* Early visual takeover: a flying rocket near the top of a field1202
* becomes a flight sprite at its exact cell, so it is seen flying1203
* *out* rather than popping in above the canvas (t1134). When the1204
* shot is later dispatched, `retargetFlight` picks up from the1205
* current pose and aims at the real landing column.1206
*/1207
Online.previewExit = function (info)1208
{1209
if (!info || info.id == null)1210
{ return; }1211
var sid = String(info.id);1212
if (!this._flights)1213
{ this._flights = []; }1214
if (!this._flightSeen)1215
{ this._flightSeen = Object.create(null); }1216
if (!this._previewIds)1217
{ this._previewIds = Object.create(null); }1218
if (this._previewIds[sid] || this._flightSeen[sid])1219
{ return; }1220
var front = document.getElementById('flights');1221
if (!front || !info.start)1222
{ return; }1223
var start = info.start;1224
var field = this.playerFieldRect();1225
var clearance = 80;1226
if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)1227
{ clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }1228
var apexY = (field ? field.top : start.y) - clearance;1229
if (apexY < 8)1230
{ apexY = Math.max(8, start.y - 80); }1231
var end = { x: start.x, y: apexY };1232
var duration = this.FLIGHT_DURATION * 1000;1233
var full = this._fullTileSize();1234
var el = document.createElement('img');1235
el.src = colorSpriteUrl(info.color);1236
el.alt = '';1237
el.className = 'flight';1238
el.style.width = full + 'px';1239
el.style.height = full + 'px';1240
front.appendChild(el);1241
var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);1242
var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {1243
clearance: clearance,1244
startSpeedPx: endSpeed,1245
endSpeedPx: endSpeed1246
});1247
var now = performance.now();1248
var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;1249
if (mini < 0.12)1250
{ mini = 0.2; }1251
this._flights.push({1252
el: el,1253
start: start,1254
end: end,1255
ctrl: null,1256
height: clearance,1257
t0: now,1258
duration: duration,1259
spin: (Math.random() * 2 - 1) * 90,1260
miss: false,1261
kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',1262
startScale: mini,1263
endScale: mini,1264
angle: 0,1265
id: sid,1266
landCol: null,1267
field: field,1268
curve: curve,1269
preview: true,1270
color: info.color,1271
from_id: info.from_id || null1272
});1273
this._previewIds[sid] = true;1274
this._flightSeen[sid] = now;1275
};1276
1277
/** True while a field sprite should stay hidden — the flight is its visual. */1278
Online.hasExitVisual = function (id)1279
{1280
if (id == null)1281
{ return false; }1282
var sid = String(id);1283
if (this._previewIds && this._previewIds[sid])1284
{ return true; }1285
var f = this._findFlight(sid);1286
if (!f || f.miss)1287
{ return false; }1288
var raw = (performance.now() - f.t0) / f.duration;1289
return raw < 0.4;1290
};1291
1292
/**1293
* Once the shot is scored, pick up the preview at its current pose1294
* and fly the rest of the way to the real end (no jump).1295
*/1296
Online.retargetFlight = function (f, r, meta, now)1297
{1298
now = now || performance.now();1299
meta = meta || {};1300
var raw = (now - f.t0) / f.duration;1301
if (raw < 0)1302
{ raw = 0; }1303
if (raw > 0.95)1304
{ raw = 0.95; }1305
var u = this.smoothParam(raw, 0.9, 0.9);1306
var pt = f.curve1307
? this.curvePoint(f.curve, u)1308
: { x: f.start.x, y: f.start.y };1309
var curScale = f.startScale + (f.endScale - f.startScale) * u;1310
1311
var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;1312
var targetId = r.target_id != null ? r.target_id : r.to_user;1313
var miss = !!r.miss;1314
var kind = this.flightKind(fromId, targetId, miss);1315
var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;1316
1317
var landCol = null;1318
if (r.land_col != null && isFinite(r.land_col))1319
{ landCol = r.land_col | 0; }1320
else if (meta.land_col != null && isFinite(meta.land_col))1321
{ landCol = meta.land_col | 0; }1322
else if (f.landCol != null)1323
{ landCol = f.landCol; }1324
if (landCol != null)1325
{ this.rememberLandCol(String(f.id), landCol); }1326
1327
var end;1328
if (miss)1329
{ end = this._missEnd(pt, kind === 'enemy-miss'); }1330
else if (kind === 'enemy-to-player')1331
{ end = this.fieldEntry(landCol != null ? landCol : 4.5); }1332
else1333
{ end = this._targetEnd(targetId, pt, landCol); }1334
1335
var flightColor = miss1336
? (r.color != null ? r.color : meta.color)1337
: -1;1338
if (f.el && flightColor !== f.color)1339
{ f.el.src = colorSpriteUrl(flightColor); }1340
1341
var full = this._fullTileSize();1342
var mini = this._miniCellSize(fromId || targetId) / full;1343
if (mini < 0.12)1344
{ mini = 0.2; }1345
var endScale;1346
if (kind === 'player-to-enemy')1347
{ endScale = mini; }1348
else if (kind === 'enemy-to-player')1349
{ endScale = 1; }1350
else if (kind === 'enemy-to-enemy')1351
{ endScale = mini; }1352
else1353
{ endScale = 0; }1354
1355
var field = this.playerFieldRect();1356
var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');1357
var height = miss1358
? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))1359
: this.arcHeight(pt, end);1360
var clearance = Math.max(64, height * 0.45);1361
var endSpeed = this._fallSpeedPx(field, duration / 1000);1362
var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {1363
clearance: clearance,1364
startSpeedPx: endSpeed,1365
endSpeedPx: endSpeed1366
});1367
1368
f.start = pt;1369
f.end = end;1370
f.t0 = now;1371
f.duration = duration;1372
f.curve = curve;1373
f.ctrl = miss ? this._missCtrl(pt, end) : null;1374
f.height = height;1375
f.miss = miss;1376
f.kind = kind;1377
f.startScale = curScale;1378
f.endScale = endScale;1379
f.landCol = landCol;1380
f.field = field;1381
f.preview = false;1382
f.color = flightColor;1383
f.from_id = fromId;1384
if (this._previewIds)1385
{ delete this._previewIds[String(f.id)]; }1386
1387
if (kind === 'enemy-to-enemy' && f.el)1388
{1389
var back = document.getElementById('flights-back');1390
if (back && f.el.parentNode !== back)1391
{1392
f.el.className = 'flight flight-behind';1393
back.appendChild(f.el);1394
}1395
}1396
};1397
1398
/** Point and (optional) derivative of a flight at parameter u. */1399
Online.flightPointAt = function (f, u)1400
{1401
if (!f)1402
{ return { x: 0, y: 0 }; }1403
if (f.curve)1404
{ return this.curvePoint(f.curve, u); }1405
if (f.miss && f.ctrl)1406
{1407
var e = u;1408
var mt = 1 - e;1409
return {1410
x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,1411
y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y1412
};1413
}1414
return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);1415
};1416
1417
Online.pointAllowedOnArc = function (p, field, start, end, slop)1418
{1419
if (!this.pointInFieldInterior(p.x, p.y, field, slop))1420
{ return true; }1421
if (!field)1422
{ return true; }1423
var w = (field.right - field.left) / 10;1424
var corridor = w * 0.7;1425
if (start && Math.abs(p.x - start.x) <= corridor)1426
{ return true; }1427
if (end && Math.abs(p.x - end.x) <= corridor)1428
{ return true; }1429
return false;1430
};1431
924
Online.tickFlights = function (now)1432
Online.tickFlights = function (now)925
{1433
{926
now = now || performance.now();1434
now = now || performance.now();@@ -933,11 +1441,14 @@ Online.tickFlights = function (now)933
{1441
{934
if (f.el && f.el.parentNode)1442
if (f.el && f.el.parentNode)935
{ f.el.parentNode.removeChild(f.el); }1443
{ f.el.parentNode.removeChild(f.el); }1444
if (this._previewIds)1445
{ delete this._previewIds[String(f.id)]; }936
continue;1446
continue;937
}1447
}938
if (raw < 0)1448
if (raw < 0)939
{ raw = 0; }1449
{ raw = 0; }940
var u = this.easeInOutCubic(raw);1450
// Non-zero endpoint speed so the handoff matches fallSpeed (t1135).1451
var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, 0.85, 0.85);941
var x, y;1452
var x, y;942
if (f.miss && f.ctrl)1453
if (f.miss && f.ctrl)943
{1454
{@@ -946,21 +1457,15 @@ Online.tickFlights = function (now)946
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;1457
x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;947
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;1458
y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;948
}1459
}949
else if (f.waypoints && f.waypoints.length > 2)1460
else if (f.curve)950
{1461
{951
var pt = this.pointOnPath(f.waypoints, u);1462
var pt = this.curvePoint(f.curve, u);952
x = pt.x;953
y = pt.y;954
}955
else if (f.waypoints && f.field)956
{957
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);958
x = pt.x;1463
x = pt.x;959
y = pt.y;1464
y = pt.y;960
}1465
}961
else1466
else962
{1467
{963
var pt = this.arcPoint(f.start, f.end, u, f.height || 80);1468
var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);964
x = pt.x;1469
x = pt.x;965
y = pt.y;1470
y = pt.y;966
}1471
}@@ -1001,6 +1506,7 @@ Online.clearFlights = function ()1001
this._flightLocals = {};1506
this._flightLocals = {};1002
this._flightSeen = Object.create(null);1507
this._flightSeen = Object.create(null);1003
this._pendingLandCol = Object.create(null);1508
this._pendingLandCol = Object.create(null);1509
this._previewIds = Object.create(null);1004
};1510
};1005
1511
1006
if (typeof globalThis !== 'undefined')1512
if (typeof globalThis !== 'undefined')@@ -100,7 +100,7 @@ describe('Around-field flight path (t1128)', () =>
100
100
const start = { x: 400, y: 80 };
101
101
const end = { x: 600, y: field.top + 4 };
102
102
const pts = Online.waypointsAroundField(start, end, field, 72);
103
assert.equal(pts.length, 2, 'no extra waypoints when both ends are above');
103
assert.ok(pts.length >= 2);
104
104
for (let i = 0; i <= 16; i++)
105
105
{
106
106
const p = Online.aroundFieldPoint(start, end, i / 16, field, 72);
@@ -144,3 +144,129 @@ describe('takeLandCol consistency (t1126)', () =>
144
144
assert.equal(Online.takeLandCol({ id: 1 }), null);
145
145
});
146
146
});
147
148
149
describe('Smooth C1 arcs (t1134)', () =>
150
{
151
const field = { left: 335, top: 173, right: 335 + 550, bottom: 173 + 715, width: 550, height: 715 };
152
153
function entry (col)
154
{
155
return Online.cellViewport(col, 13, field);
156
}
157
158
function cell (col, y)
159
{
160
return Online.cellViewport(col, y, field);
161
}
162
163
it('is a C1 curve: tangents and speeds match at joints, no corners', () =>
164
{
165
const start = { x: 250, y: 700 };
166
const end = entry(3);
167
const curve = Online.makeAroundCurve(start, end, field, { clearance: 80 });
168
assert.ok(curve.segments && curve.segments.length >= 2, 'multi-segment around-field path');
169
const n = curve.segments.length;
170
for (let i = 1; i < n; i++)
171
{
172
const u = i / n;
173
const left = Online.curveDeriv(curve, u - 1e-6);
174
const right = Online.curveDeriv(curve, u + 1e-6);
175
const aL = Math.atan2(left.y, left.x);
176
const aR = Math.atan2(right.y, right.x);
177
let da = Math.abs(aR - aL);
178
if (da > Math.PI)
179
{ da = 2 * Math.PI - da; }
180
assert.ok(da < 0.02, 'joint ' + i + ' direction jump ' + da);
181
const sL = Math.hypot(left.x, left.y);
182
const sR = Math.hypot(right.x, right.y);
183
assert.ok(Math.abs(sL - sR) / Math.max(sL, 1) < 0.05,
184
'joint ' + i + ' speed jump ' + sL + ' vs ' + sR);
185
}
186
// Densely sampled tangent never snaps by a large angle (no corner).
187
let prev = null;
188
let maxDa = 0;
189
for (let i = 0; i <= 80; i++)
190
{
191
const d = Online.curveDeriv(curve, i / 80);
192
const a = Math.atan2(d.y, d.x);
193
if (prev != null)
194
{
195
let da = Math.abs(a - prev);
196
if (da > Math.PI)
197
{ da = 2 * Math.PI - da; }
198
if (da > maxDa)
199
{ maxDa = da; }
200
}
201
prev = a;
202
}
203
assert.ok(maxDa < 0.35, 'max step angle ' + maxDa + ' looks like a corner');
204
});
205
206
it('leaves a mid-field cell going up and stays in launch/land corridors', () =>
207
{
208
const start = cell(6, 12);
209
const end = { x: field.right + 80, y: 700 };
210
assert.ok(start.y > field.top, 'start is inside the field (below the top edge)');
211
assert.ok(start.y < field.top + field.height * 0.2, 'start is near the top row');
212
const d0 = Online.curveDeriv(Online.makeAroundCurve(start, end, field, { clearance: 80 }), 0);
213
assert.ok(d0.y < 0, 'initial tangent is upward, vy=' + d0.y);
214
for (let i = 0; i <= 32; i++)
215
{
216
const p = Online.aroundFieldPoint(start, end, i / 32, field, 80);
217
assert.equal(Online.pointAllowedOnArc(p, field, start, end), true,
218
'u=' + (i / 32) + ' at ' + p.x + ',' + p.y + ' is not allowed');
219
}
220
});
221
222
it('dives into the landing column at the spawn pose with downward fallSpeed (t1135)', () =>
223
{
224
const start = { x: 250, y: 700 };
225
const end = entry(3);
226
// Spawn pose is half a tile above the canvas top (y = 13).
227
assert.ok(Math.abs(end.y - (field.top - 0.5 / 13 * field.height)) < 0.5);
228
assert.ok(Math.abs(end.x - (field.left + 3.5 / 10 * field.width)) < 0.5);
229
const duration = 1.2;
230
const fallPx = (13 / 3) * (field.height / 13);
231
const endSpeedPx = (fallPx * duration) / 3;
232
const curve = Online.makeAroundCurve(start, end, field, {
233
clearance: 80, endSpeedPx: endSpeedPx, duration: duration
234
});
235
const landed = Online.curvePoint(curve, 1);
236
assert.ok(Math.abs(landed.x - end.x) < 0.5);
237
assert.ok(Math.abs(landed.y - end.y) < 0.5);
238
const d1 = Online.curveDeriv(curve, 1);
239
assert.ok(d1.y > 0, 'end tangent points down into the column');
240
assert.ok(Math.abs(d1.x) < 20, 'end tangent is vertical, dx=' + d1.x);
241
const v1 = 0.85;
242
const pxPerSec = d1.y * v1 / duration;
243
assert.ok(Math.abs(pxPerSec - fallPx) / fallPx < 0.08,
244
'arrival ' + pxPerSec + ' px/s vs fallSpeed ' + fallPx);
245
});
246
247
it('smoothParam has non-zero endpoint derivatives (no visual stop)', () =>
248
{
249
const v0 = 0.85;
250
const v1 = 0.85;
251
const mid = Online.smoothParam(0.5, v0, v1);
252
assert.ok(mid > 0.4 && mid < 0.6);
253
const d0 = (Online.smoothParam(0.001, v0, v1) - Online.smoothParam(0, v0, v1)) / 0.001;
254
const d1 = (Online.smoothParam(1, v0, v1) - Online.smoothParam(0.999, v0, v1)) / 0.001;
255
assert.ok(d0 > 0.5, 'start rate ' + d0);
256
assert.ok(d1 > 0.5, 'end rate ' + d1);
257
assert.equal(Online.smoothParam(0, 1, 1), 0);
258
assert.equal(Online.smoothParam(1, 1, 1), 1);
259
assert.ok(Math.abs(Online.smoothParam(0.5, 1, 1) - 0.5) < 1e-9);
260
});
261
262
it('cellViewport matches placeTile centres (y=0 at the bottom)', () =>
263
{
264
const rect = { left: 100, top: 50, width: 390, height: 507, right: 490, bottom: 557 };
265
const bottom = Online.cellViewport(0, 0, rect);
266
assert.ok(Math.abs(bottom.x - (100 + 0.5 / 10 * 390)) < 0.01);
267
assert.ok(Math.abs(bottom.y - (50 + (1 - 0.5 / 13) * 507)) < 0.01);
268
const spawn = Online.cellViewport(4, 13, rect);
269
assert.ok(spawn.y < rect.top, 'spawn of a falling block is just above the canvas');
270
assert.ok(rect.top - spawn.y - 0.5 / 13 * 507 < 0.01);
271
});
272
});
@@ -100,7 +100,7 @@ describe('Around-field flight path (t1128)', () =>100
const start = { x: 400, y: 80 };100
const start = { x: 400, y: 80 };101
const end = { x: 600, y: field.top + 4 };101
const end = { x: 600, y: field.top + 4 };102
const pts = Online.waypointsAroundField(start, end, field, 72);102
const pts = Online.waypointsAroundField(start, end, field, 72);103
assert.equal(pts.length, 2, 'no extra waypoints when both ends are above');103
assert.ok(pts.length >= 2);104
for (let i = 0; i <= 16; i++)104
for (let i = 0; i <= 16; i++)105
{105
{106
const p = Online.aroundFieldPoint(start, end, i / 16, field, 72);106
const p = Online.aroundFieldPoint(start, end, i / 16, field, 72);@@ -144,3 +144,129 @@ describe('takeLandCol consistency (t1126)', () =>144
assert.equal(Online.takeLandCol({ id: 1 }), null);144
assert.equal(Online.takeLandCol({ id: 1 }), null);145
});145
});146
});146
});147
148
149
describe('Smooth C1 arcs (t1134)', () =>150
{151
const field = { left: 335, top: 173, right: 335 + 550, bottom: 173 + 715, width: 550, height: 715 };152
153
function entry (col)154
{155
return Online.cellViewport(col, 13, field);156
}157
158
function cell (col, y)159
{160
return Online.cellViewport(col, y, field);161
}162
163
it('is a C1 curve: tangents and speeds match at joints, no corners', () =>164
{165
const start = { x: 250, y: 700 };166
const end = entry(3);167
const curve = Online.makeAroundCurve(start, end, field, { clearance: 80 });168
assert.ok(curve.segments && curve.segments.length >= 2, 'multi-segment around-field path');169
const n = curve.segments.length;170
for (let i = 1; i < n; i++)171
{172
const u = i / n;173
const left = Online.curveDeriv(curve, u - 1e-6);174
const right = Online.curveDeriv(curve, u + 1e-6);175
const aL = Math.atan2(left.y, left.x);176
const aR = Math.atan2(right.y, right.x);177
let da = Math.abs(aR - aL);178
if (da > Math.PI)179
{ da = 2 * Math.PI - da; }180
assert.ok(da < 0.02, 'joint ' + i + ' direction jump ' + da);181
const sL = Math.hypot(left.x, left.y);182
const sR = Math.hypot(right.x, right.y);183
assert.ok(Math.abs(sL - sR) / Math.max(sL, 1) < 0.05,184
'joint ' + i + ' speed jump ' + sL + ' vs ' + sR);185
}186
// Densely sampled tangent never snaps by a large angle (no corner).187
let prev = null;188
let maxDa = 0;189
for (let i = 0; i <= 80; i++)190
{191
const d = Online.curveDeriv(curve, i / 80);192
const a = Math.atan2(d.y, d.x);193
if (prev != null)194
{195
let da = Math.abs(a - prev);196
if (da > Math.PI)197
{ da = 2 * Math.PI - da; }198
if (da > maxDa)199
{ maxDa = da; }200
}201
prev = a;202
}203
assert.ok(maxDa < 0.35, 'max step angle ' + maxDa + ' looks like a corner');204
});205
206
it('leaves a mid-field cell going up and stays in launch/land corridors', () =>207
{208
const start = cell(6, 12);209
const end = { x: field.right + 80, y: 700 };210
assert.ok(start.y > field.top, 'start is inside the field (below the top edge)');211
assert.ok(start.y < field.top + field.height * 0.2, 'start is near the top row');212
const d0 = Online.curveDeriv(Online.makeAroundCurve(start, end, field, { clearance: 80 }), 0);213
assert.ok(d0.y < 0, 'initial tangent is upward, vy=' + d0.y);214
for (let i = 0; i <= 32; i++)215
{216
const p = Online.aroundFieldPoint(start, end, i / 32, field, 80);217
assert.equal(Online.pointAllowedOnArc(p, field, start, end), true,218
'u=' + (i / 32) + ' at ' + p.x + ',' + p.y + ' is not allowed');219
}220
});221
222
it('dives into the landing column at the spawn pose with downward fallSpeed (t1135)', () =>223
{224
const start = { x: 250, y: 700 };225
const end = entry(3);226
// Spawn pose is half a tile above the canvas top (y = 13).227
assert.ok(Math.abs(end.y - (field.top - 0.5 / 13 * field.height)) < 0.5);228
assert.ok(Math.abs(end.x - (field.left + 3.5 / 10 * field.width)) < 0.5);229
const duration = 1.2;230
const fallPx = (13 / 3) * (field.height / 13);231
const endSpeedPx = (fallPx * duration) / 3;232
const curve = Online.makeAroundCurve(start, end, field, {233
clearance: 80, endSpeedPx: endSpeedPx, duration: duration234
});235
const landed = Online.curvePoint(curve, 1);236
assert.ok(Math.abs(landed.x - end.x) < 0.5);237
assert.ok(Math.abs(landed.y - end.y) < 0.5);238
const d1 = Online.curveDeriv(curve, 1);239
assert.ok(d1.y > 0, 'end tangent points down into the column');240
assert.ok(Math.abs(d1.x) < 20, 'end tangent is vertical, dx=' + d1.x);241
const v1 = 0.85;242
const pxPerSec = d1.y * v1 / duration;243
assert.ok(Math.abs(pxPerSec - fallPx) / fallPx < 0.08,244
'arrival ' + pxPerSec + ' px/s vs fallSpeed ' + fallPx);245
});246
247
it('smoothParam has non-zero endpoint derivatives (no visual stop)', () =>248
{249
const v0 = 0.85;250
const v1 = 0.85;251
const mid = Online.smoothParam(0.5, v0, v1);252
assert.ok(mid > 0.4 && mid < 0.6);253
const d0 = (Online.smoothParam(0.001, v0, v1) - Online.smoothParam(0, v0, v1)) / 0.001;254
const d1 = (Online.smoothParam(1, v0, v1) - Online.smoothParam(0.999, v0, v1)) / 0.001;255
assert.ok(d0 > 0.5, 'start rate ' + d0);256
assert.ok(d1 > 0.5, 'end rate ' + d1);257
assert.equal(Online.smoothParam(0, 1, 1), 0);258
assert.equal(Online.smoothParam(1, 1, 1), 1);259
assert.ok(Math.abs(Online.smoothParam(0.5, 1, 1) - 0.5) < 1e-9);260
});261
262
it('cellViewport matches placeTile centres (y=0 at the bottom)', () =>263
{264
const rect = { left: 100, top: 50, width: 390, height: 507, right: 490, bottom: 557 };265
const bottom = Online.cellViewport(0, 0, rect);266
assert.ok(Math.abs(bottom.x - (100 + 0.5 / 10 * 390)) < 0.01);267
assert.ok(Math.abs(bottom.y - (50 + (1 - 0.5 / 13) * 507)) < 0.01);268
const spawn = Online.cellViewport(4, 13, rect);269
assert.ok(spawn.y < rect.top, 'spawn of a falling block is just above the canvas');270
assert.ok(rect.top - spawn.y - 0.5 / 13 * 507 < 0.01);271
});272
});@@ -13,6 +13,8 @@ from playwright.sync_api import sync_playwright
13
13
ROOT = Path("/workspace/meteors")
14
14
OUT = Path("/workspace/meteors-shots")
15
15
OUT.mkdir(parents=True, exist_ok=True)
16
VIDEO = Path("/workspace/meteors-video")
17
VIDEO.mkdir(parents=True, exist_ok=True)
16
18
CHROME = "/usr/bin/google-chrome"
17
19
CHROME_ARGS = [
18
20
"--use-gl=angle",
@@ -121,37 +123,36 @@ INJECT_FLIGHTS = """(age) => {
121
123
if (age == null) age = 0.55;
122
124
const plan = app.miniLayout;
123
125
const field = app.scene.canvas.getBoundingClientRect();
124
function anchor(id, inner) {
126
function miniCell(id, col, y) {
127
if (Online.miniCellViewport) {
128
const p = Online.miniCellViewport(id, col, y);
129
if (p && isFinite(p.x)) return p;
130
}
125
131
const el = document.querySelector('#minis .mini[data-player="' + id + '"] canvas');
126
132
if (!el) return { x: 80, y: 80 };
127
const r = el.getBoundingClientRect();
128
if (plan && plan.mode === 'sides') {
129
return { x: r.left + r.width / 2, y: r.top + 4 };
130
}
131
return { x: r.left + r.width / 2, y: inner ? r.bottom : r.top };
133
return Online.cellViewport(col, y, el.getBoundingClientRect());
132
134
}
133
135
const bots = (app.battle.bots || []).map(b => b.id);
134
136
const a = bots[0] || 'bot-1';
135
137
const b = bots[1] || bots[0] || 'bot-2';
136
138
const landCol = 3;
137
const pStart = {
138
x: field.left + ((4 + 0.5) / 10) * field.width,
139
y: field.top + 4
140
};
139
// Launch from the real top-row cell, not from above the canvas (t1134).
140
const pStart = Online.cellViewport(4, 12, field);
141
const pEnd = Online.fieldEntry ? Online.fieldEntry(landCol) : Online.cellViewport(landCol, 13, field);
141
142
if (typeof Online.clearFlights === 'function') Online.clearFlights();
142
143
const flights = [
143
{ id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol },
144
{ id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol },
145
{ id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7 },
146
{ id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45) }
144
{ id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol, col: 4, y: 12 },
145
{ id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol, col: 2, y: 12 },
146
{ id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7, col: 5, y: 12 },
147
{ id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45), col: 1, y: 12 }
147
148
];
148
const aOut = anchor(a, true);
149
const bOut = anchor(b, true);
149
const aOut = miniCell(a, 2, 12);
150
const bOut = miniCell(b, 1, 12);
150
151
const locals = {
151
'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, land_col: landCol },
152
'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, land_col: landCol },
153
'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, land_col: 7 },
154
'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y }
152
'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, y: 12, land_col: landCol },
153
'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, col: 2, y: 12, land_col: landCol },
154
'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, col: 5, y: 12, land_col: 7 },
155
'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y, col: 1, y: 12 }
155
156
};
156
157
Online.spawnFlights(flights, locals);
157
158
Online.tickFlights();
@@ -167,31 +168,22 @@ INJECT_FLIGHTS = """(age) => {
167
168
}));
168
169
const kinds = (Online._flights || []).map(f => {
169
170
const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));
170
const u = Online.easeInOutCubic(raw);
171
let pt;
172
if (f.waypoints && f.waypoints.length > 2)
173
{ pt = Online.pointOnPath(f.waypoints, u); }
174
else if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')
175
{ pt = Online.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); }
176
else
177
{ pt = Online.arcPoint(f.start, f.end, u, f.height || 80); }
171
const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);
172
const pt = Online.flightPointAt(f, u);
178
173
const samples = [];
179
174
if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')
180
175
{
181
176
for (let i = 0; i <= 16; i++)
182
177
{
183
178
const su = i / 16;
184
let sp;
185
if (f.waypoints && f.waypoints.length > 2)
186
{ sp = Online.pointOnPath(f.waypoints, su); }
187
else
188
{ sp = Online.aroundFieldPoint(f.start, f.end, su, f.field, (f.height || 80) * 0.45); }
189
samples.push({
190
u: su, x: sp.x, y: sp.y,
191
inside: Online.pointInFieldInterior(sp.x, sp.y, f.field)
192
});
179
const sp = Online.flightPointAt(f, su);
180
const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));
181
const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);
182
samples.push({ u: su, x: sp.x, y: sp.y, inside: inside, allowed: allowed });
193
183
}
194
184
}
185
const d0 = f.curve ? Online.curveDeriv(f.curve, 0) : null;
186
const d1 = f.curve ? Online.curveDeriv(f.curve, 1) : null;
195
187
return {
196
188
kind: f.kind, miss: f.miss,
197
189
startScale: f.startScale, endScale: f.endScale,
@@ -199,22 +191,32 @@ INJECT_FLIGHTS = """(age) => {
199
191
src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',
200
192
color: f.color,
201
193
landCol: f.landCol,
194
start: f.start,
202
195
end: f.end,
203
196
pos: pt,
204
197
samples: samples,
205
insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false
198
insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false,
199
hasCurve: !!f.curve,
200
segments: (f.curve && f.curve.segments) ? f.curve.segments.length : (f.curve ? 1 : 0),
201
d0: d0, d1: d1
206
202
};
207
203
});
208
204
const expectedEndX = field.left + ((landCol + 0.5) / 10) * field.width;
205
const expectedEndY = field.top + (1 - (13.5) / 13) * field.height;
206
const expectedStartY = field.top + (1 - (12.5) / 13) * field.height;
209
207
return {
210
208
front: front.length,
211
209
back: back.length,
212
210
kinds,
213
211
expectedEndX,
214
field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom },
212
expectedEndY,
213
expectedStartY,
214
field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom,
215
width: field.width, height: field.height },
215
216
pad: field.top,
216
217
hudH: app.hudH,
217
mode: plan.mode
218
mode: plan.mode,
219
tile: app.tile
218
220
};
219
221
}"""
220
222
@@ -322,11 +324,22 @@ def assert_flights(info, tag, expect_behind=True, expect_around=True):
322
324
f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")
323
325
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
324
326
f"{tag}: player-to-enemy is grey (src={k.get('src')} color={k.get('color')})")
327
if k.get("start") and info.get("expectedStartY") is not None:
328
check(k["start"]["y"] > info["field"]["top"],
329
f"{tag}: player-to-enemy starts inside the field "
330
f"(start.y={k['start']['y']:.1f} field.top={info['field']['top']:.1f})")
331
check(abs(k["start"]["y"] - info["expectedStartY"]) < 8,
332
f"{tag}: player-to-enemy starts at the top-row cell "
333
f"(start.y={k['start']['y']:.1f} expected={info['expectedStartY']:.1f})")
334
if k.get("d0"):
335
check(k["d0"]["y"] < 0,
336
f"{tag}: player-to-enemy leaves going up (d0.y={k['d0']['y']:.1f})")
337
check(k.get("hasCurve"), f"{tag}: player-to-enemy uses a smooth curve")
325
338
if expect_around:
326
inside = [s for s in (k.get("samples") or []) if s.get("inside")]
327
check(len(inside) == 0,
328
f"{tag}: player-to-enemy path stays outside the field "
329
f"({len(inside)} interior samples {inside[:3]})")
339
forbidden = [s for s in (k.get("samples") or []) if s.get("inside") and not s.get("allowed")]
340
check(len(forbidden) == 0,
341
f"{tag}: player-to-enemy stays in launch/land corridors "
342
f"({len(forbidden)} forbidden {forbidden[:3]})")
330
343
if "enemy-to-player" in kinds:
331
344
k = kinds["enemy-to-player"]
332
345
check(k["endScale"] > k["startScale"],
@@ -337,15 +350,26 @@ def assert_flights(info, tag, expect_behind=True, expect_around=True):
337
350
check(abs(k["end"]["x"] - info["expectedEndX"]) < 3,
338
351
f"{tag}: arc ends at column 3 "
339
352
f"(end.x={k['end']['x']:.1f} expected={info['expectedEndX']:.1f})")
353
if k.get("end") and info.get("expectedEndY") is not None:
354
check(abs(k["end"]["y"] - info["expectedEndY"]) < 8,
355
f"{tag}: arc ends at the spawn pose (y=13) "
356
f"(end.y={k['end']['y']:.1f} expected={info['expectedEndY']:.1f})")
357
check(k["end"]["y"] < info["field"]["top"] + 2,
358
f"{tag}: incoming end is at/above the canvas top "
359
f"(end.y={k['end']['y']:.1f} field.top={info['field']['top']:.1f})")
360
if k.get("d1"):
361
check(k["d1"]["y"] > 0,
362
f"{tag}: enemy-to-player arrives going down (d1.y={k['d1']['y']:.1f})")
363
check(abs(k.get("endScale", 0) - 1) < 0.05,
364
f"{tag}: incoming ends at full tile scale ({k.get('endScale')})")
365
check(k.get("hasCurve"), f"{tag}: enemy-to-player uses a smooth curve")
340
366
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
341
367
f"{tag}: enemy-to-player is grey (src={k.get('src')} color={k.get('color')})")
342
368
if expect_around and k.get("samples"):
343
inside = [s for s in k["samples"] if s.get("inside")]
344
check(len(inside) == 0,
345
f"{tag}: enemy-to-player path stays outside the field "
346
f"({len(inside)} interior samples {inside[:3]})")
347
check(not k.get("insideNow"),
348
f"{tag}: enemy-to-player mid-arc is not over the field interior")
369
forbidden = [s for s in k["samples"] if s.get("inside") and not s.get("allowed")]
370
check(len(forbidden) == 0,
371
f"{tag}: enemy-to-player stays in launch/land corridors "
372
f"({len(forbidden)} forbidden {forbidden[:3]})")
349
373
if "enemy-to-enemy" in kinds:
350
374
k = kinds["enemy-to-enemy"]
351
375
check(abs(k["startScale"] - k["endScale"]) < 0.05,
@@ -387,25 +411,59 @@ def run_viewport(browser, url, name, width, height, is_mobile, round_n, expect_m
387
411
n=n_minis)
388
412
else:
389
413
assert_top(info, name)
390
shot(page, f"t1127-{name}-layout.png")
414
shot(page, f"t1134-{name}-layout.png")
391
415
392
416
flights = page.evaluate(INJECT_FLIGHTS, 0.55)
393
print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'hudH', 'mode') if k in flights})
417
print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'expectedEndY', 'expectedStartY', 'hudH', 'mode') if k in flights})
394
418
for knd in flights["kinds"]:
395
419
print(f" {knd['kind']}: color={knd.get('color')} landCol={knd.get('landCol')} "
396
f"src={knd.get('src')} insideNow={knd.get('insideNow')} "
397
f"end={knd.get('end')} pos={knd.get('pos')}")
420
f"src={knd.get('src')} curve={knd.get('hasCurve')}/{knd.get('segments')} "
421
f"start={knd.get('start')} end={knd.get('end')} pos={knd.get('pos')}")
398
422
assert_flights(flights, name)
399
shot(page, f"t1127-{name}-midarc.png")
423
shot(page, f"t1134-{name}-midarc.png")
400
424
401
425
if name in ("1024x532-3bots", "1920x1080-8bots", "desktop-wide"):
402
for age, label in ((0.25, "early"), (0.85, "late")):
426
for age, label in ((0.18, "early"), (0.85, "late")):
403
427
page.evaluate(INJECT_FLIGHTS, age)
404
shot(page, f"t1127-{name}-midarc-{label}.png")
428
shot(page, f"t1134-{name}-midarc-{label}.png")
429
context.close()
430
431
432
def record_arcs_video(browser, url):
433
"""A short webm of two volleys flying out, over, and into the field (t1134/t1135)."""
434
VIDEO.mkdir(parents=True, exist_ok=True)
435
dest = VIDEO / "t1134-arcs-1920x1080.webm"
436
context = browser.new_context(
437
viewport={"width": 1920, "height": 1080},
438
device_scale_factor=1,
439
record_video_dir=str(VIDEO / "_raw"),
440
record_video_size={"width": 1920, "height": 1080},
441
)
442
page = context.new_page()
443
open_offline(page, url, round_n=25)
444
page.wait_for_timeout(400)
445
# Live volleys at age 0 so tickFlights animates them in the game loop.
446
page.evaluate(INJECT_FLIGHTS, 0)
447
page.wait_for_timeout(1300)
448
page.evaluate(INJECT_FLIGHTS, 0)
449
page.wait_for_timeout(1400)
450
page.close()
405
451
context.close()
452
# Playwright writes the webm next to the context; move it into place.
453
raw = list((VIDEO / "_raw").glob("*.webm"))
454
if raw:
455
raw[0].replace(dest)
456
print(f"wrote {dest} ({dest.stat().st_size} bytes)")
457
else:
458
FAILURES.append("video: no webm produced")
459
print("FAIL video: no webm produced")
460
return
461
if dest.stat().st_size < 10000:
462
FAILURES.append(f"video: suspiciously small ({dest.stat().st_size} bytes)")
406
463
407
464
408
465
def main():
466
409
467
port = free_port()
410
468
http = start_http(port)
411
469
url = f"http://127.0.0.1:{port}/"
@@ -426,6 +484,7 @@ def main():
426
484
expect_one_row=True, n_minis=8)
427
485
run_viewport(browser, url, "1920x1080-8bots", 1920, 1080, False, 25, "sides",
428
486
expect_one_row=True, n_minis=8)
487
record_arcs_video(browser, url)
429
488
browser.close()
430
489
finally:
431
490
http.terminate()
@@ -13,6 +13,8 @@ from playwright.sync_api import sync_playwright13
ROOT = Path("/workspace/meteors")13
ROOT = Path("/workspace/meteors")14
OUT = Path("/workspace/meteors-shots")14
OUT = Path("/workspace/meteors-shots")15
OUT.mkdir(parents=True, exist_ok=True)15
OUT.mkdir(parents=True, exist_ok=True)16
VIDEO = Path("/workspace/meteors-video")17
VIDEO.mkdir(parents=True, exist_ok=True)16
CHROME = "/usr/bin/google-chrome"18
CHROME = "/usr/bin/google-chrome"17
CHROME_ARGS = [19
CHROME_ARGS = [18
"--use-gl=angle",20
"--use-gl=angle",@@ -121,37 +123,36 @@ INJECT_FLIGHTS = """(age) => {121
if (age == null) age = 0.55;123
if (age == null) age = 0.55;122
const plan = app.miniLayout;124
const plan = app.miniLayout;123
const field = app.scene.canvas.getBoundingClientRect();125
const field = app.scene.canvas.getBoundingClientRect();124
function anchor(id, inner) {126
function miniCell(id, col, y) {127
if (Online.miniCellViewport) {128
const p = Online.miniCellViewport(id, col, y);129
if (p && isFinite(p.x)) return p;130
}125
const el = document.querySelector('#minis .mini[data-player="' + id + '"] canvas');131
const el = document.querySelector('#minis .mini[data-player="' + id + '"] canvas');126
if (!el) return { x: 80, y: 80 };132
if (!el) return { x: 80, y: 80 };127
const r = el.getBoundingClientRect();133
return Online.cellViewport(col, y, el.getBoundingClientRect());128
if (plan && plan.mode === 'sides') {129
return { x: r.left + r.width / 2, y: r.top + 4 };130
}131
return { x: r.left + r.width / 2, y: inner ? r.bottom : r.top };132
}134
}133
const bots = (app.battle.bots || []).map(b => b.id);135
const bots = (app.battle.bots || []).map(b => b.id);134
const a = bots[0] || 'bot-1';136
const a = bots[0] || 'bot-1';135
const b = bots[1] || bots[0] || 'bot-2';137
const b = bots[1] || bots[0] || 'bot-2';136
const landCol = 3;138
const landCol = 3;137
const pStart = {139
// Launch from the real top-row cell, not from above the canvas (t1134).138
x: field.left + ((4 + 0.5) / 10) * field.width,140
const pStart = Online.cellViewport(4, 12, field);139
y: field.top + 4141
const pEnd = Online.fieldEntry ? Online.fieldEntry(landCol) : Online.cellViewport(landCol, 13, field);140
};141
if (typeof Online.clearFlights === 'function') Online.clearFlights();142
if (typeof Online.clearFlights === 'function') Online.clearFlights();142
const flights = [143
const flights = [143
{ id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol },144
{ id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol, col: 4, y: 12 },144
{ id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol },145
{ id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol, col: 2, y: 12 },145
{ id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7 },146
{ id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7, col: 5, y: 12 },146
{ id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45) }147
{ id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45), col: 1, y: 12 }147
];148
];148
const aOut = anchor(a, true);149
const aOut = miniCell(a, 2, 12);149
const bOut = anchor(b, true);150
const bOut = miniCell(b, 1, 12);150
const locals = {151
const locals = {151
'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, land_col: landCol },152
'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, y: 12, land_col: landCol },152
'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, land_col: landCol },153
'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, col: 2, y: 12, land_col: landCol },153
'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, land_col: 7 },154
'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, col: 5, y: 12, land_col: 7 },154
'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y }155
'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y, col: 1, y: 12 }155
};156
};156
Online.spawnFlights(flights, locals);157
Online.spawnFlights(flights, locals);157
Online.tickFlights();158
Online.tickFlights();@@ -167,31 +168,22 @@ INJECT_FLIGHTS = """(age) => {167
}));168
}));168
const kinds = (Online._flights || []).map(f => {169
const kinds = (Online._flights || []).map(f => {169
const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));170
const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));170
const u = Online.easeInOutCubic(raw);171
const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);171
let pt;172
const pt = Online.flightPointAt(f, u);172
if (f.waypoints && f.waypoints.length > 2)173
{ pt = Online.pointOnPath(f.waypoints, u); }174
else if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')175
{ pt = Online.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); }176
else177
{ pt = Online.arcPoint(f.start, f.end, u, f.height || 80); }178
const samples = [];173
const samples = [];179
if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')174
if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')180
{175
{181
for (let i = 0; i <= 16; i++)176
for (let i = 0; i <= 16; i++)182
{177
{183
const su = i / 16;178
const su = i / 16;184
let sp;179
const sp = Online.flightPointAt(f, su);185
if (f.waypoints && f.waypoints.length > 2)180
const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));186
{ sp = Online.pointOnPath(f.waypoints, su); }181
const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);187
else182
samples.push({ u: su, x: sp.x, y: sp.y, inside: inside, allowed: allowed });188
{ sp = Online.aroundFieldPoint(f.start, f.end, su, f.field, (f.height || 80) * 0.45); }189
samples.push({190
u: su, x: sp.x, y: sp.y,191
inside: Online.pointInFieldInterior(sp.x, sp.y, f.field)192
});193
}183
}194
}184
}185
const d0 = f.curve ? Online.curveDeriv(f.curve, 0) : null;186
const d1 = f.curve ? Online.curveDeriv(f.curve, 1) : null;195
return {187
return {196
kind: f.kind, miss: f.miss,188
kind: f.kind, miss: f.miss,197
startScale: f.startScale, endScale: f.endScale,189
startScale: f.startScale, endScale: f.endScale,@@ -199,22 +191,32 @@ INJECT_FLIGHTS = """(age) => {199
src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',191
src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',200
color: f.color,192
color: f.color,201
landCol: f.landCol,193
landCol: f.landCol,194
start: f.start,202
end: f.end,195
end: f.end,203
pos: pt,196
pos: pt,204
samples: samples,197
samples: samples,205
insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false198
insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false,199
hasCurve: !!f.curve,200
segments: (f.curve && f.curve.segments) ? f.curve.segments.length : (f.curve ? 1 : 0),201
d0: d0, d1: d1206
};202
};207
});203
});208
const expectedEndX = field.left + ((landCol + 0.5) / 10) * field.width;204
const expectedEndX = field.left + ((landCol + 0.5) / 10) * field.width;205
const expectedEndY = field.top + (1 - (13.5) / 13) * field.height;206
const expectedStartY = field.top + (1 - (12.5) / 13) * field.height;209
return {207
return {210
front: front.length,208
front: front.length,211
back: back.length,209
back: back.length,212
kinds,210
kinds,213
expectedEndX,211
expectedEndX,214
field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom },212
expectedEndY,213
expectedStartY,214
field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom,215
width: field.width, height: field.height },215
pad: field.top,216
pad: field.top,216
hudH: app.hudH,217
hudH: app.hudH,217
mode: plan.mode218
mode: plan.mode,219
tile: app.tile218
};220
};219
}"""221
}"""220
222
@@ -322,11 +324,22 @@ def assert_flights(info, tag, expect_behind=True, expect_around=True):322
f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")324
f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")323
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,325
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,324
f"{tag}: player-to-enemy is grey (src={k.get('src')} color={k.get('color')})")326
f"{tag}: player-to-enemy is grey (src={k.get('src')} color={k.get('color')})")327
if k.get("start") and info.get("expectedStartY") is not None:328
check(k["start"]["y"] > info["field"]["top"],329
f"{tag}: player-to-enemy starts inside the field "330
f"(start.y={k['start']['y']:.1f} field.top={info['field']['top']:.1f})")331
check(abs(k["start"]["y"] - info["expectedStartY"]) < 8,332
f"{tag}: player-to-enemy starts at the top-row cell "333
f"(start.y={k['start']['y']:.1f} expected={info['expectedStartY']:.1f})")334
if k.get("d0"):335
check(k["d0"]["y"] < 0,336
f"{tag}: player-to-enemy leaves going up (d0.y={k['d0']['y']:.1f})")337
check(k.get("hasCurve"), f"{tag}: player-to-enemy uses a smooth curve")325
if expect_around:338
if expect_around:326
inside = [s for s in (k.get("samples") or []) if s.get("inside")]339
forbidden = [s for s in (k.get("samples") or []) if s.get("inside") and not s.get("allowed")]327
check(len(inside) == 0,340
check(len(forbidden) == 0,328
f"{tag}: player-to-enemy path stays outside the field "341
f"{tag}: player-to-enemy stays in launch/land corridors "329
f"({len(inside)} interior samples {inside[:3]})")342
f"({len(forbidden)} forbidden {forbidden[:3]})")330
if "enemy-to-player" in kinds:343
if "enemy-to-player" in kinds:331
k = kinds["enemy-to-player"]344
k = kinds["enemy-to-player"]332
check(k["endScale"] > k["startScale"],345
check(k["endScale"] > k["startScale"],@@ -337,15 +350,26 @@ def assert_flights(info, tag, expect_behind=True, expect_around=True):337
check(abs(k["end"]["x"] - info["expectedEndX"]) < 3,350
check(abs(k["end"]["x"] - info["expectedEndX"]) < 3,338
f"{tag}: arc ends at column 3 "351
f"{tag}: arc ends at column 3 "339
f"(end.x={k['end']['x']:.1f} expected={info['expectedEndX']:.1f})")352
f"(end.x={k['end']['x']:.1f} expected={info['expectedEndX']:.1f})")353
if k.get("end") and info.get("expectedEndY") is not None:354
check(abs(k["end"]["y"] - info["expectedEndY"]) < 8,355
f"{tag}: arc ends at the spawn pose (y=13) "356
f"(end.y={k['end']['y']:.1f} expected={info['expectedEndY']:.1f})")357
check(k["end"]["y"] < info["field"]["top"] + 2,358
f"{tag}: incoming end is at/above the canvas top "359
f"(end.y={k['end']['y']:.1f} field.top={info['field']['top']:.1f})")360
if k.get("d1"):361
check(k["d1"]["y"] > 0,362
f"{tag}: enemy-to-player arrives going down (d1.y={k['d1']['y']:.1f})")363
check(abs(k.get("endScale", 0) - 1) < 0.05,364
f"{tag}: incoming ends at full tile scale ({k.get('endScale')})")365
check(k.get("hasCurve"), f"{tag}: enemy-to-player uses a smooth curve")340
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,366
check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,341
f"{tag}: enemy-to-player is grey (src={k.get('src')} color={k.get('color')})")367
f"{tag}: enemy-to-player is grey (src={k.get('src')} color={k.get('color')})")342
if expect_around and k.get("samples"):368
if expect_around and k.get("samples"):343
inside = [s for s in k["samples"] if s.get("inside")]369
forbidden = [s for s in k["samples"] if s.get("inside") and not s.get("allowed")]344
check(len(inside) == 0,370
check(len(forbidden) == 0,345
f"{tag}: enemy-to-player path stays outside the field "371
f"{tag}: enemy-to-player stays in launch/land corridors "346
f"({len(inside)} interior samples {inside[:3]})")372
f"({len(forbidden)} forbidden {forbidden[:3]})")347
check(not k.get("insideNow"),348
f"{tag}: enemy-to-player mid-arc is not over the field interior")349
if "enemy-to-enemy" in kinds:373
if "enemy-to-enemy" in kinds:350
k = kinds["enemy-to-enemy"]374
k = kinds["enemy-to-enemy"]351
check(abs(k["startScale"] - k["endScale"]) < 0.05,375
check(abs(k["startScale"] - k["endScale"]) < 0.05,@@ -387,25 +411,59 @@ def run_viewport(browser, url, name, width, height, is_mobile, round_n, expect_m387
n=n_minis)411
n=n_minis)388
else:412
else:389
assert_top(info, name)413
assert_top(info, name)390
shot(page, f"t1127-{name}-layout.png")414
shot(page, f"t1134-{name}-layout.png")391
415
392
flights = page.evaluate(INJECT_FLIGHTS, 0.55)416
flights = page.evaluate(INJECT_FLIGHTS, 0.55)393
print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'hudH', 'mode') if k in flights})417
print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'expectedEndY', 'expectedStartY', 'hudH', 'mode') if k in flights})394
for knd in flights["kinds"]:418
for knd in flights["kinds"]:395
print(f" {knd['kind']}: color={knd.get('color')} landCol={knd.get('landCol')} "419
print(f" {knd['kind']}: color={knd.get('color')} landCol={knd.get('landCol')} "396
f"src={knd.get('src')} insideNow={knd.get('insideNow')} "420
f"src={knd.get('src')} curve={knd.get('hasCurve')}/{knd.get('segments')} "397
f"end={knd.get('end')} pos={knd.get('pos')}")421
f"start={knd.get('start')} end={knd.get('end')} pos={knd.get('pos')}")398
assert_flights(flights, name)422
assert_flights(flights, name)399
shot(page, f"t1127-{name}-midarc.png")423
shot(page, f"t1134-{name}-midarc.png")400
424
401
if name in ("1024x532-3bots", "1920x1080-8bots", "desktop-wide"):425
if name in ("1024x532-3bots", "1920x1080-8bots", "desktop-wide"):402
for age, label in ((0.25, "early"), (0.85, "late")):426
for age, label in ((0.18, "early"), (0.85, "late")):403
page.evaluate(INJECT_FLIGHTS, age)427
page.evaluate(INJECT_FLIGHTS, age)404
shot(page, f"t1127-{name}-midarc-{label}.png")428
shot(page, f"t1134-{name}-midarc-{label}.png")429
context.close()430
431
432
def record_arcs_video(browser, url):433
"""A short webm of two volleys flying out, over, and into the field (t1134/t1135)."""434
VIDEO.mkdir(parents=True, exist_ok=True)435
dest = VIDEO / "t1134-arcs-1920x1080.webm"436
context = browser.new_context(437
viewport={"width": 1920, "height": 1080},438
device_scale_factor=1,439
record_video_dir=str(VIDEO / "_raw"),440
record_video_size={"width": 1920, "height": 1080},441
)442
page = context.new_page()443
open_offline(page, url, round_n=25)444
page.wait_for_timeout(400)445
# Live volleys at age 0 so tickFlights animates them in the game loop.446
page.evaluate(INJECT_FLIGHTS, 0)447
page.wait_for_timeout(1300)448
page.evaluate(INJECT_FLIGHTS, 0)449
page.wait_for_timeout(1400)450
page.close()405
context.close()451
context.close()452
# Playwright writes the webm next to the context; move it into place.453
raw = list((VIDEO / "_raw").glob("*.webm"))454
if raw:455
raw[0].replace(dest)456
print(f"wrote {dest} ({dest.stat().st_size} bytes)")457
else:458
FAILURES.append("video: no webm produced")459
print("FAIL video: no webm produced")460
return461
if dest.stat().st_size < 10000:462
FAILURES.append(f"video: suspiciously small ({dest.stat().st_size} bytes)")406
463
407
464
408
def main():465
def main():466
409
port = free_port()467
port = free_port()410
http = start_http(port)468
http = start_http(port)411
url = f"http://127.0.0.1:{port}/"469
url = f"http://127.0.0.1:{port}/"@@ -426,6 +484,7 @@ def main():426
expect_one_row=True, n_minis=8)484
expect_one_row=True, n_minis=8)427
run_viewport(browser, url, "1920x1080-8bots", 1920, 1080, False, 25, "sides",485
run_viewport(browser, url, "1920x1080-8bots", 1920, 1080, False, 25, "sides",428
expect_one_row=True, n_minis=8)486
expect_one_row=True, n_minis=8)487
record_arcs_video(browser, url)429
browser.close()488
browser.close()430
finally:489
finally:431
http.terminate()490
http.terminate()@@ -0,0 +1,455 @@
1
#!/usr/bin/env python3
2
"""t1136: online multiplayer uses the same presentation as Offline Strijd.
3
4
Two (and a third) Playwright clients against a local PHP server with
5
loopback test-auth. After the match starts we inspect MiniLayout and
6
feed shot_flights through Online._handleTransitions — the same path
7
a real poll uses — then assert sides/outer-edge/pad, around-field
8
C¹ arcs, land_col endings, grey hits, launch from the cell, and a
9
smooth dive into the spawn pose.
10
"""
11
from __future__ import annotations
12
13
import os
14
import shutil
15
import socket
16
import subprocess
17
import sys
18
import tempfile
19
import time
20
from pathlib import Path
21
22
from playwright.sync_api import sync_playwright
23
24
ROOT = Path("/workspace/meteors")
25
OUT = Path("/workspace/meteors-shots")
26
OUT.mkdir(parents=True, exist_ok=True)
27
CHROME = "/usr/bin/google-chrome"
28
CHROME_ARGS = [
29
"--use-gl=angle",
30
"--use-angle=swiftshader",
31
"--no-sandbox",
32
"--disable-dev-shm-usage",
33
]
34
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
35
FAILURES = []
36
URL = ""
37
38
39
def free_port():
40
s = socket.socket()
41
s.bind(("127.0.0.1", 0))
42
port = s.getsockname()[1]
43
s.close()
44
return port
45
46
47
def check(cond, msg):
48
if not cond:
49
FAILURES.append(msg)
50
print("FAIL", msg)
51
else:
52
print("OK ", msg)
53
return cond
54
55
56
def shot(page, name):
57
path = OUT / name
58
page.screenshot(path=str(path), full_page=False)
59
print(f"wrote {path} ({path.stat().st_size} bytes)")
60
return path
61
62
63
def start_php(port, data_dir):
64
env = os.environ.copy()
65
env["METEORS_DATA_DIR"] = str(data_dir)
66
proc = subprocess.Popen(
67
[PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"),
68
str(ROOT / "build" / "router.php")],
69
cwd=str(ROOT / "build"),
70
stdout=subprocess.DEVNULL,
71
stderr=open(str(Path(data_dir) / "php.log"), "w"),
72
env=env,
73
)
74
time.sleep(0.5)
75
if proc.poll() is not None:
76
log = Path(data_dir) / "php.log"
77
err = log.read_text(encoding="utf-8", errors="replace") if log.exists() else ""
78
raise RuntimeError("php -S failed: " + err)
79
return proc
80
81
82
def login(page, n):
83
page.goto(f"{URL}auth.php?test={n}&next=index.html",
84
wait_until="domcontentloaded", timeout=15000)
85
page.wait_for_timeout(250)
86
page.goto(f"{URL}index.html?online=1",
87
wait_until="domcontentloaded", timeout=15000)
88
page.wait_for_timeout(400)
89
90
91
def wait_visible(page, sel, timeout=8000):
92
page.locator(sel).wait_for(state="visible", timeout=timeout)
93
94
95
INSPECT = """() => {
96
const plan = app.miniLayout || {};
97
const fieldEl = app.scene && app.scene.canvas;
98
const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;
99
const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {
100
const r = el.getBoundingClientRect();
101
return {
102
id: el.getAttribute('data-player'),
103
left: r.left, right: r.right, top: r.top, bottom: r.bottom
104
};
105
});
106
const me = Online.mePlayer && Online.mePlayer();
107
const ops = (Online.opponents && Online.opponents()) || [];
108
return {
109
mode: plan.mode,
110
sidesClass: document.getElementById('minis').classList.contains('sides'),
111
n: plan.n,
112
fieldY: app.fieldY,
113
hudH: app.hudH,
114
pad: (typeof MiniLayout !== 'undefined') ? MiniLayout.ARC_TOP_PAD : null,
115
field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,
116
width: fr.width, height: fr.height } : null,
117
minis,
118
positions: plan.positions || [],
119
me: me && me.id,
120
opponents: ops.map(o => o.id),
121
online: !!app.online,
122
offline: !!app.offline,
123
vw: window.innerWidth,
124
vh: window.innerHeight
125
};
126
}"""
127
128
129
POLL_FLIGHTS = """() => {
130
const me = Online.mePlayer();
131
const ops = Online.opponents() || [];
132
const a = ops[0];
133
const b = ops[1] || ops[0];
134
if (!a || !me) return { error: 'no opponents or me' };
135
const field = app.scene.canvas.getBoundingClientRect();
136
if (Online.clearFlights) Online.clearFlights();
137
// Exact poll path: shot_flights only, no rememberFlightLocal (t1136).
138
Online._handleTransitions('playing', {
139
incoming: [],
140
shot_results: [],
141
shot_flights: [
142
{ id: 601, client_id: 'on-e2p', from_id: a.id, from_user: a.id,
143
target_id: me.id, miss: false, color: 1, flight_duration: 1.2,
144
age: 0.5, land_col: 3, col: 6, y: 12 },
145
{ id: 602, client_id: 'on-p2e', from_id: me.id, from_user: me.id,
146
target_id: a.id, miss: false, color: 0, flight_duration: 1.2,
147
age: 0.35, land_col: 5, col: 4, y: 12 },
148
{ id: 603, client_id: 'on-e2e', from_id: a.id, from_user: a.id,
149
target_id: b.id, miss: false, color: 2, flight_duration: 1.2,
150
age: 0.45, land_col: 7, col: 2, y: 12 },
151
{ id: 604, client_id: 'on-miss', from_id: b.id, from_user: b.id,
152
target_id: null, miss: true, color: 3, flight_duration: 1.2,
153
age: 0.3, col: 1, y: 12 }
154
]
155
});
156
Online.tickFlights();
157
const expectedEndX = field.left + ((3 + 0.5) / 10) * field.width;
158
const expectedEndY = field.top + (1 - 13.5 / 13) * field.height;
159
const expectedStartY = field.top + (1 - 12.5 / 13) * field.height;
160
const kinds = (Online._flights || []).map(f => {
161
const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));
162
const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);
163
const pt = Online.flightPointAt(f, u);
164
const samples = [];
165
if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy') {
166
for (let i = 0; i <= 16; i++) {
167
const su = i / 16;
168
const sp = Online.flightPointAt(f, su);
169
const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));
170
const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);
171
samples.push({ u: su, inside, allowed });
172
}
173
}
174
return {
175
kind: f.kind, miss: f.miss, color: f.color, landCol: f.landCol,
176
start: f.start, end: f.end, pos: pt,
177
startScale: f.startScale, endScale: f.endScale,
178
parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '',
179
src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',
180
hasCurve: !!f.curve,
181
d0: f.curve ? Online.curveDeriv(f.curve, 0) : null,
182
d1: f.curve ? Online.curveDeriv(f.curve, 1) : null,
183
samples,
184
forbidden: samples.filter(s => s.inside && !s.allowed).length
185
};
186
});
187
return {
188
kinds,
189
expectedEndX, expectedEndY, expectedStartY,
190
field: { left: field.left, right: field.right, top: field.top,
191
bottom: field.bottom, width: field.width, height: field.height },
192
front: document.querySelectorAll('#flights .flight').length,
193
back: document.querySelectorAll('#flights-back .flight').length
194
};
195
}"""
196
197
198
def assert_layout(info, tag, n_ops):
199
check(info.get("online") is True, f"{tag}: app.online is true")
200
check(info.get("offline") is False, f"{tag}: not in offline mode")
201
check(info.get("mode") == "sides", f"{tag}: mode is sides (got {info.get('mode')})")
202
check(info.get("sidesClass"), f"{tag}: #minis has .sides")
203
check((info.get("n") or 0) >= 1, f"{tag}: at least one opponent mini (n={info.get('n')})")
204
if (info.get("n") or 0) < n_ops:
205
print(f"note {tag}: wanted {n_ops} opponents, got {info.get('n')} (flights still verified)")
206
pad = info.get("pad") or 0
207
if pad and info.get("hudH") is not None and info.get("fieldY") is not None:
208
check(info["fieldY"] >= info["hudH"] + pad - 1,
209
f"{tag}: ARC_TOP_PAD (fieldY={info['fieldY']} hud={info['hudH']} pad={pad})")
210
field = info.get("field") or {}
211
minis = info.get("minis") or []
212
vw = info.get("vw") or 0
213
# Outer-edge: first two minis sit near the left and right screen edges.
214
if len(minis) >= 1:
215
lefts = sorted(minis, key=lambda m: m["left"])
216
check(lefts[0]["left"] < 40,
217
f"{tag}: leftmost mini is on the outer left edge ({lefts[0]['left']:.0f})")
218
if len(minis) >= 2:
219
rights = sorted(minis, key=lambda m: -m["right"])
220
check(abs(vw - rights[0]["right"]) < 40,
221
f"{tag}: rightmost mini is on the outer right edge "
222
f"(right={rights[0]['right']:.0f} vw={vw})")
223
# Bottom-aligned with the field
224
if field.get("bottom"):
225
for m in minis:
226
check(abs(m["bottom"] - field["bottom"]) < 16,
227
f"{tag}: mini {m['id']} bottom-aligned "
228
f"(mini={m['bottom']:.0f} field={field['bottom']:.0f})")
229
230
231
def assert_online_flights(info, tag):
232
kinds = {k["kind"]: k for k in info.get("kinds") or []}
233
check("player-to-enemy" in kinds, f"{tag}: player-to-enemy via shot_flights")
234
check("enemy-to-player" in kinds, f"{tag}: enemy-to-player via shot_flights")
235
if "player-to-enemy" in kinds:
236
k = kinds["player-to-enemy"]
237
check(k.get("hasCurve"), f"{tag}: p2e smooth curve")
238
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
239
f"{tag}: p2e is grey")
240
if k.get("start") and info.get("expectedStartY") is not None:
241
check(k["start"]["y"] > info["field"]["top"],
242
f"{tag}: p2e launches from inside the field "
243
f"(y={k['start']['y']:.1f} top={info['field']['top']:.1f})")
244
check(abs(k["start"]["y"] - info["expectedStartY"]) < 10,
245
f"{tag}: p2e start at y=12 cell")
246
if k.get("d0"):
247
check(k["d0"]["y"] < 0, f"{tag}: p2e leaves going up")
248
check(k.get("forbidden", 0) == 0, f"{tag}: p2e corridors only")
249
if "enemy-to-player" in kinds:
250
k = kinds["enemy-to-player"]
251
check(k.get("hasCurve"), f"{tag}: e2p smooth curve")
252
check(k.get("landCol") == 3, f"{tag}: e2p land_col=3 (got {k.get('landCol')})")
253
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
254
f"{tag}: e2p is grey")
255
if k.get("end") and info.get("expectedEndX") is not None:
256
check(abs(k["end"]["x"] - info["expectedEndX"]) < 4,
257
f"{tag}: e2p ends at land_col x")
258
check(abs(k["end"]["y"] - info["expectedEndY"]) < 10,
259
f"{tag}: e2p ends at spawn pose y=13")
260
if k.get("d1"):
261
check(k["d1"]["y"] > 0, f"{tag}: e2p arrives going down")
262
check(abs(k.get("endScale", 0) - 1) < 0.05, f"{tag}: e2p end scale is 1")
263
check(k.get("forbidden", 0) == 0, f"{tag}: e2p corridors only")
264
if "enemy-to-enemy" in kinds:
265
k = kinds["enemy-to-enemy"]
266
check(k["parent"] == "flights-back",
267
f"{tag}: e2e behind the field ({k['parent']})")
268
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
269
f"{tag}: e2e is grey")
270
check(info.get("back", 0) >= 1, f"{tag}: #flights-back has a flight")
271
if "enemy-miss" in kinds:
272
k = kinds["enemy-miss"]
273
check(k.get("color") != -1, f"{tag}: miss keeps sender colour")
274
275
276
def leave_if_needed(page):
277
if page.locator("#online-lobby").is_visible() and page.locator("#btn-leave-lobby").is_visible():
278
page.locator("#btn-leave-lobby").click()
279
page.wait_for_timeout(400)
280
281
282
def start_match(browser, width, height, n_players=3):
283
contexts = []
284
pages = []
285
for i in range(n_players):
286
ctx = browser.new_context(viewport={"width": width, "height": height})
287
page = ctx.new_page()
288
contexts.append(ctx)
289
pages.append(page)
290
login(page, i + 1)
291
wait_visible(page, "#online-panel")
292
leave_if_needed(page)
293
294
p1 = pages[0]
295
wait_visible(p1, "#btn-create")
296
p1.locator("#btn-create").click()
297
wait_visible(p1, "#online-lobby")
298
p1.wait_for_function(
299
"() => document.getElementById('lobby-code') && "
300
"document.getElementById('lobby-code').textContent.trim().length >= 4",
301
timeout=8000,
302
)
303
code = p1.locator("#lobby-code").inner_text().strip()
304
check(len(code) >= 4, f"lobby code ({code})")
305
306
for p in pages[1:]:
307
wait_visible(p, "#join-code")
308
p.locator("#join-code").fill(code)
309
p.locator("#btn-join").click()
310
wait_visible(p, "#online-lobby")
311
p.wait_for_timeout(400)
312
for _ in range(20):
313
if p1.locator("#lobby-players li").count() >= n_players:
314
break
315
p1.wait_for_timeout(300)
316
counts = [pg.locator("#lobby-players li").count() for pg in pages]
317
print(f"lobby player counts: {counts}")
318
check(counts[0] >= 2, f"host sees at least 2 players ({counts[0]})")
319
320
for p in pages:
321
# ready
322
btn = p.locator("#btn-ready")
323
if btn.is_visible():
324
btn.click()
325
p.wait_for_timeout(200)
326
327
start = p1.locator("#btn-start")
328
enabled = False
329
for _ in range(20):
330
if start.is_visible() and start.is_enabled():
331
enabled = True
332
break
333
p1.wait_for_timeout(300)
334
check(enabled, "host can start")
335
if not enabled:
336
raise RuntimeError("host Starten stayed disabled")
337
start.click()
338
for i, p in enumerate(pages):
339
try:
340
p.wait_for_function(
341
"() => app && app.mode === 'playing' && app.online && app.core",
342
timeout=15000,
343
)
344
except Exception as e:
345
state = p.evaluate(
346
"""() => ({
347
mode: typeof app === 'undefined' ? 'no-app' : app.mode,
348
online: !!(typeof app !== 'undefined' && app.online),
349
hasCore: !!(typeof app !== 'undefined' && app.core),
350
lobby: (typeof Online !== 'undefined' && Online.lobby)
351
? { status: Online.lobby.status, n: (Online.lobby.players||[]).length }
352
: null,
353
visible: {
354
panel: !document.getElementById('online-panel').hidden,
355
lobby: !document.getElementById('online-lobby').hidden,
356
hud: !document.getElementById('hud').hidden,
357
planet: !document.getElementById('planet-select').hidden
358
}
359
})"""
360
)
361
shot(p, f"t1136-debug-p{i+1}.png")
362
print(f"start failed on player {i+1}: {state}")
363
raise
364
p.wait_for_selector("canvas", state="visible", timeout=8000)
365
p.wait_for_timeout(500)
366
return contexts, pages
367
368
369
def run_viewport(browser, name, width, height, n_players=3):
370
print(f"\n======== online {name} ========")
371
contexts, pages = start_match(browser, width, height, n_players=n_players)
372
p1 = pages[0]
373
info = p1.evaluate(INSPECT)
374
print("layout", {k: info.get(k) for k in
375
("mode", "n", "fieldY", "hudH", "pad", "online", "vw", "vh",
376
"sidesClass", "opponents")})
377
assert_layout(info, name, n_players - 1)
378
shot(p1, f"t1136-{name}-layout.png")
379
380
flights = p1.evaluate(POLL_FLIGHTS)
381
print("flights", {k: flights.get(k) for k in
382
("front", "back", "expectedEndX", "expectedEndY", "expectedStartY")})
383
for knd in flights.get("kinds") or []:
384
print(f" {knd['kind']}: land={knd.get('landCol')} color={knd.get('color')} "
385
f"curve={knd.get('hasCurve')} start={knd.get('start')} end={knd.get('end')}")
386
if flights.get("error"):
387
check(False, f"{name}: {flights['error']}")
388
else:
389
assert_online_flights(flights, name)
390
shot(p1, f"t1136-{name}-midarc.png")
391
# early / late
392
for age_delta, label in ((-0.3, "early"), (0.3, "late")):
393
# re-inject by running POLL_FLIGHTS is mid; use evaluate with age via a small wrapper
394
p1.evaluate(
395
"""(age) => {
396
const payload = { incoming: [], shot_results: [], shot_flights: [] };
397
// Just retick existing? Clear and let POLL-like ages set in a short helper.
398
const me = Online.mePlayer();
399
const ops = Online.opponents() || [];
400
const a = ops[0], b = ops[1] || ops[0];
401
if (Online.clearFlights) Online.clearFlights();
402
Online._handleTransitions('playing', {
403
incoming: [], shot_results: [],
404
shot_flights: [
405
{ id: 701, client_id: 'e-'+age, from_id: a.id, target_id: me.id,
406
miss: false, color: 1, flight_duration: 1.2, age: age,
407
land_col: 3, col: 6, y: 12 },
408
{ id: 702, client_id: 'p-'+age, from_id: me.id, target_id: a.id,
409
miss: false, color: 0, flight_duration: 1.2, age: age,
410
land_col: 5, col: 4, y: 12 }
411
]
412
});
413
Online.tickFlights();
414
}""",
415
0.2 if label == "early" else 0.85,
416
)
417
shot(p1, f"t1136-{name}-midarc-{label}.png")
418
419
for c in contexts:
420
c.close()
421
422
423
def main():
424
global URL
425
port = free_port()
426
data = tempfile.mkdtemp(prefix="meteors-online-")
427
URL = f"http://127.0.0.1:{port}/"
428
proc = start_php(port, data)
429
try:
430
with sync_playwright() as p:
431
browser = p.chromium.launch(
432
executable_path=CHROME, args=CHROME_ARGS, headless=True
433
)
434
run_viewport(browser, "1920x1080", 1920, 1080, n_players=2)
435
run_viewport(browser, "1024x532", 1024, 532, n_players=2)
436
browser.close()
437
finally:
438
proc.terminate()
439
try:
440
proc.wait(timeout=3)
441
except subprocess.TimeoutExpired:
442
proc.kill()
443
shutil.rmtree(data, ignore_errors=True)
444
445
if FAILURES:
446
print(f"\n{len(FAILURES)} failure(s):")
447
for f in FAILURES:
448
print(" -", f)
449
return 1
450
print("\nall online presentation checks passed")
451
return 0
452
453
454
if __name__ == "__main__":
455
sys.exit(main())
@@ -0,0 +1,455 @@1
#!/usr/bin/env python32
"""t1136: online multiplayer uses the same presentation as Offline Strijd.3
4
Two (and a third) Playwright clients against a local PHP server with5
loopback test-auth. After the match starts we inspect MiniLayout and6
feed shot_flights through Online._handleTransitions — the same path7
a real poll uses — then assert sides/outer-edge/pad, around-field8
C¹ arcs, land_col endings, grey hits, launch from the cell, and a9
smooth dive into the spawn pose.10
"""11
from __future__ import annotations12
13
import os14
import shutil15
import socket16
import subprocess17
import sys18
import tempfile19
import time20
from pathlib import Path21
22
from playwright.sync_api import sync_playwright23
24
ROOT = Path("/workspace/meteors")25
OUT = Path("/workspace/meteors-shots")26
OUT.mkdir(parents=True, exist_ok=True)27
CHROME = "/usr/bin/google-chrome"28
CHROME_ARGS = [29
"--use-gl=angle",30
"--use-angle=swiftshader",31
"--no-sandbox",32
"--disable-dev-shm-usage",33
]34
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")35
FAILURES = []36
URL = ""37
38
39
def free_port():40
s = socket.socket()41
s.bind(("127.0.0.1", 0))42
port = s.getsockname()[1]43
s.close()44
return port45
46
47
def check(cond, msg):48
if not cond:49
FAILURES.append(msg)50
print("FAIL", msg)51
else:52
print("OK ", msg)53
return cond54
55
56
def shot(page, name):57
path = OUT / name58
page.screenshot(path=str(path), full_page=False)59
print(f"wrote {path} ({path.stat().st_size} bytes)")60
return path61
62
63
def start_php(port, data_dir):64
env = os.environ.copy()65
env["METEORS_DATA_DIR"] = str(data_dir)66
proc = subprocess.Popen(67
[PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"),68
str(ROOT / "build" / "router.php")],69
cwd=str(ROOT / "build"),70
stdout=subprocess.DEVNULL,71
stderr=open(str(Path(data_dir) / "php.log"), "w"),72
env=env,73
)74
time.sleep(0.5)75
if proc.poll() is not None:76
log = Path(data_dir) / "php.log"77
err = log.read_text(encoding="utf-8", errors="replace") if log.exists() else ""78
raise RuntimeError("php -S failed: " + err)79
return proc80
81
82
def login(page, n):83
page.goto(f"{URL}auth.php?test={n}&next=index.html",84
wait_until="domcontentloaded", timeout=15000)85
page.wait_for_timeout(250)86
page.goto(f"{URL}index.html?online=1",87
wait_until="domcontentloaded", timeout=15000)88
page.wait_for_timeout(400)89
90
91
def wait_visible(page, sel, timeout=8000):92
page.locator(sel).wait_for(state="visible", timeout=timeout)93
94
95
INSPECT = """() => {96
const plan = app.miniLayout || {};97
const fieldEl = app.scene && app.scene.canvas;98
const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;99
const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {100
const r = el.getBoundingClientRect();101
return {102
id: el.getAttribute('data-player'),103
left: r.left, right: r.right, top: r.top, bottom: r.bottom104
};105
});106
const me = Online.mePlayer && Online.mePlayer();107
const ops = (Online.opponents && Online.opponents()) || [];108
return {109
mode: plan.mode,110
sidesClass: document.getElementById('minis').classList.contains('sides'),111
n: plan.n,112
fieldY: app.fieldY,113
hudH: app.hudH,114
pad: (typeof MiniLayout !== 'undefined') ? MiniLayout.ARC_TOP_PAD : null,115
field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,116
width: fr.width, height: fr.height } : null,117
minis,118
positions: plan.positions || [],119
me: me && me.id,120
opponents: ops.map(o => o.id),121
online: !!app.online,122
offline: !!app.offline,123
vw: window.innerWidth,124
vh: window.innerHeight125
};126
}"""127
128
129
POLL_FLIGHTS = """() => {130
const me = Online.mePlayer();131
const ops = Online.opponents() || [];132
const a = ops[0];133
const b = ops[1] || ops[0];134
if (!a || !me) return { error: 'no opponents or me' };135
const field = app.scene.canvas.getBoundingClientRect();136
if (Online.clearFlights) Online.clearFlights();137
// Exact poll path: shot_flights only, no rememberFlightLocal (t1136).138
Online._handleTransitions('playing', {139
incoming: [],140
shot_results: [],141
shot_flights: [142
{ id: 601, client_id: 'on-e2p', from_id: a.id, from_user: a.id,143
target_id: me.id, miss: false, color: 1, flight_duration: 1.2,144
age: 0.5, land_col: 3, col: 6, y: 12 },145
{ id: 602, client_id: 'on-p2e', from_id: me.id, from_user: me.id,146
target_id: a.id, miss: false, color: 0, flight_duration: 1.2,147
age: 0.35, land_col: 5, col: 4, y: 12 },148
{ id: 603, client_id: 'on-e2e', from_id: a.id, from_user: a.id,149
target_id: b.id, miss: false, color: 2, flight_duration: 1.2,150
age: 0.45, land_col: 7, col: 2, y: 12 },151
{ id: 604, client_id: 'on-miss', from_id: b.id, from_user: b.id,152
target_id: null, miss: true, color: 3, flight_duration: 1.2,153
age: 0.3, col: 1, y: 12 }154
]155
});156
Online.tickFlights();157
const expectedEndX = field.left + ((3 + 0.5) / 10) * field.width;158
const expectedEndY = field.top + (1 - 13.5 / 13) * field.height;159
const expectedStartY = field.top + (1 - 12.5 / 13) * field.height;160
const kinds = (Online._flights || []).map(f => {161
const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));162
const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);163
const pt = Online.flightPointAt(f, u);164
const samples = [];165
if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy') {166
for (let i = 0; i <= 16; i++) {167
const su = i / 16;168
const sp = Online.flightPointAt(f, su);169
const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));170
const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);171
samples.push({ u: su, inside, allowed });172
}173
}174
return {175
kind: f.kind, miss: f.miss, color: f.color, landCol: f.landCol,176
start: f.start, end: f.end, pos: pt,177
startScale: f.startScale, endScale: f.endScale,178
parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '',179
src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',180
hasCurve: !!f.curve,181
d0: f.curve ? Online.curveDeriv(f.curve, 0) : null,182
d1: f.curve ? Online.curveDeriv(f.curve, 1) : null,183
samples,184
forbidden: samples.filter(s => s.inside && !s.allowed).length185
};186
});187
return {188
kinds,189
expectedEndX, expectedEndY, expectedStartY,190
field: { left: field.left, right: field.right, top: field.top,191
bottom: field.bottom, width: field.width, height: field.height },192
front: document.querySelectorAll('#flights .flight').length,193
back: document.querySelectorAll('#flights-back .flight').length194
};195
}"""196
197
198
def assert_layout(info, tag, n_ops):199
check(info.get("online") is True, f"{tag}: app.online is true")200
check(info.get("offline") is False, f"{tag}: not in offline mode")201
check(info.get("mode") == "sides", f"{tag}: mode is sides (got {info.get('mode')})")202
check(info.get("sidesClass"), f"{tag}: #minis has .sides")203
check((info.get("n") or 0) >= 1, f"{tag}: at least one opponent mini (n={info.get('n')})")204
if (info.get("n") or 0) < n_ops:205
print(f"note {tag}: wanted {n_ops} opponents, got {info.get('n')} (flights still verified)")206
pad = info.get("pad") or 0207
if pad and info.get("hudH") is not None and info.get("fieldY") is not None:208
check(info["fieldY"] >= info["hudH"] + pad - 1,209
f"{tag}: ARC_TOP_PAD (fieldY={info['fieldY']} hud={info['hudH']} pad={pad})")210
field = info.get("field") or {}211
minis = info.get("minis") or []212
vw = info.get("vw") or 0213
# Outer-edge: first two minis sit near the left and right screen edges.214
if len(minis) >= 1:215
lefts = sorted(minis, key=lambda m: m["left"])216
check(lefts[0]["left"] < 40,217
f"{tag}: leftmost mini is on the outer left edge ({lefts[0]['left']:.0f})")218
if len(minis) >= 2:219
rights = sorted(minis, key=lambda m: -m["right"])220
check(abs(vw - rights[0]["right"]) < 40,221
f"{tag}: rightmost mini is on the outer right edge "222
f"(right={rights[0]['right']:.0f} vw={vw})")223
# Bottom-aligned with the field224
if field.get("bottom"):225
for m in minis:226
check(abs(m["bottom"] - field["bottom"]) < 16,227
f"{tag}: mini {m['id']} bottom-aligned "228
f"(mini={m['bottom']:.0f} field={field['bottom']:.0f})")229
230
231
def assert_online_flights(info, tag):232
kinds = {k["kind"]: k for k in info.get("kinds") or []}233
check("player-to-enemy" in kinds, f"{tag}: player-to-enemy via shot_flights")234
check("enemy-to-player" in kinds, f"{tag}: enemy-to-player via shot_flights")235
if "player-to-enemy" in kinds:236
k = kinds["player-to-enemy"]237
check(k.get("hasCurve"), f"{tag}: p2e smooth curve")238
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),239
f"{tag}: p2e is grey")240
if k.get("start") and info.get("expectedStartY") is not None:241
check(k["start"]["y"] > info["field"]["top"],242
f"{tag}: p2e launches from inside the field "243
f"(y={k['start']['y']:.1f} top={info['field']['top']:.1f})")244
check(abs(k["start"]["y"] - info["expectedStartY"]) < 10,245
f"{tag}: p2e start at y=12 cell")246
if k.get("d0"):247
check(k["d0"]["y"] < 0, f"{tag}: p2e leaves going up")248
check(k.get("forbidden", 0) == 0, f"{tag}: p2e corridors only")249
if "enemy-to-player" in kinds:250
k = kinds["enemy-to-player"]251
check(k.get("hasCurve"), f"{tag}: e2p smooth curve")252
check(k.get("landCol") == 3, f"{tag}: e2p land_col=3 (got {k.get('landCol')})")253
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),254
f"{tag}: e2p is grey")255
if k.get("end") and info.get("expectedEndX") is not None:256
check(abs(k["end"]["x"] - info["expectedEndX"]) < 4,257
f"{tag}: e2p ends at land_col x")258
check(abs(k["end"]["y"] - info["expectedEndY"]) < 10,259
f"{tag}: e2p ends at spawn pose y=13")260
if k.get("d1"):261
check(k["d1"]["y"] > 0, f"{tag}: e2p arrives going down")262
check(abs(k.get("endScale", 0) - 1) < 0.05, f"{tag}: e2p end scale is 1")263
check(k.get("forbidden", 0) == 0, f"{tag}: e2p corridors only")264
if "enemy-to-enemy" in kinds:265
k = kinds["enemy-to-enemy"]266
check(k["parent"] == "flights-back",267
f"{tag}: e2e behind the field ({k['parent']})")268
check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),269
f"{tag}: e2e is grey")270
check(info.get("back", 0) >= 1, f"{tag}: #flights-back has a flight")271
if "enemy-miss" in kinds:272
k = kinds["enemy-miss"]273
check(k.get("color") != -1, f"{tag}: miss keeps sender colour")274
275
276
def leave_if_needed(page):277
if page.locator("#online-lobby").is_visible() and page.locator("#btn-leave-lobby").is_visible():278
page.locator("#btn-leave-lobby").click()279
page.wait_for_timeout(400)280
281
282
def start_match(browser, width, height, n_players=3):283
contexts = []284
pages = []285
for i in range(n_players):286
ctx = browser.new_context(viewport={"width": width, "height": height})287
page = ctx.new_page()288
contexts.append(ctx)289
pages.append(page)290
login(page, i + 1)291
wait_visible(page, "#online-panel")292
leave_if_needed(page)293
294
p1 = pages[0]295
wait_visible(p1, "#btn-create")296
p1.locator("#btn-create").click()297
wait_visible(p1, "#online-lobby")298
p1.wait_for_function(299
"() => document.getElementById('lobby-code') && "300
"document.getElementById('lobby-code').textContent.trim().length >= 4",301
timeout=8000,302
)303
code = p1.locator("#lobby-code").inner_text().strip()304
check(len(code) >= 4, f"lobby code ({code})")305
306
for p in pages[1:]:307
wait_visible(p, "#join-code")308
p.locator("#join-code").fill(code)309
p.locator("#btn-join").click()310
wait_visible(p, "#online-lobby")311
p.wait_for_timeout(400)312
for _ in range(20):313
if p1.locator("#lobby-players li").count() >= n_players:314
break315
p1.wait_for_timeout(300)316
counts = [pg.locator("#lobby-players li").count() for pg in pages]317
print(f"lobby player counts: {counts}")318
check(counts[0] >= 2, f"host sees at least 2 players ({counts[0]})")319
320
for p in pages:321
# ready322
btn = p.locator("#btn-ready")323
if btn.is_visible():324
btn.click()325
p.wait_for_timeout(200)326
327
start = p1.locator("#btn-start")328
enabled = False329
for _ in range(20):330
if start.is_visible() and start.is_enabled():331
enabled = True332
break333
p1.wait_for_timeout(300)334
check(enabled, "host can start")335
if not enabled:336
raise RuntimeError("host Starten stayed disabled")337
start.click()338
for i, p in enumerate(pages):339
try:340
p.wait_for_function(341
"() => app && app.mode === 'playing' && app.online && app.core",342
timeout=15000,343
)344
except Exception as e:345
state = p.evaluate(346
"""() => ({347
mode: typeof app === 'undefined' ? 'no-app' : app.mode,348
online: !!(typeof app !== 'undefined' && app.online),349
hasCore: !!(typeof app !== 'undefined' && app.core),350
lobby: (typeof Online !== 'undefined' && Online.lobby)351
? { status: Online.lobby.status, n: (Online.lobby.players||[]).length }352
: null,353
visible: {354
panel: !document.getElementById('online-panel').hidden,355
lobby: !document.getElementById('online-lobby').hidden,356
hud: !document.getElementById('hud').hidden,357
planet: !document.getElementById('planet-select').hidden358
}359
})"""360
)361
shot(p, f"t1136-debug-p{i+1}.png")362
print(f"start failed on player {i+1}: {state}")363
raise364
p.wait_for_selector("canvas", state="visible", timeout=8000)365
p.wait_for_timeout(500)366
return contexts, pages367
368
369
def run_viewport(browser, name, width, height, n_players=3):370
print(f"\n======== online {name} ========")371
contexts, pages = start_match(browser, width, height, n_players=n_players)372
p1 = pages[0]373
info = p1.evaluate(INSPECT)374
print("layout", {k: info.get(k) for k in375
("mode", "n", "fieldY", "hudH", "pad", "online", "vw", "vh",376
"sidesClass", "opponents")})377
assert_layout(info, name, n_players - 1)378
shot(p1, f"t1136-{name}-layout.png")379
380
flights = p1.evaluate(POLL_FLIGHTS)381
print("flights", {k: flights.get(k) for k in382
("front", "back", "expectedEndX", "expectedEndY", "expectedStartY")})383
for knd in flights.get("kinds") or []:384
print(f" {knd['kind']}: land={knd.get('landCol')} color={knd.get('color')} "385
f"curve={knd.get('hasCurve')} start={knd.get('start')} end={knd.get('end')}")386
if flights.get("error"):387
check(False, f"{name}: {flights['error']}")388
else:389
assert_online_flights(flights, name)390
shot(p1, f"t1136-{name}-midarc.png")391
# early / late392
for age_delta, label in ((-0.3, "early"), (0.3, "late")):393
# re-inject by running POLL_FLIGHTS is mid; use evaluate with age via a small wrapper394
p1.evaluate(395
"""(age) => {396
const payload = { incoming: [], shot_results: [], shot_flights: [] };397
// Just retick existing? Clear and let POLL-like ages set in a short helper.398
const me = Online.mePlayer();399
const ops = Online.opponents() || [];400
const a = ops[0], b = ops[1] || ops[0];401
if (Online.clearFlights) Online.clearFlights();402
Online._handleTransitions('playing', {403
incoming: [], shot_results: [],404
shot_flights: [405
{ id: 701, client_id: 'e-'+age, from_id: a.id, target_id: me.id,406
miss: false, color: 1, flight_duration: 1.2, age: age,407
land_col: 3, col: 6, y: 12 },408
{ id: 702, client_id: 'p-'+age, from_id: me.id, target_id: a.id,409
miss: false, color: 0, flight_duration: 1.2, age: age,410
land_col: 5, col: 4, y: 12 }411
]412
});413
Online.tickFlights();414
}""",415
0.2 if label == "early" else 0.85,416
)417
shot(p1, f"t1136-{name}-midarc-{label}.png")418
419
for c in contexts:420
c.close()421
422
423
def main():424
global URL425
port = free_port()426
data = tempfile.mkdtemp(prefix="meteors-online-")427
URL = f"http://127.0.0.1:{port}/"428
proc = start_php(port, data)429
try:430
with sync_playwright() as p:431
browser = p.chromium.launch(432
executable_path=CHROME, args=CHROME_ARGS, headless=True433
)434
run_viewport(browser, "1920x1080", 1920, 1080, n_players=2)435
run_viewport(browser, "1024x532", 1024, 532, n_players=2)436
browser.close()437
finally:438
proc.terminate()439
try:440
proc.wait(timeout=3)441
except subprocess.TimeoutExpired:442
proc.kill()443
shutil.rmtree(data, ignore_errors=True)444
445
if FAILURES:446
print(f"\n{len(FAILURES)} failure(s):")447
for f in FAILURES:448
print(" -", f)449
return 1450
print("\nall online presentation checks passed")451
return 0452
453
454
if __name__ == "__main__":455
sys.exit(main())