Merge origin/master into faction-play-1
Conflicts: GameData/Aetheria.cc takes master's blob (doctrine-catalog and verse-grammar re-applied in a later commit, follow-up catalog-blob-merge-order); IffAndCombatTests NewShip admits through zone.Admit(ship, piloted); Program.cs keeps master's cases plus doctrine-catalog; FireControlPerWeaponTests keeps master's asserts with the branch's Minion constructor. Master-only compile sites adapted: Minion(ship, doctrine) in FireControlPerWeaponTests, LayoutAimTests, ScannerTests; AgentFires threshold in SolutionTests; Zone.Remove and VerseGrammar in FlightTests. Not verified to build until the verify run at the end of the pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
86c3a94880
817 changed files with 66571 additions and 16096 deletions
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
|
@ -6,16 +7,22 @@ using GameCult.Caching.MessagePack;
|
|||
// Aetheria's stores: one home store per type, composed here and nowhere else.
|
||||
public static class AetheriaStores
|
||||
{
|
||||
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData) };
|
||||
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(VerseGrammar), typeof(VerseVerb) };
|
||||
public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) };
|
||||
public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) };
|
||||
|
||||
// Attaches (hydrates) the catalog read-only unless catalogWritable, then the run and player stores when given.
|
||||
// Throws when a [CultGlobal] type routed to the catalog has no record. The one exemption is a writable catalog with
|
||||
// no records at all, a seed store being authored from nothing; a populated catalog is held to it however it opens.
|
||||
public static CultCache Open(string catalogPath, string runPath = null, string playerPath = null, bool catalogWritable = false)
|
||||
// The registry is the process-wide one unless the caller scopes it (the test host does, so its own document types never
|
||||
// become catalog globals); the global check above is judged against whichever registry opened the cache.
|
||||
public static CultCache Open(string catalogPath, string runPath = null, string playerPath = null, bool catalogWritable = false,
|
||||
CultDocumentRegistry registry = null)
|
||||
{
|
||||
var cache = new CultCache();
|
||||
// A read-only open of an absent catalog would hydrate an empty game; a shipped player missing its catalog stops here.
|
||||
if (!catalogWritable && !File.Exists(catalogPath))
|
||||
throw new FileNotFoundException($"Catalog {catalogPath} does not exist; a read-only open never invents one.", catalogPath);
|
||||
var cache = new CultCache(registry);
|
||||
try
|
||||
{
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, !catalogWritable), CatalogTypes);
|
||||
|
|
@ -33,6 +40,7 @@ public static class AetheriaStores
|
|||
// 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);
|
||||
VerseGrammarValidation.ValidateAll(cache.GetAll<VerseVerb>());
|
||||
return cache;
|
||||
}
|
||||
catch
|
||||
|
|
@ -72,11 +80,15 @@ public static class CultRecordRefs
|
|||
{
|
||||
StatValidation.ValidateHeatResponse(data);
|
||||
StatValidation.ValidateStatModifiers(data.Name, data.Behaviors);
|
||||
StatValidation.ValidateMunitionParts(data.Name, data.Behaviors);
|
||||
StatValidation.ValidateMineLayerFlat(data.Name, data.Behaviors);
|
||||
StatValidation.ValidateRoleUsage(data.Name, data.Roles, data.Behaviors);
|
||||
}
|
||||
if (document is ConsumableItemData consumable)
|
||||
{
|
||||
StatValidation.ValidateStatModifiers(consumable.Name, consumable.Behaviors);
|
||||
StatValidation.ValidateMunitionParts(consumable.Name, consumable.Behaviors);
|
||||
StatValidation.ValidateMineLayerFlat(consumable.Name, consumable.Behaviors);
|
||||
StatValidation.ValidateRoleUsage(consumable.Name, consumable.Roles, consumable.Behaviors);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,22 +33,24 @@ public class CombatState : BaseState
|
|||
_availableLockingWeapons.Clear();
|
||||
|
||||
var toTarget = target.Position - _agent.Ship.Position;
|
||||
var targetDistance = length(toTarget);
|
||||
var targetDistance = length(toTarget.xz);
|
||||
|
||||
// Cut 2 (docs/fire-control-cut.md): aim at whichever revealed weapon on the target hits hardest at
|
||||
// this range, or clear the aim point when nothing qualifies -- the same predicate
|
||||
// (FireControl.IsRevealed) and the same writer (TrySelectTargetItem) the player path uses.
|
||||
// (FireControl.IsRevealed) and the same writer (TrySelectTargetItem) the player path uses. Which weapons it
|
||||
// believes the target has, and how hard each hits, come from its book's claims, not the target's live gear
|
||||
// (aetheria-ew, classify-from-belief; ew-claim-weapon-measure-ruled: the claimed design's rated figures); the
|
||||
// reveal's Item is the aim and stays the truth.
|
||||
EquippedItem bestTargetItem = null;
|
||||
var bestTargetDps = float.MinValue;
|
||||
foreach (var targetItem in target.Equipment)
|
||||
foreach (var reveal in _agent.Ship.RevealedWeapons(target))
|
||||
{
|
||||
if (!(targetItem.Behaviors.FirstOrDefault(b => b is Weapon) is Weapon targetWeapon)) continue;
|
||||
if (!FireControl.IsRevealed(_agent.Ship, targetItem)) continue;
|
||||
var dps = targetWeapon.RangeDamagePerSecond(targetDistance);
|
||||
if (!FireControl.IsRevealed(_agent.Ship, reveal.Item)) continue;
|
||||
var dps = reveal.Claimed.Behaviors.OfType<WeaponData>().First().RatedRangeDamagePerSecond(targetDistance);
|
||||
if (dps > bestTargetDps)
|
||||
{
|
||||
bestTargetDps = dps;
|
||||
bestTargetItem = targetItem;
|
||||
bestTargetItem = reveal.Item;
|
||||
}
|
||||
}
|
||||
_agent.Ship.TrySelectTargetItem(bestTargetItem);
|
||||
|
|
@ -108,9 +110,8 @@ public class CombatState : BaseState
|
|||
// Cut 3 (docs/fire-control-cut.md): the one prediction function, shared with FireControl.Fire's
|
||||
// own snapshot and the roll's deviation measurement -- two separate predictions here and in the
|
||||
// roll would let an AI aim at one point and get judged for missing a different one.
|
||||
var targetHullData = _agent.ItemManager.GetData(target.Hull) as HullData;
|
||||
var predictedPosition = FireControl.PredictedIntercept(testWeapon, _agent.Ship, target);
|
||||
predictedPosition.y = _agent.Ship.Zone.GetHeight(predictedPosition.xz) + targetHullData.GridOffset;
|
||||
predictedPosition.y = target.RideHeight(predictedPosition.xz);
|
||||
toTarget = normalize(predictedPosition - _agent.Ship.Position);
|
||||
}
|
||||
|
||||
|
|
@ -138,8 +139,8 @@ public class CombatState : BaseState
|
|||
var maxRange = Single.MinValue;
|
||||
foreach (var weapon in _agent.Ship.Weapons)
|
||||
{
|
||||
if (weapon.Range < minRange)
|
||||
minRange = weapon.Range;
|
||||
if (weapon.MinRange < minRange)
|
||||
minRange = weapon.MinRange;
|
||||
if (weapon.Range > maxRange)
|
||||
maxRange = weapon.Range;
|
||||
}
|
||||
|
|
@ -152,7 +153,7 @@ public class CombatState : BaseState
|
|||
float dps = 0;
|
||||
foreach (var weapon in _agent.Ship.Weapons)
|
||||
{
|
||||
if (weapon.Item.Online.Value && weapon.MinRange < range && range < weapon.Range)
|
||||
if (weapon.Item.Online.Value)
|
||||
dps += weapon.RangeDamagePerSecond(range);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,185 +0,0 @@
|
|||
/* 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 GameCult.Caching;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship), RuntimeInspectable]
|
||||
public class AetherDriveData : BehaviorData
|
||||
{
|
||||
[Inspectable, JsonProperty("diameters"), Key(1)]
|
||||
public float3 RotorDiameter;
|
||||
|
||||
[Inspectable, JsonProperty("masses"), Key(2)]
|
||||
public float3 RotorMass;
|
||||
|
||||
[Inspectable, JsonProperty("rpm"), Key(3), RuntimeInspectable]
|
||||
public PerformanceStat MaximumRpm;
|
||||
|
||||
[Inspectable, JsonProperty("couplingLambdas"), Key(4)]
|
||||
public float3 CouplingLambda;
|
||||
|
||||
[Inspectable, JsonProperty("lambdaMultiplier"), Key(5)]
|
||||
public PerformanceStat LambdaMultiplier;
|
||||
|
||||
[Inspectable, JsonProperty("couplingEfficiency"), Key(6), RuntimeInspectable]
|
||||
public PerformanceStat CouplingEfficiency;
|
||||
|
||||
[Inspectable, JsonProperty("torque"), Key(7), RuntimeInspectable]
|
||||
public PerformanceStat Torque;
|
||||
|
||||
[Inspectable, JsonProperty("torqueProfile"), Key(8), RuntimeInspectable]
|
||||
public BezierCurve TorqueProfile;
|
||||
|
||||
[Inspectable, JsonProperty("draw"), Key(9), RuntimeInspectable]
|
||||
public PerformanceStat EnergyDraw;
|
||||
|
||||
[Inspectable, JsonProperty("passiveCoupling"), Key(10), RuntimeInspectable]
|
||||
public PerformanceStat PassiveCoupling;
|
||||
|
||||
[Inspectable, JsonProperty("rpmAudio"), Key(11), RuntimeInspectable]
|
||||
public uint RpmAudioParameter;
|
||||
|
||||
[Inspectable, JsonProperty("torqueAudio"), Key(12), RuntimeInspectable]
|
||||
public uint TorqueRatioAudioParameter;
|
||||
|
||||
[Inspectable, CultInspectorAssetGuid, JsonProperty("particles"), Key(13)]
|
||||
public string Particles;
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new AetherDrive(this, item);
|
||||
}
|
||||
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new AetherDrive(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class AetherDrive : Behavior, IPowerConsumer
|
||||
{
|
||||
private AetherDriveData _data;
|
||||
private float3 _axis;
|
||||
|
||||
public float3 Thrust { get; private set; }
|
||||
public float3 Rpm { get; private set; }
|
||||
public float MaximumRpm { get; private set; }
|
||||
public float2 ThrustDirection { get; private set; }
|
||||
|
||||
public AetherDriveData DriveData => _data;
|
||||
|
||||
// Cut 8 (operator ask 2026-09-19): the equivalent quantity to Thruster.Condition -- Torque is the stat that
|
||||
// actually governs this behaviour's rotor spin-up (PowerRequest/Execute above both read it), so it is what
|
||||
// "broken" means for a drive. 1f for the item-less ConsumableItemEffect case, same reasoning as Thruster.
|
||||
public float Condition => Item?.ConditionRatio(_data.Torque) ?? 1f;
|
||||
|
||||
public float3 Axis
|
||||
{
|
||||
get => _axis;
|
||||
set => _axis = clamp(value, -1, 1);
|
||||
}
|
||||
|
||||
public AetherDrive(AetherDriveData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public AetherDrive(AetherDriveData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
// Cut 3 (docs/stats-and-power-cut.md): the request PowerBus needs before Execute runs. Only the rotor
|
||||
// spin-up (torque accelerating Rpm toward MaximumRpm) costs power -- spending existing spin into thrust
|
||||
// (Execute's decay-to-thrust arithmetic below) is free, same as before. Pure and side-effect-free: it reads
|
||||
// Rpm but does not write it, so Execute's own identical arithmetic a few lines later -- which does perform
|
||||
// the real decay -- produces the same numbers Rpm actually moves by. Accepts the recompute (Q3's ruling).
|
||||
//
|
||||
// Nominal-request ruling (docs/stats-and-power-cut.md, operator ruling 2026-09-19): Torque, LambdaMultiplier,
|
||||
// MaximumRpm, PassiveCoupling and EnergyDraw are all registered request fields (StatValidation.
|
||||
// PowerRequestFields) -- read nominally (what full power would produce) so Torque carrying its own
|
||||
// PowerSupply term (Cut 7's brownout curve) no longer makes this tick's request depend on this tick's own
|
||||
// grant. Execute below is unchanged: it calls the real, curved Evaluate, so the actual spin-up still
|
||||
// degrades with whatever the bus actually grants.
|
||||
public float PowerRequest(float dt)
|
||||
{
|
||||
var couplingLambda = _data.CouplingLambda * Item.EvaluateNominalPower(_data.LambdaMultiplier) * max(abs(_axis), EvaluateNominalPower(_data.PassiveCoupling));
|
||||
var rpmAfterDecay = decay(Rpm, couplingLambda, dt);
|
||||
var maximumRpm = EvaluateNominalPower(_data.MaximumRpm);
|
||||
var torqueProfile = float3(
|
||||
_data.TorqueProfile.Evaluate(rpmAfterDecay.x / maximumRpm),
|
||||
_data.TorqueProfile.Evaluate(rpmAfterDecay.y / maximumRpm),
|
||||
_data.TorqueProfile.Evaluate(rpmAfterDecay.z / maximumRpm));
|
||||
var potentialTorque = EvaluateNominalPower(_data.Torque) * torqueProfile;
|
||||
var potentialRpmDelta = potentialTorque / length(_data.RotorMass) * dt;
|
||||
var actualRpmDelta = min(maximumRpm - rpmAfterDecay, potentialRpmDelta);
|
||||
var torqueRatio = actualRpmDelta / potentialRpmDelta;
|
||||
var draw = torqueRatio * EvaluateNominalPower(_data.EnergyDraw) / 3;
|
||||
return (draw.x + draw.y + draw.z) * dt;
|
||||
}
|
||||
|
||||
// Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Medium -- mobility, same as Thruster.
|
||||
public int DefaultPowerTier => PowerTiers.Medium;
|
||||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
var rotorSpeed = Rpm * _data.RotorDiameter / 100;
|
||||
|
||||
var forward = normalize(Entity.Direction);
|
||||
var right = forward.Rotate(ItemRotation.Clockwise);
|
||||
|
||||
var speed = float2(dot(Entity.Velocity, forward), dot(Entity.Velocity, right));
|
||||
var couplingEfficiency = Evaluate(_data.CouplingEfficiency);
|
||||
var efficiency = float3(saturate(1 - speed / max(rotorSpeed.xy, 1) * sign(_axis.xy)) * couplingEfficiency, 1);
|
||||
|
||||
Thrust = (Rpm - decay(Rpm, _data.CouplingLambda, dt)) * _data.RotorMass * efficiency;
|
||||
|
||||
var couplingLambda = _data.CouplingLambda * Item.Evaluate(_data.LambdaMultiplier) * max(abs(_axis), Evaluate(_data.PassiveCoupling));
|
||||
var previousRpm = Rpm;
|
||||
Rpm = decay(Rpm, couplingLambda, dt);
|
||||
var rpmLoss = previousRpm - Rpm;
|
||||
var force = rpmLoss * _data.RotorMass * efficiency;
|
||||
|
||||
var heat = rpmLoss * _data.RotorMass * (1 - couplingEfficiency);
|
||||
AddHeat((heat.x + heat.y + heat.z)*ItemManager.GameplaySettings.AetherHeatMultiplier);
|
||||
|
||||
ThrustDirection = forward * (_axis.x * force.x / Entity.Mass) + right * (_axis.y * force.y / Entity.Mass);
|
||||
Entity.Velocity += ThrustDirection;
|
||||
|
||||
Entity.Direction = mul(Entity.Direction,
|
||||
CultMath.float2x2.Rotate(force.z * _axis.z * ItemManager.GameplaySettings.AetherTorqueMultiplier / Entity.Mass));
|
||||
|
||||
if(float.IsNaN(Entity.Velocity.x))
|
||||
ItemManager.Log("FUCK FUCK FUCK FUCK");
|
||||
|
||||
MaximumRpm = Evaluate(_data.MaximumRpm);
|
||||
var torqueProfile = float3(
|
||||
_data.TorqueProfile.Evaluate(Rpm.x / MaximumRpm),
|
||||
_data.TorqueProfile.Evaluate(Rpm.y / MaximumRpm),
|
||||
_data.TorqueProfile.Evaluate(Rpm.z / MaximumRpm));
|
||||
var potentialTorque = Evaluate(_data.Torque) * torqueProfile;
|
||||
var potentialRpmDelta = potentialTorque / length(_data.RotorMass) * dt;
|
||||
var actualRpmDelta = min(MaximumRpm - Rpm, potentialRpmDelta);
|
||||
var torqueRatio = actualRpmDelta / potentialRpmDelta;
|
||||
|
||||
Item.SetAudioParameter(SpecialAudioParameter.Intensity, max(max(abs(_axis.x), abs(_axis.y)), abs(_axis.z)));
|
||||
Item.SetAudioParameter(_data.RpmAudioParameter, (Rpm.x + Rpm.y + Rpm.z) / 3 / MaximumRpm);
|
||||
Item.SetAudioParameter(_data.TorqueRatioAudioParameter, max(max(torqueRatio.x, torqueRatio.y), torqueRatio.z));
|
||||
|
||||
// Cut 7 (docs/stats-and-power-target.md): actualRpmDelta already derives from Evaluate(_data.Torque)
|
||||
// above, so a Torque stat carrying a PowerSupply term already shrinks the rotor's spin-up under a
|
||||
// partial grant -- this no longer demands a full one, only that supply has not been cut to true zero.
|
||||
if (Item.PowerSupply > 1e-4f)
|
||||
{
|
||||
Rpm += actualRpmDelta;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 2022c838bbc64a0d86cfbd477e6a379c
|
||||
timeCreated: 1618332827
|
||||
|
|
@ -93,11 +93,6 @@ public interface IActivatedBehavior
|
|||
void Deactivate();
|
||||
}
|
||||
|
||||
public interface IAnalogBehavior
|
||||
{
|
||||
float Axis { get; set; }
|
||||
}
|
||||
|
||||
public interface IEventBehavior
|
||||
{
|
||||
void ResetEvents();
|
||||
|
|
@ -157,7 +152,7 @@ public interface IPowerConsumer
|
|||
Union(9, typeof(WearData)),
|
||||
Union(10, typeof(VelocityConversionData)),
|
||||
Union(11, typeof(VelocityLimitData)),
|
||||
Union(12, typeof(AetherDriveData)),
|
||||
// Union(12): retired, do not reuse -- was AetherDriveData (retire-longinusx; parked/aether-drive)
|
||||
// Union(14, typeof(TowingControllerData)),
|
||||
Union(15, typeof(CooldownData)),
|
||||
Union(16, typeof(HeatData)),
|
||||
|
|
@ -187,6 +182,17 @@ public interface IPowerConsumer
|
|||
// superseded draft quoted -- checked directly here rather than trusted from that document.
|
||||
Union(39, typeof(TargetingSystemData)),
|
||||
Union(40, typeof(MineLayerData)),
|
||||
Union(41, typeof(ThrottleLockData)),
|
||||
Union(42, typeof(VapourDumpData)),
|
||||
Union(43, typeof(MunitionHullData)),
|
||||
Union(44, typeof(MunitionThrusterData)),
|
||||
Union(45, typeof(MunitionSeekerData)),
|
||||
Union(46, typeof(MunitionControlData)),
|
||||
Union(47, typeof(MunitionFuelData)),
|
||||
Union(48, typeof(PickupData)),
|
||||
Union(49, typeof(LaunchSuppressorData)),
|
||||
Union(50, typeof(ListenerData)),
|
||||
Union(51, typeof(ScannerData)),
|
||||
JsonObject(MemberSerialization.OptIn)]
|
||||
public abstract class BehaviorData
|
||||
{
|
||||
|
|
|
|||
|
|
@ -54,6 +54,15 @@ public class ChargedWeaponData : InstantWeaponData
|
|||
{
|
||||
return new ChargedWeapon(this, item);
|
||||
}
|
||||
|
||||
// The one formula of a charged weapon's damage per second at a range (see InstantWeaponData.RangeDamagePerSecond).
|
||||
internal static float RangeDamagePerSecond(float damage, float chargeFiringDamageMultiplier, float cooldown, float chargeTime,
|
||||
float rangeFactor) =>
|
||||
damage * chargeFiringDamageMultiplier * rangeFactor / (cooldown + chargeTime);
|
||||
|
||||
public override float RatedRangeDamagePerSecond(float range) =>
|
||||
RangeDamagePerSecond(PerRound(Damage.Max, Count.Max), ChargeFiringDamageMultiplier, Cooldown.Max, ChargeTime.Max,
|
||||
RatedRangeFactor(range));
|
||||
}
|
||||
|
||||
public class ChargedWeapon : InstantWeapon
|
||||
|
|
@ -75,13 +84,14 @@ public class ChargedWeapon : InstantWeapon
|
|||
// authored charge-up speed IS its sustained rate of fire, not a second, disconnected number.
|
||||
protected override float RateOverride => Evaluate(_data.ChargeEnergy);
|
||||
|
||||
public override float DamagePerSecond => Damage * _data.ChargeFiringDamageMultiplier / (Cooldown + ChargeTime);
|
||||
// The charge multiplier lives in the formula alone: Damage is lerped by charge for the shot itself (UpdateStats), so the
|
||||
// live reads take the uncharged damage, and a nominal weapon reads its design's rated figure at every charge.
|
||||
private float _unchargedDamage;
|
||||
public override float DamagePerSecond => _unchargedDamage * _data.ChargeFiringDamageMultiplier / (Cooldown + ChargeTime);
|
||||
public override float RangeDamagePerSecond(float range)
|
||||
{
|
||||
return Damage *
|
||||
_data.ChargeFiringDamageMultiplier *
|
||||
_data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range))) /
|
||||
(Cooldown + ChargeTime);
|
||||
return ChargedWeaponData.RangeDamagePerSecond(_unchargedDamage, _data.ChargeFiringDamageMultiplier, Cooldown, ChargeTime,
|
||||
RangeFactor(range));
|
||||
}
|
||||
|
||||
public event Action OnStartCharging;
|
||||
|
|
@ -121,6 +131,7 @@ public class ChargedWeapon : InstantWeapon
|
|||
ChargeTime = Evaluate(_data.ChargeTime);
|
||||
ChargeEnergy = Evaluate(_data.ChargeEnergy);
|
||||
ChargeHeat = Evaluate(_data.ChargeHeat);
|
||||
_unchargedDamage = Damage;
|
||||
Damage *= lerp(1, _data.ChargeFiringDamageMultiplier, saturate(_charge));
|
||||
Heat *= lerp(1, _data.ChargeFiringHeatMultiplier, saturate(_charge));
|
||||
Spread *= lerp(1, _data.ChargeFiringSpreadMultiplier, saturate(_charge));
|
||||
|
|
@ -134,7 +145,6 @@ public class ChargedWeapon : InstantWeapon
|
|||
if (_charging)
|
||||
{
|
||||
_charge += dt / ChargeTime;
|
||||
Item.SetAudioParameter(SpecialAudioParameter.ChargeLevel, saturate(_charge));
|
||||
if (!_charged)
|
||||
{
|
||||
AddHeat(ChargeHeat * (dt / ChargeTime));
|
||||
|
|
@ -151,7 +161,6 @@ public class ChargedWeapon : InstantWeapon
|
|||
_coolingDown = true;
|
||||
_charge = 0;
|
||||
OnFailed?.Invoke();
|
||||
Item.FireAudioEvent(ChargedWeaponAudioEvent.Fail);
|
||||
CauseDamage(_data.FailureDamage);
|
||||
}
|
||||
}
|
||||
|
|
@ -166,7 +175,6 @@ public class ChargedWeapon : InstantWeapon
|
|||
if(!_charging && CanFire && !FireControl.Refuses(this, Entity))
|
||||
{
|
||||
OnStartCharging?.Invoke();
|
||||
Item.FireAudioEvent(ChargedWeaponAudioEvent.Start);
|
||||
_charging = true;
|
||||
_charged = false;
|
||||
}
|
||||
|
|
@ -182,7 +190,6 @@ public class ChargedWeapon : InstantWeapon
|
|||
_charge = 0;
|
||||
}
|
||||
OnStopCharging?.Invoke();
|
||||
Item.FireAudioEvent(ChargedWeaponAudioEvent.Stop);
|
||||
_charging = false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,12 @@ public class ConstantWeaponData : WeaponData
|
|||
{
|
||||
return new ConstantWeapon(this, item);
|
||||
}
|
||||
|
||||
// The one formula of a beam's damage per second at a range (see InstantWeaponData.RangeDamagePerSecond).
|
||||
internal static float RangeDamagePerSecond(float damage, float rangeFactor) => damage * rangeFactor;
|
||||
|
||||
public override float RatedRangeDamagePerSecond(float range) =>
|
||||
RangeDamagePerSecond(Damage.Max, RatedRangeFactor(range));
|
||||
}
|
||||
|
||||
public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerConsumer
|
||||
|
|
@ -49,7 +55,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC
|
|||
public override float DamagePerSecond => Damage;
|
||||
public override float RangeDamagePerSecond(float range)
|
||||
{
|
||||
return Damage * _data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range)));
|
||||
return ConstantWeaponData.RangeDamagePerSecond(Damage, RangeFactor(range));
|
||||
}
|
||||
|
||||
public event Action OnReloadBegin;
|
||||
|
|
@ -170,7 +176,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC
|
|||
|
||||
CauseWearDamage(dt);
|
||||
AddHeat(Evaluate(_data.Heat) * dt);
|
||||
Entity.VisibilitySources[this] = Evaluate(_data.Visibility);
|
||||
Entity.SetSignature(this, SignatureChannel.LaunchFlash, Evaluate(_data.Visibility), Item);
|
||||
|
||||
// Cut 4 (docs/fire-control-cut.md): a beam is a sequence of rolls, not a continuous truth -- one
|
||||
// FireControl.Fire per BeamResolveInterval, for that interval's worth of Damage, through the same
|
||||
|
|
|
|||
|
|
@ -30,6 +30,16 @@ public class InstantWeaponData : WeaponData
|
|||
{
|
||||
return new InstantWeapon(this, item);
|
||||
}
|
||||
|
||||
// The one formula of an instant weapon's damage per second at a range; the live weapon calls it with its evaluated
|
||||
// stats, the design with its rated ones. A burst's round carries its share of the totals: PerRound, the one divisor
|
||||
// UpdateStats and the rated read both use.
|
||||
internal static float PerRound(float total, float burstCount) => total / (int) burstCount;
|
||||
|
||||
internal static float RangeDamagePerSecond(float damage, float cooldown, float rangeFactor) => damage * rangeFactor / cooldown;
|
||||
|
||||
public override float RatedRangeDamagePerSecond(float range) =>
|
||||
RangeDamagePerSecond(PerRound(Damage.Max, Count.Max), Cooldown.Max, RatedRangeFactor(range));
|
||||
}
|
||||
|
||||
public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerConsumer
|
||||
|
|
@ -61,7 +71,7 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
public override float DamagePerSecond => Damage / Cooldown;
|
||||
public override float RangeDamagePerSecond(float range)
|
||||
{
|
||||
return Damage * _data.DamageCurve.Evaluate(saturate(unlerp(MinRange, Range, range))) / Cooldown;
|
||||
return InstantWeaponData.RangeDamagePerSecond(Damage, Cooldown, RangeFactor(range));
|
||||
}
|
||||
|
||||
public override int Ammo
|
||||
|
|
@ -129,9 +139,9 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
BurstTime = Evaluate(_data.BurstTime);
|
||||
Cooldown = Evaluate(_data.Cooldown);
|
||||
|
||||
Damage /= (int) BurstCount;
|
||||
Heat /= (int) BurstCount;
|
||||
Energy /= (int) BurstCount;
|
||||
Damage = InstantWeaponData.PerRound(Damage, BurstCount);
|
||||
Heat = InstantWeaponData.PerRound(Heat, BurstCount);
|
||||
Energy = InstantWeaponData.PerRound(Energy, BurstCount);
|
||||
}
|
||||
|
||||
// Cut 4 (docs/stats-and-power-cut.md §7 Q4): capacity and rate, resolved fresh rather than off the cached
|
||||
|
|
@ -230,7 +240,6 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
}
|
||||
}
|
||||
|
||||
var firedThisFrame = false;
|
||||
_burstTimer += dt;
|
||||
while (_burstRemaining > 0 && _burstTimer > 0)
|
||||
{
|
||||
|
|
@ -270,14 +279,9 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo
|
|||
// Evaluate it into a local first.
|
||||
var shotId = FireControl.Fire(this, Item, Entity);
|
||||
OnFire?.Invoke(shotId);
|
||||
if(!firedThisFrame)
|
||||
{
|
||||
Item.FireAudioEvent(WeaponAudioEvent.Fire);
|
||||
firedThisFrame = true;
|
||||
}
|
||||
CauseWearDamage(1);
|
||||
AddHeat(Heat);
|
||||
Entity.VisibilitySources[this] = Visibility;
|
||||
Entity.SetSignature(this, SignatureChannel.LaunchFlash, Visibility, Item);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
62
Assets/Scripts/ServerShared/Behaviors/LaunchSuppressor.cs
Normal file
62
Assets/Scripts/ServerShared/Behaviors/LaunchSuppressor.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
/* 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 MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using static CultMath.math;
|
||||
|
||||
// Electronic warfare, hide-launch (campaign aetheria-ew, invariants lie-is-own-emission and lies-cost-real-heat): a
|
||||
// gear that thins its own ship's launch flash. It never stores a factor and never writes a signature: Entity.SetSignature
|
||||
// asks each equipped suppressor at write time, so the order in which a weapon and a suppressor execute decides nothing.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class LaunchSuppressorData : BehaviorData
|
||||
{
|
||||
// The multiplier on the flash, clamped to 0..1: a suppressor never brightens a launch.
|
||||
[Inspectable, JsonProperty("factor"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Factor = new PerformanceStat();
|
||||
|
||||
// Heat paid to the suppressor's own cell per unit of strength it removed.
|
||||
[Inspectable, JsonProperty("heatPerUnit"), Key(2)]
|
||||
public PerformanceStat HeatPerUnit = new PerformanceStat();
|
||||
|
||||
// Above this item temperature the suppressor scales nothing and pays nothing.
|
||||
[Inspectable, JsonProperty("ratedTemperature"), Key(3)]
|
||||
public PerformanceStat RatedTemperature = new PerformanceStat();
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new LaunchSuppressor(this, item);
|
||||
}
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new LaunchSuppressor(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class LaunchSuppressor : Behavior
|
||||
{
|
||||
private readonly LaunchSuppressorData _data;
|
||||
|
||||
public LaunchSuppressor(LaunchSuppressorData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
public LaunchSuppressor(LaunchSuppressorData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
// Called by Entity.SetSignature for every light signature the ship writes; the strength passes through unchanged
|
||||
// unless this is a launch flash and the suppressor is running below its rated temperature.
|
||||
internal float Suppress(SignatureChannel channel, float strength)
|
||||
{
|
||||
if (channel != SignatureChannel.LaunchFlash || Item == null || !Item.Active.Value || Temperature > Evaluate(_data.RatedTemperature))
|
||||
return strength;
|
||||
var scaled = strength * clamp(Evaluate(_data.Factor), 0f, 1f);
|
||||
AddHeat((strength - scaled) * Evaluate(_data.HeatPerUnit));
|
||||
return scaled;
|
||||
}
|
||||
|
||||
public override bool Execute(float dt) => true;
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: be58ee6eb8c74ea89518ee8200add0ba
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -18,14 +18,7 @@ public class LauncherData : LockWeaponData
|
|||
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(28)]
|
||||
public float4[] LiftCurve;
|
||||
|
||||
[Inspectable, JsonProperty("thrust"), Key(29)]
|
||||
public PerformanceStat Thrust = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("frequency"), Key(30)]
|
||||
public float DodgeFrequency;
|
||||
|
||||
[Inspectable, JsonProperty("missileSpeed"), Key(31), RuntimeInspectable]
|
||||
public PerformanceStat MissileVelocity = new PerformanceStat();
|
||||
// Keys 29-31 were Thrust, DodgeFrequency and MissileVelocity, retired for the munition parts (MunitionParts.cs); do not reuse.
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
@ -45,14 +38,7 @@ public class GuidedWeaponData : InstantWeaponData
|
|||
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(23)]
|
||||
public float4[] LiftCurve;
|
||||
|
||||
[Inspectable, JsonProperty("thrust"), Key(24)]
|
||||
public PerformanceStat Thrust = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("frequency"), Key(25)]
|
||||
public float DodgeFrequency;
|
||||
|
||||
[Inspectable, JsonProperty("missileSpeed"), Key(26), RuntimeInspectable]
|
||||
public PerformanceStat MissileVelocity = new PerformanceStat();
|
||||
// Keys 24-26 were Thrust, DodgeFrequency and MissileVelocity, retired for the munition parts (MunitionParts.cs); do not reuse.
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
|
|||
44
Assets/Scripts/ServerShared/Behaviors/Listener.cs
Normal file
44
Assets/Scripts/ServerShared/Behaviors/Listener.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/* 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 MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
// Passive listening gear (ruling sensor-stat-set): hears other ships' emissions at a multiple of their own range,
|
||||
// bearing only. It emits nothing; Entity.HearingMultiple asks each active listener at hearing time. Its power is the
|
||||
// design's EnergyDraw and its activity is the item's Active, as for sensors.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class ListenerData : BehaviorData
|
||||
{
|
||||
// How many times an emitter's own reach this listener hears it at.
|
||||
[Inspectable, JsonProperty("multiple"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Multiple = new PerformanceStat();
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new Listener(this, item);
|
||||
}
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new Listener(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class Listener : Behavior
|
||||
{
|
||||
private readonly ListenerData _data;
|
||||
|
||||
public Listener(ListenerData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
public Listener(ListenerData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public float Multiple => Evaluate(_data.Multiple);
|
||||
|
||||
public override bool Execute(float dt) => true;
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/Listener.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/Listener.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5b0e1f6c2d7a4e39a8c4d1f27e6b3a90
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -23,6 +23,11 @@ public class LockWeaponData : InstantWeaponData
|
|||
|
||||
[Inspectable, JsonProperty("decay"), Key(25)]
|
||||
public PerformanceStat Decay = new PerformanceStat();
|
||||
|
||||
// The ratio of how far this lock sees to how far others hear it (ruling sensor-stat-set); a design without it
|
||||
// reads as 1.
|
||||
[Inspectable, JsonProperty("interceptFactor"), Key(34)]
|
||||
public PerformanceStat InterceptFactor;
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
@ -50,6 +55,7 @@ public class LockWeapon : InstantWeapon
|
|||
public float LockAngle { get; private set; }
|
||||
public float DirectionImpact { get; private set; }
|
||||
public float Decay { get; private set; }
|
||||
public float InterceptFactor => _data.InterceptFactor == null ? 1f : Evaluate(_data.InterceptFactor);
|
||||
|
||||
public override float Progress => saturate(_cooldown > 0 ? _cooldown : _lock);
|
||||
|
||||
|
|
@ -102,6 +108,8 @@ public class LockWeapon : InstantWeapon
|
|||
{
|
||||
var lerp = 1 - unlerp(0, 90, degrees);
|
||||
_lock = saturate(_lock + pow(lerp, DirectionImpact) * dt * LockSpeed * pow(Entity.EntityInfoGathered[target], SensorImpact));
|
||||
target.ReceivePaint(Entity, Item, PaintMode.Track, Lock);
|
||||
Entity.Emit(Item, Range / InterceptFactor);
|
||||
}
|
||||
else _lock = saturate(_lock - dt * Decay);
|
||||
}
|
||||
|
|
@ -109,4 +117,3 @@ public class LockWeapon : InstantWeapon
|
|||
return base.Execute(dt);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
125
Assets/Scripts/ServerShared/Behaviors/MunitionParts.cs
Normal file
125
Assets/Scripts/ServerShared/Behaviors/MunitionParts.cs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
/* 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.Linq;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
// A missile type's stats, as five dedicated gear-part behaviours on the launcher's own design, one per gear
|
||||
// category the entity cut will derive them from (ruling drones-and-munitions-are-entities: "dedicated gear so a
|
||||
// missile thruster is not the same as a ship thruster"). Ruling missile-stats-now-gear-later, in the operator's
|
||||
// words: "For now these stats will belong to the missile, later they will be derived from gear." Each part becomes
|
||||
// a derivation from (or moves onto) that munition gear when munitions are entities.
|
||||
//
|
||||
// Each part is its own BehaviorData because every stat walker (role validation, StatModifier targeting, AetherDb
|
||||
// roles, the trade panel) reads PerformanceStat fields one level deep. The parts are inert: nothing here executes,
|
||||
// and no ship-wide reader (thrust allocator, sensing, signatures) reads them, because a missile thruster is not a
|
||||
// ship thruster and a seeker is not a ship sensor. MunitionParts.Of is the one read path.
|
||||
public abstract class MunitionPartData : BehaviorData
|
||||
{
|
||||
public override Behavior CreateInstance(EquippedItem item) => new MunitionPart(this, item);
|
||||
public override Behavior CreateInstance(ConsumableItemEffect consumable) => new MunitionPart(this, consumable);
|
||||
}
|
||||
|
||||
// What a part instantiates to: no state and no override, so Execute stays the default true.
|
||||
public sealed class MunitionPart : Behavior
|
||||
{
|
||||
public MunitionPart(MunitionPartData data, EquippedItem item) : base(data, item) { }
|
||||
public MunitionPart(MunitionPartData data, ConsumableItemEffect consumable) : base(data, consumable) { }
|
||||
}
|
||||
|
||||
public static class MunitionParts
|
||||
{
|
||||
// The design's one part of that type. Catalog load and Upsert refuse a munition without exactly one of each.
|
||||
public static T Of<T>(EquippedItem item) where T : MunitionPartData =>
|
||||
item.Behaviors.Select(b => b.Data).OfType<T>().Single();
|
||||
}
|
||||
|
||||
// The missile hull.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public sealed class MunitionHullData : MunitionPartData
|
||||
{
|
||||
[Inspectable, JsonProperty("durability"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Durability = new PerformanceStat();
|
||||
|
||||
// Metres.
|
||||
[Inspectable, JsonProperty("radius"), Key(2)]
|
||||
public PerformanceStat Radius = new PerformanceStat();
|
||||
}
|
||||
|
||||
// The missile thruster.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public sealed class MunitionThrusterData : MunitionPartData
|
||||
{
|
||||
// The main motor, m/s^2.
|
||||
[Inspectable, JsonProperty("acceleration"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Acceleration = new PerformanceStat();
|
||||
|
||||
// The sideways acceleration cap, m/s^2.
|
||||
[Inspectable, JsonProperty("lateral"), Key(2)]
|
||||
public PerformanceStat Lateral = new PerformanceStat();
|
||||
|
||||
// m/s.
|
||||
[Inspectable, JsonProperty("maxSpeed"), Key(3), RuntimeInspectable]
|
||||
public PerformanceStat MaxSpeed = new PerformanceStat();
|
||||
|
||||
// The strength of this motor's DrivePlume at full throttle, as ThrusterData.Visibility. A datum only: it is
|
||||
// never registered as the launching ship's signature.
|
||||
[Inspectable, JsonProperty("visibility"), Key(4)]
|
||||
public PerformanceStat Visibility = new PerformanceStat();
|
||||
}
|
||||
|
||||
// The seeker. Passive here: it reads a target and emits nothing.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public sealed class MunitionSeekerData : MunitionPartData
|
||||
{
|
||||
// Detection power, as SensorData.Sensitivity.
|
||||
[Inspectable, JsonProperty("sensitivity"), Key(1)]
|
||||
public PerformanceStat Sensitivity = new PerformanceStat();
|
||||
|
||||
// The full cone, in degrees (ruling sensor-stat-set's name and unit).
|
||||
[Inspectable, JsonProperty("beamWidth"), Key(2)]
|
||||
public PerformanceStat BeamWidth = new PerformanceStat();
|
||||
|
||||
// Metres.
|
||||
[Inspectable, JsonProperty("range"), Key(3)]
|
||||
public PerformanceStat Range = new PerformanceStat();
|
||||
}
|
||||
|
||||
// Guidance and its cognition.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public sealed class MunitionControlData : MunitionPartData
|
||||
{
|
||||
// The proportional-navigation constant.
|
||||
[Inspectable, JsonProperty("navigation"), Key(1)]
|
||||
public PerformanceStat Navigation = new PerformanceStat();
|
||||
|
||||
// The share of Lateral spent jinking.
|
||||
[Inspectable, JsonProperty("evasion"), Key(2)]
|
||||
public PerformanceStat Evasion = new PerformanceStat();
|
||||
|
||||
// Hz.
|
||||
[Inspectable, JsonProperty("evasionFrequency"), Key(3), RuntimeInspectable]
|
||||
public PerformanceStat EvasionFrequency = new PerformanceStat();
|
||||
|
||||
// Seconds.
|
||||
[Inspectable, JsonProperty("lifetime"), Key(4)]
|
||||
public PerformanceStat Lifetime = new PerformanceStat();
|
||||
|
||||
// The missile's own skill, 0 to 1 (ruling missile-cognition: "a smarter missile can better spend its delta v").
|
||||
// Four uses: guidance efficiency, when to jink against point defense, how much fuel it keeps for the terminal,
|
||||
// and the price of the hit.
|
||||
[Inspectable, JsonProperty("cognition"), Key(5)]
|
||||
public PerformanceStat Cognition = new PerformanceStat();
|
||||
}
|
||||
|
||||
// The tank.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
|
||||
public sealed class MunitionFuelData : MunitionPartData
|
||||
{
|
||||
// Total manoeuvre budget, m/s.
|
||||
[Inspectable, JsonProperty("deltaV"), Key(1)]
|
||||
public PerformanceStat DeltaV = new PerformanceStat();
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/MunitionParts.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/MunitionParts.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6d4eac117ca042aaba71d1f6491b4617
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
171
Assets/Scripts/ServerShared/Behaviors/Pickup.cs
Normal file
171
Assets/Scripts/ServerShared/Behaviors/Pickup.cs
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
|
||||
// The tractor beam: the capability that lets a ship collect floating items. It spins its beam up in sim time toward
|
||||
// the pilot's command, and once the beam is up claims the free item nearest its axis and runs one timed grab
|
||||
// (extend, envelop, pull) that ends in Zone.TryPickUp, the one commit of a pickup. Its stats are flat
|
||||
// (Min == Max), as the other behaviours that carry their own timings.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class PickupData : BehaviorData
|
||||
{
|
||||
// How far along the beam's axis an item can be claimed, and how far off the axis.
|
||||
[Inspectable, JsonProperty("range"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Range = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("beamRadius"), Key(2), RuntimeInspectable]
|
||||
public PerformanceStat BeamRadius = new PerformanceStat();
|
||||
|
||||
// The spin-up (0..1) needed to claim an item, and to keep a grab going.
|
||||
[Inspectable, JsonProperty("grabPower"), Key(3), RuntimeInspectable]
|
||||
public PerformanceStat GrabPower = new PerformanceStat();
|
||||
|
||||
// Seconds of each phase of a grab.
|
||||
[Inspectable, JsonProperty("extendTime"), Key(4), RuntimeInspectable]
|
||||
public PerformanceStat ExtendTime = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("envelopTime"), Key(5), RuntimeInspectable]
|
||||
public PerformanceStat EnvelopTime = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("pullTime"), Key(6), RuntimeInspectable]
|
||||
public PerformanceStat PullTime = new PerformanceStat();
|
||||
|
||||
// Spin-up and spin-down, in power per sim second.
|
||||
[Inspectable, JsonProperty("spinRate"), Key(7), RuntimeInspectable]
|
||||
public PerformanceStat SpinRate = new PerformanceStat();
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new Pickup(this, item);
|
||||
}
|
||||
|
||||
// A beam is a piece of gear the pilot holds on; no consumable carries one.
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item) =>
|
||||
throw new NotSupportedException("pickup: gear only");
|
||||
}
|
||||
|
||||
// Owns this ship's beam power and its one grab. Power is written only here; Zone owns the held item's pose.
|
||||
public class Pickup : Behavior, IAlwaysUpdatedBehavior
|
||||
{
|
||||
private readonly PickupData _data;
|
||||
// Power and the grab clock are kept in double so a fixed tick count lands on the same side of a boundary
|
||||
// whatever dt the zone steps by.
|
||||
private double _power;
|
||||
private bool _grabbing;
|
||||
private FloatingBodyId _target;
|
||||
private double _elapsed;
|
||||
// How many of Envelop and Pull have been published so far (0, 1 or 2).
|
||||
private int _published;
|
||||
|
||||
public Pickup(PickupData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
// The beam's spun-up state in [0, 1]: what the pilot's command has driven it to.
|
||||
public float Power => (float) _power;
|
||||
|
||||
public void Update(float dt)
|
||||
{
|
||||
var active = Item.Active.Value;
|
||||
var command = active ? Math.Clamp(Entity.TractorCommand, 0f, 1f) : 0f;
|
||||
var step = (double) Evaluate(_data.SpinRate) * dt;
|
||||
_power = Math.Clamp(_power + Math.Clamp(command - _power, -step, step), 0.0, 1.0);
|
||||
|
||||
var zone = Entity.Zone;
|
||||
var grabPower = Evaluate(_data.GrabPower);
|
||||
var extend = (double) Evaluate(_data.ExtendTime);
|
||||
var envelop = (double) Evaluate(_data.EnvelopTime);
|
||||
var pull = (double) Evaluate(_data.PullTime);
|
||||
var range = Evaluate(_data.Range);
|
||||
var radius = Evaluate(_data.BeamRadius);
|
||||
var origin = Entity.Position.xz;
|
||||
|
||||
if (!_grabbing)
|
||||
{
|
||||
if (!active || _power < grabPower) return;
|
||||
var item = Select(zone, origin, range, radius);
|
||||
if (item == null || !zone.TryHold(Entity, item.Id)) return;
|
||||
_grabbing = true;
|
||||
_target = item.Id;
|
||||
_elapsed = 0;
|
||||
_published = 0;
|
||||
Publish(GrabPhase.Started, item, 0);
|
||||
Publish(GrabPhase.Extend, item, (float) extend);
|
||||
return;
|
||||
}
|
||||
|
||||
var held = zone.FloatingItems.FirstOrDefault(f => f.Id.Equals(_target));
|
||||
if (held == null || !ReferenceEquals(held.Holder, Entity))
|
||||
{
|
||||
_grabbing = false;
|
||||
Entity.Capabilities.PublishGrab(new GrabEvent(_target, GrabPhase.Cancelled, float3(0), 0));
|
||||
return;
|
||||
}
|
||||
|
||||
var pulling = _elapsed >= extend + envelop;
|
||||
if (!active || _power < grabPower || (!pulling && !InBeam(held.Body.Position, origin, range, radius, out _)))
|
||||
{
|
||||
_grabbing = false;
|
||||
zone.Free(_target);
|
||||
Publish(GrabPhase.Cancelled, held, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
_elapsed += dt;
|
||||
if (_published < 1 && _elapsed >= extend) { _published = 1; Publish(GrabPhase.Envelop, held, (float) envelop); }
|
||||
if (_published < 2 && _elapsed >= extend + envelop) { _published = 2; Publish(GrabPhase.Pull, held, (float) pull); }
|
||||
if (_published == 2)
|
||||
zone.SetHeldProgress(_target, pull > 0 ? (float) ((_elapsed - extend - envelop) / pull) : 1f);
|
||||
if (_elapsed < extend + envelop + pull) return;
|
||||
|
||||
_grabbing = false;
|
||||
if (zone.TryPickUp(Entity, _target)) Publish(GrabPhase.Completed, held, 0);
|
||||
else
|
||||
{
|
||||
zone.Free(_target);
|
||||
Publish(GrabPhase.Cancelled, held, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// The one beam region: within Range along the aim axis (never behind) and BeamRadius off it. Selection claims
|
||||
// from it and the grab holds on to its item only while the item stays in it. A zero aim has no region.
|
||||
private bool InBeam(float2 position, float2 origin, float range, float radius, out float off)
|
||||
{
|
||||
off = 0;
|
||||
var aim = Entity.Aim.xz;
|
||||
if (lengthsq(aim) <= 0) return false;
|
||||
var axis = normalize(aim);
|
||||
var to = position - origin;
|
||||
var along = dot(to, axis);
|
||||
off = length(to - axis * along);
|
||||
return along >= 0 && along <= range && off <= radius;
|
||||
}
|
||||
|
||||
// The free item nearest the beam axis within the beam region that some cargo bay can store whole (the bay's own
|
||||
// TryFindSpace, the test TryStore opens with); ties go to the lowest id. A zero aim selects nothing.
|
||||
private FloatingItem Select(Zone zone, float2 origin, float range, float radius)
|
||||
{
|
||||
FloatingItem best = null;
|
||||
var bestOff = float.MaxValue;
|
||||
foreach (var floating in zone.FloatingItems)
|
||||
{
|
||||
if (floating.Holder != null) continue;
|
||||
if (!InBeam(floating.Body.Position, origin, range, radius, out var off)) continue;
|
||||
if (!Entity.CargoBays.Any(bay => bay.TryFindSpace(floating.Item))) continue;
|
||||
if (off < bestOff || (off == bestOff && floating.Id.Value < best.Id.Value))
|
||||
{
|
||||
best = floating;
|
||||
bestOff = off;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private void Publish(GrabPhase phase, FloatingItem item, float duration) =>
|
||||
Entity.Capabilities.PublishGrab(new GrabEvent(item.Id, phase, float3(item.Body.Position.x, DrawAhead.FloaterHeight(Entity.Zone, Entity.ItemManager.GameplaySettings, item.Body.Position, 0), item.Body.Position.y), duration));
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/Pickup.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/Pickup.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: ac7678d240564331be7486588d28c5ee
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -118,7 +118,7 @@ public class Radiator : Behavior, IAlwaysUpdatedBehavior, IInitializableBehavior
|
|||
Emissivity = Evaluate(_data.Emissivity);
|
||||
var rad = pow(RadiatorTemperature, ItemManager.GameplaySettings.HeatRadiationExponent) * ItemManager.GameplaySettings.HeatRadiationMultiplier * Emissivity;
|
||||
RadiatorTemperature -= rad * delta;
|
||||
Entity.VisibilitySources[this] = rad;
|
||||
Entity.SetSignature(this, SignatureChannel.Thermal, rad, Item);
|
||||
}
|
||||
|
||||
public void Initialize()
|
||||
|
|
|
|||
|
|
@ -94,8 +94,6 @@ public class Reactor : Behavior
|
|||
Draw = 0;
|
||||
}
|
||||
|
||||
Item.SetAudioParameter(SpecialAudioParameter.Intensity, max(.25f, 1 - 1 / CurrentLoadRatio));
|
||||
|
||||
AddHeat(heat);
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ public class Reflector : Behavior
|
|||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
Entity.VisibilitySources[this] = Evaluate(_data.CrossSection) * Entity.Zone.GetLight(Entity.Position.xz);
|
||||
Entity.SetSignature(this, SignatureChannel.Reflection, Evaluate(_data.CrossSection) * Entity.Zone.GetLight(Entity.Position.xz), Item);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
100
Assets/Scripts/ServerShared/Behaviors/Scanner.cs
Normal file
100
Assets/Scripts/ServerShared/Behaviors/Scanner.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/* 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 MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using static CultMath.math;
|
||||
|
||||
// Inspection (campaign aetheria-release, rulings quiet-gear-identifiable-hull-layout-known, scan-held-beam,
|
||||
// scan-is-an-act): a gear that, held on the ship's tracked target within Range for ScanTime, reveals everything fitted to
|
||||
// that target, quiet gear that never acts included. The scan is an emission like a lock: the target is painted and
|
||||
// third parties hear it at Range over the intercept factor.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class ScannerData : BehaviorData
|
||||
{
|
||||
// The planar distance to the target within which a scan builds.
|
||||
[Inspectable, JsonProperty("range"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Range = new PerformanceStat();
|
||||
|
||||
// Seconds a held scan takes to finish; a broken scan decays over the same span.
|
||||
[Inspectable, JsonProperty("scanTime"), Key(2), RuntimeInspectable]
|
||||
public PerformanceStat ScanTime = new PerformanceStat();
|
||||
|
||||
// The ratio of how far this scanner sees to how far others hear it (ruling sensor-stat-set); a design without it
|
||||
// reads as 1.
|
||||
[Inspectable, JsonProperty("interceptFactor"), Key(3)]
|
||||
public PerformanceStat InterceptFactor;
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new Scanner(this, item);
|
||||
}
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new Scanner(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class Scanner : Behavior, IProgressBehavior
|
||||
{
|
||||
private readonly ScannerData _data;
|
||||
private Entity _target;
|
||||
private float _built;
|
||||
private double _heldAt;
|
||||
|
||||
// The scan's progress now: what Execute last built, less ScanTime-relative decay over the time since a tick last held
|
||||
// it (ruling scan-held-beam: a broken scan decays over ScanTime, the item inactive or destroyed included). Derived from
|
||||
// the zone clock, never from tick order, so a scanner decays on the tick it breaks whether its host runs Execute
|
||||
// before the always-updated pass (EquippedItem) or after it (ConsumableItemEffect). The one decay site. It is the
|
||||
// progress against the ship's target now: a scan built on another ship reads 0 the moment the target changes, whether
|
||||
// or not the item is running to reset it.
|
||||
public float Progress => _target == Entity.Target.Value.Entity ? Remaining(_heldAt) : 0f;
|
||||
|
||||
public Scanner(ScannerData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
public Scanner(ScannerData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
private float Remaining(double since)
|
||||
{
|
||||
if (_built <= 0f) return 0f;
|
||||
var now = Entity.Zone?.ExactTime ?? since;
|
||||
return saturate(_built - (float) (now - since) / Evaluate(_data.ScanTime));
|
||||
}
|
||||
|
||||
// Runs only while the item is Active. The scan builds while the ship's own Target is a tracked ship within Range, and
|
||||
// is painted and emitted on every tick it builds; at 1 the target's fitted items enter the book and the scan starts over.
|
||||
// A tick that does not hold the scan builds nothing, and the zone clock carries its decay (Progress).
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
var target = Entity.Target.Value.Entity;
|
||||
if (_target != target)
|
||||
{
|
||||
_built = 0f;
|
||||
_target = target;
|
||||
}
|
||||
|
||||
var range = Evaluate(_data.Range);
|
||||
if (target != null && Entity.VisibleEntities.Contains(target) && Entity.TargetRange <= range)
|
||||
{
|
||||
// Decay over the ticks since the last held one, not counting this tick, which holds.
|
||||
var progress = saturate(Remaining(_heldAt + dt) + dt / Evaluate(_data.ScanTime));
|
||||
_built = progress;
|
||||
_heldAt = Entity.Zone?.ExactTime ?? _heldAt;
|
||||
target.ReceivePaint(Entity, Item, PaintMode.Scan, progress);
|
||||
Entity.Emit(Item, range / (_data.InterceptFactor == null ? 1f : Evaluate(_data.InterceptFactor)));
|
||||
if (progress >= 1f)
|
||||
{
|
||||
Entity.RecordInspection(target);
|
||||
_built = 0f;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/Scanner.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/Scanner.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: bf9e034c7a31410ea1c516f46b43825c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -24,8 +24,7 @@ public class SensorData : BehaviorData
|
|||
[Inspectable, JsonProperty("pingEnergy"), Key(6), RuntimeInspectable]
|
||||
public PerformanceStat PingEnergy;
|
||||
|
||||
[Inspectable, JsonProperty("pingVisibility"), Key(7), RuntimeInspectable]
|
||||
public PerformanceStat PingVisibility;
|
||||
// Key 7 (pingVisibility) is retired: never reuse it.
|
||||
|
||||
[Inspectable, JsonProperty("pingRange"), Key(8), RuntimeInspectable]
|
||||
public PerformanceStat PingRange;
|
||||
|
|
@ -38,6 +37,16 @@ public class SensorData : BehaviorData
|
|||
|
||||
[Inspectable, JsonProperty("pingRadiusExponent"), Key(11)]
|
||||
public float PingRadiusExponent = .5f;
|
||||
|
||||
// The width in degrees of the cone a ping sweeps, about the sensor's facing (ruling illuminator-beamforming:
|
||||
// how much a ping reveals is a stat). 360 or more is omnidirectional; a design without it reads as 360.
|
||||
[Inspectable, JsonProperty("beamWidth"), Key(12)]
|
||||
public PerformanceStat BeamWidth;
|
||||
|
||||
// The ratio of how far this sensor sees to how far others hear it (ruling sensor-stat-set); a design without it
|
||||
// reads as 1.
|
||||
[Inspectable, JsonProperty("interceptFactor"), Key(13)]
|
||||
public PerformanceStat InterceptFactor;
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
@ -61,7 +70,14 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
private float _pingLerp;
|
||||
private bool _pinging;
|
||||
private float _pingRadius;
|
||||
private HashSet<Entity> _pingedEntities = new HashSet<Entity>();
|
||||
|
||||
// The subjects this ping's wavefront has reached, in the beam or not; each is crossed at most once per ping.
|
||||
// Ping() is the one reset. A sweeping tick drops every subject no longer in the zone, so a subject that
|
||||
// leaves and comes back inside the front is reached again, as a ship arriving inside the front is.
|
||||
private readonly HashSet<Entity> _reached = new HashSet<Entity>();
|
||||
|
||||
// The zone the ping began in: a ping belongs to it, and ends when the pinger is anywhere else.
|
||||
private Zone _pingZone;
|
||||
|
||||
public float Cooldown
|
||||
{
|
||||
|
|
@ -73,6 +89,19 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
get => _pingRadius;
|
||||
}
|
||||
|
||||
public float BeamWidth => _data.BeamWidth == null ? 360f : Evaluate(_data.BeamWidth);
|
||||
|
||||
public float InterceptFactor => _data.InterceptFactor == null ? 1f : Evaluate(_data.InterceptFactor);
|
||||
|
||||
public float2 Facing => Direction.xz;
|
||||
|
||||
// Whether the offset `diff` (length `dist`) from this sensor lies inside its beam.
|
||||
private bool InBeam(float2 diff, float dist)
|
||||
{
|
||||
var beam = BeamWidth;
|
||||
return beam >= 360f || dot(Facing, diff) >= dist * cos(beam * .5f * .0174533f);
|
||||
}
|
||||
|
||||
public float PingBrightness => pow(1 - _pingLerp, _data.PingRadiusExponent);
|
||||
|
||||
public event Action OnPingStart;
|
||||
|
|
@ -114,12 +143,12 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
// nothing would ever fill this capacitor; bypass it rather than starving such an instance forever.
|
||||
if(_pingCooldown < 0 && (Item == null || _capacitor.TrySpend(_capacitor.Capacity)))
|
||||
{
|
||||
Entity.VisibilitySources[this] = Evaluate(_data.PingVisibility);
|
||||
_pinging = true;
|
||||
_pingZone = Entity.Zone;
|
||||
_pingCooldown = 1;
|
||||
_pingLerp = 0;
|
||||
_pingRadius = 0;
|
||||
_pingedEntities.Clear();
|
||||
_reached.Clear();
|
||||
OnPingStart?.Invoke();
|
||||
}
|
||||
}
|
||||
|
|
@ -140,15 +169,15 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
// instance never reaches PowerBus.Step (see Ping()) and so never accrues charge.
|
||||
if (Item != null)
|
||||
_capacitor.AddCharge(_capacitor.RequestedFill(dt) * Item.PowerSupply);
|
||||
if (_pinging && Entity.Zone != _pingZone) EndPing();
|
||||
var sweeping = _pinging;
|
||||
if (_pinging)
|
||||
{
|
||||
_pingLerp += dt / _data.PingDuration;
|
||||
_pingRadius = lerp(0, Evaluate(_data.PingRange), pow(_pingLerp, _data.PingRadiusExponent));
|
||||
if (_pingLerp > 1)
|
||||
{
|
||||
_pinging = false;
|
||||
OnPingEnd?.Invoke();
|
||||
}
|
||||
_reached.IntersectWith(Entity.Zone.Entities);
|
||||
Entity.Emit(Item, Evaluate(_data.PingRange) / InterceptFactor);
|
||||
if (_pingLerp > 1) EndPing();
|
||||
}
|
||||
|
||||
_pingCooldown -= dt / Evaluate(_data.PingCooldown);
|
||||
|
|
@ -160,17 +189,44 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
|
||||
var diff = entity.Position.xz - Entity.Position.xz;
|
||||
var dist = length(diff);
|
||||
var obscuration = Entity.Zone.Obscuration(Entity.Position.xz, entity.Position.xz);
|
||||
float previous, next;
|
||||
Entity.EntityInfoGathered.TryGetValue(entity, out previous);
|
||||
if (!_pingedEntities.Contains(entity) && dist < _pingRadius)
|
||||
|
||||
var sensitivity = Evaluate(_data.Sensitivity);
|
||||
var response = _data.PingBoost == null ? 0f : Evaluate(_data.PingBoost);
|
||||
var credit = 0f;
|
||||
var heard = false;
|
||||
|
||||
// The first sweeping tick this ping's wavefront is past the entity is its one crossing. Inside the beam
|
||||
// it paints the subject (it learns it is swept), credits this sensor, and is returned to every ally; an
|
||||
// ally hears it silently (ruling sensor-stat-set item 3): credit, no paint, no emission.
|
||||
if (sweeping && dist < _pingRadius && _reached.Add(entity) && InBeam(diff, dist))
|
||||
{
|
||||
_pingedEntities.Add(entity);
|
||||
next = saturate(previous + Gain(entity.Visibility, Evaluate(_data.Sensitivity), Evaluate(_data.PingBoost), dist, dt, true));
|
||||
heard = true;
|
||||
entity.ReceivePaint(Entity, Item, PaintMode.Search, 0);
|
||||
credit += Gain(entity.Visibility, sensitivity, response, dist, dt, true, obscuration);
|
||||
var pingReturn = new PingReturn(entity, dist, obscuration, Evaluate(_data.PingRange));
|
||||
foreach (var ally in Entity.Zone.Entities)
|
||||
if (ally != Entity && ally != entity && ally.Faction != null && ally.Faction == Entity.Faction && !ally.IsHostileTo(Entity))
|
||||
ally.ReceiveReturn(pingReturn);
|
||||
}
|
||||
|
||||
// An ally's ping returned off this subject (ruling ally-echo-bistatic-oval): heard while the
|
||||
// illuminated and received ranges sit inside the oval Rt x Rr < PingRange^2, credited at their geometric mean.
|
||||
foreach (var r in Entity.PingReturns)
|
||||
{
|
||||
if (r.Subject != entity || r.IlluminatedRange * dist >= r.MaxRange * r.MaxRange) continue;
|
||||
heard = true;
|
||||
credit += Gain(entity.Visibility, sensitivity, response, sqrt(r.IlluminatedRange * dist), dt, true, sqrt(r.IlluminatedObscuration * obscuration));
|
||||
}
|
||||
|
||||
if (heard)
|
||||
next = saturate(previous + credit);
|
||||
else
|
||||
{
|
||||
var angle = acos(dot(forward, normalize(diff)));
|
||||
next = saturate(previous + Gain(entity.Visibility, Evaluate(_data.Sensitivity), _data.SensitivityCurve.Evaluate(angle / PI), dist, dt, false));
|
||||
next = saturate(previous + Gain(entity.Visibility, sensitivity, _data.SensitivityCurve.Evaluate(angle / PI), dist, dt, false, obscuration));
|
||||
}
|
||||
next *= 1 - ItemManager.GameplaySettings.TargetInfoDecay * dt;
|
||||
//Context.Log($"{entity.Name} visibility {(int)(previous * 100)}% -> {(int)(next * 100)}%");
|
||||
|
|
@ -179,15 +235,23 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
return true;
|
||||
}
|
||||
|
||||
private void EndPing()
|
||||
{
|
||||
_pinging = false;
|
||||
OnPingEnd?.Invoke();
|
||||
}
|
||||
|
||||
// Mining Cut 3 (docs/mining-cut-refresh.md): the one detection gain rule -- the info one observation of a
|
||||
// target adds. A ping adds `visibility × sensitivity × PingBoost × distance` once; a passive tick adds
|
||||
// `visibility × sensitivity × curve(angle/π) × dt / distance`. `response` is PingBoost for a ping and the
|
||||
// sensitivity curve at the bearing for a passive tick. The entity loop above and the chunk query
|
||||
// (Entity.ChunkInfo, through PassiveRate) both call this; nothing else multiplies these terms.
|
||||
public static float Gain(float visibility, float sensitivity, float response, float distance, float dt, bool ping) =>
|
||||
ping
|
||||
// sensitivity curve at the bearing for a passive tick. `obscuration` is the fraction of the signal that
|
||||
// survives the vapour clouds on the sight line (Zone.Obscuration, 1f with none), scaling both. The entity
|
||||
// loop above and the chunk query (Entity.ChunkInfo, through PassiveRate) both call this; nothing else
|
||||
// multiplies these terms.
|
||||
public static float Gain(float visibility, float sensitivity, float response, float distance, float dt, bool ping, float obscuration) =>
|
||||
(ping
|
||||
? visibility * sensitivity * response * distance
|
||||
: visibility * sensitivity * response * dt / distance;
|
||||
: visibility * sensitivity * response * dt / distance) * obscuration;
|
||||
|
||||
// The passive gain per second this sensor draws from a target of `visibility` at the planar `position`:
|
||||
// Gain over one second, with the bearing measured from this sensor's own facing exactly as Execute does.
|
||||
|
|
@ -195,7 +259,8 @@ public class Sensor : Behavior, IEventBehavior, IPowerConsumer
|
|||
{
|
||||
var diff = position - Entity.Position.xz;
|
||||
var angle = acos(dot(Direction.xz, normalize(diff)));
|
||||
return Gain(visibility, Evaluate(_data.Sensitivity), _data.SensitivityCurve.Evaluate(angle / PI), length(diff), 1f, false);
|
||||
return Gain(visibility, Evaluate(_data.Sensitivity), _data.SensitivityCurve.Evaluate(angle / PI), length(diff), 1f, false,
|
||||
Entity.Zone.Obscuration(Entity.Position.xz, position));
|
||||
}
|
||||
|
||||
// An upper bound on sensitivity x response over every bearing, so PassiveRate(v, p) <= v x this / distance
|
||||
|
|
|
|||
|
|
@ -95,13 +95,13 @@ public class StatModifier : Behavior, IInitializableBehavior, IDisposable, IAlwa
|
|||
.Where(g => string.IsNullOrEmpty(data.RequireBehavior) ||
|
||||
entity.ItemManager.GetData(g.EquippableItem).Behaviors.Any(b => b.GetType().Name == data.RequireBehavior));
|
||||
return typeof(EquippableItemData).IsAssignableFrom(targetType)
|
||||
? gear.Where(g => entity.ItemManager.GetData(g.EquippableItem).GetType() == targetType)
|
||||
? gear.Where(g => targetType.IsAssignableFrom(entity.ItemManager.GetData(g.EquippableItem).GetType()))
|
||||
.Select(g => new Target(g, statField.GetValue(entity.ItemManager.GetData(g.EquippableItem)) as PerformanceStat))
|
||||
.Where(t => t.Stat != null)
|
||||
.ToArray()
|
||||
: gear.Where(g => entity.ItemManager.GetData(g.EquippableItem).Behaviors.Any(bd => bd.GetType() == targetType))
|
||||
: gear.Where(g => entity.ItemManager.GetData(g.EquippableItem).Behaviors.Any(bd => targetType.IsAssignableFrom(bd.GetType())))
|
||||
.SelectMany(g => entity.ItemManager.GetData(g.EquippableItem).Behaviors
|
||||
.Where(bd => bd.GetType() == targetType)
|
||||
.Where(bd => targetType.IsAssignableFrom(bd.GetType()))
|
||||
.Select(bd => new Target(g, statField.GetValue(bd) as PerformanceStat)))
|
||||
.Where(t => t.Stat != null)
|
||||
.ToArray();
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public class TargetingSystemData : BehaviorData
|
|||
|
||||
// Cut 6d (docs/fire-control-cut.md): grouping tightness, not a probability. FireControl.Sigma derives a
|
||||
// Gaussian kernel's sigma as 1/Precision, in hull-schematic cell units -- a higher number groups tighter
|
||||
// around whatever is aimed at (Entity.TargetItem's cells, or the hull's own centre of mass unaimed).
|
||||
// around whatever is aimed at (Entity.AimedAt: an item's cells or a mount's; the hull's own centre of mass unaimed).
|
||||
// Consumed by Cut 3's roll (folded into HitProbability as pOnHull) and by Commit's cell draw, both through
|
||||
// the one kernel function -- never re-derived separately.
|
||||
[Inspectable, JsonProperty("precision"), Key(3), RuntimeInspectable]
|
||||
|
|
|
|||
35
Assets/Scripts/ServerShared/Behaviors/ThrottleLock.cs
Normal file
35
Assets/Scripts/ServerShared/Behaviors/ThrottleLock.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
/* 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 MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
// Presence marks the lock: Entity.ThrottleLocked is true while an active effect carries one, and the thrust
|
||||
// allocator then bounds every forward-pushing column at full throttle from below in its solve. The behaviour
|
||||
// holds no state and does nothing itself; turning stays with the pilot.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class ThrottleLockData : BehaviorData
|
||||
{
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new ThrottleLock(this, item);
|
||||
}
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new ThrottleLock(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class ThrottleLock : Behavior
|
||||
{
|
||||
public ThrottleLock(ThrottleLockData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
}
|
||||
|
||||
public ThrottleLock(ThrottleLockData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
}
|
||||
|
||||
public override bool Execute(float dt) => true;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 558ff9ad01ba4fd4987d5e6ba4f31e4d
|
||||
|
|
@ -25,6 +25,11 @@ public class ThrusterData : BehaviorData
|
|||
|
||||
[Inspectable, CultInspectorAssetGuid, JsonProperty("Particles"), Key(5)]
|
||||
public string ParticlesPrefab;
|
||||
|
||||
// The gimbal's slew rate in degrees per second: the part's own stat, as a weapon's traverse is
|
||||
// (ruling mount-arc-gun-traverse). The swing limit is the hardpoint's FiringArc, the row its Row.
|
||||
[Inspectable, JsonProperty("slew"), Key(6), RuntimeInspectable]
|
||||
public PerformanceStat Slew = new PerformanceStat();
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
@ -37,12 +42,24 @@ public class ThrusterData : BehaviorData
|
|||
}
|
||||
}
|
||||
|
||||
public class Thruster : Behavior, IAnalogBehavior, IPowerConsumer
|
||||
public class Thruster : Behavior, IPowerConsumer
|
||||
{
|
||||
// Live: heat, quality, durability and power move this stat after construction, so it is read, never cached.
|
||||
public float Thrust => Evaluate(_data.Thrust);
|
||||
// Thrust at a full grant, the same stat read without the power-supply term: what a column promises. Live, like Thrust.
|
||||
public float NominalThrust => EvaluateNominalPower(_data.Thrust);
|
||||
public float Torque { get; }
|
||||
|
||||
// This thruster's effect per unit throttle at the given thrust, in the body frame: xy is the push (x starboard, y
|
||||
// forward), z the clockwise yaw rate in rad/s. Zero when the item is absent or offline. The one geometry owner for
|
||||
// the allocator and the envelope.
|
||||
public float3 Column(float thrust)
|
||||
{
|
||||
if (Item == null || !Item.Active.Value) return default;
|
||||
var push = -float2(0, 1).Rotate(Item.EquippableItem.Rotation) * thrust / Entity.Mass;
|
||||
return float3(push.x, push.y, Torque * thrust * ItemManager.GameplaySettings.TorqueMultiplier / Entity.Mass);
|
||||
}
|
||||
|
||||
public float Axis
|
||||
{
|
||||
get => _input;
|
||||
|
|
@ -84,53 +101,30 @@ public class Thruster : Behavior, IAnalogBehavior, IPowerConsumer
|
|||
// registered request field (StatValidation.PowerRequestFields) -- read nominally, same reasoning as every
|
||||
// other IPowerConsumer in this cut, though EnergyUsage carries no PowerSupply term in Thruster's own shipped
|
||||
// catalog today; Thrust (the field Cut 7 curves) is a separate stat Execute reads with the real Evaluate.
|
||||
public float PowerRequest(float dt) => _input > .01f ? _input * EvaluateNominalPower(_data.EnergyUsage) : 0f;
|
||||
public float PowerRequest(float dt) => _input > 0f ? _input * EvaluateNominalPower(_data.EnergyUsage) : 0f;
|
||||
|
||||
// Cut 5 (docs/stats-and-power-cut.md §1.3, PowerTiers.cs): Medium -- mobility. Losing thrust for a tick
|
||||
// under brownout is an inconvenience, not the cascading failure a starved radiator or shield causes.
|
||||
public int DefaultPowerTier => PowerTiers.Medium;
|
||||
|
||||
// What this thruster adds to the ship's manoeuvre envelope: Execute's own arithmetic at full input, read live.
|
||||
// Its push is Thrust / Mass along its mount, into the matching body
|
||||
// axis, even for a flank thruster that only turns (it pushes whenever it turns); its turn is |Torque| * Thrust *
|
||||
// TorqueMultiplier / Mass into the side its Torque sign fires on, when |Torque| clears the floor. Zero when the
|
||||
// item is offline or unpowered, the same gates Execute applies.
|
||||
public ManoeuvreEnvelope Manoeuvre()
|
||||
{
|
||||
if (Item == null || !Item.Active.Value || Item.PowerSupply <= 1e-4f) return default;
|
||||
var settings = ItemManager.GameplaySettings;
|
||||
var thrust = Thrust;
|
||||
var acceleration = thrust / Entity.Mass;
|
||||
var forward = normalize(Entity.Direction);
|
||||
var right = forward.Rotate(ItemRotation.Clockwise);
|
||||
var push = -forward.Rotate(Item.EquippableItem.Rotation);
|
||||
var along = dot(push, forward);
|
||||
var across = dot(push, right);
|
||||
var turn = abs(Torque) > settings.TorqueFloor ? abs(Torque) * thrust * settings.TorqueMultiplier / Entity.Mass : 0f;
|
||||
return new ManoeuvreEnvelope(
|
||||
max(along, 0f) * acceleration, max(-along, 0f) * acceleration,
|
||||
max(-across, 0f) * acceleration, max(across, 0f) * acceleration,
|
||||
Torque > 0f ? turn : 0f, Torque < 0f ? turn : 0f);
|
||||
}
|
||||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
Item.SetAudioParameter(SpecialAudioParameter.Intensity, _input);
|
||||
// Cut 7 (docs/stats-and-power-target.md): "continuous consumers brown out ... through a power supply
|
||||
// curve on their performance stats." Thrust below is a plain Evaluate() read, so once the catalog's own
|
||||
// Thrust stat carries a PowerSupply term, a partial grant already comes back reduced -- this gate no
|
||||
// longer demands a full grant, only that the thruster is being asked to do anything (_input) and that it
|
||||
// has not been cut to true zero supply (the epsilon PowerBus itself already treats as "nothing granted").
|
||||
if(_input > .01f && Item.PowerSupply > 1e-4f)
|
||||
if(_input > 0f && Item.PowerSupply > 1e-4f)
|
||||
{
|
||||
var thrust = Thrust;
|
||||
Entity.Velocity -= Direction.xz * _input * thrust / Entity.Mass * dt;
|
||||
Entity.Direction = mul(Entity.Direction,
|
||||
CultMath.float2x2.Rotate(_input * Torque * thrust * ItemManager.GameplaySettings.TorqueMultiplier / Entity.Mass * dt));
|
||||
var turnRate = _input * Torque * thrust * ItemManager.GameplaySettings.TorqueMultiplier / Entity.Mass;
|
||||
Entity.Direction = mul(Entity.Direction, CultMath.float2x2.Rotate(turnRate * dt));
|
||||
Entity.TurnRate += turnRate;
|
||||
AddHeat(_input * Evaluate(_data.Heat) * dt);
|
||||
var vis = _input * Evaluate(_data.Visibility);
|
||||
if (!Entity.VisibilitySources.ContainsKey(this) || vis > Entity.VisibilitySources[this])
|
||||
Entity.VisibilitySources[this] = vis;
|
||||
if (!Entity.VisibilitySources.TryGetValue(this, out var burn) || vis > burn.Strength)
|
||||
Entity.SetSignature(this, SignatureChannel.DrivePlume, vis, Item);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -64,13 +64,12 @@ public class TurretController : Behavior, IInitializableBehavior
|
|||
var diff = target.Position - Entity.Position;
|
||||
if (_predictShots)
|
||||
{
|
||||
var targetHullData = Entity.ItemManager.GetData(target.Hull) as HullData;
|
||||
var targetVelocity = float3(target.Velocity.x, 0, target.Velocity.y);
|
||||
var predictedPosition = first_order_intercept(
|
||||
Entity.Position, float3.zero, _shotSpeed,
|
||||
target.Position, targetVelocity
|
||||
);
|
||||
predictedPosition.y = Entity.Zone.GetHeight(predictedPosition.xz) + targetHullData.GridOffset;
|
||||
predictedPosition.y = target.RideHeight(predictedPosition.xz);
|
||||
Entity.Aim = normalize(predictedPosition - Entity.Position);
|
||||
}
|
||||
else
|
||||
|
|
|
|||
61
Assets/Scripts/ServerShared/Behaviors/VapourDump.cs
Normal file
61
Assets/Scripts/ServerShared/Behaviors/VapourDump.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
// A coolant dump that becomes a vapour cloud: the first time it runs it vents one cloud around its venter,
|
||||
// drifting with the venter's velocity. Radius, Opacity and Lifetime are evaluated through the host, so role
|
||||
// quality applies as for any other stat. Later runs vent nothing.
|
||||
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
|
||||
public class VapourDumpData : BehaviorData
|
||||
{
|
||||
[Inspectable, JsonProperty("radius"), Key(1), RuntimeInspectable]
|
||||
public PerformanceStat Radius = new PerformanceStat();
|
||||
|
||||
// How much of a sight line's signal a fresh cloud removes, in [0, 1].
|
||||
[Inspectable, JsonProperty("opacity"), Key(2), RuntimeInspectable]
|
||||
public PerformanceStat Opacity = new PerformanceStat();
|
||||
|
||||
// Seconds from venting until the cloud has faded away and is removed.
|
||||
[Inspectable, JsonProperty("lifetime"), Key(3), RuntimeInspectable]
|
||||
public PerformanceStat Lifetime = new PerformanceStat();
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
return new VapourDump(this, item);
|
||||
}
|
||||
|
||||
public override Behavior CreateInstance(ConsumableItemEffect item)
|
||||
{
|
||||
return new VapourDump(this, item);
|
||||
}
|
||||
}
|
||||
|
||||
public class VapourDump : Behavior
|
||||
{
|
||||
private VapourDumpData _data;
|
||||
private bool _vented;
|
||||
|
||||
public VapourDump(VapourDumpData data, EquippedItem item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public VapourDump(VapourDumpData data, ConsumableItemEffect item) : base(data, item)
|
||||
{
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
if (_vented) return true;
|
||||
_vented = true;
|
||||
Entity.Zone.Vent(new VapourCloud
|
||||
{
|
||||
Body = new KinematicBody { Position = Entity.Position.xz, Velocity = Entity.Velocity },
|
||||
Radius = Evaluate(_data.Radius),
|
||||
Opacity = Evaluate(_data.Opacity),
|
||||
Lifetime = Evaluate(_data.Lifetime),
|
||||
Venter = Entity
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Behaviors/VapourDump.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Behaviors/VapourDump.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 961a74683c574807a300eb26694f206d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -15,6 +15,9 @@ public class VisibilityData : BehaviorData
|
|||
|
||||
[Inspectable, JsonProperty("visibilityDecay"), Key(2)]
|
||||
public PerformanceStat VisibilityDecay = new PerformanceStat();
|
||||
|
||||
[Inspectable, JsonProperty("channel"), Key(3)]
|
||||
public SignatureChannel Channel = SignatureChannel.Thermal;
|
||||
|
||||
public override Behavior CreateInstance(EquippedItem item)
|
||||
{
|
||||
|
|
@ -41,7 +44,7 @@ public class Visibility : Behavior
|
|||
|
||||
public override bool Execute(float dt)
|
||||
{
|
||||
Entity.VisibilitySources[this] = Evaluate(_data.Visibility);
|
||||
Entity.SetSignature(this, _data.Channel, Evaluate(_data.Visibility), Item);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -37,8 +37,16 @@ public abstract class WeaponData : BehaviorData
|
|||
[Inspectable, JsonProperty("range"), Key(6)]
|
||||
public PerformanceStat Range = new PerformanceStat();
|
||||
|
||||
[InspectableAnimationCurve, JsonProperty("damageCurve"), Key(7)]
|
||||
public BezierCurve DamageCurve;
|
||||
// Key 7 was the damage curve, retired and never reused.
|
||||
|
||||
// The range up to which a round does its full damage; from here to Range damage lerps to DamageAtMaxRange. Unauthored
|
||||
// is no falloff (Tracking's precedent): +infinity clamps to Range in RangeFactor.
|
||||
[Inspectable, JsonProperty("effectiveRange"), Key(35)]
|
||||
public PerformanceStat EffectiveRange = new PerformanceStat { Min = float.PositiveInfinity, Max = float.PositiveInfinity };
|
||||
|
||||
// The multiplier on damage at Range, the end of the lerp (0 is nothing arriving at maximum range).
|
||||
[Inspectable, JsonProperty("damageAtMaxRange"), Key(36)]
|
||||
public float DamageAtMaxRange;
|
||||
|
||||
[Inspectable, CultInspectorAssetGuid, JsonProperty("effect"), Key(8)]
|
||||
public string EffectPrefab;
|
||||
|
|
@ -71,6 +79,25 @@ public abstract class WeaponData : BehaviorData
|
|||
// weapon-tracking-authored). Unauthored is a mount that follows anything: FireControl.PMount reads +infinity as 1.
|
||||
[Inspectable, JsonProperty("tracking"), Key(33), RuntimeInspectable]
|
||||
public PerformanceStat Tracking = new PerformanceStat { Min = float.PositiveInfinity, Max = float.PositiveInfinity };
|
||||
|
||||
// What an observer who believes this is the design measures it by (aetheria-ew, ew-claim-weapon-measure-ruled): the
|
||||
// design's rated figures, each stat's Max (what a stat with no terms resolves to), through the same formula the
|
||||
// live weapon's RangeDamagePerSecond runs over its evaluated stats. Never the carrier's quality, heat, wear or power.
|
||||
public abstract float RatedRangeDamagePerSecond(float range);
|
||||
public float RatedRangeFactor(float at) => RangeFactor(MinRange.Max, EffectiveRange.Max, Range.Max, DamageAtMaxRange, at);
|
||||
|
||||
// The one function of how much of a weapon's damage arrives at a planar range: 0 outside [min, max] (inclusive, as
|
||||
// FireControl.Designated), 1 up to the effective range, then one lerp to damageAtMax at max. An effective range outside
|
||||
// [min, max] clamps into it.
|
||||
public static float RangeFactor(float min, float effective, float max, float damageAtMax, float at)
|
||||
{
|
||||
if (at < min || at > max) return 0f;
|
||||
var e = clamp(effective, min, max);
|
||||
return e >= max ? 1f : lerp(1f, damageAtMax, saturate(unlerp(e, max, at)));
|
||||
}
|
||||
|
||||
[IgnoreMember]
|
||||
public float RatedRange => Range.Max;
|
||||
}
|
||||
|
||||
public abstract class Weapon : Behavior, IActivatedBehavior
|
||||
|
|
@ -81,11 +108,13 @@ public abstract class Weapon : Behavior, IActivatedBehavior
|
|||
public abstract float RangeDamagePerSecond(float range);
|
||||
public abstract int Ammo { get; }
|
||||
public WeaponData WeaponData => _data;
|
||||
public float RangeFactor(float at) => WeaponData.RangeFactor(MinRange, EffectiveRange, Range, _data.DamageAtMaxRange, at);
|
||||
|
||||
public float Damage { get; protected set; }
|
||||
public float Penetration { get; protected set; }
|
||||
public float DamageSpread { get; protected set; }
|
||||
public float MinRange { get; protected set; }
|
||||
public float EffectiveRange { get; protected set; }
|
||||
public float Range { get; protected set; }
|
||||
public float Energy { get; protected set; }
|
||||
public float Heat { get; protected set; }
|
||||
|
|
@ -112,14 +141,10 @@ public abstract class Weapon : Behavior, IActivatedBehavior
|
|||
// so a weapon is never safed against one.
|
||||
public bool StanceAllowsFire => Entity.Target.Value.Entity == null || Entity.IsHostileTo(Entity.Target.Value.Entity);
|
||||
|
||||
// Cut 3 (docs/fire-control-cut.md, Q2): player fire is arc-gated like everyone else's. This is the same
|
||||
// predicate (FireControl.InArc) Combat.cs and TurretController.cs gate AI and turret fire with, read at
|
||||
// the one point every shooter's trigger passes through (InstantWeapon.Trigger) -- not a parallel check, and
|
||||
// not the AI's own AgentMinHitProbability heuristic, which is a "worth it" decision layered above this
|
||||
// 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.
|
||||
// FireControl owns the gate, including its one exemption: a fused weapon fires out of arc.
|
||||
// The trigger gate for player and AI shooters alike, read at the one point every shooter's trigger passes
|
||||
// through (InstantWeapon.Trigger). A gun fires on its solution (FireControl.Solution) without the aim, else
|
||||
// along the aim when the aim is inside its arc, else it holds. An AI shooter's aim is its intercept, so its
|
||||
// fire is unchanged. FireControl owns the gate, including its exemption: a fused weapon fires out of arc.
|
||||
public bool ArcAllowsFire => FireControl.ArcPermitsFire(this, Entity);
|
||||
|
||||
public Weapon(WeaponData data, EquippedItem item) : base(data, item)
|
||||
|
|
@ -138,6 +163,7 @@ public abstract class Weapon : Behavior, IActivatedBehavior
|
|||
Penetration = Evaluate(_data.Penetration);
|
||||
DamageSpread = Evaluate(_data.DamageSpread);
|
||||
MinRange = Evaluate(_data.MinRange);
|
||||
EffectiveRange = Evaluate(_data.EffectiveRange);
|
||||
Range = Evaluate(_data.Range);
|
||||
Energy = Evaluate(_data.Energy);
|
||||
Heat = Evaluate(_data.Heat);
|
||||
|
|
|
|||
|
|
@ -7,30 +7,35 @@ using UniRx;
|
|||
using CultMath;
|
||||
|
||||
// Capability event contract (docs/headless-playground-cut.md fork L, operator ruling 2026-09-17):
|
||||
// pickup, impact absorption, melee blade and propulsion are separate item capabilities. Simulation
|
||||
// (not yet built -- this file only stands up the wire shape) will own each capability's rules and
|
||||
// emit these events; any number of presentations (the field shield today, later an IFS shatter
|
||||
// plane or an advected particle field) subscribe to the event kinds they visualize and decide
|
||||
// nothing about the rule. This file has no engine dependency: it compiles into the headless
|
||||
// Aetheria.Shared build (see Aetheria.Shared.csproj) with no publisher wired up yet.
|
||||
// pickup, impact absorption, melee blade and propulsion are separate item capabilities. Simulation owns
|
||||
// each capability's rules and emits these events (FireControl publishes Absorb; the others are not yet
|
||||
// built); any number of presentations (the field shield today, later an IFS shatter plane or an advected
|
||||
// particle field) subscribe to the event kinds they visualize and decide nothing about the rule. This file
|
||||
// has no engine dependency: it compiles into the headless Aetheria.Shared build (see Aetheria.Shared.csproj).
|
||||
|
||||
// One absorbed impact: a hit landing on the item's shield/armor capability. DamageType rides along
|
||||
// so presenters can vary visuals per type; the damage-type mask itself belongs to the absorb
|
||||
// capability's own data and is out of scope for this cut (operator, 2026-09-17) -- this struct only
|
||||
// carries the hit's existing type through, unfiltered.
|
||||
// Which layer of the receiver took an absorbed impact.
|
||||
public enum AbsorbLayer { Shield, Hull }
|
||||
|
||||
// One absorbed impact on a shield or a hull, published once per receiver by FireControl on that entity's
|
||||
// Entity.Capabilities. Position is a world point on the receiver's sim pose at the tick the impact lands (a
|
||||
// presenter draws it with DrawAhead.Carried); Direction is the way the impact travels. DamageType rides along
|
||||
// so presenters can vary visuals per type; the damage-type mask itself belongs to the absorb capability's own
|
||||
// data and is out of scope (operator, 2026-09-17) -- this struct only carries the hit's existing type through.
|
||||
public readonly struct AbsorbEvent
|
||||
{
|
||||
public readonly float3 Position;
|
||||
public readonly float3 Direction;
|
||||
public readonly float Magnitude;
|
||||
public readonly DamageType DamageType;
|
||||
public readonly AbsorbLayer Layer;
|
||||
|
||||
public AbsorbEvent(float3 position, float3 direction, float magnitude, DamageType damageType)
|
||||
public AbsorbEvent(float3 position, float3 direction, float magnitude, DamageType damageType, AbsorbLayer layer)
|
||||
{
|
||||
Position = position;
|
||||
Direction = direction;
|
||||
Magnitude = magnitude;
|
||||
DamageType = damageType;
|
||||
Layer = layer;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -47,19 +52,18 @@ public enum GrabPhase
|
|||
Cancelled
|
||||
}
|
||||
|
||||
// The target is identified by a plain handle, not a Unity type: the simulation will own the real
|
||||
// target identity (a loot drop or item instance id) once the pickup capability exists. Today's only
|
||||
// publisher (the FieldShieldTest scene) hands out its own handles; nothing here interprets them.
|
||||
// One phase of a grab. The target is the floating item the Pickup behaviour holds (the FieldShieldTest scene
|
||||
// publishes its own handles as ids); nothing here interprets it.
|
||||
public readonly struct GrabEvent
|
||||
{
|
||||
public readonly int TargetHandle;
|
||||
public readonly FloatingBodyId Target;
|
||||
public readonly GrabPhase Phase;
|
||||
public readonly float3 TargetPosition;
|
||||
public readonly float PhaseDuration;
|
||||
|
||||
public GrabEvent(int targetHandle, GrabPhase phase, float3 targetPosition, float phaseDuration)
|
||||
public GrabEvent(FloatingBodyId target, GrabPhase phase, float3 targetPosition, float phaseDuration)
|
||||
{
|
||||
TargetHandle = targetHandle;
|
||||
Target = target;
|
||||
Phase = phase;
|
||||
TargetPosition = targetPosition;
|
||||
PhaseDuration = phaseDuration;
|
||||
|
|
@ -101,10 +105,10 @@ public readonly struct ThrustEvent
|
|||
}
|
||||
}
|
||||
|
||||
// Per-entity (or per-item) source of capability events. One instance is owned by whatever will
|
||||
// eventually decide these rules; today the FieldShieldTest scene stands in for that owner. Follows
|
||||
// the Subject<T>-per-event-kind idiom already used on Entity (IncomingHit, HullDamage, etc): each
|
||||
// event kind gets its own stream, and a subscriber to one kind never sees another.
|
||||
// Per-entity source of capability events: one instance per Entity (Entity.Capabilities), published by
|
||||
// FireControl for Absorb; the FieldShieldTest scene keeps its own instance. Follows the Subject<T>-per-event-kind
|
||||
// idiom already used on Entity (IncomingHit, HullDamage, etc): each event kind gets its own stream, and a
|
||||
// subscriber to one kind never sees another.
|
||||
public class CapabilityEvents
|
||||
{
|
||||
private readonly Subject<AbsorbEvent> _absorb = new Subject<AbsorbEvent>();
|
||||
|
|
|
|||
68
Assets/Scripts/ServerShared/Contacts.cs
Normal file
68
Assets/Scripts/ServerShared/Contacts.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/* 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.Linq;
|
||||
using CultMath;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
|
||||
// A ship touching a ship (aetheria-release cut sim-contact; ruling unity-presents-only-r3): the simulation owns
|
||||
// contact between ships. Orbital entities (stations, turrets) sit on the orbital layer above the ship plane and floaters
|
||||
// below it, so neither touches a ship (ruling aetheria-gravity:orbitals-above-floaters-below). Each hull is a disc about its centre of mass that bounds every occupied cell, and
|
||||
// two discs that touch while closing along the line between their centres take the normal impulse
|
||||
// j = -(1 + e)(v_rel . n) / (1/m1 + 1/m2) (ruling ship-bounce-restitution-setting): momentum is conserved, the
|
||||
// result is frame-independent, and a pair that has separated is not bounced again. e is
|
||||
// GameplaySettings.ContactRestitution.
|
||||
// Presentations read Zone.Contacted; no Unity collision callback writes an Entity.
|
||||
public readonly struct ContactEvent
|
||||
{
|
||||
public readonly Entity A;
|
||||
public readonly Entity B;
|
||||
public readonly float2 Point;
|
||||
// Unit vector from A to B.
|
||||
public readonly float2 Normal;
|
||||
|
||||
public ContactEvent(Entity a, Entity b, float2 point, float2 normal)
|
||||
{
|
||||
A = a;
|
||||
B = b;
|
||||
Point = point;
|
||||
Normal = normal;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Contacts
|
||||
{
|
||||
public static float Radius(Entity e) => e.HullData.Reach(e.ItemManager.GameplaySettings.SchematicCellSize);
|
||||
|
||||
// For each unordered pair of the zone's ships, in list order: if their discs touch and are closing along
|
||||
// the normal, the impulse moves each one's velocity along the normal only (the tangent components are
|
||||
// untouched), and the contact is published. Pairs resolve one after another in list order, each from the
|
||||
// velocities the earlier pairs left, so a body touching two others in one tick depends on that order; the
|
||||
// total momentum does not. A docked entity (it has a Parent and takes its parent's pose) and an inactive one
|
||||
// are not hulls in the zone. No positional push-out.
|
||||
public static void Step(Zone zone)
|
||||
{
|
||||
var entities = zone.Entities.OfType<Ship>().Where(e => e.Active && e.Parent == null).ToArray();
|
||||
var radii = entities.Select(Radius).ToArray();
|
||||
for (var i = 0; i < entities.Length; i++)
|
||||
for (var j = i + 1; j < entities.Length; j++)
|
||||
{
|
||||
var a = entities[i];
|
||||
var b = entities[j];
|
||||
var offset = b.Position.xz - a.Position.xz;
|
||||
var distance = length(offset);
|
||||
// Coincident centres have no normal.
|
||||
if (distance <= 0f || distance >= radii[i] + radii[j]) continue;
|
||||
var n = offset / distance;
|
||||
var closing = dot(n, b.Velocity - a.Velocity);
|
||||
if (closing >= 0f) continue;
|
||||
|
||||
var impulse = -(1f + a.ItemManager.GameplaySettings.ContactRestitution) * closing / (1f / a.Mass + 1f / b.Mass);
|
||||
a.Velocity -= n * (impulse / a.Mass);
|
||||
b.Velocity += n * (impulse / b.Mass);
|
||||
zone.Contacted.OnNext(new ContactEvent(a, b, a.Position.xz + n * radii[i], n));
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Contacts.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Contacts.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7c1e5a3b9d4f4e2a8b6c0d1f2e3a4b5c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
162
Assets/Scripts/ServerShared/DrawAhead.cs
Normal file
162
Assets/Scripts/ServerShared/DrawAhead.cs
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
/* 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 CultMath;
|
||||
using GameCult.Caching;
|
||||
using static CultMath.math;
|
||||
|
||||
// Pure presentation statics over sim state, never called by ServerShared, with no state of their own: the sim owns every
|
||||
// pose and no presenter stores one, a previous state or a velocity of its own.
|
||||
// The rule: a presenter draws every moving thing at the drawn time T = Zone.ExactTime + Clock.Lead. A pose the sim defines
|
||||
// in closed form of time (an orbit, a belt chunk, a well, the field's height, the flow scroll) is that function evaluated
|
||||
// at T; a pose the sim integrates (a ship, a kinematic body) is its last step plus its step velocity times Lead; a child
|
||||
// is drawn where its parent is. DrawAhead.Time is the one definition of T. Ships ride the field at that drawn xz and T (a
|
||||
// ship's height is the field's there, not the last step's). A ballistic round's flight is presentation
|
||||
// (ruling projectile-flight-is-presentation), drawn from the sim's facts: its frozen line, the published outcome, the
|
||||
// commit tick, the impact cell on the target's drawn pose, the burst point.
|
||||
public static class DrawAhead
|
||||
{
|
||||
// The drawn time: the one definition of T.
|
||||
public static double Time(Zone zone, float lead) => zone.ExactTime + lead;
|
||||
|
||||
// An orbit's node at the drawn time: the rail law at T, not the step's memo.
|
||||
public static float2 Orbit(Zone zone, CultRecordKey orbit, float lead) => zone.OrbitPositionAt(orbit, Time(zone, lead));
|
||||
|
||||
// The field's height at a point at the drawn time, its wells where their rails put them at T.
|
||||
public static float Height(Zone zone, float2 planar, float lead) => zone.GetHeight(planar, Time(zone, lead));
|
||||
|
||||
// The drawn height of a floater (loot, mines): the field at the drawn time plus the floater layer.
|
||||
public static float FloaterHeight(Zone zone, GameplaySettings settings, float2 planar, float lead) => Height(zone, planar, lead) + settings.FloaterLayerHeight;
|
||||
|
||||
// A ship in a wormhole animation has its pose scripted by the step, not integrated from Velocity and TurnRate,
|
||||
// so it is drawn where the step put it: extrapolating a scripted pose draws a streak that resets every step.
|
||||
// A child is drawn where its parent is drawn, as the step copies the parent's pose onto it.
|
||||
public static float3 Position(Entity entity, float lead)
|
||||
{
|
||||
if (entity is Ship { WormholeAnimationInProgress: true }) return entity.Position;
|
||||
if (entity.Parent != null) return Position(entity.Parent, lead);
|
||||
// A body on a rail (a station) is on its orbit at T: the rail is closed form, not integrated.
|
||||
var planar = entity is OrbitalEntity { OrbitData: var orbit } && orbit.IsSet()
|
||||
? Orbit(entity.Zone, orbit, lead)
|
||||
: entity.Position.xz + entity.Velocity * lead;
|
||||
return float3(planar.x, entity.RideHeight(planar, Time(entity.Zone, lead)), planar.y);
|
||||
}
|
||||
|
||||
// The point `distance` out along a planar bearing from the ship's drawn position: where the HUD anchors a marker to the
|
||||
// ship the camera follows (an incoming lock, a remembered contact, a ping's flash).
|
||||
public static float3 AtBearing(Entity origin, float2 bearing, float distance, float lead)
|
||||
{
|
||||
var at = Position(origin, lead);
|
||||
return float3(at.x + bearing.x * distance, at.y, at.z + bearing.y * distance);
|
||||
}
|
||||
|
||||
// One well as the shader takes it: its body's rail at the drawn time, with the strength, core and reference the sim's
|
||||
// GetHeight sums with. GravityLowering copies it into the shader's record and decides nothing.
|
||||
public readonly struct DrawnWell
|
||||
{
|
||||
public readonly float2 Position;
|
||||
public readonly float Strength, CoreRadius, Reference;
|
||||
public DrawnWell(float2 position, float strength, float coreRadius, float reference)
|
||||
{
|
||||
Position = position;
|
||||
Strength = strength;
|
||||
CoreRadius = coreRadius;
|
||||
Reference = reference;
|
||||
}
|
||||
}
|
||||
|
||||
public static DrawnWell Well(Zone zone, Planet body, float lead) =>
|
||||
new DrawnWell(Orbit(zone, body.BodyData.Orbit.Key, lead), body.WellStrength, body.RocheLimit, zone.WellReference(body));
|
||||
|
||||
// A free body (a vapour cloud) drawn where the frame falls lead sim seconds after the last step, by the velocity
|
||||
// that step moved it with: the launch velocity and the drift together.
|
||||
public static float2 Position(KinematicBody body, float lead) => body.Position + body.TotalVelocity * lead;
|
||||
|
||||
// The ship's rotation turned about its own up axis by the rate its last step turned, for lead seconds.
|
||||
public static quaternion Rotation(Ship ship, float lead) =>
|
||||
ship.WormholeAnimationInProgress ? ship.Rotation : Turned(ship.Rotation, ship.TurnRate * lead);
|
||||
|
||||
// q turned about its own up axis by the angle, in the sense Direction turns for a positive TurnRate.
|
||||
public static quaternion Turned(quaternion q, float angle)
|
||||
{
|
||||
var u = float3(q.x, q.y, q.z);
|
||||
var up = float3(0, 1, 0);
|
||||
up += 2 * (q.w * cross(u, up) + cross(u, cross(u, up)));
|
||||
var half = angle * .5f;
|
||||
var s = sin(half);
|
||||
var t = new quaternion(up.x * s, up.y * s, up.z * s, cos(half));
|
||||
// Hamilton product t * q: CultMath carries no quaternion product (a gap in CultMath, not filled here).
|
||||
return normalize(new quaternion(
|
||||
t.w * q.x + t.x * q.w + t.y * q.z - t.z * q.y,
|
||||
t.w * q.y - t.x * q.z + t.y * q.w + t.z * q.x,
|
||||
t.w * q.z + t.x * q.y - t.y * q.x + t.z * q.w,
|
||||
t.w * q.w - t.x * q.x - t.y * q.y - t.z * q.z));
|
||||
}
|
||||
|
||||
// A ballistic round at the drawn time (DrawAhead.Time, passed in by the caller; the target's lead is that time less its zone's step time, derived here, never a second input): on its frozen line while the outcome is unknown or a
|
||||
// miss, with the barrel's offset from that line decaying to nothing over blendTime sim seconds from the moment of firing.
|
||||
// A round the sim published as a hit or burst steers from its line, from the commit tick, onto where it ends by the
|
||||
// time damage lands: a burst's frozen point, else the impact cell on the target's drawn pose; and is held there after.
|
||||
public static float3 Round(in PendingShot shot, ShotOutcome known, float3 barrel, float blendTime, double drawnTime)
|
||||
{
|
||||
var time = (float) drawnTime;
|
||||
var drawn = Lifted(shot, Line(shot, known?.Result, time), barrel, blendTime, time);
|
||||
if (known == null || known.Result == ShotResult.Miss) return drawn;
|
||||
var end = known.HasBurstPoint
|
||||
? float3(known.BurstPoint.x, shot.FireOrigin.y, known.BurstPoint.y)
|
||||
: Impact(known.Target, known.Cell, (float) (drawnTime - known.Target.Zone.ExactTime));
|
||||
var commit = shot.ArrivalTime - known.ArrivalIn;
|
||||
var steer = shot.ArrivalTime > commit ? saturate((time - commit) / (shot.ArrivalTime - commit)) : 1f;
|
||||
return drawn + (end - drawn) * steer;
|
||||
}
|
||||
|
||||
// The impact cell's centre on the target's drawn pose.
|
||||
public static float3 Impact(Entity target, int2 cell, float lead)
|
||||
{
|
||||
var world = target.ToWorldPoint((float2) cell);
|
||||
return Carried(target, float3(world.x, target.Position.y, world.y), lead);
|
||||
}
|
||||
|
||||
// A world point on the target's sim pose, moved and turned with the target for lead seconds exactly as Position and
|
||||
// Rotation draw the entity: the one owner of where a point on a hull is drawn, for the drawn round's end and for
|
||||
// impact presenters.
|
||||
public static float3 Carried(Entity target, float3 simPoint, float lead)
|
||||
{
|
||||
var at = Position(target, lead);
|
||||
var offset = float2(simPoint.x - target.Position.x, simPoint.z - target.Position.z);
|
||||
var turned = mul(offset, CultMath.float2x2.Rotate(Turn(target, lead)));
|
||||
return float3(at.x + turned.x, at.y + (simPoint.y - target.Position.y), at.z + turned.y);
|
||||
}
|
||||
|
||||
// Whether the drawn flight is over by time: only a published miss ends by the clock. A hit or burst ends on ShotResolved.
|
||||
public static bool RoundOver(in PendingShot shot, ShotOutcome known, double drawnTime) =>
|
||||
known != null && known.Result == ShotResult.Miss && (float) drawnTime >= RoundEnd(shot, ShotResult.Miss);
|
||||
|
||||
// The sim time a round's drawn line ends, for what is known of its outcome. A round that hit or burst (or whose outcome
|
||||
// is not yet published) ends at its ArrivalTime; a round the sim has published as a Miss flies on to the weapon's frozen
|
||||
// range and never ends short of its own arrival (a direct round's FireRange is measured to any target, in range or not).
|
||||
public static float RoundEnd(in PendingShot shot, ShotResult? known) =>
|
||||
known == ShotResult.Miss
|
||||
? max(shot.ArrivalTime, shot.FireTime + (shot.Speed > .01f ? shot.MaxRange / shot.Speed : 0f))
|
||||
: shot.ArrivalTime;
|
||||
|
||||
// The frozen line a round follows until it steers: from its frozen origin along its frozen direction at its frozen
|
||||
// speed, held at RoundEnd once it has flown that far. With no outcome known the round is drawn no further than its
|
||||
// arrival point and waits there for the sim to publish one.
|
||||
private static float2 Line(in PendingShot shot, ShotResult? known, float time)
|
||||
{
|
||||
if (shot.Speed <= .01f) return shot.FireOrigin.xz;
|
||||
var flown = clamp(time - shot.FireTime, 0f, RoundEnd(shot, known) - shot.FireTime);
|
||||
return shot.FireOrigin.xz + shot.TravelDirection * (shot.Speed * flown);
|
||||
}
|
||||
|
||||
private static float Turn(Entity entity, float lead) =>
|
||||
entity is Ship { WormholeAnimationInProgress: true } ? 0f : entity.TurnRate * lead;
|
||||
|
||||
private static float3 Lifted(in PendingShot shot, float2 planar, float3 barrel, float blendTime, float time)
|
||||
{
|
||||
var blend = blendTime > 0 ? saturate(1 - (time - shot.FireTime) / blendTime) : 0f;
|
||||
return float3(planar.x, shot.FireOrigin.y, planar.y) + (barrel - shot.FireOrigin) * blend;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/DrawAhead.cs.meta
Normal file
11
Assets/Scripts/ServerShared/DrawAhead.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 007fe4255cd84c26a010151a399f45c2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -5,6 +5,7 @@
|
|||
using GameCult.Caching;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
using UniRx;
|
||||
|
|
@ -14,14 +15,23 @@ using int2 = CultMath.int2;
|
|||
|
||||
public abstract class Entity
|
||||
{
|
||||
// Every hull cell's temperature (kelvin) when the entity is built.
|
||||
public const float StartingCellTemperature = 280;
|
||||
|
||||
public Zone Zone;
|
||||
public Faction Faction;
|
||||
// The mark of a zone's boss, written only by ZoneGenerator and restored from the pack. RunGoal reads it.
|
||||
public bool IsBoss;
|
||||
public EquippableItem Hull;
|
||||
public EquippedItem EquippedHull;
|
||||
|
||||
public float3 Position;
|
||||
public float2 Direction = float2(0,1);
|
||||
public float2 Velocity;
|
||||
// Rad per sim second, signed as the step turns Direction: the sum of this step's rotation actuators' applied
|
||||
// angle over the step. Runtime only, zeroed at the start of Update, so a staged, loaded or wormhole write to
|
||||
// Direction is never a turn. Read only by presenters that draw ahead of the step.
|
||||
public float TurnRate;
|
||||
|
||||
// Runtime only, never saved; Entity.Update is the one writer of both. Acceleration is the planar velocity change
|
||||
// across the base update over its delta (thrust, not the drag or gravity a subclass applies before calling it),
|
||||
|
|
@ -59,24 +69,67 @@ public abstract class Entity
|
|||
private readonly ReactiveProperty<TargetRef> _target = new ReactiveProperty<TargetRef>(TargetRef.None);
|
||||
public IReadOnlyReactiveProperty<TargetRef> Target => _target;
|
||||
|
||||
// Cut 2 (docs/fire-control-cut.md): the stored aim-point slot. Written only by TrySelectTargetItem
|
||||
// below, and nulled whenever Target changes (subscribed in Activate). Do not read this field directly
|
||||
// outside Entity -- read ResolvedTargetItem, which re-validates on every call, so decay (or the item
|
||||
// leaving the target) drops the aim point the moment it is no longer earned, with no loop that has to
|
||||
// notice and clear it.
|
||||
public ReactiveProperty<EquippedItem> TargetItem = new ReactiveProperty<EquippedItem>((EquippedItem)null);
|
||||
// The one aim slot on the Target (docs/fire-control-cut.md, Cut 2): a revealed item or a mount of the hull this
|
||||
// observer believes the target to be, never both. Written only by TrySelectTargetItem (a revealed item: Combat's path
|
||||
// and the player's) and TrySelectMount (a believed mount), and nulled whenever Target changes (subscribed in
|
||||
// Activate). Do not read it outside Entity -- read ResolvedAim, which re-validates both gates on every call, so decay,
|
||||
// a perceived destruction, or the item leaving the target drops the aim the moment it is no longer earned, with no
|
||||
// loop that has to notice and clear it. (Not `Aim`: that is the pilot's pointing direction below.)
|
||||
public AimTarget AimedAt { get; private set; }
|
||||
|
||||
// Where the pilot points: reticle, lock cone, tractor, guided rounds, fire direction. Steers nothing; the
|
||||
// hull turns only by Ship.Turn.
|
||||
public float3 Aim;
|
||||
|
||||
|
||||
public string Name;
|
||||
|
||||
// Names the entity for assertion messages and logs: xunit and the debugger format an object by walking its graph
|
||||
// unless it has a ToString, and an Entity's graph is the whole zone. Entity has no id; Name is the hull's or the scenario's.
|
||||
public override string ToString() => $"{GetType().Name} '{Name}'";
|
||||
|
||||
// public int Population;
|
||||
// public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
|
||||
|
||||
public readonly Dictionary<string, float> Messages = new Dictionary<string, float>();
|
||||
public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
|
||||
private readonly Dictionary<object, Signature> _visibilitySources = new Dictionary<object, Signature>();
|
||||
// A read-only view: the only writes are SetSignature and the decay loop in Update, both below.
|
||||
// A ReadOnlyDictionary over the private field, created once: a cast back to Dictionary fails.
|
||||
private ReadOnlyDictionary<object, Signature> _visibilityView;
|
||||
public IReadOnlyDictionary<object, Signature> VisibilitySources => _visibilityView ??= new ReadOnlyDictionary<object, Signature>(_visibilitySources);
|
||||
|
||||
// The one writer of VisibilitySources (the decay loop in Update is the one decayer). Every light signature
|
||||
// names its channel and the item that produced it (null for the hull). Emission is active emission (paints now,
|
||||
// Entity.Emit after emissions-heard), never light: ruling visibility-per-capability-reveal, map R1.
|
||||
public void SetSignature(object source, SignatureChannel channel, float strength, EquippedItem item)
|
||||
{
|
||||
if (channel == SignatureChannel.Emission)
|
||||
throw new ArgumentException("Emission is active emission, never a light signature.", nameof(channel));
|
||||
// A light signature is thinned by the ship's own gear at the moment it is written (aetheria-ew, lie-is-own-emission):
|
||||
// each equipped suppressor folds the strength in equipment order and pays for what it alone removed.
|
||||
foreach (var suppressor in GetBehaviors<LaunchSuppressor>())
|
||||
strength = suppressor.Suppress(channel, strength);
|
||||
_visibilitySources[source] = new Signature(channel, strength, item, ClaimOf(item));
|
||||
}
|
||||
|
||||
// What this ship's acts claim (aetheria-ew, lie-is-own-emission, classify-from-belief): per equipped item, the
|
||||
// equippable class every act of that item is stamped with (SetSignature, Emit, ReceivePaint). The hull is the
|
||||
// item EquippedHull, so its claim lives in the same slot as every other: the hull class its own acts carry and
|
||||
// the profile an observer derives (ClaimedHull) are one value. The truth unless claimed otherwise. Claim is the
|
||||
// one write port; its production writer is the EW behaviour of cut ew-masquerade, tests only until then.
|
||||
// Deactivate clears the slots. Aim, damage and physics keep the truth.
|
||||
private readonly Dictionary<EquippedItem, EquippableItemData> _itemClaims = new Dictionary<EquippedItem, EquippableItemData>();
|
||||
public HullData ClaimedHull => (ClaimOf(EquippedHull) as HullData) ?? HullData;
|
||||
public EquippableItemData ClaimOf(EquippedItem item) =>
|
||||
item == null ? null : _itemClaims.TryGetValue(item, out var claimed) ? claimed : item.Data;
|
||||
internal void Claim(HullData hull) => Claim(EquippedHull, hull);
|
||||
internal void Claim(EquippedItem item, EquippableItemData claimed)
|
||||
{
|
||||
// One hull class in the book: a hull class is claimed by the hull and only by the hull, whichever side asks.
|
||||
if (claimed != null && (item == EquippedHull) != (claimed is HullData))
|
||||
throw new ArgumentException("Only the hull claims a hull class, and the hull claims nothing else.", nameof(claimed));
|
||||
if (claimed == null) _itemClaims.Remove(item);
|
||||
else _itemClaims[item] = claimed;
|
||||
}
|
||||
public readonly ReactiveDictionary<Entity, float> EntityInfoGathered = new ReactiveDictionary<Entity, float>();
|
||||
|
||||
public (List<Weapon> weapons, List<EquippedItem> items)[] WeaponGroups;
|
||||
|
|
@ -125,7 +178,11 @@ public abstract class Entity
|
|||
|
||||
public bool OverrideShutdown { get; set; }
|
||||
|
||||
public float TractorPower { get; set; }
|
||||
// The pilot's tractor command (0..1); the Pickup behaviour spins its beam toward it.
|
||||
public float TractorCommand;
|
||||
|
||||
// The beam's spun-up state: Pickup's, or 0 without one.
|
||||
public float TractorPower => GetBehavior<Pickup>()?.Power ?? 0f;
|
||||
|
||||
public bool Active
|
||||
{
|
||||
|
|
@ -149,9 +206,11 @@ public abstract class Entity
|
|||
public ItemManager ItemManager { get; }
|
||||
public int AssignedPopulation => PopulationAssignments.Sum(pa => pa.AssignedPopulation);
|
||||
public float Mass { get; private set; }
|
||||
public float Visibility => VisibilitySources.Values.Sum();
|
||||
public float Visibility => VisibilitySources.Values.Sum(s => s.Strength);
|
||||
|
||||
public Subject<Entity> IncomingHit = new Subject<Entity>();
|
||||
// One per entity, created with it, never replaced: FireControl publishes each landed impact on it (Absorb).
|
||||
public readonly CapabilityEvents Capabilities = new CapabilityEvents();
|
||||
public Subject<(int2 pos, float damage)> ArmorDamage = new Subject<(int2, float)>();
|
||||
public Subject<(EquippedItem item, float damage)> ItemDamage = new Subject<(EquippedItem, float)>();
|
||||
// public Subject<EquippedItem> ItemOffline = new Subject<EquippedItem>();
|
||||
|
|
@ -162,8 +221,46 @@ public abstract class Entity
|
|||
public Subject<Unit> HeatstrokeDeath = new Subject<Unit>();
|
||||
public Subject<Unit> HypothermiaRisk = new Subject<Unit>();
|
||||
public Subject<Unit> HypothermiaDeath = new Subject<Unit>();
|
||||
public Subject<Entity> TargetedBy = new Subject<Entity>();
|
||||
public ReactiveProperty<int> TargetedByCount = new ReactiveProperty<int>(0);
|
||||
// Selection tells the selected ship nothing: a warning comes only from a paint. A search paint is a ping
|
||||
// sweeping this ship (Sensor.Execute); a track paint is a lock (LockWeapon.Execute). Each reports into the
|
||||
// inbox the tick it paints; PublishInbox publishes the inbox once, so a warning lives exactly one tick after
|
||||
// its last paint.
|
||||
// The inbox keeps who painted and with what beside the warning: the warning is all a reader of IncomingPaints
|
||||
// gets, the emitter and item are for PublishInbox, which records the emitter's reveal.
|
||||
private readonly struct PendingPaint
|
||||
{
|
||||
public readonly PaintWarning Warning;
|
||||
public readonly Entity Emitter;
|
||||
public readonly EquippedItem Item;
|
||||
|
||||
public PendingPaint(PaintWarning warning, Entity emitter, EquippedItem item)
|
||||
{
|
||||
Warning = warning;
|
||||
Emitter = emitter;
|
||||
Item = item;
|
||||
}
|
||||
}
|
||||
private readonly List<PendingPaint> _paintInbox = new List<PendingPaint>();
|
||||
private readonly List<PaintWarning> _incomingPaints = new List<PaintWarning>();
|
||||
public IReadOnlyList<PaintWarning> IncomingPaints => _incomingPaints;
|
||||
// An ally's sensor posts a return on the tick its ping crosses a subject; published with paints, read by this
|
||||
// ship's own sensors for one tick.
|
||||
private readonly List<PingReturn> _returnInbox = new List<PingReturn>();
|
||||
private readonly List<PingReturn> _pingReturns = new List<PingReturn>();
|
||||
internal IReadOnlyList<PingReturn> PingReturns => _pingReturns;
|
||||
// What this ship's active sensors and lock paints emit this tick (Emit), heard by other ships' Sense (ruling
|
||||
// sensor-stat-set): written in Update, read by Sense in the same tick, cleared by the next PublishInbox.
|
||||
private readonly List<ActiveEmission> _emissions = new List<ActiveEmission>();
|
||||
// What this observer has seen each ship's items do (ruling visibility-per-capability-reveal), keyed (subject,
|
||||
// item). Written only by RecordReveal (an act, or a scan through RecordInspection, enters) and EndReveals (an end the observer perceives, or a departed
|
||||
// subject's entries aged past BearingMemory), cleared by Deactivate (ruling reveal-ends-on-perception).
|
||||
private readonly Dictionary<Entity, Dictionary<EquippedItem, Reveal>> _reveals = new Dictionary<Entity, Dictionary<EquippedItem, Reveal>>();
|
||||
// The mounts of each subject whose item this observer perceived destroyed (PerceivesDestroyed), so the target cycle
|
||||
// skips them and no aim rests on them: observer state, written only by RecordSeenDestroyed in Sense, dropped with the
|
||||
// subject's reveals (EndReveals) and cleared by Deactivate. Truth enters only through the one perception rule.
|
||||
private readonly Dictionary<Entity, HashSet<HardpointData>> _seenDestroyed = new Dictionary<Entity, HashSet<HardpointData>>();
|
||||
private readonly List<EquippedItem> _endedItems = new List<EquippedItem>();
|
||||
private readonly List<Entity> _agedSubjects = new List<Entity>();
|
||||
public ReactiveProperty<SecurityLevel> CurrentSecurityLevel = new ReactiveProperty<SecurityLevel>(SecurityLevel.Open);
|
||||
public ReadOnlyReactiveProperty<bool> PresencePermitted;
|
||||
|
||||
|
|
@ -194,12 +291,10 @@ public abstract class Entity
|
|||
return presencePermitted;
|
||||
}), initialValue: true);
|
||||
|
||||
foreach (var item in Equipment)
|
||||
foreach (var behavior in item.Behaviors)
|
||||
{
|
||||
if(behavior is IInitializableBehavior initializableBehavior)
|
||||
initializableBehavior.Initialize();
|
||||
}
|
||||
// One initialiser for everything that computes targets here: gear and the effects still running, so a
|
||||
// consumable active across a refit retargets to the new items exactly as gear does.
|
||||
InitializeBehaviors(Equipment.SelectMany(item => item.Behaviors));
|
||||
InitializeBehaviors(_activeConsumables.SelectMany(effect => effect.Behaviors));
|
||||
foreach(var entity in Zone.Entities)
|
||||
{
|
||||
EntityInfoGathered[entity] = 0;
|
||||
|
|
@ -220,9 +315,13 @@ public abstract class Entity
|
|||
VisibleEntities.Remove(remove.Value);
|
||||
VisibleEnemies.Remove(remove.Value);
|
||||
VisibleFriendlies.Remove(remove.Value);
|
||||
// A stance lasts the sitting: it goes with an entity gone for good (destroyed, warped away, unloaded), not
|
||||
// with a ship docking, which leaves the zone parented to its dock (TryDock) and rejoins it on undock.
|
||||
if (remove.Value.Parent == null) _iffOverrides.Remove(remove.Value);
|
||||
if (remove.Value == this)
|
||||
{
|
||||
// A ship out of the zone is no longer published to: it holds no warnings (nothing would ever clear them).
|
||||
_paintInbox.Clear();
|
||||
_incomingPaints.Clear();
|
||||
}
|
||||
ReleaseStance(remove.Value);
|
||||
if (_grudgeSubscriptions.TryGetValue(remove.Value, out var grudgeSubs))
|
||||
{
|
||||
foreach (var s in grudgeSubs) s.Dispose();
|
||||
|
|
@ -244,13 +343,6 @@ public abstract class Entity
|
|||
{
|
||||
if (Target.Value.Entity == remove.Value) SetTarget(TargetRef.None);
|
||||
}));
|
||||
// Only an entity is ever targeted by: a chunk has no one to tell.
|
||||
_subscriptions.Add(Target.Subscribe(target => target.Entity?.TargetedBy.OnNext(this)));
|
||||
_subscriptions.Add(TargetedBy.Subscribe(enemy =>
|
||||
{
|
||||
TargetedByCount.Value++;
|
||||
enemy.Target.Where(t => t.Entity != this).Take(1).Subscribe(_ => TargetedByCount.Value--);
|
||||
}));
|
||||
|
||||
//
|
||||
_subscriptions.Add(EntityInfoGathered.ObserveReplace().Subscribe(replace =>
|
||||
|
|
@ -300,16 +392,16 @@ public abstract class Entity
|
|||
_watchedEntitySubscriptions.Remove(disappearingEntity.Value);
|
||||
}));
|
||||
|
||||
// Cut 2 (docs/fire-control-cut.md): a Target change nulls the aim point. Fires immediately on
|
||||
// subscribe with whatever Target already holds, which is harmless -- TargetItem starts null anyway.
|
||||
_subscriptions.Add(Target.Subscribe(_ => TargetItem.Value = null));
|
||||
// Cut 2 (docs/fire-control-cut.md): a Target change nulls the aim. Fires immediately on
|
||||
// subscribe with whatever Target already holds, which is harmless -- AimedAt starts empty anyway.
|
||||
_subscriptions.Add(Target.Subscribe(_ => AimedAt = AimTarget.None));
|
||||
|
||||
// 9.3 (docs/fire-control-cut.md, Soul C3): a Target surviving Deactivate can point at an entity
|
||||
// this zone removed while inactive -- Deactivate disposes the Zone.Entities.ObserveRemove
|
||||
// subscription that is the only thing that nulls a stale Target, and EntityInfoGathered was just
|
||||
// rebuilt above from the zone's *current* membership, not from whatever Target still remembers.
|
||||
// Reconcile here, now that both the fresh EntityInfoGathered and the Target-change subscription
|
||||
// above are live (so this write also clears TargetItem through it): an active entity's Target
|
||||
// above are live (so this write also clears the aim through it): an active entity's Target
|
||||
// must always be an entity it has info on. Activate owns this reconciliation rather than
|
||||
// Deactivate nulling Target outright, because nulling on every dock would throw away a target
|
||||
// that is still alive and simply never changed while docked -- the common case, and not the one
|
||||
|
|
@ -324,15 +416,15 @@ public abstract class Entity
|
|||
GenerateWeaponGroups();
|
||||
}
|
||||
|
||||
// Cut 2 (docs/fire-control-cut.md): the only writer of TargetItem. Accepts null (clearing the aim
|
||||
// point) or an item belonging to the current Target that FireControl.IsRevealed resolves true for this
|
||||
// entity as observer. Returns whether the write took effect; a rejected non-null selection leaves
|
||||
// TargetItem unchanged.
|
||||
// Cut 2 (docs/fire-control-cut.md): one of the aim slot's two writers (the other is TrySelectMount). Accepts null
|
||||
// (clearing the aim) or a revealed item (FireControl.IsRevealed: this entity saw it act) belonging to the current
|
||||
// Target. A fitted item the observer has only located is aimed as its mount, never as an item. Returns whether the
|
||||
// write took effect; a rejected non-null selection leaves the aim unchanged.
|
||||
public bool TrySelectTargetItem(EquippedItem item)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
TargetItem.Value = null;
|
||||
AimedAt = AimTarget.None;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -340,17 +432,64 @@ public abstract class Entity
|
|||
if (Target.Value.Entity == null || item.Entity != Target.Value.Entity || !FireControl.IsRevealed(this, item))
|
||||
return false;
|
||||
|
||||
TargetItem.Value = item;
|
||||
AimedAt = AimTarget.OfItem(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The read path for TargetItem (see the field's own comment): null once the aimed item is no longer
|
||||
// revealed to this entity, or no longer belongs to the current Target, even though nothing wrote
|
||||
// TargetItem.Value at the moment that became true. Re-checked on every call; never cached.
|
||||
public EquippedItem ResolvedTargetItem =>
|
||||
TargetItem.Value != null && Target.Value.Entity == TargetItem.Value.Entity && FireControl.IsRevealed(this, TargetItem.Value)
|
||||
? TargetItem.Value
|
||||
: null;
|
||||
// The aim slot's other writer: a mount of the hull this entity believes the Target to be (LayoutOf, by reference),
|
||||
// unless this entity perceived that mount's item destroyed (SeenDestroyed). Reads only observer state, so whether a
|
||||
// mount can be aimed at says nothing of the Target's truth (ruling cycle-skips-only-perceived-destroyed).
|
||||
public bool TrySelectMount(HardpointData mount)
|
||||
{
|
||||
if (!MountAimable(Target.Value.Entity, mount)) return false;
|
||||
AimedAt = AimTarget.OfMount(mount);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool MountAimable(Entity subject, HardpointData mount) =>
|
||||
subject != null && mount != null && LayoutOf(subject).Contains(mount) && !SeenDestroyed(subject, mount);
|
||||
|
||||
// The read path for the aim slot (see its comment): the aim only while its gate still holds -- an item still revealed
|
||||
// and still the Target's, a mount still in the believed layout and not seen destroyed -- else none, even though
|
||||
// nothing wrote the slot at the moment that stopped being true. Re-checked on every call; never cached.
|
||||
public AimTarget ResolvedAim
|
||||
{
|
||||
get
|
||||
{
|
||||
var subject = Target.Value.Entity;
|
||||
var aim = AimedAt;
|
||||
if (subject == null) return AimTarget.None;
|
||||
if (aim.Item != null) return FireControl.IsRevealed(this, aim.Item) ? aim : AimTarget.None;
|
||||
return MountAimable(subject, aim.Mount) ? aim : AimTarget.None;
|
||||
}
|
||||
}
|
||||
|
||||
public EquippedItem ResolvedTargetItem => ResolvedAim.Item;
|
||||
|
||||
// What the cycle visits on `subject`, in schematic order: its rows (revealed items, then every mount of the hull this
|
||||
// ship believes it to be, empty or not) minus the mounts this ship saw destroyed. Reads the same rows the schematic
|
||||
// shows and the record, never `subject`'s equipment or live Durability.
|
||||
public IEnumerable<AimTarget> AimCycle(Entity subject) =>
|
||||
SchematicRows(subject)
|
||||
.Where(r => r.Item != null || !SeenDestroyed(subject, r.Mount))
|
||||
.Select(r => r.Item != null ? AimTarget.OfItem(r.Item) : AimTarget.OfMount(r.Mount));
|
||||
|
||||
// The player's cycle key: steps the aim to the next AimCycle entry after the resolved one and wraps; an entry its
|
||||
// writer refuses (a revealed item since destroyed) is passed over; nothing to visit clears the aim.
|
||||
public void CycleAim()
|
||||
{
|
||||
var subject = Target.Value.Entity;
|
||||
if (subject == null) return;
|
||||
var cycle = AimCycle(subject).ToList();
|
||||
var now = ResolvedAim;
|
||||
var index = cycle.FindIndex(a => a.Item == now.Item && a.Mount == now.Mount && (now.Item != null || now.Mount != null));
|
||||
for (var step = 1; step <= cycle.Count; step++)
|
||||
{
|
||||
var next = cycle[(index + step + cycle.Count) % cycle.Count];
|
||||
if (next.Item != null ? TrySelectTargetItem(next.Item) : TrySelectMount(next.Mount)) return;
|
||||
}
|
||||
AimedAt = AimTarget.None;
|
||||
}
|
||||
|
||||
// Mining Cut 3 (docs/mining-cut-refresh.md): the one writer of Target, called by the player's handlers and the
|
||||
// agents alike. A chunk is taken only while this entity can see it, so a rock in darkness cannot be picked; an
|
||||
|
|
@ -364,22 +503,30 @@ public abstract class Entity
|
|||
|
||||
// Mining Cut 3 (Q14 A): this entity's info on a chunk, computed when asked and stored nowhere. It is the value
|
||||
// the per-tick sensor rule (Sensor.Execute, through Sensor.Gain) would settle at for a target this bright,
|
||||
// here, now. Each active sensor applies x <- saturate(x + G_i dt)(1 - k dt) every tick, so with n sensors the
|
||||
// info settles where the gain balances the decay: sum(G_i) / (n k), capped at 1. A ping adds nothing that
|
||||
// lasts, so only the passive gain enters.
|
||||
// here, now (PassiveInfo at the chunk's brightness), capped at 1.
|
||||
public float ChunkInfo(ChunkId chunk)
|
||||
{
|
||||
var visibility = Zone.ChunkVisibility(chunk);
|
||||
if (visibility <= 0f) return 0f;
|
||||
var position = Zone.ChunkPose(chunk.Field, chunk.Index).xy;
|
||||
return saturate(PassiveInfo(Zone.ChunkPose(chunk.Field, chunk.Index).xy, visibility));
|
||||
}
|
||||
|
||||
// The info a target of `signature` at `position` would settle at under this entity's passive sensing, before
|
||||
// the cap at 1. Each active sensor applies x <- saturate(x + G_i dt)(1 - k dt) every tick, so with n sensors the
|
||||
// info settles where the gain balances the decay: sum(G_i) / (n k). A ping adds nothing that lasts, so only the
|
||||
// passive gain enters. ChunkInfo asks it for a chunk's brightness; Sense asks it for a unit signature once per
|
||||
// ship, because it is linear in the signature below saturation and so answers for every act at a place. Zero
|
||||
// with no active sensor.
|
||||
public float PassiveInfo(float2 position, float signature)
|
||||
{
|
||||
var rate = 0f;
|
||||
var sensors = 0;
|
||||
foreach (var sensor in ActiveSensors())
|
||||
{
|
||||
rate += sensor.PassiveRate(visibility, position);
|
||||
rate += sensor.PassiveRate(signature, position);
|
||||
sensors++;
|
||||
}
|
||||
return sensors == 0 ? 0f : saturate(rate / (sensors * ItemManager.GameplaySettings.TargetInfoDecay));
|
||||
return sensors == 0 ? 0f : rate / (sensors * ItemManager.GameplaySettings.TargetInfoDecay);
|
||||
}
|
||||
|
||||
// Mining Cut 3: the detection threshold, read through the chunk path. A chunk is visible exactly as an entity
|
||||
|
|
@ -606,10 +753,44 @@ public abstract class Entity
|
|||
return max(gain, 0f) / (sensors * ItemManager.GameplaySettings.TargetInfoDecay * threshold) * 1.0001f;
|
||||
}
|
||||
|
||||
// Every sensor behaviour that runs this tick: those on active equipment, and those of active consumables.
|
||||
private IEnumerable<Sensor> ActiveSensors() =>
|
||||
Equipment.Where(item => item.Active.Value).SelectMany(item => item.Behaviors).OfType<Sensor>()
|
||||
.Concat(_activeConsumables.SelectMany(effect => effect.Behaviors).OfType<Sensor>());
|
||||
// Every sensor behaviour that runs this tick: those on active equipment, and those of active consumables. The
|
||||
// list is this entity's one buffer, refilled per call (Sense asks once per other ship per tick, allocating
|
||||
// nothing), so callers use it before asking again.
|
||||
private readonly List<Sensor> _activeSensors = new List<Sensor>();
|
||||
private List<Sensor> ActiveSensors()
|
||||
{
|
||||
_activeSensors.Clear();
|
||||
for (var i = 0; i < Equipment.Count; i++)
|
||||
{
|
||||
var item = Equipment[i];
|
||||
if (!item.Active.Value) continue;
|
||||
foreach (var behavior in item.Behaviors)
|
||||
if (behavior is Sensor sensor) _activeSensors.Add(sensor);
|
||||
}
|
||||
foreach (var effect in _activeConsumables)
|
||||
foreach (var behavior in effect.Behaviors)
|
||||
if (behavior is Sensor sensor) _activeSensors.Add(sensor);
|
||||
return _activeSensors;
|
||||
}
|
||||
|
||||
// How much of an emission's reach this observer's instruments hear it at (ruling sensor-stat-set: listeners hear at
|
||||
// a multiple of an emitter's own range): the largest of 1 (any active sensor) and each active listener's Multiple,
|
||||
// 0 with neither. Catalog values come from AetherDb sensor-stat-set.
|
||||
private float HearingMultiple()
|
||||
{
|
||||
var multiple = ActiveSensors().Count > 0 ? 1f : 0f;
|
||||
for (var i = 0; i < Equipment.Count; i++)
|
||||
{
|
||||
var item = Equipment[i];
|
||||
if (!item.Active.Value) continue;
|
||||
foreach (var behavior in item.Behaviors)
|
||||
if (behavior is Listener listener) multiple = max(multiple, listener.Multiple);
|
||||
}
|
||||
foreach (var effect in _activeConsumables)
|
||||
foreach (var behavior in effect.Behaviors)
|
||||
if (behavior is Listener listener) multiple = max(multiple, listener.Multiple);
|
||||
return multiple;
|
||||
}
|
||||
|
||||
// Cut 12.3 (docs/fire-control-cut.md): "armour absorbs first" -- the per-cell armour phase, split out of
|
||||
// what used to be Absorb's own first half (moved verbatim from DamageSchematic's per-cell body, Cut 3) so
|
||||
|
|
@ -776,6 +957,297 @@ public abstract class Entity
|
|||
VisibleEntities.Clear();
|
||||
VisibleEnemies.Clear();
|
||||
VisibleFriendlies.Clear();
|
||||
_paintInbox.Clear();
|
||||
_incomingPaints.Clear();
|
||||
_returnInbox.Clear();
|
||||
_pingReturns.Clear();
|
||||
_emissions.Clear();
|
||||
_reveals.Clear();
|
||||
_seenDestroyed.Clear();
|
||||
_itemClaims.Clear();
|
||||
}
|
||||
|
||||
// Zone.Update runs this on every entity before any entity updates, so a paint made during tick N is published
|
||||
// at the start of tick N+1 whatever order the emitter and this ship update in; a paint that stops is gone
|
||||
// one tick later for every ordering.
|
||||
internal void PublishInbox()
|
||||
{
|
||||
_emissions.Clear(); // written in Update, read by Sense in the same tick
|
||||
_incomingPaints.Clear();
|
||||
foreach (var paint in _paintInbox)
|
||||
{
|
||||
_incomingPaints.Add(paint.Warning);
|
||||
RecordReveal(paint.Emitter, paint.Item, SignatureChannel.Emission, paint.Warning.EmitterClass);
|
||||
}
|
||||
_paintInbox.Clear();
|
||||
_pingReturns.Clear();
|
||||
_pingReturns.AddRange(_returnInbox);
|
||||
_returnInbox.Clear();
|
||||
}
|
||||
|
||||
internal void ReceiveReturn(PingReturn pingReturn)
|
||||
{
|
||||
if (!_active) return;
|
||||
_returnInbox.Add(pingReturn);
|
||||
}
|
||||
|
||||
// The callers are Sensor.Execute (a sweeping ping) and LockWeapon.Execute (a lock paint): this ship's `item` emits this
|
||||
// tick and is heard by another ship's Sense within `hearRange` (the emitter's range over its intercept factor,
|
||||
// fixed here), bearing only.
|
||||
internal void Emit(EquippedItem item, float hearRange)
|
||||
{
|
||||
if (!_active) return;
|
||||
_emissions.Add(new ActiveEmission(item, hearRange, ClaimOf(item)));
|
||||
}
|
||||
|
||||
// The callers are Sensor.Execute (a Search paint, Strength 0) and LockWeapon.Execute (a Track paint, Strength
|
||||
// the emitter's own Lock at that paint). The emitter's class is the class its ship claims for the item (ClaimOf: the
|
||||
// item's data unless claimed otherwise; null with no item: a consumable's effect, which has no item and so is never
|
||||
// revealed).
|
||||
internal void ReceivePaint(Entity emitter, EquippedItem item, PaintMode mode, float strength)
|
||||
{
|
||||
if (!_active) return;
|
||||
_paintInbox.Add(new PendingPaint(new PaintWarning(normalize((emitter.Position - Position).xz), emitter.ClaimOf(item), mode, strength), emitter, item));
|
||||
}
|
||||
|
||||
// The reveal book's one way in and its one membership gate (callers: Sense, PublishInbox and RecordInspection, all in
|
||||
// this file): this observer saw `item` of `subject` act on `channel`, now, from this bearing. An item-less act (hull
|
||||
// radiation, a consumable) reveals nothing, and neither does a subject that is not in the zone: a departed
|
||||
// subject's entries are never created or refreshed, from any caller, and neither does an item this observer
|
||||
// perceives destroyed (PerceivesDestroyed). A later act of the same item replaces the
|
||||
// earlier one. `claimed` is the class the carrier (signature, emission or paint) stamped: what this observer's
|
||||
// classifying readers will believe of the act; `item` stays the aim and book key.
|
||||
internal void RecordReveal(Entity subject, EquippedItem item, SignatureChannel? channel, EquippableItemData claimed)
|
||||
{
|
||||
if (!_active || item == null || !Zone.Entities.Contains(subject) || PerceivesDestroyed(subject, item)) return;
|
||||
if (!_reveals.TryGetValue(subject, out var book))
|
||||
_reveals[subject] = book = new Dictionary<EquippedItem, Reveal>();
|
||||
book[item] = new Reveal(item, channel, normalize((subject.Position - Position).xz), Zone.Time, claimed);
|
||||
}
|
||||
|
||||
// A finished scan (Scanner.Execute; rulings scan-is-an-act, quiet-gear-identifiable-hull-layout-known: quiet gear
|
||||
// that never acts stays identifiable through special gear): this observer learns every fitted item of `subject`,
|
||||
// channel null. It records what the item claims, not what it is (ClaimOf, as every act's carrier stamps it: the
|
||||
// aetheria-ew one judge, classify-from-belief), skips the hull (its class is the track's to give) and a destroyed
|
||||
// item, and goes through RecordReveal's gate like any act. It calls no EndReveals: a scan ends nothing
|
||||
// (reveal-ends-on-perception).
|
||||
internal void RecordInspection(Entity subject)
|
||||
{
|
||||
foreach (var item in subject.Equipment)
|
||||
{
|
||||
if (item == subject.EquippedHull || item.EquippableItem.IsDestroyed) continue;
|
||||
RecordReveal(subject, item, null, subject.ClaimOf(item));
|
||||
}
|
||||
}
|
||||
|
||||
// This observer resolves `subject`'s gear (ContactOf's Identified gate) and `item` of it is destroyed: the one rule
|
||||
// for a destroyed item an observer perceives, read by the book's entry (RecordReveal), its end (Sense) and the
|
||||
// seen-destroyed record (RecordSeenDestroyed).
|
||||
private bool PerceivesDestroyed(Entity subject, EquippedItem item) =>
|
||||
item.EquippableItem.IsDestroyed
|
||||
&& EntityInfoGathered.TryGetValue(subject, out var info) && info >= ItemManager.GameplaySettings.TargetGearInfoThreshold;
|
||||
|
||||
// A stance lasts the sitting: it goes with a subject gone for good (destroyed, warped away, unloaded) once the book no
|
||||
// longer remembers it, not with a ship docking, which leaves the zone parented to its dock (TryDock) and rejoins it on
|
||||
// undock. Called when the subject leaves the zone and when the book drops it, so the override and the book end together.
|
||||
private void ReleaseStance(Entity subject)
|
||||
{
|
||||
if (subject.Parent == null && !Zone.Entities.Contains(subject) && !_reveals.ContainsKey(subject)) _iffOverrides.Remove(subject);
|
||||
}
|
||||
|
||||
// This observer perceives `subject`'s gear (ContactOf's Identified gate): each of its destroyed items leaves its mount
|
||||
// in the seen-destroyed record. The same PerceivesDestroyed Sense ends reveals by, applied to mounts. The record is read
|
||||
// only for mounts of LayoutOf (MountAimable, AimCycle), so a true mount outside the believed layout is never asked for.
|
||||
private void RecordSeenDestroyed(Entity subject)
|
||||
{
|
||||
// Indexed: Sense runs for every pair of ships every tick.
|
||||
for (var i = 0; i < subject.Equipment.Count; i++)
|
||||
{
|
||||
var item = subject.Equipment[i];
|
||||
if (item.Hardpoint == null || !PerceivesDestroyed(subject, item)) continue;
|
||||
if (!_seenDestroyed.TryGetValue(subject, out var seen)) _seenDestroyed[subject] = seen = new HashSet<HardpointData>();
|
||||
seen.Add(item.Hardpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private bool SeenDestroyed(Entity subject, HardpointData mount) =>
|
||||
_seenDestroyed.TryGetValue(subject, out var seen) && seen.Contains(mount);
|
||||
|
||||
// The book's one way out (caller: Sense): `item` null ends every reveal of `subject`, otherwise that item's.
|
||||
// The subject's key goes with its last entry; ending all of them also drops the subject's seen-destroyed record.
|
||||
private void EndReveals(Entity subject, EquippedItem item)
|
||||
{
|
||||
if (item == null) _seenDestroyed.Remove(subject);
|
||||
if (!_reveals.TryGetValue(subject, out var book)) return;
|
||||
if (item != null) book.Remove(item);
|
||||
else book.Clear();
|
||||
if (book.Count != 0) return;
|
||||
_reveals.Remove(subject);
|
||||
ReleaseStance(subject);
|
||||
}
|
||||
|
||||
// The subjects this observer holds any reveal of, departed ones included until the prune: with VisibleEntities, every
|
||||
// contact it has (ContactOf is Detected for a tracked subject or one with a young reveal).
|
||||
public IReadOnlyCollection<Entity> RevealedSubjects => _reveals.Keys;
|
||||
|
||||
// The hostile subjects this observer holds only by a bearing: revealed, Detected, not Tracked (what bearing markers and
|
||||
// the music show). Hostile is the observer's own live stance (IsHostileTo): the observer always knows its own decision,
|
||||
// and an override outlives a departed subject exactly as long as the book remembers it (ReleaseStance). Reads the book
|
||||
// and ContactOf, never the subject's Position or gear.
|
||||
public IEnumerable<Entity> RememberedHostiles => RevealedSubjects.Where(s => IsHostileTo(s) && ContactOf(s) is { Detected: true, Tracked: false });
|
||||
|
||||
// What this observer has seen `subject`'s items do: each item's latest act, and nothing the subject's present
|
||||
// gear or Durability says (ruling contact-reads-book-aim-reads-live). A reveal ends only on what this observer
|
||||
// perceives (ruling reveal-ends-on-perception): the destruction of an item of a ship it identifies, the death,
|
||||
// dock or warp of a subject its instruments could see leave, or, for a subject that has left the zone, the
|
||||
// freshest entry aging past BearingMemory; Deactivate clears it all. Whether an item can be aimed at now is
|
||||
// FireControl.IsRevealed's question, not this one.
|
||||
public IEnumerable<Reveal> RevealsOf(Entity subject) =>
|
||||
_reveals.TryGetValue(subject, out var book) ? book.Values : Enumerable.Empty<Reveal>();
|
||||
|
||||
// The weapons this observer believes `subject` has: each reveal whose claimed class carries a weapon behaviour, in the
|
||||
// subject's equipment order (never the book's slot order, which follows when reveals were made and ended). The one
|
||||
// classifying read of the book for weapons, shared by the enemy schematic and Combat (aetheria-ew, classify-from-belief);
|
||||
// a gun claimed as a non-weapon is not listed, though RevealsOf holds it for aim.
|
||||
public IEnumerable<Reveal> RevealedWeapons(Entity subject) =>
|
||||
InFittedOrder(subject, RevealsOf(subject).Where(r => r.Claimed != null && r.Claimed.Behaviors.Any(b => b is WeaponData)));
|
||||
|
||||
// The gear this observer believes `subject` has: each reveal whose claimed class carries no weapon behaviour and is not a
|
||||
// hull, in the order of RevealedWeapons. A hull's layout is known, not revealed, so it is never a gear row.
|
||||
public IEnumerable<Reveal> RevealedGear(Entity subject) =>
|
||||
InFittedOrder(subject, RevealsOf(subject).Where(r => r.Claimed != null && !(r.Claimed is HullData) && !r.Claimed.Behaviors.Any(b => b is WeaponData)));
|
||||
|
||||
private static IEnumerable<Reveal> InFittedOrder(Entity subject, IEnumerable<Reveal> reveals) =>
|
||||
reveals.OrderBy(r => FittedIndex(subject, r.Item)).ThenBy(r => r.Item.EquippableItem.Lot);
|
||||
|
||||
// The classes `subject` has claimed to this observer, distinct and by name: what a bearing marker is labelled with. Reads
|
||||
// each reveal's Claimed only, never the item's true data (aetheria-ew, classify-from-belief).
|
||||
public IEnumerable<EquippableItemData> ClaimedClasses(Entity subject) =>
|
||||
RevealsOf(subject).Select(r => r.Claimed).Where(c => c != null).Distinct().OrderBy(c => c.Name, StringComparer.Ordinal);
|
||||
|
||||
// A revealed item's place in the subject's equipment; gear the subject no longer carries follows all fitted gear
|
||||
// (ties among it fall to the lot, a stable id), never ahead of it.
|
||||
private static int FittedIndex(Entity subject, EquippedItem item)
|
||||
{
|
||||
var index = subject.Equipment.IndexOf(item);
|
||||
return index < 0 ? int.MaxValue : index;
|
||||
}
|
||||
|
||||
// The rows of `subject`'s schematic as this ship reads it: its own weapons when `subject` is this ship (each row its
|
||||
// own data and live range, nothing to doubt about your own ship), otherwise the revealed weapons (each row the claimed
|
||||
// class and that design's rated range) then the revealed gear (each row the claimed class, no range), then one mount
|
||||
// row for every mount of the hull this ship believes `subject` to be (LayoutOf), empty or not and whether or not a
|
||||
// revealed item has a row of its own (ruling quiet-gear-identifiable-hull-layout-known): the rows never compare the
|
||||
// subject's items to the believed layout, so a liar and an honest ship of the claimed hull show the same count. The
|
||||
// one owner of which rows, which class and which range an enemy schematic shows; the Unity SchematicDisplay renders it.
|
||||
public IEnumerable<SchematicRow> SchematicRows(Entity subject)
|
||||
{
|
||||
if (subject == this)
|
||||
return subject.Equipment.Where(i => i.Behaviors.Any(b => b.Data is WeaponData)).Select(i => new SchematicRow(i, i.Data, true));
|
||||
var claimed = RevealedWeapons(subject).Concat(RevealedGear(subject)).Select(r => new SchematicRow(r.Item, r.Claimed, false)).ToList();
|
||||
return claimed.Concat(LayoutOf(subject).Select(h => new SchematicRow(h)));
|
||||
}
|
||||
|
||||
// Where `subject`'s mounts are as this ship believes them: the hull it is identified as (Contact.Profile, the claimed
|
||||
// hull), never the subject's own HullData; empty below identification. Derived on every read, nothing stored.
|
||||
public IReadOnlyList<HardpointData> LayoutOf(Entity subject) => ContactOf(subject).Profile?.Hardpoints ?? (IReadOnlyList<HardpointData>) Array.Empty<HardpointData>();
|
||||
|
||||
// Whether this observer's book for `subject` holds `item`: the book's membership, no live gear read.
|
||||
internal bool HasReveal(Entity subject, EquippedItem item) =>
|
||||
_reveals.TryGetValue(subject, out var book) && book.ContainsKey(item);
|
||||
|
||||
// The one derivation of how much this observer holds of `subject`: see Contact.
|
||||
public Contact ContactOf(Entity subject)
|
||||
{
|
||||
var settings = ItemManager.GameplaySettings;
|
||||
var info = EntityInfoGathered.TryGetValue(subject, out var gathered) ? gathered : 0f;
|
||||
var tracked = VisibleEntities.Contains(subject);
|
||||
var any = false;
|
||||
var freshest = default(Reveal);
|
||||
foreach (var reveal in RevealsOf(subject))
|
||||
if (!any || reveal.Time > freshest.Time)
|
||||
{
|
||||
any = true;
|
||||
freshest = reveal;
|
||||
}
|
||||
var remembered = any && Zone.Time - freshest.Time < settings.BearingMemory;
|
||||
var detected = tracked || remembered;
|
||||
var bearing = tracked ? normalize((subject.Position - Position).xz) : remembered ? freshest.Bearing : default;
|
||||
var identified = info >= settings.TargetGearInfoThreshold;
|
||||
// Profile is the one derivation of the hull this observer believes (no stored belief until the judge, ew-masquerade).
|
||||
return new Contact(detected, tracked, detected && any, identified, bearing, info, identified ? subject.ClaimedHull : null);
|
||||
}
|
||||
|
||||
// What this observer's instruments receive of other ships' acts this tick (Zone.Update calls it once, after every
|
||||
// entity has updated): every light signature of an item that would alone settle this observer's passive info above
|
||||
// TargetDetectionInfoThreshold is revealed (ruling visibility-per-capability-reveal). Hull radiation names no
|
||||
// item and only feeds the track. One PassiveInfo per ship. Zone.Update calls it
|
||||
// for every entity after all of them have updated, so what a ship shows is what every observer receives on that
|
||||
// tick whatever order the zone lists them in.
|
||||
internal void Sense()
|
||||
{
|
||||
if (!_active) return;
|
||||
var threshold = ItemManager.GameplaySettings.TargetDetectionInfoThreshold;
|
||||
var hearing = HearingMultiple();
|
||||
var entities = Zone.Entities;
|
||||
for (var i = 0; i < entities.Count; i++)
|
||||
{
|
||||
var other = entities[i];
|
||||
if (other == this) continue;
|
||||
var perSignature = -1f;
|
||||
foreach (var signature in other._visibilitySources.Values)
|
||||
{
|
||||
if (signature.Item == null) continue;
|
||||
if (perSignature < 0f) perSignature = PassiveInfo(other.Position.xz, 1f);
|
||||
if (signature.Strength * perSignature > threshold) RecordReveal(other, signature.Item, signature.Channel, signature.Claimed);
|
||||
}
|
||||
// Every emission this ship made this tick that reaches this observer is revealed, bearing only (ruling
|
||||
// sensor-stat-set), through RecordReveal's one gate. It feeds no track.
|
||||
if (hearing > 0 && other._emissions.Count > 0)
|
||||
{
|
||||
var planar = length(other.Position.xz - Position.xz);
|
||||
var obscuration = Zone.Obscuration(Position.xz, other.Position.xz);
|
||||
for (var j = 0; j < other._emissions.Count; j++)
|
||||
{
|
||||
var emission = other._emissions[j];
|
||||
if (planar <= emission.HearRange * hearing * obscuration) RecordReveal(other, emission.Item, SignatureChannel.Emission, emission.Claimed);
|
||||
}
|
||||
}
|
||||
// The observer resolves this ship's gear (PerceivesDestroyed), so it perceives an item of it destroyed: the
|
||||
// item's mount is recorded and its reveal ends here; RecordReveal refuses the same item's lingering flash.
|
||||
RecordSeenDestroyed(other);
|
||||
if (_reveals.TryGetValue(other, out var book))
|
||||
{
|
||||
foreach (var item in book.Keys)
|
||||
if (PerceivesDestroyed(other, item)) _endedItems.Add(item);
|
||||
for (var j = 0; j < _endedItems.Count; j++) EndReveals(other, _endedItems[j]);
|
||||
_endedItems.Clear();
|
||||
}
|
||||
}
|
||||
// A subject that left the zone (death, dock, warp, any removal) is perceived gone under the light-act gate: as
|
||||
// bright as its whole Visibility was at removal, from where it was. A re-admitted subject did not leave.
|
||||
var departures = Zone.Departures;
|
||||
for (var i = 0; i < departures.Count; i++)
|
||||
{
|
||||
var departure = departures[i];
|
||||
if (!_reveals.ContainsKey(departure.Subject) || entities.Contains(departure.Subject)) continue;
|
||||
if (departure.Signature * PassiveInfo(departure.Position, 1f) > threshold) EndReveals(departure.Subject, null);
|
||||
}
|
||||
// What stays of a departed subject is memory: pruned once its freshest entry is as old as ContactOf stops
|
||||
// remembering it.
|
||||
var memory = ItemManager.GameplaySettings.BearingMemory;
|
||||
foreach (var pair in _reveals)
|
||||
{
|
||||
if (entities.Contains(pair.Key)) continue;
|
||||
var freshest = float.MinValue;
|
||||
foreach (var reveal in pair.Value.Values) freshest = Math.Max(freshest, reveal.Time);
|
||||
if (Zone.Time - freshest >= memory) _agedSubjects.Add(pair.Key);
|
||||
}
|
||||
// A record of a subject that left and holds no book (a quiet ship, never seen to act) has no entry to age: it goes now.
|
||||
foreach (var subject in _seenDestroyed.Keys)
|
||||
if (!entities.Contains(subject) && !_reveals.ContainsKey(subject)) _agedSubjects.Add(subject);
|
||||
for (var i = 0; i < _agedSubjects.Count; i++) EndReveals(_agedSubjects[i], null);
|
||||
_agedSubjects.Clear();
|
||||
}
|
||||
|
||||
public Entity(ItemManager itemManager, Zone zone, EquippableItem hull, EntitySettings settings)
|
||||
|
|
@ -792,10 +1264,10 @@ public abstract class Entity
|
|||
for(int i=0; i<itemManager.GameplaySettings.WeaponGroupCount; i++)
|
||||
WeaponGroups[i] = (new List<Weapon>(), new List<EquippedItem>());
|
||||
|
||||
ItemDestroyed = ItemDamage.Where(x => x.item.EquippableItem.Durability < .01f).Select(x=>x.item);
|
||||
ItemDestroyed = ItemDamage.Where(x => x.item.EquippableItem.IsDestroyed).Select(x=>x.item);
|
||||
WeaponDestroyed = ItemDestroyed.Select(x => x.Behaviors.FirstOrDefault(b => b is Weapon) as Weapon).Where(x => x != null);
|
||||
HullArmorDepleted = ArmorDamage.Where(x => Armor[x.pos.x, x.pos.y] < .01f).Select(x => x.pos);
|
||||
Death = HullDamage.Where(_ => Hull.Durability < .01f).Select(_ => CauseOfDeath.HullDestroyed)
|
||||
Death = HullDamage.Where(_ => Hull.IsDestroyed).Select(_ => CauseOfDeath.HullDestroyed)
|
||||
.Merge(HeatstrokeDeath.Select(_ => CauseOfDeath.Heatstroke))
|
||||
.Merge(HypothermiaDeath.Select(_ => CauseOfDeath.Hypothermia))
|
||||
.Merge(ItemDestroyed.Where(i=>i.GetBehavior<Cockpit>()!=null).Select(_ => CauseOfDeath.CockpitDestroyed))
|
||||
|
|
@ -854,9 +1326,23 @@ public abstract class Entity
|
|||
|
||||
public void ActivateConsumable(ConsumableItem item)
|
||||
{
|
||||
_activeConsumables.Add(new ConsumableItemEffect(item, this));
|
||||
var effect = new ConsumableItemEffect(item, this);
|
||||
// The same hook Activate runs over Equipment: a behaviour that computes its targets there (StatModifier)
|
||||
// would otherwise reach its second tick uninitialised.
|
||||
InitializeBehaviors(effect.Behaviors);
|
||||
_activeConsumables.Add(effect);
|
||||
}
|
||||
|
||||
private static void InitializeBehaviors(IEnumerable<Behavior> behaviors)
|
||||
{
|
||||
foreach (var behavior in behaviors.ToList())
|
||||
if (behavior is IInitializableBehavior initializable)
|
||||
initializable.Initialize();
|
||||
}
|
||||
|
||||
// Derived, never written: true iff an active consumable effect carries a ThrottleLock.
|
||||
public bool ThrottleLocked => _activeConsumables.Any(e => e.Behaviors.OfType<ThrottleLock>().Any());
|
||||
|
||||
public ConsumableItemEffect FindActiveConsumable(ConsumableItemData data)
|
||||
{
|
||||
return _activeConsumables.FirstOrDefault(ac => ac.Data == data);
|
||||
|
|
@ -914,7 +1400,7 @@ public abstract class Entity
|
|||
Armor[v.x, v.y] += Hardpoints[v.x, v.y].Armor;
|
||||
MaxArmor[v.x, v.y] += Hardpoints[v.x, v.y].Armor;
|
||||
}
|
||||
Temperature[v.x, v.y] = 280;
|
||||
Temperature[v.x, v.y] = StartingCellTemperature;
|
||||
ThermalMass[v.x, v.y] = hullData.Mass * hullData.SpecificHeat / cellCount;
|
||||
}
|
||||
GearOccupancy = new EquippedItem[hullData.Shape.Width, hullData.Shape.Height];
|
||||
|
|
@ -1268,7 +1754,7 @@ public abstract class Entity
|
|||
{
|
||||
bay.DockedShip = ship;
|
||||
ship.SetParent(this);
|
||||
Zone.Entities.Remove(ship);
|
||||
Zone.Remove(ship);
|
||||
ship.Deactivate();
|
||||
ship.Docked.OnNext(this);
|
||||
}
|
||||
|
|
@ -1355,13 +1841,17 @@ public abstract class Entity
|
|||
yield return b;
|
||||
}
|
||||
|
||||
// The phase between the items' performance update and the power bus: what an entity commands its items to do this
|
||||
// tick, read from the same liveness and stats Execute then acts on. Ship's allocation lives here.
|
||||
protected virtual void UpdateThrottles() { }
|
||||
|
||||
public virtual void Update(float delta)
|
||||
{
|
||||
TurnRate = 0;
|
||||
if (!_active) return;
|
||||
|
||||
var velocityBefore = Velocity;
|
||||
LimitClamp = float2(0, 0);
|
||||
var hullData = ItemManager.GetData(Hull) as HullData;
|
||||
|
||||
// Mining Cut 3: a chunk target is lost the moment this entity can no longer see it -- the lost-track rule
|
||||
// through the chunk path. One check of the one slot per tick, not a detection loop over chunks.
|
||||
|
|
@ -1373,16 +1863,17 @@ public abstract class Entity
|
|||
var localSecurityLevel = Zone.GetSecurityLevel(Position.xz);
|
||||
if (CurrentSecurityLevel.Value != localSecurityLevel) CurrentSecurityLevel.Value = localSecurityLevel;
|
||||
|
||||
foreach (var v in VisibilitySources.Keys.ToArray())
|
||||
foreach (var v in _visibilitySources.Keys.ToArray())
|
||||
{
|
||||
VisibilitySources[v] = decay(VisibilitySources[v], ItemManager.GameplaySettings.VisibilityDecay, delta);
|
||||
_visibilitySources[v] = _visibilitySources[v].WithStrength(decay(_visibilitySources[v].Strength, ItemManager.GameplaySettings.VisibilityDecay, delta));
|
||||
|
||||
if (VisibilitySources[v] < 0.1f) VisibilitySources.Remove(v);
|
||||
if (_visibilitySources[v].Strength < 0.1f) _visibilitySources.Remove(v);
|
||||
}
|
||||
|
||||
UpdateTemperature(delta);
|
||||
|
||||
foreach (var item in _orderedEquipment) item.UpdatePerformance();
|
||||
UpdateThrottles();
|
||||
|
||||
if (_active)
|
||||
{
|
||||
|
|
@ -1441,11 +1932,16 @@ public abstract class Entity
|
|||
for (var i = 0; i < _activeConsumables.Count; i++)
|
||||
{
|
||||
_activeConsumables[i].Update(delta);
|
||||
if (_activeConsumables[i].RemainingDuration < 0)
|
||||
if (_activeConsumables[i].RemainingDuration <= 0)
|
||||
{
|
||||
// Cut 2 Gate 1 fix (docs/stats-and-power-cut.md): an expired consumable dropped out of this
|
||||
// list without ever telling the resolver, leaving its generation/cache/modifier entries
|
||||
// reachable (keyed by this ConsumableItemEffect instance) for the rest of the process.
|
||||
// A StatModifier's attachments are keyed by its target items, not by the effect, so Forget alone
|
||||
// leaves a boost attached to its targets: dispose each behaviour first.
|
||||
foreach (var behavior in _activeConsumables[i].Behaviors)
|
||||
if (behavior is IDisposable disposable)
|
||||
disposable.Dispose();
|
||||
Resolver.Forget(_activeConsumables[i]);
|
||||
_activeConsumables.RemoveAt(i--);
|
||||
}
|
||||
|
|
@ -1475,12 +1971,22 @@ public abstract class Entity
|
|||
Position = Parent.Position;
|
||||
Velocity = Parent.Velocity;
|
||||
}
|
||||
else Position.y = Zone.GetHeight(Position.xz) + hullData.GridOffset;
|
||||
else Position.y = RideHeight(Position.xz);
|
||||
|
||||
Acceleration = delta > 0f ? (Velocity + LimitClamp - velocityBefore) / delta : float2(0, 0);
|
||||
Manoeuvre.Observe(Acceleration, delta, ItemManager.GameplaySettings.SolutionWindow);
|
||||
}
|
||||
|
||||
// The height above the field of the layer this kind of entity rides on (GameplaySettings): ships the ship plane,
|
||||
// orbital entities the orbital layer above it.
|
||||
public abstract float LayerHeight { get; }
|
||||
|
||||
// Where an unparented entity sits on the field at a planar point: the zone's height there plus the layer this kind of
|
||||
// entity rides on. The step rides at its own time and xz, the presenter at the drawn time and its drawn xz (DrawAhead).
|
||||
public float RideHeight(float2 planar, double time) => Zone.GetHeight(planar, time) + LayerHeight;
|
||||
|
||||
public float RideHeight(float2 planar) => RideHeight(planar, Zone.ExactTime);
|
||||
|
||||
private void UpdateTemperature(float delta)
|
||||
{
|
||||
var hullData = ItemManager.GetData(Hull) as HullData;
|
||||
|
|
@ -1562,7 +2068,7 @@ public abstract class Entity
|
|||
MaxTemp = NewTemperature[v.x, v.y];
|
||||
}
|
||||
|
||||
VisibilitySources[this] = radiation;
|
||||
SetSignature(this, SignatureChannel.Thermal, radiation, null);
|
||||
var swap = Temperature;
|
||||
Temperature = NewTemperature;
|
||||
NewTemperature = swap;
|
||||
|
|
@ -1646,7 +2152,6 @@ public class EquippedItem : IStatContext
|
|||
|
||||
private bool _thermalOnline;
|
||||
private bool _durabilityOnline;
|
||||
public WwiseMetaSoundBank SoundBank;
|
||||
|
||||
public Behavior[] Behaviors { get; }
|
||||
public Dictionary<int, BehaviorGroup> BehaviorGroups { get; }
|
||||
|
|
@ -1672,10 +2177,6 @@ public class EquippedItem : IStatContext
|
|||
public ReadOnlyReactiveProperty<bool> Active { get; }
|
||||
public ItemManager ItemManager { get; }
|
||||
|
||||
public Subject<uint> AudioEvents { get; } = new Subject<uint>();
|
||||
public Subject<(uint id, float v)> AudioParameters { get; } = new Subject<(uint id, float v)>();
|
||||
public Dictionary<uint, float> AudioParameterValues { get; } = new Dictionary<uint, float>();
|
||||
|
||||
private float oldTemperature;
|
||||
public float Temperature
|
||||
{
|
||||
|
|
@ -1687,77 +2188,6 @@ public class EquippedItem : IStatContext
|
|||
}
|
||||
}
|
||||
|
||||
public void FireAudioEvent(uint eventId, bool skipVerify = false)
|
||||
{
|
||||
if(SoundBank != null && (skipVerify || SoundBank.IncludedEvents.Any(o => o.Id == eventId)))
|
||||
AudioEvents.OnNext(eventId);
|
||||
}
|
||||
|
||||
public void FireAudioEvent(WwiseSoundBinding soundBinding)
|
||||
{
|
||||
FireAudioEvent(soundBinding.PlayEvent);
|
||||
}
|
||||
|
||||
public void PlaySound(WwiseLoopingSoundBinding soundBinding)
|
||||
{
|
||||
FireAudioEvent(soundBinding.PlayEvent);
|
||||
}
|
||||
|
||||
public void StopSound(WwiseLoopingSoundBinding soundBinding)
|
||||
{
|
||||
FireAudioEvent(soundBinding.StopEvent);
|
||||
}
|
||||
|
||||
public void FireAudioEvent(WeaponAudioEvent weaponAudioEvent)
|
||||
{
|
||||
if (SoundBank == null) return;
|
||||
var eventObject = SoundBank.GetEvent(weaponAudioEvent);
|
||||
if (eventObject == null)
|
||||
{
|
||||
ItemManager.Log($"Attempted to trigger {Enum.GetName(typeof(WeaponAudioEvent), weaponAudioEvent)} weapon audio event, but the soundbank doesn't support it!");
|
||||
return;
|
||||
}
|
||||
FireAudioEvent(eventObject.Id, true);
|
||||
}
|
||||
|
||||
public void FireAudioEvent(ChargedWeaponAudioEvent weaponAudioEvent)
|
||||
{
|
||||
if (SoundBank == null) return;
|
||||
var eventObject = SoundBank.GetEvent(weaponAudioEvent);
|
||||
if (eventObject == null)
|
||||
{
|
||||
ItemManager.Log($"Attempted to trigger {Enum.GetName(typeof(ChargedWeaponAudioEvent), weaponAudioEvent)} weapon audio event, but the soundbank doesn't support it!");
|
||||
return;
|
||||
}
|
||||
FireAudioEvent(eventObject.Id, true);
|
||||
}
|
||||
|
||||
public void SetAudioParameter(uint id, float v, bool skipVerify = false)
|
||||
{
|
||||
if (SoundBank != null && (skipVerify || SoundBank.GameParameters.Any(o => o.Id == id)))
|
||||
{
|
||||
AudioParameterValues[id] = v;
|
||||
AudioParameters.OnNext((id, v));
|
||||
}
|
||||
}
|
||||
|
||||
// public void SetAudioParameter(WwiseParameterBinding binding)
|
||||
// {
|
||||
// FireAudioEvent(binding.Parameter);
|
||||
// }
|
||||
|
||||
public void SetAudioParameter(SpecialAudioParameter p, float v)
|
||||
{
|
||||
if (SoundBank == null) return;
|
||||
var metaObject = SoundBank.GetParameter(p);
|
||||
if (metaObject == null)
|
||||
{
|
||||
ItemManager.Log($"Attempted to set {Enum.GetName(typeof(ChargedWeaponAudioEvent), p)} audio parameter, but the soundbank doesn't support it!");
|
||||
return;
|
||||
}
|
||||
SetAudioParameter(metaObject.Id, v, true);
|
||||
}
|
||||
|
||||
public EquippedItem(ItemManager itemManager, EquippableItem item, int2 position, Entity entity, HardpointData hardpoint)
|
||||
{
|
||||
ItemManager = itemManager;
|
||||
|
|
@ -1821,7 +2251,7 @@ public class EquippedItem : IStatContext
|
|||
// RefreshInputCapacitor implementation now calls for a request-field stat, and it pins that stat's own
|
||||
// PowerSupplyFactor to 1 regardless of what Terms the stat declares -- so a direct PowerSupply term on a
|
||||
// request field can no longer make the request depend on its own answer, and the six shipped records this
|
||||
// ruling exists to make legal again (RadiatorData.PumpedHeat, AetherDriveData.Torque) are not an authoring
|
||||
// ruling exists to make legal again (RadiatorData.PumpedHeat) are not an authoring
|
||||
// error to refuse. What is still refused: a request field fed a PowerSupply-tainted value through a
|
||||
// *modifier chain* (StatModifier.ValidateNoPowerSupplyChain, StatModifier.cs) -- EvaluateNominalPower
|
||||
// forwards ScaleModifier/ConstantModifier to the item's real, non-nominal resolver entries (same as
|
||||
|
|
@ -1837,8 +2267,8 @@ public class EquippedItem : IStatContext
|
|||
// Nominal-request ruling (docs/stats-and-power-cut.md, operator ruling 2026-09-19): what this item wants at
|
||||
// full power supply, not what it is currently managing -- the read every PowerRequest/RefreshReserve/
|
||||
// RefreshInputCapacitor implementation uses for a stat named in StatValidation.PowerRequestFields, so a stat
|
||||
// that is both what a request asks for and what it also produces (RadiatorData.PumpedHeat, AetherDriveData.
|
||||
// Torque) stops being circular at the root instead of being forbidden outright. Only PowerSupply is pinned:
|
||||
// that is both what a request asks for and what it also produces (RadiatorData.PumpedHeat)
|
||||
// stops being circular at the root instead of being forbidden outright. Only PowerSupply is pinned:
|
||||
// Heat and Durability are NOT, because they are not the term a request would be circular through -- this
|
||||
// tick's PowerBus.Step (which calls PowerRequest) always runs before this tick's grant exists, so nothing
|
||||
// here could depend on an answer that has not been computed yet, and a hot or worn item honestly asking for
|
||||
|
|
@ -1951,17 +2381,12 @@ public class EquippedItem : IStatContext
|
|||
deltaTemp * ItemManager.GameplaySettings.DeltaTempWearExponent
|
||||
) * Data.Durability / Data.ThermalResilience;
|
||||
ThermalOnline.Value = ThermalPerformance > performanceThreshold || Entity.OverrideShutdown && EquippableItem.OverrideShutdown;
|
||||
DurabilityOnline.Value = EquippableItem.Durability > .01f;
|
||||
DurabilityOnline.Value = !EquippableItem.IsDestroyed;
|
||||
oldTemperature = temp;
|
||||
}
|
||||
|
||||
public void Update(float delta)
|
||||
{
|
||||
foreach (var audioStat in Data.AudioStats)
|
||||
{
|
||||
SetAudioParameter(audioStat.Parameter, Evaluate(audioStat.Stat));
|
||||
}
|
||||
|
||||
if (Active.Value)
|
||||
{
|
||||
foreach (var group in BehaviorGroups.Values)
|
||||
|
|
@ -2126,7 +2551,7 @@ public class EquippedCargoBay : EquippedItem
|
|||
// Returns true only when ALL of the items are successfully stored
|
||||
public bool TryStore(SimpleCommodity item)
|
||||
{
|
||||
TryFindSpace(item, out var positions);
|
||||
if (!TryFindSpace(item, out var positions)) return false;
|
||||
foreach (var position in positions)
|
||||
{
|
||||
if (TryStore(item, position)) return true;
|
||||
|
|
@ -2332,6 +2757,4 @@ public class BehaviorGroup
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
//public IAnalogBehavior Axis;
|
||||
}
|
||||
|
|
@ -28,6 +28,7 @@ public static class EntitySerializer
|
|||
else throw new ArgumentException("Attempted to pack an instance of abstract class Entity!");
|
||||
|
||||
pack.Settings = entity.Settings;
|
||||
pack.Boss = entity.IsBoss;
|
||||
|
||||
pack.Hull = entity.Hull;
|
||||
pack.Name = entity.Name;
|
||||
|
|
@ -81,6 +82,7 @@ public static class EntitySerializer
|
|||
private static void Restore(ItemManager itemManager, Zone zone, EntityPack pack, Entity entity)
|
||||
{
|
||||
entity.Name = pack.Name;
|
||||
entity.IsBoss = pack.Boss;
|
||||
entity.Faction = itemManager.ItemData.Get(pack.Faction);
|
||||
entity.Children = pack.Children.Select(c =>
|
||||
{
|
||||
|
|
@ -187,6 +189,8 @@ public abstract class EntityPack
|
|||
[Key(14)] public EntitySettings Settings;
|
||||
[Key(15)] public CultRecordRef<Faction> Faction;
|
||||
[Key(16)] public int[][] WeaponGroups;
|
||||
// Keys 17-20 belong to the subclasses; the base's next free key is 21.
|
||||
[Key(21)] public bool Boss;
|
||||
|
||||
private int _price;
|
||||
|
||||
|
|
|
|||
|
|
@ -49,8 +49,7 @@ public enum HardpointType
|
|||
Energy,
|
||||
Ballistic,
|
||||
Launcher,
|
||||
ControlModule,
|
||||
AetherDrive
|
||||
ControlModule
|
||||
}
|
||||
|
||||
public enum WeaponType
|
||||
|
|
@ -204,34 +203,6 @@ public enum TemperatureUnit
|
|||
Fahrenheit
|
||||
}
|
||||
|
||||
public enum WeaponAudioEvent
|
||||
{
|
||||
Fire,
|
||||
Hit,
|
||||
Miss
|
||||
}
|
||||
|
||||
public enum ChargedWeaponAudioEvent
|
||||
{
|
||||
Start,
|
||||
Stop,
|
||||
Fail
|
||||
}
|
||||
|
||||
public enum SpecialAudioParameter
|
||||
{
|
||||
ShipVelocity,
|
||||
ChargeLevel,
|
||||
TargetLock,
|
||||
Intensity,
|
||||
}
|
||||
|
||||
public enum LoopingAudioEvent
|
||||
{
|
||||
Play,
|
||||
Stop
|
||||
}
|
||||
|
||||
public enum MusicType
|
||||
{
|
||||
Overworld,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ using float2 = CultMath.float2;
|
|||
public class ZoneEnvironment
|
||||
{
|
||||
[JsonProperty("nebula"), Key(0)] public NebulaSettings Nebula;
|
||||
[JsonProperty("flow"), Key(1)] public FlowSettings Flow;
|
||||
// Key 1 is retired (it held the flow, now PlanetSettings.Flow); never reuse it.
|
||||
[JsonProperty("noise"), Key(2)] public NoiseSettings Noise;
|
||||
[JsonProperty("lighting"), Key(3)] public AmbientLightingSettings Lighting;
|
||||
[JsonProperty("grid"), Key(4)] public GridSettings Grid;
|
||||
|
|
|
|||
40
Assets/Scripts/ServerShared/Feedback.cs
Normal file
40
Assets/Scripts/ServerShared/Feedback.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/* 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 CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
// What an impact presenter renders, derived once. Engine-free and never called by ServerShared: FireControl
|
||||
// publishes the fact (AbsorbEvent), this derives how it reads, and every presenter (visual, audio, camera) renders
|
||||
// the same cue instead of computing its own.
|
||||
public readonly struct ImpactCue
|
||||
{
|
||||
public readonly AbsorbLayer Layer;
|
||||
public readonly float3 Position;
|
||||
public readonly float3 Direction;
|
||||
public readonly float Intensity;
|
||||
public readonly float Shake;
|
||||
|
||||
public ImpactCue(AbsorbLayer layer, float3 position, float3 direction, float intensity, float shake)
|
||||
{
|
||||
Layer = layer;
|
||||
Position = position;
|
||||
Direction = direction;
|
||||
Intensity = intensity;
|
||||
Shake = shake;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Feedback
|
||||
{
|
||||
// Intensity is the hit's share of what the receiver's hull can take, scaled by the presenter and saturated to
|
||||
// 0..1; a receiver with no hull to measure against reads 0. Shake follows intensity for the player's own ship
|
||||
// only, scaled by the player's ScreenShake preference.
|
||||
public static ImpactCue Cue(AbsorbEvent e, float receiverMaxDurability, bool receiverIsPlayer, float shakePreference, float intensityScale)
|
||||
{
|
||||
var intensity = receiverMaxDurability > 0f ? saturate(e.Magnitude / receiverMaxDurability * intensityScale) : 0f;
|
||||
var shake = receiverIsPlayer ? intensity * saturate(shakePreference) : 0f;
|
||||
return new ImpactCue(e.Layer, e.Position, e.Direction, intensity, shake);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Feedback.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Feedback.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 51efa531176e4871835ae88104c92c85
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -67,24 +67,18 @@ public static class FireControl
|
|||
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.
|
||||
// Mining Cut 3: a chunk target bears through its own position, on the plane the bearing test reads.
|
||||
// The one gate on the trigger (operator rulings fire-on-solutions, controls-solution-trigger, 2026-10-06). A gun
|
||||
// fires on its solution without the aim, else free along the aim if the aim is inside its arc, else it holds.
|
||||
// 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 mine layer
|
||||
// lays a body, not a round, and is never arc-gated. The price of a free shot at a target that does not bear is
|
||||
// HitProbability's: zero.
|
||||
public static bool ArcPermitsFire(Weapon weapon, Entity shooter)
|
||||
{
|
||||
var target = shooter.Target.Value;
|
||||
if (target.IsNone) return true;
|
||||
float3 toTarget;
|
||||
if (target.Chunk is ChunkId chunk)
|
||||
{
|
||||
var at = shooter.Zone.ChunkPose(chunk.Field, chunk.Index).xy;
|
||||
toTarget = float3(at.x, 0, at.y) - shooter.Position;
|
||||
}
|
||||
else toTarget = target.Entity.Position - shooter.Position;
|
||||
return FuseOf(weapon.Item, out _) != null || IsMineLayer(weapon) || InArc(weapon.Item, toTarget);
|
||||
if (FuseOf(weapon.Item, out _) != null || IsMineLayer(weapon)) return true;
|
||||
var solution = Solution(weapon, shooter, shooter.Target.Value);
|
||||
return solution.Bears || solution.Free;
|
||||
}
|
||||
|
||||
// Whether the shooter's next round from this weapon is refused: the weapons ask before they spend anything, so
|
||||
|
|
@ -132,36 +126,43 @@ public static class FireControl
|
|||
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.
|
||||
//
|
||||
// Ranking: the target's own non-hull equipment, hardpoint-mounted gear first (the big obvious things),
|
||||
// then by size descending, ties broken by equipment order (OrderByDescending is a stable sort, so this
|
||||
// needs no explicit tie-break key). Item i of N reveals once info crosses
|
||||
// lerp(TargetArmorInfoThreshold, TargetGearInfoThreshold, i / max(1, N - 1)) -- the first item to reveal
|
||||
// does so at the armor tier, the last at the gear tier.
|
||||
public static bool IsRevealed(Entity observer, EquippedItem item)
|
||||
// The one owner of a gun's solution against its subject (the designated target; ruling controls-solution-subject).
|
||||
// Bears: the gun can engage the subject, so the player fires on it without the aim. Free: the aim is inside the
|
||||
// arc, so the gun can fire along it. Direction: where a round from this gun travels and where its barrel points --
|
||||
// the subject's intercept when it bears, else the arc-clamped aim. A chunk subject bears through its pose and
|
||||
// flies the aim, as an untargeted round (Subject is null for it). Derived on every read and never stored: turrets
|
||||
// traverse instantly in the simulation. Traverse is the weapon's Tracking (ruling mount-arc-gun-traverse), priced in
|
||||
// TrackingRate; this holds no slew state, and a rig's slew is presentation. It never prices; HitProbability is the one price.
|
||||
public static GunSolution Solution(Weapon weapon, Entity shooter, TargetRef subject)
|
||||
{
|
||||
var target = item.Entity;
|
||||
// Cut 5, 5.5 (Soul finding 10): a destroyed item drops out of the ranking entirely rather than merely
|
||||
// failing its own tier -- ranked.IndexOf(item) then returns -1 for it (the same "no longer on this
|
||||
// target" path below), and the survivors' tiers close up over the gap instead of leaving one.
|
||||
var ranked = target.Equipment
|
||||
.Where(e => e.Data.HardpointType != HardpointType.Hull && e.EquippableItem.Durability >= .01f)
|
||||
.OrderByDescending(e => e.Data.HardpointType != HardpointType.Tool)
|
||||
.ThenByDescending(e => e.Data.Shape.Coordinates.Length)
|
||||
.ToList();
|
||||
var index = ranked.IndexOf(item);
|
||||
if (index < 0) return false; // the hull itself, or an item that is no longer on this target
|
||||
|
||||
var settings = observer.ItemManager.GameplaySettings;
|
||||
var info = observer.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f;
|
||||
var tier = lerp(settings.TargetArmorInfoThreshold, settings.TargetGearInfoThreshold,
|
||||
(float) index / max(1, ranked.Count - 1));
|
||||
return info >= tier;
|
||||
var bears = false;
|
||||
if (subject.Entity != null) bears = Bears(weapon, shooter, subject.Entity, out _);
|
||||
else if (subject.Chunk is ChunkId chunk)
|
||||
{
|
||||
var at = shooter.Zone.ChunkPose(chunk.Field, chunk.Index).xy;
|
||||
bears = InArc(weapon.Item, float3(at.x, 0, at.y) - shooter.Position);
|
||||
}
|
||||
return new GunSolution
|
||||
{
|
||||
Subject = subject.Entity,
|
||||
Bears = bears,
|
||||
Free = InArc(weapon.Item, shooter.Aim),
|
||||
Direction = bears && subject.Entity != null
|
||||
? TravelDirection(weapon, shooter, subject.Entity)
|
||||
: AimDirection(weapon.Item, shooter)
|
||||
};
|
||||
}
|
||||
|
||||
// The aiming read, and the only reader of live gear beside the book (rulings visibility-per-capability-reveal,
|
||||
// quiet-gear-identifiable-hull-layout-known, reveal-ends-on-perception): `observer` can aim at `item` when its own
|
||||
// book holds a reveal of it (Entity.HasReveal: it saw the item act) and the item is still fitted to its ship and
|
||||
// not destroyed. The book says what was seen; the live item says whether it can still be aimed at. Derived on
|
||||
// every read, never cached; watching a ship reveals no gear. Any aiming choice that reads an item's class or
|
||||
// stats (Combat's target-item choice, its dps) asks this; it is the item gate of Entity's aim slot (TrySelectTargetItem,
|
||||
// ResolvedAim). A mount is aimed by TrySelectMount, which reads no item at all.
|
||||
public static bool IsRevealed(Entity observer, EquippedItem item) =>
|
||||
!item.EquippableItem.IsDestroyed && item.Entity.Equipment.Contains(item) && observer.HasReveal(item.Entity, item);
|
||||
|
||||
// Cut 2, Q4: the stats an entity actually fires with. A working targeting system (equipped, online --
|
||||
// not destroyed, not shut down) supplies its own resolved stats; anything else falls back to the
|
||||
// authored unaided figures, which make aiming without one a last resort rather than an alternative.
|
||||
|
|
@ -277,21 +278,26 @@ public static class FireControl
|
|||
!(weapon is LockWeapon lockWeapon && !lockWeapon.IsLocked);
|
||||
}
|
||||
|
||||
// `designated` is the answer above. `inArc` is the bearing test, asked only once a target is designated.
|
||||
// Whether this gun can engage this target: designated and inside the arc. The one test of it; PFire prices a shot
|
||||
// at zero unless it holds, and Solution reads it to decide whether the gun fires on the target. `designated` is
|
||||
// the answer above, kept apart for Solve's burst flight: a designated target out of arc still sets the burst range.
|
||||
public static bool Bears(Weapon weapon, Entity source, Entity target, out float range) =>
|
||||
Bears(weapon, source, target, out range, out _);
|
||||
|
||||
private static bool Bears(Weapon weapon, Entity source, Entity target, out float range, out bool designated)
|
||||
{
|
||||
designated = Designated(weapon, source, target, out range);
|
||||
return designated && InArc(weapon.Item, target.Position - source.Position);
|
||||
}
|
||||
|
||||
// `designated` is the answer above. `inArc` is Bears, 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;
|
||||
|
||||
designated = Designated(weapon, source, target, out range);
|
||||
if (!designated) return 0f;
|
||||
inArc = InArc(weapon.Item, target.Position - source.Position);
|
||||
inArc = Bears(weapon, source, target, out range, out designated);
|
||||
if (!inArc) return 0f;
|
||||
|
||||
var settings = source.ItemManager.GameplaySettings;
|
||||
|
|
@ -316,8 +322,8 @@ public static class FireControl
|
|||
// GetBehavior<TargetingSystem> calls (Accuracy, Resolution via PSensor, Precision), at ~40 B each -- each
|
||||
// one walks Entity.Equipment, a ReactiveCollection<T> whose enumerator is heap-allocated per foreach. It is
|
||||
// NOT `Behaviors` (the earlier wording here was wrong): EquippedItem.Behaviors is a plain array, allocates
|
||||
// nothing to enumerate. With an item aimed at, ResolveAimPoint -> CellsOf also allocates (a List, then
|
||||
// ToArray) -- about 944 B per HitProbability, on top of the three GetBehavior calls. None of this is
|
||||
// nothing to enumerate. With an item or a mount aimed at, ResolveAimPoint also allocates: CellsOf (a List, then
|
||||
// ToArray) about 944 B per HitProbability, measured; MountCells (a LINQ Select, then ToArray) not measured. Both are on top of the three GetBehavior calls. None of this is
|
||||
// Silhouette's or this pooling's cost; it predates Cut 12.2 and belongs to Entity's own collection choice
|
||||
// and to CellsOf, out of this cut's scope. Cut 10's own guard is what actually matters
|
||||
// operationally: HitProbability and CommitProbability both bail before Forecast is ever called for the
|
||||
|
|
@ -334,7 +340,8 @@ public static class FireControl
|
|||
Silhouette sil;
|
||||
try
|
||||
{
|
||||
sil = Silhouette(target, targetHull, source.ResolvedTargetItem, bearing, precision, buffer);
|
||||
var aim = source.ResolvedAim;
|
||||
sil = Silhouette(target, targetHull, aim.Item, bearing, precision, buffer, aim.Mount);
|
||||
var settings = source.ItemManager.GameplaySettings;
|
||||
pSpread = PSpread(weapon.Spread, sil.Span, range, settings.SchematicCellSize);
|
||||
}
|
||||
|
|
@ -581,7 +588,8 @@ public static class FireControl
|
|||
// 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
|
||||
// BurstReach the planar distance from the shooter at which the payload is delivered (a direct round's target, a fused
|
||||
// round's burst point, 0 for an untargeted direct round), which Fire's range factor reads for every outcome. 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)
|
||||
{
|
||||
|
|
@ -616,7 +624,7 @@ public static class FireControl
|
|||
// 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 travelDirection = Solution(weapon, source, target).Direction;
|
||||
|
||||
var arming = fuse != null ? blastRadius : 0f;
|
||||
var burstPosition = engaged != null ? engaged.Position : origin;
|
||||
|
|
@ -712,14 +720,19 @@ public static class FireControl
|
|||
|
||||
var commitHorizon = source.ItemManager.GameplaySettings.CommitHorizon;
|
||||
|
||||
var aim = source.ResolvedAim;
|
||||
var shot = new PendingShot
|
||||
{
|
||||
ShotId = zone.NextShotId(),
|
||||
Source = source,
|
||||
Target = engaged,
|
||||
Weapon = item,
|
||||
Aimed = source.ResolvedTargetItem,
|
||||
Aimed = aim.Item,
|
||||
AimedMount = aim.Mount,
|
||||
Damage = damageOverride ?? weapon.Damage,
|
||||
FireMinRange = weapon.MinRange,
|
||||
FireEffectiveRange = weapon.EffectiveRange,
|
||||
FireDamageAtMaxRange = weapon.WeaponData.DamageAtMaxRange,
|
||||
Penetration = weapon.Penetration,
|
||||
DamageSpread = weapon.DamageSpread,
|
||||
DamageType = weapon.WeaponData.DamageType,
|
||||
|
|
@ -730,6 +743,8 @@ public static class FireControl
|
|||
Spread = weapon.Spread,
|
||||
FireRange = fireRange,
|
||||
FireTime = now,
|
||||
Speed = weapon.Velocity,
|
||||
MaxRange = weapon.Range,
|
||||
FireOrigin = origin,
|
||||
FireTargetPosition = targetPosition,
|
||||
FireTargetVelocity = targetVelocity,
|
||||
|
|
@ -743,11 +758,20 @@ public static class FireControl
|
|||
BlastRadius = blastRadius,
|
||||
Committed = false
|
||||
};
|
||||
// A round whose delivery point Solve plans reads the falloff here, at that point (BurstReach); a no-lock fused round's
|
||||
// point is decided at its commit (CommitBurst), which reads it there. Each shot reads it once.
|
||||
if (!shot.DeliveredAtCommit) Deliver(ref shot, solution.BurstReach);
|
||||
|
||||
zone.PendingShots.Add(shot);
|
||||
return shot.ShotId;
|
||||
}
|
||||
|
||||
// The one place a shot's damage meets range: the weapon's falloff at the planar distance its payload is delivered at,
|
||||
// over the stats frozen at Fire. A delivery is never farther than the Range it was fired with (a burst is pulled back to
|
||||
// it), so rounding in its distance must not read as beyond it.
|
||||
private static void Deliver(ref PendingShot shot, float reach) =>
|
||||
shot.Damage *= WeaponData.RangeFactor(shot.FireMinRange, shot.FireEffectiveRange, shot.MaxRange, shot.FireDamageAtMaxRange, min(reach, shot.MaxRange));
|
||||
|
||||
// Lays a mine for a mine layer: freezes the payload as evaluated now (stats, the item's blast radius, the
|
||||
// layer and its faction) and hands the body to Zone.Lay, the one adder. It launches at the shooter's velocity
|
||||
// plus the mount direction turned by a dice angle within +-Spread/2, times Velocity; the dice are the mine's
|
||||
|
|
@ -779,6 +803,8 @@ public static class FireControl
|
|||
FuseDelay = data.FuseDelay,
|
||||
Lifetime = data.Lifetime,
|
||||
BlastRadius = blastRadius,
|
||||
// Mines are flat (ruling effective-range-authoring-ruled): a mine layer carries no falloff authoring
|
||||
// (StatValidation.ValidateMineLayerFlat), so its figure is the AI's and the panel's at every distance it can engage.
|
||||
Damage = weapon.Damage,
|
||||
DamageType = weapon.WeaponData.DamageType,
|
||||
Layer = source,
|
||||
|
|
@ -823,11 +849,13 @@ public static class FireControl
|
|||
|
||||
if (!shot.Committed && now >= shot.CommitTime)
|
||||
{
|
||||
shot.Outcome = Commit(zone, shot, now);
|
||||
shot.Outcome = Commit(zone, ref shot, now);
|
||||
shot.Committed = true;
|
||||
// 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);
|
||||
// Written back before ShotCommitted fires: a presenter re-reading the record there (Zone.TryGetShot) sees
|
||||
// the committed ArrivalTime a contact burst has just shortened.
|
||||
shots[i] = shot;
|
||||
zone.ShotCommitted.OnNext(shot.Outcome);
|
||||
}
|
||||
|
|
@ -873,16 +901,16 @@ public static class FireControl
|
|||
|
||||
var bearing = Bearing(shot.Target, shot.TravelDirection);
|
||||
var hullData = shot.Target.ItemManager.GetData(shot.Target.Hull) as HullData;
|
||||
sil = Silhouette(shot.Target, hullData, shot.Aimed, bearing, shot.Precision);
|
||||
sil = Silhouette(shot.Target, hullData, shot.Aimed, bearing, shot.Precision, null, shot.AimedMount);
|
||||
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)
|
||||
private static ShotOutcome Commit(Zone zone, ref 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);
|
||||
if (shot.DeliveredAtCommit) return CommitBurst(zone, ref 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) --
|
||||
|
|
@ -974,12 +1002,14 @@ public static class FireControl
|
|||
// 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)
|
||||
private static ShotOutcome CommitBurst(Zone zone, ref 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));
|
||||
// The delivery point is decided here, so the falloff is read here, at the distance the round travelled to it.
|
||||
Deliver(ref shot, travelled);
|
||||
if (travelled < reach)
|
||||
{
|
||||
outcome.BurstPoint = shot.FireOrigin.xz + shot.TravelDirection * travelled;
|
||||
|
|
@ -1134,6 +1164,8 @@ public static class FireControl
|
|||
|
||||
if (shot.Outcome.Shielded)
|
||||
{
|
||||
Publish(shot.Target, AbsorbLayer.Shield, ImpactPoint(shot.Target, shot.Outcome.Cell),
|
||||
float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType);
|
||||
shot.Target.Shield.TakeHit(shot.DamageType, shot.Damage);
|
||||
return;
|
||||
}
|
||||
|
|
@ -1177,9 +1209,31 @@ public static class FireControl
|
|||
|
||||
for (var li = 0; li < laneCount; li++) ArrayPool<LaneCell>.Shared.Return(buffers[li]);
|
||||
|
||||
Publish(target, AbsorbLayer.Hull, ImpactPoint(target, shot.Outcome.Cell),
|
||||
float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType);
|
||||
target.DamageHull(hullDamage);
|
||||
}
|
||||
|
||||
// Where a landed direct hit meets the receiver: the impact cell's world point on its sim pose, at its height.
|
||||
private static float3 ImpactPoint(Entity target, int2 cell)
|
||||
{
|
||||
var world = target.ToWorldPoint((float2) cell);
|
||||
return float3(world.x, target.Position.y, world.y);
|
||||
}
|
||||
|
||||
// The one publisher of an absorbed impact: once per receiver, on its Capabilities, before the damage it reports.
|
||||
private static void Publish(Entity receiver, AbsorbLayer layer, float3 position, float3 direction, float magnitude, DamageType damageType) =>
|
||||
receiver.Capabilities.PublishAbsorb(new AbsorbEvent(position, direction, magnitude, damageType, layer));
|
||||
|
||||
// A blast's impact on one entity: at the blast point (on the entity's height), travelling from the blast out through
|
||||
// the entity's centre, or zero when they coincide.
|
||||
private static void PublishBlast(Entity entity, float2 blast, AbsorbLayer layer, float magnitude, DamageType damageType)
|
||||
{
|
||||
var away = entity.Position.xz - blast;
|
||||
var direction = lengthsq(away) > 0f ? normalize(away) : float2.zero;
|
||||
Publish(entity, layer, float3(blast.x, entity.Position.y, blast.y), float3(direction.x, 0, direction.y), magnitude, damageType);
|
||||
}
|
||||
|
||||
// Cut 12.4(b) (docs/fire-control-cut.md, "Where P is"): a contact or delayed blast needs a committed hit --
|
||||
// on a miss nothing happens, exactly like a direct hit's own gate. IncomingHit fires once, for the host,
|
||||
// before the blast is handed to Detonate (which then treats the host like any other entity in the radius:
|
||||
|
|
@ -1562,6 +1616,7 @@ public static class FireControl
|
|||
{
|
||||
if (shield.CanTakeHit(damageType, totalShare))
|
||||
{
|
||||
PublishBlast(entity, worldPlanar, AbsorbLayer.Shield, totalShare, damageType);
|
||||
shield.TakeHit(damageType, totalShare);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -1591,6 +1646,7 @@ public static class FireControl
|
|||
for (var i = 0; i < amounts.Length; i++) hullTotal += amounts[i];
|
||||
}
|
||||
|
||||
PublishBlast(entity, worldPlanar, AbsorbLayer.Hull, totalShare, damageType);
|
||||
entity.DamageHull(hullTotal);
|
||||
}
|
||||
}
|
||||
|
|
@ -1712,12 +1768,13 @@ public static class FireControl
|
|||
private const float SigmaFloor = 0.5f;
|
||||
private static float Sigma(float precision) => max(1f / max(precision, 1e-3f), SigmaFloor);
|
||||
|
||||
// The aim point a silhouette is centred on (R10/Q6: the same frozen Aimed both HitProbability and Fire
|
||||
// read) -- the aimed item's own cell centroid when it currently occupies cells on the target, else the
|
||||
// hull's own centre of mass. One path; the uniform-random branch Cut 6d replaced stays deleted.
|
||||
private static float2 ResolveAimPoint(Entity target, HullData hullData, EquippedItem aimed)
|
||||
// The aim point a silhouette is centred on (R10/Q6: the same frozen Aimed and AimedMount both HitProbability and Fire
|
||||
// read) -- the cells of the mount aimed at when the aim was frozen at a mount (the shooter has not learned what is
|
||||
// fitted there, so never the fitted item's cells), else the aimed item's own cell centroid when it currently occupies
|
||||
// cells on the target, else the hull's own centre of mass. One path; the uniform-random branch Cut 6d replaced stays deleted.
|
||||
private static float2 ResolveAimPoint(Entity target, HullData hullData, EquippedItem aimed, HardpointData mount)
|
||||
{
|
||||
var aimedCells = aimed != null ? CellsOf(target, aimed) : null;
|
||||
var aimedCells = mount != null ? MountCells(mount) : aimed == null ? null : CellsOf(target, aimed);
|
||||
if (aimedCells != null && aimedCells.Length > 0)
|
||||
return aimedCells.Aggregate(float2.zero, (total, c) => total + (float2) c) / aimedCells.Length;
|
||||
return hullData.Shape.CenterOfMass;
|
||||
|
|
@ -1737,7 +1794,7 @@ public static class FireControl
|
|||
// call that follows, so it still passes null and gets an owned allocation. A caller-supplied buffer may be
|
||||
// larger than coords.Length (ArrayPool rents "at least"), so every loop below is bounded by coords.Length,
|
||||
// never buffer.Length.
|
||||
public static Silhouette Silhouette(Entity target, HullData hull, EquippedItem aimed, float2 bearing, float precision, Interval[] buffer = null)
|
||||
public static Silhouette Silhouette(Entity target, HullData hull, EquippedItem aimed, float2 bearing, float precision, Interval[] buffer = null, HardpointData mount = null)
|
||||
{
|
||||
var ell = Lateral(bearing);
|
||||
var coords = hull.Shape.Coordinates;
|
||||
|
|
@ -1759,7 +1816,7 @@ public static class FireControl
|
|||
}
|
||||
|
||||
var sigma = Sigma(precision);
|
||||
var aimPoint = ResolveAimPoint(target, hull, aimed);
|
||||
var aimPoint = ResolveAimPoint(target, hull, aimed, mount);
|
||||
var a = dot(aimPoint, ell);
|
||||
|
||||
var pOnHull = 0f;
|
||||
|
|
@ -1914,6 +1971,10 @@ public static class FireControl
|
|||
exit = min(exit, max(t1, t2));
|
||||
}
|
||||
|
||||
// The hull-schematic cells a hardpoint covers, laid as Entity builds its Hardpoints[,] grid.
|
||||
private static int2[] MountCells(HardpointData hardpoint) =>
|
||||
hardpoint.Shape.Coordinates.Select(c => hardpoint.Position + c).ToArray();
|
||||
|
||||
// The cells of the target's hull schematic actually occupied by `item` -- GearOccupancy is the one source
|
||||
// of truth for where an equipped item's footprint lands, the same table Detonate and ApplyPooled read.
|
||||
private static int2[] CellsOf(Entity target, EquippedItem item)
|
||||
|
|
@ -1938,10 +1999,18 @@ public struct PendingShot
|
|||
public Entity Target;
|
||||
public EquippedItem Weapon;
|
||||
public EquippedItem Aimed;
|
||||
// The mount the aim was at, when it was at a mount rather than an item (Entity.ResolvedAim at Fire), frozen with Aimed:
|
||||
// a reveal between Fire and Commit does not move where this shot was aimed. Null for an item aim or none.
|
||||
public HardpointData AimedMount;
|
||||
|
||||
// The frozen payload (R10, Q6): the gun's own stats at the instant the trigger was pulled. Nothing
|
||||
// downstream re-evaluates any of these.
|
||||
public float Damage;
|
||||
// The weapon's falloff stats at Fire (with MaxRange below), frozen like the rest: what the range factor reads, at Fire or
|
||||
// at commit.
|
||||
public float FireMinRange;
|
||||
public float FireEffectiveRange;
|
||||
public float FireDamageAtMaxRange;
|
||||
public float Penetration;
|
||||
public float DamageSpread;
|
||||
public DamageType DamageType;
|
||||
|
|
@ -1974,11 +2043,20 @@ public struct PendingShot
|
|||
public float3 FireTargetPosition;
|
||||
public float3 FireTargetVelocity;
|
||||
public float FireTime;
|
||||
// The weapon's Velocity at Fire, frozen with the rest so a presenter draws the same line whatever happens to the stat later.
|
||||
public float Speed;
|
||||
// The weapon's Range at Fire, likewise frozen: how far a presenter may draw a round that misses. FireRange above
|
||||
// is the distance to the engaged target (0 for a round with none), not how far a round that misses flies on.
|
||||
public float MaxRange;
|
||||
public float CommitTime;
|
||||
public float ArrivalTime;
|
||||
|
||||
public bool Committed;
|
||||
public ShotOutcome Outcome;
|
||||
|
||||
// A fused round with no target: where it bursts is decided at its commit (the first hull its aim line meets), so its
|
||||
// damage reads the falloff there rather than at Fire.
|
||||
public bool DeliveredAtCommit => Fuse != null && Target == null;
|
||||
}
|
||||
|
||||
// What a round does when fired (FireControl.Solve): Direct resolves against its target, Burst detonates at a
|
||||
|
|
@ -1990,8 +2068,18 @@ public enum FireOutcome
|
|||
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.
|
||||
// A gun's solution against its subject (FireControl.Solution): whether the gun bears on the subject, whether the
|
||||
// aim is free (inside the arc), and the direction a round from it travels.
|
||||
public struct GunSolution
|
||||
{
|
||||
public Entity Subject;
|
||||
public bool Bears;
|
||||
public bool Free;
|
||||
public float2 Direction;
|
||||
}
|
||||
|
||||
// Solve's answer. Outcome and BurstReach (planar distance from the shooter to the burst point; the HUD reads it for
|
||||
// Burst, Fire's range factor for both outcomes) are what the HUD shows; the rest is what Fire freezes into the PendingShot.
|
||||
public struct FireSolution
|
||||
{
|
||||
public FireOutcome Outcome;
|
||||
|
|
@ -2045,8 +2133,9 @@ public struct FireControlDiagnostic
|
|||
}
|
||||
|
||||
// What a ship can do at this instant, in its own frame: acceleration along each body axis (m/s^2) and the kinematic
|
||||
// turn rate each way (rad/s; turning toward the ship's right is Clockwise). Each propulsor reports its share with
|
||||
// its own Execute arithmetic and Ship sums them; nothing stores it. Zero is the envelope of anything that is not a Ship.
|
||||
// turn rate each way (rad/s; turning toward the ship's right is Clockwise). Ship derives it each update as the box
|
||||
// extremes of its thrusters' columns (Ship.RecalculateEnvelope); nothing stores it. Zero is the envelope of anything
|
||||
// that is not a Ship.
|
||||
public readonly struct ManoeuvreEnvelope
|
||||
{
|
||||
public readonly float Forward, Reverse, Left, Right, Clockwise, CounterClockwise;
|
||||
|
|
@ -2060,10 +2149,6 @@ public readonly struct ManoeuvreEnvelope
|
|||
Clockwise = clockwise;
|
||||
CounterClockwise = counterClockwise;
|
||||
}
|
||||
|
||||
public static ManoeuvreEnvelope operator +(ManoeuvreEnvelope a, ManoeuvreEnvelope b) => new ManoeuvreEnvelope(
|
||||
a.Forward + b.Forward, a.Reverse + b.Reverse, a.Left + b.Left, a.Right + b.Right,
|
||||
a.Clockwise + b.Clockwise, a.CounterClockwise + b.CounterClockwise);
|
||||
}
|
||||
|
||||
// How unpredictably an entity is changing its motion, observed from its measured acceleration. The trend is an
|
||||
|
|
|
|||
|
|
@ -40,3 +40,20 @@ public struct KinematicBody
|
|||
Position += (Velocity + Drift) * dt;
|
||||
}
|
||||
}
|
||||
|
||||
// An item adrift in a zone: a death drop or jettisoned cargo. Zone.Release is its only adder; Zone's floating-item
|
||||
// step (expiry) and TryPickUp are its only removers. Zone.TryHold and Free are the only writers of Holder, the
|
||||
// entity grabbing it with a tractor beam; a held item is placed by Zone, not drifted. Runtime state, never saved.
|
||||
public sealed class FloatingItem
|
||||
{
|
||||
public FloatingBodyId Id;
|
||||
public ItemInstance Item;
|
||||
public KinematicBody Body;
|
||||
public double ReleasedAt;
|
||||
public float Lifetime;
|
||||
// The entity holding it, or null when it floats free; HeldFrom is where it was claimed and HeldProgress how far
|
||||
// along its pull to the holder (0..1).
|
||||
public Entity Holder;
|
||||
public float2 HeldFrom;
|
||||
public float HeldProgress;
|
||||
}
|
||||
|
|
|
|||
78
Assets/Scripts/ServerShared/FlowField.cs
Normal file
78
Assets/Scripts/ServerShared/FlowField.cs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
using CultMath;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
using float3 = CultMath.float3;
|
||||
|
||||
/// <summary>
|
||||
/// The global flow law: the one definition of the drift that stardust and nebula follow and that the sim knows.
|
||||
/// A pure function of the zone's FlowSettings, a position, a scroll and a downhill gradient; nothing here keeps
|
||||
/// a clock. Zone.Flow evaluates it at zone time. Assets/Shaders/Volumetric.cginc (globalFlow, slopeFlow) is its
|
||||
/// HLSL lowering, driven by VolumeSampling.LowerFlow and pinned to it by Aetheria.EditorTools.FlowFieldParityVerify.
|
||||
/// </summary>
|
||||
public static class FlowField
|
||||
{
|
||||
// The second octave of the noise samples at position * Golden (Volumetric.cginc Tri3D).
|
||||
const float Golden = 1.61803398875f;
|
||||
|
||||
// The scroll of the noise field, in field units: speed times zone time, for each of the two octaves, as a phase.
|
||||
// Every term of Tri3D reaches the scrolled axis through frac, so a phase is only meaningful modulo 1: the fold
|
||||
// happens here in double, where zone time is exact, and the float that reaches the shaders is in [0, 1) however
|
||||
// old the zone is. x is the first octave's phase, y the second's (the second octave's axis is scaled by Golden).
|
||||
public static float2 Scroll(FlowSettings settings, double zoneTime)
|
||||
{
|
||||
var scroll = (double) settings.GlobalScrollSpeed * zoneTime;
|
||||
return float2(Phase(scroll), Phase(scroll * Golden));
|
||||
}
|
||||
|
||||
// A phase in [0, 1) strictly: a double just below an integer rounds up to 1f in the cast, and 1 is 0 modulo 1.
|
||||
static float Phase(double value)
|
||||
{
|
||||
var phase = (float) frac(value);
|
||||
return phase < 1f ? phase : 0f;
|
||||
}
|
||||
|
||||
// The phase of a cycle of `period` seconds at zone time, in [0, 1). The nebula's flow-advected noise cycles and
|
||||
// Stardust's particle lifetimes take their phase from here, so drift follows sim time and stops with the sim.
|
||||
public static float Cycle(double zoneTime, float period) => period == 0f ? 0f : Phase(zoneTime / period);
|
||||
|
||||
// The procedural term (Volumetric.cginc globalFlow): a Tri3D field of position / scale, scrolled along y.
|
||||
// Skipped when its amplitude is zero, as the shader's FLOW_GLOBAL keyword skips it.
|
||||
public static float3 Global(FlowSettings settings, float3 position, float2 scroll)
|
||||
{
|
||||
if (settings.GlobalAmplitude == 0f) return float3.zero;
|
||||
var field = position / settings.GlobalScale;
|
||||
var sample = Tri3D(field - float3(0f, scroll.x, 0f), field * Golden - float3(0f, scroll.y, 0f)) * settings.GlobalAmplitude;
|
||||
sample.y *= .5f;
|
||||
return sample;
|
||||
}
|
||||
|
||||
// The slope term (Volumetric.cginc slopeFlow): swirl around and slide along the gravity gradient.
|
||||
// `downhill` is the DOWNHILL gradient, -grad(height) in world xz. The shader's texel gradient is that same
|
||||
// vector (getUV negates the world x and z axes), and Zone.GetNormal's xz is proportional to it.
|
||||
// Skipped when both amplitudes are zero (the FLOW_SLOPE keyword), and zero for a zero gradient.
|
||||
public static float3 Slope(FlowSettings settings, float2 downhill)
|
||||
{
|
||||
if (settings.SlopeAmplitude == 0f && settings.SwirlAmplitude == 0f) return float3.zero;
|
||||
if (dot(downhill, downhill) == 0f) return float3.zero;
|
||||
var direction = normalize(downhill);
|
||||
return float3(direction.y, 0f, -direction.x) * settings.SwirlAmplitude
|
||||
+ float3(direction.x, 0f, direction.y) * settings.SlopeAmplitude;
|
||||
}
|
||||
|
||||
public static float3 At(FlowSettings settings, float3 position, float2 scroll, float2 downhill) =>
|
||||
Global(settings, position, scroll) + Slope(settings, downhill);
|
||||
|
||||
// Volumetric.cginc tri / tri3 / Tri3D, term for term.
|
||||
static float Tri(float x) => abs(frac(x) - .5f);
|
||||
|
||||
static float3 Tri3(float3 p) =>
|
||||
float3(Tri(p.z + Tri(p.y)), Tri(p.z + Tri(p.x)), Tri(p.y + Tri(p.x)));
|
||||
|
||||
// The two octaves' positions are given already scrolled (see Scroll).
|
||||
static float3 Tri3D(float3 p, float3 pGolden)
|
||||
{
|
||||
var t1 = normalize(Tri3(p));
|
||||
var t2 = normalize(Tri3(pGolden));
|
||||
return cross(t1, t2);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/ServerShared/FlowField.cs.meta
Normal file
2
Assets/Scripts/ServerShared/FlowField.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 8105a45840c4552459aaf44e6c0e19ce
|
||||
|
|
@ -24,7 +24,7 @@ public class Galaxy
|
|||
public Faction[] Factions { get; }
|
||||
public GalaxyZone[] Zones { get; }
|
||||
public GalaxyZone Entrance { get; }
|
||||
public GalaxyZone Exit { get; }
|
||||
public GalaxyZone Exit { get; private set; }
|
||||
public Dictionary<Faction, FactionRelationship> FactionRelationships { get; } = new Dictionary<Faction, FactionRelationship>();
|
||||
private Action<string> Log { get; }
|
||||
public bool IsPrelude { get; }
|
||||
|
|
@ -33,7 +33,6 @@ public class Galaxy
|
|||
// restored from a save.
|
||||
public uint Seed { get; }
|
||||
|
||||
private HashSet<CultRecordKey> _containedFactions;
|
||||
private GalaxyZone[] _exitPath;
|
||||
private Dictionary<Faction, MarkovNameGenerator> _nameGenerators = new Dictionary<Faction, MarkovNameGenerator>();
|
||||
private readonly CultCache _cache;
|
||||
|
|
@ -143,6 +142,18 @@ public class Galaxy
|
|||
return _cache.GetAll<Faction>().FirstOrDefault(f => f.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase));
|
||||
}
|
||||
|
||||
// A cast member of a prelude galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field.
|
||||
private Faction ResolveCast(string field, string name) =>
|
||||
ResolveFaction(name) ?? throw new InvalidOperationException($"cast faction {name} ({field}) is not in the catalog");
|
||||
|
||||
// Gives a prelude galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit
|
||||
// besides the constructors.
|
||||
public void PlaceGate(Faction antagonist)
|
||||
{
|
||||
BossZones[antagonist] = HomeZones[antagonist];
|
||||
Exit = HomeZones[antagonist];
|
||||
}
|
||||
|
||||
// How many jumps a faction's influence reaches in this galaxy: its authored distance, halved (rounding up) in a
|
||||
// prelude. Derived, never written back to the catalog's Faction, so one galaxy's generation cannot change the next.
|
||||
public int InfluenceOf(Faction faction) =>
|
||||
|
|
@ -169,20 +180,23 @@ public class Galaxy
|
|||
|
||||
var factions = new List<Faction>();
|
||||
|
||||
var protagonistFaction = ResolveFaction(settings.ProtagonistFaction);
|
||||
var protagonistFaction = ResolveCast(nameof(settings.ProtagonistFaction), settings.ProtagonistFaction);
|
||||
factions.Add(protagonistFaction);
|
||||
|
||||
var antagonistFaction = ResolveFaction(settings.AntagonistFaction);
|
||||
var antagonistFaction = ResolveCast(nameof(settings.AntagonistFaction), settings.AntagonistFaction);
|
||||
factions.Add(antagonistFaction);
|
||||
|
||||
var bufferFaction = ResolveFaction(settings.BufferFaction);
|
||||
var bufferFaction = ResolveCast(nameof(settings.BufferFaction), settings.BufferFaction);
|
||||
factions.Add(bufferFaction);
|
||||
|
||||
var questFaction = ResolveFaction(settings.QuestFaction);
|
||||
factions.Add(questFaction);
|
||||
// A cast without a quest faction places no quest zone.
|
||||
var questFaction = string.IsNullOrEmpty(settings.QuestFaction)
|
||||
? null
|
||||
: ResolveCast(nameof(settings.QuestFaction), settings.QuestFaction);
|
||||
if (questFaction != null) factions.Add(questFaction);
|
||||
|
||||
var neutralFactions = settings.NeutralFactions
|
||||
.Select(ResolveFaction)
|
||||
.Select(name => ResolveCast(nameof(settings.NeutralFactions), name))
|
||||
.ToArray();
|
||||
factions.AddRange(neutralFactions);
|
||||
|
||||
|
|
@ -223,17 +237,20 @@ public class Galaxy
|
|||
|
||||
CalculateFactionInfluence(progressCallback);
|
||||
|
||||
var potentialQuestZones = Zones
|
||||
.Where(z => z.Factions.Contains(antagonistFaction) && z.Factions.Contains(bufferFaction));
|
||||
if (potentialQuestZones.Any())
|
||||
HomeZones[questFaction] = potentialQuestZones
|
||||
.MaxBy(z => z.Distance[HomeZones[antagonistFaction]] * ConnectedRegion(z, InfluenceOf(questFaction)).Count);
|
||||
else
|
||||
HomeZones[questFaction] = Zones
|
||||
.Where(z => z.Factions.Contains(antagonistFaction))
|
||||
.MinBy(z=>z.Distance[HomeZones[bufferFaction]]);
|
||||
|
||||
CalculateFactionInfluence(progressCallback);
|
||||
if (questFaction != null)
|
||||
{
|
||||
var potentialQuestZones = Zones
|
||||
.Where(z => z.Factions.Contains(antagonistFaction) && z.Factions.Contains(bufferFaction));
|
||||
if (potentialQuestZones.Any())
|
||||
HomeZones[questFaction] = potentialQuestZones
|
||||
.MaxBy(z => z.Distance[HomeZones[antagonistFaction]] * ConnectedRegion(z, InfluenceOf(questFaction)).Count);
|
||||
else
|
||||
HomeZones[questFaction] = Zones
|
||||
.Where(z => z.Factions.Contains(antagonistFaction))
|
||||
.MinBy(z=>z.Distance[HomeZones[bufferFaction]]);
|
||||
|
||||
CalculateFactionInfluence(progressCallback);
|
||||
}
|
||||
|
||||
Entrance = Zones.Where(z => z.Owner == null).MinBy(z => z.Distance[HomeZones[protagonistFaction]]);
|
||||
|
||||
|
|
@ -432,12 +449,6 @@ public class Galaxy
|
|||
}
|
||||
}
|
||||
|
||||
public bool ContainsFaction(CultRecordRef<Faction> faction)
|
||||
{
|
||||
_containedFactions ??= new HashSet<CultRecordKey>(Factions.Select(f => _cache.RefOf(f).Key));
|
||||
return _containedFactions.Contains(faction.Key);
|
||||
}
|
||||
|
||||
class DijkstraVertex
|
||||
{
|
||||
public float Cost;
|
||||
|
|
|
|||
|
|
@ -68,7 +68,10 @@ public sealed class GalaxyStage
|
|||
}
|
||||
|
||||
// A prelude galaxy: the tutorial settings and their fixed factions, centred in dense cloud.
|
||||
public Galaxy Prelude()
|
||||
public Galaxy Prelude() => Prelude(_prelude);
|
||||
|
||||
// A prelude galaxy of the given fixed cast, centred in dense cloud.
|
||||
public Galaxy Prelude(TutorialGenerationSettings cast)
|
||||
{
|
||||
var background = Copy(_preludeBackground);
|
||||
var random = new Random(Seed);
|
||||
|
|
@ -78,7 +81,7 @@ public sealed class GalaxyStage
|
|||
background.NoisePosition = random.NextFloat() * 1000;
|
||||
_progress?.Invoke($"Finding Galaxy Position: iteration {iteration++}");
|
||||
} while (background.CloudDensity(float2(.5f)) < .5f);
|
||||
return new Galaxy(_prelude, background, _names, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed);
|
||||
return new Galaxy(cast, background, _names, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed);
|
||||
}
|
||||
|
||||
private static SectorBackgroundSettings Copy(SectorBackgroundSettings settings) =>
|
||||
|
|
|
|||
32
Assets/Scripts/ServerShared/GravityField.cs
Normal file
32
Assets/Scripts/ServerShared/GravityField.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
using CultMath;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
|
||||
/// <summary>
|
||||
/// The law of one gravity well: a 2D point mass with a softened core. Outside the core radius the potential is
|
||||
/// logarithmic and the pull is c / r; inside it the pull falls linearly to zero at the centre and meets the tail in
|
||||
/// value and slope at the core radius. c is the well's strength (u^2/s^2), R its core radius (u). No threshold
|
||||
/// anywhere: a well pulls at every distance. Zone.GetForce and Zone.GetHeight sum this over a zone's bodies.
|
||||
/// </summary>
|
||||
public static class GravityField
|
||||
{
|
||||
// The tail's additive constant: it makes the tail meet the core in value at the core radius. Gravity.cginc is generated from it.
|
||||
public const float TailOffset = .5f;
|
||||
|
||||
// The potential at distance r from the body, defined up to a constant (callers subtract their reference).
|
||||
// A well of no strength (a body whose curves are unauthored, so c = 0 and R = 0) digs nothing.
|
||||
public static float Potential(float c, float coreRadius, float r) =>
|
||||
c == 0f ? 0f :
|
||||
r < coreRadius
|
||||
? c * r * r / (2 * coreRadius * coreRadius)
|
||||
: c * (log(r / coreRadius) + TailOffset);
|
||||
|
||||
// The acceleration at `offsetFromBody`, toward the body: zero at the body itself.
|
||||
public static float2 Acceleration(float c, float coreRadius, float2 offsetFromBody)
|
||||
{
|
||||
var r = length(offsetFromBody);
|
||||
if (r == 0f) return float2.zero;
|
||||
var pull = r < coreRadius ? c * r / (coreRadius * coreRadius) : c / r;
|
||||
return -offsetFromBody / r * pull;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/GravityField.cs.meta
Normal file
11
Assets/Scripts/ServerShared/GravityField.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5b0c7d3e9a1f4e2c8d6a7f1b3c9e0a42
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
63
Assets/Scripts/ServerShared/GravityShader.cs
Normal file
63
Assets/Scripts/ServerShared/GravityShader.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System.Globalization;
|
||||
|
||||
/// <summary>
|
||||
/// The single author of Assets/Shaders/Gravity.cginc, the GPU lowering of the zone's potential. The law is
|
||||
/// GravityField's (its constants are read here, not respelled) and the height is Zone.GetHeight: each well's
|
||||
/// potential minus its reference, summed, divided by the exaggeration. Unity does not run C# when it imports a
|
||||
/// shader, so the committed cginc is this output; GravityShaderTests fails unless it equals Source() exactly.
|
||||
/// To change the shader, change this file and regenerate: AETHERIA_REGENERATE_GRAVITY_CGINC=1 dotnet test --filter GravityShaderTests.
|
||||
/// </summary>
|
||||
public static class GravityShader
|
||||
{
|
||||
public const string Path = "Assets/Shaders/Gravity.cginc";
|
||||
|
||||
/// <summary>The whole file, with LF line ends.</summary>
|
||||
public static string Source() => (Template
|
||||
.Replace("@TAIL@", GravityField.TailOffset.ToString("R", CultureInfo.InvariantCulture)))
|
||||
.Replace("\r\n", "\n");
|
||||
|
||||
private const string Template = @"#ifndef AETHERIA_GRAVITY_INCLUDED
|
||||
#define AETHERIA_GRAVITY_INCLUDED
|
||||
|
||||
// GENERATED by ServerShared/GravityShader.cs from GravityField; do not edit (GravityShaderTests fails on any difference).
|
||||
// The lowering of the zone's potential (aetheria-gravity, cut grid-lowering). The law is ServerShared's GravityField
|
||||
// and the height is Zone.GetHeight; this file decides nothing. GravityLowering.Lower fills the buffer and the globals
|
||||
// from the zone (positions from Orbit.Position, reference from Zone.WellReference) each frame.
|
||||
// GravityFieldParityVerify renders it and compares every texel with -Zone.GetHeight.
|
||||
|
||||
struct GravityWell
|
||||
{
|
||||
float2 position;
|
||||
float strength;
|
||||
float coreRadius;
|
||||
float reference;
|
||||
};
|
||||
|
||||
StructuredBuffer<GravityWell> _GravityWells;
|
||||
int _GravityWellCount;
|
||||
float _HeightExaggeration;
|
||||
|
||||
// GravityField.Potential: c is the well's strength, R its core radius, r the distance.
|
||||
float gravityPotential(float c, float R, float r)
|
||||
{
|
||||
return c == 0 ? 0 :
|
||||
r < R
|
||||
? c * r * r / (2 * R * R)
|
||||
: c * (log(r / R) + @TAIL@);
|
||||
}
|
||||
|
||||
// Zone.GetHeight at world xz: each well's potential minus its own reference, summed, divided by the exaggeration.
|
||||
float gravityHeight(float2 p)
|
||||
{
|
||||
float result = 0;
|
||||
for (int i = 0; i < _GravityWellCount; i++)
|
||||
{
|
||||
GravityWell well = _GravityWells[i];
|
||||
result += gravityPotential(well.strength, well.coreRadius, length(p - well.position)) - well.reference;
|
||||
}
|
||||
return result / _HeightExaggeration;
|
||||
}
|
||||
|
||||
#endif
|
||||
";
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/GravityShader.cs.meta
Normal file
11
Assets/Scripts/ServerShared/GravityShader.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 9a3fa1e9df764459b709270e58e79974
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -519,8 +519,7 @@ public class HullData : EquippableItemData
|
|||
[Inspectable, JsonProperty("hullType"), Key(25)]
|
||||
public HullType HullType;
|
||||
|
||||
[Inspectable, JsonProperty("gridOffset"), Key(26)]
|
||||
public float GridOffset;
|
||||
// Key(26) retired 2026-10-16 (per-hull GridOffset; the layer is the kind's, GameplaySettings). Do not reuse.
|
||||
|
||||
[Inspectable, JsonProperty("armor"), Key(27)]
|
||||
public float Armor;
|
||||
|
|
@ -536,6 +535,19 @@ public class HullData : EquippableItemData
|
|||
[Inspectable, JsonProperty("visual"), Key(32)]
|
||||
public CultRecordRef<ShipAuthoring> Visual;
|
||||
|
||||
// The farthest corner of any occupied hull cell from the centre of mass the schematic frame uses, in world
|
||||
// units: a true bound on how far the hull reaches from its position (the half-diagonal of the bounding box is not,
|
||||
// as FireControl.Detonate's comment records). A cell at (x, y) spans x +/- .5 and y +/- .5.
|
||||
public float Reach(float cellSize)
|
||||
{
|
||||
var com = Shape.CenterOfMass;
|
||||
var far = 0f;
|
||||
foreach (var c in Shape.Coordinates)
|
||||
foreach (var (dx, dy) in new[] { (-.5f, -.5f), (.5f, -.5f), (-.5f, .5f), (.5f, .5f) })
|
||||
far = max(far, length(float2(c.x + dx, c.y + dy) - com));
|
||||
return far * cellSize;
|
||||
}
|
||||
|
||||
[IgnoreMember]
|
||||
public Shape InteriorCells
|
||||
{
|
||||
|
|
@ -566,7 +578,12 @@ public class HardpointData
|
|||
[Inspectable, JsonProperty("armor"), Key(5)] public float Armor;
|
||||
// Full arc width in degrees a weapon on this hardpoint may bear across; 0 means "use
|
||||
// GameplaySettings.FiringArc" (docs/fire-control-cut.md R6). Turrets author 360 (Q1).
|
||||
// On a Thruster hardpoint it is the full gimbal width: the row swings +-FiringArc/2 about Rotation, 0 is a
|
||||
// fixed thruster, and there is no GameplaySettings fallback.
|
||||
[Inspectable, JsonProperty("firingArc"), Key(6)] public float FiringArc;
|
||||
// Thruster hardpoints sharing a non-empty Row swing as one row; a Thruster hardpoint with FiringArc > 0 and no Row
|
||||
// is a row of one. Only a Thruster hardpoint may state one.
|
||||
[Inspectable, JsonProperty("row"), Key(7)] public string Row;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
|
|
@ -720,7 +737,10 @@ public class PerformanceStat
|
|||
_ => throw new ArgumentOutOfRangeException(nameof(term.Source), term.Source, $"Unknown StatSource on {Min}-{Max} stat")
|
||||
};
|
||||
}
|
||||
return (lerp(Min, Max, factor) * context.ScaleModifier(this) + context.ConstantModifier(this)) * powerMultiplier;
|
||||
// A stat whose span is a single value has nothing to interpolate: an unauthored stat is +infinity at both ends
|
||||
// (Tracking, EffectiveRange), and lerp(+inf, +inf, f) is NaN.
|
||||
var interpolated = Min == Max ? Min : lerp(Min, Max, factor);
|
||||
return (interpolated * context.ScaleModifier(this) + context.ConstantModifier(this)) * powerMultiplier;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -815,6 +835,38 @@ public static class StatValidation
|
|||
}
|
||||
}
|
||||
|
||||
// Ruling missile-stats-now-gear-later: a munition design (a LauncherData or GuidedWeaponData behaviour) carries exactly
|
||||
// one of each of the five munition parts, and any other design carries none. Runs wherever ValidateStatModifiers runs,
|
||||
// so a launcher missing a part is named at catalog load and Upsert rather than at its first launch.
|
||||
public static void ValidateMunitionParts(string ownerName, IEnumerable<BehaviorData> behaviors)
|
||||
{
|
||||
var all = (behaviors ?? Enumerable.Empty<BehaviorData>()).Where(b => b != null).ToArray();
|
||||
var isMunition = all.Any(b => b is LauncherData || b is GuidedWeaponData);
|
||||
foreach (var part in new[] { typeof(MunitionHullData), typeof(MunitionThrusterData), typeof(MunitionSeekerData), typeof(MunitionControlData), typeof(MunitionFuelData) })
|
||||
{
|
||||
var count = all.Count(b => b.GetType() == part);
|
||||
var expected = isMunition ? 1 : 0;
|
||||
if (count != expected)
|
||||
throw new InvalidOperationException(
|
||||
$"{ownerName}: carries {count} {part.Name}, but a {(isMunition ? "munition" : "non-munition")} design carries {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
// Ruling effective-range-authoring-ruled: mines are flat. A mine layer's Range and MinRange gate where it may lay; its
|
||||
// damage meets no range, so it carries no falloff authoring, and WeaponData.RangeFactor reads 1 inside the gate for the
|
||||
// mine, the AI and the panel alike. Refused here, with the other catalog rules, wherever those run.
|
||||
public static void ValidateMineLayerFlat(string ownerName, IEnumerable<BehaviorData> behaviors)
|
||||
{
|
||||
foreach (var layer in (behaviors ?? Enumerable.Empty<BehaviorData>()).OfType<MineLayerData>())
|
||||
{
|
||||
var effective = layer.EffectiveRange;
|
||||
if (effective == null || !float.IsPositiveInfinity(effective.Min) || !float.IsPositiveInfinity(effective.Max) || (effective.Terms != null && effective.Terms.Count > 0))
|
||||
throw new InvalidOperationException($"{ownerName}: {nameof(MineLayerData)}.{nameof(WeaponData.EffectiveRange)} is authored, but a mine layer carries no damage falloff");
|
||||
if (layer.DamageAtMaxRange != 0f)
|
||||
throw new InvalidOperationException($"{ownerName}: {nameof(MineLayerData)}.{nameof(WeaponData.DamageAtMaxRange)} is authored, but a mine layer carries no damage falloff");
|
||||
}
|
||||
}
|
||||
|
||||
// Cut 7 (docs/stats-and-power-cut.md): "a stat naming a role its design lacks" must be refused, not silently
|
||||
// fall back to the lot's own workmanship (Lot.QualityForRole already falls back for a role a lot never rolled
|
||||
// -- that is the intended forward-compat path for an old lot meeting a newly-authored role. This is the other
|
||||
|
|
@ -855,8 +907,7 @@ public static class StatValidation
|
|||
//
|
||||
// F6 (docs/stats-and-power-cut.md, Soul pass 2026-09-19) named every field a PowerRequest implementation
|
||||
// actually reads, not just each consumer's top-level request field: Radiator.PowerRequest also reads
|
||||
// PumpedHeat and WasteHeat, AetherDrive.PowerRequest also reads Torque, LambdaMultiplier, MaximumRpm and
|
||||
// PassiveCoupling, Shield.PowerRequest (via RefreshReserve) also reads RefillDuration and RestoreDuration,
|
||||
// PumpedHeat and WasteHeat, Shield.PowerRequest (via RefreshReserve) also reads RefillDuration and RestoreDuration,
|
||||
// InstantWeapon.PowerRequest (via RefreshInputCapacitor) also reads Cooldown and Count, and Sensor.
|
||||
// PowerRequest (via RefreshInputCapacitor) also reads PingCooldown. Audited directly against each
|
||||
// PowerRequest method's own body (and RefreshReserve/RefreshInputCapacitor, which PowerRequest calls into)
|
||||
|
|
@ -892,11 +943,6 @@ public static class StatValidation
|
|||
(typeof(RadiatorData), nameof(RadiatorData.EnergyUsage)),
|
||||
(typeof(RadiatorData), nameof(RadiatorData.PumpedHeat)),
|
||||
(typeof(RadiatorData), nameof(RadiatorData.WasteHeat)),
|
||||
(typeof(AetherDriveData), nameof(AetherDriveData.EnergyDraw)),
|
||||
(typeof(AetherDriveData), nameof(AetherDriveData.Torque)),
|
||||
(typeof(AetherDriveData), nameof(AetherDriveData.LambdaMultiplier)),
|
||||
(typeof(AetherDriveData), nameof(AetherDriveData.MaximumRpm)),
|
||||
(typeof(AetherDriveData), nameof(AetherDriveData.PassiveCoupling)),
|
||||
};
|
||||
|
||||
// Whether `stat` is the request stat of some IPowerConsumer behaviour on `data` -- used by StatModifier's
|
||||
|
|
|
|||
|
|
@ -53,6 +53,9 @@ public class EquippableItem : CraftedItemInstance
|
|||
[JsonProperty("durability"), Key(7)] public float Durability;
|
||||
[JsonProperty("override"), Key(8)] public bool OverrideShutdown;
|
||||
|
||||
// The one rule for a destroyed item: its wear is spent.
|
||||
[IgnoreMember] public bool IsDestroyed => Durability < .01f;
|
||||
|
||||
// Cut 5 (docs/stats-and-power-cut.md §1.3, §0b "A power tier"): a player choice, stored on the unit rather
|
||||
// than the design, so two units of the same design can be prioritized differently. PowerTiers.Unassigned
|
||||
// until the first equip seeds a behaviour-kind default (EquippedItem's constructor) or the player overrides
|
||||
|
|
|
|||
|
|
@ -140,6 +140,7 @@ public class ItemManager
|
|||
{
|
||||
Design = ItemData.RefOf<ItemData>(design),
|
||||
Origin = new Attributed { Faction = product.Manufacturer },
|
||||
Product = ItemData.RefOf(product),
|
||||
Quality = RollQuality(),
|
||||
Roles = new List<RoleFill>()
|
||||
};
|
||||
|
|
@ -182,6 +183,9 @@ public class ItemManager
|
|||
};
|
||||
}
|
||||
|
||||
if (design is ConsumableItemData)
|
||||
return new ConsumableItem { Data = l.Design, Lot = lot };
|
||||
|
||||
return new CompoundCommodity
|
||||
{
|
||||
Data = l.Design, Lot = lot
|
||||
|
|
@ -200,9 +204,10 @@ public class ItemManager
|
|||
return CreateInstance(CreateLot(product));
|
||||
}
|
||||
|
||||
// Who made an item and what it is branded as, derived from its lot's provenance. Null maker (an unset faction,
|
||||
// or an Extracted lot with none) means no brand at all; a set maker with no matching product still shows the
|
||||
// maker, with no product name or flavour text.
|
||||
// Who made an item and what it is branded as. The maker derives from its lot's provenance and the product is the
|
||||
// one its lot records; nothing re-derives it. Null maker (an unset faction, or an Extracted lot with none) means
|
||||
// no brand at all; a set maker whose lot records no product (or one the catalog no longer holds) still shows
|
||||
// the maker, with no product name or flavour text.
|
||||
public (Faction Maker, FactionProductData Product) Brand(CraftedItemInstance item)
|
||||
{
|
||||
var lot = GetLot(item);
|
||||
|
|
@ -214,13 +219,15 @@ public class ItemManager
|
|||
};
|
||||
if (!maker.IsSet()) return (null, null);
|
||||
|
||||
var product = ItemData.GetAll<FactionProductData>()
|
||||
.Where(p => p.Manufacturer.Key.Equals(maker.Key) && p.Design.Key.Equals(item.Data.Key))
|
||||
.OrderBy(p => ItemData.RefOf(p).Key.Value, StringComparer.Ordinal)
|
||||
.FirstOrDefault();
|
||||
var product = ItemData.Get(lot.Product);
|
||||
return (ItemData.Get(maker), product);
|
||||
}
|
||||
|
||||
// What the player reads an item as: its lot's product name when it records one,
|
||||
// otherwise the design's own name (unbranded, console-given and extracted lots, and commodities).
|
||||
public string Title(ItemInstance item) =>
|
||||
(item is CraftedItemInstance crafted ? Brand(crafted).Product?.Name : null) ?? GetData(item).Name;
|
||||
|
||||
public (RarityTier tier, int upgrades) GetTier(CraftedItemInstance item)
|
||||
{
|
||||
var quality = GetLot(item).Quality;
|
||||
|
|
|
|||
|
|
@ -190,7 +190,7 @@ public static class Loadouts
|
|||
return () => (EquippableItem) itemManager.CreateInstance(product);
|
||||
}
|
||||
|
||||
private static FactionProductData[] ProductsInKeyOrder(CultCache cache) =>
|
||||
internal static FactionProductData[] ProductsInKeyOrder(CultCache cache) =>
|
||||
cache.GetAll<FactionProductData>().OrderBy(p => cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray();
|
||||
|
||||
private static string Cell(LoadoutSlot slot) => $"slot {slot.Position.x},{slot.Position.y}";
|
||||
|
|
|
|||
|
|
@ -16,6 +16,14 @@ public class LoadoutGenerator
|
|||
public Faction Faction { get; }
|
||||
public float PriceExponent { get; }
|
||||
|
||||
// Consumables are scarce (operator, 2026-10-09): a quarter of stations stock one product, one ship in ten carries
|
||||
// one unit, and a carried consumable becomes loot when its ship dies. The units are the most a roll can stock; a
|
||||
// station draws 1 to the maximum.
|
||||
public const float StationConsumableChance = .25f;
|
||||
public const int StationConsumableUnits = 2;
|
||||
public const float ShipConsumableChance = .1f;
|
||||
public const int ShipConsumableUnits = 1;
|
||||
|
||||
public LoadoutGenerator(
|
||||
ref Random random,
|
||||
ItemManager itemManager,
|
||||
|
|
@ -46,6 +54,8 @@ public class LoadoutGenerator
|
|||
var entity = new Ship(ItemManager, null, hull, ItemManager.GameplaySettings.DefaultEntitySettings);
|
||||
entity.Faction = Faction;
|
||||
OutfitEntity(entity);
|
||||
EquipPickup(entity);
|
||||
StockConsumables(entity, ShipConsumableChance, ShipConsumableUnits);
|
||||
return EntitySerializer.Pack(entity);
|
||||
}
|
||||
|
||||
|
|
@ -107,6 +117,11 @@ public class LoadoutGenerator
|
|||
|
||||
FillInterior(entity);
|
||||
|
||||
// The consumable goes in before the gear stock: sixteen gear picks drawn with replacement can fill a real hold,
|
||||
// and a roll that hit must leave the entity holding one (the ruled rate is the rule). With no consumable on
|
||||
// offer nothing is drawn here, so the gear draws are exactly what they were.
|
||||
StockConsumables(entity, StationConsumableChance, StationConsumableUnits);
|
||||
|
||||
var cargo = entity.CargoBays.First();
|
||||
var inventory = RandomProducts<EquippableItemData>(16, 1,
|
||||
data => !(data is HullData hull && hull.HullType != HullType.Ship) && !(data is CargoBayData))
|
||||
|
|
@ -122,6 +137,25 @@ public class LoadoutGenerator
|
|||
return EntitySerializer.Pack(entity) as OrbitalEntityPack;
|
||||
}
|
||||
|
||||
// A loadout's one consumable step. With no consumable on offer, or no hold to put one in, nothing is drawn, so a
|
||||
// catalog without consumables generates exactly what it did before them. Otherwise one roll decides whether the
|
||||
// entity has any, and a hit stocks 1 to maxUnits instances of one product, stopping when no hold takes another.
|
||||
private void StockConsumables(Entity entity, float chance, int maxUnits)
|
||||
{
|
||||
var (available, _) = AvailableProducts<ConsumableItemData>(null, false);
|
||||
if (available.Length == 0 || !entity.CargoBays.Any()) return;
|
||||
if (Random.NextFloat() >= chance) return;
|
||||
|
||||
var (product, design) = RandomProducts<ConsumableItemData>(1, 0).FirstOrDefault();
|
||||
if (design == null) return;
|
||||
var units = Random.NextInt(1, maxUnits + 1);
|
||||
for (var i = 0; i < units; i++)
|
||||
{
|
||||
var instance = ItemManager.CreateInstance(product);
|
||||
if (!entity.CargoBays.Any(bay => bay.TryStore(instance))) break;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsHeater(GearData item) =>
|
||||
item.HardpointType == HardpointType.Tool &&
|
||||
item.Behaviors.Any(b => b is ThermotoggleData { HighPass: false }) &&
|
||||
|
|
@ -139,16 +173,28 @@ public class LoadoutGenerator
|
|||
// Products normally come only from manufacturers present in the galaxy and known to the zone's faction; a
|
||||
// required item falls back to any manufacturer when none of those make one, which means the product table
|
||||
// lacks variety, so it is logged rather than hidden.
|
||||
public (FactionProductData product, T design)[] RandomProducts<T>(int count, float sizeExponent, Predicate<T> filter = null, bool required = false) where T : EquippableItemData
|
||||
public (FactionProductData product, T design)[] RandomProducts<T>(int count, float sizeExponent, Predicate<T> filter = null, bool required = false) where T : CraftedItemData
|
||||
{
|
||||
var hulls = ItemManager.ItemData.GetAll<HullData>().ToArray();
|
||||
var (available, preferManufacturers) = AvailableProducts(filter, required);
|
||||
return available.WeightedRandomElements(ref Random, entry =>
|
||||
(preferManufacturers ? ManufacturerPreference(entry.product.Manufacturer) : 1) *
|
||||
pow(entry.design.Shape.Coordinates.Length, sizeExponent) / // Prioritize larger items
|
||||
pow(entry.design.Price, PriceExponent), // Penalize item price to a controllable degree
|
||||
count);
|
||||
}
|
||||
|
||||
// The products this faction can be offered for a design kind (only gear needs a home), and whether manufacturer preference applies (it does
|
||||
// not once a required item has fallen back to any manufacturer). The one availability rule for every selection.
|
||||
private ((FactionProductData product, T design)[] available, bool preferManufacturers) AvailableProducts<T>(Predicate<T> filter, bool required) where T : CraftedItemData
|
||||
{
|
||||
var hulls = SoldHulls(ItemManager.ItemData);
|
||||
var candidates = ItemManager.ItemData.GetAll<FactionProductData>()
|
||||
.Select(product => (product, design: ItemManager.ItemData.Get(product.Design) as T))
|
||||
.Where(entry =>
|
||||
entry.design != null &&
|
||||
entry.design.Price > 0 &&
|
||||
entry.product.Manufacturer.IsSet() &&
|
||||
HasHome(entry.design, hulls) &&
|
||||
(!(entry.design is EquippableItemData equippable) || HasHome(equippable, hulls)) &&
|
||||
(filter?.Invoke(entry.design) ?? true))
|
||||
.ToArray();
|
||||
var available = candidates.Where(entry => IsAvailable(entry.product)).ToArray();
|
||||
|
|
@ -160,40 +206,65 @@ public class LoadoutGenerator
|
|||
preferManufacturers = false;
|
||||
}
|
||||
|
||||
return available.WeightedRandomElements(ref Random, entry =>
|
||||
(preferManufacturers ? ManufacturerPreference(entry.product.Manufacturer) : 1) *
|
||||
pow(entry.design.Shape.Coordinates.Length, sizeExponent) / // Prioritize larger items
|
||||
pow(entry.design.Price, PriceExponent), // Penalize item price to a controllable degree
|
||||
count);
|
||||
return (available, preferManufacturers);
|
||||
}
|
||||
|
||||
// A faction's boss: its BossHull when the faction sets one and a product sells it, else the most expensive ship hull
|
||||
// the faction can be offered, with the gap logged. Null only when no ship hull is on offer at all.
|
||||
public EntityPack GenerateBossLoadout()
|
||||
{
|
||||
var bossHull = Faction != null && Faction.BossHull.IsSet() ? ItemManager.ItemData.Get(Faction.BossHull) : null;
|
||||
if (bossHull != null)
|
||||
{
|
||||
var boss = GenerateShipLoadout(hull => hull == bossHull);
|
||||
if (boss != null) return boss;
|
||||
ItemManager.Log($"{Faction.Name}'s BossHull {bossHull.Name} is not sold by any product; its boss flies the most expensive ship hull instead.");
|
||||
}
|
||||
else
|
||||
ItemManager.Log($"{Faction?.Name ?? "This faction"} has no BossHull; its boss flies the most expensive ship hull instead.");
|
||||
|
||||
var (available, _) = AvailableProducts<HullData>(hull => hull.HullType == HullType.Ship, required: true);
|
||||
if (available.Length == 0) return null;
|
||||
var priciest = available.OrderByDescending(entry => entry.design.Price).ThenBy(entry => entry.design.Name, StringComparer.Ordinal).First().design;
|
||||
return GenerateShipLoadout(hull => hull == priciest);
|
||||
}
|
||||
|
||||
// Hardpoint gear that no hull in the catalog can mount has no home (operator, 2026-09-30: "we'll need to author a
|
||||
// bunch more hulls before all the gear variety in the game has a home"): generation never offers it, so no station
|
||||
// stocks it. It gains one the moment a hull with a hardpoint that takes it exists. Tool gear goes in any interior.
|
||||
private static bool HasHome(EquippableItemData design, HullData[] hulls) =>
|
||||
// Only a hull some product sells gives gear a home: a hull no faction builds (the Smoke Test Hull) is a test fixture, so its
|
||||
// hardpoints never put gear on a shelf. The one definition of the hulls HasHome considers.
|
||||
public static HullData[] SoldHulls(CultCache items) =>
|
||||
items.GetAll<FactionProductData>().Select(product => items.Get(product.Design)).OfType<HullData>().Distinct().ToArray();
|
||||
|
||||
public static bool HasHome(EquippableItemData design, HullData[] hulls) =>
|
||||
design.HardpointType == HardpointType.Tool || design.HardpointType == HardpointType.Hull ||
|
||||
hulls.Any(hull => hull.Hardpoints.Any(hardpoint => hardpoint.Takes(design)));
|
||||
|
||||
// No galaxy means no availability to filter by: every product is on offer. A fixture generates loadouts that
|
||||
// way, so a test can exercise placement and products without standing up a whole galaxy; no game path does.
|
||||
// Loadouts.Materialize takes availability as a predicate; RunStart, the game's one preset spawner, passes this, so
|
||||
// presets and generation share one availability rule. In a galaxy, a faction always reaches its own manufacturer's
|
||||
// gear, and otherwise gear made by a manufacturer in that galaxy that its allegiance names (operator, 2026-09-30:
|
||||
// allegiance lists only other factions).
|
||||
// No galaxy, or no faction, means no allegiance to filter by: every product is on offer. A fixture generates
|
||||
// loadouts that way, so a test can exercise placement and products without standing up a whole galaxy; a scenario
|
||||
// stage has no faction and reaches every maker. Loadouts.Materialize takes availability as a predicate; RunStart,
|
||||
// the game's one preset spawner, passes this, so presets and generation share one availability rule. A faction
|
||||
// always reaches its own manufacturer's gear, and otherwise gear made by a manufacturer its allegiance names
|
||||
// (operator, 2026-09-30: allegiance lists only other factions). Whether that manufacturer is present in the galaxy
|
||||
// does not matter (operator, 2026-10-06: a faction need not be present for its gear to be available).
|
||||
public bool IsAvailable(FactionProductData product) =>
|
||||
Galaxy == null || Galaxy.IsPrelude ||
|
||||
Faction != null && ItemManager.ItemData.Get(product.Manufacturer) == Faction ||
|
||||
Galaxy.ContainsFaction(product.Manufacturer) && (Faction == null || Faction.Allegiance.ContainsKey(product.Manufacturer));
|
||||
Galaxy == null || Faction == null ||
|
||||
ItemManager.ItemData.Get(product.Manufacturer) == Faction || Faction.Allegiance.ContainsKey(product.Manufacturer);
|
||||
|
||||
// Prioritize products from the zone faction and its allies, penalizing distance to the manufacturer's headquarters
|
||||
private float ManufacturerPreference(CultRecordRef<Faction> manufacturer)
|
||||
// Prioritize products from the zone faction and its allies, penalizing distance to the manufacturer's headquarters.
|
||||
// A manufacturer with no home zone in this galaxy weighs as if its headquarters lay one jump beyond the farthest
|
||||
// zone this zone reaches: reachable through allegiance, least preferred.
|
||||
public float ManufacturerPreference(CultRecordRef<Faction> manufacturer)
|
||||
{
|
||||
if (Faction == null || Galaxy == null) return 1;
|
||||
var maker = ItemManager.ItemData.Get(manufacturer);
|
||||
var allegiance = maker == Faction ? 1 :
|
||||
Faction.Allegiance.TryGetValue(manufacturer, out var a) ? a : 0;
|
||||
var home = maker != null && Galaxy.HomeZones.TryGetValue(maker, out var h) ? h : null;
|
||||
var distance = home != null && Zone?.Distance != null && Zone.Distance.TryGetValue(home, out var d) ? d : 0;
|
||||
var distance = Zone?.Distance == null ? 0 :
|
||||
home != null && Zone.Distance.TryGetValue(home, out var d) ? d :
|
||||
home == null && Zone.Distance.Count > 0 ? Zone.Distance.Values.Max() + 1 : 0;
|
||||
return allegiance / (1 + distance);
|
||||
}
|
||||
|
||||
|
|
@ -217,6 +288,24 @@ public class LoadoutGenerator
|
|||
FillInterior(entity);
|
||||
}
|
||||
|
||||
// Every ship carries a tractor beam: picking up needs a pickup behaviour (scenarios ruling, "everyone gets tractor
|
||||
// beams"). It goes in after the shared outfitting, which stations and turrets also run and which adds none, into
|
||||
// whatever interior the hull has left; a hull with no cell for one cannot be generated.
|
||||
private void EquipPickup(Entity entity)
|
||||
{
|
||||
var emptyShape = entity.UnoccupiedSpace;
|
||||
var (product, design) = RandomProduct<GearData>(2, item =>
|
||||
item.Behaviors.Any(b => b is PickupData) &&
|
||||
item.Shape.FitsWithin(emptyShape, out _, out _), required: true);
|
||||
if (design == null) throw new InvalidLoadoutException("No compatible tractor beam found for ship!");
|
||||
|
||||
design.Shape.FitsWithin(emptyShape, out var rotation, out var position);
|
||||
var beam = ItemManager.CreateInstance(product) as EquippableItem;
|
||||
beam.Rotation = rotation;
|
||||
if (!entity.TryEquip(beam, position))
|
||||
throw new InvalidLoadoutException("Failed to equip selected tractor beam!");
|
||||
}
|
||||
|
||||
private void EquipHardpoints(Entity entity)
|
||||
{
|
||||
var hullData = ItemManager.GetData(entity.Hull) as HullData;
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ public class OrbitalEntity : Entity
|
|||
OrbitData = orbit;
|
||||
}
|
||||
|
||||
public override float LayerHeight => ItemManager.GameplaySettings.OrbitalLayerHeight;
|
||||
|
||||
public override void Update(float delta)
|
||||
{
|
||||
if (OrbitData.IsSet())
|
||||
|
|
|
|||
|
|
@ -64,6 +64,8 @@ public class PlayerGraphicsSettings
|
|||
{
|
||||
[Key(0)] public Quality NebulaQuality = Quality.Normal;
|
||||
[Key(1)] public bool ShowAsteroidsInMinimap;
|
||||
// How hard the camera shakes when the player's ship takes an impact: 0 off, 1 full (Feedback.Cue).
|
||||
[Key(2)] public float ScreenShake = 1f;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
// every other item on the hull (EquippedItem.UpdatePerformance). Feed it first or lose the rest anyway.
|
||||
// - High: Shield. Hull survival the player is actively trading power for; not a life-support constant, so it
|
||||
// sits below Radiator rather than beside it.
|
||||
// - Medium: Thruster, AetherDrive. Mobility -- needed to hold position, evade, or disengage, but a ship that
|
||||
// - Medium: Thruster. Mobility -- needed to hold position, evade, or disengage, but a ship that
|
||||
// loses thrust for a tick under brownout is inconvenienced, not dead the way an overheating hull is.
|
||||
// - Low: ConstantWeapon, InstantWeapon. Offense. The ruling's own framing ("low-priority subsystems starve
|
||||
// first") names weapons as the default example of what a reactor throttle should sacrifice first.
|
||||
|
|
|
|||
|
|
@ -58,8 +58,8 @@ public class ProvenanceLedger
|
|||
}
|
||||
}
|
||||
|
||||
// One lot: the design it built, who made it and from what, its rolled workmanship, and how well each design role
|
||||
// was filled. Immutable once minted; instances carry a LotId, never a copy.
|
||||
// One lot: the design it built, who made it and from what, its rolled workmanship, how well each design role
|
||||
// was filled, and the branded product it was made as. Immutable once minted; instances carry a LotId, never a copy.
|
||||
[MessagePackObject]
|
||||
public class Lot
|
||||
{
|
||||
|
|
@ -68,6 +68,10 @@ public class Lot
|
|||
[Key(2)] public float Quality;
|
||||
[Key(3)] public List<RoleFill> Roles;
|
||||
|
||||
// The product the lot was made as: the one owner of which product names its units. Unset for unbranded lots
|
||||
// (console give, presets, extracted), which brand their maker only.
|
||||
[Key(4)] public CultRecordRef<FactionProductData> Product;
|
||||
|
||||
// The quality a stat reads for one of the design's roles. An unnamed role, a design without roles, and a lot
|
||||
// minted before roles existed all fall back to the lot's own workmanship.
|
||||
public float QualityForRole(string role)
|
||||
|
|
|
|||
42
Assets/Scripts/ServerShared/RunGoal.cs
Normal file
42
Assets/Scripts/ServerShared/RunGoal.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using System.Linq;
|
||||
using CultMath;
|
||||
using static CultMath.math;
|
||||
|
||||
// The run's goal: whether a zone's boss lives, and so whether the exit gate is open. Engine-free and stateless; the
|
||||
// answer is derived from Zone.Entities (the death path removes the dead, Zone.cs), so no "boss defeated" flag exists to
|
||||
// disagree with it, and no presentation decides it.
|
||||
public static class RunGoal
|
||||
{
|
||||
public static Entity Boss(Zone zone) => zone.Entities.FirstOrDefault(entity => entity.IsBoss);
|
||||
|
||||
public static bool BossAlive(Zone zone) => Boss(zone) != null;
|
||||
|
||||
// The exit gate fails closed: it is open only in the galaxy's exit zone, once a boss was spawned there and no living
|
||||
// boss remains. An exit zone that never got a boss stays sealed, so a missing boss can never read as a dead one.
|
||||
public static bool ExitOpen(Zone zone) =>
|
||||
zone.Galaxy?.Exit != null && zone.GalaxyZone == zone.Galaxy.Exit && zone.Pack.BossSpawned && !BossAlive(zone);
|
||||
|
||||
// Where the exit gate sits: at the adjacency wormholes' radius (the zone's radius times the ratio), in the middle of
|
||||
// the widest angular gap between them, so it shares a point with none. A zone with no neighbours gets the +x axis.
|
||||
public static float2 ExitGatePosition(Zone zone, float wormholeDistanceRatio)
|
||||
{
|
||||
var radius = zone.Pack.Radius * wormholeDistanceRatio;
|
||||
var angles = zone.GalaxyZone.AdjacentZones
|
||||
.Select(adjacent => normalize(adjacent.Position - zone.GalaxyZone.Position))
|
||||
.Select(direction => atan2(direction.y, direction.x))
|
||||
.OrderBy(angle => angle)
|
||||
.ToArray();
|
||||
if (angles.Length == 0) return float2(radius, 0);
|
||||
|
||||
var bestAngle = 0f;
|
||||
var bestGap = -1f;
|
||||
for (var i = 0; i < angles.Length; i++)
|
||||
{
|
||||
var next = i + 1 < angles.Length ? angles[i + 1] : angles[0] + 2 * PI;
|
||||
if (next - angles[i] <= bestGap) continue;
|
||||
bestGap = next - angles[i];
|
||||
bestAngle = angles[i] + bestGap / 2;
|
||||
}
|
||||
return float2(cos(bestAngle), sin(bestAngle)) * radius;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/ServerShared/RunGoal.cs.meta
Normal file
2
Assets/Scripts/ServerShared/RunGoal.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: de03c3545cb04ce38bf85b713dc5df74
|
||||
|
|
@ -105,18 +105,23 @@ public sealed class ScenarioStage
|
|||
}
|
||||
|
||||
// Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's
|
||||
// pilot; an unpiloted entity has none and goes nowhere on its own. A turret hull stays where it is put.
|
||||
public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false)
|
||||
// pilot; an unpiloted entity has none and goes nowhere on its own unless it is placed moving: velocity is the planar
|
||||
// velocity it starts with, and the sim carries it from there. A turret hull stays where it is put.
|
||||
public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false,
|
||||
float2 velocity = default)
|
||||
{
|
||||
var where = $"entity {_placements++}";
|
||||
var entity = Build(fit, where, at, facing);
|
||||
if (entity == null) return null;
|
||||
entity.Velocity = velocity;
|
||||
if (piloted && !(entity is Ship)) _failures.Add($"{where}: {entity.Name} is not a ship hull, so it cannot be piloted");
|
||||
_placed.Add(new Placement { Entity = entity, Stance = stance, Piloted = piloted });
|
||||
return entity;
|
||||
}
|
||||
|
||||
// Items in the entity's first cargo bay, one per design named.
|
||||
// Items in the entity's first cargo bay, one per design named. A name is an equippable design (built as a fit
|
||||
// builds it) or a consumable design (built from its first available product in key order, as a generated hold is
|
||||
// stocked); a name that is neither is a failure.
|
||||
public void Cargo(Entity entity, params string[] designs)
|
||||
{
|
||||
if (entity == null) return;
|
||||
|
|
@ -124,10 +129,27 @@ public sealed class ScenarioStage
|
|||
var bay = entity.CargoBays.FirstOrDefault();
|
||||
foreach (var design in designs)
|
||||
{
|
||||
var data = Named<EquippableItemData>(design, where);
|
||||
var data = Named<CraftedItemData>(design, where, found => found is EquippableItemData || found is ConsumableItemData);
|
||||
if (data == null) continue;
|
||||
var build = Loadouts.Resolve(_items, _items.ItemData.RefOf(data), _available, where, _failures);
|
||||
if (build != null && (bay == null || !bay.TryStore(build())))
|
||||
Func<CraftedItemInstance> build;
|
||||
if (data is ConsumableItemData)
|
||||
{
|
||||
var key = _items.ItemData.RefOf(data).Key;
|
||||
var product = Loadouts.ProductsInKeyOrder(_items.ItemData).Where(p => p.Design.Key.Equals(key)).FirstOrDefault(p => _available(p));
|
||||
if (product == null)
|
||||
{
|
||||
_failures.Add($"{where}: no product offers {design}");
|
||||
continue;
|
||||
}
|
||||
build = () => _items.CreateInstance(product);
|
||||
}
|
||||
else
|
||||
{
|
||||
var equippable = Loadouts.Resolve(_items, _items.ItemData.RefOf((EquippableItemData) data), _available, where, _failures);
|
||||
if (equippable == null) continue;
|
||||
build = equippable;
|
||||
}
|
||||
if (bay == null || !bay.TryStore(build()))
|
||||
_failures.Add($"{where}: no room for {design}");
|
||||
}
|
||||
}
|
||||
|
|
@ -151,9 +173,9 @@ public sealed class ScenarioStage
|
|||
return entity;
|
||||
}
|
||||
|
||||
private T Named<T>(string name, string where) where T : EquippableItemData
|
||||
private T Named<T>(string name, string where, Func<T, bool> among = null) where T : CraftedItemData
|
||||
{
|
||||
var named = _items.ItemData.GetAll<T>().Where(data => data.Name == name).Take(2).ToArray();
|
||||
var named = _items.ItemData.GetAll<T>().Where(data => data.Name == name && (among == null || among(data))).Take(2).ToArray();
|
||||
if (named.Length == 1) return named[0];
|
||||
_failures.Add(named.Length == 0 ? $"{where}: no design named {name}" : $"{where}: more than one design is named {name}");
|
||||
return null;
|
||||
|
|
|
|||
36
Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs
Normal file
36
Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class AiFusedDiscipline : Scenario
|
||||
{
|
||||
public override string Name => "AI Fused Discipline";
|
||||
public override string Brief => "A Djinni; a piloted neutral Longinus carrying a Smoke Proximity and a piloted hostile Longinus whose only weapon is " +
|
||||
"Smoke Refused. Verify: the hostile closes on you and never fires its refused weapon; the neutral never fires its " +
|
||||
"fused one.";
|
||||
public override uint Seed => 110;
|
||||
public override bool Ambient => false;
|
||||
|
||||
public static readonly CultMath.float2 Hostile = float2(0, 700), Neutral = float2(500, 300);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
ScenarioFit Armed(string weapon) => stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
(weapon, int2(1, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise));
|
||||
|
||||
stage.Player(stage.Generated("Djinni"), float2(0, 0));
|
||||
stage.Place(Armed("Smoke Refused"), Hostile, facing: float2(0, -1), stance: ScenarioStance.Hostile, piloted: true);
|
||||
stage.Place(Armed("Smoke Proximity"), Neutral, facing: float2(-1, 0), piloted: true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0d71dbf0ab5847a6ab58f96a50678ac7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -4,43 +4,57 @@ using static ItemRotation;
|
|||
public sealed class Arcs : Scenario
|
||||
{
|
||||
public override string Name => "Arcs";
|
||||
public override string Brief => "Forward mounts, a bare hull off the bow, one off the stern, a hostile turret. Verify: the bow " +
|
||||
"hull can be hit, nothing fires at the stern one through the ship, the turret tracks you all the way round.";
|
||||
public override string Brief => "The Smoke Test Hull with forward mounts and a side mount on each flank; a bare hull off the bow, one off " +
|
||||
"the stern, one abeam to port, one abeam to starboard, and a hostile turret. Verify: the hull keeps its " +
|
||||
"heading while you aim at the stern hull, and the forward guns hold. Designate the bow hull and fire with the " +
|
||||
"aim anywhere: the forward guns fire on it and hit. The side guns fire at their beam hull and never through " +
|
||||
"the hull. Designate the starboard hull, aim ahead and fire its group: it fires on the hull without the aim " +
|
||||
"and the port group holds; undesignate and aim to port: the port group fires free. The turret tracks you " +
|
||||
"all the way round.";
|
||||
public override uint Seed => 103;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// Where the targets sit: the player is at the origin facing +z, and every mount fires forward.
|
||||
public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 0);
|
||||
// Where the targets sit: the player is at the origin facing +z. The forward mounts fire forward, the starboard mount
|
||||
// (Clockwise) along +x and the port mount (CounterClockwise) along -x.
|
||||
public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 300),
|
||||
Port = float2(-400, 0), Starboard = float2(400, 0);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude();
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var fighter = stage.Fit("LonginusX",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Traction", int2(2, 3), None),
|
||||
("Core Power", int2(2, 1), None),
|
||||
("GT 3K", int2(0, 5), None),
|
||||
("GT 3K", int2(5, 5), None),
|
||||
("FastBlast+-", int2(1, 8), None),
|
||||
("FastBlast+-", int2(4, 8), None),
|
||||
("Iapyx", int2(1, 2), CounterClockwise),
|
||||
("Iapyx", int2(4, 2), Clockwise),
|
||||
("not if i see you first", int2(3, 10), None),
|
||||
("Fire Control Array", int2(2, 5), None));
|
||||
var fighter = stage.Fit("Smoke Test Hull",
|
||||
("Cockpit 2x2", int2(4, 6), None),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Large Drive", int2(5, 0), Reversed),
|
||||
("Rugged Drive", int2(4, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(5, 14), Clockwise),
|
||||
("Compact Reactor", int2(4, 4), None),
|
||||
("Guided Missile Launcher", int2(2, 5), None),
|
||||
("Guided Missile Launcher", int2(7, 5), None),
|
||||
("Cell Blaster", int2(3, 8), None),
|
||||
("Cell Blaster", int2(6, 8), None),
|
||||
("Radiator", int2(4, 2), CounterClockwise),
|
||||
("Radiator", int2(5, 2), Clockwise),
|
||||
("Compact Sensor", int2(5, 10), None),
|
||||
("Fire Control Array", int2(3, 6), Clockwise),
|
||||
("Autocannon", int2(8, 4), Clockwise),
|
||||
("Charged Scatter Blaster", int2(0, 4), CounterClockwise));
|
||||
var turret = stage.Fit("Turret",
|
||||
("ClearPath", int2(1, 2), None),
|
||||
("ClearPath", int2(5, 2), None),
|
||||
("Skiron", int2(0, 2), CounterClockwise),
|
||||
("Skiron", int2(7, 2), Clockwise),
|
||||
("Core Power", int2(3, 3), None),
|
||||
("Light Machine Gun", int2(1, 2), None),
|
||||
("Light Machine Gun", int2(5, 2), None),
|
||||
("Long Radiator", int2(0, 2), CounterClockwise),
|
||||
("Long Radiator", int2(7, 2), Clockwise),
|
||||
("Compact Reactor", int2(3, 3), None),
|
||||
("Turret Control Module", int2(3, 5), None),
|
||||
("not if i see you first", int2(4, 5), None),
|
||||
("Compact Sensor", int2(4, 5), None),
|
||||
("Fire Control Array", int2(3, 6), None));
|
||||
|
||||
stage.Player(fighter, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Place(stage.Bare("LonginusX"), Bow);
|
||||
stage.Place(stage.Bare("LonginusX"), Stern);
|
||||
stage.Place(stage.Bare("Longinus"), Bow);
|
||||
stage.Place(stage.Bare("Longinus"), Stern);
|
||||
stage.Place(turret, Turret, stance: ScenarioStance.Hostile);
|
||||
stage.Place(stage.Bare("Longinus"), Port);
|
||||
stage.Place(stage.Bare("Longinus"), Starboard);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
48
Assets/Scripts/ServerShared/Scenarios/Belt.cs
Normal file
48
Assets/Scripts/ServerShared/Scenarios/Belt.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
using System.Linq;
|
||||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class Belt : Scenario
|
||||
{
|
||||
public override string Name => "Belt";
|
||||
public override string Brief => "The biggest asteroid belt the generator made, with the Longinus parked 100 m outside its ring, facing along it, " +
|
||||
"and nothing else in the arena. Verify: next and previous target step through the rocks and the reticle sweeps " +
|
||||
"across the belt without a hitch; Previous with nothing targeted takes the farthest rock; the target indicator " +
|
||||
"sits on the rock it names.";
|
||||
|
||||
// Seeds 1-256 scanned for the arena whose entrance zone holds the belt with the most asteroids: seed 24, a belt of
|
||||
// 615 rocks. The next four: 179 (553), 251 (548), 221 (532), 29 (515).
|
||||
public override uint Seed => 24;
|
||||
public override bool Ambient => false;
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var fighter = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Guided Missile Launcher", int2(5, 5), None),
|
||||
("Lightning Projector", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise));
|
||||
|
||||
// The belt is a ring about its parent's position at the belt orbit's distance. The player stands 100 m outside
|
||||
// it, at the point nearest the origin, facing along the ring.
|
||||
var arena = stage.Arena;
|
||||
var belt = arena.Planets.Values.OfType<AsteroidBeltData>().OrderByDescending(candidate => candidate.Asteroids.Length).First();
|
||||
var orbit = arena.Orbits[belt.Orbit.Key].Data;
|
||||
var centre = arena.GetOrbitPosition(orbit.Parent.Key);
|
||||
var outward = lengthsq(centre) > 0f ? normalize(-centre) : float2(1, 0);
|
||||
var at = centre + outward * (orbit.Distance + 100f);
|
||||
stage.Player(fighter, at, facing: float2(-outward.y, outward.x));
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/Belt.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/Belt.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 6177c598b87544d6bb0cefdfb4f01acc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
52
Assets/Scripts/ServerShared/Scenarios/Crossing.cs
Normal file
52
Assets/Scripts/ServerShared/Scenarios/Crossing.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class Crossing : Scenario
|
||||
{
|
||||
public override string Name => "Crossing";
|
||||
public override string Brief => "A Lightning Projector at the starboard gun and a Cell Blaster at the port gun, an unpiloted Djinni coasting across the bow " +
|
||||
"close ahead and an unpiloted one waiting at range. The crosser is launched to port at 50 m/s and only coasts: nothing steers it, " +
|
||||
"its hull drag slows it to about 25 m/s at the bow line, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " +
|
||||
"(thrusting from the start carries you past it). Verify: as the Djinni crosses close, FastBlast lands some and projector " +
|
||||
"almost none; against the Djinni at range both land. Fly it again without the Fire Control Array: " +
|
||||
"with it the small gun lands more.";
|
||||
public override uint Seed => 112;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// Where the Djinni sit: the player is at Origin facing +z. Origin is 250 m or more from every body, where the zone's
|
||||
// pull is weakest (about 1.4 u/s^2; the sum of the wells never drops to nothing, and at the old origin the player sat on the star).
|
||||
// The crosser is unpiloted and placed moving at the Djinni's 50 m/s cap, so its pass is ballistic: bent by the field and slowed
|
||||
// by hull drag (it reaches the bow line at about 25 m/s relative to the player, 3.6 s in), and nothing steers it.
|
||||
// CrosserAt is the centre of the start window in which the pass holds: shifting it by 10 m along either axis keeps the pass
|
||||
// inside the test's time and distance windows (CrossingHoldsAcrossTheStartWindow).
|
||||
// The waiting Djinni sits inside the Lightning Projector's arc at 80% of its Range.
|
||||
public static readonly CultMath.float2 Origin = float2(724, 124);
|
||||
public static readonly CultMath.float2 CrosserAt = Origin + float2(-128, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(50, 0);
|
||||
public const float ProjectorRange = 1216f; // the Lightning Projector's Range in metres, 1216.4 as the fit stands settled at rest
|
||||
public static readonly CultMath.float2 Waiting = Origin + float2(0, ProjectorRange * .8f);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var fighter = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Guided Missile Launcher", int2(5, 5), None),
|
||||
("Lightning Projector", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise));
|
||||
|
||||
stage.Player(fighter, Origin, facing: float2(0, 1));
|
||||
stage.Place(stage.Generated("Djinni"), CrosserAt, facing: CrosserFacing, stance: ScenarioStance.Hostile, velocity: CrosserVelocity);
|
||||
stage.Place(stage.Bare("Djinni"), Waiting);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/Crossing.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/Crossing.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 0cc3edfb4b0e4ea485cce71354f41748
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
41
Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs
Normal file
41
Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
using float2 = CultMath.float2;
|
||||
|
||||
// The demo: one gate, one region and one boss, with a fixed cast. The Pirates are the protagonist's ostensible
|
||||
// employer, Zhestokost the antagonist whose home is the boss zone and the exit, Lucent Media and Aeronautics Unlimited
|
||||
// the neutrals. A prelude galaxy of that cast; the player, who is not a Pirate, flies the base Longinus.
|
||||
public sealed class DemoTerminus : Scenario
|
||||
{
|
||||
public static readonly TutorialGenerationSettings Cast = new TutorialGenerationSettings
|
||||
{
|
||||
ProtagonistFaction = "Pirates",
|
||||
AntagonistFaction = "Zhe",
|
||||
BufferFaction = "Luc",
|
||||
NeutralFactions = new[] { "Aero" },
|
||||
QuestFaction = null,
|
||||
ZoneCount = 64,
|
||||
LinkDensity = .5f
|
||||
};
|
||||
|
||||
public override string Name => "Terminus (Demo)";
|
||||
public override string Brief => "One gate, one region, one boss. Allied: the Pirates. Opposed: Zhestokost. " +
|
||||
"Neutral: Lucent Media and Aeronautics Unlimited.";
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage)
|
||||
{
|
||||
var galaxy = stage.Prelude(Cast);
|
||||
galaxy.PlaceGate(galaxy.ResolveFaction(Cast.AntagonistFaction));
|
||||
return galaxy;
|
||||
}
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var galaxy = stage.Galaxy;
|
||||
var pirates = galaxy.ResolveFaction(Cast.ProtagonistFaction);
|
||||
galaxy.FactionRelationships[pirates] = FactionRelationship.Friendly;
|
||||
galaxy.FactionRelationships[galaxy.ResolveFaction(Cast.AntagonistFaction)] = FactionRelationship.Hated;
|
||||
galaxy.FactionRelationships[galaxy.ResolveFaction(Cast.BufferFaction)] = FactionRelationship.Neutral;
|
||||
foreach (var neutral in Cast.NeutralFactions)
|
||||
galaxy.FactionRelationships[galaxy.ResolveFaction(neutral)] = FactionRelationship.Neutral;
|
||||
stage.Player(stage.Generated("Longinus"), float2.zero);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 5ba7152d3c8b46a98924a4148be550db
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -3,13 +3,22 @@ using float2 = CultMath.float2;
|
|||
public sealed class DjinniShakedown : Scenario
|
||||
{
|
||||
public override string Name => "Djinni Shakedown";
|
||||
public override string Brief => "A fitted Djinni in empty space. Verify: its thrusters move and turn it; with the hull " +
|
||||
"offline and thrusters firing, its speed does not run away.";
|
||||
public override string Brief => "A fitted Djinni in empty space, facing +z, with a bare hull dead ahead and one abeam. Verify: its thrusters " +
|
||||
"move and turn it; with the hull offline and thrusters firing, its speed does not run away. Its " +
|
||||
"articulated ballistic barrel points at the hull ahead when it bears, and rests at the arc edge while you " +
|
||||
"aim at the hull abeam.";
|
||||
public override uint Seed => 101;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// Where the targets sit: the ballistic mount faces +z, so Ahead is inside its arc and Abeam outside it.
|
||||
public static readonly float2 Ahead = new float2(0, 400), Abeam = new float2(400, 0);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude();
|
||||
|
||||
public override void Stage(ScenarioStage stage) =>
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
stage.Player(stage.Generated("Djinni"), float2.zero);
|
||||
stage.Place(stage.Bare("Longinus"), Ahead);
|
||||
stage.Place(stage.Bare("Longinus"), Abeam);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ using static ItemRotation;
|
|||
public sealed class Duel : Scenario
|
||||
{
|
||||
public override string Name => "Duel";
|
||||
public override string Brief => "One piloted, hostile LonginusX with slow GT 3K missiles and a Spectra in its hold. Verify: rolled " +
|
||||
public override string Brief => "One piloted, hostile Longinus with slow guided missiles and a Light Laser in its hold. Verify: rolled " +
|
||||
"hits and near-misses, subsystem aim, beam reads above bow, armour takes the missile, loot keeps its brand.";
|
||||
public override uint Seed => 104;
|
||||
public override bool Ambient => false;
|
||||
|
|
@ -13,23 +13,26 @@ public sealed class Duel : Scenario
|
|||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var fighter = stage.Fit("LonginusX",
|
||||
var fighter = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Traction", int2(2, 3), None),
|
||||
("Core Power", int2(2, 1), None),
|
||||
("GT 3K", int2(0, 5), None),
|
||||
("GT 3K", int2(5, 5), None),
|
||||
("FastBlast+-", int2(1, 8), None),
|
||||
("FastBlast+-", int2(4, 8), None),
|
||||
("Iapyx", int2(1, 2), CounterClockwise),
|
||||
("Iapyx", int2(4, 2), Clockwise),
|
||||
("not if i see you first", int2(3, 10), None),
|
||||
("PotaT+-", int2(1, 5), None),
|
||||
("Fire Control Array", int2(2, 5), None),
|
||||
("Store-All Plus", int2(2, 8), None));
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Guided Missile Launcher", int2(5, 5), None),
|
||||
("Cell Blaster", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Capacitor", int2(1, 5), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise),
|
||||
("Cargo Bay", int2(2, 8), None));
|
||||
|
||||
stage.Player(fighter, float2(0, 0));
|
||||
var rival = stage.Place(fighter, float2(0, 900), facing: float2(0, -1), stance: ScenarioStance.Hostile, piloted: true);
|
||||
stage.Cargo(rival, "Spectra");
|
||||
stage.Cargo(rival, "Light Laser");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
51
Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs
Normal file
51
Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class FusedRounds : Scenario
|
||||
{
|
||||
public override string Name => "Fused Rounds";
|
||||
public override string Brief => "The Smoke Test Hull with Smoke Proximity, Smoke Delayed and a Cluster Cannon; a hostile bare Longinus at mid range, a bare " +
|
||||
"hull dead ahead, a fragile one to starboard, a close one inside the proximity blast radius, and one astern. " +
|
||||
"Verify with nothing selected: aim past every hull and the round bursts at max range along the aim; aim at the hull " +
|
||||
"ahead and it stops and bursts on it; fire the Cluster Cannon at the fragile hull and, once it is hurt, a Smoke " +
|
||||
"Proximity round at it: the hull dies before the round lands, no burst. Select the astern hull: the round fires and bursts at its range along the arc edge. Select the " +
|
||||
"close hull: the burst is pushed out to the blast radius from your centre. A Smoke Proximity burst beside the " +
|
||||
"Longinus damages where the model shows the blast; a Smoke Delayed round into its nose bursts inside. The HUD " +
|
||||
"reads Direct, Burst at N m or Refused for the fused weapons and a percentage for the Cluster Cannon, and the " +
|
||||
"smoke weapons show no Manufacturer row.";
|
||||
public override uint Seed => 108;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// Where everything sits: the player is at the origin facing +z. Ahead lies on the initial aim line, inside every forward
|
||||
// mount's arc. Fragile is a bare Longinus inside the Cluster Cannon's effective range (full damage; the scenario test reads the bound from the weapon); Close is inside Smoke Proximity's blast radius
|
||||
// (8 m from the ship's centre) and beside the aim line, not across it; Stern is outside every mount's arc.
|
||||
public static readonly CultMath.float2 Mid = float2(-200, 600), Ahead = float2(0, 300), Fragile = float2(80, 240),
|
||||
Close = float2(6.4f, 4f), Stern = float2(0, -400);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var shooter = stage.Fit("Smoke Test Hull",
|
||||
("Cockpit 2x2", int2(4, 6), None),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Large Drive", int2(5, 0), Reversed),
|
||||
("Rugged Drive", int2(4, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(5, 14), Clockwise),
|
||||
("Compact Reactor", int2(4, 4), None),
|
||||
("Smoke Proximity", int2(3, 8), None),
|
||||
("Smoke Delayed", int2(6, 8), None),
|
||||
("Cluster Cannon", int2(5, 17), None),
|
||||
("Radiator", int2(4, 2), CounterClockwise),
|
||||
("Radiator", int2(5, 2), Clockwise),
|
||||
("Compact Sensor", int2(5, 10), None),
|
||||
("Fire Control Array", int2(3, 6), Clockwise));
|
||||
|
||||
stage.Player(shooter, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Place(stage.Bare("Longinus"), Mid, stance: ScenarioStance.Hostile);
|
||||
stage.Place(stage.Bare("Longinus"), Ahead);
|
||||
stage.Place(stage.Bare("Longinus"), Fragile);
|
||||
stage.Place(stage.Bare("Longinus"), Close);
|
||||
stage.Place(stage.Bare("Longinus"), Stern);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4afe22415e8546849f2366c39a40fd8f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -4,8 +4,8 @@ using static ItemRotation;
|
|||
public sealed class LauncherAngles : Scenario
|
||||
{
|
||||
public override string Name => "Launcher Angles";
|
||||
public override string Brief => "A GT 3K, a pswarm and two FastBlasts; a hostile LonginusX broadside on, a bare Longinus beside it. " +
|
||||
"Verify: hits pulse only the facing edge; a pswarm round whose target dies fades unexploded.";
|
||||
public override string Brief => "A Guided Missile Launcher, a Swarm Rocket Pod and two Cell Blasters; a hostile bare Longinus broadside on, another beside it. " +
|
||||
"Verify: hits pulse only the facing edge; a Swarm Rocket Pod round whose target dies fades unexploded.";
|
||||
public override uint Seed => 105;
|
||||
public override bool Ambient => false;
|
||||
|
||||
|
|
@ -13,21 +13,24 @@ public sealed class LauncherAngles : Scenario
|
|||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var launcher = stage.Fit("LonginusX",
|
||||
var launcher = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Traction", int2(2, 3), None),
|
||||
("Core Power", int2(2, 1), None),
|
||||
("GT 3K", int2(0, 5), None),
|
||||
("pswarm", int2(5, 5), None),
|
||||
("FastBlast+-", int2(1, 8), None),
|
||||
("FastBlast+-", int2(4, 8), None),
|
||||
("Iapyx", int2(1, 2), CounterClockwise),
|
||||
("Iapyx", int2(4, 2), Clockwise),
|
||||
("not if i see you first", int2(3, 10), None),
|
||||
("Fire Control Array", int2(2, 5), None));
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Swarm Rocket Pod", int2(5, 5), None),
|
||||
("Cell Blaster", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise));
|
||||
|
||||
stage.Player(launcher, float2(0, 0));
|
||||
stage.Place(stage.Bare("LonginusX"), float2(0, 900), facing: float2(1, 0), stance: ScenarioStance.Hostile);
|
||||
stage.Place(stage.Bare("Longinus"), float2(0, 900), facing: float2(1, 0), stance: ScenarioStance.Hostile);
|
||||
stage.Place(stage.Bare("Longinus"), float2(300, 700));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
46
Assets/Scripts/ServerShared/Scenarios/LockOn.cs
Normal file
46
Assets/Scripts/ServerShared/Scenarios/LockOn.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class LockOn : Scenario
|
||||
{
|
||||
public override string Name => "Lock On";
|
||||
public override string Brief => "A hostile closes from out of sight, finds you and locks. Verify: no warning at first; once it locks, one " +
|
||||
"indicator appears toward it and tightens as the lock grows; break line of sight or range and it vanishes; " +
|
||||
"your own ping shows no incoming paint on its side, only the lock does.";
|
||||
public override uint Seed => 113;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// The hostile starts about 4000 m off, ahead and to port of the player, facing the player. At that range its passive
|
||||
// sensors hold no track of the player (the test asks the sim's own PassiveInfo against the detection threshold). The
|
||||
// hostile closes, sees the player some fourteen seconds in and locks. The zone's pull bends the hostile's run and moves the
|
||||
// player, and the warning must still point at where the hostile was staged to within 5 degrees at the lock: this side keeps
|
||||
// the bend under one degree (on the far side it is more than seven). At Duel's 900 m (and at 600 m) it sees and locks
|
||||
// within a second.
|
||||
public static readonly CultMath.float2 HostileAt = float2(-2000, 3450);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var fighter = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Guided Missile Launcher", int2(5, 5), None),
|
||||
("Cell Blaster", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Capacitor", int2(1, 5), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise),
|
||||
("Cargo Bay", int2(2, 8), None));
|
||||
|
||||
stage.Player(fighter, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Place(fighter, HostileAt, facing: normalize(-HostileAt), stance: ScenarioStance.Hostile, piloted: true);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/LockOn.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/LockOn.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3f0b6d2a9c7e4a1b8d5e2c6f7a9b0c14
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
60
Assets/Scripts/ServerShared/Scenarios/Pursuit.cs
Normal file
60
Assets/Scripts/ServerShared/Scenarios/Pursuit.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class Pursuit : Scenario
|
||||
{
|
||||
// The pursuer starts astern, inside the 400 at which VapourCloudTests.ACloudBreaksALockAtRange shows a fresh vent
|
||||
// cloud breaking a sensor's lock, and well outside the 40 at which AStrongCloseSensorBurnsThrough shows a close
|
||||
// sensor burning through.
|
||||
private const float Astern = 300;
|
||||
|
||||
public override string Name => "Pursuit";
|
||||
public override string Brief => "A hostile Longinus on your tail; a Mine Launcher fitted, three Coolant Vents and two Thruster " +
|
||||
"Overdrives aboard. Verify: lay mines in its path, the mine pulses slowly after 2 s, fast when " +
|
||||
"the hostile is near, explodes 2 s later; vent and coast to lose it; overdrive away.";
|
||||
public override uint Seed => 111;
|
||||
public override bool Ambient => false;
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var layer = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Mine Launcher", int2(0, 5), None),
|
||||
("Swarm Rocket Pod", int2(5, 5), None),
|
||||
("Cell Blaster", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise),
|
||||
("Cargo Bay", int2(2, 8), None));
|
||||
var pursuer = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Compact Reactor", int2(2, 4), None),
|
||||
("Guided Missile Launcher", int2(0, 5), None),
|
||||
("Guided Missile Launcher", int2(5, 5), None),
|
||||
("Cell Blaster", int2(1, 8), None),
|
||||
("Cell Blaster", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Capacitor", int2(1, 5), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise),
|
||||
("Cargo Bay", int2(2, 8), None));
|
||||
|
||||
var player = stage.Player(layer, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Cargo(player, "Coolant Vent", "Coolant Vent", "Coolant Vent", "Thruster Overdrive", "Thruster Overdrive");
|
||||
stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/Pursuit.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/Pursuit.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 4b0587057e6a4618bf63944364298870
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
40
Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs
Normal file
40
Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class RefusedRounds : Scenario
|
||||
{
|
||||
public override string Name => "Refused Rounds";
|
||||
public override string Brief => "The Smoke Test Hull with Smoke Refused, Smoke Refused Beam, Smoke Refused Charge and an Autocannon; a bare Longinus " +
|
||||
"dead ahead. Each smoke weapon's blast radius is wider than its range, so it can never be fired. Verify: pull each " +
|
||||
"trigger and a refused shot costs no ammo, energy, heat, sound, visibility or cooldown, the beam never starts and " +
|
||||
"the charged weapon never starts charging; the Autocannon fires normally.";
|
||||
public override uint Seed => 109;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// The one target, ahead of the nose: inside every forward mount's arc.
|
||||
public static readonly CultMath.float2 Target = float2(0, 300);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var shooter = stage.Fit("Smoke Test Hull",
|
||||
("Cockpit 2x2", int2(4, 6), None),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Large Drive", int2(5, 0), Reversed),
|
||||
("Rugged Drive", int2(4, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(5, 14), Clockwise),
|
||||
("Compact Reactor", int2(4, 4), None),
|
||||
("Smoke Refused", int2(3, 8), None),
|
||||
("Smoke Refused Beam", int2(6, 8), None),
|
||||
("Smoke Refused Charge", int2(3, 17), None),
|
||||
("Autocannon", int2(5, 17), None),
|
||||
("Radiator", int2(4, 2), CounterClockwise),
|
||||
("Radiator", int2(5, 2), Clockwise),
|
||||
("Compact Sensor", int2(5, 10), None),
|
||||
("Fire Control Array", int2(3, 6), Clockwise));
|
||||
|
||||
stage.Player(shooter, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Place(stage.Bare("Longinus"), Target);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c72528ae3b7144989483462543f2de88
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -1,11 +1,14 @@
|
|||
// Every way to set up a new run, in the order New Game lists them. Modes are the game; Tests are arenas built to check
|
||||
// one system each, listed only in editor and development builds.
|
||||
// Every way to set up a new run, in the order New Game lists them. Modes are what a release build lists; Development
|
||||
// are the other ways the game sets up a run and Tests are arenas built to check one system each, both listed only in
|
||||
// editor and development builds.
|
||||
public static class Scenarios
|
||||
{
|
||||
public static readonly Scenario[] Modes = { new TutorialGalaxy(), new MainGalaxy() };
|
||||
public static readonly Scenario[] Modes = { new DemoTerminus() };
|
||||
|
||||
public static readonly Scenario[] Development = { new TutorialGalaxy(), new MainGalaxy() };
|
||||
|
||||
public static readonly Scenario[] Tests =
|
||||
{
|
||||
new DjinniShakedown(), new StarvedReactor(), new Arcs(), new Duel(), new LauncherAngles(), new LongHaul()
|
||||
new DjinniShakedown(), new StarvedReactor(), new Arcs(), new Duel(), new LauncherAngles(), new WeaponFeel(), new FusedRounds(), new RefusedRounds(), new AiFusedDiscipline(), new LongHaul(), new Pursuit(), new Crossing(), new Belt(), new LockOn()
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ using static ItemRotation;
|
|||
public sealed class StarvedReactor : Scenario
|
||||
{
|
||||
public override string Name => "Starved Reactor";
|
||||
public override string Brief => "Two Spectras on a MoveOnPro, which can fall to a quarter of Core Power's charge, and a bare hull " +
|
||||
public override string Brief => "Two Light Lasers on a Muon Fusion Reactor, which can fall to a quarter of the Compact Reactor's charge, and a bare hull " +
|
||||
"to shoot. Verify: starvation reads as starvation, brownout degrades, refills stutter.";
|
||||
public override uint Seed => 102;
|
||||
public override bool Ambient => false;
|
||||
|
|
@ -13,17 +13,20 @@ public sealed class StarvedReactor : Scenario
|
|||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var starved = stage.Fit("LonginusX",
|
||||
var starved = stage.Fit("Longinus",
|
||||
("Cockpit 2x2", int2(2, 6), None),
|
||||
("Traction", int2(2, 3), None),
|
||||
("MoveOnPro", int2(2, 1), None),
|
||||
("Spectra", int2(1, 8), None),
|
||||
("Spectra", int2(4, 8), None),
|
||||
("Iapyx", int2(1, 2), CounterClockwise),
|
||||
("Iapyx", int2(4, 2), Clockwise),
|
||||
("not if i see you first", int2(3, 10), None),
|
||||
("Fire Control Array", int2(2, 5), None));
|
||||
("Large Drive", int2(1, 0), Reversed),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Rugged Drive", int2(2, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(3, 14), Clockwise),
|
||||
("Muon Fusion Reactor", int2(2, 4), None),
|
||||
("Light Laser", int2(1, 8), None),
|
||||
("Light Laser", int2(4, 8), None),
|
||||
("Radiator", int2(2, 2), CounterClockwise),
|
||||
("Radiator", int2(3, 2), Clockwise),
|
||||
("Compact Sensor", int2(3, 10), None),
|
||||
("Fire Control Array", int2(1, 6), Clockwise));
|
||||
stage.Player(starved, float2(0, 0));
|
||||
stage.Place(stage.Bare("LonginusX"), float2(0, 400));
|
||||
stage.Place(stage.Bare("Longinus"), float2(0, 400));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
38
Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs
Normal file
38
Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
using static CultMath.math;
|
||||
using static ItemRotation;
|
||||
|
||||
public sealed class WeaponFeel : Scenario
|
||||
{
|
||||
public override string Name => "Weapon Feel";
|
||||
public override string Brief => "The Smoke Test Hull with a Charged Scatter Blaster, an Autocannon and a Cell Blaster burst weapon; a bare Longinus dead ahead. " +
|
||||
"Verify: Charged Scatter Blaster and Autocannon fire with effects, particles and action-bar icons; the burst weapon's " +
|
||||
"cadence is as before; a fast release-and-press on the Charged Scatter Blaster starts no second charge.";
|
||||
public override uint Seed => 107;
|
||||
public override bool Ambient => false;
|
||||
|
||||
// The one target, ahead of the nose: inside every forward mount's arc.
|
||||
public static readonly CultMath.float2 Target = float2(0, 400);
|
||||
|
||||
public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast);
|
||||
|
||||
public override void Stage(ScenarioStage stage)
|
||||
{
|
||||
var shooter = stage.Fit("Smoke Test Hull",
|
||||
("Cockpit 2x2", int2(4, 6), None),
|
||||
("Large Drive", int2(3, 0), Reversed),
|
||||
("Large Drive", int2(5, 0), Reversed),
|
||||
("Rugged Drive", int2(4, 14), CounterClockwise),
|
||||
("Rugged Drive", int2(5, 14), Clockwise),
|
||||
("Compact Reactor", int2(4, 4), None),
|
||||
("Charged Scatter Blaster", int2(3, 17), None),
|
||||
("Autocannon", int2(5, 17), None),
|
||||
("Cell Blaster", int2(3, 8), None),
|
||||
("Radiator", int2(4, 2), CounterClockwise),
|
||||
("Radiator", int2(5, 2), Clockwise),
|
||||
("Compact Sensor", int2(5, 10), None),
|
||||
("Fire Control Array", int2(3, 6), Clockwise));
|
||||
|
||||
stage.Player(shooter, float2(0, 0), facing: float2(0, 1));
|
||||
stage.Place(stage.Bare("Longinus"), Target);
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 74c554ab5a6a4ac5ad0334a29135dc7f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
224
Assets/Scripts/ServerShared/Sensing.cs
Normal file
224
Assets/Scripts/ServerShared/Sensing.cs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
/* 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.Linq;
|
||||
using CultMath;
|
||||
|
||||
// Light signatures split by channel (ruling visibility-per-capability-reveal): an observer learns what a ship
|
||||
// is by which channel carries the light. Append-only: values are serialized in VisibilityData.
|
||||
public enum SignatureChannel
|
||||
{
|
||||
Thermal,
|
||||
Reflection,
|
||||
DrivePlume,
|
||||
LaunchFlash,
|
||||
Emission
|
||||
}
|
||||
|
||||
public readonly struct Signature
|
||||
{
|
||||
public readonly SignatureChannel Channel;
|
||||
public readonly float Strength;
|
||||
public readonly EquippedItem Item;
|
||||
// The class this act claims: the true item's Data unless its ship's EW claims otherwise (aetheria-ew,
|
||||
// classify-from-belief). Stamped by Entity.SetSignature from the ship's claim.
|
||||
public readonly EquippableItemData Claimed;
|
||||
|
||||
public Signature(SignatureChannel channel, float strength, EquippedItem item, EquippableItemData claimed)
|
||||
{
|
||||
Channel = channel;
|
||||
Strength = strength;
|
||||
Item = item;
|
||||
Claimed = claimed;
|
||||
}
|
||||
|
||||
public Signature WithStrength(float strength) => new Signature(Channel, strength, Item, Claimed);
|
||||
}
|
||||
|
||||
// What a painted ship learns of a beam on it (ruling sensor-stat-set item 4): a Search paint is a ping sweeping
|
||||
// it (Strength 0); a Track paint is a lock (Strength is the emitter's own lock progress, 0..1, ruling
|
||||
// lock-warning-strength). A Scan paint is a held scanner: Strength is its scan progress 0..1 (ruling scan-is-an-act).
|
||||
// Never summed.
|
||||
public enum PaintMode
|
||||
{
|
||||
Search,
|
||||
Track,
|
||||
Scan
|
||||
}
|
||||
|
||||
// An ally's ping crossed `Subject` at `IlluminatedRange` through `IlluminatedObscuration`; `MaxRange` is that
|
||||
// sensor's PingRange. Posted on the crossing tick and read for one tick by the receiving ship's own sensors.
|
||||
public readonly struct PingReturn
|
||||
{
|
||||
public readonly Entity Subject;
|
||||
public readonly float IlluminatedRange;
|
||||
public readonly float IlluminatedObscuration;
|
||||
public readonly float MaxRange;
|
||||
|
||||
public PingReturn(Entity subject, float illuminatedRange, float illuminatedObscuration, float maxRange)
|
||||
{
|
||||
Subject = subject;
|
||||
IlluminatedRange = illuminatedRange;
|
||||
IlluminatedObscuration = illuminatedObscuration;
|
||||
MaxRange = maxRange;
|
||||
}
|
||||
}
|
||||
|
||||
// An item's emission this tick, heard by another ship's Sense within `HearRange` x its HearingMultiple x obscuration;
|
||||
// it decides nothing by itself.
|
||||
public readonly struct ActiveEmission
|
||||
{
|
||||
public readonly EquippedItem Item;
|
||||
public readonly float HearRange;
|
||||
// The class this emission claims (see Signature.Claimed); stamped by Entity.Emit.
|
||||
public readonly EquippableItemData Claimed;
|
||||
|
||||
public ActiveEmission(EquippedItem item, float hearRange, EquippableItemData claimed)
|
||||
{
|
||||
Item = item;
|
||||
HearRange = hearRange;
|
||||
Claimed = claimed;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct PaintWarning
|
||||
{
|
||||
public readonly float2 Bearing;
|
||||
public readonly EquippableItemData EmitterClass;
|
||||
public readonly PaintMode Mode;
|
||||
public readonly float Strength;
|
||||
|
||||
public PaintWarning(float2 bearing, EquippableItemData emitterClass, PaintMode mode, float strength)
|
||||
{
|
||||
Bearing = bearing;
|
||||
EmitterClass = emitterClass;
|
||||
Mode = mode;
|
||||
Strength = strength;
|
||||
}
|
||||
}
|
||||
|
||||
// What an observer has seen `Item` do (ruling visibility-per-capability-reveal): the channel it showed on, the
|
||||
// bearing at that act and the zone clock then. Held per (subject, item) in the observer's Entity; the latest act
|
||||
// replaces the earlier one. Position is never carried: only the track gives it. `Item` stays the true item: it is the
|
||||
// book's key and what aim reads. `Claimed` is the class the act claimed, and is what every classifying reader reads
|
||||
// (aetheria-ew, classify-from-belief). A null `Channel` is a reveal by the observer's own scan (Entity.RecordInspection),
|
||||
// whose `Claimed` is the subject's claim for the item.
|
||||
public readonly struct Reveal
|
||||
{
|
||||
public readonly EquippedItem Item;
|
||||
public readonly EquippableItemData Claimed;
|
||||
public readonly SignatureChannel? Channel;
|
||||
public readonly float2 Bearing;
|
||||
public readonly float Time;
|
||||
|
||||
public Reveal(EquippedItem item, SignatureChannel? channel, float2 bearing, float time, EquippableItemData claimed)
|
||||
{
|
||||
Item = item;
|
||||
Claimed = claimed;
|
||||
Channel = channel;
|
||||
Bearing = bearing;
|
||||
Time = time;
|
||||
}
|
||||
}
|
||||
|
||||
// What an observer aims at on its target (Entity.AimedAt): exactly one of a revealed item or a mount of the hull the observer
|
||||
// believes the target to be (Entity.LayoutOf), or nothing. A mount is a believed position, never the true item on it.
|
||||
public readonly struct AimTarget
|
||||
{
|
||||
public readonly EquippedItem Item;
|
||||
public readonly HardpointData Mount;
|
||||
|
||||
private AimTarget(EquippedItem item, HardpointData mount)
|
||||
{
|
||||
Item = item;
|
||||
Mount = mount;
|
||||
}
|
||||
|
||||
public static AimTarget None => default;
|
||||
public static AimTarget OfItem(EquippedItem item) => new AimTarget(item, null);
|
||||
public static AimTarget OfMount(HardpointData mount) => new AimTarget(null, mount);
|
||||
}
|
||||
|
||||
// One weapon or gear row of a ship's schematic as its viewer is entitled to read it (aetheria-ew, classify-from-belief; ruling
|
||||
// ew-claim-weapon-measure-ruled). Made only by Entity.SchematicRows. `Item` is the true item: the selection mark's key and,
|
||||
// on the viewer's own ship, the live gear. `Claimed` is the class the row shows. The range label is the live range on
|
||||
// the viewer's own ship and the claimed design's rated range on any other; a row whose claimed class is not a weapon has
|
||||
// no range. The viewer never sees a target item's quality, wear or power. A renderer shows these and decides nothing.
|
||||
// A mount row (`Mount` set, `Item` and `Claimed` null) is a hardpoint of the hull the viewer believes the ship to be, with
|
||||
// nothing of the ship's claimed on it: where something is, not what.
|
||||
public readonly struct SchematicRow
|
||||
{
|
||||
public readonly EquippedItem Item;
|
||||
public readonly EquippableItemData Claimed;
|
||||
public readonly HardpointData Mount;
|
||||
private readonly bool _own;
|
||||
|
||||
internal SchematicRow(EquippedItem item, EquippableItemData claimed, bool own)
|
||||
{
|
||||
Item = item;
|
||||
Claimed = claimed;
|
||||
Mount = null;
|
||||
_own = own;
|
||||
}
|
||||
|
||||
internal SchematicRow(HardpointData mount) : this()
|
||||
{
|
||||
Mount = mount;
|
||||
}
|
||||
|
||||
// What a renderer compares to know the rows changed. Range is a reading, not part of the key.
|
||||
public (EquippedItem, EquippableItemData, HardpointData) Key => (Item, Claimed, Mount);
|
||||
|
||||
// Whether this row is the one `aim` points at: a claimed-item row by its item, a mount row by its mount.
|
||||
public bool Marks(AimTarget aim) => Item != null ? aim.Item == Item : aim.Mount != null && aim.Mount == Mount;
|
||||
|
||||
public float? Range => _own
|
||||
? Item.Behaviors.OfType<Weapon>().First().Range
|
||||
: Claimed?.Behaviors.OfType<WeaponData>().FirstOrDefault()?.RatedRange;
|
||||
}
|
||||
|
||||
// A subject's removal from a zone as the zone recorded it (death, dock, warp, any removal): where it was and how
|
||||
// bright its light was (its Visibility at removal). Judged by each observer's Sense under the
|
||||
// light-act gate; notification only, one tick long, it decides nothing.
|
||||
public readonly struct Departure
|
||||
{
|
||||
public readonly Entity Subject;
|
||||
public readonly float2 Position;
|
||||
public readonly float Signature;
|
||||
|
||||
public Departure(Entity subject, float2 position, float signature)
|
||||
{
|
||||
Subject = subject;
|
||||
Position = position;
|
||||
Signature = signature;
|
||||
}
|
||||
}
|
||||
|
||||
// How much an observer holds of one subject, derived on read by Entity.ContactOf from its track, its reveals and
|
||||
// the zone clock. Detected: tracked, or a reveal younger than GameplaySettings.BearingMemory. Tracked: exactly
|
||||
// membership of VisibleEntities. Classified: detected, with any reveal in the book. Identified: the track has reached
|
||||
// TargetGearInfoThreshold, and holds a hull belief: Profile, the hull class this observer believes the subject is (null
|
||||
// below Identified; aetheria-ew, classify-from-belief; seen-through arrives with the judge). Bearing is the true
|
||||
// bearing while tracked, else the freshest reveal's.
|
||||
public readonly struct Contact
|
||||
{
|
||||
public readonly bool Detected;
|
||||
public readonly bool Tracked;
|
||||
public readonly bool Classified;
|
||||
public readonly bool Identified;
|
||||
public readonly float2 Bearing;
|
||||
public readonly float Info;
|
||||
public readonly HullData Profile;
|
||||
|
||||
public Contact(bool detected, bool tracked, bool classified, bool identified, float2 bearing, float info, HullData profile)
|
||||
{
|
||||
Profile = profile;
|
||||
Detected = detected;
|
||||
Tracked = tracked;
|
||||
Classified = classified;
|
||||
Identified = identified;
|
||||
Bearing = bearing;
|
||||
Info = info;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/Sensing.cs.meta
Normal file
11
Assets/Scripts/ServerShared/Sensing.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: a3c91e5d7b2f4086b1d4e9f07c6a2358
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
|
|
@ -13,25 +13,27 @@ using static CultMath.math;
|
|||
[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject]
|
||||
public class PlanetSettings
|
||||
{
|
||||
public float ZoneDepthExponent;
|
||||
public float ZoneDepth;
|
||||
public float ZoneBoundaryFog;
|
||||
public ExponentialCurve GravityDepth;
|
||||
public ExponentialCurve GravityRadius;
|
||||
public ExponentialCurve WaveDepth;
|
||||
public ExponentialCurve WaveRadius;
|
||||
public ExponentialCurve WaveFrequency;
|
||||
public ExponentialCurve WaveSpeed;
|
||||
public ExponentialCurve LightRadius;
|
||||
public ExponentialCurve BodyRadius;
|
||||
|
||||
// The closest a child may orbit its parent, in u, by the parent's mass, and the softened core radius of the parent's
|
||||
// well (the steepest drawn slope sits at the Roche limit). Authored like BodyRadius, never per body.
|
||||
public ExponentialCurve RocheLimit = new ExponentialCurve();
|
||||
|
||||
// A body's well strength by its mass (GravityField): c in u^2/s^2 (the pull is c / r beyond the core, which is the Roche limit).
|
||||
public ExponentialCurve WellStrength = new ExponentialCurve();
|
||||
|
||||
// The one global exaggeration of gravity height: height = potential / K, in u/s^2 per unit of height.
|
||||
public float HeightExaggeration = 1f;
|
||||
public float AsteroidVerticalOffset = -5f;
|
||||
public ExponentialLerp AsteroidSize;
|
||||
public ExponentialLerp AsteroidHitpoints;
|
||||
public ExponentialLerp AsteroidRespawnTime;
|
||||
public float GravityStrength;
|
||||
public float SecureAreaRadiusMultiplier = .45f;
|
||||
|
||||
public ExponentialCurve OrbitPeriod;
|
||||
|
||||
// The global flow stardust and nebula follow and the sim knows (FlowField). Zero flow by default.
|
||||
public FlowSettings Flow = new FlowSettings();
|
||||
}
|
||||
|
||||
[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject]
|
||||
|
|
@ -178,6 +180,11 @@ public class GameplaySettings
|
|||
public float FloatingBodyDrag = .05f;
|
||||
public float FloatingBodyLaunchDrag = .2f;
|
||||
public float FloatingBodyGravity = 1f;
|
||||
// Loot: the chance each equipped item (the hull excepted) drops when its carrier dies, the launch speed of a
|
||||
// dropped item, and how many seconds a floating item lasts.
|
||||
public float LootDropProbability = .25f;
|
||||
public float LootDropVelocity = 25f;
|
||||
public float FloatingItemLifetime = 30f;
|
||||
public float SevereHeatstrokeRiskThreshold = .25f;
|
||||
public float WormholeDepth = 1000;
|
||||
public float WormholeExitVelocity = 20;
|
||||
|
|
@ -211,14 +218,13 @@ public class GameplaySettings
|
|||
public float LockIndicatorNoiseAmplitude = 50f;
|
||||
public ExponentialLerp LockIndicatorFrequency;
|
||||
public ExponentialLerp LockSpinSpeed;
|
||||
public float TorqueFloor;
|
||||
public float TorqueMultiplier;
|
||||
public float AetherTorqueMultiplier;
|
||||
public float AetherHeatMultiplier;
|
||||
public float VisibilityDecay;
|
||||
// Seconds a reveal's bearing keeps a ship Detected after its last act with no track (Entity.ContactOf).
|
||||
public float BearingMemory = 6;
|
||||
public float TargetInfoDecay;
|
||||
public float TargetDetectionInfoThreshold;
|
||||
public float TargetArmorInfoThreshold;
|
||||
// Also the Identified threshold: the track level at which a ship's hull class, and with it its layout, is known.
|
||||
public float TargetGearInfoThreshold;
|
||||
public float ConvergenceMinimumDistance;
|
||||
public float FiringArc = 120;
|
||||
|
|
@ -240,7 +246,7 @@ public class GameplaySettings
|
|||
// UnaidedTracking above -- FireControl.Precision falls back to this the same way it already falls back to
|
||||
// UnaidedAccuracy/UnaidedTracking. Precision is now a grouping tightness (FireControl.Sigma = 1/Precision,
|
||||
// in hull-schematic cell units), not the old coin-flip probability, so the unaided floor has to be
|
||||
// authored on that scale. .3 -> sigma 3.33 cells: against the live catalog's own hulls (LonginusX 6x17,
|
||||
// authored on that scale. .3 -> sigma 3.33 cells: against the live catalog's own hulls (Longinus 6x17,
|
||||
// Zenith 12x12, Turret 8x8) that puts pOnHull at the hull's own centre of mass around .5-.84 -- broadly
|
||||
// sprayed across the whole silhouette (sigma is a large fraction of the hull's own width) while still
|
||||
// landing on the ship more often than not. A tighter floor (e.g. .1, sigma 10) was tried first and
|
||||
|
|
@ -268,6 +274,17 @@ public class GameplaySettings
|
|||
// (pSpread) to turn a hull's cell footprint into a real-world silhouette size at range.
|
||||
public float SchematicCellSize = 2f;
|
||||
|
||||
// Restitution of a hull striking a hull (Contacts.Step): the speed at which a pair separates along the contact
|
||||
// normal is this times the speed at which it closed. 0 is perfectly inelastic, 1 perfectly elastic.
|
||||
public float ContactRestitution = .5f;
|
||||
|
||||
// Heights above the field of the ship plane, the orbital layer (stations, turrets: every OrbitalEntity) and the floater
|
||||
// layer (loot, mines): orbitals above ships and floaters below them, so no ship ever touches either (ruling
|
||||
// aetheria-gravity:orbitals-above-floaters-below).
|
||||
public float ShipLayerHeight = 3f;
|
||||
public float OrbitalLayerHeight = 15f;
|
||||
public float FloaterLayerHeight = 0f;
|
||||
|
||||
// The floor an AI's own predicted hit probability (FireControl.HitProbability) must clear before it counts
|
||||
// a firing solution worth taking (Combat.cs, TurretController.cs). Player fire is gated on arc alone
|
||||
// (Weapon.ArcAllowsFire, Q2) -- this threshold is an AI fire-discipline heuristic, not part of the roll.
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ using System.Linq;
|
|||
using System.Reflection;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using UniRx;
|
||||
using CultMath;
|
||||
using static CultMath.math;
|
||||
using quaternion = CultMath.quaternion;
|
||||
|
|
@ -17,6 +16,8 @@ using quaternion = CultMath.quaternion;
|
|||
[MessagePackObject]
|
||||
public class Ship : Entity
|
||||
{
|
||||
public override float LayerHeight => ItemManager.GameplaySettings.ShipLayerHeight;
|
||||
|
||||
|
||||
// [Key("bindings")] public Dictionary<KeyCode,Guid> Bindings = new Dictionary<KeyCode,Guid>();
|
||||
//[IgnoreMember] public int HullHardpointCount;
|
||||
|
|
@ -30,16 +31,11 @@ public class Ship : Entity
|
|||
public float Turn;
|
||||
public bool IsPlayerShip;
|
||||
|
||||
private HashSet<EquippedItem> _thrusterItems;
|
||||
private Thruster[] _allThrusters;
|
||||
private HashSet<Thruster> _forwardThrusters;
|
||||
private HashSet<Thruster> _reverseThrusters;
|
||||
private HashSet<Thruster> _rightThrusters;
|
||||
private HashSet<Thruster> _leftThrusters;
|
||||
private HashSet<Thruster> _clockwiseThrusters;
|
||||
private HashSet<Thruster> _counterClockwiseThrusters;
|
||||
private HashSet<EquippedItem> _aetherDriveItems;
|
||||
private HashSet<AetherDrive> _aetherDrives;
|
||||
// One column per thruster (its effect per unit throttle, in the body frame) and the throttles the allocator answers with.
|
||||
private float3[] _columns;
|
||||
private float[] _throttles;
|
||||
private readonly ThrustAllocator _allocator = new ThrustAllocator();
|
||||
|
||||
private bool _exitingWormhole = false;
|
||||
private bool _enteringWormhole = false;
|
||||
|
|
@ -50,23 +46,6 @@ public class Ship : Entity
|
|||
private float2 _wormholeExitVelocity;
|
||||
|
||||
public bool WormholeAnimationInProgress => _enteringWormhole || _exitingWormhole;
|
||||
public float ForwardThrust { get; private set; }
|
||||
public float ReverseThrust { get; private set; }
|
||||
public float LeftStrafeThrust { get; private set; }
|
||||
public float RightStrafeThrust { get; private set; }
|
||||
public float ClockwiseTorque { get; private set; }
|
||||
public float CounterClockwiseTorque { get; private set; }
|
||||
public float LeftStrafeTotalTorque { get; private set; }
|
||||
private List<Thruster> LeftStrafeTorqueThrusters = new List<Thruster>();
|
||||
public float RightStrafeTotalTorque { get; private set; }
|
||||
private List<Thruster> RightStrafeTorqueThrusters = new List<Thruster>();
|
||||
|
||||
public float TurnTime(float2 direction)
|
||||
{
|
||||
var angleDiff = Direction.Angle(normalize(direction));
|
||||
var clockwise = dot(direction, Direction.Rotate(ItemRotation.Clockwise)) > 0;
|
||||
return angleDiff / ((clockwise ? ClockwiseTorque : CounterClockwiseTorque) / Mass);
|
||||
}
|
||||
|
||||
public event Action OnExitedWormhole;
|
||||
public event Action OnEnteredWormhole;
|
||||
|
|
@ -96,217 +75,65 @@ public class Ship : Entity
|
|||
{
|
||||
base.Activate();
|
||||
|
||||
_aetherDrives = new HashSet<AetherDrive>(GetBehaviors<AetherDrive>());
|
||||
_aetherDriveItems = new HashSet<EquippedItem>(_aetherDrives.Select(x => x.Item));
|
||||
|
||||
_allThrusters = GetBehaviors<Thruster>().ToArray();
|
||||
_thrusterItems = new HashSet<EquippedItem>(_allThrusters.Select(x=>x.Item));
|
||||
|
||||
_forwardThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Reversed));
|
||||
|
||||
_reverseThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.None));
|
||||
|
||||
_rightThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise));
|
||||
|
||||
_leftThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Clockwise));
|
||||
|
||||
_counterClockwiseThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Torque < -ItemManager.GameplaySettings.TorqueFloor));
|
||||
|
||||
_clockwiseThrusters = new HashSet<Thruster>(_allThrusters
|
||||
.Where(x => x.Torque > ItemManager.GameplaySettings.TorqueFloor));
|
||||
_columns = new float3[_allThrusters.Length];
|
||||
_throttles = new float[_allThrusters.Length];
|
||||
}
|
||||
|
||||
public Ship(ItemManager itemManager, Zone zone, EquippableItem hull, EntitySettings settings) : base(itemManager, zone, hull, settings)
|
||||
{
|
||||
ItemDestroyed.Where(item=>_thrusterItems.Contains(item)).Subscribe(RemoveThruster);
|
||||
ItemDestroyed.Where(item=>_aetherDriveItems.Contains(item)).Subscribe(RemoveAetherDrive);
|
||||
}
|
||||
|
||||
private void RemoveAetherDrive(EquippedItem item)
|
||||
{
|
||||
_aetherDriveItems.Remove(item);
|
||||
_aetherDrives.Remove(item.GetBehavior<AetherDrive>());
|
||||
}
|
||||
|
||||
private void RemoveThruster(EquippedItem item)
|
||||
{
|
||||
_thrusterItems.Remove(item);
|
||||
var thruster = item.GetBehavior<Thruster>();
|
||||
if (_forwardThrusters.Contains(thruster)) _forwardThrusters.Remove(thruster);
|
||||
if (_reverseThrusters.Contains(thruster)) _reverseThrusters.Remove(thruster);
|
||||
if (_rightThrusters.Contains(thruster)) _rightThrusters.Remove(thruster);
|
||||
if (_leftThrusters.Contains(thruster)) _leftThrusters.Remove(thruster);
|
||||
if (_clockwiseThrusters.Contains(thruster)) _clockwiseThrusters.Remove(thruster);
|
||||
if (_counterClockwiseThrusters.Contains(thruster)) _counterClockwiseThrusters.Remove(thruster);
|
||||
}
|
||||
|
||||
#region ThrustCalculation
|
||||
|
||||
// What this ship can do at this instant (see ManoeuvreEnvelope): the sum of what each live propulsor reports with
|
||||
// its own Execute arithmetic; thrusters are its only propulsors. Derived each update, never saved. The aggregates above are not an envelope (they
|
||||
// mix units and cancel a lone off-axis strafer), so nothing in it reads them.
|
||||
// What this ship can do at this instant (see ManoeuvreEnvelope): the box extremes of the thrusters' columns at their
|
||||
// live thrust (zero when unpowered or not Active), because it reports what the ship can do now. The allocator solves
|
||||
// with Column(NominalThrust), the full-grant column, because a column promises what a thruster does at a full grant
|
||||
// and the allocator must not reshape its answer as the grant moves. Same geometry (Thruster.Column), different thrust.
|
||||
// Derived each update, never saved.
|
||||
public ManoeuvreEnvelope Envelope { get; private set; }
|
||||
|
||||
private void RecalculateEnvelope()
|
||||
{
|
||||
var envelope = default(ManoeuvreEnvelope);
|
||||
foreach (var thruster in _allThrusters) envelope += thruster.Manoeuvre();
|
||||
Envelope = envelope;
|
||||
}
|
||||
|
||||
private void RecalculateThrust()
|
||||
{
|
||||
RecalculateEnvelope();
|
||||
RecalculateForwardThrust();
|
||||
RecalculateReverseThrust();
|
||||
RecalculateLeftStrafeThrust();
|
||||
RecalculateRightStrafeThrust();
|
||||
RecalculateClockwiseTorque();
|
||||
RecalculateCounterClockwiseTorque();
|
||||
}
|
||||
|
||||
private void RecalculateForwardThrust()
|
||||
{
|
||||
ForwardThrust = 0;
|
||||
foreach (var thruster in _forwardThrusters)
|
||||
if (thruster.Item.Active.Value)
|
||||
ForwardThrust += thruster.Thrust;
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
ForwardThrust += drive.Thrust.x;
|
||||
}
|
||||
|
||||
private void RecalculateReverseThrust()
|
||||
{
|
||||
ReverseThrust = 0;
|
||||
foreach (var thruster in _reverseThrusters)
|
||||
if (thruster.Item.Active.Value)
|
||||
ReverseThrust += thruster.Thrust;
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
ReverseThrust += drive.Thrust.x;
|
||||
}
|
||||
|
||||
private void RecalculateLeftStrafeThrust()
|
||||
{
|
||||
LeftStrafeThrust = 0;
|
||||
LeftStrafeTotalTorque = 0;
|
||||
foreach (var thruster in _leftThrusters)
|
||||
float forward = 0, back = 0, left = 0, right = 0, clockwise = 0, counterClockwise = 0;
|
||||
foreach (var thruster in _allThrusters)
|
||||
{
|
||||
if(thruster.Item.Active.Value)
|
||||
{
|
||||
LeftStrafeThrust += thruster.Thrust;
|
||||
LeftStrafeTotalTorque += thruster.Torque * thruster.Thrust;
|
||||
}
|
||||
var column = thruster.Column(thruster.Item != null && thruster.Item.PowerSupply > 1e-4f ? thruster.Thrust : 0f);
|
||||
forward += max(column.y, 0f);
|
||||
back += max(-column.y, 0f);
|
||||
left += max(-column.x, 0f);
|
||||
right += max(column.x, 0f);
|
||||
clockwise += max(column.z, 0f);
|
||||
counterClockwise += max(-column.z, 0f);
|
||||
}
|
||||
LeftStrafeTorqueThrusters.Clear();
|
||||
foreach(var thruster in _leftThrusters)
|
||||
if (abs(sign(thruster.Torque) - sign(LeftStrafeTotalTorque)) < .01f)
|
||||
LeftStrafeTorqueThrusters.Add(thruster);
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
LeftStrafeThrust += drive.Thrust.y;
|
||||
}
|
||||
|
||||
private void RecalculateRightStrafeThrust()
|
||||
{
|
||||
RightStrafeThrust = 0;
|
||||
RightStrafeTotalTorque = 0;
|
||||
foreach (var thruster in _rightThrusters)
|
||||
{
|
||||
if(thruster.Item.Active.Value)
|
||||
{
|
||||
RightStrafeThrust += thruster.Thrust;
|
||||
RightStrafeTotalTorque += thruster.Torque * thruster.Thrust;
|
||||
}
|
||||
}
|
||||
RightStrafeTorqueThrusters.Clear();
|
||||
foreach(var thruster in _rightThrusters)
|
||||
if (abs(sign(thruster.Torque) - sign(RightStrafeTotalTorque)) < .01f)
|
||||
RightStrafeTorqueThrusters.Add(thruster);
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
RightStrafeThrust += drive.Thrust.y;
|
||||
}
|
||||
|
||||
private void RecalculateClockwiseTorque()
|
||||
{
|
||||
ClockwiseTorque = 0;
|
||||
foreach (var thruster in _clockwiseThrusters)
|
||||
if (thruster.Item.Active.Value)
|
||||
ClockwiseTorque += thruster.Torque;
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
ClockwiseTorque += drive.Thrust.z;
|
||||
}
|
||||
|
||||
private void RecalculateCounterClockwiseTorque()
|
||||
{
|
||||
CounterClockwiseTorque = 0;
|
||||
foreach (var thruster in _counterClockwiseThrusters)
|
||||
if (thruster.Item.Active.Value)
|
||||
CounterClockwiseTorque -= thruster.Torque;
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
if (drive.Item.Active.Value)
|
||||
CounterClockwiseTorque += drive.Thrust.z;
|
||||
Envelope = new ManoeuvreEnvelope(forward, back, left, right, clockwise, counterClockwise);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
// Called by Entity.Update once the items' performance is current and before the power bus is stepped and the items
|
||||
// execute: liveness, thrust and the throttles they decide are one phase, the one Execute acts on. The lock is a
|
||||
// bound on the allocator's solve; intent reaches the allocator here and nowhere else.
|
||||
protected override void UpdateThrottles()
|
||||
{
|
||||
if (_exitingWormhole || _enteringWormhole) return;
|
||||
RecalculateEnvelope();
|
||||
for (var i = 0; i < _allThrusters.Length; i++)
|
||||
_columns[i] = _allThrusters[i].Column(_allThrusters[i].NominalThrust);
|
||||
_allocator.Allocate(_columns, MovementDirection, Turn, _throttles, ThrottleLocked);
|
||||
for (var i = 0; i < _allThrusters.Length; i++) _allThrusters[i].Axis = _throttles[i];
|
||||
}
|
||||
|
||||
public override void Update(float delta)
|
||||
{
|
||||
if (_active && !_exitingWormhole && !_enteringWormhole)
|
||||
{
|
||||
RecalculateThrust();
|
||||
foreach (var thruster in _allThrusters) thruster.Axis = 0;
|
||||
var rightThrusterTorqueCompensation = abs(RightStrafeTotalTorque) / RightStrafeTorqueThrusters.Count;
|
||||
foreach (var thruster in _rightThrusters)
|
||||
{
|
||||
var thrust = 0f;
|
||||
thrust += MovementDirection.x;
|
||||
if (RightStrafeTorqueThrusters.Contains(thruster))
|
||||
thrust -= MovementDirection.x * (rightThrusterTorqueCompensation / (abs(thruster.Torque) * thruster.Thrust));
|
||||
thruster.Axis = thrust;
|
||||
}
|
||||
var leftThrusterTorqueCompensation = abs(LeftStrafeTotalTorque) / LeftStrafeTorqueThrusters.Count;
|
||||
foreach (var thruster in _leftThrusters)
|
||||
{
|
||||
var thrust = 0f;
|
||||
thrust += -MovementDirection.x;
|
||||
if (LeftStrafeTorqueThrusters.Contains(thruster))
|
||||
thrust += MovementDirection.x * (leftThrusterTorqueCompensation / (abs(thruster.Torque) * thruster.Thrust));
|
||||
thruster.Axis = thrust;
|
||||
}
|
||||
foreach (var thruster in _forwardThrusters) thruster.Axis += MovementDirection.y;
|
||||
foreach (var thruster in _reverseThrusters) thruster.Axis += -MovementDirection.y;
|
||||
|
||||
foreach (var thruster in _clockwiseThrusters) thruster.Axis += Turn;
|
||||
foreach (var thruster in _counterClockwiseThrusters) thruster.Axis += -Turn;
|
||||
|
||||
foreach (var drive in _aetherDrives)
|
||||
drive.Axis = float3(MovementDirection.y, MovementDirection.x, Turn);
|
||||
}
|
||||
|
||||
var velocityMagnitude = length(Velocity);
|
||||
if(velocityMagnitude > .01f)
|
||||
Velocity = normalize(Velocity) * decay(velocityMagnitude, HullData.Drag, delta);
|
||||
|
||||
Position.xz += Velocity * delta;
|
||||
|
||||
Velocity += Zone.GetForce(Position.xz) * delta;
|
||||
var normal = Zone.GetNormal(Position.xz);
|
||||
var force = new float2(normal.x, normal.z);
|
||||
Velocity += Zone.GravityAcceleration(force, Zone.Settings.GravityStrength) * delta;
|
||||
var shipRight = Direction.Rotate(ItemRotation.Clockwise);
|
||||
var forward = cross(float3(shipRight.x, 0, shipRight.y), normal);
|
||||
Rotation = quaternion.LookRotation(forward, normal);
|
||||
|
|
|
|||
|
|
@ -17,6 +17,22 @@ public sealed class ShipAuthoring
|
|||
[Key(2)] public string ModelAsset;
|
||||
[Key(3)] public List<ShipAnchor> Anchors = new List<ShipAnchor>();
|
||||
[Key(4)] public List<ShipPolyline> SchematicLines = new List<ShipPolyline>();
|
||||
// The moving parts of the rig, presentation only (ruling rig-is-presentation): no joint value feeds the simulation.
|
||||
[Key(5)] public List<ShipJoint> Joints = new List<ShipJoint>();
|
||||
}
|
||||
|
||||
// A rig joint: a bone of the model's armature. Axes are three floats per degree of freedom, a unit vector in Ship Root
|
||||
// space at rest (glTF axes, +Y up); Min and Max are that degree of freedom's limits in degrees.
|
||||
[MessagePackObject]
|
||||
public sealed class ShipJoint
|
||||
{
|
||||
// The bone's aetheria.id, which is also its GLB node id.
|
||||
[Key(0)] public string Id;
|
||||
// The nearest joint above this one in the model, or null for a root joint.
|
||||
[Key(1)] public string Parent;
|
||||
[Key(2)] public float[] Axes;
|
||||
[Key(3)] public float[] Min;
|
||||
[Key(4)] public float[] Max;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
|
|
@ -25,13 +41,15 @@ public sealed class ShipAnchor
|
|||
// Stable semantic identity. HullData.Hardpoints[].Transform names this ID for mounts.
|
||||
[Key(0)] public string Id;
|
||||
// One of: map-icon, hull-collider, shield, tractor, thruster-emitter, weapon-mount,
|
||||
// weapon-muzzle, radiator-mesh, or articulation (a pivot, never a mount).
|
||||
// weapon-muzzle, or radiator-mesh.
|
||||
[Key(1)] public string Role;
|
||||
// Stable node ID in the compiled model, never a Blender display name.
|
||||
[Key(2)] public string ModelNodeId;
|
||||
// Only child roles use ParentId; e.g. a muzzle names its weapon hardpoint.
|
||||
[Key(3)] public string ParentId;
|
||||
[Key(4)] public int Order;
|
||||
// On a weapon-mount anchor: the id of the nearest joint above its node in the model; null or empty is a fixed mount.
|
||||
[Key(5)] public string Joint;
|
||||
}
|
||||
|
||||
// Evaluated or baked Grease Pencil stroke coordinates in Blender's right-handed Z-up
|
||||
|
|
@ -53,8 +71,7 @@ public static class ShipAuthoringStore
|
|||
// ShipAnchor.Role's vocabulary.
|
||||
private static readonly HashSet<string> Roles = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh",
|
||||
"articulation"
|
||||
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh"
|
||||
};
|
||||
|
||||
// The anchor role a visible hardpoint's mount plays, or null for an internal hardpoint, which has no anchor.
|
||||
|
|
@ -71,7 +88,7 @@ public static class ShipAuthoringStore
|
|||
var cache = new CultCache();
|
||||
try
|
||||
{
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, !writable), new[] { typeof(HullData), typeof(ShipAuthoring) });
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, !writable), new[] { typeof(HullData), typeof(ShipAuthoring), typeof(FactionProductData) });
|
||||
return cache;
|
||||
}
|
||||
catch
|
||||
|
|
@ -88,6 +105,14 @@ public static class ShipAuthoringStore
|
|||
cache.UpsertAsync(typeof(ShipAuthoring), visual, ShipModCatalog.AuthoringKey(visual.Id)).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
// A package's product by one maker. These two are the only product writers; the key is the ship and the maker, so a
|
||||
// maker has at most one product of the hull and writing again replaces it.
|
||||
public static void WriteProduct(CultCache cache, string shipId, FactionProductData product) =>
|
||||
cache.UpsertAsync(typeof(FactionProductData), product, ShipModCatalog.ProductKey(shipId, product.Manufacturer.Key)).GetAwaiter().GetResult();
|
||||
|
||||
public static bool DeleteProduct(CultCache cache, string shipId, CultRecordKey maker) =>
|
||||
cache.Remove(ShipModCatalog.ProductKey(shipId, maker));
|
||||
|
||||
// A new mod hull that flies like a shipped one. Every member of the reference is copied through the type's own
|
||||
// MessagePack round trip, so a member added to HullData later is copied too; then the six that are the shipped ship's
|
||||
// own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic,
|
||||
|
|
@ -106,8 +131,8 @@ public static class ShipAuthoringStore
|
|||
}
|
||||
|
||||
// The structure of a ship file, without judging its content (drafts load): exactly one hull and one visual, each at
|
||||
// its deterministic key, the hull naming that visual by its typed ref.
|
||||
public static (HullData Hull, ShipAuthoring Visual) Load(string path)
|
||||
// its deterministic key, the hull naming that visual by its typed ref, and the hull's products, each at its maker's key.
|
||||
public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Load(string path)
|
||||
{
|
||||
RefuseLegacyEmbeddedHull(path);
|
||||
try { return LoadRecords(path); }
|
||||
|
|
@ -150,7 +175,7 @@ public static class ShipAuthoringStore
|
|||
|
||||
private const int RetiredHullKey = 1;
|
||||
|
||||
private static (HullData Hull, ShipAuthoring Visual) LoadRecords(string path)
|
||||
private static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) LoadRecords(string path)
|
||||
{
|
||||
using var cache = Open(path);
|
||||
var hulls = cache.GetAll<HullData>().ToArray();
|
||||
|
|
@ -163,14 +188,44 @@ public static class ShipAuthoringStore
|
|||
if (!cache.TryGetHandle(hull).Value.Key.Equals(ShipModCatalog.HullKey(visual.Id)) ||
|
||||
!cache.TryGetHandle(visual).Value.Key.Equals(ShipModCatalog.AuthoringKey(visual.Id)))
|
||||
throw new InvalidOperationException($"{path}: {visual.Id}: records must be stored under {ShipModCatalog.HullKey(visual.Id).Value} and {ShipModCatalog.AuthoringKey(visual.Id).Value}.");
|
||||
return (hull, visual);
|
||||
var products = cache.GetAll<FactionProductData>().ToArray();
|
||||
foreach (var product in products)
|
||||
{
|
||||
if (!product.Manufacturer.IsSet() || ShipModCatalog.IsModKey(product.Manufacturer.Key))
|
||||
throw new InvalidOperationException($"{path}: {visual.Id}: a product needs a manufacturer that is a shipped faction.");
|
||||
var productKey = ShipModCatalog.ProductKey(visual.Id, product.Manufacturer.Key);
|
||||
if (!cache.TryGetHandle(product).Value.Key.Equals(productKey))
|
||||
throw new InvalidOperationException($"{path}: {visual.Id}: a product must be stored at {productKey.Value}.");
|
||||
if (!product.Design.IsSet() || !product.Design.Key.Equals(ShipModCatalog.HullKey(visual.Id)))
|
||||
throw new InvalidOperationException($"{path}: {visual.Id}: a product must name the package hull {ShipModCatalog.HullKey(visual.Id).Value} as its design.");
|
||||
}
|
||||
return (hull, visual, products);
|
||||
}
|
||||
|
||||
public static (HullData Hull, ShipAuthoring Visual) Read(string path)
|
||||
public static (HullData Hull, ShipAuthoring Visual, FactionProductData[] Products) Read(string path)
|
||||
{
|
||||
var (hull, visual, products) = Load(path);
|
||||
ValidateLoaded(hull, visual, products);
|
||||
return (hull, visual, products);
|
||||
}
|
||||
|
||||
// Every judgement a loaded package's records face, in one place: Read, and validate on a draft with no model yet, call it.
|
||||
public static void ValidateLoaded(HullData hull, ShipAuthoring visual, FactionProductData[] products)
|
||||
{
|
||||
var (hull, visual) = Load(path);
|
||||
Validate(hull, visual);
|
||||
return (hull, visual);
|
||||
ValidateProducts(hull, visual, products);
|
||||
}
|
||||
|
||||
// What a package may sell: every product named, no name twice, and a price above 0, because generation skips price 0.
|
||||
private static void ValidateProducts(HullData hull, ShipAuthoring visual, FactionProductData[] products)
|
||||
{
|
||||
if (products.Length == 0) return;
|
||||
if (products.Any(product => string.IsNullOrWhiteSpace(product.Name)))
|
||||
throw new InvalidOperationException($"{visual.Id}: every product needs a name.");
|
||||
if (products.Select(product => product.Name).Distinct(StringComparer.Ordinal).Count() != products.Length)
|
||||
throw new InvalidOperationException($"{visual.Id}: product names must be unique within the package.");
|
||||
if (hull.Price <= 0)
|
||||
throw new InvalidOperationException($"{visual.Id}: a hull with products needs a price above 0 (generation skips price 0).");
|
||||
}
|
||||
|
||||
// A hull names one body: a Unity prefab (shipped hulls) or a ShipAuthoring record (mod ships), never both, so no
|
||||
|
|
@ -182,19 +237,33 @@ public static class ShipAuthoringStore
|
|||
throw new InvalidOperationException($"{label}: a hull names one body, but this one names both a Unity prefab and a visual record.");
|
||||
}
|
||||
|
||||
// The one ship-ID rule, shared by Validate and ship-authoring create. The ID becomes a folder name on every platform, so
|
||||
// Windows device names (alone or before a dot) and a trailing dot are refused too. The messages name the rule, never the value.
|
||||
public static void RequireShipId(string id)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id)) throw new InvalidOperationException("Ship ID is required.");
|
||||
if (!(id[0] >= 'a' && id[0] <= 'z' || id[0] >= '0' && id[0] <= '9') || id.Any(c =>
|
||||
!(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-')))
|
||||
throw new InvalidOperationException("Ship ID must use lower-case ASCII letters, digits, dots, underscores, or hyphens.");
|
||||
if (id[id.Length - 1] == '.') throw new InvalidOperationException("Ship ID must not end with a dot.");
|
||||
var stem = id.Split('.')[0];
|
||||
if (stem is "con" or "prn" or "aux" or "nul"
|
||||
|| stem.Length == 4 && (stem.StartsWith("com") || stem.StartsWith("lpt")) && stem[3] >= '1' && stem[3] <= '9')
|
||||
throw new InvalidOperationException("Ship ID must not be a Windows device name.");
|
||||
}
|
||||
|
||||
// The one semantic check every path shares: the hull and its visual, judged together.
|
||||
public static void Validate(HullData hull, ShipAuthoring ship)
|
||||
{
|
||||
if (ship == null) throw new InvalidOperationException("Ship authoring record is null.");
|
||||
if (string.IsNullOrWhiteSpace(ship.Id)) throw new InvalidOperationException("Ship ID is required.");
|
||||
if (!(ship.Id[0] >= 'a' && ship.Id[0] <= 'z' || ship.Id[0] >= '0' && ship.Id[0] <= '9') || ship.Id.Any(c =>
|
||||
!(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-')))
|
||||
throw new InvalidOperationException($"{ship.Id}: ship ID must use lower-case ASCII letters, digits, dots, underscores, or hyphens.");
|
||||
RequireShipId(ship.Id);
|
||||
if (hull == null) throw new InvalidOperationException($"{ship.Id}: hull data is required.");
|
||||
if (string.IsNullOrWhiteSpace(hull.Name)) throw new InvalidOperationException($"{ship.Id}: hull name is required.");
|
||||
if (hull.Shape?.Cells == null || !hull.Shape.Cells.Cast<bool>().Any(occupied => occupied))
|
||||
throw new InvalidOperationException($"{ship.Id}: schematic must contain at least one cell.");
|
||||
RequireOneBody(hull, ship.Id);
|
||||
if (hull.HullType == HullType.Ship && !(hull.Behaviors ?? new List<BehaviorData>()).Any(behavior => behavior is VelocityLimitData))
|
||||
throw new InvalidOperationException($"{ship.Id}: a ship hull needs a top speed (VelocityLimit).");
|
||||
if (!hull.Visual.Key.Equals(ShipModCatalog.AuthoringKey(ship.Id)))
|
||||
throw new InvalidOperationException($"{ship.Id}: the hull must name its visual record {ShipModCatalog.AuthoringKey(ship.Id).Value}.");
|
||||
if (string.IsNullOrWhiteSpace(ship.ModelAsset) || Path.IsPathRooted(ship.ModelAsset) ||
|
||||
|
|
@ -233,6 +302,11 @@ public static class ShipAuthoringStore
|
|||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has an unknown rotation {(int)hardpoint.Rotation}.");
|
||||
if (!float.IsFinite(hardpoint.Armor) || hardpoint.Armor < 0 || !float.IsFinite(hardpoint.FiringArc) || hardpoint.FiringArc < 0)
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} armor and firing arc must be finite and not negative.");
|
||||
// A thruster's gimbal range is the judge's alone, a row of one included: no thruster swings further than a turn.
|
||||
if (hardpoint.Type == HardpointType.Thruster && hardpoint.FiringArc > 360f)
|
||||
throw new InvalidOperationException($"{ship.Id}: thruster hardpoint {hardpoint.Transform} firing arc may be at most 360 degrees.");
|
||||
if (!string.IsNullOrEmpty(hardpoint.Row) && hardpoint.Type != HardpointType.Thruster)
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} is a {hardpoint.Type} hardpoint, and only a Thruster hardpoint may state a row.");
|
||||
if (hardpoint.Shape?.Cells == null || !hardpoint.Shape.Cells.Cast<bool>().Any(occupied => occupied))
|
||||
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} has no cells.");
|
||||
for (var cellX = 0; cellX < hardpoint.Shape.Width; cellX++)
|
||||
|
|
@ -256,14 +330,23 @@ public static class ShipAuthoringStore
|
|||
if (mountRole != null && mountAnchor.Role != mountRole)
|
||||
throw new InvalidOperationException($"{ship.Id}: {hardpoint.Type} hardpoint {hardpoint.Transform} needs a {mountRole} anchor of that id.");
|
||||
}
|
||||
foreach (var row in mounts.Values.Where(hardpoint => hardpoint.Type == HardpointType.Thruster && !string.IsNullOrEmpty(hardpoint.Row))
|
||||
.GroupBy(hardpoint => hardpoint.Row, StringComparer.Ordinal))
|
||||
{
|
||||
var lead = row.First();
|
||||
foreach (var hardpoint in row)
|
||||
if (hardpoint.Rotation != lead.Rotation || hardpoint.FiringArc != lead.FiringArc)
|
||||
throw new InvalidOperationException($"{ship.Id}: thruster hardpoints {lead.Transform} and {hardpoint.Transform} are in row {row.Key} and must share Rotation and FiringArc.");
|
||||
if (!(lead.FiringArc > 0f))
|
||||
throw new InvalidOperationException($"{ship.Id}: thruster row {row.Key} must state a gimbal FiringArc above 0.");
|
||||
}
|
||||
foreach (var anchor in anchors)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(anchor.ParentId) && !mounts.ContainsKey(anchor.ParentId))
|
||||
throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} has unknown hardpoint parent {anchor.ParentId}.");
|
||||
// A mount-role anchor is the mount of a hardpoint of its type, never a loose node. The hardpoint loop above has
|
||||
// already refused one whose id names a hardpoint of another type, so here it only has to name a hardpoint.
|
||||
if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh" || anchor.Role == "weapon-mount") &&
|
||||
!mounts.ContainsKey(anchor.Id))
|
||||
if ((RigChains.Actuates(anchor.Role) || anchor.Role == "radiator-mesh") && !mounts.ContainsKey(anchor.Id))
|
||||
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} must be the mount of a hardpoint of its type.");
|
||||
if (anchor.Role == "weapon-muzzle" &&
|
||||
(string.IsNullOrEmpty(anchor.ParentId) || !IsWeapon(mounts[anchor.ParentId].Type)))
|
||||
|
|
@ -272,6 +355,7 @@ public static class ShipAuthoringStore
|
|||
foreach (var hardpoint in mounts.Values.Where(hardpoint => IsWeapon(hardpoint.Type)))
|
||||
if (!anchors.Any(anchor => anchor.Role == "weapon-muzzle" && anchor.ParentId == hardpoint.Transform))
|
||||
throw new InvalidOperationException($"{ship.Id}: weapon hardpoint {hardpoint.Transform} needs at least one muzzle anchor.");
|
||||
ValidateRig(ship, anchors, mounts, nodeIds);
|
||||
|
||||
foreach (var line in ship.SchematicLines ?? new List<ShipPolyline>())
|
||||
{
|
||||
|
|
@ -291,4 +375,158 @@ public static class ShipAuthoringStore
|
|||
throw new InvalidOperationException($"{ship.Id}: schematic line color must be finite RGBA.");
|
||||
}
|
||||
}
|
||||
|
||||
// A degree of freedom counts as yaw when its axis lies within 5 degrees of Ship Root up (glTF +Y).
|
||||
private static readonly float YawAxisCos = MathF.Cos(5f * MathF.PI / 180f);
|
||||
|
||||
// The joints, which anchors ride them, and whether each driven joint's chain can sweep the arc its guns state. The
|
||||
// joints are presentation, so this judges only that the rig could point the gun where the hardpoint says it may fire.
|
||||
private static void ValidateRig(ShipAuthoring ship, List<ShipAnchor> anchors, Dictionary<string, HardpointData> mounts, HashSet<string> nodeIds)
|
||||
{
|
||||
var joints = ship.Joints ?? new List<ShipJoint>();
|
||||
var byId = new Dictionary<string, ShipJoint>(StringComparer.Ordinal);
|
||||
foreach (var joint in joints)
|
||||
{
|
||||
if (joint == null || string.IsNullOrWhiteSpace(joint.Id) || byId.ContainsKey(joint.Id))
|
||||
throw new InvalidOperationException($"{ship.Id}: joint IDs must be present and unique.");
|
||||
if (nodeIds.Contains(joint.Id))
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} is also an anchor's model node.");
|
||||
byId.Add(joint.Id, joint);
|
||||
}
|
||||
foreach (var joint in joints)
|
||||
{
|
||||
var dofs = joint.Min?.Length ?? 0;
|
||||
if (dofs < 1 || joint.Max?.Length != dofs || joint.Axes?.Length != 3 * dofs)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} needs one or more degrees of freedom: Axes holds three values each, Min and Max one each.");
|
||||
for (var dof = 0; dof < dofs; dof++)
|
||||
{
|
||||
var (x, y, z) = (joint.Axes[3 * dof], joint.Axes[3 * dof + 1], joint.Axes[3 * dof + 2]);
|
||||
var (min, max) = (joint.Min[dof], joint.Max[dof]);
|
||||
if (!float.IsFinite(x) || !float.IsFinite(y) || !float.IsFinite(z) || !float.IsFinite(min) || !float.IsFinite(max))
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} axes and limits must be finite.");
|
||||
if (MathF.Abs(MathF.Sqrt(x * x + y * y + z * z) - 1f) > 1e-3f)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} axis {dof} must be a unit vector.");
|
||||
if (min < -180f || max > 180f || min > max)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} limits {dof} must satisfy -180 <= Min <= Max <= 180.");
|
||||
}
|
||||
if (!string.IsNullOrEmpty(joint.Parent) && !byId.ContainsKey(joint.Parent))
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} has an unknown parent joint.");
|
||||
}
|
||||
foreach (var joint in joints)
|
||||
{
|
||||
var step = joint;
|
||||
for (var depth = 0; !string.IsNullOrEmpty(step.Parent); depth++)
|
||||
{
|
||||
if (depth >= joints.Count)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} is on a parent cycle.");
|
||||
step = byId[step.Parent];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var anchor in anchors.Where(anchor => !string.IsNullOrEmpty(anchor.Joint)))
|
||||
{
|
||||
if (anchor.Role == "radiator-mesh")
|
||||
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} may not ride a joint.");
|
||||
if (!RigChains.Actuates(anchor.Role))
|
||||
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} may not name a joint; only a weapon mount or a thruster emitter rides one.");
|
||||
if (!byId.ContainsKey(anchor.Joint))
|
||||
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} names an unknown joint.");
|
||||
}
|
||||
|
||||
// A joint has one actuator (ruling one-joint-one-actuator), and RigChains.Drives is the only place that says what drives a
|
||||
// joint: a joint carrying two actuators, or whose reach passes through a joint another actuator drives, is refused here,
|
||||
// whatever the two actuators are.
|
||||
var drives = RigChains.Drives(ship).Select(drive => (drive.Joint, Hardpoint: mounts[drive.Anchor.Id])).ToArray();
|
||||
foreach (var onJoint in drives.GroupBy(drive => drive.Joint, StringComparer.Ordinal))
|
||||
{
|
||||
var lead = onJoint.First().Hardpoint;
|
||||
var other = onJoint.Select(drive => drive.Hardpoint).FirstOrDefault(hardpoint => RigChains.Actuator(hardpoint) != RigChains.Actuator(lead));
|
||||
if (other != null)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {onJoint.Key} carries more than one actuator ({lead.Transform} and {other.Transform}); a joint has one actuator.");
|
||||
}
|
||||
var driven = RigChains.Driven(ship);
|
||||
foreach (var joint in driven)
|
||||
{
|
||||
var through = RigChains.Chain(ship, joint).SkipLast(1).FirstOrDefault(driven.Contains);
|
||||
if (through != null)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint} reaches through joint {through}, which another actuator drives; a joint has one actuator.");
|
||||
}
|
||||
|
||||
var ridden = drives.Where(drive => IsWeapon(drive.Hardpoint.Type)).ToArray();
|
||||
foreach (var (_, hardpoint) in ridden)
|
||||
if (!(hardpoint.FiringArc > 0f))
|
||||
throw new InvalidOperationException($"{ship.Id}: weapon hardpoint {hardpoint.Transform} rides a joint, so it must state its firing arc above 0.");
|
||||
foreach (var group in ridden.GroupBy(mount => mount.Joint, StringComparer.Ordinal))
|
||||
{
|
||||
var lead = group.First().Hardpoint;
|
||||
foreach (var (_, hardpoint) in group)
|
||||
if (hardpoint.Rotation != lead.Rotation || hardpoint.FiringArc != lead.FiringArc)
|
||||
throw new InvalidOperationException($"{ship.Id}: weapon hardpoints {lead.Transform} and {hardpoint.Transform} ride joint {group.Key} and must share Rotation and FiringArc.");
|
||||
var reach = YawReach(ship, group.Key);
|
||||
if (reach < lead.FiringArc)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {group.Key} chain reaches {reach} degrees of yaw, short of the {lead.FiringArc} degree firing arc of {lead.Transform}.");
|
||||
}
|
||||
|
||||
// A thruster row is a gimbal: its hardpoints' stated FiringArc is how far the row swings, so a row on a joint rides it
|
||||
// whole, and the joint's chain must be able to sweep that arc. A hardpoint with no Row is a row of one.
|
||||
var thrusters = mounts.Values.Where(hardpoint => hardpoint.Type == HardpointType.Thruster).ToArray();
|
||||
var tilted = drives.Where(drive => drive.Hardpoint.Type == HardpointType.Thruster).ToArray();
|
||||
foreach (var (_, hardpoint) in tilted)
|
||||
if (!(hardpoint.FiringArc > 0f))
|
||||
throw new InvalidOperationException($"{ship.Id}: thruster hardpoint {hardpoint.Transform} rides a joint, so it must state its firing arc above 0; a fixed thruster may not ride a joint.");
|
||||
foreach (var onJoint in tilted.GroupBy(drive => drive.Joint, StringComparer.Ordinal))
|
||||
{
|
||||
var lead = onJoint.First().Hardpoint;
|
||||
var members = string.IsNullOrEmpty(lead.Row) ? new[] { lead } : thrusters.Where(hardpoint => hardpoint.Row == lead.Row).ToArray();
|
||||
foreach (var member in members)
|
||||
if (!tilted.Any(drive => drive.Hardpoint == member && drive.Joint == onJoint.Key))
|
||||
throw new InvalidOperationException($"{ship.Id}: thruster hardpoint {member.Transform} is in the row of {lead.Transform} on joint {onJoint.Key} and must ride it too; a row rides one joint whole.");
|
||||
var reach = YawReach(ship, onJoint.Key);
|
||||
if (reach < lead.FiringArc)
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {onJoint.Key} chain reaches {reach} degrees of yaw, short of the {lead.FiringArc} degree gimbal arc of {lead.Transform}.");
|
||||
}
|
||||
}
|
||||
|
||||
// The yaw a driven joint's chain can sweep: the summed range of every degree of freedom whose axis is yaw, capped at a turn.
|
||||
private static float YawReach(ShipAuthoring ship, string jointId)
|
||||
{
|
||||
var joints = ship.Joints.ToDictionary(joint => joint.Id, StringComparer.Ordinal);
|
||||
var reach = 0f;
|
||||
foreach (var joint in RigChains.Chain(ship, jointId).Select(id => joints[id]))
|
||||
for (var dof = 0; dof < joint.Min.Length; dof++)
|
||||
if (MathF.Abs(joint.Axes[3 * dof + 1]) >= YawAxisCos)
|
||||
reach += joint.Max[dof] - joint.Min[dof];
|
||||
return MathF.Min(reach, 360f);
|
||||
}
|
||||
}
|
||||
|
||||
// A rig's actuators and the joints they drive. An actuator is a weapon mount or a thruster emitter that names a joint; a gun
|
||||
// group (every gun on a joint) or a thruster row is one actuator, and a joint has at most one (ruling one-joint-one-actuator).
|
||||
// This is the only place that says which anchors are actuators, so the judge, the binder and the plan all follow it.
|
||||
public static class RigChains
|
||||
{
|
||||
public static bool Actuates(string role) => role == "weapon-mount" || role == "thruster-emitter";
|
||||
|
||||
// Every actuator anchor that names a joint, with the joint it drives.
|
||||
public static IEnumerable<(string Joint, ShipAnchor Anchor)> Drives(ShipAuthoring ship) =>
|
||||
ship.Anchors.Where(anchor => Actuates(anchor.Role) && !string.IsNullOrEmpty(anchor.Joint)).Select(anchor => (anchor.Joint, anchor));
|
||||
|
||||
public static HashSet<string> Driven(ShipAuthoring ship) =>
|
||||
new HashSet<string>(Drives(ship).Select(drive => drive.Joint), StringComparer.Ordinal);
|
||||
|
||||
// The actuator a mount belongs to: all guns on a joint are one, a thruster is its row, and a thruster of no row is its own.
|
||||
public static string Actuator(HardpointData hardpoint) =>
|
||||
ShipAuthoringStore.IsWeapon(hardpoint.Type) ? "weapon" : string.IsNullOrEmpty(hardpoint.Row) ? "thruster:" + hardpoint.Transform : "row:" + hardpoint.Row;
|
||||
|
||||
// The joint and its ancestors, root-first. The judge refuses a driven joint whose ancestors another actuator drives,
|
||||
// so for an accepted ship this is the whole chain the actuator's reach is summed over.
|
||||
public static string[] Chain(ShipAuthoring ship, string jointId)
|
||||
{
|
||||
var joints = ship.Joints.ToDictionary(joint => joint.Id, StringComparer.Ordinal);
|
||||
var chain = new List<string> { jointId };
|
||||
for (var parent = joints[jointId].Parent; !string.IsNullOrEmpty(parent); parent = joints[parent].Parent)
|
||||
chain.Add(parent);
|
||||
chain.Reverse();
|
||||
return chain.ToArray();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,14 +16,18 @@ public static class ShipModCatalog
|
|||
public ShipAuthoring Visual;
|
||||
public string ModelPath;
|
||||
public Dictionary<string, uint> NodeIndices;
|
||||
// The package's own products, read from its ship.cc; empty for a package taken from the catalog, where gameplay reads products.
|
||||
public FactionProductData[] Products = Array.Empty<FactionProductData>();
|
||||
}
|
||||
|
||||
public static CultRecordKey HullKey(string id) => new CultRecordKey("mod-hull:" + id);
|
||||
public static CultRecordKey AuthoringKey(string id) => new CultRecordKey("mod-ship:" + id);
|
||||
|
||||
public static CultRecordKey ProductKey(string id, CultRecordKey maker) => new CultRecordKey("mod-product:" + id + ":" + maker.Value);
|
||||
|
||||
// A key the mods own. The shipped catalog and its authored records never reference one: a mod may be uninstalled.
|
||||
public static bool IsModKey(CultRecordKey key) =>
|
||||
key.IsSet() && (key.Value.StartsWith("mod-hull:", StringComparison.Ordinal) || key.Value.StartsWith("mod-ship:", StringComparison.Ordinal));
|
||||
key.IsSet() && (key.Value.StartsWith("mod-hull:", StringComparison.Ordinal) || key.Value.StartsWith("mod-ship:", StringComparison.Ordinal) || key.Value.StartsWith("mod-product:", StringComparison.Ordinal));
|
||||
|
||||
// A package left out of the composition, named by its directory, with every reason it was left out.
|
||||
public sealed class Exclusion
|
||||
|
|
@ -45,7 +49,7 @@ public static class ShipModCatalog
|
|||
// named. A collision (with the shipped catalog, or with another package's hull name) excludes every package involved,
|
||||
// since neither has a claim to the name. The derived catalog holds the shipped catalog plus the included packages.
|
||||
// Unsafe inputs and outputs (a missing catalog, a derived file that would replace a source) still throw: nothing is composed.
|
||||
public static Composition Compose(string shippedCatalog, string outputCatalog, string modsRoot)
|
||||
public static Composition Compose(string shippedCatalog, string outputCatalog, string modsRoot, CultDocumentRegistry registry = null)
|
||||
{
|
||||
var source = Path.GetFullPath(shippedCatalog);
|
||||
var output = Path.GetFullPath(outputCatalog);
|
||||
|
|
@ -84,7 +88,7 @@ public static class ShipModCatalog
|
|||
Directory.CreateDirectory(workspace);
|
||||
File.Copy(source, temporary);
|
||||
Composition composition;
|
||||
using (var cache = AetheriaStores.Open(temporary, catalogWritable: true))
|
||||
using (var cache = AetheriaStores.Open(temporary, catalogWritable: true, registry: registry))
|
||||
{
|
||||
// Collisions are judged against the shipped records alone, before any package is written, so the
|
||||
// verdict does not depend on directory order. CultCache indexes names per concrete type and lets the
|
||||
|
|
@ -93,6 +97,8 @@ public static class ShipModCatalog
|
|||
var keys = new HashSet<CultRecordKey>(cache.AllStoredDocuments.Select(record => record.Key));
|
||||
var itemNames = new HashSet<string>(cache.GetAll<ItemData>().Select(item => item.Name), StringComparer.Ordinal);
|
||||
var shipIds = new HashSet<string>(cache.GetAll<ShipAuthoring>().Select(existing => existing.Id), StringComparer.Ordinal);
|
||||
var factionKeys = new HashSet<CultRecordKey>(cache.GetAll<Faction>().Select(faction => cache.TryGetHandle(faction).Value.Key));
|
||||
var productNames = new HashSet<string>(cache.GetAll<FactionProductData>().Select(product => product.Name), StringComparer.Ordinal);
|
||||
foreach (var (directory, package) in packages)
|
||||
{
|
||||
var (hull, ship) = (package.Hull, package.Visual);
|
||||
|
|
@ -102,16 +108,33 @@ public static class ShipModCatalog
|
|||
Exclude(directory, $"hull name '{hull.Name}' collides with an existing catalog item.");
|
||||
if (shipIds.Contains(ship.Id))
|
||||
Exclude(directory, $"ship ID collides with an existing catalog ship authoring record.");
|
||||
foreach (var product in package.Products)
|
||||
{
|
||||
if (!factionKeys.Contains(product.Manufacturer.Key))
|
||||
Exclude(directory, $"product '{product.Name}' names a manufacturer the shipped catalog holds no faction for.");
|
||||
if (keys.Contains(ProductKey(ship.Id, product.Manufacturer.Key)))
|
||||
Exclude(directory, $"a mod product key collides with an existing catalog record.");
|
||||
if (productNames.Contains(product.Name))
|
||||
Exclude(directory, $"product name '{product.Name}' collides with an existing catalog product.");
|
||||
}
|
||||
}
|
||||
foreach (var claim in packages.GroupBy(package => package.Package.Hull.Name, StringComparer.Ordinal).Where(group => group.Count() > 1))
|
||||
foreach (var (directory, package) in claim)
|
||||
Exclude(directory, $"hull name '{claim.Key}' is also claimed by " +
|
||||
string.Join(", ", claim.Where(other => other.Directory != directory).Select(other => other.Directory)) + ".");
|
||||
foreach (var claim in packages.SelectMany(package => package.Package.Products.Select(product => (package.Directory, product.Name)))
|
||||
.GroupBy(entry => entry.Name, StringComparer.Ordinal).Where(group => group.Select(entry => entry.Directory).Distinct().Count() > 1))
|
||||
foreach (var directory in claim.Select(entry => entry.Directory).Distinct())
|
||||
Exclude(directory, $"product name '{claim.Key}' is also claimed by " +
|
||||
string.Join(", ", claim.Select(entry => entry.Directory).Where(other => other != directory).Distinct()) + ".");
|
||||
|
||||
var included = packages.Where(package => !reasons.ContainsKey(package.Directory)).Select(package => package.Package).ToArray();
|
||||
foreach (var package in included)
|
||||
// Verbatim: the mod store's own two records, under the keys it already holds them at.
|
||||
{
|
||||
// Verbatim: the mod store's own records, under the keys it already holds them at.
|
||||
ShipAuthoringStore.Write(cache, package.Hull, package.Visual);
|
||||
foreach (var product in package.Products) ShipAuthoringStore.WriteProduct(cache, package.Visual.Id, product);
|
||||
}
|
||||
// Shipped hulls too: the derived catalog must not hold a hull that names two bodies.
|
||||
foreach (var hull in cache.GetAll<HullData>())
|
||||
ShipAuthoringStore.RequireOneBody(hull, hull.Name);
|
||||
|
|
@ -135,8 +158,8 @@ public static class ShipModCatalog
|
|||
public static Package ReadPackage(string shipPath)
|
||||
{
|
||||
var path = Path.GetFullPath(shipPath);
|
||||
var (hull, ship) = ShipAuthoringStore.Read(path);
|
||||
return Bind(hull, ship, Path.GetDirectoryName(path), path);
|
||||
var (hull, ship, products) = ShipAuthoringStore.Read(path);
|
||||
return Bind(hull, ship, products, Path.GetDirectoryName(path), path);
|
||||
}
|
||||
|
||||
// The package a catalog hull names: its two records come from the catalog, and only the GLB comes from the mod
|
||||
|
|
@ -147,31 +170,32 @@ public static class ShipModCatalog
|
|||
throw new InvalidOperationException($"{hull.Name}: the catalog holds no visual record {hull.Visual.Key.Value}.");
|
||||
ShipAuthoringStore.Validate(hull, ship);
|
||||
var directory = Path.Combine(Path.GetFullPath(modsRoot), ship.Id);
|
||||
return Bind(hull, ship, directory, Path.Combine(directory, "ship.cc"));
|
||||
return Bind(hull, ship, Array.Empty<FactionProductData>(), directory, Path.Combine(directory, "ship.cc"));
|
||||
}
|
||||
|
||||
// The one game-side choice of catalog: the shipped file when no package is installed or none survives composition,
|
||||
// otherwise the derived file, composed afresh from the shipped one and the surviving packages. Recomposed every
|
||||
// call, so the derived file is never stale and never an authority. Excluded packages come back named, for the menu.
|
||||
public static (string Catalog, Exclusion[] Excluded) ResolveCatalog(string shippedCatalog, string derivedCatalog, string modsRoot)
|
||||
public static (string Catalog, Exclusion[] Excluded) ResolveCatalog(string shippedCatalog, string derivedCatalog, string modsRoot,
|
||||
CultDocumentRegistry registry = null)
|
||||
{
|
||||
if (!Directory.Exists(modsRoot) ||
|
||||
!Directory.GetDirectories(modsRoot).Any(directory => File.Exists(Path.Combine(directory, "ship.cc"))))
|
||||
return (shippedCatalog, Array.Empty<Exclusion>());
|
||||
Composition composition;
|
||||
// A failure of the composition itself (an unwritable derived path, say) is still a mod problem, never a reason not to boot.
|
||||
try { composition = Compose(shippedCatalog, derivedCatalog, modsRoot); }
|
||||
try { composition = Compose(shippedCatalog, derivedCatalog, modsRoot, registry); }
|
||||
catch (Exception error) { return (shippedCatalog, new[] { new Exclusion { Package = "(all mods)", Reason = error.Message } }); }
|
||||
return (composition.Included.Length == 0 ? shippedCatalog : derivedCatalog, composition.Excluded);
|
||||
}
|
||||
|
||||
private static Package Bind(HullData hull, ShipAuthoring ship, string directory, string path)
|
||||
private static Package Bind(HullData hull, ShipAuthoring ship, FactionProductData[] products, string directory, string path)
|
||||
{
|
||||
if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"{path}: ship ID must match its package directory name.");
|
||||
var modelPath = Path.GetFullPath(Path.Combine(directory, ship.ModelAsset));
|
||||
// Containment is ShipAuthoringStore.Validate's job: it refuses rooted and `..` model paths before this line.
|
||||
if (!File.Exists(modelPath) || !string.Equals(Path.GetExtension(modelPath), ".glb", StringComparison.OrdinalIgnoreCase))
|
||||
if (!File.Exists(modelPath) || !string.Equals(Path.GetExtension(modelPath), ".glb", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"{ship.Id}: model asset must name an existing GLB inside its package.");
|
||||
var modelNodes = ReadNodeIds(modelPath);
|
||||
foreach (var anchor in ship.Anchors)
|
||||
|
|
@ -182,17 +206,52 @@ public static class ShipModCatalog
|
|||
foreach (var anchor in ship.Anchors)
|
||||
if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh") && !modelNodes[anchor.ModelNodeId].HasMesh)
|
||||
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none.");
|
||||
BindRig(ship, modelNodes);
|
||||
CultRecordRefs.Validate(hull);
|
||||
return new Package
|
||||
{
|
||||
Hull = hull, Visual = ship, ModelPath = modelPath,
|
||||
Hull = hull, Visual = ship, Products = products, ModelPath = modelPath,
|
||||
NodeIndices = modelNodes.ToDictionary(node => node.Key, node => node.Value.Index, StringComparer.Ordinal)
|
||||
};
|
||||
}
|
||||
|
||||
// GLB is the xenos asset boundary. Only its node extras, and whether each node names a mesh, are read here; geometry
|
||||
// belongs to the runtime importer.
|
||||
public static Dictionary<string, (uint Index, bool HasMesh)> ReadNodeIds(string path)
|
||||
// The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's
|
||||
// Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator
|
||||
// mesh sits under no joint.
|
||||
private static void BindRig(ShipAuthoring ship, Dictionary<string, (uint Index, bool HasMesh, int Parent)> nodes)
|
||||
{
|
||||
var joints = new HashSet<string>((ship.Joints ?? new List<ShipJoint>()).Select(joint => joint.Id), StringComparer.Ordinal);
|
||||
var idAt = nodes.ToDictionary(node => (int)node.Value.Index, node => node.Key);
|
||||
// Parent is already the nearest ancestor that carries an id, so the walk up is the chain of those.
|
||||
string JointAbove(string nodeId)
|
||||
{
|
||||
// glTF forbids cycles; the bound keeps a malformed model from hanging the binder.
|
||||
var parent = nodes[nodeId].Parent;
|
||||
for (var steps = 0; parent >= 0 && steps <= nodes.Count; steps++, parent = nodes[idAt[parent]].Parent)
|
||||
if (joints.Contains(idAt[parent])) return idAt[parent];
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var joint in ship.Joints ?? new List<ShipJoint>())
|
||||
{
|
||||
if (!nodes.ContainsKey(joint.Id))
|
||||
throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={joint.Id} for a joint.");
|
||||
if (!string.Equals(JointAbove(joint.Id) ?? "", joint.Parent ?? "", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"{ship.Id}: joint {joint.Id} must name the nearest joint above its model node as its Parent.");
|
||||
}
|
||||
foreach (var anchor in ship.Anchors.Where(anchor => RigChains.Actuates(anchor.Role) || anchor.Role == "radiator-mesh"))
|
||||
{
|
||||
var above = JointAbove(anchor.ModelNodeId);
|
||||
if (string.Equals(above ?? "", anchor.Joint ?? "", StringComparison.Ordinal)) continue;
|
||||
throw new InvalidOperationException(anchor.Role == "radiator-mesh"
|
||||
? $"{ship.Id}: {anchor.Role} anchor {anchor.Id} sits under a joint in the model."
|
||||
: $"{ship.Id}: {(anchor.Role == "weapon-mount" ? "weapon mount" : "thruster emitter")} {anchor.Id} must name the nearest joint above its model node as its Joint.");
|
||||
}
|
||||
}
|
||||
|
||||
// GLB is the xenos asset boundary. Only its node extras, whether each node names a mesh, and its nearest identified ancestor's node index
|
||||
// (-1 for none) are read here; geometry belongs to the runtime importer.
|
||||
public static Dictionary<string, (uint Index, bool HasMesh, int Parent)> ReadNodeIds(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
using var reader = new BinaryReader(stream);
|
||||
|
|
@ -203,17 +262,29 @@ public static class ShipModCatalog
|
|||
if (reader.ReadUInt32() != 0x4E4F534A || chunkLength > stream.Length - stream.Position)
|
||||
throw new InvalidOperationException($"{path}: missing GLB JSON chunk.");
|
||||
var json = JObject.Parse(Encoding.UTF8.GetString(reader.ReadBytes((int)chunkLength)));
|
||||
var ids = new Dictionary<string, (uint Index, bool HasMesh)>(StringComparer.Ordinal);
|
||||
var nodes = json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>();
|
||||
var ids = new Dictionary<string, (uint Index, bool HasMesh, int Parent)>(StringComparer.Ordinal);
|
||||
var nodes = (json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>()).ToArray();
|
||||
var parents = Enumerable.Repeat(-1, nodes.Length).ToArray();
|
||||
for (var parent = 0; parent < nodes.Length; parent++)
|
||||
foreach (var child in nodes[parent]["children"]?.Select(token => (int)token) ?? Enumerable.Empty<int>())
|
||||
if (child >= 0 && child < nodes.Length) parents[child] = parent;
|
||||
uint index = 0;
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
var id = (string)node["extras"]?["aetheria.id"];
|
||||
if (string.IsNullOrEmpty(id)) { index++; continue; }
|
||||
if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null)))
|
||||
if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index))))
|
||||
throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}.");
|
||||
index++;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static int IdentifiedAncestor(int[] parents, JObject[] nodes, int index)
|
||||
{
|
||||
var parent = parents[index];
|
||||
for (var steps = 0; parent >= 0 && steps <= nodes.Length; steps++, parent = parents[parent])
|
||||
if (!string.IsNullOrEmpty((string)nodes[parent]["extras"]?["aetheria.id"])) return parent;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ public sealed class ShipModPlan
|
|||
public string[] Radiators;
|
||||
// Each weapon mount (role weapon-mount) and its muzzle anchors, by Order then id.
|
||||
public (string Mount, string[] Muzzles)[] Weapons;
|
||||
// One entry per driven joint (one a weapon mount names), by its first weapon in hull order: the joint, its chain
|
||||
// root-first (RigChains), and the lead mount (the joint's first weapon in hull order) with that mount's first muzzle.
|
||||
// Presentation only: the assembler rigs these and nothing here reaches the simulation.
|
||||
public (string Joint, string[] Chain, string LeadMount, string LeadMuzzle)[] Rigs;
|
||||
|
||||
// Maps a pair Validate accepts; every rule about which anchor may play which part is Validate's, so this refuses nothing.
|
||||
public static ShipModPlan Build(HullData hull, ShipAuthoring visual)
|
||||
|
|
@ -26,6 +30,12 @@ public sealed class ShipModPlan
|
|||
var muzzles = visual.Anchors.Where(anchor => anchor.Role == "weapon-muzzle")
|
||||
.OrderBy(anchor => anchor.Order).ThenBy(anchor => anchor.Id, StringComparer.Ordinal).ToArray();
|
||||
|
||||
var weapons = hardpoints.Where(hardpoint => ShipAuthoringStore.IsWeapon(hardpoint.Type)).Select(hardpoint => hardpoint.Transform).ToHashSet(StringComparer.Ordinal);
|
||||
var jointOf = RigChains.Drives(visual).Where(drive => weapons.Contains(drive.Anchor.Id))
|
||||
.ToDictionary(drive => drive.Anchor.Id, drive => drive.Joint, StringComparer.Ordinal);
|
||||
var leads = hardpoints.Where(hardpoint => jointOf.ContainsKey(hardpoint.Transform)).GroupBy(hardpoint => jointOf[hardpoint.Transform], StringComparer.Ordinal)
|
||||
.Select(group => (Joint: group.Key, Lead: group.First().Transform));
|
||||
|
||||
return new ShipModPlan
|
||||
{
|
||||
MapIcon = Only("map-icon"),
|
||||
|
|
@ -36,7 +46,9 @@ public sealed class ShipModPlan
|
|||
Radiators = Mounts(HardpointType.Radiator),
|
||||
Weapons = hardpoints.Where(hardpoint => ShipAuthoringStore.IsWeapon(hardpoint.Type)).Select(hardpoint => (
|
||||
hardpoint.Transform,
|
||||
muzzles.Where(muzzle => muzzle.ParentId == hardpoint.Transform).Select(muzzle => muzzle.Id).ToArray())).ToArray()
|
||||
muzzles.Where(muzzle => muzzle.ParentId == hardpoint.Transform).Select(muzzle => muzzle.Id).ToArray())).ToArray(),
|
||||
Rigs = leads.Select(rig => (rig.Joint, RigChains.Chain(visual, rig.Joint), rig.Lead,
|
||||
muzzles.First(muzzle => muzzle.ParentId == rig.Lead).Id)).ToArray()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
68
Assets/Scripts/ServerShared/SimClock.cs
Normal file
68
Assets/Scripts/ServerShared/SimClock.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/* 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;
|
||||
|
||||
// The one relation between simulation time and real time. Real seconds go in; whole fixed steps come out, each
|
||||
// handed to the caller's step action with the same Step. Nothing else in the game converts frame time to sim time,
|
||||
// and nothing integrates a sim quantity on this clock: presenters read Lead to draw ahead of the latest step
|
||||
// (DrawAhead) and decide no sim fact.
|
||||
public sealed class SimClock
|
||||
{
|
||||
// The longest real time one frame may feed. A hitch (a load, a breakpoint) is a slow frame, not a burst of
|
||||
// catch-up steps.
|
||||
public const float MaxFrameSeconds = .1f;
|
||||
|
||||
private readonly double _period;
|
||||
private double _accumulator;
|
||||
private bool _advancing;
|
||||
|
||||
public SimClock(float step, float stepsPerRealSecond = 60)
|
||||
{
|
||||
if (!(step > 0)) throw new ArgumentOutOfRangeException(nameof(step));
|
||||
if (!(stepsPerRealSecond > 0)) throw new ArgumentOutOfRangeException(nameof(stepsPerRealSecond));
|
||||
Step = step;
|
||||
StepsPerRealSecond = stepsPerRealSecond;
|
||||
_period = 1.0 / stepsPerRealSecond;
|
||||
}
|
||||
|
||||
// Sim seconds per step, fixed for the clock's life.
|
||||
public float Step { get; }
|
||||
|
||||
public float StepsPerRealSecond { get; }
|
||||
|
||||
public long Steps { get; private set; }
|
||||
|
||||
// Sim seconds since the last step, 0 <= Lead < Step.
|
||||
public float Lead => (float) (_accumulator * StepsPerRealSecond * Step);
|
||||
|
||||
// Forgets the real time paid toward the next step (a new zone starts between steps). A step cannot do this to the
|
||||
// clock that is running it.
|
||||
public void Reset()
|
||||
{
|
||||
if (_advancing) throw new InvalidOperationException("A step cannot reset the clock that is running it.");
|
||||
_accumulator = 0;
|
||||
}
|
||||
|
||||
// Feeds real seconds (negative counts as none, one frame counts at most MaxFrameSeconds) and runs the whole
|
||||
// steps they pay for. Returns how many ran.
|
||||
public int Advance(float realSeconds, Action<float> step)
|
||||
{
|
||||
_accumulator += Math.Min(Math.Max(realSeconds, 0f), MaxFrameSeconds);
|
||||
var ran = 0;
|
||||
_advancing = true;
|
||||
try
|
||||
{
|
||||
while (_accumulator >= _period)
|
||||
{
|
||||
_accumulator -= _period;
|
||||
step(Step);
|
||||
Steps++;
|
||||
ran++;
|
||||
}
|
||||
}
|
||||
finally { _advancing = false; }
|
||||
return ran;
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/SimClock.cs.meta
Normal file
11
Assets/Scripts/ServerShared/SimClock.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7a9e3edac65f4a8e8313bdbfe69ccebd
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue