Merge fire control fix batches 5-8: fused weapons follow player intent
One Solve decision feeds Fire, Inspect and Refuses. Literal arming distance on every detonation path; no-lock rounds of any fuse stop at the first hull; a round fired at a target that leaves does not burst; refusal is free, cooldown included; AI decides per weapon and never fires a refused weapon; the HUD shows the outcome. Soul passes 5-7; batch 8 closes their follow-ups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
06001b57a8
22 changed files with 2587 additions and 210 deletions
|
|
@ -535,7 +535,7 @@ public class ActionGameManager : MonoBehaviour
|
|||
missileManager.OnFireGuided.Where(x => x.source == _currentEntity).Take(1).Subscribe(x =>
|
||||
{
|
||||
FollowCamera.Follow = x.missile.transform;
|
||||
FollowCamera.LookAt = x.target;
|
||||
FollowCamera.LookAt = x.target ? x.target : x.missile.transform;
|
||||
x.missile.OnKill += () =>
|
||||
{
|
||||
FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint;
|
||||
|
|
@ -1282,6 +1282,13 @@ public class ActionGameManager : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
private static string ResultLabel(ShotResult result) => result switch
|
||||
{
|
||||
ShotResult.Hit => "HIT",
|
||||
ShotResult.Burst => "BURST",
|
||||
_ => "MISS"
|
||||
};
|
||||
|
||||
private void UpdateFireControlDebug(Entity target)
|
||||
{
|
||||
if (DebugInfoText == null) return;
|
||||
|
|
@ -1310,7 +1317,7 @@ public class ActionGameManager : MonoBehaviour
|
|||
var shot = CurrentEntity.Zone.PendingShots[i];
|
||||
if (shot.Source != CurrentEntity || shot.Weapon != selectedItem) continue;
|
||||
if (shot.Committed)
|
||||
pendingLine = $"shot {shot.ShotId}: committed {(shot.Outcome.Hit ? "HIT" : "MISS")}";
|
||||
pendingLine = $"shot {shot.ShotId}: committed {ResultLabel(shot.Outcome.Result)}";
|
||||
else
|
||||
{
|
||||
var pDeviation = FireControl.DeviationProbability(shot, CurrentEntity.Zone.Time, out var deviation);
|
||||
|
|
@ -1324,11 +1331,16 @@ public class ActionGameManager : MonoBehaviour
|
|||
}
|
||||
|
||||
var lastLine = _debugLastShots.TryGetValue(selectedItem, out var lastShot)
|
||||
? $"last {lastShot.ShotId}: {(lastShot.Hit ? "HIT" : "MISS")} cell {lastShot.Cell.x},{lastShot.Cell.y}"
|
||||
? $"last {lastShot.ShotId}: {ResultLabel(lastShot.Result)} cell {lastShot.Cell.x},{lastShot.Cell.y}"
|
||||
: "last: none";
|
||||
var gates = target == null
|
||||
? "target: none"
|
||||
: $"gates vis {d.Visible} range {d.InRange} arc {d.InArc} lock {d.Locked}";
|
||||
: $"gates designated {d.Designated} arc {d.InArc}";
|
||||
|
||||
// A fused weapon's forecast is its outcome, not a hit chance: the burst point or the refusal.
|
||||
var outcomeLine = d.Outcome == FireOutcome.Burst ? $"burst at {d.BurstReach:F0}"
|
||||
: d.Outcome == FireOutcome.Refused ? "refused: arming distance exceeds range"
|
||||
: $"base {d.PBase:P1}";
|
||||
|
||||
DebugInfoText.text =
|
||||
$"FIRE CONTROL - {selectedItem.Data.Name}\n" +
|
||||
|
|
@ -1337,7 +1349,7 @@ public class ActionGameManager : MonoBehaviour
|
|||
$"info {d.Info:F3}/{d.InfoDemandCeiling:F3} sensor {d.PSensor:F3}\n" +
|
||||
$"accuracy {d.Accuracy:F3} spread {d.PSpread:F3} hull {d.POnHull:F3}\n" +
|
||||
$"precision {d.Precision:F3} tracking {d.Tracking:F1}\n" +
|
||||
$"base {d.PBase:P1}\n" +
|
||||
$"{outcomeLine}\n" +
|
||||
$"{pendingLine}\n" +
|
||||
lastLine;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -203,8 +203,11 @@ public class EntityInstance : MonoBehaviour
|
|||
// Cut 3 (docs/fire-control-cut.md): carries the ShotId FireControl.Fire assigned so the
|
||||
// effect manager (and whatever it spawns) can bind its presentation to Zone.ShotCommitted /
|
||||
// ShotResolved instead of deciding or applying anything itself.
|
||||
// The target handed to the effect is the shot's own, not the shooter's selection: a fused round
|
||||
// whose selected target was invalid, or out of arc, flies at none (FireControl.Fire) and the
|
||||
// effect must not chase one.
|
||||
instantWeapon.OnFire += shotId =>
|
||||
_instantWeaponManagers[data].Fire(instantWeapon, item, this, entity.Target.Value != null && ZoneRenderer.EntityInstances.ContainsKey(entity.Target.Value) ? ZoneRenderer.EntityInstances[entity.Target.Value] : null, shotId);
|
||||
_instantWeaponManagers[data].Fire(instantWeapon, item, this, ShotTarget(shotId), shotId);
|
||||
|
||||
if (behavior is ChargedWeapon chargedWeapon)
|
||||
{
|
||||
|
|
@ -336,6 +339,10 @@ public class EntityInstance : MonoBehaviour
|
|||
}
|
||||
}
|
||||
|
||||
private EntityInstance ShotTarget(int shotId) =>
|
||||
Entity.Zone.TryGetShot(shotId, out var shot) && shot.Target != null &&
|
||||
ZoneRenderer.EntityInstances.TryGetValue(shot.Target, out var instance) ? instance : null;
|
||||
|
||||
private void OnSensorPingEnd()
|
||||
{
|
||||
Destroy(_currentPing.transform.gameObject);
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ public class GuidedProjectile : MonoBehaviour
|
|||
private float _prevDist;
|
||||
private bool _active;
|
||||
private bool _alive;
|
||||
private float _spawnTime;
|
||||
private Vector3 _targetVelocity;
|
||||
private Vector3 _previousTargetPosition;
|
||||
|
||||
|
|
@ -46,11 +47,74 @@ public class GuidedProjectile : MonoBehaviour
|
|||
public Vector3 Velocity { get; set; }
|
||||
public Entity SourceEntity { get; set; }
|
||||
|
||||
// How long after spawn the round keeps its binding to the simulation's verdict: the shot's own flight time (the
|
||||
// manager sets it from the committed shot's ArrivalTime), so a round that faded out early still lives to show
|
||||
// the detonation the simulation resolves at arrival. 0 (the default) kills the round when its fade ends.
|
||||
public float BindingLifetime { get; set; }
|
||||
|
||||
public event Action OnKill;
|
||||
|
||||
// The simulation's verdict on this round, bound by GuidedProjectileManager to Zone.ShotCommitted and
|
||||
// ShotResolved for its ShotId: this object flies and looks, and neither decides where the round bursts nor when.
|
||||
// The one owner of the subscription's lifetime: a new binding disposes the one it replaces, Kill disposes it,
|
||||
// and so does destruction, so a projectile torn down with its scene never leaves an observer on the zone's
|
||||
// subjects to touch a destroyed transform.
|
||||
public IDisposable Binding
|
||||
{
|
||||
get => _binding;
|
||||
set
|
||||
{
|
||||
_binding?.Dispose();
|
||||
_binding = value;
|
||||
}
|
||||
}
|
||||
|
||||
private IDisposable _binding;
|
||||
|
||||
void OnDestroy() => Binding = null;
|
||||
|
||||
// The commit named a burst point: fly to it, whatever this round was homing on (a target it would have
|
||||
// passed, or a Range clamp it would have overshot). The point is a static target, so the old target's motion
|
||||
// is dropped with it: the jump to the new point must not feed the guidance a target velocity.
|
||||
public void BurstAt(Vector3 point)
|
||||
{
|
||||
Target = null;
|
||||
TargetPosition = () => point;
|
||||
_previousTargetPosition = point;
|
||||
_targetVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
// The resolution. A round that detonated (a hit, or a burst) bursts now, at the simulation's burst point when
|
||||
// it has one; a round the simulation resolved without a detonation (a contact or delayed round that missed,
|
||||
// one whose target is gone) just falls away, with no explosion to show.
|
||||
public void Resolve(bool detonated, Vector3? point)
|
||||
{
|
||||
// A round that already faded out (overshot, out of flight) still shows the simulation's detonation: only a
|
||||
// round that has been killed is done. The fade is stopped so it cannot Kill the round a second time.
|
||||
if (!_alive) return;
|
||||
if (!detonated)
|
||||
{
|
||||
if (_active) StartCoroutine(FadeOut());
|
||||
return;
|
||||
}
|
||||
StopAllCoroutines();
|
||||
// A hit carries no burst point: the effect plays where the round was homing (a round that faded out has stopped
|
||||
// short of it), and is skipped when the round never knew where its target was.
|
||||
Vector3? effectAt = point ?? (TargetPosition != null ? TargetPosition() : Target ? Target.position : (Vector3?) null);
|
||||
if (point.HasValue) transform.position = point.Value;
|
||||
if (HitEffect != null && effectAt.HasValue)
|
||||
{
|
||||
var ht = HitEffect.Instantiate<Transform>();
|
||||
ht.position = effectAt.Value;
|
||||
}
|
||||
StartCoroutine(Kill());
|
||||
}
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_active = _alive = true;
|
||||
_spawnTime = Time.time;
|
||||
BindingLifetime = 0f; // a pooled round starts unbound; the manager binds it after enabling
|
||||
_phase = Random.value * 100;
|
||||
_prevDist = Single.MaxValue;
|
||||
Particles.startColor = Color.white;
|
||||
|
|
@ -84,14 +148,11 @@ public class GuidedProjectile : MonoBehaviour
|
|||
var targetDist = diff.magnitude;
|
||||
var sourceDist = length(StartPosition.xz - position.xz);
|
||||
|
||||
// Out of range, or flown past its target: the round falls away. Only the simulation's detonation
|
||||
// (Resolve) shows an explosion; a round that merely ran out of flight has none.
|
||||
if (sourceDist > Range || dot(diff.ToCultMath(), Velocity.ToCultMath()) < 0)
|
||||
{
|
||||
StartCoroutine(FadeOut());
|
||||
if (HitEffect != null)
|
||||
{
|
||||
var ht = HitEffect.Instantiate<Transform>();
|
||||
ht.position = t.position;
|
||||
}
|
||||
return;
|
||||
}
|
||||
_prevDist = targetDist;
|
||||
|
|
@ -165,11 +226,16 @@ public class GuidedProjectile : MonoBehaviour
|
|||
yield return null;
|
||||
}
|
||||
|
||||
// The wait holds still: a round waiting on the verdict must not drift off its last position.
|
||||
Velocity = Vector3.zero;
|
||||
// Faded, but the simulation's verdict has not necessarily arrived: wait for it until the shot's flight is over.
|
||||
while (Time.time - _spawnTime < BindingLifetime) yield return null;
|
||||
StartCoroutine(Kill());
|
||||
}
|
||||
|
||||
IEnumerator Kill()
|
||||
{
|
||||
Binding = null;
|
||||
_active = false;
|
||||
_alive = false;
|
||||
Particles.Stop(true, ParticleSystemStopBehavior.StopEmitting);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,22 @@ using static CultMath.math;
|
|||
|
||||
public class GuidedProjectileManager : InstantWeaponEffectManager
|
||||
{
|
||||
// Presentation follows the committed shot (FireControl): the round retargets to the burst point the commit
|
||||
// names and bursts when the shot resolves, rather than predicting either from its own homing.
|
||||
private static void Bind(GuidedProjectile p, Zone zone, int shotId)
|
||||
{
|
||||
Vector3 At(ShotOutcome o) => new Vector3(o.BurstPoint.x, p.transform.position.y, o.BurstPoint.y);
|
||||
var bindings = new CompositeDisposable();
|
||||
zone.ShotCommitted.Where(o => o.ShotId == shotId && o.HasBurstPoint).Subscribe(o => p.BurstAt(At(o))).AddTo(bindings);
|
||||
zone.ShotResolved.Where(o => o.ShotId == shotId)
|
||||
.Subscribe(o => p.Resolve(o.Result == ShotResult.Hit || o.Result == ShotResult.Burst, o.HasBurstPoint ? At(o) : (Vector3?) null))
|
||||
.AddTo(bindings);
|
||||
// The binding outlives a fade-out until the shot's own arrival (the moment the simulation resolves it), plus a
|
||||
// second of margin; a shot no longer pending has nothing left to resolve.
|
||||
p.BindingLifetime = zone.TryGetShot(shotId, out var shot) ? max(0f, shot.ArrivalTime - zone.Time) + 1f : 0f;
|
||||
p.Binding = bindings; // replaces, and so disposes, any binding the projectile already had
|
||||
}
|
||||
|
||||
public Prototype ProjectilePrototype;
|
||||
|
||||
public Subject<(Entity source, Transform target, GuidedProjectile missile)> OnFireGuided = new Subject<(Entity source, Transform target, GuidedProjectile missile)>();
|
||||
|
|
@ -17,12 +33,17 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
|
|||
{
|
||||
if(weapon.Data is LauncherData launcher)
|
||||
{
|
||||
if (target == null) return;
|
||||
// A round the simulation fired at no target (FireControl.Fire: a fused round with no valid targeting
|
||||
// data, or out of arc) flies to the point it bursts at; one with no target and no burst is not a shot.
|
||||
PendingShot shot = default;
|
||||
if (target == null && !(source.Entity.Zone.TryGetShot(shotId, out shot) && shot.Fuse != null)) return;
|
||||
var burst = shot.BurstPosition.ToUnity();
|
||||
var p = ProjectilePrototype.Instantiate<GuidedProjectile>();
|
||||
p.ShotId = shotId;
|
||||
p.Source = source.transform;
|
||||
p.SourceEntity = source.Entity;
|
||||
p.Target = target.transform;
|
||||
if (target != null) p.Target = target.transform;
|
||||
else p.TargetPosition = () => burst;
|
||||
p.Frequency = launcher.DodgeFrequency;
|
||||
var hp = source.Entity.Hardpoints[item.Position.x, item.Position.y];
|
||||
var barrel = source.GetBarrel(hp);
|
||||
|
|
@ -34,7 +55,9 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
|
|||
p.Velocity = barrel.forward * weapon.Velocity;
|
||||
p.Thrust = item.Evaluate(launcher.Thrust);
|
||||
p.TopSpeed = item.Evaluate(launcher.MissileVelocity);
|
||||
OnFireGuided.OnNext((source.Entity, target.transform, p));
|
||||
Bind(p, source.Entity.Zone, shotId);
|
||||
// A round with no target (a fused round fired at none) has no transform to hand a listener.
|
||||
OnFireGuided.OnNext((source.Entity, target != null ? target.transform : null, p));
|
||||
}
|
||||
else if(weapon.Data is GuidedWeaponData guidance)
|
||||
{
|
||||
|
|
@ -54,6 +77,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
|
|||
p.Thrust = item.Evaluate(guidance.Thrust);
|
||||
p.TopSpeed = item.Evaluate(guidance.MissileVelocity);
|
||||
p.TargetPosition = () => (source.Entity.Position + length(source.LookAtPoint.position.ToCultMath() - source.Entity.Position) * source.Entity.LookDirection).ToUnity();
|
||||
Bind(p, source.Entity.Zone, shotId);
|
||||
}
|
||||
else Debug.LogError($"Weapon {item.Data.Name} linked to {name} effect, but is not a Launcher!");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,22 +29,10 @@ public static class AetheriaStores
|
|||
cache.AllStoredDocuments.All(stored => stored.Descriptor != descriptor));
|
||||
if (missing != null)
|
||||
throw new InvalidOperationException($"Catalog {catalogPath} has no {missing.SchemaName} record; catalog globals are authored, never invented.");
|
||||
// R-heat (docs/stats-and-power-cut.md): every equippable design's heat response must describe a
|
||||
// coherent range before anything reads it. Fails loudly, naming the item.
|
||||
foreach (var data in cache.GetAll<EquippableItemData>())
|
||||
{
|
||||
StatValidation.ValidateHeatResponse(data);
|
||||
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
|
||||
// Cut 7 (docs/stats-and-power-cut.md): a stat naming a role its design lacks is refused.
|
||||
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
|
||||
}
|
||||
// Cut 2 (docs/stats-and-power-cut.md): a consumable's own StatModifierData needs the same check;
|
||||
// consumables carry no heat response, so this is not folded into the loop above.
|
||||
foreach (var data in cache.GetAll<ConsumableItemData>())
|
||||
{
|
||||
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
|
||||
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
|
||||
}
|
||||
// Every catalog document is held to the one check Upsert applies on write: R-heat (docs/stats-and-power-
|
||||
// cut.md), stat modifiers, role usage (Cut 7). Fails loudly, naming the item.
|
||||
foreach (var data in cache.GetAll<EquippableItemData>()) CultRecordRefs.Validate(data);
|
||||
foreach (var data in cache.GetAll<ConsumableItemData>()) CultRecordRefs.Validate(data);
|
||||
return cache;
|
||||
}
|
||||
catch
|
||||
|
|
|
|||
|
|
@ -57,10 +57,12 @@ public class CombatState : BaseState
|
|||
var group = _agent.Ship.WeaponGroups[i];
|
||||
var dps = 0f;
|
||||
foreach (var weapon in group.weapons)
|
||||
if (weapon.Item.Online.Value &&
|
||||
weapon.MinRange < targetDistance &&
|
||||
targetDistance < weapon.Range &&
|
||||
(weapon is ConstantWeapon ||
|
||||
// The range test is FireControl's (Designated), and a weapon Solve refuses adds nothing to a group's
|
||||
// damage.
|
||||
if (weapon.Item.Online.Value &&
|
||||
FireControl.Designated(weapon, _agent.Ship, target, out _) &&
|
||||
!FireControl.Refuses(weapon, _agent.Ship) &&
|
||||
(weapon is ConstantWeapon ||
|
||||
weapon is InstantWeapon instantWeapon && instantWeapon.CanFire))
|
||||
{
|
||||
if(weapon is LockWeapon lockWeapon)
|
||||
|
|
@ -111,13 +113,12 @@ public class CombatState : BaseState
|
|||
toTarget = normalize(predictedPosition - _agent.Ship.Position);
|
||||
}
|
||||
|
||||
// Cut 3: replaces Cut 1's bare InArc, which HitProbability already subsumes (it returns zero out
|
||||
// of arc) -- this is the AI's own "worth it" heuristic layered on top of the shared gate, not a
|
||||
// second gate.
|
||||
var shouldFire = FireControl.HitProbability(testWeapon, _agent.Ship, target) >= _agent.Settings.AgentMinHitProbability;
|
||||
// Each weapon decides for itself (operator ruling 2026-09-30): a group shares a trigger, not a
|
||||
// verdict. FireControl.AgentFires is the AI's "worth it" heuristic for a weapon that hits what it
|
||||
// fires at, and "the target is designated" for a fused one.
|
||||
foreach (var weapon in _agent.Ship.WeaponGroups[selectedGroup].weapons)
|
||||
{
|
||||
if (shouldFire)
|
||||
if (FireControl.AgentFires(weapon, _agent.Ship, target))
|
||||
weapon.Activate();
|
||||
else if (weapon.Firing)
|
||||
weapon.Deactivate();
|
||||
|
|
|
|||
|
|
@ -160,7 +160,10 @@ public class ChargedWeapon : InstantWeapon
|
|||
|
||||
public override void Activate()
|
||||
{
|
||||
if(!_charging && !_coolingDown)
|
||||
// CanFire also holds a weapon whose released charge has a burst pending: its cooldown starts at its first round,
|
||||
// so a charge started before then would overlap it.
|
||||
// A refused weapon never starts charging: it would pay charge heat and audio for a shot Trigger drops.
|
||||
if(!_charging && CanFire && !FireControl.Refuses(this, Entity))
|
||||
{
|
||||
OnStartCharging?.Invoke();
|
||||
Item.FireAudioEvent(ChargedWeaponAudioEvent.Start);
|
||||
|
|
|
|||
|
|
@ -91,7 +91,13 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC
|
|||
// Cut 5 (docs/fire-control-cut.md, 5.3, Soul finding 9): StanceAllowsFire alone let a side-mounted beam
|
||||
// fire forward -- ArcAllowsFire joins it here, matching InstantWeapon.cs's player arc gate (Q2: manual and
|
||||
// programmatic are one truth, and a continuous weapon is no exception).
|
||||
public float PowerRequest(float dt) => _firing && StanceAllowsFire && ArcAllowsFire ? EvaluateNominalPower(_data.Energy) * dt : 0f;
|
||||
// Operator ruling 2026-09-30: a refused round is free, and a beam is a stream of rounds, so a fused beam whose
|
||||
// arming distance exceeds its Range fires nothing and draws nothing -- no power, ammo, wear, heat or
|
||||
// visibility. FireControl.Refuses is the one arming test; it reads the Range Execute last refreshed, the same
|
||||
// one-tick lag every PowerRequest reads its stats with.
|
||||
private bool MayFire => StanceAllowsFire && ArcAllowsFire && !FireControl.Refuses(this, Entity);
|
||||
|
||||
public float PowerRequest(float dt) => _firing && MayFire ? EvaluateNominalPower(_data.Energy) * dt : 0f;
|
||||
|
||||
// Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Low -- offense, same as InstantWeapon.
|
||||
public int DefaultPowerTier => PowerTiers.Low;
|
||||
|
|
@ -99,10 +105,11 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC
|
|||
public override bool Execute(float dt)
|
||||
{
|
||||
base.Execute(dt);
|
||||
if (_firing && !(StanceAllowsFire && ArcAllowsFire))
|
||||
if (_firing && !MayFire)
|
||||
{
|
||||
// Safed: shooter has a target and hasn't declared hostility toward it, or the target no longer
|
||||
// bears (5.3: a beam obeys its arc exactly as InstantWeapon's trigger does).
|
||||
// bears (5.3: a beam obeys its arc exactly as InstantWeapon's trigger does), or a fused round is
|
||||
// refused.
|
||||
_firing = false;
|
||||
OnStopFiring?.Invoke();
|
||||
return false;
|
||||
|
|
@ -187,7 +194,9 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC
|
|||
|
||||
public override void Activate()
|
||||
{
|
||||
if(!_firing && !_reloading)
|
||||
// A refused beam never starts (operator ruling 2026-09-30): OnStartFiring drives the beam's visuals and
|
||||
// audio, so starting it only for Execute to stop it a tick later would flash a beam that fires nothing.
|
||||
if(!_firing && !_reloading && !FireControl.Refuses(this, Entity))
|
||||
{
|
||||
_firing = true;
|
||||
OnStartFiring?.Invoke();
|
||||
|
|
|
|||
|
|
@ -41,6 +41,8 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
protected readonly InputCapacitor _capacitor = new InputCapacitor();
|
||||
|
||||
protected int _burstRemaining;
|
||||
private bool _burstPaid;
|
||||
private bool _burstStarted;
|
||||
private float _burstTimer;
|
||||
private float _burstInterval;
|
||||
protected float _cooldown; // Normalized
|
||||
|
|
@ -52,7 +54,8 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
public float Cooldown { get; protected set; }
|
||||
public virtual bool CanFire
|
||||
{
|
||||
get => !_coolingDown;
|
||||
// A triggered burst that has not yet fired a round is not ready either: its cooldown has not started.
|
||||
get => !_coolingDown && (_burstStarted || _burstRemaining == 0);
|
||||
}
|
||||
|
||||
public override float DamagePerSecond => Damage / Cooldown;
|
||||
|
|
@ -103,16 +106,20 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
// through -- a player's action-bar Activate() reaches this exactly the same way Combat.cs's and
|
||||
// TurretController.cs's Activate() calls do.
|
||||
if (!ArcAllowsFire) return;
|
||||
// A refused round is free (operator ruling 2026-09-30): no ammo, energy or cooldown is spent on a burst
|
||||
// whose first round FireControl would refuse.
|
||||
if (FireControl.Refuses(this, Entity)) return;
|
||||
|
||||
// If 1 ammo is consumed per burst, perform ammo and energy consumption here
|
||||
// UseAmmo returns false when triggering reload; cancel firing if that is the case
|
||||
if(_data.SingleAmmoBurst && (!TrySpendActivationEnergy() || !UseAmmo())) return;
|
||||
|
||||
// A burst that pays once (SingleAmmoBurst) pays at its first round that is not refused, in Execute, judged
|
||||
// with the Range that round flies with: paying here would judge with the Range of the previous tick, and a
|
||||
// Range that fell in between would spend the ammo on rounds Fire then refuses.
|
||||
_burstPaid = false;
|
||||
_burstRemaining = (int) BurstCount;
|
||||
_burstInterval = BurstTime / _burstRemaining;
|
||||
_burstTimer = 0;
|
||||
_cooldown = 1;
|
||||
_coolingDown = true;
|
||||
// The cooldown starts with the burst's first round that is not refused (Execute), not here: a burst whose
|
||||
// every round is refused fires nothing and leaves no cooldown behind.
|
||||
_burstStarted = false;
|
||||
}
|
||||
|
||||
protected override void UpdateStats()
|
||||
|
|
@ -227,16 +234,32 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
_burstTimer += dt;
|
||||
while (_burstRemaining > 0 && _burstTimer > 0)
|
||||
{
|
||||
// If multiple ammo is consumed per burst, perform ammo and energy consumption here
|
||||
// UseAmmo returns false when triggering reload; cancel firing if that is the case
|
||||
if (!_data.SingleAmmoBurst && (!TrySpendActivationEnergy() || !UseAmmo()))
|
||||
// A fused round whose arming distance Range cannot reach is refused, per round, before anything is
|
||||
// spent (operator ruling 2026-09-30): it costs no ammo, energy, sound, heat, wear or visibility.
|
||||
// The decision is FireControl's; Fire makes the same one.
|
||||
var refused = FireControl.Refuses(this, Entity);
|
||||
// Ammo and energy are consumed here, per round, or once per burst at its first unrefused round
|
||||
// (SingleAmmoBurst). UseAmmo returns false when triggering reload; cancel firing if that is the case
|
||||
if (!refused && !_burstPaid && (!TrySpendActivationEnergy() || !UseAmmo()))
|
||||
{
|
||||
_burstRemaining = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!refused)
|
||||
{
|
||||
_burstPaid = _data.SingleAmmoBurst;
|
||||
if (!_burstStarted)
|
||||
{
|
||||
_burstStarted = true;
|
||||
_cooldown = 1 - dt / Cooldown;
|
||||
// The round starts the cooldown after this tick's decrement above: charge the tick to it, so the cadence stays Cooldown
|
||||
_coolingDown = true;
|
||||
}
|
||||
}
|
||||
|
||||
_burstRemaining--;
|
||||
_burstTimer -= _burstInterval;
|
||||
if (refused) continue;
|
||||
// Cut 3: this is fire authority's one entry point. FireControl.Fire freezes the payload snapshot
|
||||
// (Q6 -- the gun's own stats at this exact instant, base.Execute(dt) above already refreshed them
|
||||
// this tick) and queues a PendingShot; nothing downstream re-evaluates a stat.
|
||||
|
|
|
|||
|
|
@ -73,16 +73,12 @@ public class TurretController : Behavior, IInitializableBehavior
|
|||
}
|
||||
else
|
||||
Entity.LookDirection = normalize(diff);
|
||||
var dist = length(diff);
|
||||
|
||||
foreach (var x in _weapons)
|
||||
{
|
||||
var data = x.Data as WeaponData;
|
||||
// Cut 3 (docs/fire-control-cut.md): the same gate and threshold Combat.cs uses -- HitProbability
|
||||
// already subsumes the bare arc test (zero out of arc), so this is the "worth it" heuristic, not
|
||||
// a parallel arc check.
|
||||
var fire = FireControl.HitProbability(x, Entity, Entity.Target.Value) >= Entity.ItemManager.GameplaySettings.AgentMinHitProbability;
|
||||
if (x.Evaluate(data.Range) > dist && fire)
|
||||
// The same per-weapon decision Combat.cs makes; the range test is part of it (a shot out of range
|
||||
// is not designated and prices at zero).
|
||||
if (FireControl.AgentFires(x, Entity, Entity.Target.Value))
|
||||
{
|
||||
x.Activate();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,16 +107,8 @@ public abstract class Weapon : Behavior, IActivatedBehavior
|
|||
// gate, not the gate itself. With no target set, behaviour is unchanged (nothing to bear on).
|
||||
// Cut 5, 5.4 (Soul finding 11): the point-blank special case this used to carry moved into InArc itself --
|
||||
// one bearing test, one owner, so every caller (not just this one) gets a point-blank shot that bears.
|
||||
public bool ArcAllowsFire
|
||||
{
|
||||
get
|
||||
{
|
||||
var target = Entity.Target.Value;
|
||||
if (target == null) return true;
|
||||
var toTarget = target.Position - Entity.Position;
|
||||
return FireControl.InArc(Item, toTarget);
|
||||
}
|
||||
}
|
||||
// FireControl owns the gate, including its one exemption: a fused weapon fires out of arc.
|
||||
public bool ArcAllowsFire => FireControl.ArcPermitsFire(this, Entity);
|
||||
|
||||
public Weapon(WeaponData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -57,6 +57,67 @@ public static class FireControl
|
|||
return dot(MountDirection(weapon), planarTarget) >= cos(radians(arc / 2f));
|
||||
}
|
||||
|
||||
// The one place a weapon's payload is read: its blast radius, and the fuse it detonates with. A weapon
|
||||
// detonates only with both a fuse and a radius above zero; either alone is inert and resolves as a direct
|
||||
// hit (nothing polices that), so a null return means "not fused".
|
||||
public static WeaponFuse? FuseOf(EquippedItem item, out float blastRadius)
|
||||
{
|
||||
var data = item?.Data as WeaponItemData;
|
||||
blastRadius = data?.BlastRadius > 0f ? data.BlastRadius.Value : 0f;
|
||||
return blastRadius > 0f ? data.Fuse : null;
|
||||
}
|
||||
|
||||
// The one arc gate on the trigger. A fused weapon fires whatever the arc says: a target it cannot bear on is
|
||||
// no reason to keep it silent, the round flies along the arc-clamped aim and bursts at the target's range
|
||||
// (Fire; operator ruling 2026-09-30, "the user is hoping that the arc gets the weapon close enough to still
|
||||
// splash some damage"). A weapon that only hits what it fires at still refuses. Fire reads InArc itself to
|
||||
// choose that flight, so the two share the one bearing test and differ only in this exemption.
|
||||
public static bool ArcPermitsFire(Weapon weapon, Entity shooter)
|
||||
{
|
||||
var target = shooter.Target.Value;
|
||||
if (target == null) return true;
|
||||
return FuseOf(weapon.Item, out _) != null || InArc(weapon.Item, target.Position - shooter.Position);
|
||||
}
|
||||
|
||||
// Whether the shooter's next round from this weapon is refused: the weapons ask before they spend anything, so
|
||||
// a refused round costs no ammo, energy, sound, heat, wear or visibility (operator ruling 2026-09-30). The
|
||||
// answer is Solve's own -- there is no second copy of the arming test.
|
||||
public static bool Refuses(Weapon weapon, Entity shooter) =>
|
||||
Solve(weapon, weapon.Item, shooter, shooter.Target.Value).Outcome == FireOutcome.Refused;
|
||||
|
||||
// The agents' trigger decision (Combat, TurretController), one weapon at a time (operator ruling 2026-09-30).
|
||||
// A weapon that fires at what it hits fires when the shot is worth taking. A fused weapon fires whenever its
|
||||
// target is designated, whatever the arc: the round is sent out of arc on purpose (Solve). An agent never
|
||||
// fires a fused weapon at nothing -- no target, or one it holds no valid data on, is no reason to fish -- and
|
||||
// never one Solve refuses: a refused weapon is not a weapon it can use.
|
||||
public static bool AgentFires(Weapon weapon, Entity shooter, Entity target)
|
||||
{
|
||||
if (FuseOf(weapon.Item, out _) == null)
|
||||
return HitProbability(weapon, shooter, target) >= shooter.ItemManager.GameplaySettings.AgentMinHitProbability;
|
||||
var solution = Solve(weapon, weapon.Item, shooter, target);
|
||||
return solution.Designated && solution.Outcome != FireOutcome.Refused;
|
||||
}
|
||||
|
||||
// Operator ruling 2026-09-30: a shot with nothing to bear on flies along where its shooter is aiming
|
||||
// (Entity.LookDirection -- the player's mouse or a turret's tracking), restricted by the mount's arc. The
|
||||
// arc is InArc's own cone: an aim inside it is used as is, one outside it is turned to the nearest edge of
|
||||
// the same cone. There is no second bearing test here; the edge is where InArc stops passing. A shooter
|
||||
// with no aim set (LookDirection zero) aims down the mount, the same fallback InArc takes for a zero bearing.
|
||||
// The simulation had no aim clamp before this: the Unity barrel's ArticulationPoint clamps the picture,
|
||||
// and a target outside the arc merely priced the shot at zero.
|
||||
public static float2 AimDirection(EquippedItem item, Entity shooter)
|
||||
{
|
||||
var mount = MountDirection(item).xz;
|
||||
var look = shooter.LookDirection.xz;
|
||||
if (lengthsq(look) < 1e-6f) return mount;
|
||||
look = normalize(look);
|
||||
if (InArc(item, float3(look.x, 0, look.y))) return look;
|
||||
|
||||
var half = radians(ArcFor(item) / 2f);
|
||||
var turn = mount.x * look.y - mount.y * look.x >= 0f ? half : -half;
|
||||
return float2(mount.x * cos(turn) - mount.y * sin(turn), mount.x * sin(turn) + mount.y * cos(turn));
|
||||
}
|
||||
|
||||
// Cut 2, R5: whether `observer` has resolved `item` (which must belong to some entity in the zone) well
|
||||
// enough to aim at it. Derived fresh from EntityInfoGathered on every call -- nothing caches a reveal
|
||||
// result, so decay drops it the moment info falls back below tier, with no clearing loop anywhere.
|
||||
|
|
@ -152,28 +213,47 @@ public static class FireControl
|
|||
// freezes (R10), gated exactly as HitProbability gates. Nothing about the target's facing or silhouette
|
||||
// enters here; that is Silhouette's and PSpread's job, priced fresh by HitProbability below and again,
|
||||
// live, by Commit at the commit tick. 0 the moment any gate closes.
|
||||
private static float PFire(Weapon weapon, Entity source, Entity target) => PFire(weapon, source, target, out _);
|
||||
private static float PFire(Weapon weapon, Entity source, Entity target) => PFire(weapon, source, target, out _, out _, out _);
|
||||
|
||||
// The `out range` overload is HitProbability's own gate call -- one computation of `target.Position -
|
||||
// source.Position`, not two. HitProbability used to recompute its own copy for PSpread, which is exactly
|
||||
// the kind of split authority Cut 3 named as the risk (two places computing the same vector, free to
|
||||
// drift or to have their subtraction order flipped in only one of them).
|
||||
private static float PFire(Weapon weapon, Entity source, Entity target, out float range)
|
||||
private static float PFire(Weapon weapon, Entity source, Entity target, out float range) =>
|
||||
PFire(weapon, source, target, out range, out _, out _);
|
||||
|
||||
// The one answer to "does the shooter hold valid targeting data on this target": visible, in range and locked
|
||||
// (for a LockWeapon). PFire, Solve and the agents' trigger decision all read it here, and nowhere else.
|
||||
// F8 correction (Soul's fix batch, 2026-09-24): `range` is computed for any non-null target, before any
|
||||
// gate -- Fire reads it for flightTime, and flightTime must reflect the real distance even when a gate (not
|
||||
// visible, out of range) already denies the target. Planar (R7: the simulation is 2D): the range gate, the
|
||||
// burst reach and the range clamp all measure the same distance, so a target's height never moves one of
|
||||
// them without the others.
|
||||
public static bool Designated(Weapon weapon, Entity source, Entity target, out float range)
|
||||
{
|
||||
range = 0f;
|
||||
if (target == null) return false;
|
||||
range = length((target.Position - source.Position).xz);
|
||||
return source.VisibleEntities.Contains(target) && range >= weapon.MinRange && range <= weapon.Range &&
|
||||
!(weapon is LockWeapon lockWeapon && !lockWeapon.IsLocked);
|
||||
}
|
||||
|
||||
// `designated` is the answer above. `inArc` is the bearing test, asked only once a target is designated.
|
||||
// PFire prices a shot at zero unless both hold. Fire reads them to decide what a fused round flies at
|
||||
// (operator rulings 2026-09-30): without valid data it has no target and bursts at max range; with data but
|
||||
// out of arc it bursts at the target's range, along the aim. The HUD reads Designated and the
|
||||
// arc from Solve and Inspect and decides nothing.
|
||||
private static float PFire(Weapon weapon, Entity source, Entity target, out float range, out bool designated, out bool inArc)
|
||||
{
|
||||
range = 0f;
|
||||
designated = false;
|
||||
inArc = false;
|
||||
if (target == null) return 0f;
|
||||
|
||||
// F8 correction (Soul's fix batch, 2026-09-24): range is computed for any non-null target, before any
|
||||
// gate -- Fire reads it through this same overload for flightTime, and flightTime must reflect the
|
||||
// real distance even when a gate (not visible, out of arc) already prices the shot at PFire 0. The
|
||||
// gates below still short-circuit the rest of the shooter-side probability in the same order as before.
|
||||
var toTarget = target.Position - source.Position;
|
||||
range = length(toTarget);
|
||||
|
||||
if (!source.VisibleEntities.Contains(target)) return 0f;
|
||||
if (range < weapon.MinRange || range > weapon.Range) return 0f;
|
||||
if (weapon is LockWeapon lockWeapon && !lockWeapon.IsLocked) return 0f;
|
||||
if (!InArc(weapon.Item, toTarget)) return 0f;
|
||||
designated = Designated(weapon, source, target, out range);
|
||||
if (!designated) return 0f;
|
||||
inArc = InArc(weapon.Item, target.Position - source.Position);
|
||||
if (!inArc) return 0f;
|
||||
|
||||
var settings = source.ItemManager.GameplaySettings;
|
||||
var info = source.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f;
|
||||
|
|
@ -253,13 +333,14 @@ public static class FireControl
|
|||
MinRange = weapon.MinRange,
|
||||
MaxRange = weapon.Range
|
||||
};
|
||||
var solution = Solve(weapon, weapon.Item, source, target);
|
||||
diagnostic.Outcome = solution.Outcome;
|
||||
diagnostic.BurstReach = solution.BurstReach;
|
||||
if (target == null) return diagnostic;
|
||||
|
||||
var toTarget = target.Position - source.Position;
|
||||
diagnostic.Range = length(toTarget);
|
||||
diagnostic.Visible = source.VisibleEntities.Contains(target);
|
||||
diagnostic.InRange = diagnostic.Range >= weapon.MinRange && diagnostic.Range <= weapon.Range;
|
||||
diagnostic.Locked = !(weapon is LockWeapon lockWeapon) || lockWeapon.IsLocked;
|
||||
diagnostic.Range = length(toTarget.xz);
|
||||
diagnostic.Designated = solution.Designated;
|
||||
diagnostic.InArc = InArc(weapon.Item, toTarget);
|
||||
|
||||
var targetHull = source.ItemManager.GetData(target.Hull) as HullData;
|
||||
|
|
@ -341,6 +422,92 @@ public static class FireControl
|
|||
return shot.Target == null ? 1f : saturate(1f - deviation / shot.Tracking);
|
||||
}
|
||||
|
||||
// The one decision about what a round does, made from the shooter's state and a target and nothing else:
|
||||
// no draw, no side effect. Fire freezes it into a PendingShot; Inspect shows it to the HUD; the weapons ask
|
||||
// it whether a round is refused before they spend anything -- so a refusal is decided once, by the same
|
||||
// code that would have flown the round, and the HUD cannot forecast a burst the trigger will not fire.
|
||||
// Direct: a round that resolves against its target (a weapon without a fuse). Burst: a fused round, with
|
||||
// BurstReach the planar distance from the shooter at which it bursts. Refused: a fused round whose blast
|
||||
// radius (its arming distance) exceeds the weapon's Range; it cannot be fired.
|
||||
public static FireSolution Solve(Weapon weapon, EquippedItem item, Entity source, Entity target)
|
||||
{
|
||||
var pFire = PFire(weapon, source, target, out var fireRange, out var designated, out var inArc);
|
||||
|
||||
// Cut 12.4(a) (Q12-6, "WeaponModifiers are labels, not behaviour"): a blast is a property of the
|
||||
// weapon's data fields alone, resolved and frozen here like every other payload field -- never decided
|
||||
// later by a Unity projectile, and never by a label. Solve decides "detonates" once: a fuse is frozen
|
||||
// only when BlastRadius > 0, and null otherwise, so a radius without a fuse or a fuse without a radius
|
||||
// is inert and resolves as a direct hit (nothing polices that). A zero-radius freeze is what Step below
|
||||
// still reads as "resolve this shot with Apply."
|
||||
var fuse = FuseOf(item, out var blastRadius);
|
||||
|
||||
// Operator rulings 2026-09-30. A fused round flies along the shooter's aim (AimDirection, clamped to the
|
||||
// mount's arc) and carries no target -- so nothing at resolution asks whether one is still around --
|
||||
// unless its target is designated (visible, in range, locked) and in arc:
|
||||
// * no valid targeting data (no target, or one out of range, not visible or not locked) counts as no
|
||||
// lock and bursts at the weapon's Range, the stat PFire's range gate reads: bomb fishing;
|
||||
// * valid data but out of arc bursts at the target's range, which the range gate has already held to
|
||||
// Range, along that same clamped aim: the arc is hoped to land the blast near enough to splash.
|
||||
// Either way the point frozen here is the farthest the round can burst: whatever its fuse, it detonates at the
|
||||
// first hull on its aim line short of it (CommitBurst; operator ruling 2026-09-30, "a no-lock round stops at
|
||||
// the first hull"), and bomb fishing bursts at this point only when the line is clear.
|
||||
// Either way the round flies at the weapon's Velocity like a targeted shot flies to its intercept. A shot
|
||||
// without a fuse keeps its target as before.
|
||||
// Arming distance (operator ruling 2026-09-30): the blast radius, measured from the shooter's position and
|
||||
// blind to hull size -- a large hull can take splash from its own close burst. A round never bursts nearer
|
||||
// than that, so a burst that would land nearer is pushed out along its flight line to it. A round fired at a
|
||||
// valid target inside the radius is pushed out but stays a targeted round: it keeps its target, so a target
|
||||
// that leaves the zone cancels it like any other. A round whose Range is shorter than the arming distance
|
||||
// cannot be fired at all: it is refused, per round, where Range is read after Execute refreshed it (a
|
||||
// burst's later rounds and a power-starved Range included).
|
||||
var engaged = fuse != null && !(designated && inArc) ? null : target;
|
||||
var origin = source.Position;
|
||||
var travelDirection = engaged != null ? TravelDirection(weapon, source, engaged) : AimDirection(item, source);
|
||||
|
||||
var arming = fuse != null ? blastRadius : 0f;
|
||||
var burstPosition = engaged != null ? engaged.Position : origin;
|
||||
var flightDistance = 0f;
|
||||
if (fuse != null && engaged != null)
|
||||
{
|
||||
// Nothing bursts beyond max range: an intercept a receding target leads the round past Range is
|
||||
// pulled back along its own line to Range.
|
||||
var intercept = PredictedIntercept(weapon, source, engaged);
|
||||
var interceptReach = length((intercept - origin).xz);
|
||||
var point = interceptReach > weapon.Range ? origin + (intercept - origin) * (weapon.Range / interceptReach) : intercept;
|
||||
burstPosition = Armed(origin, travelDirection, arming, point);
|
||||
flightDistance = max(fireRange, arming);
|
||||
}
|
||||
else if (fuse != null)
|
||||
{
|
||||
var reach = designated ? fireRange : weapon.Range;
|
||||
burstPosition = Armed(origin, travelDirection, arming, origin + float3(travelDirection.x, 0, travelDirection.y) * reach);
|
||||
flightDistance = max(reach, arming);
|
||||
}
|
||||
else if (engaged != null) flightDistance = fireRange;
|
||||
|
||||
var solution = new FireSolution
|
||||
{
|
||||
Outcome = weapon.Range < arming ? FireOutcome.Refused : fuse != null ? FireOutcome.Burst : FireOutcome.Direct,
|
||||
PFire = pFire,
|
||||
FireRange = fireRange,
|
||||
Designated = designated,
|
||||
Engaged = engaged,
|
||||
TravelDirection = travelDirection,
|
||||
BurstPosition = burstPosition,
|
||||
BurstReach = length((burstPosition - origin).xz),
|
||||
FlightDistance = flightDistance,
|
||||
Fuse = fuse,
|
||||
BlastRadius = blastRadius
|
||||
};
|
||||
return solution;
|
||||
}
|
||||
|
||||
// The arming rule, once: a burst point nearer to `origin` than `arming` (planar, blind to hull size) is pushed
|
||||
// out along the unit planar `direction` to it. Solve applies it to the point it plans; the detonation of a
|
||||
// contact or delayed blast, whose point is found on the hull only at resolution, applies it to that point.
|
||||
private static float3 Armed(float3 origin, float2 direction, float arming, float3 point) =>
|
||||
length((point - origin).xz) < arming ? origin + float3(direction.x, 0, direction.y) * arming : point;
|
||||
|
||||
// Cut 3, R1: called once per burst step from InstantWeapon.Execute. Computes flight time, freezes the
|
||||
// payload snapshot (R10, Q6 -- the gun that fired it, not a re-read later), and queues a PendingShot for
|
||||
// Zone.Step to age and eventually resolve. Returns the ShotId so the caller's OnFire event can carry it to
|
||||
|
|
@ -361,49 +528,34 @@ public static class FireControl
|
|||
// R1's engage gate and the shooter-side probability, evaluated now and frozen: nothing at commit time
|
||||
// re-reads a stat, an info level or a range. Cut 12.2: PFire no longer carries the spread/hull share --
|
||||
// those are priced live at Commit, against the target's facing then, not now (Bearing timing, R10).
|
||||
// F8 (Soul's fix batch, 2026-09-24): the `out range` overload is the one range HitProbability now
|
||||
// reads too -- Fire used to recompute its own second copy of `target.Position - source.Position` for
|
||||
// fireRange, right beside the copy PFire's gate already computed.
|
||||
var pFire = PFire(weapon, source, target, out var fireRange);
|
||||
var travelDirection = target != null ? TravelDirection(weapon, source, target) : float2(0, 1);
|
||||
// Solve is the one range and the one burst decision Inspect and the weapons' refusal check read too.
|
||||
var solution = Solve(weapon, item, source, target);
|
||||
if (solution.Outcome == FireOutcome.Refused) return 0;
|
||||
var pFire = solution.PFire;
|
||||
var fireRange = solution.FireRange;
|
||||
var engaged = solution.Engaged;
|
||||
var travelDirection = solution.TravelDirection;
|
||||
var burstPosition = solution.BurstPosition;
|
||||
var fuse = solution.Fuse;
|
||||
var blastRadius = solution.BlastRadius;
|
||||
var origin = source.Position;
|
||||
|
||||
var targetVelocity = float3.zero;
|
||||
var targetPosition = source.Position;
|
||||
var flightTime = 0f;
|
||||
if (target != null)
|
||||
var targetPosition = origin;
|
||||
if (engaged != null)
|
||||
{
|
||||
targetVelocity = float3(target.Velocity.x, 0, target.Velocity.y);
|
||||
targetPosition = target.Position;
|
||||
flightTime = weapon.Velocity > .01f ? fireRange / weapon.Velocity : 0f;
|
||||
targetVelocity = float3(engaged.Velocity.x, 0, engaged.Velocity.y);
|
||||
targetPosition = engaged.Position;
|
||||
}
|
||||
var flightTime = weapon.Velocity > .01f ? solution.FlightDistance / weapon.Velocity : 0f;
|
||||
|
||||
var commitHorizon = source.ItemManager.GameplaySettings.CommitHorizon;
|
||||
|
||||
// Cut 12.4(a) (Q12-6, "WeaponModifiers are labels, not behaviour"): a blast is a property of the
|
||||
// weapon's data fields alone, resolved and frozen here like every other payload field -- never decided
|
||||
// later by a Unity projectile, and never by a label. Fire decides "detonates" once: a fuse is frozen
|
||||
// only when BlastRadius > 0, and null otherwise, so a radius without a fuse or a fuse without a radius
|
||||
// is inert and resolves as a direct hit (nothing polices that). A zero-radius freeze is what Step below
|
||||
// still reads as "resolve this shot with Apply."
|
||||
var weaponItemData = item.Data as WeaponItemData;
|
||||
var blastRadius = weaponItemData?.BlastRadius > 0f ? weaponItemData.BlastRadius.Value : 0f;
|
||||
var fuse = blastRadius > 0f ? weaponItemData.Fuse : null;
|
||||
var burstPosition = blastRadius > 0f && target != null ? PredictedIntercept(weapon, source, target) : targetPosition;
|
||||
// Operator ruling 2026-09-30 ("fused weapons without a lock explode at max range"): a fused shot with no
|
||||
// target bursts where its own aim line ends -- the mount direction at the weapon's Range stat, the same
|
||||
// stat PFire's range gate reads -- and flies there at the weapon's Velocity, like a targeted shot flies
|
||||
// to its intercept. Only the burst point and flight time differ; Apply detonates it through Detonate.
|
||||
if (fuse != null && target == null)
|
||||
{
|
||||
burstPosition = source.Position + MountDirection(item) * weapon.Range;
|
||||
flightTime = weapon.Velocity > .01f ? weapon.Range / weapon.Velocity : 0f;
|
||||
}
|
||||
|
||||
var shot = new PendingShot
|
||||
{
|
||||
ShotId = zone.NextShotId(),
|
||||
Source = source,
|
||||
Target = target,
|
||||
Target = engaged,
|
||||
Weapon = item,
|
||||
Aimed = source.ResolvedTargetItem,
|
||||
Damage = damageOverride ?? weapon.Damage,
|
||||
|
|
@ -417,10 +569,14 @@ public static class FireControl
|
|||
Spread = weapon.Spread,
|
||||
FireRange = fireRange,
|
||||
FireTime = now,
|
||||
FireOrigin = origin,
|
||||
FireTargetPosition = targetPosition,
|
||||
FireTargetVelocity = targetVelocity,
|
||||
ArrivalTime = now + flightTime,
|
||||
CommitTime = now + max(0f, flightTime - commitHorizon),
|
||||
// The commit horizon exists so the target's facing can be read late (Bearing timing). A round fired at
|
||||
// nothing has no facing to read, so it commits at Fire: its burst point is decided from the poses of
|
||||
// the moment it leaves, and a Contact round short of max range can arrive as early as it truly does.
|
||||
CommitTime = fuse != null && engaged == null ? now : now + max(0f, flightTime - commitHorizon),
|
||||
BurstPosition = burstPosition,
|
||||
Fuse = fuse,
|
||||
BlastRadius = blastRadius,
|
||||
|
|
@ -432,8 +588,15 @@ public static class FireControl
|
|||
}
|
||||
|
||||
// Cut 3, R4: ages every shot in the zone, commits the ones that have reached their horizon and resolves
|
||||
// the ones that have arrived. Called from Zone.Update after the entity loop. A shot whose source or target
|
||||
// has left the zone resolves as a miss and is removed outright (0b table), whichever stage it is at.
|
||||
// the ones that have arrived. Called from Zone.Update after the entity loop. A shot whose target has left
|
||||
// the zone resolves as a miss and is removed outright (0b table), whichever stage it is at. A round outlives
|
||||
// its shooter (operator ruling 2026-09-30): the shooter is only an identity a shot carries, never asked
|
||||
// for at resolution, so a shooter that died or left the zone in flight changes nothing about the shot.
|
||||
// Resolution reads the zone and the target; there is no credit or loot for a shooter to receive.
|
||||
// A shot's queue state is settled before anything that can run user code: it is committed in the list before
|
||||
// ShotCommitted fires and removed before its damage is applied (damage observers) or ShotResolved fires, so an
|
||||
// observer that throws costs that one notification, or the rest of that blast, and cannot leave the shot to be
|
||||
// committed, resolved or applied again on every later tick.
|
||||
public static void Step(Zone zone, float dt)
|
||||
{
|
||||
var shots = zone.PendingShots;
|
||||
|
|
@ -444,19 +607,18 @@ public static class FireControl
|
|||
{
|
||||
var shot = shots[i];
|
||||
|
||||
var sourceGone = !zone.Entities.Contains(shot.Source);
|
||||
var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target);
|
||||
if (sourceGone || targetGone)
|
||||
if (targetGone)
|
||||
{
|
||||
// Cut 11 (Soul C4): a shot whose source or target has left the zone resolves as a miss whichever
|
||||
// Cut 11 (Soul C4): a shot whose target has left the zone resolves as a miss whichever
|
||||
// stage it is at (0b table). The resolution is published as a fresh miss rather than by
|
||||
// rewriting shot.Outcome: a committed outcome is immutable (R4) and stays a true record of what
|
||||
// the commit decided, while ShotResolved reports what actually happened -- nothing, because the
|
||||
// target is gone. Republishing the committed outcome here used to put a hit marker on a corpse.
|
||||
var miss = MakeOutcome(shot, false, false, false, int2.zero, float2.zero, 0f, now);
|
||||
var miss = MakeOutcome(shot, ShotResult.Miss, false, false, int2.zero, float2.zero, 0f, now);
|
||||
shots.RemoveAt(i);
|
||||
if (!shot.Committed) zone.ShotCommitted.OnNext(miss);
|
||||
zone.ShotResolved.OnNext(miss);
|
||||
shots.RemoveAt(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -464,8 +626,11 @@ public static class FireControl
|
|||
{
|
||||
shot.Outcome = Commit(zone, shot, now);
|
||||
shot.Committed = true;
|
||||
zone.ShotCommitted.OnNext(shot.Outcome);
|
||||
// A contact burst short of max range arrives when the round has flown that far, not at the frozen
|
||||
// max-range time (CommitBurst). Never later than the frozen time.
|
||||
if (shot.Outcome.Result == ShotResult.Burst) shot.ArrivalTime = min(shot.ArrivalTime, now + shot.Outcome.ArrivalIn);
|
||||
shots[i] = shot;
|
||||
zone.ShotCommitted.OnNext(shot.Outcome);
|
||||
}
|
||||
|
||||
if (shot.Committed && now >= shot.ArrivalTime)
|
||||
|
|
@ -474,9 +639,11 @@ public static class FireControl
|
|||
// which model a shot uses, through its own switch on the frozen Fuse -- Step has no damage
|
||||
// branch left. A direct hit, a proximity burst and a contact or delayed blast all arrive here
|
||||
// the same way; only Apply decides what that means.
|
||||
Apply(shot);
|
||||
zone.ShotResolved.OnNext(shot.Outcome);
|
||||
// Removed first: Apply reaches damage observers (user code), and a shot left in the queue by one
|
||||
// that throws would resolve, and hurt, again on every later tick.
|
||||
shots.RemoveAt(i);
|
||||
Apply(zone, shot);
|
||||
zone.ShotResolved.OnNext(shot.Outcome);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -522,14 +689,18 @@ public static class FireControl
|
|||
if (p <= 0f) return 0f;
|
||||
|
||||
var bearing = Bearing(shot.Target, shot.TravelDirection);
|
||||
var hullData = shot.Source.ItemManager.GetData(shot.Target.Hull) as HullData;
|
||||
var hullData = shot.Target.ItemManager.GetData(shot.Target.Hull) as HullData;
|
||||
sil = Silhouette(shot.Target, hullData, shot.Aimed, bearing, shot.Precision);
|
||||
var settings = shot.Source.ItemManager.GameplaySettings;
|
||||
var settings = shot.Target.ItemManager.GameplaySettings;
|
||||
return p * PSpread(shot.Spread, sil.Span, shot.FireRange, settings.SchematicCellSize) * sil.POnHull;
|
||||
}
|
||||
|
||||
private static ShotOutcome Commit(Zone zone, PendingShot shot, float now)
|
||||
{
|
||||
// A fused round with no target rolls nothing: it bursts. Where is decided here, at the commit, from the
|
||||
// poses of this tick (R4); Apply performs it.
|
||||
if (shot.Fuse != null && shot.Target == null) return CommitBurst(zone, shot, now);
|
||||
|
||||
// Cut 6b, 6.1 (Soul finding 6): a shot's dice belong to the shot, not to whatever else happened to
|
||||
// draw from the engine-wide shared generator first. A pure function of (zone identity, shot id) --
|
||||
// the `| 1u` guards
|
||||
|
|
@ -567,7 +738,7 @@ public static class FireControl
|
|||
bearing = Bearing(shot.Target, shot.TravelDirection);
|
||||
lateral = LateralDraw(sil, random.NextFloat());
|
||||
|
||||
var hullData = shot.Source.ItemManager.GetData(shot.Target.Hull) as HullData;
|
||||
var hullData = shot.Target.ItemManager.GetData(shot.Target.Hull) as HullData;
|
||||
var buffer = ArrayPool<LaneCell>.Shared.Rent(hullData.Shape.Coordinates.Length);
|
||||
try
|
||||
{
|
||||
|
|
@ -601,7 +772,87 @@ public static class FireControl
|
|||
}
|
||||
}
|
||||
|
||||
return MakeOutcome(shot, hit, shielded, shieldBroken, cell, bearing, lateral, now);
|
||||
// A proximity round detonates at its burst point whether or not the roll hit, so a roll that missed is a
|
||||
// Burst, not a Miss: the outcome types what happened, and the HUD must not call a real explosion a miss. A
|
||||
// contact or delayed round detonates only on a hit, so its miss stays a Miss.
|
||||
var proximity = shot.Fuse == WeaponFuse.Proximity;
|
||||
var outcome = MakeOutcome(shot, hit ? ShotResult.Hit : proximity ? ShotResult.Burst : ShotResult.Miss,
|
||||
shielded, shieldBroken, cell, bearing, lateral, now);
|
||||
if (proximity)
|
||||
{
|
||||
outcome.BurstPoint = shot.BurstPosition.xz;
|
||||
outcome.HasBurstPoint = true;
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// Operator rulings 2026-09-30. A fused round with no target bursts at the first hull its aim line crosses
|
||||
// before the max-range point Fire froze, whatever its fuse (contact, proximity and delayed alike: a round with
|
||||
// nothing locked stops on what is in its way), and at the max-range point when the line is clear. The point is
|
||||
// read from this tick's poses and frozen into the outcome (R4, the same timing Commit reads facing at).
|
||||
// Nothing is rolled or drawn, so determinism needs nothing beyond the frozen inputs.
|
||||
private static ShotOutcome CommitBurst(Zone zone, PendingShot shot, float now)
|
||||
{
|
||||
var outcome = MakeOutcome(shot, ShotResult.Burst, false, false, int2.zero, float2.zero, 0f, now);
|
||||
outcome.HasBurstPoint = true;
|
||||
var reach = length(shot.BurstPosition.xz - shot.FireOrigin.xz);
|
||||
var travelled = min(reach, max(HullDistance(zone, shot, reach), shot.BlastRadius));
|
||||
if (travelled < reach)
|
||||
{
|
||||
outcome.BurstPoint = shot.FireOrigin.xz + shot.TravelDirection * travelled;
|
||||
// The round arrives once it has flown that far, which is sooner than the frozen max-range arrival.
|
||||
outcome.ArrivalIn = max(0f, shot.FireTime + (shot.ArrivalTime - shot.FireTime) * travelled / reach - now);
|
||||
}
|
||||
else outcome.BurstPoint = shot.BurstPosition.xz;
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// The distance along a no-lock round's aim line to the first hull it crosses, or `reach` (the
|
||||
// max-range point) when it meets nothing first. The shooter's own hull is never a candidate.
|
||||
// SEAM FOR THE MINING CAMPAIGN: mining chunks are not Entities and are not on this branch. When they land,
|
||||
// whatever they are contributes its own entry distance to this minimum, and nothing else in the file changes.
|
||||
private static float HullDistance(Zone zone, PendingShot shot, float reach)
|
||||
{
|
||||
var nearest = reach;
|
||||
foreach (var entity in zone.Entities)
|
||||
{
|
||||
if (entity == shot.Source) continue;
|
||||
nearest = min(nearest, HullEntry(entity, shot.FireOrigin.xz, shot.TravelDirection));
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
// Where the line from `origin` along the unit planar `direction` meets `entity`'s hull: the world distance from
|
||||
// `origin` to the first metal cell ahead, +infinity when the line meets none, and negative when the origin is
|
||||
// already inside the hull (the blast radius floors every caller's use of it). Read through Lane's own cell
|
||||
// admission (CellsOnLine), in the entity's schematic frame: the line's lateral offset is its own, and cells
|
||||
// wholly behind the origin are skipped. Only a no-lock round asks.
|
||||
private static float HullEntry(Entity entity, float2 origin, float2 direction)
|
||||
{
|
||||
var hullData = entity.ItemManager.GetData(entity.Hull) as HullData;
|
||||
var cellSize = entity.ItemManager.GameplaySettings.SchematicCellSize;
|
||||
var start = entity.ToSchematicPoint(origin);
|
||||
var bearing = Bearing(entity, direction);
|
||||
var lateral = dot(start, Lateral(bearing));
|
||||
var along = dot(start, bearing);
|
||||
|
||||
var entry = float.PositiveInfinity;
|
||||
var buffer = ArrayPool<LaneCell>.Shared.Rent(hullData.Shape.Coordinates.Length);
|
||||
try
|
||||
{
|
||||
var count = CellsOnLine(hullData, bearing, lateral, buffer);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (!(buffer[i].Exit > along)) continue;
|
||||
entry = (buffer[i].Entry - along) * cellSize;
|
||||
break;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<LaneCell>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// R4: the commit is authoritative and immutable from here on -- this only performs what Commit already
|
||||
|
|
@ -657,13 +908,14 @@ public static class FireControl
|
|||
// contact or delayed fuse detonates only on a committed hit, at a point 12.3's own Lane/Reach machinery
|
||||
// locates. This is a default, not a ruling: a blast shot's DamageSpread is not read, and P sits on the
|
||||
// centre lane (see the fuse-point comment on the Contact/Delayed branch below).
|
||||
private static void Apply(PendingShot shot)
|
||||
private static void Apply(Zone zone, PendingShot shot)
|
||||
{
|
||||
// A fused shot with no target has nothing to hit or miss: whatever its fuse, it bursts at the point Fire
|
||||
// froze (max range along the aim line). Detonate is still the one blast path.
|
||||
if (shot.Fuse != null && shot.Target == null)
|
||||
// A Burst outcome detonates at the point Commit decided (its BurstPoint): a fused round with no target,
|
||||
// which has nothing to hit or miss, and a proximity round, which detonates whether its roll hit or not.
|
||||
// Detonate is still the one blast path.
|
||||
if (shot.Outcome.Result == ShotResult.Burst || shot.Fuse == WeaponFuse.Proximity)
|
||||
{
|
||||
Detonate(shot.Source.Zone, shot.BurstPosition.xz, shot.BlastRadius, shot.Damage, shot.DamageType);
|
||||
Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -672,11 +924,6 @@ public static class FireControl
|
|||
case null:
|
||||
ApplyDirectHit(shot);
|
||||
return;
|
||||
case WeaponFuse.Proximity:
|
||||
// Detonates at shot.BurstPosition.xz, which PredictedIntercept froze at Fire (today's airburst
|
||||
// rule, unchanged) -- no roll, and no gate on shot.Outcome.Hit.
|
||||
Detonate(shot.Source.Zone, shot.BurstPosition.xz, shot.BlastRadius, shot.Damage, shot.DamageType);
|
||||
return;
|
||||
case WeaponFuse.Contact:
|
||||
case WeaponFuse.Delayed:
|
||||
ApplyBlastHit(shot);
|
||||
|
|
@ -791,7 +1038,10 @@ public static class FireControl
|
|||
// cancels the host's pose, so the host's own damage is fixed by the commit (R4 holds for it), while
|
||||
// every bystander is judged against where it actually is at arrival -- the same live rule a proximity
|
||||
// burst already applies to everyone.
|
||||
var worldPoint = target.ToWorldPoint(schematicPoint);
|
||||
// The arming rule applies to this point as it does to every other burst (Solve's Armed): a hull met nearer
|
||||
// the muzzle than the blast radius is detonated on at the radius, along the round's own flight line.
|
||||
var hullPoint = target.ToWorldPoint(schematicPoint);
|
||||
var worldPoint = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(hullPoint.x, shot.FireOrigin.y, hullPoint.y)).xz;
|
||||
Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType);
|
||||
}
|
||||
|
||||
|
|
@ -1042,7 +1292,7 @@ public static class FireControl
|
|||
return walked;
|
||||
}
|
||||
|
||||
private static ShotOutcome MakeOutcome(PendingShot shot, bool hit, bool shielded, bool shieldBroken, int2 cell, float2 bearing, float lateral, float now)
|
||||
private static ShotOutcome MakeOutcome(PendingShot shot, ShotResult result, bool shielded, bool shieldBroken, int2 cell, float2 bearing, float lateral, float now)
|
||||
{
|
||||
return new ShotOutcome
|
||||
{
|
||||
|
|
@ -1050,7 +1300,7 @@ public static class FireControl
|
|||
Source = shot.Source,
|
||||
Target = shot.Target,
|
||||
Weapon = shot.Weapon,
|
||||
Hit = hit,
|
||||
Result = result,
|
||||
Shielded = shielded,
|
||||
ShieldBroken = shieldBroken,
|
||||
Cell = cell,
|
||||
|
|
@ -1381,24 +1631,10 @@ public static class FireControl
|
|||
return sil.A; // sil.Count == 0: no metal in the shadow at all -- unreachable while POnHull > 0 gated Commit's roll
|
||||
}
|
||||
|
||||
// Cut 12.2 (docs/fire-control-cut.md, "the rules every sub-cut reads"): exact slab traversal along the
|
||||
// bearing at a fixed lateral offset s, replacing the old 0.5-step sampling march. Collects the occupied
|
||||
// cells whose shadow interval contains s, each with its own entry/exit parameter along b, ordered by
|
||||
// entry (ties broken by dot(cell, b), then cell index for full determinism), then walks forward while
|
||||
// consecutive cells are contiguous (`next.entry <= current.exit + 1e-4`) -- the first gap ends the walk,
|
||||
// the same rule Entity.cs's old march kept. A direct hit starts outside the hull (t -> -infinity), so the
|
||||
// walk's first element is the impact cell. Only that first element is read in 12.2; the rest is 12.3's
|
||||
// armour-first absorption march. Writes into the caller-supplied pooled buffer and returns the walked
|
||||
// count; never allocates on its own.
|
||||
// Cut 12.2 fix batch (S1, Soul's second pass): admission is now decided ONCE, by the exact same shadow
|
||||
// interval Silhouette sums over (Extent(c, ell), the shared function above) -- not by a re-derivation and
|
||||
// not by a second, independent geometric test. The old code ran two tests: this shadow prefilter (a
|
||||
// "re-derivation" of Silhouette's own centre/h, inline) AND SlabAlongB, an independent 2-axis ray-box
|
||||
// intersection that could reject a cell the shadow test had just admitted, purely on float rounding at an
|
||||
// interval edge -- an empty lane for a shot that had already passed its roll (R3 violation, the crash Soul
|
||||
// reproduced through Zone.Update). Deleting the second gate removes the split authority: a cell the shadow
|
||||
// sum counted metal for can no longer be un-counted here.
|
||||
public static int Lane(HullData hull, float2 b, float s, LaneCell[] buffer)
|
||||
// Every occupied cell the line meets, sorted by entry, in the pooled buffer; returns how many. Lane below
|
||||
// walks the contiguous run from the first; a caller that needs the whole line (a contact fuse looking for
|
||||
// the first cell ahead of its origin) reads all of them. One admission test either way.
|
||||
private static int CellsOnLine(HullData hull, float2 b, float s, LaneCell[] buffer)
|
||||
{
|
||||
var ell = Lateral(b);
|
||||
var coords = hull.Shape.Coordinates;
|
||||
|
|
@ -1420,7 +1656,29 @@ public static class FireControl
|
|||
}
|
||||
|
||||
Array.Sort(buffer, 0, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
// Cut 12.2 (docs/fire-control-cut.md, "the rules every sub-cut reads"): exact slab traversal along the
|
||||
// bearing at a fixed lateral offset s, replacing the old 0.5-step sampling march. Collects the occupied
|
||||
// cells whose shadow interval contains s, each with its own entry/exit parameter along b, ordered by
|
||||
// entry (ties broken by dot(cell, b), then cell index for full determinism), then walks forward while
|
||||
// consecutive cells are contiguous (`next.entry <= current.exit + 1e-4`) -- the first gap ends the walk,
|
||||
// the same rule Entity.cs's old march kept. A direct hit starts outside the hull (t -> -infinity), so the
|
||||
// walk's first element is the impact cell. Only that first element is read in 12.2; the rest is 12.3's
|
||||
// armour-first absorption march. Writes into the caller-supplied pooled buffer and returns the walked
|
||||
// count; never allocates on its own.
|
||||
// Cut 12.2 fix batch (S1, Soul's second pass): admission is now decided ONCE, by the exact same shadow
|
||||
// interval Silhouette sums over (Extent(c, ell), the shared function above) -- not by a re-derivation and
|
||||
// not by a second, independent geometric test. The old code ran two tests: this shadow prefilter (a
|
||||
// "re-derivation" of Silhouette's own centre/h, inline) AND SlabAlongB, an independent 2-axis ray-box
|
||||
// intersection that could reject a cell the shadow test had just admitted, purely on float rounding at an
|
||||
// interval edge -- an empty lane for a shot that had already passed its roll (R3 violation, the crash Soul
|
||||
// reproduced through Zone.Update). Deleting the second gate removes the split authority: a cell the shadow
|
||||
// sum counted metal for can no longer be un-counted here.
|
||||
public static int Lane(HullData hull, float2 b, float s, LaneCell[] buffer)
|
||||
{
|
||||
var n = CellsOnLine(hull, b, s, buffer);
|
||||
var walked = n > 0 ? 1 : 0;
|
||||
for (var i = 1; i < n; i++)
|
||||
{
|
||||
|
|
@ -1509,12 +1767,15 @@ public struct PendingShot
|
|||
|
||||
// Cut 12.4(a): the blast payload, frozen at Fire alongside everything else above. BlastRadius is zero for
|
||||
// a weapon whose data does not carry one -- Step reads that zero as "resolve with Apply," not a separate
|
||||
// bool. Fuse is frozen only when BlastRadius > 0 (Fire decides "detonates" once); it is unread until
|
||||
// bool. Fuse is frozen only when BlastRadius > 0 (Solve decides "detonates" once); it is unread until
|
||||
// Apply's fuse switch (12.4(b)).
|
||||
public float3 BurstPosition;
|
||||
public WeaponFuse? Fuse;
|
||||
public float BlastRadius;
|
||||
|
||||
// Frozen with the rest of the shooter's decision: where the round left from. A round outlives its shooter, so
|
||||
// nothing at resolution reads the shooter's position.
|
||||
public float3 FireOrigin;
|
||||
public float3 FireTargetPosition;
|
||||
public float3 FireTargetVelocity;
|
||||
public float FireTime;
|
||||
|
|
@ -1525,12 +1786,38 @@ public struct PendingShot
|
|||
public ShotOutcome Outcome;
|
||||
}
|
||||
|
||||
// What a round does when fired (FireControl.Solve): Direct resolves against its target, Burst detonates at a
|
||||
// point, Refused cannot be fired -- its blast radius exceeds the weapon's Range.
|
||||
public enum FireOutcome
|
||||
{
|
||||
Direct,
|
||||
Burst,
|
||||
Refused
|
||||
}
|
||||
|
||||
// Solve's answer. Outcome and BurstReach (planar distance from the shooter to the burst point, read for Burst
|
||||
// only) are what the HUD shows; the rest is what Fire freezes into the PendingShot.
|
||||
public struct FireSolution
|
||||
{
|
||||
public FireOutcome Outcome;
|
||||
public float BurstReach;
|
||||
// How far the round flies: to its burst point, or for a direct round to its target.
|
||||
public float FlightDistance;
|
||||
public float PFire;
|
||||
public float FireRange;
|
||||
// Whether the shooter holds valid targeting data on the target (Designated); the HUD and the agents read it here.
|
||||
public bool Designated;
|
||||
public Entity Engaged;
|
||||
public float2 TravelDirection;
|
||||
public float3 BurstPosition;
|
||||
public WeaponFuse? Fuse;
|
||||
public float BlastRadius;
|
||||
}
|
||||
|
||||
public struct FireControlDiagnostic
|
||||
{
|
||||
public bool HasTarget;
|
||||
public bool Visible;
|
||||
public bool InRange;
|
||||
public bool Locked;
|
||||
public bool Designated;
|
||||
public bool InArc;
|
||||
public float Range;
|
||||
public float MinRange;
|
||||
|
|
@ -1548,6 +1835,10 @@ public struct FireControlDiagnostic
|
|||
public float PSpread;
|
||||
public float POnHull;
|
||||
public float PBase;
|
||||
// What a round from this weapon does (Solve): the forecast for a fused weapon, whose percentages above do
|
||||
// not describe it. BurstReach is read only when Outcome is Burst.
|
||||
public FireOutcome Outcome;
|
||||
public float BurstReach;
|
||||
}
|
||||
|
||||
// Cut 12.2 (docs/fire-control-cut.md): a merged interval of a hull's lateral shadow, in the schematic frame's
|
||||
|
|
@ -1614,7 +1905,15 @@ public sealed class ShotOutcome
|
|||
public Entity Source;
|
||||
public Entity Target;
|
||||
public EquippedItem Weapon;
|
||||
public bool Hit;
|
||||
// What the commit decided, typed: a shot rolled and missed, rolled and hit, or was a fused round with no
|
||||
// target and so burst without rolling, or a proximity round whose roll missed but which detonates anyway
|
||||
// (Burst, at BurstPoint). Hit is derived from it, not stored beside it.
|
||||
public ShotResult Result;
|
||||
public bool Hit => Result == ShotResult.Hit;
|
||||
// World planar point a proximity or no-target round detonates at, frozen by the commit; HasBurstPoint says
|
||||
// whether this round has one (a contact or delayed round detonates where it hits, not at a frozen point).
|
||||
public float2 BurstPoint;
|
||||
public bool HasBurstPoint;
|
||||
public bool Shielded;
|
||||
// Cut 5, 5.2 (Soul finding 4): frozen alongside the rest of the outcome (R4) -- a shield present, active,
|
||||
// and unable to CanTakeHit this shot is decided broken right here, so Apply performs Break() rather than
|
||||
|
|
@ -1629,3 +1928,13 @@ public sealed class ShotOutcome
|
|||
public float ArrivalIn;
|
||||
public DamageType DamageType;
|
||||
}
|
||||
|
||||
// What a committed shot came to. A Burst is a detonation that is not a hit on a target: a fused round that had no
|
||||
// valid target and rolled nothing, or a proximity round whose roll missed but which bursts anyway. It is neither
|
||||
// a hit nor a miss, and the presentation must not call it one.
|
||||
public enum ShotResult
|
||||
{
|
||||
Miss,
|
||||
Hit,
|
||||
Burst
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,21 @@ public class Zone
|
|||
private int _nextShotId;
|
||||
public int NextShotId() => ++_nextShotId;
|
||||
|
||||
// The committed shot a presentation was handed the id of by OnFire. It carries what the simulation decided
|
||||
// -- the target it flies at (null for a round that carries none) and where it bursts -- so a presentation
|
||||
// reads that rather than the shooter's current selection.
|
||||
public bool TryGetShot(int shotId, out PendingShot shot)
|
||||
{
|
||||
foreach (var pending in PendingShots)
|
||||
if (pending.ShotId == shotId)
|
||||
{
|
||||
shot = pending;
|
||||
return true;
|
||||
}
|
||||
shot = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<Task> BeltUpdates = new List<Task>();
|
||||
|
||||
public float Time
|
||||
|
|
|
|||
|
|
@ -331,7 +331,7 @@ public sealed class FireAuthorityTests : IDisposable
|
|||
e.Zone.Update(10f); // well past arrival
|
||||
|
||||
Assert.Equal(before, e.Target.Hull.Durability);
|
||||
Assert.Empty(e.Zone.PendingShots);
|
||||
SafeAssert.NoShots(e.Zone);
|
||||
}
|
||||
|
||||
// R4: ShotCommitted fires exactly CommitHorizon before ShotResolved, once per shot. Mutation: publish only
|
||||
|
|
@ -420,7 +420,7 @@ public sealed class FireAuthorityTests : IDisposable
|
|||
e.Zone.Update(.016f); // one ordinary tick
|
||||
|
||||
Assert.Equal(new[] { "committed", "resolved" }, order);
|
||||
Assert.Empty(e.Zone.PendingShots);
|
||||
SafeAssert.NoShots(e.Zone);
|
||||
}
|
||||
|
||||
// R10/Q6: a shot's parameters freeze when the trigger is pulled. Changing the weapon's authored Damage
|
||||
|
|
|
|||
|
|
@ -305,19 +305,19 @@ public sealed class FireControlCut11Tests : IDisposable
|
|||
|
||||
var shotId = FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
e.Zone.Update(1f);
|
||||
Assert.Empty(committed);
|
||||
SafeAssert.Empty(committed);
|
||||
|
||||
e.Zone.Entities.Remove(e.Target);
|
||||
e.Zone.Update(1f);
|
||||
|
||||
foreach (var outcome in new[] { Assert.Single(committed), Assert.Single(resolved) })
|
||||
foreach (var outcome in new[] { SafeAssert.Only(committed), SafeAssert.Only(resolved) })
|
||||
{
|
||||
Assert.Equal(shotId, outcome.ShotId);
|
||||
Assert.False(outcome.Hit);
|
||||
Assert.False(outcome.Shielded, "a shot at nothing did not hit a shield");
|
||||
Assert.False(outcome.ShieldBroken, "a shot at nothing did not break a shield");
|
||||
}
|
||||
Assert.Empty(e.Zone.PendingShots);
|
||||
SafeAssert.NoShots(e.Zone);
|
||||
}
|
||||
|
||||
// ---- A targeting system's Tracking is what forgives a target that moves off its predicted line. ----
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -621,12 +621,12 @@ public sealed class FireControlCut5Tests : IDisposable
|
|||
var e = Build(TestSettings(), damage: 10000, velocity: 0, accuracy: 1, resolution: 1, spread: 0,
|
||||
hullDurability: 5, armor: 0); // one hit is lethal
|
||||
|
||||
Assert.Contains(e.Target, e.Zone.Entities);
|
||||
SafeAssert.In(e.Zone, e.Target);
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
e.Zone.Update(.1f);
|
||||
|
||||
Assert.True(e.Target.Hull.Durability < .01f);
|
||||
Assert.DoesNotContain(e.Target, e.Zone.Entities);
|
||||
SafeAssert.NotIn(e.Zone, e.Target);
|
||||
}
|
||||
|
||||
// ---- 5.7: delete the two carried-and-unread fields (Soul finding 12). ----
|
||||
|
|
|
|||
|
|
@ -293,10 +293,10 @@ public sealed class FireControlCut8Tests : IDisposable
|
|||
e.Zone.Update(.1f);
|
||||
|
||||
Assert.True(e.Target.Hull.Durability < .01f);
|
||||
Assert.DoesNotContain(e.Target, e.Zone.Entities);
|
||||
SafeAssert.NotIn(e.Zone, e.Target);
|
||||
Assert.False(e.Target.Active);
|
||||
Assert.Empty(e.Target.EntityInfoGathered);
|
||||
Assert.Empty(e.Target.VisibleEntities);
|
||||
Assert.True(e.Target.VisibleEntities.Count == 0, "the target's visible set must be empty");
|
||||
}
|
||||
|
||||
// ---- Ordering risk (8.1's own callout): EntityInstance's loot-drop subscription (EntityInstance.cs:292-325)
|
||||
|
|
|
|||
|
|
@ -428,7 +428,7 @@ public sealed class FireControlCut9Tests : IDisposable
|
|||
e.Shooter.EntityInfoGathered[e.Target] = info;
|
||||
var hud = FireControl.Inspect(e.Weapon, e.Shooter, e.Target);
|
||||
var hot = FireControl.HitProbability(e.Weapon, e.Shooter, e.Target);
|
||||
Assert.True(hud.Visible && hud.InRange && hud.Locked && hud.InArc, $"info {info}: precondition, every gate open");
|
||||
Assert.True(hud.Designated && hud.InArc, $"info {info}: precondition, every gate open");
|
||||
Assert.True(hot > 0f, $"info {info}, Precision {precision}: precondition, a shot that can land");
|
||||
Assert.Equal(hot, hud.Accuracy * hud.PSensor * hud.PSpread * hud.POnHull, 5);
|
||||
sawPartialSpread |= hud.PSpread < .99f;
|
||||
|
|
@ -445,7 +445,7 @@ public sealed class FireControlCut9Tests : IDisposable
|
|||
}
|
||||
|
||||
e.Target.Position = origin + float3(0, 0, 5000);
|
||||
Closed("out of range", d => d.InRange);
|
||||
Closed("out of range", d => d.Designated);
|
||||
e.Target.Position = origin + float3(0, 0, -100);
|
||||
Closed("behind the mount", d => d.InArc);
|
||||
|
||||
|
|
@ -455,13 +455,13 @@ public sealed class FireControlCut9Tests : IDisposable
|
|||
e.Target.Position = float3(600, 0, 500);
|
||||
var far = FireControl.Inspect(e.Weapon, e.Shooter, e.Target);
|
||||
Assert.Equal(500f, far.Range, 3);
|
||||
Assert.True(far.InRange && FireControl.HitProbability(e.Weapon, e.Shooter, e.Target) > 0f, "shooter far from the origin");
|
||||
Assert.True(far.Designated && FireControl.HitProbability(e.Weapon, e.Shooter, e.Target) > 0f, "shooter far from the origin");
|
||||
checkedConfigurations++;
|
||||
e.Shooter.Position = origin;
|
||||
e.Target.Position = origin + float3(0, 0, 100);
|
||||
|
||||
e.Shooter.VisibleEntities.Remove(e.Target);
|
||||
Closed("not visible", d => d.Visible);
|
||||
Closed("not visible", d => d.Designated);
|
||||
|
||||
Assert.False(FireControl.Inspect(e.Weapon, e.Shooter, null).HasTarget);
|
||||
Assert.Equal(0f, FireControl.HitProbability(e.Weapon, e.Shooter, null));
|
||||
|
|
|
|||
789
tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs
Normal file
789
tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs
Normal file
|
|
@ -0,0 +1,789 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using UniRx;
|
||||
using Xunit;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
using float3 = CultMath.float3;
|
||||
using int2 = CultMath.int2;
|
||||
|
||||
// Operator rulings 2026-09-30 (fuse batch 5): AI and turrets decide per weapon and a fused weapon needs a
|
||||
// designated target; the HUD forecast shows a fused weapon's outcome and reads the same decision Fire flies; a
|
||||
// refused round is free, for a discrete weapon and for a beam. Builds its own fixture, the convention every
|
||||
// fire-control test file follows: its shooter carries several mounts and can hold either kind of weapon.
|
||||
public sealed class FireControlPerWeaponTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-firecontrolperweapon-" + Guid.NewGuid().ToString("N"));
|
||||
private string Catalog => Path.Combine(_root, "Aetheria.cc");
|
||||
|
||||
public FireControlPerWeaponTests() => Directory.CreateDirectory(_root);
|
||||
|
||||
private readonly List<CultCache> _openCaches = new List<CultCache>();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var c in _openCaches) c.Dispose();
|
||||
Directory.Delete(_root, true);
|
||||
}
|
||||
|
||||
private static GameplaySettings TestSettings(float minHit) => new GameplaySettings
|
||||
{
|
||||
DefaultEntitySettings = new EntitySettings(),
|
||||
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
|
||||
QualityPriceModifier = new ExponentialLerp(),
|
||||
TargetDetectionInfoThreshold = .1f,
|
||||
TargetArmorInfoThreshold = .2f,
|
||||
TargetGearInfoThreshold = .8f,
|
||||
FiringArc = 170,
|
||||
CommitHorizon = .5f,
|
||||
SchematicCellSize = 2f,
|
||||
UnaidedAccuracy = .05f,
|
||||
UnaidedTracking = 10f,
|
||||
UnaidedPrecision = 1000f,
|
||||
AgentMinHitProbability = minHit,
|
||||
BeamResolveInterval = .1f
|
||||
};
|
||||
|
||||
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
|
||||
|
||||
private static Shape SolidShape(int w, int h)
|
||||
{
|
||||
var shape = new Shape(w, h);
|
||||
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
|
||||
return shape;
|
||||
}
|
||||
|
||||
private sealed class Gun
|
||||
{
|
||||
public EquippedItem Item;
|
||||
public Weapon Weapon;
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public Zone Zone;
|
||||
public Ship Shooter;
|
||||
public Ship Target;
|
||||
public List<Gun> Guns = new List<Gun>();
|
||||
public Gun Gun => Guns[0];
|
||||
public Gun Decoy;
|
||||
}
|
||||
|
||||
// Mount 0 (None, arc 0) bears on a target dead ahead; (Clockwise, arc 0) is a side mount the default 170
|
||||
// degree arc cannot bring to bear on it. Fused: Proximity with `blast`, which is also its arming distance: blast 30
|
||||
// arms at 30, so a Range of 29.5 refuses and 40 fires.
|
||||
private Rig Build(
|
||||
(ItemRotation Rotation, float Arc)[] mounts = null, bool beam = false, WeaponFuse? fuse = null, float blast = 0f,
|
||||
float range = 100f, float targetRange = 60f, float accuracy = 1f, float minHit = .2f, bool lockWeapon = false,
|
||||
bool turret = false, float energy = 0f, float heat = 0f, float visibility = 0f, int magazine = 0, bool singleAmmoBurst = false, bool decoy = false, bool charged = false, bool auto = false)
|
||||
{
|
||||
mounts ??= new[] { (ItemRotation.None, 0f) };
|
||||
var hullData = new HullData
|
||||
{
|
||||
Name = "Hull", HullType = HullType.Ship, Shape = SolidShape(5, 4), Durability = 1000000, Mass = 1000, Armor = 0,
|
||||
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } }
|
||||
};
|
||||
var shooterHullData = new HullData
|
||||
{
|
||||
Name = "ShooterHull", HullType = HullType.Ship, Shape = SolidShape(5, 5), Durability = 1000000, Mass = 1000
|
||||
};
|
||||
for (var i = 0; i < mounts.Length; i++)
|
||||
shooterHullData.Hardpoints.Add(new HardpointData
|
||||
{
|
||||
Type = HardpointType.Sensors, Position = new int2(i, 0), Shape = new Shape(),
|
||||
Rotation = mounts[i].Rotation, FiringArc = mounts[i].Arc
|
||||
});
|
||||
// A second weapon type on its own mount (a group of its own, since groups are per item type), dead ahead
|
||||
// and unfused, weaker than the gun: what a group pick falls back to when the gun's group is refused.
|
||||
if (decoy)
|
||||
shooterHullData.Hardpoints.Add(new HardpointData
|
||||
{
|
||||
Type = HardpointType.Sensors, Position = new int2(mounts.Length, 0), Shape = new Shape(),
|
||||
Rotation = ItemRotation.None, FiringArc = 0f
|
||||
});
|
||||
|
||||
WeaponData behavior;
|
||||
if (beam)
|
||||
behavior = new ConstantWeaponData();
|
||||
else if (lockWeapon)
|
||||
behavior = new LockWeaponData
|
||||
{
|
||||
LockSpeed = Constant(1000), SensorImpact = Constant(1), LockAngle = Constant(0), DirectionImpact = Constant(1), Decay = Constant(1),
|
||||
Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1)
|
||||
};
|
||||
else if (charged)
|
||||
behavior = new ChargedWeaponData
|
||||
{
|
||||
Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1), SingleAmmoBurst = singleAmmoBurst,
|
||||
ChargeTime = Constant(1), ChargeEnergy = Constant(0), ChargeHeat = Constant(5000), CanFireEarly = true
|
||||
};
|
||||
else if (auto)
|
||||
behavior = new AutoWeaponData { Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1), SingleAmmoBurst = singleAmmoBurst };
|
||||
else
|
||||
behavior = new InstantWeaponData { Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1), SingleAmmoBurst = singleAmmoBurst };
|
||||
behavior.Damage = Constant(100);
|
||||
behavior.Range = Constant(range);
|
||||
behavior.MinRange = Constant(0);
|
||||
behavior.Velocity = Constant(0);
|
||||
behavior.Spread = Constant(0);
|
||||
behavior.DamageSpread = Constant(0);
|
||||
behavior.Penetration = Constant(0);
|
||||
behavior.Energy = Constant(energy);
|
||||
behavior.Heat = Constant(heat);
|
||||
behavior.Visibility = Constant(visibility);
|
||||
behavior.MagazineSize = magazine;
|
||||
behavior.DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } };
|
||||
|
||||
var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true);
|
||||
_openCaches.Add(cache);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
cache.Upsert(hullData);
|
||||
cache.Upsert(shooterHullData);
|
||||
cache.Upsert(new WeaponItemData
|
||||
{
|
||||
Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Fuse = fuse, BlastRadius = blast,
|
||||
Behaviors = { behavior }
|
||||
});
|
||||
cache.Upsert(new WeaponItemData
|
||||
{
|
||||
Name = "Decoy", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Behaviors =
|
||||
{
|
||||
new InstantWeaponData
|
||||
{
|
||||
Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1), Damage = Constant(50), Range = Constant(100),
|
||||
MinRange = Constant(0), Velocity = Constant(0), Spread = Constant(0), DamageSpread = Constant(0), Penetration = Constant(0),
|
||||
Energy = Constant(0), Heat = Constant(0), Visibility = Constant(0),
|
||||
DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } }
|
||||
}
|
||||
}
|
||||
});
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Behaviors = { new TargetingSystemData { Accuracy = Constant(accuracy), Resolution = Constant(1000f), Precision = Constant(1000f), Tracking = Constant(1000000f) } }
|
||||
});
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Behaviors = { new ReactorData { Charge = Constant(1000), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2) } }
|
||||
});
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Turret", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Behaviors = { new TurretControllerData() }
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
|
||||
var ledger = new ProvenanceLedger();
|
||||
for (var i = 1; i <= 100; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 };
|
||||
var items = new ItemManager(cache, ledger, TestSettings(minHit), _ => { });
|
||||
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "PerWeapon", Owner = null }, null);
|
||||
|
||||
EquippableItem Make(string name, int lot, float durability) => new EquippableItem
|
||||
{
|
||||
Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<ItemData>(name)), Durability = durability, Lot = lot
|
||||
};
|
||||
|
||||
var lot = 1;
|
||||
var shooterHullRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("ShooterHull"));
|
||||
var hullRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("Hull"));
|
||||
var shooter = new Ship(items, zone, new EquippableItem { Data = shooterHullRef, Durability = 1000000, Lot = lot++ }, new EntitySettings());
|
||||
var rig = new Rig();
|
||||
for (var i = 0; i < mounts.Length; i++)
|
||||
{
|
||||
var gun = Make("Gun", lot++, 1);
|
||||
Assert.True(shooter.TryEquip(gun, new int2(i, 0)));
|
||||
var item = shooter.Equipment.Single(x => x.EquippableItem == gun);
|
||||
rig.Guns.Add(new Gun { Item = item, Weapon = (Weapon) item.Behaviors.Single(b => b is Weapon) });
|
||||
}
|
||||
if (decoy)
|
||||
{
|
||||
var d = Make("Decoy", lot++, 1);
|
||||
Assert.True(shooter.TryEquip(d, new int2(mounts.Length, 0)));
|
||||
var item = shooter.Equipment.Single(x => x.EquippableItem == d);
|
||||
rig.Decoy = new Gun { Item = item, Weapon = (Weapon) item.Behaviors.Single(b => b is Weapon) };
|
||||
}
|
||||
var targeting = Make("Targeting", lot++, 1);
|
||||
Assert.True(shooter.TryFindSpace(targeting, out var tpos));
|
||||
Assert.True(shooter.TryEquip(targeting, tpos));
|
||||
if (true)
|
||||
{
|
||||
var reactor = Make("Reactor", lot++, 10);
|
||||
Assert.True(shooter.TryFindSpace(reactor, out var rpos));
|
||||
Assert.True(shooter.TryEquip(reactor, rpos));
|
||||
}
|
||||
if (turret)
|
||||
{
|
||||
var t = Make("Turret", lot++, 1);
|
||||
Assert.True(shooter.TryFindSpace(t, out var upos));
|
||||
Assert.True(shooter.TryEquip(t, upos));
|
||||
}
|
||||
|
||||
var target = new Ship(items, zone, new EquippableItem { Data = hullRef, Durability = 1000000, Lot = lot++ }, new EntitySettings());
|
||||
Assert.True(target.TryEquip(Make("Gun", lot++, 1), new int2(0, 0)));
|
||||
|
||||
zone.Entities.Add(shooter);
|
||||
zone.Entities.Add(target);
|
||||
shooter.Activate();
|
||||
target.Activate();
|
||||
|
||||
shooter.Position = float3(-53, 0, -101);
|
||||
target.Position = shooter.Position + float3(0, 0, targetRange);
|
||||
shooter.Target.Value = target;
|
||||
shooter.EntityInfoGathered[target] = 1f;
|
||||
shooter.SetIff(target, true);
|
||||
|
||||
zone.Update(1f);
|
||||
|
||||
rig.Zone = zone;
|
||||
rig.Shooter = shooter;
|
||||
rig.Target = target;
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static void Aim(Rig r, float2 direction) => r.Shooter.LookDirection = float3(direction.x, 0, direction.y);
|
||||
|
||||
private static readonly (ItemRotation, float)[] SideThenForward = { (ItemRotation.Clockwise, 0f), (ItemRotation.None, 0f) };
|
||||
private static readonly (ItemRotation, float)[] SideMount = { (ItemRotation.Clockwise, 0f) };
|
||||
|
||||
// ==== Ruling 1: per weapon, and a fused weapon needs a designated target ====
|
||||
|
||||
// A weapon group shares a trigger, not a verdict: two guns of one type, the first on a side mount that cannot
|
||||
// bear on the target and the second dead ahead. Only the second fires. Kills: the group's verdict read off its
|
||||
// first weapon (Combat's old `testWeapon`), which silences the group.
|
||||
[Fact]
|
||||
public void CombatDecidesEachWeaponOfAGroupForItself()
|
||||
{
|
||||
var r = Build(SideThenForward);
|
||||
var group = r.Shooter.WeaponGroups.Single(g => g.weapons.Count == 2).weapons;
|
||||
Assert.True(ReferenceEquals(group[0], r.Guns[0].Weapon), "fixture: the side mount leads the group");
|
||||
r.Zone.Agents.Add(new Minion(r.Shooter));
|
||||
|
||||
r.Zone.Update(1f);
|
||||
r.Zone.Update(1f);
|
||||
|
||||
Assert.False(r.Guns[0].Weapon.Firing, "the side-mounted gun cannot bear");
|
||||
Assert.True(r.Guns[1].Weapon.Firing, "the forward gun bears and is worth firing");
|
||||
}
|
||||
|
||||
// A fused weapon fires whenever its target is designated, whatever the arc: the same group, now fused, fires
|
||||
// both guns, the side mount included. Kills: Combat reading HitProbability (zero out of arc) for a fused weapon.
|
||||
[Fact]
|
||||
public void CombatFiresAFusedWeaponAtADesignatedTargetOutOfArc()
|
||||
{
|
||||
var r = Build(SideThenForward, fuse: WeaponFuse.Proximity, blast: 4f);
|
||||
r.Zone.Agents.Add(new Minion(r.Shooter));
|
||||
|
||||
r.Zone.Update(1f);
|
||||
r.Zone.Update(1f);
|
||||
|
||||
Assert.True(r.Guns[0].Weapon.Firing, "a designated target is enough, arc or no");
|
||||
Assert.True(r.Guns[1].Weapon.Firing);
|
||||
}
|
||||
|
||||
// The turret makes the same per-weapon decision. Kills: TurretController reading HitProbability, or its own
|
||||
// range test, for a fused weapon.
|
||||
[Fact]
|
||||
public void ATurretFiresAFusedWeaponAtADesignatedTargetOutOfArc()
|
||||
{
|
||||
var r = Build(SideMount, fuse: WeaponFuse.Proximity, blast: 4f, turret: true);
|
||||
|
||||
r.Zone.Update(1f);
|
||||
r.Zone.Update(1f);
|
||||
|
||||
Assert.True(r.Gun.Weapon.Firing, "the turret must fire a fused weapon at a designated target out of arc");
|
||||
}
|
||||
|
||||
public enum Withheld { NoTarget, OutOfRange, NotVisible, Unlocked }
|
||||
|
||||
// The AI never fires a fused weapon at nothing: a missing target, one out of range, one not visible and one
|
||||
// an unlocked LockWeapon holds no lock on are each no reason to fish. The direct-hit control fires (true) on
|
||||
// the same rig once the target is valid. Kills: `designated` dropped from the fused branch (null included).
|
||||
[Theory]
|
||||
[InlineData(Withheld.NoTarget)]
|
||||
[InlineData(Withheld.OutOfRange)]
|
||||
[InlineData(Withheld.NotVisible)]
|
||||
[InlineData(Withheld.Unlocked)]
|
||||
public void AnAgentNeverFiresAFusedWeaponAtNothing(Withheld reason)
|
||||
{
|
||||
var r = Build(fuse: WeaponFuse.Proximity, blast: 4f, range: 100f,
|
||||
targetRange: reason == Withheld.OutOfRange ? 150f : 60f, lockWeapon: reason == Withheld.Unlocked);
|
||||
var target = r.Target;
|
||||
if (reason == Withheld.NoTarget) target = null;
|
||||
if (reason == Withheld.NotVisible) r.Shooter.VisibleEntities.Remove(r.Target);
|
||||
|
||||
Assert.False(FireControl.AgentFires(r.Gun.Weapon, r.Shooter, target));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAgentFiresAFusedWeaponAtAValidTargetWhateverItsHitChance()
|
||||
{
|
||||
// Accuracy 0 prices every direct hit at zero; the fused weapon is unmoved.
|
||||
var r = Build(SideMount, fuse: WeaponFuse.Proximity, blast: 4f, accuracy: 0f);
|
||||
|
||||
Assert.True(FireControl.AgentFires(r.Gun.Weapon, r.Shooter, r.Target));
|
||||
}
|
||||
|
||||
// A weapon that fires at what it hits keeps the AgentMinHitProbability threshold, per weapon.
|
||||
// Kills: the threshold dropped for a direct-hit weapon, or applied to a fused one.
|
||||
[Theory]
|
||||
[InlineData(.5f, .2f, true)]
|
||||
[InlineData(.5f, .9f, false)]
|
||||
public void AnAgentKeepsTheHitProbabilityThresholdForADirectHitWeapon(float accuracy, float minHit, bool fires)
|
||||
{
|
||||
var r = Build(accuracy: accuracy, minHit: minHit);
|
||||
var p = FireControl.HitProbability(r.Gun.Weapon, r.Shooter, r.Target);
|
||||
Assert.True(p > .3f && p < .7f, $"fixture: the shot must price near the accuracy, priced {p}");
|
||||
|
||||
Assert.Equal(fires, FireControl.AgentFires(r.Gun.Weapon, r.Shooter, r.Target));
|
||||
}
|
||||
|
||||
// ==== Ruling 2: the HUD forecast is Fire's own decision ====
|
||||
|
||||
// Inspect's Outcome and BurstReach against what Fire then does with the same rig: Refused iff Fire returns 0,
|
||||
// and a Burst's reach is the planar distance to the burst point Fire froze. Rows: a target beyond the arming
|
||||
// distance (burst at its range), one inside it (pushed out to 30), no target (max range), out of arc, a
|
||||
// Range that cannot reach the arming distance, and a weapon without a fuse.
|
||||
// Kills: an Inspect that computes its own reach (ignoring the arming push or the Range clamp).
|
||||
[Theory]
|
||||
[InlineData(60f, 100f, false, false, FireOutcome.Burst, 60f)]
|
||||
[InlineData(20f, 100f, false, false, FireOutcome.Burst, 30f)]
|
||||
[InlineData(60f, 40f, true, false, FireOutcome.Burst, 40f)]
|
||||
[InlineData(60f, 100f, false, true, FireOutcome.Burst, 60f)]
|
||||
[InlineData(60f, 29.5f, false, false, FireOutcome.Refused, 0f)]
|
||||
[InlineData(60f, 29.5f, true, false, FireOutcome.Refused, 0f)]
|
||||
public void TheForecastIsTheOutcomeFireDelivers(float targetRange, float range, bool noTarget, bool outOfArc, FireOutcome outcome, float reach)
|
||||
{
|
||||
var r = Build(outOfArc ? SideMount : null, fuse: WeaponFuse.Proximity, blast: 30f, range: range, targetRange: targetRange);
|
||||
if (noTarget) r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
|
||||
var d = FireControl.Inspect(r.Gun.Weapon, r.Shooter, r.Shooter.Target.Value);
|
||||
var shotId = FireControl.Fire(r.Gun.Weapon, r.Gun.Item, r.Shooter);
|
||||
|
||||
Assert.Equal(outcome, d.Outcome);
|
||||
Assert.Equal(outcome != FireOutcome.Refused, shotId != 0);
|
||||
if (outcome == FireOutcome.Refused) return;
|
||||
Assert.Equal(reach, d.BurstReach, 2);
|
||||
var shot = SafeAssert.OnlyShot(r.Zone);
|
||||
Assert.Equal(d.BurstReach, length((shot.BurstPosition - shot.FireOrigin).xz), 2);
|
||||
}
|
||||
|
||||
// A weapon without a fuse forecasts a direct hit and keeps its percentages. Kills: Solve calling everything a burst.
|
||||
[Fact]
|
||||
public void AWeaponWithoutAFuseForecastsADirectHit()
|
||||
{
|
||||
var r = Build();
|
||||
|
||||
var d = FireControl.Inspect(r.Gun.Weapon, r.Shooter, r.Target);
|
||||
|
||||
Assert.Equal(FireOutcome.Direct, d.Outcome);
|
||||
Assert.True(d.PBase > 0f);
|
||||
}
|
||||
|
||||
// ==== Ruling 3: a refused round is free ====
|
||||
|
||||
private sealed class Costs
|
||||
{
|
||||
public int Ammo;
|
||||
public float ChargeSpent;
|
||||
public int Sounds;
|
||||
public int Wears;
|
||||
public float Heat;
|
||||
public bool Visible;
|
||||
public int Announced;
|
||||
public int Shots;
|
||||
public bool CanFire;
|
||||
}
|
||||
|
||||
// One discrete weapon, triggered once at no target, with every cost observable: a magazine, an energy charge,
|
||||
// a sound bank, wear events, heat and visibility. Range 29.5 refuses (arming 30); Range 40 fires.
|
||||
private Costs Pull(float range, bool single, bool viaTrigger, bool staleRange = false, bool auto = false)
|
||||
{
|
||||
var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: range, energy: 50f, heat: 5000f, visibility: 100f, magazine: 5, singleAmmoBurst: single, auto: auto);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (InstantWeapon) r.Gun.Weapon;
|
||||
var capacitor = (InputCapacitor) typeof(InstantWeapon).GetField("_capacitor", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(weapon);
|
||||
r.Gun.Item.SoundBank = new WwiseMetaSoundBank { IncludedEvents = new[] { new WwiseMetaObject { Id = 7, Name = "gun_fire" } } };
|
||||
var costs = new Costs();
|
||||
r.Gun.Item.AudioEvents.Subscribe(_ => costs.Sounds++);
|
||||
r.Zone.ShotCommitted.Subscribe(_ => costs.Shots++); // a fused round with no flight commits and resolves in its own tick
|
||||
r.Shooter.ItemDamage.Subscribe(t => { if (t.Item1 == r.Gun.Item) costs.Wears++; });
|
||||
weapon.OnFire += _ => costs.Announced++;
|
||||
capacitor.AddCharge(1000f); // a full buffer, so the first round can be paid for
|
||||
var chargeBefore = capacitor.Charge;
|
||||
var heatBefore = r.Gun.Item.Temperature;
|
||||
var ammoBefore = weapon.Ammo;
|
||||
Assert.True(chargeBefore > 0f && ammoBefore == 5, "fixture: a full buffer and magazine");
|
||||
|
||||
// The Range the previous tick's Execute left, before this tick refreshes it: a power-dependent Range that
|
||||
// has since fallen. Set through the property's own setter, so the trigger sees a Range the round will not.
|
||||
if (staleRange) typeof(Weapon).GetProperty("Range").GetSetMethod(true).Invoke(weapon, new object[] { 100f });
|
||||
if (auto)
|
||||
{
|
||||
// AutoWeapon's own trigger: a held weapon whose cooldown has run out retriggers inside Execute.
|
||||
typeof(Weapon).GetField("_firing", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(weapon, true);
|
||||
typeof(InstantWeapon).GetField("_cooldown", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(weapon, -1f);
|
||||
}
|
||||
else if (viaTrigger) weapon.Activate();
|
||||
else typeof(InstantWeapon).GetField("_burstRemaining", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(weapon, 1);
|
||||
r.Zone.Update(.01f);
|
||||
|
||||
costs.Ammo = ammoBefore - weapon.Ammo;
|
||||
costs.ChargeSpent = chargeBefore - capacitor.Charge;
|
||||
costs.Heat = r.Gun.Item.Temperature - heatBefore;
|
||||
costs.Visible = r.Shooter.VisibilitySources.TryGetValue(weapon, out var v) && v > 1f;
|
||||
costs.CanFire = weapon.CanFire;
|
||||
return costs;
|
||||
}
|
||||
|
||||
// Control: the same weapon with Range to spare pays every cost, so a free refusal below is not a fixture that
|
||||
// never spends. Then the refusal costs nothing: no ammo, no energy, no sound, no wear, no heat, no
|
||||
// visibility, no shot. `single` is a weapon that pays once per burst, at its first unrefused round rather than at each;
|
||||
// `viaTrigger` false authorises the burst directly (the way a trigger that passed leaves it) on a weapon whose
|
||||
// Range is short, so the Trigger check cannot be what stops the round and Execute must refuse it itself.
|
||||
// Kills, one per row of the assertions: a spend that precedes the refusal (Execute or Trigger), an
|
||||
// announcement, a sound, wear, heat or visibility left ahead of the `continue`.
|
||||
[Theory]
|
||||
[InlineData(false, true)]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(false, false)]
|
||||
public void ARefusedDiscreteRoundCostsNothing(bool single, bool viaTrigger)
|
||||
{
|
||||
var fired = Pull(40f, single, viaTrigger);
|
||||
Assert.True(fired.Shots == 1, $"shots {fired.Shots}");
|
||||
Assert.True(fired.Ammo == 1, $"ammo spent {fired.Ammo}");
|
||||
Assert.True(fired.ChargeSpent > 1f, "a fired round spends its energy");
|
||||
Assert.Equal(1, fired.Sounds);
|
||||
Assert.True(fired.Wears > 0);
|
||||
Assert.True(fired.Heat > 0f);
|
||||
Assert.True(fired.Visible);
|
||||
Assert.Equal(1, fired.Announced);
|
||||
|
||||
var refused = Pull(29.5f, single, viaTrigger);
|
||||
Assert.Equal(0, refused.Shots);
|
||||
Assert.Equal(0, refused.Ammo);
|
||||
Assert.Equal(0f, refused.ChargeSpent);
|
||||
Assert.Equal(0, refused.Sounds);
|
||||
Assert.Equal(0, refused.Wears);
|
||||
Assert.True(fired.Heat - refused.Heat > 5f, $"a refused round adds no heat ({refused.Heat} vs {fired.Heat})");
|
||||
Assert.False(refused.Visible);
|
||||
Assert.Equal(0, refused.Announced);
|
||||
}
|
||||
|
||||
// The same rule for a beam: a fused beam whose arming distance exceeds Range fires nothing and draws
|
||||
// nothing. The control (Range 40) rolls shots, wears, draws power and shows; the refused beam does none of
|
||||
// that, asks the bus for nothing, and never starts (ARefusedBeamNeverStarts).
|
||||
// Kills: ConstantWeapon spending (power request, wear, heat, visibility) before the refusal, or not
|
||||
// consulting FireControl at all.
|
||||
private (int Shots, int Wears, float Request, bool Visible, float Heat, int Stops, bool Firing) Burn(float range)
|
||||
{
|
||||
var r = Build(beam: true, fuse: WeaponFuse.Proximity, blast: 30f, range: range, energy: 50f, heat: 5000f, visibility: 100f);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (ConstantWeapon) r.Gun.Weapon;
|
||||
var wears = 0;
|
||||
var stops = 0;
|
||||
var shots = 0;
|
||||
r.Zone.ShotResolved.Subscribe(_ => shots++);
|
||||
r.Shooter.ItemDamage.Subscribe(t => { if (t.Item1 == r.Gun.Item) wears++; });
|
||||
weapon.OnStopFiring += () => stops++;
|
||||
var heatBefore = r.Gun.Item.Temperature;
|
||||
|
||||
weapon.Activate();
|
||||
var request = weapon.PowerRequest(.1f);
|
||||
for (var i = 0; i < 5; i++) r.Zone.Update(.1f);
|
||||
|
||||
var visible = r.Shooter.VisibilitySources.TryGetValue(weapon, out var v) && v > 1f;
|
||||
return (shots, wears, request, visible, r.Gun.Item.Temperature - heatBefore, stops, weapon.Firing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARefusedBeamCostsNothing()
|
||||
{
|
||||
var fired = Burn(40f);
|
||||
Assert.True(fired.Shots > 0, "control: the beam rolls shots");
|
||||
Assert.True(fired.Wears > 0);
|
||||
Assert.True(fired.Request > 0f);
|
||||
Assert.True(fired.Visible);
|
||||
Assert.True(fired.Heat > 0f);
|
||||
|
||||
var refused = Burn(29.5f);
|
||||
Assert.Equal(0, refused.Shots);
|
||||
Assert.Equal(0, refused.Wears);
|
||||
Assert.Equal(0f, refused.Request);
|
||||
Assert.False(refused.Visible);
|
||||
Assert.True(fired.Heat - refused.Heat > 5f, $"a refused beam adds no heat ({refused.Heat} vs {fired.Heat})");
|
||||
Assert.True(refused.Stops == 0 && !refused.Firing, "a refused beam never starts, so it never has to stop");
|
||||
}
|
||||
|
||||
// A beam is a stream of rounds, so a refused beam never starts: OnStartFiring drives the beam's visuals and
|
||||
// audio, and starting it for Execute to stop a tick later would flash a beam that fires nothing. The control
|
||||
// (Range 40) starts once and keeps firing. Kills: Activate that starts a beam without asking FireControl.
|
||||
[Theory]
|
||||
[InlineData(40f, 1)]
|
||||
[InlineData(29.5f, 0)]
|
||||
public void ARefusedBeamNeverStarts(float range, int starts)
|
||||
{
|
||||
var r = Build(beam: true, fuse: WeaponFuse.Proximity, blast: 30f, range: range);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (ConstantWeapon) r.Gun.Weapon;
|
||||
var started = 0;
|
||||
weapon.OnStartFiring += () => started++;
|
||||
|
||||
weapon.Activate();
|
||||
for (var i = 0; i < 5; i++) r.Zone.Update(.1f);
|
||||
|
||||
Assert.Equal(starts, started);
|
||||
Assert.Equal(starts == 1, weapon.Firing);
|
||||
}
|
||||
|
||||
// A refused weapon is not one an agent can use: a fused weapon whose arming distance (30) exceeds its Range
|
||||
// (29.5) is not fired at a target inside that Range, where the same weapon with Range to spare is.
|
||||
// Kills: AgentFires answering "designated" without asking whether Solve refuses.
|
||||
[Theory]
|
||||
[InlineData(29.5f, false)]
|
||||
[InlineData(40f, true)]
|
||||
public void AnAgentNeverFiresARefusedFusedWeapon(float range, bool fires)
|
||||
{
|
||||
var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: range, targetRange: 20f);
|
||||
|
||||
Assert.Equal(fires, FireControl.AgentFires(r.Gun.Weapon, r.Shooter, r.Target));
|
||||
}
|
||||
|
||||
// Combat's group pick counts only weapons that can fire: the refused gun's group out-damages the decoy's, so a
|
||||
// pick that counted it would select a group whose weapons are then never fired, and the decoy would stay silent.
|
||||
// Kills: Combat counting a refused weapon's damage toward its group.
|
||||
[Fact]
|
||||
public void CombatDoesNotPickAGroupWhoseWeaponIsRefused()
|
||||
{
|
||||
var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 29.5f, targetRange: 20f, decoy: true);
|
||||
Assert.True(r.Gun.Weapon.RangeDamagePerSecond(20f) > r.Decoy.Weapon.RangeDamagePerSecond(20f), "fixture: the refused gun is the stronger group");
|
||||
r.Zone.Agents.Add(new Minion(r.Shooter));
|
||||
|
||||
r.Zone.Update(1f);
|
||||
r.Zone.Update(1f);
|
||||
|
||||
Assert.False(r.Gun.Weapon.Firing, "a refused weapon is never activated");
|
||||
Assert.True(r.Decoy.Weapon.Firing, "the group that can fire is the one picked");
|
||||
}
|
||||
|
||||
// Combat's group pick counts only weapons whose target is designated: the stronger gun's Range (10) does not reach the
|
||||
// target (20), so its group is not picked and the decoy's, which does reach, is. Kills: Combat asking
|
||||
// Designated nothing (a group of weapons that cannot reach the target selected).
|
||||
[Fact]
|
||||
public void CombatDoesNotPickAGroupWhoseWeaponCannotReachTheTarget()
|
||||
{
|
||||
var r = Build(range: 10f, targetRange: 20f, decoy: true);
|
||||
Assert.True(r.Gun.Weapon.RangeDamagePerSecond(20f) > r.Decoy.Weapon.RangeDamagePerSecond(20f), "fixture: the short gun is the stronger group");
|
||||
r.Zone.Agents.Add(new Minion(r.Shooter));
|
||||
|
||||
r.Zone.Update(1f);
|
||||
r.Zone.Update(1f);
|
||||
|
||||
Assert.False(r.Gun.Weapon.Firing, "a weapon that cannot reach the target is never activated");
|
||||
Assert.True(r.Decoy.Weapon.Firing, "the group that reaches is the one picked");
|
||||
}
|
||||
|
||||
// Combat's range test is Designated's, not a second one: a target exactly at max range is in reach (the old
|
||||
// private test was strict). Kills: a range comparison of Combat's own.
|
||||
[Fact]
|
||||
public void CombatCountsATargetExactlyAtMaxRangeAsInReach()
|
||||
{
|
||||
var r = Build(range: 60f, targetRange: 60f);
|
||||
// The agent is driven directly, not through the zone, so the shooter stays exactly at max range: the first
|
||||
// update leaves the root state for combat, the second is combat deciding.
|
||||
var agent = new Minion(r.Shooter);
|
||||
agent.Update(.01f);
|
||||
agent.Update(.01f);
|
||||
|
||||
Assert.True(r.Gun.Weapon.Firing);
|
||||
}
|
||||
|
||||
// The trigger's threshold is inclusive: a shot priced exactly at AgentMinHitProbability is worth taking, and
|
||||
// one priced a hair under it is not. Kills: `>` for `>=`.
|
||||
[Fact]
|
||||
public void AnAgentFiresAtExactlyTheHitProbabilityThreshold()
|
||||
{
|
||||
var probe = Build(accuracy: .5f);
|
||||
var price = FireControl.HitProbability(probe.Gun.Weapon, probe.Shooter, probe.Target);
|
||||
Assert.True(price > 0f);
|
||||
|
||||
var atThreshold = Build(accuracy: .5f, minHit: price);
|
||||
var overThreshold = Build(accuracy: .5f, minHit: MathF.BitIncrement(price));
|
||||
|
||||
Assert.True(FireControl.AgentFires(atThreshold.Gun.Weapon, atThreshold.Shooter, atThreshold.Target));
|
||||
Assert.False(FireControl.AgentFires(overThreshold.Gun.Weapon, overThreshold.Shooter, overThreshold.Target));
|
||||
}
|
||||
|
||||
// A round refused on a Range that fell between the trigger and the round is still free: the burst is paid
|
||||
// (SingleAmmoBurst) at its first round that is not refused, judged with the Range that round flies with.
|
||||
// The trigger saw a stale Range of 100; the round's Range is 29.5, under the arming distance. The refusal
|
||||
// starts no cooldown either (operator ruling 2026-09-30): the weapon can fire again at once, while the
|
||||
// control (Range 40) fired and is cooling down. Covers the player's trigger and AutoWeapon's own.
|
||||
// Kills: paying for the burst at the trigger; starting the cooldown at the trigger (Trigger or AutoWeapon).
|
||||
[Theory]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(false, false)]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(false, true)]
|
||||
public void ARefusedBurstThatPassedTheTriggerOnAStaleRangeCostsNothing(bool single, bool auto)
|
||||
{
|
||||
var fired = Pull(40f, single, viaTrigger: true, staleRange: true, auto: auto);
|
||||
Assert.Equal(1, fired.Shots);
|
||||
Assert.False(fired.CanFire, "control: a fired burst starts the cooldown");
|
||||
|
||||
var refused = Pull(29.5f, single, viaTrigger: true, staleRange: true, auto: auto);
|
||||
|
||||
Assert.Equal(0, refused.Shots);
|
||||
Assert.Equal(0, refused.Ammo);
|
||||
Assert.Equal(0f, refused.ChargeSpent);
|
||||
Assert.Equal(0, refused.Announced);
|
||||
Assert.True(refused.CanFire, "a burst that fired nothing leaves no cooldown");
|
||||
}
|
||||
|
||||
// A refused charged weapon never starts charging: no charge heat, no audio, no start event, and it can be
|
||||
// triggered again at once. The control (Range 40) charges, sounds and heats.
|
||||
// Kills: ChargedWeapon.Activate that does not ask FireControl.
|
||||
private (int Starts, int Sounds, float Heat, bool Charging) Charge(float range)
|
||||
{
|
||||
var r = Build(charged: true, fuse: WeaponFuse.Proximity, blast: 30f, range: range);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (ChargedWeapon) r.Gun.Weapon;
|
||||
r.Gun.Item.SoundBank = new WwiseMetaSoundBank { IncludedEvents = new[] { new WwiseMetaObject { Id = 7, Name = "gun_charge_play" } } };
|
||||
var starts = 0;
|
||||
var sounds = 0;
|
||||
weapon.OnStartCharging += () => starts++;
|
||||
r.Gun.Item.AudioEvents.Subscribe(_ => sounds++);
|
||||
var heatBefore = r.Gun.Item.Temperature;
|
||||
|
||||
weapon.Activate();
|
||||
for (var i = 0; i < 3; i++) r.Zone.Update(.1f);
|
||||
|
||||
return (starts, sounds, r.Gun.Item.Temperature - heatBefore, weapon.Progress > 0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARefusedChargedWeaponNeverStartsCharging()
|
||||
{
|
||||
var fired = Charge(40f);
|
||||
Assert.Equal(1, fired.Starts);
|
||||
Assert.True(fired.Sounds > 0, "control: charging sounds");
|
||||
Assert.True(fired.Heat > 0f, "control: charging heats");
|
||||
|
||||
var refused = Charge(29.5f);
|
||||
Assert.Equal(0, refused.Starts);
|
||||
Assert.Equal(0, refused.Sounds);
|
||||
Assert.True(fired.Heat - refused.Heat > 5f, $"a refused weapon adds no charge heat ({refused.Heat} vs {fired.Heat})");
|
||||
}
|
||||
// A triggered burst has not started its cooldown, but it is not ready either: pulled again before its first round
|
||||
// flies it would restart the burst. Kills: CanFire that reads the cooldown alone.
|
||||
[Fact]
|
||||
public void ATriggeredBurstIsNotReadyBeforeItsFirstRound()
|
||||
{
|
||||
var r = Build(range: 100f);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (InstantWeapon) r.Gun.Weapon;
|
||||
r.Zone.Update(.01f); // resolves the gun's stats, which size the burst
|
||||
Assert.True(weapon.CanFire);
|
||||
|
||||
weapon.Activate();
|
||||
|
||||
Assert.False(weapon.CanFire);
|
||||
}
|
||||
|
||||
// A charge released with a burst pending has not started its cooldown, but it is not ready either: pressed
|
||||
// again before that burst's first round it would start a second charge over it. Kills: ChargedWeapon.Activate
|
||||
// that reads the cooldown alone instead of CanFire.
|
||||
[Fact]
|
||||
public void AChargedWeaponPressedAgainBeforeItsReleasedRoundFliesStartsNoSecondCharge()
|
||||
{
|
||||
var r = Build(charged: true, range: 100f);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (ChargedWeapon) r.Gun.Weapon;
|
||||
var starts = 0;
|
||||
weapon.OnStartCharging += () => starts++;
|
||||
r.Zone.Update(.01f); // resolves the stats
|
||||
weapon.Activate();
|
||||
for (var i = 0; i < 15; i++) r.Zone.Update(.1f);
|
||||
Assert.Equal(1, starts);
|
||||
|
||||
weapon.Deactivate();
|
||||
weapon.Activate();
|
||||
r.Zone.Update(.1f);
|
||||
|
||||
Assert.Equal(1, starts);
|
||||
Assert.False((bool) typeof(ChargedWeapon).GetField("_charging", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(weapon));
|
||||
}
|
||||
|
||||
// Holding the trigger fires once per Cooldown: the round that starts the cooldown pays for the tick it flew in.
|
||||
// Cooldown 1 at .25 s ticks is a shot every 5 ticks, 12 in 15 s. And a burst whose every round is refused
|
||||
// leaves no cooldown: the same held trigger is ready every tick. Kills: a first round that starts the cooldown
|
||||
// at 1 after the tick's decrement (a shot every 6 ticks, 10 in 15 s); a cooldown left by a refused burst.
|
||||
[Theory]
|
||||
[InlineData(100f, 12)]
|
||||
[InlineData(29.5f, 0)]
|
||||
public void AHeldTriggerFiresOncePerCooldownAndARefusedBurstLeavesNone(float range, int shots)
|
||||
{
|
||||
var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: range);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (InstantWeapon) r.Gun.Weapon;
|
||||
var fired = 0;
|
||||
weapon.OnFire += _ => fired++;
|
||||
r.Zone.Update(.25f); // resolves the stats
|
||||
var readyTicks = 0;
|
||||
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
weapon.Activate();
|
||||
r.Zone.Update(.25f);
|
||||
if (weapon.CanFire) readyTicks++;
|
||||
}
|
||||
|
||||
Assert.Equal(shots, fired);
|
||||
if (shots == 0) Assert.Equal(60, readyTicks);
|
||||
}
|
||||
|
||||
// Kills: Trigger that leaves _burstStarted true from the previous burst, so the next burst reads as started
|
||||
// (and ready) before its first round has flown.
|
||||
[Fact]
|
||||
public void ABurstTriggeredAfterAFiredOneIsNotReadyBeforeItsFirstRound()
|
||||
{
|
||||
var r = Build(range: 100f);
|
||||
r.Shooter.Target.Value = null;
|
||||
Aim(r, float2(0, 1));
|
||||
var weapon = (InstantWeapon) r.Gun.Weapon;
|
||||
r.Zone.Update(.25f);
|
||||
weapon.Activate();
|
||||
r.Zone.Update(.25f);
|
||||
Assert.False(weapon.CanFire, "control: the first burst fired and is cooling");
|
||||
for (var i = 0; i < 10 && !weapon.CanFire; i++) r.Zone.Update(.25f);
|
||||
Assert.True(weapon.CanFire, "fixture: the cooldown expired");
|
||||
|
||||
weapon.Activate();
|
||||
|
||||
Assert.False(weapon.CanFire);
|
||||
}
|
||||
}
|
||||
|
|
@ -32,7 +32,7 @@ public sealed class IffAndCombatTests : IDisposable
|
|||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
|
||||
Behaviors = { new InstantWeaponData() }
|
||||
Behaviors = { new InstantWeaponData { Count = new PerformanceStat { Min = 1, Max = 1 }, Cooldown = new PerformanceStat { Min = 1, Max = 1 } } }
|
||||
});
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
|
|
@ -248,9 +248,11 @@ public sealed class IffAndCombatTests : IDisposable
|
|||
shooter.Target.Value = target;
|
||||
shooter.SetIff(target, false); // explicitly neutral
|
||||
|
||||
weapon.Execute(.01f); // resolves the gun's stats: a burst has no rounds before the first tick
|
||||
weapon.Activate();
|
||||
weapon.Execute(.01f);
|
||||
|
||||
Assert.Equal(0f, weapon.Progress); // Trigger() was safed: no cooldown/burst was started
|
||||
Assert.True(weapon.CanFire); // Trigger() was safed: no burst fired, so no cooldown
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -264,9 +266,11 @@ public sealed class IffAndCombatTests : IDisposable
|
|||
shooter.Target.Value = target;
|
||||
shooter.SetIff(target, true);
|
||||
|
||||
weapon.Execute(.01f); // resolves the gun's stats: a burst has no rounds before the first tick
|
||||
weapon.Activate();
|
||||
weapon.Execute(.01f);
|
||||
|
||||
Assert.Equal(1f, weapon.Progress); // Trigger() ran: cooldown/burst started
|
||||
Assert.False(weapon.CanFire); // Trigger() ran: the burst fired and the cooldown runs
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
@ -277,9 +281,11 @@ public sealed class IffAndCombatTests : IDisposable
|
|||
var shooter = NewShip(items, zone, new Faction { Name = "Shooter" }, equipGun: true);
|
||||
var weapon = (InstantWeapon) shooter.Equipment.Single(e => e.Behaviors.Any(b => b is Weapon)).Behaviors.Single(b => b is Weapon);
|
||||
|
||||
weapon.Execute(.01f); // resolves the gun's stats: a burst has no rounds before the first tick
|
||||
weapon.Activate();
|
||||
weapon.Execute(.01f);
|
||||
|
||||
Assert.Equal(1f, weapon.Progress);
|
||||
Assert.False(weapon.CanFire); // Trigger() ran: the burst fired and the cooldown runs
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
37
tests/Aetheria.Shared.Tests/SafeAssert.cs
Normal file
37
tests/Aetheria.Shared.Tests/SafeAssert.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Xunit;
|
||||
|
||||
// Assertions over collections of entities and shots. xunit formats a collection's contents into its failure
|
||||
// message, and an Entity, a PendingShot or a ShotOutcome drags the whole zone graph in with it: the formatter
|
||||
// recurses until the test host dies of a stack overflow, which a mutation tool scores as a kill of every test
|
||||
// that was running. A failure here must be an ordinary red naming the test, so these compare counts and
|
||||
// identities and never hand xunit an entity.
|
||||
internal static class SafeAssert
|
||||
{
|
||||
public static void NoShots(Zone zone) =>
|
||||
Assert.True(zone.PendingShots.Count == 0, $"{zone.PendingShots.Count} shot(s) still pending");
|
||||
|
||||
public static PendingShot OnlyShot(Zone zone)
|
||||
{
|
||||
Assert.True(zone.PendingShots.Count == 1, $"expected exactly one pending shot, found {zone.PendingShots.Count}");
|
||||
return zone.PendingShots[0];
|
||||
}
|
||||
|
||||
public static T Only<T>(List<T> list)
|
||||
{
|
||||
Assert.True(list.Count == 1, $"expected exactly one {typeof(T).Name}, found {list.Count}");
|
||||
return list[0];
|
||||
}
|
||||
|
||||
public static void Empty<T>(List<T> list) => Assert.True(list.Count == 0, $"expected no {typeof(T).Name}, found {list.Count}");
|
||||
|
||||
public static void In(Zone zone, Entity entity, string why = "entity should be in the zone") =>
|
||||
Assert.True(zone.Entities.Contains(entity), why);
|
||||
|
||||
public static void NotIn(Zone zone, Entity entity, string why = "entity should have left the zone") =>
|
||||
Assert.False(zone.Entities.Contains(entity), why);
|
||||
}
|
||||
Loading…
Reference in a new issue