Draw every moving body at the drawn time T = ExactTime + Lead

Planets, belts, wells, loot, mines, stations, the chunk reticle and the flow
clock are evaluated through DrawAhead (Time, Orbit, Height, Position) at one
drawn time; the rail law lives once in Zone.Offset; OrbitPositionAt, GetHeight,
ChunkPose, EvaluateBelt and RideHeight take a time. Fixes the planet jumping
against a co-moving ship at display rates above the step rate.

Not yet built or run (Unity presenter files are verified by compile only on
Starfire).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-15 21:26:36 +02:00
commit b57207045d
14 changed files with 429 additions and 62 deletions

View file

@ -157,8 +157,9 @@ public static class FloatingItemsDrawnSmoke
ItemPickup[] Pickups() => rootObject.GetComponentsInChildren<ItemPickup>(true).Where(p => p != null).ToArray();
void At(ItemPickup pickup, FloatingItem floating, string what)
{
var at = floating.Body.Position;
var want = new Vector3(at.x, zone.GetHeight(at), at.y);
var lead = ActionGameManager.Clock.Lead;
var at = DrawAhead.Position(floating.Body, lead);
var want = new Vector3(at.x, DrawAhead.Height(zone, at, lead), at.y);
Require(Vector3.Distance(pickup.transform.position, want) < 1e-3f,
$"{what}: the pickup is at {pickup.transform.position}, the body at {want}.");
}

View file

@ -71,7 +71,7 @@ namespace Aetheria.EditorTools
?? throw new InvalidOperationException("No Gravity Field.mat.");
var zone = BuildZone(settings, work, out var orbits);
GravityLowering.Lower(zone, ref wells);
GravityLowering.Lower(zone, 0f, ref wells);
field = GravityLowering.CreateField(material);
// Three frames through the one buffer, as ZoneRenderer.Update runs it: the bodies as built, then two moves
@ -80,11 +80,11 @@ namespace Aetheria.EditorTools
CheckFrame("built", zone, orbits);
orbits[1].Position = new float2(-420f, 560f);
orbits[2].Position = new float2(900f, -700f);
GravityLowering.Lower(zone, ref wells);
GravityLowering.Lower(zone, 0f, ref wells);
CheckFrame("moved", zone, orbits);
orbits[0].Position = new float2(210f, -95f);
orbits[2].Position = new float2(-1800f, 1300f);
GravityLowering.Lower(zone, ref wells);
GravityLowering.Lower(zone, 0f, ref wells);
CheckFrame("moved-again", zone, orbits);
Debug.Log($"{Tag} max error {_maxError:G4} u (tolerance {Tolerance:G4}); max gradient angle {_maxAngle:F2} degrees (limit {GradientDegrees:F0})");

View file

@ -1178,10 +1178,12 @@ public class ActionGameManager : MonoBehaviour
}
}
// A chunk's simulated position is planar (Zone.ChunkPose); the renderer draws it at the asteroid layer's height.
// A chunk's pose is planar (Zone.ChunkPose), read at the drawn time so the reticle sits on the drawn rock; the renderer
// draws it at the asteroid layer's height.
private float3 ChunkWorldPosition(ChunkId chunk)
{
var pose = CurrentEntity.Zone.ChunkPose(chunk.Field, chunk.Index);
var zone = CurrentEntity.Zone;
var pose = zone.ChunkPose(chunk.Field, chunk.Index, DrawAhead.Time(zone, Clock.Lead));
return float3(pose.x, Settings.PlanetSettings.AsteroidVerticalOffset, pose.y);
}

View file

@ -390,6 +390,9 @@ public class EntityInstance : MonoBehaviour
x.Value.material.SetFloat("_Emission", Entity.ItemManager.GameplaySettings.TemperatureEmissionCurve.Evaluate(x.Key.RadiatorTemperature));
}
// The drawn pose first: the camera's LookAt and the barrels read this frame's pose, not the last frame's.
var drawn = DrawAhead.Position(Entity, ActionGameManager.Clock.Lead);
LocalSpace.localPosition = transform.position = drawn.ToUnity();
var aimDistance = !Entity.Target.Value.IsNone
? max(Entity.TargetRange, Entity.ItemManager.GameplaySettings.ConvergenceMinimumDistance)
: 10000;
@ -402,8 +405,6 @@ public class EntityInstance : MonoBehaviour
var direction = FireControl.Solution(weapon, Entity, Entity.Target.Value).Direction;
group.Value.position = barrel + new Vector3(direction.x, 0, direction.y) * aimDistance;
}
var drawn = DrawAhead.Position(Entity, ActionGameManager.Clock.Lead);
LocalSpace.localPosition = transform.position = drawn.ToUnity();
if (_influenceInstance)
_influenceInstance.position = new Vector3(drawn.x, 0, drawn.z);
}

View file

@ -40,8 +40,9 @@ public class ItemPickup : MonoBehaviour
private void Place()
{
var p = _floating.Body.Position;
transform.position = new Vector3(p.x, _zone.GetHeight(p) + GridOffset, p.y);
var lead = ActionGameManager.Clock.Lead;
var p = DrawAhead.Position(_floating.Body, lead);
transform.position = new Vector3(p.x, DrawAhead.Height(_zone, p, lead) + GridOffset, p.y);
}
private void Update()

View file

@ -55,8 +55,9 @@ public class MineInstance : MonoBehaviour
private void Place()
{
var p = _mine.Body.Position;
transform.position = new Vector3(p.x, _zone.GetHeight(p) + GridOffset, p.y);
var lead = ActionGameManager.Clock.Lead;
var p = DrawAhead.Position(_mine.Body, lead);
transform.position = new Vector3(p.x, DrawAhead.Height(_zone, p, lead) + GridOffset, p.y);
}
// The mine left Zone.Mines, which only its blast does: show it where it was drawn last.

View file

@ -3,16 +3,29 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using CultMath;
using GameCult.Caching;
using static CultMath.math;
// Pure presentation statics over sim state, never called by ServerShared, with no state of their own: the sim owns every
// pose and no presenter stores one, a previous state or a velocity of its own. Ships are drawn where the frame falls Lead
// sim seconds after the last step, by their last step's velocity and turn, and ride the field at that drawn xz (a ship's height is the field's there, not
// the last step's). A ballistic round's flight is presentation
// pose and no presenter stores one, a previous state or a velocity of its own.
// The rule: a presenter draws every moving thing at the drawn time T = Zone.ExactTime + Clock.Lead. A pose the sim defines
// in closed form of time (an orbit, a belt chunk, a well, the field's height, the flow scroll) is that function evaluated
// at T; a pose the sim integrates (a ship, a kinematic body) is its last step plus its step velocity times Lead; a child
// is drawn where its parent is. DrawAhead.Time is the one definition of T. Ships ride the field at that drawn xz and T (a
// ship's height is the field's there, not the last step's). A ballistic round's flight is presentation
// (ruling projectile-flight-is-presentation), drawn from the sim's facts: its frozen line, the published outcome, the
// commit tick, the impact cell on the target's drawn pose, the burst point.
public static class DrawAhead
{
// The drawn time: the one definition of T.
public static double Time(Zone zone, float lead) => zone.ExactTime + lead;
// An orbit's node at the drawn time: the rail law at T, not the step's memo.
public static float2 Orbit(Zone zone, CultRecordKey orbit, float lead) => zone.OrbitPositionAt(orbit, Time(zone, lead));
// The field's height at a point at the drawn time, its wells where their rails put them at T.
public static float Height(Zone zone, float2 planar, float lead) => zone.GetHeight(planar, Time(zone, lead));
// A ship in a wormhole animation has its pose scripted by the step, not integrated from Velocity and TurnRate,
// so it is drawn where the step put it: extrapolating a scripted pose draws a streak that resets every step.
// A child is drawn where its parent is drawn, as the step copies the parent's pose onto it.
@ -20,8 +33,11 @@ public static class DrawAhead
{
if (entity is Ship { WormholeAnimationInProgress: true }) return entity.Position;
if (entity.Parent != null) return Position(entity.Parent, lead);
var planar = entity.Position.xz + entity.Velocity * lead;
return float3(planar.x, entity.RideHeight(planar), planar.y);
// A body on a rail (a station) is on its orbit at T: the rail is closed form, not integrated.
var planar = entity is OrbitalEntity { OrbitData: var orbit } && orbit.IsSet()
? Orbit(entity.Zone, orbit, lead)
: entity.Position.xz + entity.Velocity * lead;
return float3(planar.x, entity.RideHeight(planar, Time(entity.Zone, lead)), planar.y);
}
// A free body (a vapour cloud) drawn where the frame falls lead sim seconds after the last step, by the velocity

View file

@ -1975,8 +1975,10 @@ public abstract class Entity
}
// Where an unparented entity sits on the field at a planar point: the zone's height there plus the hull's grid offset.
// The step puts the entity here at its own xz, and the presenter at its drawn xz (DrawAhead).
public float RideHeight(float2 planar) => Zone.GetHeight(planar) + (ItemManager.GetData(Hull) as HullData).GridOffset;
// The step rides at its own time and xz, the presenter at the drawn time and its drawn xz (DrawAhead).
public float RideHeight(float2 planar, double time) => Zone.GetHeight(planar, time) + (ItemManager.GetData(Hull) as HullData).GridOffset;
public float RideHeight(float2 planar) => RideHeight(planar, Zone.ExactTime);
private void UpdateTemperature(float delta)
{

View file

@ -507,31 +507,57 @@ public class Zone
if (!_updatedOrbits.Contains(orbitID))
{
var orbit = Orbits[orbitID];
float2 pos = float2.zero;
// An infinite period (a parentless orbit, or one with no field to circle in) leaves the orbit at its phase:
// frac(t / inf) is 0.
if (orbit.Period > .01f)
{
var phase = (float) frac(_time / orbit.Period);
pos = OrbitData.Evaluate(frac(phase + orbit.Data.Phase)) * orbit.Data.Distance;
if (float.IsNaN(pos.x))
{
//_context.Log("Orbit position is NaN, something went very wrong!");
pos = float2.zero;
}
}
var parentPosition = !Orbits[orbitID].Data.Parent.IsSet()
? Orbits[orbitID].Data.FixedPosition :
var parentPosition = !orbit.Data.Parent.IsSet()
? orbit.Data.FixedPosition :
GetOrbitPosition(orbit.Data.Parent.Key);
Orbits[orbitID].Position = parentPosition + pos;
orbit.Position = parentPosition + Offset(orbit, _time);
_updatedOrbits.Add(orbitID);
}
return Orbits[orbitID].Position;
}
// The rail law, once: where an orbit sits from its parent's node at a time. An infinite period (a parentless orbit,
// or one with no field to circle in) leaves the orbit at its phase: frac(t / inf) is 0.
private static float2 Offset(Orbit orbit, double time)
{
var pos = float2.zero;
if (orbit.Period > .01f)
{
var phase = (float) frac(time / orbit.Period);
pos = OrbitData.Evaluate(frac(phase + orbit.Data.Phase)) * orbit.Data.Distance;
if (float.IsNaN(pos.x))
pos = float2.zero;
}
return pos;
}
// The same rail law at any time, with no memo read or written: a parent is its own rail at that time.
private float2 RailAt(CultRecordKey orbitID, double time)
{
if (!orbitID.IsSet() || !Orbits.TryGetValue(orbitID, out var orbit))
return float2.zero;
var parentPosition = !orbit.Data.Parent.IsSet() ? orbit.Data.FixedPosition : RailAt(orbit.Data.Parent.Key, time);
return parentPosition + Offset(orbit, time);
}
// Where an orbit is at a time: pure, writes nothing. At the step's own time it is the step's memo (GetOrbitPosition);
// at any other time (a presenter's drawn time) it is the rail law evaluated there.
public float2 OrbitPositionAt(CultRecordKey orbitID, double time)
{
if (!orbitID.IsSet())
return float2.zero;
if (!Orbits.ContainsKey(orbitID))
{
Log?.Invoke("Requested orbit is not part of this zone!");
return float2.zero;
}
return time == _time ? GetOrbitPosition(orbitID) : RailAt(orbitID, time);
}
// orbit -> the well-bearing body on it, and orbit -> the orbits whose parent it is. Derived from the pack in the
// constructor, read only by PeriodAround and Strength.
private readonly Dictionary<CultRecordKey, Planet> _wellOn = new Dictionary<CultRecordKey, Planet>();
@ -656,12 +682,15 @@ public class Zone
// Cut 1 (docs/mining-cut.md): a chunk's pose is a pure function of zone time, computed when asked. No stored
// pose survives a tick; the sim and the renderer both read it fresh through here.
public float4 ChunkPose(CultRecordKey belt, int index)
public float4 ChunkPose(CultRecordKey belt, int index) => ChunkPose(belt, index, _time);
// The same pose at any time: the sim reads it at _time, a presenter at the drawn time (DrawAhead.Time).
public float4 ChunkPose(CultRecordKey belt, int index, double time)
{
var beltData = Planets[belt] as AsteroidBeltData;
var parentPosition = GetOrbitPosition(Orbits[beltData.Orbit.Key].Data.Parent.Key);
var parentPosition = OrbitPositionAt(Orbits[beltData.Orbit.Key].Data.Parent.Key, time);
var size = ChunkRadius(new ChunkId(belt, index));
return AsteroidBelts[belt].Pose(index, _time, parentPosition, size);
return AsteroidBelts[belt].Pose(index, time, parentPosition, size);
}
// Mining Cut 3 (docs/mining-cut-refresh.md): how bright a chunk is -- Reflector's rule (cross-section × the light
@ -676,13 +705,13 @@ public class Zone
return kind.CrossSection * PI * cells * cells * GetLight(ChunkPose(chunk.Field, chunk.Index).xy);
}
public void EvaluateBelt(CultRecordKey belt, Span<float4> into)
public void EvaluateBelt(CultRecordKey belt, Span<float4> into, double time)
{
var beltData = Planets[belt] as AsteroidBeltData;
var parentPosition = GetOrbitPosition(Orbits[beltData.Orbit.Key].Data.Parent.Key);
var parentPosition = OrbitPositionAt(Orbits[beltData.Orbit.Key].Data.Parent.Key, time);
var beltInstance = AsteroidBelts[belt];
for (var i = 0; i < beltData.Asteroids.Length; i++)
into[i] = beltInstance.Pose(i, _time, parentPosition, ChunkRadius(new ChunkId(belt, i)));
into[i] = beltInstance.Pose(i, time, parentPosition, ChunkRadius(new ChunkId(belt, i)));
}
public SecurityLevel GetSecurityLevel(float2 pos)
@ -706,12 +735,16 @@ public class Zone
// reference. GetHeight sums with it and the renderer's lowering (GravityLowering) hands it to the shader unchanged.
public float WellReference(Planet body) => GravityField.Potential(body.WellStrength, body.RocheLimit, Pack.Radius);
public float GetHeight(float2 position)
public float GetHeight(float2 position) => GetHeight(position, _time);
// The field at a time: each well sits where its body's rail puts it then. The sim reads it at _time, a presenter at
// the drawn time, so a ship rides the same slope the drawn planet's well makes.
public float GetHeight(float2 position, double time)
{
var result = 0f;
foreach (var body in PlanetInstances.Values)
{
var offset = position - body.Orbit.Position;
var offset = position - OrbitPositionAt(body.BodyData.Orbit.Key, time);
result += GravityField.Potential(body.WellStrength, body.RocheLimit, length(offset)) - WellReference(body);
}

View file

@ -32,9 +32,10 @@ public static class GravityLowering
/// <summary>
/// Fills one record per body of the zone (a null zone has none) and sets the shader globals. The buffer is the
/// caller's, (re)allocated to the body count (at least one, so the global is always bound).
/// caller's, (re)allocated to the body count (at least one, so the global is always bound). Wells are lowered at the
/// drawn time (DrawAhead.Time), the same T the planets and a ship's ride height use.
/// </summary>
public static void Lower(Zone zone, ref ComputeBuffer wells)
public static void Lower(Zone zone, float lead, ref ComputeBuffer wells)
{
var count = zone?.PlanetInstances.Count ?? 0;
var capacity = Mathf.Max(count, 1);
@ -50,7 +51,7 @@ public static class GravityLowering
foreach (var body in zone.PlanetInstances.Values)
_records[i++] = new WellRecord
{
Position = new Vector2(body.Orbit.Position.x, body.Orbit.Position.y),
Position = DrawAhead.Orbit(zone, body.BodyData.Orbit.Key, lead).ToUnity(),
Strength = body.WellStrength,
CoreRadius = body.RocheLimit,
Reference = zone.WellReference(body)

View file

@ -106,10 +106,12 @@ public class VolumeSampling : MonoBehaviour
static GlobalKeyword KeywordFlowSlope => _keywordFlowSlope ??= GlobalKeyword.Create("FLOW_SLOPE");
/// <summary>
/// The time the flow runs on: the zone's own (so drift stops with the sim and follows sim speed), or on menus,
/// where no zone exists, the presentation clock.
/// The time the flow runs on: the zone's drawn time (DrawAhead.Time, so drift stops with the sim and follows sim
/// speed), or on menus, where no zone exists, the presentation clock.
/// </summary>
public static double FlowClock => ActionGameManager.Instance?.Zone?.ExactTime ?? Time.timeSinceLevelLoad;
public static double FlowClock => ActionGameManager.Instance?.Zone is { } zone
? DrawAhead.Time(zone, ActionGameManager.Clock.Lead)
: Time.timeSinceLevelLoad;
/// <summary>
/// The one place that sets the flow uniforms and keywords: every shader flow term derives from FlowSettings and

View file

@ -520,7 +520,8 @@ public class ZoneRenderer : MonoBehaviour
void Update()
{
var maxDepth = 0f;
GravityLowering.Lower(Zone, ref _gravityWells);
var lead = ActionGameManager.Clock.Lead;
GravityLowering.Lower(Zone, lead, ref _gravityWells);
foreach (var loot in _floatingItems.Values)
{
loot.ViewOrigin = PerspectiveEntity.Position;
@ -542,11 +543,11 @@ public class ZoneRenderer : MonoBehaviour
foreach (var (key, belt) in Zone.AsteroidBelts)
{
// Cut 1 (docs/mining-cut.md): belts have no stored pose any more. The renderer fills its own buffer
// from Zone.EvaluateBelt, at the current zone time, every frame.
var orbitPosition = Zone.GetOrbitPosition(Zone.Orbits[belt.Data.Orbit.Key].Data.Parent.Key);
var height = Zone.GetHeight(orbitPosition);
// from Zone.EvaluateBelt, at the drawn time (DrawAhead.Time), every frame.
var orbitPosition = DrawAhead.Orbit(Zone, Zone.Orbits[belt.Data.Orbit.Key].Data.Parent.Key, lead);
var height = DrawAhead.Height(Zone, orbitPosition, lead);
var transforms = _beltTransforms[key];
Zone.EvaluateBelt(key, transforms);
Zone.EvaluateBelt(key, transforms, DrawAhead.Time(Zone, lead));
if(isVisible(new Bounds(
new Vector3(orbitPosition.x,height,orbitPosition.y),
new Vector3(belt.Radius * 2,100,belt.Radius * 2))))
@ -579,8 +580,8 @@ public class ZoneRenderer : MonoBehaviour
foreach (var planet in Planets)
{
var planetInstance = Zone.PlanetInstances[planet.Key];
var p = Zone.GetOrbitPosition(planetInstance.BodyData.Orbit.Key);
var height = Zone.GetHeight(p);
var p = DrawAhead.Orbit(Zone, planetInstance.BodyData.Orbit.Key, lead);
var height = DrawAhead.Height(Zone, p, lead);
if (-height > maxDepth) maxDepth = -height;
planet.Value.transform.position = new Vector3(p.x, 0, p.y);
planet.Value.Body.transform.localPosition = new Vector3(0, height + planetInstance.BodyRadius * 2, 0);
@ -589,7 +590,7 @@ public class ZoneRenderer : MonoBehaviour
{
if (!(planet.Value is SunObject))
{
var toParent = normalize(Zone.GetOrbitPosition(Zone.Orbits[planetInstance.BodyData.Orbit.Key].Data.Parent.Key) - p);
var toParent = normalize(DrawAhead.Orbit(Zone, Zone.Orbits[planetInstance.BodyData.Orbit.Key].Data.Parent.Key, lead) - p);
gasGiantObject.SunMaterial.LightingDirection = new Vector3(toParent.x, 0, toParent.y);
}
}
@ -716,7 +717,7 @@ public class AsteroidBeltUI
public void Update(float4[] transforms, float height)
{
var parentPosition = _zone.GetOrbitPosition(_orbitParent);
var parentPosition = DrawAhead.Orbit(_zone, _orbitParent, ActionGameManager.Clock.Lead);
for (var i = 0; i < transforms.Length; i++)
{
var transform = transforms[i];