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:
Meta Vens 2026-10-16 20:18:54 +02:00
commit 86c3a94880
817 changed files with 66571 additions and 16096 deletions

View file

@ -0,0 +1,244 @@
using System;
using System.IO;
using GameCult.Caching;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for campaign aetheria-gravity, cut ambient-follows-populated-area: the ambient tint falls softly to
/// dark and never hits an edge (ruling dark-beyond-populated-area). It opens ARPG.unity, takes the Ambient Fog Light the
/// scene wires into ZoneRenderer, sizes it for a generated zone with ZoneRenderer.FitAmbientLight (the call LoadZone
/// makes, not a copy), renders it through an orthographic camera that culls its layer into a target built from the descriptor of the production
/// Fog Tint render texture (B10G11R11_UFloatPack32, the format the Tint cameras write), and checks the
/// radial profile against exp(-(r/P)^2 ln(1/_EdgeBrightness)) times the centre, to within what that format stores (a
/// 5-bit mantissa) wherever the gaussian is at least a few ZoneRenderer.AmbientFloor (P is Zone.PopulatedRadius), that it
/// is lit at Pack.Radius, that the quad's rim and every lit texel beside a dark one are
/// at most two floors, and that no two lit texels are more than half a decade apart.
///
/// Renders, so it needs a graphics device: run WITHOUT -nographics.
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.AmbientEdgeVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class AmbientEdgeVerify
{
const string Tag = "[AmbientEdgeVerify]";
const int Size = 512;
const int AmbientLayer = 13;
const string FogTintPath = "Assets/Resources/Fog Tint.renderTexture";
// A float with a 5-bit mantissa (Fog Tint's blue) steps by 2^-5 of its value, and the target truncates to a step.
const float FormatRelativeError = 1f / 32f;
// The profile is held to the gaussian where it is at least this many floors; below that the format's tail is measured, not held.
const float FaithfulFloors = 8f;
// The rim and every lit texel beside a dark one hold at most this many floors, 2^-14 (the smallest normal of the format's
// floats): the one step to dark is the format's last value. Measured on the Fog Tint format it is 1.5 floors at most.
const float StepToDarkFloors = 2f;
static bool _ok = true;
static void OnLog(string message, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && !message.StartsWith(Tag))
Fail("logged-error", message.Split('\n')[0]);
}
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
Application.logMessageReceived += OnLog;
var work = Path.Combine(Path.GetTempPath(), "ambient-edge-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.Combine(work, "probe"));
try
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
// Generated zones have the populated radius at about .78 of the pack radius (p50 over 1500 zones): this one's
// pack radius is set so, which puts Pack.Radius where it sits in play, inside the quad's reach.
var probe = GravityFieldParityVerify.BuildZone(settings, Path.Combine(work, "probe"), out _);
var zone = GravityFieldParityVerify.BuildZone(settings, work, out _, probe.PopulatedRadius / .78f);
EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single);
try
{
var renderer = UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>(FindObjectsInactive.Include);
if (renderer == null || renderer.AmbientLight == null) throw new InvalidOperationException("ARPG.unity wires no ZoneRenderer.AmbientLight.");
Check(renderer, zone);
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
Application.logMessageReceived -= OnLog;
try { Directory.Delete(work, true); } catch { }
}
EditorApplication.Exit(_ok ? 0 : 1);
}
// A bare ambient quad for the verifies that run LoadZone on a renderer built in code: the scene's material, no scene.
public static Transform NewAmbientLight()
{
var quad = new GameObject("Ambient Fog Light") { layer = AmbientLayer };
quad.AddComponent<MeshFilter>().sharedMesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");
quad.AddComponent<MeshRenderer>().sharedMaterial = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Brushes/Sector Tint.mat");
return quad.transform;
}
static void Check(ZoneRenderer renderer, Zone zone)
{
var production = AssetDatabase.LoadAssetAtPath<RenderTexture>(FogTintPath);
if (production == null || production.graphicsFormat != GraphicsFormat.B10G11R11_UFloatPack32)
Fail("format", $"Fog Tint is {(production == null ? "missing" : production.graphicsFormat.ToString())}, not the B10G11R11_UFloatPack32 that AmbientFloor and FormatRelativeError describe");
var light = renderer.AmbientLight;
if (light.parent != null) Fail("wiring", $"the ambient quad sits under {light.parent.name}, whose scale is the pack radius's");
if (light.gameObject.layer != AmbientLayer) Fail("wiring", $"the ambient quad is on layer {light.gameObject.layer}, not {AmbientLayer}");
ZoneRenderer.FitAmbientLight(light, zone);
var meshRenderer = light.GetComponent<MeshRenderer>();
var material = meshRenderer.sharedMaterial;
var edge = material.GetFloat("_EdgeBrightness");
var tint = material.GetColor("_Color").linear;
var centre = material.GetFloat("_Depth") * Mathf.Max(tint.r, Mathf.Max(tint.g, tint.b));
var populated = zone.PopulatedRadius;
var half = light.localScale.x / 2f;
Debug.Log($"{Tag} populated radius {populated:F1} u, pack radius {zone.Pack.Radius:F1} u, quad half-extent {half:F1} u, edge brightness {edge:G3}, centre {centre:G4}");
if (!(populated > 0f) || !(half > populated)) { Fail("sizing", $"the quad half-extent {half:F1} u does not reach beyond the populated radius {populated:F1} u"); return; }
Render(light, half * 1.05f, out var value, out var world);
var floor = ZoneRenderer.AmbientFloor;
Debug.Log($"{Tag} format floor {floor:E2} = {floor / centre:E2} of the centre; tail (drawn / floor): "
+ string.Join(" ", System.Linq.Enumerable.Select(new[] { 1.5f, 1.75f, 1.9f, 2f, 2.05f, 2.1f, 2.15f, 2.2f },
k => $"{k}P:{Sample(value, world, new Vector2(k * populated, 0f)) / floor:G3}")));
var logFall = Mathf.Log(1f / edge);
foreach (var k in new[] { 0f, .5f, 1f, 1.5f, 2f })
{
var drawn = Sample(value, world, new Vector2(k * populated, 0f));
Debug.Log($"{Tag} r = {k} P: drawn {drawn:G5}, expected {centre * Mathf.Exp(-k * k * logFall):G5}");
}
var worstProfile = 0f;
var compared = 0;
var rim = 0f;
for (var i = 0; i < value.Length; i++)
{
if (float.IsNaN(value[i])) { Fail("texels", $"texel {i}: NaN"); return; }
var r = world[i].magnitude;
var expected = centre * Mathf.Exp(-(r / populated) * (r / populated) * logFall);
if (r <= half && expected >= FaithfulFloors * floor)
{
var error = Mathf.Abs(value[i] - expected) / (FormatRelativeError * expected);
worstProfile = Mathf.Max(worstProfile, error);
compared++;
if (error > 1f) { Fail("profile", $"at r = {r / populated:F3} P: expected {expected:G5}, drawn {value[i]:G5}, off by {error:F2} times the format's step"); return; }
}
// The rim: the texels in the quad's outermost ring (within two texels of its edge).
var edgeDistance = half - Mathf.Max(Mathf.Abs(world[i].x), Mathf.Abs(world[i].y));
if (edgeDistance >= 0f && edgeDistance < 2f * (half * 1.05f * 2f / Size)) rim = Mathf.Max(rim, value[i]);
}
Debug.Log($"{Tag} profile: {compared} texels held to the gaussian, worst error {worstProfile:F3} of the format's step; rim {rim / centre:E2} of the centre");
if (compared < Size * Size / 16) Fail("profile", $"only {compared} texels were held to the gaussian; the check is vacuous");
if (rim > floor * StepToDarkFloors) Fail("rim", $"the quad's rim is {rim / floor:G3} times the format floor");
var atPack = Sample(value, world, new Vector2(zone.Pack.Radius, 0f));
Debug.Log($"{Tag} at Pack.Radius: {atPack / centre:E2} of the centre");
if (!(atPack > 0f)) Fail("pack-radius", "the ambient is zero at Pack.Radius");
var worstJump = 0f;
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var here = value[y * Size + x];
if (here <= 0f) continue;
foreach (var next in new[] { x + 1 < Size ? value[y * Size + x + 1] : 0f, y + 1 < Size ? value[(y + 1) * Size + x] : 0f })
{
if (next <= 0f) { if (here > floor * StepToDarkFloors) Fail("last-step", $"a lit texel of {here / floor:G3} floors sits beside a dark one"); continue; }
worstJump = Mathf.Max(worstJump, Mathf.Abs(Mathf.Log10(here / next)));
}
}
Debug.Log($"{Tag} largest jump between neighbouring lit texels: {worstJump:F3} decades (limit 0.5)");
if (worstJump > .5f) Fail("jump", $"neighbouring texels differ by {worstJump:F2} decades");
var lit = 0;
foreach (var v in value) if (v > 0f) lit++;
if (lit < Size * Size / 2) Fail("jump", $"only {lit} texels are lit; the check is vacuous");
}
static float Sample(float[] value, Vector2[] world, Vector2 at)
{
var best = 0;
for (var i = 1; i < world.Length; i++)
if ((world[i] - at).sqrMagnitude < (world[best] - at).sqrMagnitude) best = i;
return value[best];
}
// Renders the ambient layer through a downward orthographic camera centred on the origin, as the Tint cameras see it,
// and returns the brightest channel of every texel with the world xz of its centre, which is asked of the camera.
static void Render(Transform light, float half, out float[] value, out Vector2[] world)
{
var production = AssetDatabase.LoadAssetAtPath<RenderTexture>(FogTintPath) ?? throw new InvalidOperationException("No Fog Tint render texture.");
var rt = new RenderTexture(production.descriptor) { filterMode = FilterMode.Point };
var cameraObject = new GameObject("Ambient Edge Camera");
var read = new Texture2D(Size, Size, TextureFormat.RGBAFloat, false);
var previous = RenderTexture.active;
try
{
var camera = cameraObject.AddComponent<Camera>();
camera.orthographic = true;
camera.orthographicSize = half;
camera.aspect = 1f;
camera.nearClipPlane = .3f;
camera.farClipPlane = 1000f;
camera.cullingMask = 1 << light.gameObject.layer;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.black;
camera.allowHDR = false;
camera.allowMSAA = false;
camera.targetTexture = rt;
cameraObject.transform.SetPositionAndRotation(new Vector3(0f, 100f, 0f), Quaternion.Euler(90f, 0f, 0f));
camera.Render();
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, Size, Size), 0, 0);
read.Apply();
var pixels = read.GetPixelData<float>(0);
value = new float[Size * Size];
for (var i = 0; i < value.Length; i++)
value[i] = Mathf.Max(pixels[4 * i], Mathf.Max(pixels[4 * i + 1], pixels[4 * i + 2]));
world = new Vector2[Size * Size];
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var p = camera.ViewportToWorldPoint(new Vector3((x + .5f) / Size, (y + .5f) / Size, 100f));
world[y * Size + x] = new Vector2(p.x, p.z);
}
}
finally
{
RenderTexture.active = previous;
UnityEngine.Object.DestroyImmediate(cameraObject);
UnityEngine.Object.DestroyImmediate(read);
rt.Release();
UnityEngine.Object.DestroyImmediate(rt);
}
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 63b03af05dfdae44c89e21ca7ebec892

View file

@ -0,0 +1,208 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using GameCult.Caching;
using UnityEditor;
using UnityEngine;
using CultMath;
using static CultMath.math;
// Batch proof of the capability presenters' wiring, without a scene: a zone ship is bound to an EntityInstance through the
// game's own SetEntity, and impacts and grabs are published on the ship's Capabilities exactly as the simulation does. A hull absorb spawns
// one hull effect under the instance and, for the player's ship at ScreenShake 1, raises one camera impulse; ScreenShake 0
// or another ship raises none; a shield absorb spawns no hull effect. The shield ripple itself (ShieldManager.ShowHit
// needs a shield material and a rig) is looked at in the editor, not here. Grabs: a Tractor Beam prefab under the instance
// is bound by the same SetEntity and presents a grab from events alone (emission at Power and the aim at the held point
// from Started to Completed or Cancelled, nothing otherwise, nothing for another entity's grab).
//
// Unity -batchmode -nographics -projectPath <project> -executeMethod CapabilityPresentationSmoke.Run -logFile <log>
//
// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
public static class CapabilityPresentationSmoke
{
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static void Run()
{
var work = Path.Combine(Path.GetTempPath(), $"capability-presentation-smoke-{Guid.NewGuid():N}");
GameObject[] objects = null;
try
{
Directory.CreateDirectory(work);
objects = Check(work);
Clean(objects, work);
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
Clean(objects, work);
EditorApplication.Exit(1);
}
}
// Edit mode runs no Awake or Start; the smoke runs the ones the game's scene would have.
private static void Awaken(Component component) => component.GetType().GetMethod("Awake", Any)?.Invoke(component, null);
private static GameObject[] Check(string work)
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")?.GameplaySettings
?? throw new InvalidOperationException("No Settings.asset.");
var shape = new Shape(5, 4);
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
var hullData = new HullData
{
Name = "Smoke Hull", HullType = HullType.Ship, Shape = shape, Durability = 1000, Mass = 1000, Armor = 0
};
var cache = AetheriaStores.Open(Path.Combine(work, "smoke.cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.Upsert(hullData);
cache.FlushAsync().Wait();
var ledger = new ProvenanceLedger();
for (var i = 1; i <= 8; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 };
var items = new ItemManager(cache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Smoke", Owner = null }, null);
var hullRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("Smoke Hull"));
var ship = new Ship(items, zone, new EquippableItem { Data = hullRef, Durability = 1000, Lot = 1 }, new EntitySettings());
var other = new Ship(items, zone, new EquippableItem { Data = hullRef, Durability = 1000, Lot = 2 }, new EntitySettings());
zone.Admit(ship, piloted: false);
zone.Admit(other, piloted: false);
// The scene's side: the tuning object with a pooled effect, and the game manager that names the player's ship.
var feedbackObject = new GameObject("Smoke Impact Feedback");
var feedback = feedbackObject.AddComponent<ImpactFeedback>();
Awaken(feedback);
var effectObject = new GameObject("Smoke Hull Effect");
feedback.HullEffect = effectObject.AddComponent<Prototype>();
var managerObject = new GameObject("Smoke Game Manager");
var manager = managerObject.AddComponent<ActionGameManager>();
typeof(ActionGameManager).GetProperty("Instance", Any).SetValue(null, manager);
manager.CurrentEntity = ship;
var beamPrefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Content/Prefabs/Tractor Beam.prefab")
?? throw new InvalidOperationException("No Tractor Beam prefab.");
// An entity's instance as the game builds it: the beam is a child before SetEntity on both ship paths, so the
// binder finds it as the game does.
(GameObject Object, EntityInstance Instance, TractorBeam Beam) Bound(string name, Entity entity)
{
var go = new GameObject(name);
var bound = go.AddComponent<EntityInstance>();
Awaken(bound);
bound.HullColliders = new HullCollider[0];
bound.RadiatorHardpoints = new RadiatorHardpoint[0];
bound.ThrusterHardpoints = new ThrusterHardpoint[0];
bound.WeaponHardpoints = new WeaponHardpoint[0];
bound.ArticulationPoints = new ArticulationPoint[0];
var tractor = ((GameObject)PrefabUtility.InstantiatePrefab(beamPrefab, go.transform)).GetComponent<TractorBeam>();
tractor.Power = .8f;
tractor.Direction = Vector3.forward;
bound.SetEntity(null, entity);
return (go, bound, tractor);
}
var (instanceObject, instance, beam) = Bound("Smoke Entity Instance", ship);
var (otherObject, _, otherBeam) = Bound("Smoke Other Instance", other);
int Effects() => instance.GetComponentsInChildren<Prototype>(true).Count(p => p != null && !p.isOriginalPrototype);
void Expect(string what, int effects, int kicks)
{
if (Effects() != effects || feedback.KicksRaised != kicks)
throw new InvalidOperationException($"{what}: {Effects()} hull effects (want {effects}), {feedback.KicksRaised} impulses (want {kicks}).");
}
AbsorbEvent Hit(AbsorbLayer layer) => new AbsorbEvent(float3(1f, 0f, 2f), float3(0f, 0f, 1f), 100f, DamageType.Kinetic, layer);
ActionGameManager.PlayerSettings.GraphicsSettings.ScreenShake = 1f;
ship.Capabilities.PublishAbsorb(Hit(AbsorbLayer.Hull));
Expect("player's hull hit", 1, 1);
var effect = instance.GetComponentsInChildren<Prototype>(true).Single(p => !p.isOriginalPrototype);
var drawn = DrawAhead.Carried(ship, float3(1f, 0f, 2f), ActionGameManager.Clock.Lead);
if (abs(effect.transform.position.x - drawn.x) > 1e-3f || abs(effect.transform.position.z - drawn.z) > 1e-3f)
throw new InvalidOperationException("The hull effect is not at the drawn impact point.");
ActionGameManager.PlayerSettings.GraphicsSettings.ScreenShake = 0f;
ship.Capabilities.PublishAbsorb(Hit(AbsorbLayer.Hull));
Expect("hull hit at ScreenShake 0", 2, 1);
ActionGameManager.PlayerSettings.GraphicsSettings.ScreenShake = 1f;
manager.CurrentEntity = other;
ship.Capabilities.PublishAbsorb(Hit(AbsorbLayer.Hull));
// An untracked ship is not drawn at (ActionGameManager.DrawsAt, since contact-hud): no hull effect, no impulse.
Expect("hull hit on an untracked ship", 2, 1);
// Once the player's instruments track it, the same hit is drawn.
other.VisibleEntities.Add(ship);
ship.Capabilities.PublishAbsorb(Hit(AbsorbLayer.Hull));
Expect("hull hit on a tracked ship", 3, 1);
other.VisibleEntities.Remove(ship);
manager.CurrentEntity = ship;
ship.Capabilities.PublishAbsorb(Hit(AbsorbLayer.Shield));
Expect("player's shield hit", 3, 2);
// Grabs: the beam presents the simulation's events and nothing else.
float Emission() => beam.ParticleSystem.emission.rateOverTimeMultiplier;
void ExpectBeam(string what, float emission, bool towardHeld)
{
beam.Update();
var forward = beam.transform.forward;
var aimed = towardHeld ? forward.x > .999f : forward.z > .999f;
if (abs(Emission() - emission) > 1e-4f || !aimed)
throw new InvalidOperationException($"{what}: emission {Emission()} (want {emission}), forward {forward} (want {(towardHeld ? "+x" : "+z")}).");
}
GrabEvent Grab(GrabPhase phase, float3 at) => new GrabEvent(new FloatingBodyId(7), phase, at, 1f);
ExpectBeam("idle beam", 0f, false);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Started, float3(20f, 0f, 0f)));
ExpectBeam("grab started", .8f, true);
foreach (var phase in new[] { GrabPhase.Extend, GrabPhase.Envelop, GrabPhase.Pull })
{
ship.Capabilities.PublishGrab(Grab(phase, float3(20f, 0f, 0f)));
ExpectBeam($"grab {phase}", .8f, true);
}
ship.Capabilities.PublishGrab(Grab(GrabPhase.Completed, float3(20f, 0f, 0f)));
ExpectBeam("grab completed", 0f, false);
// A grab cancelled after its item vanished carries no position: the beam goes dark and never turns toward it.
ship.Capabilities.PublishGrab(Grab(GrabPhase.Started, float3(20f, 0f, 0f)));
ExpectBeam("second grab started", .8f, true);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Cancelled, float3(0f, 0f, 0f)));
ExpectBeam("grab cancelled", 0f, false);
// Aim is on the ground plane: a beam above the held point does not pitch toward it.
var beamHome = beam.transform.position;
beam.transform.position = beamHome + new Vector3(0f, 10f, 0f);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Started, float3(20f, 7f, 0f)));
ExpectBeam("grab from above", .8f, true);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Completed, float3(20f, 7f, 0f)));
beam.transform.position = beamHome;
// A grab held at the beam's own position has no direction to take: the beam keeps the aim it had.
beam.Direction = Vector3.right;
var atBeam = float3(beam.transform.position.x, 0f, beam.transform.position.z);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Started, atBeam));
ExpectBeam("grab at the beam", .8f, true);
ship.Capabilities.PublishGrab(Grab(GrabPhase.Completed, atBeam));
beam.Direction = Vector3.forward;
ExpectBeam("after the grab at the beam", 0f, false);
// The beam belongs to the ship's entity: another entity's grab, with its own beam bound, moves only that beam.
other.Capabilities.PublishGrab(Grab(GrabPhase.Started, float3(20f, 0f, 0f)));
ExpectBeam("another entity's grab", 0f, false);
otherBeam.Update();
if (abs(otherBeam.ParticleSystem.emission.rateOverTimeMultiplier - .8f) > 1e-4f)
throw new InvalidOperationException("The other entity's own beam did not present its grab.");
Debug.Log("CAPABILITY_PRESENTATION_SMOKE ok effects=3 impulses=2 grabs=ok");
return new[] { feedbackObject, effectObject, managerObject, instanceObject, otherObject };
}
private static void Clean(GameObject[] objects, string work)
{
if (objects != null)
foreach (var go in objects)
if (go != null) UnityEngine.Object.DestroyImmediate(go);
try { if (Directory.Exists(work)) Directory.Delete(work, true); }
catch (Exception error) { Debug.LogWarning($"Impact presenter smoke left {work}: {error.Message}"); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b1b27e4493b2cfe48805c786a5090cd3

View file

@ -0,0 +1,216 @@
using System;
using System.Collections;
using System.IO;
using System.Linq;
using GameCult.Caching;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// Batch proof that the presenters read the drawn pose through the clock: DrawnPoseTests pins the pose maths headlessly,
// and this is what pins that each presenter passes ActionGameManager.Clock.Lead into it. A zone is loaded into a fresh
// ZoneRenderer with the pickup and mine prefabs ARPG.unity's ZoneRenderer names; a loose Projectile is launched on the
// zone. The zone is stepped once, then the clock is set to leads 0, 0.008 and 0.015 s with no step, and each presenter's
// own Update places its transform. A body is drawn at its last step plus its step velocity times the lead, spelled here
// from the body's fields, so a presenter that reads lead 0 (or half the lead) sits on the step and fails.
//
// Reached: ItemPickup, MineInstance, Projectile.Draw. Not reached: ZoneRenderer.Update (Lower needs a ComputeBuffer, a
// GPU device) and the ActionGameManager markers (they need the ARPG scene running); a Lower split so its record fill is
// pure, or a run with a GPU and ARPG.unity in play mode, would reach them.
//
// Unity -batchmode -nographics -projectPath <project> -executeMethod Aetheria.EditorTools.DrawnPoseWiringVerify.Run -logFile <log>
//
// Do not pass -quit: Run enters play mode (a domain reload), the check runs there, and the Editor exits itself, 0 on
// success and 1 on any failure.
namespace Aetheria.EditorTools
{
[InitializeOnLoad]
public static class DrawnPoseWiringVerify
{
private const string Tag = "[DrawnPoseWiringVerify]";
private const string Flag = "DrawnPoseWiringVerify.running";
private const string Wiring = "DrawnPoseWiringVerify.wiring";
private const double Budget = 300; // real seconds
private const float RoundSpeed = 100f, Tolerance = 1e-3f;
private static IEnumerator _check;
private static double _started;
private static string _work;
static DrawnPoseWiringVerify()
{
if (SessionState.GetBool(Flag, false)) EditorApplication.playModeStateChanged += OnPlayMode;
}
public static void Run()
{
try
{
SessionState.SetString(Wiring, ReadWiring());
SessionState.SetBool(Flag, true);
EditorApplication.EnterPlaymode();
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void OnPlayMode(PlayModeStateChange change)
{
if (change != PlayModeStateChange.EnteredPlayMode) return;
_work = Path.Combine(Path.GetTempPath(), $"drawn-pose-wiring-{Guid.NewGuid():N}");
Directory.CreateDirectory(_work);
_started = Time.realtimeSinceStartupAsDouble;
_check = Check();
EditorApplication.update += Step;
}
private static void Step()
{
try
{
if (Time.realtimeSinceStartupAsDouble - _started > Budget) throw new InvalidOperationException($"The check did not finish in {Budget} seconds.");
if (_check.MoveNext()) return;
Finish(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
Finish(1);
}
}
private static void Finish(int code)
{
EditorApplication.update -= Step;
SessionState.SetBool(Flag, false);
try { if (Directory.Exists(_work)) Directory.Delete(_work, true); } catch (Exception) { /* a temp directory */ }
EditorApplication.Exit(code);
}
private static void Require(bool condition, string what)
{
if (!condition) throw new InvalidOperationException(what);
}
private static IEnumerator Check()
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")?.GameplaySettings
?? throw new InvalidOperationException("No Settings.asset.");
settings.FloaterLayerHeight = -1.5f; // nonzero, so a presenter that drops the floater layer fails
var wired = SessionState.GetString(Wiring, "").Split('|').Select(entry => entry.Split('=')).ToDictionary(pair => pair[0], pair => pair[1]);
var pickupPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(wired["SimpleCommodityPickup"])?.GetComponent<ItemPickup>();
var minePrefab = AssetDatabase.LoadAssetAtPath<GameObject>(wired["MinePrefab"])?.GetComponent<MineInstance>();
Require(pickupPrefab != null, "ZoneRenderer.SimpleCommodityPickup is not an ItemPickup in ARPG.unity.");
Require(minePrefab != null, "ZoneRenderer.MinePrefab is not a MineInstance in ARPG.unity.");
var oneCell = new Shape(1, 1);
oneCell[new CultMath.int2(0, 0)] = true;
var cache = AetheriaStores.Open(Path.Combine(_work, "wiring.cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.Upsert(new SimpleCommodityData { Name = "Wiring Ore", Shape = oneCell, MaxStack = 100 });
cache.FlushAsync().Wait();
var ledger = new ProvenanceLedger();
var items = new ItemManager(cache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), null, null);
var rootObject = new GameObject("Wiring Zone Root");
var rendererObject = new GameObject("Wiring Zone Renderer");
rendererObject.SetActive(false); // inactive: ZoneRenderer.Update needs a GPU and is not part of this check
var renderer = rendererObject.AddComponent<ZoneRenderer>();
renderer.ZoneRoot = rootObject.transform;
renderer.SimpleCommodityPickup = pickupPrefab;
renderer.MinePrefab = minePrefab;
renderer.ItemManager = items;
renderer.SectorBrushes = new GameObject("Wiring Brushes").transform;
renderer.AmbientLight = AmbientEdgeVerify.NewAmbientLight();
renderer.SlimeGravityCamera = new GameObject("Wiring Gravity Camera").AddComponent<Camera>();
var slimeObject = new GameObject("Wiring Slime");
slimeObject.SetActive(false);
renderer.SlimeRenderer = slimeObject.AddComponent<Slime>();
renderer.LoadZone(zone);
var ore = new SimpleCommodity { Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<SimpleCommodityData>("Wiring Ore")), Quantity = 7 };
var floating = zone.Release(ore, new float2(3, 4), new float2(10, 0));
var mine = new Mine
{
Body = new KinematicBody { Position = new float2(-20, 8), Velocity = new float2(0, 14) },
ArmingDelay = 1e6f, FuseDelay = 1f, Lifetime = 1e6f, BlastRadius = 1f
};
zone.Lay(mine);
// A round on its frozen line, no target and no outcome known: drawn at FireOrigin + direction * speed * (T - FireTime).
var shot = new PendingShot
{
ShotId = 1, FireOrigin = new float3(0, 0, 0), FireTime = 0f, TravelDirection = new float2(1, 0), Speed = RoundSpeed,
MaxRange = 1e6f, FireRange = 1e6f, CommitTime = 1e5f, ArrivalTime = 2e5f
};
var projectile = new GameObject("Wiring Round").AddComponent<Projectile>();
projectile.Launch(zone, shot, new Vector3(0, 0, 0));
yield return null;
zone.Update(.5f);
var pickup = rootObject.GetComponentsInChildren<ItemPickup>(true).Single(p => p.Item == ore);
var mineInstance = UnityEngine.Object.FindObjectsByType<MineInstance>(FindObjectsInactive.Include, FindObjectsSortMode.None).Single();
var pickupVelocity = floating.Body.TotalVelocity;
var mineVelocity = mine.Body.TotalVelocity;
Require(Mathf.Abs(pickupVelocity.x) > 1f && Mathf.Abs(mineVelocity.y) > 1f, "The fixture's bodies stopped: a lead would not move them.");
Vector2 baseline = default;
foreach (var leadSeconds in new[] { 0f, .008f, .015f })
{
ActionGameManager.Clock.Reset();
if (leadSeconds > 0) ActionGameManager.Clock.Advance(leadSeconds, _ => throw new InvalidOperationException("a step ran"));
var lead = ActionGameManager.Clock.Lead;
Require(Mathf.Abs(lead - leadSeconds) < 1e-6f, $"The clock's lead is {lead}, not {leadSeconds}.");
yield return null;
var seen = pickup.transform.position;
var want = floating.Body.Position + pickupVelocity * lead;
Require(Mathf.Abs(seen.x - want.x) < Tolerance && Mathf.Abs(seen.z - want.y) < Tolerance,
$"ItemPickup at lead {lead}: drawn x/z {seen.x},{seen.z}, the step plus velocity times lead {want.x},{want.y}.");
seen = mineInstance.transform.position;
want = mine.Body.Position + mineVelocity * lead;
Require(Mathf.Abs(seen.x - want.x) < Tolerance && Mathf.Abs(seen.z - want.y) < Tolerance,
$"MineInstance at lead {lead}: drawn x/z {seen.x},{seen.z}, the step plus velocity times lead {want.x},{want.y}.");
Require(Mathf.Abs(seen.y - DrawAhead.FloaterHeight(zone, settings, new float2(want.x, want.y), lead)) < Tolerance,
$"MineInstance y {seen.y} is not on the floater layer.");
// The round's line is a function of the drawn time: it moves RoundSpeed * lead along its direction between leads.
seen = projectile.transform.position;
if (leadSeconds == 0f) baseline = new Vector2(seen.x, seen.z);
var moved = new Vector2(seen.x, seen.z) - baseline;
Require(Mathf.Abs(moved.x - RoundSpeed * lead) < Tolerance && Mathf.Abs(moved.y) < Tolerance,
$"Projectile at lead {lead}: drawn {moved.x},{moved.y} past its lead-0 pose, expected {RoundSpeed * lead},0.");
}
ActionGameManager.Clock.Reset();
Debug.Log($"{Tag} ok: ItemPickup, MineInstance and Projectile draw at the clock's lead (0, 0.008, 0.015 s)");
}
// What ARPG.unity's ZoneRenderer names in the pickup and mine fields, read from the saved scene before the play session
// (a scene cannot be opened inside one) and carried across the domain reload as asset paths.
private static string ReadWiring()
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Additive);
try
{
var found = UnityEngine.Object.FindObjectsByType<ZoneRenderer>(FindObjectsInactive.Include, FindObjectsSortMode.None)
.Where(r => r.gameObject.scene == scene).ToArray();
Require(found.Length == 1, $"ARPG.unity has {found.Length} ZoneRenderers.");
var wired = found[0];
return string.Join("|", new (string, UnityEngine.Object)[]
{
("SimpleCommodityPickup", wired.SimpleCommodityPickup), ("MinePrefab", wired.MinePrefab)
}.Select(f => f.Item1 + "=" + (f.Item2 == null ? "" : AssetDatabase.GetAssetPath(f.Item2))));
}
finally { EditorSceneManager.CloseScene(scene, true); }
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c2270cf68a4af384eb715c8b5a55f5e8

View file

@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TMPro;
using UnityEditor;
using UnityEngine;
// Every single-code-point emoji of the pinned Unicode Emoji version that Twemoji draws, and the Pirates product
// names read from the shipped catalog, render through an ordinary TMP text on the game's body font with no
// missing code point, no blank glyph, ink in the emoji atlas, and each glyph served by the emoji asset or by the
// body font itself, never by a third font. TMP Settings must route emoji by two named routes (operator ruling
// emoji-fallback-route): the global fallback names Emoji.asset and the emoji fallback list is exactly Emoji.asset,
// so dropping either fails.
// Run as -executeMethod EmojiCheck.Run (exit 1 on failure in batchmode, as EngineAssetCheck). Corpus:
// tools/emoji/emoji-singles.txt (from emoji-test.txt); the emoji Twemoji lacks are listed in
// tools/emoji/emoji-unsupported.txt and reported, not rendered; -emojiLimit N spreads N entries evenly for a spike.
// Every fully-qualified multi-code-point sequence (tools/emoji/emoji-sequences.txt: ZWJ, skin tone, flag, keycap,
// tag) must also render as exactly one visible character, which needs `liga` on the rendering component: every
// TMP text in every prefab and scene must have it, and so must one added at runtime (as ActionGameManager's
// FACE AIM mark is), or a family or flag would show as its pieces.
public static class EmojiCheck
{
const string BodyFontPath = "Assets/Fonts/Ubuntu/Ubuntu-L Small SDF.asset";
const string PiratesFaction = "Pirates";
const int Chunk = 64;
[MenuItem("Aetheria/Text/Check Emoji Rendering")]
public static void Run()
{
var failures = new List<string>();
var summary = RunCheck(failures);
foreach (var failure in failures.Take(20)) Debug.LogError(failure);
Debug.Log($"EmojiCheck: {summary}; {failures.Count} failure(s).");
if (Application.isBatchMode) EditorApplication.Exit(failures.Count == 0 ? 0 : 1);
}
// Public so a scratch driver can mutate TMP Settings in memory and watch this fail; adds to failures.
public static string RunCheck(List<string> failures)
{
var emoji = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(EmojiFont.AssetPath);
var body = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(BodyFontPath);
if (emoji == null || body == null)
{
failures.Add("EmojiCheck: Emoji.asset or the body font is missing; run EmojiFont.Build first.");
return "nothing checked";
}
// Two routes (operator ruling emoji-fallback-route): the emoji fallback list is exactly Emoji.asset, and the global list below names it.
if (TMP_Settings.emojiFallbackTextAssets == null || TMP_Settings.emojiFallbackTextAssets.Count != 1 || TMP_Settings.emojiFallbackTextAssets[0] != emoji)
failures.Add("TMP Settings' emoji fallback list is not exactly Emoji.asset: FE0F-followed bases the body font draws will not reach Twemoji.");
if (TMP_Settings.fallbackFontAssets == null || !TMP_Settings.fallbackFontAssets.Contains(emoji))
failures.Add("TMP Settings' global fallback list does not name Emoji.asset: the route for every single code point is gone.");
var unsupported = new HashSet<int>(LoadCodePoints("emoji-unsupported.txt"));
var corpus = LoadSingles().Where(cp => !unsupported.Contains(cp)).ToList();
var sequences = LoadSequences();
var missing = new HashSet<int>();
TMP_Text.MissingCharacterEventCallback onMissing = (unicode, index, source, asset, component) => missing.Add(unicode);
TMP_Text.OnMissingCharacter += onMissing;
var canvas = new GameObject("EmojiCheck", typeof(Canvas));
var text = new GameObject("Text", typeof(RectTransform)).AddComponent<TextMeshProUGUI>();
text.transform.SetParent(canvas.transform, false);
text.font = body;
text.textWrappingMode = TextWrappingModes.NoWrap;
text.rectTransform.sizeDelta = new Vector2(100000, 100000);
int viaEmoji = 0, viaBody = 0, blank = 0, pirateNames = 0, notOne = 0, runtimeLiga = 0;
var strays = new HashSet<string>();
try
{
void Render(string content, string label)
{
text.text = content;
text.ForceMeshUpdate();
for (var i = 0; i < text.textInfo.characterCount; i++)
{
var info = text.textInfo.characterInfo[i];
if (info.character == ' ' || info.elementType != TMP_TextElementType.Character) continue;
if (info.fontAsset == emoji) viaEmoji++;
else if (info.fontAsset == body) viaBody++;
else if (strays.Add($"{info.fontAsset.name}:{(int)info.character:X}"))
failures.Add($"U+{(int)info.character:X4} in {label} was served by {info.fontAsset.name}, not Emoji.asset or the body font");
if (info.fontAsset == emoji && info.textElement.glyph.glyphRect.width <= 0)
{
blank++;
failures.Add($"blank glyph U+{(int)info.character:X4} in {label}");
}
}
}
for (var i = 0; i < corpus.Count; i += Chunk)
{
var slice = corpus.Skip(i).Take(Chunk).ToList();
Render(string.Join(" ", slice.Select(char.ConvertFromUtf32)), $"chunk {i}");
}
// A text created at runtime inherits liga from TMP Settings, with no wiring of its own.
var runtime = new GameObject("Runtime", typeof(RectTransform));
runtime.transform.SetParent(canvas.transform, false);
runtimeLiga = runtime.AddComponent<TextMeshProUGUI>().fontFeatures
.Contains(UnityEngine.TextCore.OTL_FeatureTag.liga) ? 1 : 0;
if (runtimeLiga == 0) failures.Add("a TextMeshProUGUI added at runtime does not have liga: TMP Settings' features are not inherited");
// Sequences: space-separated groups, each of which must end as one visible character.
for (var i = 0; i < sequences.Count; i += Chunk)
{
var slice = sequences.Skip(i).Take(Chunk).ToList();
text.text = string.Join(" ", slice.Select(ToText));
text.ForceMeshUpdate();
var visible = new List<int> { 0 };
var shown = new List<string> { "" };
for (var c = 0; c < text.textInfo.characterCount; c++)
{
var info = text.textInfo.characterInfo[c];
if (info.character == ' ') { visible.Add(0); shown.Add(""); }
else if (info.isVisible)
{
visible[visible.Count - 1]++;
shown[shown.Count - 1] += $" U+{(int)info.character:X}:{info.fontAsset.name}";
}
}
if (visible.Count != slice.Count) failures.Add($"sequence chunk {i}: {visible.Count} groups rendered for {slice.Count} sequences");
for (var g = 0; g < Math.Min(visible.Count, slice.Count); g++)
if (visible[g] != 1)
{
notOne++;
failures.Add($"sequence {slice[g]} rendered {visible[g]} visible characters, not one:{shown[g]}");
}
}
// The Pirates names as the shipped catalog stores them, through the game's own catalog reader.
var catalogPath = Path.Combine(Directory.GetParent(Application.dataPath).FullName, "GameData", "Aetheria.cc");
using (var catalog = AetheriaStores.Open(catalogPath))
{
var pirates = catalog.GetAll<Faction>().SingleOrDefault(faction => faction.Name == PiratesFaction);
if (pirates == null) failures.Add($"the catalog has no {PiratesFaction} faction");
else
{
var key = catalog.RefOf(pirates);
foreach (var product in catalog.GetAll<FactionProductData>().Where(product => product.Manufacturer.Equals(key)))
{
pirateNames++;
Render(product.Name, $"Pirates product name \"{product.Name}\"");
}
if (pirateNames == 0) failures.Add($"the catalog has no {PiratesFaction} products");
}
}
}
finally
{
TMP_Text.OnMissingCharacter -= onMissing;
UnityEngine.Object.DestroyImmediate(canvas);
}
foreach (var cp in missing.OrderBy(c => c)) failures.Add($"missing code point U+{cp:X4}");
// Every serialized TMP text has liga (an instance inherits it from its prefab, so this reads the effective value).
int texts = 0, withoutLiga = 0;
EmojiFont.VisitSerializedTexts(component =>
{
texts++;
if (!component.fontFeatures.Contains(UnityEngine.TextCore.OTL_FeatureTag.liga))
{
withoutLiga++;
failures.Add($"TMP text {component.name} has no liga: {GetPath(component)}");
}
return false;
});
// TMP over-allocates atlasTextures by doubling its capacity when a page is added, so entries past
// atlasTextureCount are null by design (3 pages in a 4-slot array). Only the used pages count.
long ink = 0, colour = 0;
for (var i = 0; i < emoji.atlasTextureCount; i++)
{
var page = emoji.atlasTextures[i];
if (page == null) { failures.Add($"emoji atlas page {i} of {emoji.atlasTextureCount} is null"); continue; }
var pixels = page.GetPixels32();
ink += pixels.LongCount(p => p.a != 0);
colour += pixels.LongCount(p => p.a != 0 && (p.r != p.g || p.g != p.b));
}
if (ink == 0) failures.Add("the emoji atlas holds no ink after rendering");
else if (colour == 0) failures.Add("the emoji atlas holds no coloured pixel: the glyphs rendered monochrome");
var pages = emoji.atlasTextureCount;
// Dynamic atlas content is cache: drop it so this check leaves the asset as Build wrote it.
emoji.ClearFontAssetData(true);
if (unsupported.Count > 0)
Debug.LogWarning($"EmojiCheck: Twemoji lacks {unsupported.Count} single-code-point emoji of the Emoji version: " +
string.Join(" ", unsupported.OrderBy(c => c).Select(c => $"U+{c:X4}")));
return $"{sequences.Count} sequences ({notOne} not one visible character), {texts} serialized TMP texts ({withoutLiga} without liga), runtime text liga {runtimeLiga}; " +
$"checked {corpus.Count} single code points ({unsupported.Count} not drawn by Twemoji, listed in the warning) + {pirateNames} Pirates product names, " +
$"{missing.Count} missing, {viaEmoji} glyphs via the emoji asset, {viaBody} via the body font, {strays.Count} via other fonts, {blank} blank, " +
$"{ink} atlas ink pixels of which {colour} coloured, {pages} atlas pages";
}
static string GetPath(Component component) =>
component.gameObject.scene.IsValid() ? component.gameObject.scene.path : AssetDatabase.GetAssetPath(component);
static string ToText(string sequence) => string.Concat(sequence.Split(' ').Select(cp => char.ConvertFromUtf32(Convert.ToInt32(cp, 16))));
static List<string> LoadSequences() =>
File.ReadAllLines(Path.Combine(Directory.GetParent(Application.dataPath).FullName, "tools", "emoji", "emoji-sequences.txt"))
.Where(l => l.Length > 0).ToList();
static List<int> LoadSingles()
{
var all = LoadCodePoints("emoji-singles.txt");
var args = Environment.GetCommandLineArgs();
var at = Array.IndexOf(args, "-emojiLimit");
if (at < 0 || at + 1 >= args.Length) return all;
var limit = int.Parse(args[at + 1]);
return Enumerable.Range(0, limit).Select(i => all[i * all.Count / limit]).ToList();
}
static List<int> LoadCodePoints(string file)
{
var path = Path.Combine(Directory.GetParent(Application.dataPath).FullName, "tools", "emoji", file);
return File.ReadAllLines(path).Where(l => l.Length > 0).Select(l => Convert.ToInt32(l, 16)).ToList();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c6f940add256a754daac8460fc79480d

View file

@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
// The one writer of the emoji font asset and of TMP Settings' emoji routing. The font file is the
// output of tools/emoji/fetch_emoji_font.py; the asset is a dynamic COLOR font asset whose atlas pages
// are cache, filled on first use at runtime and cleared here. Every TMP text reaches emoji through TMP
// Settings alone (no component names an emoji font), by two routes that both name only Emoji.asset (operator ruling
// emoji-fallback-route): the global fallback serves every code point, including the 200 text-presentation emoji the
// emoji list alone leaves unresolved; the emoji fallback list is what TMP tries first when FE0F follows, so a keycap
// or FE0F/ZWJ sequence whose first code point the body font also draws reaches Twemoji, whose ligatures collapse it.
// Sequences (ZWJ, skin tone, flag, keycap) resolve only through the emoji font's GSUB ligatures, and TMP applies
// them per component, gated by that component's font features: EnableLigatures writes `liga` into every
// serialized TMP text and into TMP Settings (so a text created later inherits it); there is no global switch.
public static class EmojiFont
{
public const string FontPath = "Assets/Fonts/Emoji/Twemoji.ttf";
public const string AssetPath = "Assets/Fonts/Emoji/Emoji.asset";
// Colour outlines (COLRv0) are rasterised at one size; 109 is the strike size a CBDT set needs.
const int SamplingPointSize = 64;
const int AtlasPadding = 4;
const int AtlasSize = 2048;
// Menu entry for interactive use; -executeMethod EmojiFont.Build for batchmode, exit 1 on failure.
[MenuItem("Aetheria/Text/Build Emoji Font")]
public static void Build()
{
var ok = TryBuild(out var message);
if (ok) Debug.Log(message); else Debug.LogError(message);
if (Application.isBatchMode) EditorApplication.Exit(ok ? 0 : 1);
}
static bool TryBuild(out string message)
{
var font = AssetDatabase.LoadAssetAtPath<Font>(FontPath);
if (font == null)
{
message = $"EmojiFont: {FontPath} is missing; run tools/emoji/fetch_emoji_font.py.";
return false;
}
// An existing asset keeps its GUID, so a second Build changes nothing the settings point at.
var asset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(AssetPath);
if (asset == null)
{
asset = TMP_FontAsset.CreateFontAsset(font, SamplingPointSize, AtlasPadding, GlyphRenderMode.COLOR,
AtlasSize, AtlasSize, AtlasPopulationMode.Dynamic, enableMultiAtlasSupport: true);
if (asset == null)
{
message = $"EmojiFont: TMP could not create a font asset from {FontPath}.";
return false;
}
asset.name = "Emoji";
AssetDatabase.CreateAsset(asset, AssetPath);
foreach (var page in asset.atlasTextures)
{
page.name = "Emoji Atlas";
AssetDatabase.AddObjectToAsset(page, asset);
}
asset.material.name = "Emoji Atlas Material";
AssetDatabase.AddObjectToAsset(asset.material, asset);
}
// The atlas pages are cache: Build leaves them empty, the same state EmojiCheck restores.
asset.ClearFontAssetData(true);
// Two routes: the global fallback serves every code point (text-presentation emoji too, U+263A without FE0F);
// the emoji list is tried first when FE0F follows.
TMP_Settings.emojiFallbackTextAssets = new List<TMP_Asset> { asset };
TMP_Settings.fallbackFontAssets = new List<TMP_FontAsset> { asset };
TMP_Settings.defaultSpriteAsset = null;
EditorUtility.SetDirty(asset);
EditorUtility.SetDirty(TMP_Settings.instance);
AssetDatabase.SaveAssets();
message = "EmojiFont: built " + AssetPath + " and named it in both of TMP Settings' emoji routes (the global fallback and the emoji fallback list).";
return true;
}
// Menu entry for interactive use; -executeMethod EmojiFont.EnableLigatures for batchmode, exit 1 on failure.
// Idempotent: a second run changes nothing and saves nothing.
[MenuItem("Aetheria/Text/Enable Ligatures")]
public static void EnableLigatures()
{
try
{
var settings = TMP_Settings.fontFeatures;
var settingsChanged = Enable(settings);
if (settingsChanged) EditorUtility.SetDirty(TMP_Settings.instance);
var (files, components) = VisitSerializedTexts(text =>
{
var features = text.fontFeatures.ToList();
if (!Enable(features, new SerializedObject(text).FindProperty("m_enableKerning").boolValue)) return false;
text.fontFeatures = features;
EditorUtility.SetDirty(text);
return true;
});
AssetDatabase.SaveAssets();
Debug.Log($"EmojiFont: liga added to {components} TMP component(s) in {files} file(s)" +
(settingsChanged ? " and to TMP Settings." : "; TMP Settings already had it."));
if (Application.isBatchMode) EditorApplication.Exit(0);
}
catch (Exception e)
{
Debug.LogError("EmojiFont.EnableLigatures failed: " + e);
if (Application.isBatchMode) EditorApplication.Exit(1);
}
}
// A legacy list ([0], no feature serialized) is first converted to [kern] when kerning is on, as TMP does on load.
static bool Enable(List<OTL_FeatureTag> features, bool kerning = true)
{
if (features.Contains(OTL_FeatureTag.liga)) return false;
features.RemoveAll(tag => tag == 0);
if (kerning && !features.Contains(OTL_FeatureTag.kern)) features.Add(OTL_FeatureTag.kern);
features.Add(OTL_FeatureTag.liga);
return true;
}
// The one walk over every TMP text a serialized asset owns: each prefab and each scene under Assets/, skipping a
// component that belongs to a prefab instance unless that instance overrides its font features (otherwise it
// inherits from its source prefab, which is walked itself). `visit` returns whether it changed the component;
// an asset that changed is saved. Returns the files and components changed.
public static (int files, int components) VisitSerializedTexts(Func<TMP_Text, bool> visit)
{
int files = 0, components = 0;
bool Owns(TMP_Text text) =>
!PrefabUtility.IsPartOfPrefabInstance(text) ||
new SerializedObject(text).FindProperty("m_ActiveFontFeatures")?.prefabOverride == true;
int Visit(IEnumerable<TMP_Text> texts) => texts.Where(Owns).Count(visit);
foreach (var path in AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath))
{
var root = PrefabUtility.LoadPrefabContents(path);
try
{
var changed = Visit(root.GetComponentsInChildren<TMP_Text>(true));
if (changed == 0) continue;
PrefabUtility.SaveAsPrefabAsset(root, path);
files++;
components += changed;
}
finally { PrefabUtility.UnloadPrefabContents(root); }
}
foreach (var path in AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath))
{
var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
try
{
var changed = Visit(scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<TMP_Text>(true)));
if (changed == 0) continue;
EditorSceneManager.SaveScene(scene);
files++;
components += changed;
}
finally { EditorSceneManager.CloseScene(scene, true); }
}
return (files, components);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bd3a902defe23f14fbe821ca9fb26a08

View file

@ -0,0 +1,262 @@
using System;
using System.Collections;
using System.IO;
using System.Linq;
using GameCult.Caching;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using float2 = CultMath.float2;
// Batch proof that ZoneRenderer draws Zone.FloatingItems and nothing else, in a play session with no scene of its own:
// the pickup prefabs are the ones ARPG.unity's ZoneRenderer names (so the wiring is read here too), a zone is loaded
// into a fresh ZoneRenderer, and the zone's own Release, step, expiry and TryPickUp are what move and remove the
// pickups. Zone.Release adds exactly one ItemPickup, placed at the body's position; stepping the zone moves it with the
// body; expiry and TryPickUp each destroy it; an item already in the zone when the renderer loads it is drawn too.
//
// Unity -batchmode -nographics -projectPath <project> -executeMethod FloatingItemsDrawnSmoke.Run -logFile <log>
//
// Do not pass -quit: Run enters play mode (a domain reload), the check runs there, and the Editor exits itself, 0 on
// success and 1 on any failure. Destroy only takes effect in a play session, which is why this is not an edit-mode check.
[InitializeOnLoad]
public static class FloatingItemsDrawnSmoke
{
private const string Flag = "FloatingItemsDrawnSmoke.running";
private const string Wiring = "FloatingItemsDrawnSmoke.wiring";
private static IEnumerator _check;
private const double Budget = 300; // real seconds: batch frames can be far shorter than a game second
private static double _started;
private static string _work;
static FloatingItemsDrawnSmoke()
{
if (SessionState.GetBool(Flag, false)) EditorApplication.playModeStateChanged += OnPlayMode;
}
public static void Run()
{
try
{
SessionState.SetString(Wiring, ReadWiring());
SessionState.SetBool(Flag, true);
EditorApplication.EnterPlaymode();
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void OnPlayMode(PlayModeStateChange change)
{
if (change != PlayModeStateChange.EnteredPlayMode) return;
_work = Path.Combine(Path.GetTempPath(), $"floating-items-smoke-{Guid.NewGuid():N}");
Directory.CreateDirectory(_work);
_started = Time.realtimeSinceStartupAsDouble;
_check = Check();
EditorApplication.update += Step;
}
private static void Step()
{
try
{
if (Time.realtimeSinceStartupAsDouble - _started > Budget) throw new InvalidOperationException($"The check did not finish in {Budget} seconds.");
if (_check.MoveNext()) return;
Finish(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
Finish(1);
}
}
private static void Finish(int code)
{
EditorApplication.update -= Step;
SessionState.SetBool(Flag, false);
try { if (Directory.Exists(_work)) Directory.Delete(_work, true); } catch (Exception) { /* a temp directory */ }
EditorApplication.Exit(code);
}
private static void Require(bool condition, string what)
{
if (!condition) throw new InvalidOperationException(what);
}
private static IEnumerator Check()
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")?.GameplaySettings
?? throw new InvalidOperationException("No Settings.asset.");
// A floater rides its own layer: a nonzero one (never saved back to the asset), so a presenter that drops it fails.
settings.FloaterLayerHeight = -1.5f;
// The wiring: the scene's ZoneRenderer names an ItemPickup prefab in each of the four fields, and none of those
// prefabs keeps a script that no longer exists.
var wired = SessionState.GetString(Wiring, "").Split('|').Select(entry => entry.Split('=')).Select(pair =>
(Field: pair[0], Pickup: pair[1] == "" ? null : AssetDatabase.LoadAssetAtPath<GameObject>(pair[1])?.GetComponent<ItemPickup>())).ToArray();
Require(wired.Length == 4, "The wiring was not carried into the play session.");
foreach (var (name, pickup) in wired)
{
Require(pickup != null, $"ZoneRenderer.{name} is not an ItemPickup in ARPG.unity.");
Require(pickup.ScanLabel != null && pickup.ScanLabelContainer != null, $"{name}'s prefab has no scan label.");
Require(!pickup.GetComponentsInChildren<Component>(true).Any(c => c == null), $"{name}'s prefab has a missing script.");
}
var shape = new Shape(5, 5);
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
var cargoShape = new Shape(4, 4);
foreach (var cell in cargoShape.AllCoordinates) cargoShape[cell] = true;
var oneCell = new Shape(1, 1);
oneCell[new CultMath.int2(0, 0)] = true;
var cache = AetheriaStores.Open(Path.Combine(_work, "smoke.cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.Upsert(new HullData { Name = "Smoke Hub", HullType = HullType.Station, Shape = shape, Durability = 1000, Mass = 1000 });
cache.Upsert(new CargoBayData { Name = "Smoke Crate", Shape = new Shape(), InteriorShape = cargoShape, Durability = 4 });
cache.Upsert(new GearData
{
Name = "Smoke Spare", Hardpoint = HardpointType.Tool, Shape = oneCell, Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000
});
cache.Upsert(new SimpleCommodityData { Name = "Smoke Ore", Shape = oneCell, MaxStack = 100 });
cache.FlushAsync().Wait();
var ledger = new ProvenanceLedger();
for (var i = 1; i <= 8; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 };
var items = new ItemManager(cache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), null, null);
EquippableItem Make(string name, int lot) => new EquippableItem
{
Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<EquippableItemData>(name)), Durability = 1, Lot = lot
};
// A station with a crate takes the picked-up stack. It is not admitted: the zone holds no entity for the renderer to draw.
var hubRef = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("Smoke Hub"));
var taker = new OrbitalEntity(items, zone, new EquippableItem { Data = hubRef, Durability = 1000, Lot = 1 }, default, new EntitySettings());
Require(taker.TryEquip(Make("Smoke Crate", 2), new CultMath.int2(1, 1)), "The smoke station took no crate.");
// An item already in the zone when the renderer loads it: drawn from the load, not only from the add.
var early = zone.Release(Make("Smoke Spare", 3), new float2(5, 6), float2.zero);
// The renderer's side. Inactive while it is configured, so it runs no Awake or Start of the scene's own.
var rootObject = new GameObject("Smoke Zone Root");
var rendererObject = new GameObject("Smoke Zone Renderer");
rendererObject.SetActive(false);
var renderer = rendererObject.AddComponent<ZoneRenderer>();
renderer.ZoneRoot = rootObject.transform;
foreach (var (name, pickup) in wired)
typeof(ZoneRenderer).GetField(name).SetValue(renderer, pickup);
renderer.ItemManager = items;
renderer.SectorBrushes = new GameObject("Smoke Brushes").transform;
renderer.AmbientLight = Aetheria.EditorTools.AmbientEdgeVerify.NewAmbientLight();
renderer.SlimeGravityCamera = new GameObject("Smoke Gravity Camera").AddComponent<Camera>();
var slimeObject = new GameObject("Smoke Slime");
slimeObject.SetActive(false); // the real Slime needs its compute shader; LoadZone only sets its radius
renderer.SlimeRenderer = slimeObject.AddComponent<Slime>();
renderer.LoadZone(zone);
yield return null;
ItemPickup[] Pickups() => rootObject.GetComponentsInChildren<ItemPickup>(true).Where(p => p != null).ToArray();
void At(ItemPickup pickup, FloatingItem floating, string what)
{
var lead = ActionGameManager.Clock.Lead;
var at = DrawAhead.Position(floating.Body, lead);
var want = new Vector3(at.x, DrawAhead.FloaterHeight(zone, settings, at, lead), at.y);
Require(Vector3.Distance(pickup.transform.position, want) < 1e-3f,
$"{what}: the pickup is at {pickup.transform.position}, the body at {want}.");
}
Require(Pickups().Length == 1, $"load: {Pickups().Length} pickups for one existing floating item.");
At(Pickups()[0], early, "load");
// Release adds exactly one pickup, at the body's position, bound to its item.
var ore = new SimpleCommodity { Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<SimpleCommodityData>("Smoke Ore")), Quantity = 7 };
var released = zone.Release(ore, new float2(3, 4), new float2(10, 0));
yield return null;
Require(Pickups().Length == 2, $"release: {Pickups().Length} pickups for two floating items.");
var drawn = Pickups().Single(p => p.Item == ore);
At(drawn, released, "release");
// Stepping the zone moves the sim body; the pickup follows it on its next update, with nothing of its own.
var before = drawn.transform.position;
zone.Update(.5f);
yield return null;
Require(released.Body.Position.x > 3.5f, "the sim body did not drift.");
At(drawn, released, "step");
Require(drawn.transform.position != before, "the pickup did not move with the body.");
// A held item keeps its label lit, so a pull is read as it happens. The label is let go dark first (nothing views
// it), then the zone holds the item through its own TryHold and the label must come up.
var earlyPickup = Pickups().Single(p => p.Item == early.Item);
earlyPickup.LabelPersistDuration = 1;
earlyPickup.LabelFadeDuration = .2f;
// Game time, not frames: batch frames can be far shorter than a game second, so a frame count can run out before the fade.
var labelUntil = Time.time + earlyPickup.LabelPersistDuration + earlyPickup.LabelFadeDuration + 1f;
while (Time.time < labelUntil && earlyPickup.ScanLabel.color.a > .05f) yield return null;
Require(earlyPickup.ScanLabel.color.a <= .05f, "label: an unviewed, unheld label did not go dark.");
Require(zone.TryHold(taker, early.Id), "label: the zone refused to hold the item.");
labelUntil = Time.time + earlyPickup.LabelPersistDuration + earlyPickup.LabelFadeDuration + 1f;
while (Time.time < labelUntil && earlyPickup.ScanLabel.color.a < .95f) yield return null;
Require(earlyPickup.ScanLabel.color.a >= .95f, "label: a held item's label is not lit.");
// The test scene's stand-in sim and tendril ride the zone's own held-pose curve: its pose at each point of a grab
// is where the zone puts a held item at the same progress.
var (extend, envelop, pull) = (1.5f, .75f, 1.5f);
var holderAt = new CultMath.float3(taker.Position.x, 0f, taker.Position.z);
var claimedAt = new CultMath.float3(early.HeldFrom.x, 0f, early.HeldFrom.y);
foreach (var elapsed in new[] { 0f, extend + envelop - .01f, extend + envelop + .3f, extend + envelop + .75f, extend + envelop + pull })
{
zone.SetHeldProgress(early.Id, Mathf.Clamp01((elapsed - extend - envelop) / pull)); // the pull starts after Extend and Envelop
zone.Update(.01f);
var want = FieldTester.PulledPosition(claimedAt, holderAt, elapsed, extend, envelop, pull);
Require(Mathf.Abs(early.Body.Position.x - want.x) < 1e-3f && Mathf.Abs(early.Body.Position.y - want.z) < 1e-3f,
$"stand-in pose at {elapsed}s is {want}, the zone holds the item at {early.Body.Position}.");
}
zone.Free(early.Id);
// Pickup destroys exactly the picked-up item's pickup.
Require(zone.TryPickUp(taker, released.Id), "the station refused a one-cell stack.");
yield return null;
yield return null;
Require(drawn == null, "pickup: the pickup is still there.");
Require(Pickups().Length == 1 && Pickups()[0].Item == early.Item, "pickup: the wrong pickup went.");
// Expiry destroys the pickup of an item nobody took.
zone.Update(3600f); // far past any lifetime
yield return null;
yield return null;
Require(zone.FloatingItems.Count == 0, "expiry: the item did not expire.");
Require(Pickups().Length == 0, $"expiry: {Pickups().Length} pickups left.");
// A later release is drawn again, and clearing the renderer takes what is left.
zone.Release(Make("Smoke Spare", 4), new float2(1, 1), float2.zero);
yield return null;
Require(Pickups().Length == 1, "re-release: not drawn.");
renderer.ClearZone();
yield return null;
yield return null;
Require(Pickups().Length == 0, "clear: pickups left after ClearZone.");
Debug.Log("FLOATING_ITEMS_SMOKE ok");
}
// What ARPG.unity's ZoneRenderer names in each pickup field, read from the saved scene before the play session (a
// scene cannot be opened inside one) and carried across the domain reload as the prefabs' asset paths.
private static string ReadWiring()
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Additive);
try
{
var found = UnityEngine.Object.FindObjectsByType<ZoneRenderer>(FindObjectsInactive.Include, FindObjectsSortMode.None)
.Where(r => r.gameObject.scene == scene).ToArray();
Require(found.Length == 1, $"ARPG.unity has {found.Length} ZoneRenderers.");
var wired = found[0];
return string.Join("|", new[]
{
("SimpleCommodityPickup", wired.SimpleCommodityPickup), ("CompoundCommodityPickup", wired.CompoundCommodityPickup),
("GearPickup", wired.GearPickup), ("WeaponPickup", wired.WeaponPickup)
}.Select(f => f.Item1 + "=" + (f.Item2 == null ? "" : AssetDatabase.GetAssetPath(f.Item2))));
}
finally { EditorSceneManager.CloseScene(scene, true); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 67544a932f794a2458741c731ef04d11

View file

@ -0,0 +1,302 @@
using System;
using System.IO;
using GameCult.Caching;
using UnityEditor;
using UnityEngine;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for flow-shader-parity (campaign aetheria-fauna, cut fauna-flow-field): the HLSL globalFlow and
/// slopeFlow of Assets/Shaders/Volumetric.cginc give the values of FlowField (ServerShared) for the same position,
/// scroll, settings and gradient. It drives the real lowering: a Zone is stepped, VolumeSampling.LowerFlow sets the
/// shader globals from the zone's Settings.Flow and FlowScroll, FlowParity.compute reads those globals, and the
/// results are compared with FlowField. It also checks that Settings.asset carries the authored flow under
/// PlanetSettings and that the shader got the zone's scroll (speed times zone time).
///
/// Dispatches a compute kernel, so it needs a graphics device: run WITHOUT -nographics (as ShieldPanelCut3Verify).
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.FlowFieldParityVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class FlowFieldParityVerify
{
const string Tag = "[FlowFieldParityVerify]";
// Measured disagreement between the HLSL and the C# on this tree (float32 on both sides, positions to 10000,
// scrolls to 100, through the keyword-gated flow()): max 2.9e-5 of amplitude (the "max error" line this run
// prints). The tolerance is 5x that noise, so constant errors of 0.05% (y factor .501, swirl or amplitude
// x1.0005: 4e-4 to 8e-4) fail; a 0.01% error is at the noise floor and unresolvable.
const float RelativeTolerance = 1.5e-4f;
static float _maxError;
static bool _ok = true;
static void OnLog(string message, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && !message.StartsWith(Tag))
Fail("logged-error", message.Split('\n')[0]);
}
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
// The flow's error lines (a shader keyword that does not exist, a missing property) fail the check.
Application.logMessageReceived += OnLog;
var work = Path.Combine(Path.GetTempPath(), "flow-parity-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(work);
try
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
var compute = AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/Shaders/Compute/FlowParity.compute")
?? throw new InvalidOperationException("No FlowParity.compute.");
CheckAuthoredFlow(settings.PlanetSettings.Flow);
// The authored flow (global term only: its slope amplitudes are authored zero), then a flow with every
// term live and a scroll speed that reaches scrolls up to 100.
var authored = settings.PlanetSettings.Flow;
CheckParity("authored", settings, work, compute, authored, new[] { 0.0, 3.1, 40.0, 100.0 });
var wide = new FlowSettings
{
GlobalScale = authored.GlobalScale, GlobalAmplitude = authored.GlobalAmplitude, Period = authored.Period,
GlobalScrollSpeed = 1f, SlopeAmplitude = 3f, SwirlAmplitude = 5f
};
CheckParity("wide", settings, work, compute, wide, new[] { 0.0, 1.0, 17.0, 60.0, 100.0 });
CheckNoiseClock(compute);
Debug.Log($"{Tag} max error {_maxError:G4} of amplitude (tolerance {RelativeTolerance:G4})");
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
Application.logMessageReceived -= OnLog;
try { Directory.Delete(work, true); } catch { }
}
EditorApplication.Exit(_ok ? 0 : 1);
}
// Settings.asset carries the authored flow under PlanetSettings (it moved from DefaultEnvironment unchanged).
static void CheckAuthoredFlow(FlowSettings flow)
{
if (flow == null) { Fail("authored-flow", "PlanetSettings.Flow is null"); return; }
if (flow.GlobalScale != 512f || flow.GlobalAmplitude != 15f || flow.GlobalScrollSpeed != .025f ||
flow.Period != 8f || flow.SlopeAmplitude != 0f || flow.SwirlAmplitude != 0f)
Fail("authored-flow", $"PlanetSettings.Flow is {flow.GlobalScale}/{flow.GlobalAmplitude}/{flow.GlobalScrollSpeed}/" +
$"{flow.Period}/{flow.SlopeAmplitude}/{flow.SwirlAmplitude}, authored 512/15/0.025/8/0/0");
}
internal static Zone BuildZone(GameSettings settings, string work, FlowSettings flow, double time = 0)
{
var cache = AetheriaStores.Open(Path.Combine(work, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), settings.GameplaySettings, _ => { });
return new Zone(items, new PlanetSettings { Flow = flow }, new ZonePack { Time = time }, new GalaxyZone { Name = "Parity", Owner = null }, null);
}
static void CheckParity(string label, GameSettings settings, string work, ComputeShader compute, FlowSettings flow,
double[] zoneTimes)
{
var zone = BuildZone(settings, work, flow);
var kernel = compute.FindKernel("Evaluate");
var rng = new System.Random(label.Length * 7919);
const int positionCount = 256, gradientCount = 64;
const int count = positionCount;
var positions = new Vector3[count];
for (var i = 0; i < positionCount; i++)
positions[i] = new Vector3((float) (rng.NextDouble() * 20000 - 10000), (float) (rng.NextDouble() * 200 - 100),
(float) (rng.NextDouble() * 20000 - 10000));
// Gradients of any direction and magnitude, plus one zero gradient.
var gradients = new Vector2[count];
for (var i = 1; i < gradientCount; i++)
{
var angle = rng.NextDouble() * Math.PI * 2;
var magnitude = (float) Math.Exp(rng.NextDouble() * 8 - 4);
gradients[i] = new Vector2((float) Math.Cos(angle) * magnitude, (float) Math.Sin(angle) * magnitude);
}
gradients[0] = Vector2.zero;
var positionBuffer = new ComputeBuffer(count, 12);
var gradientBuffer = new ComputeBuffer(count, 8);
var globalBuffer = new ComputeBuffer(count, 12);
var slopeBuffer = new ComputeBuffer(count, 12);
var gatedBuffer = new ComputeBuffer(count, 12);
ComputeBuffer noiseBuffer = null;
// flow() reads the nebula's gravity height under FLOW_SLOPE. A ramp rising along the texture's x gives every
// position inside the grid the gradient direction (1, 0), so the slope term is live where a flat height
// would zero it (and the FLOW_SLOPE keyword and its pragma would not matter).
const int rampSize = 64;
var height = new Texture2D(rampSize, rampSize, TextureFormat.RFloat, false)
{ filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp };
var ramp = new float[rampSize * rampSize];
for (var i = 0; i < ramp.Length; i++) ramp[i] = (i % rampSize) / (float) (rampSize - 1);
height.SetPixelData(ramp, 0);
height.Apply();
var rampGradient = new CultMath.float2(1f, 0f);
try
{
positionBuffer.SetData(positions);
gradientBuffer.SetData(gradients);
compute.SetBuffer(kernel, "positions", positionBuffer);
compute.SetBuffer(kernel, "gradients", gradientBuffer);
compute.SetBuffer(kernel, "globalOut", globalBuffer);
compute.SetBuffer(kernel, "slopeOut", slopeBuffer);
compute.SetBuffer(kernel, "gatedOut", gatedBuffer);
compute.SetTexture(kernel, "_NebulaSurfaceHeight", height);
compute.SetVector("_NebulaSurfaceHeight_TexelSize", new Vector4(1f / rampSize, 1f / rampSize, rampSize, rampSize));
// The grid spans 40000: every sampled position (|xz| to 10000) is inside the ramp's uv range.
Shader.SetGlobalVector("_GridTransform", new Vector4(0f, 0f, 40000f, 0f));
noiseBuffer = new ComputeBuffer(count, 4);
compute.SetBuffer(kernel, "noiseOut", noiseBuffer);
compute.SetInt("count", count);
var elapsed = 0.0;
foreach (var target in zoneTimes)
{
// Step the zone to the target by an awkward step; the sum is the zone's time.
while (elapsed < target - 1e-9)
{
var dt = (float) Math.Min(0.37, target - elapsed);
zone.Update(dt);
elapsed += dt;
}
VolumeSampling.LowerFlow(zone.Settings.Flow, zone.ExactTime);
// The shader got the zone's scroll and cycle: the same zone time Zone.Flow evaluates at.
var zoneScroll = zone.FlowScroll;
var lowered = Shader.GetGlobalVector("_FlowScroll");
if (Math.Abs(lowered.x - zoneScroll.x) > 1e-6 || Math.Abs(lowered.y - zoneScroll.y) > 1e-6)
Fail($"{label}-lowered-scroll", $"at zone time {elapsed:F3} the shader got _FlowScroll ({lowered.x}, {lowered.y}), the zone's is ({zoneScroll.x}, {zoneScroll.y})");
if (Math.Abs(Shader.GetGlobalFloat("_FlowCycle") - zone.CyclePhase(flow.Period)) > 1e-6)
Fail($"{label}-lowered-cycle", $"at zone time {elapsed:F3} the shader got _FlowCycle {Shader.GetGlobalFloat("_FlowCycle")}, the zone's phase is {zone.CyclePhase(flow.Period)}");
if (Shader.GetGlobalFloat("_FlowScale") != flow.GlobalScale || Shader.GetGlobalFloat("_FlowAmplitude") != flow.GlobalAmplitude ||
Shader.GetGlobalFloat("_FlowSlopeAmplitude") != flow.SlopeAmplitude ||
Shader.GetGlobalFloat("_FlowSwirlAmplitude") != flow.SwirlAmplitude || Shader.GetGlobalFloat("_FlowPeriod") != flow.Period)
Fail($"{label}-lowered-settings", "a flow uniform does not equal the zone's FlowSettings");
compute.Dispatch(kernel, (count + 63) / 64, 1, 1);
var globalOut = new Vector3[count];
var slopeOut = new Vector3[count];
var gatedOut = new Vector3[count];
globalBuffer.GetData(globalOut);
slopeBuffer.GetData(slopeOut);
gatedBuffer.GetData(gatedOut);
var at = $"{label} zone time {elapsed:F2} scroll {zoneScroll.x:F4}";
for (var i = 0; i < positionCount; i++)
{
var p = positions[i];
var expected = FlowField.Global(flow, new CultMath.float3(p.x, p.y, p.z), zoneScroll);
Compare($"{label}-global", at, i, new Vector3(expected.x, expected.y, expected.z), globalOut[i], flow.GlobalAmplitude);
}
// flow() is the keyword-gated function the nebula and stardust call: the global term plus, under
// FLOW_SLOPE, the slope term of the ramp's gradient. A flow that is live must not read zero.
var live = 0;
var gatedScale = Math.Max(Math.Abs(flow.GlobalAmplitude), Math.Max(Math.Abs(flow.SlopeAmplitude), Math.Abs(flow.SwirlAmplitude)));
for (var i = 0; i < positionCount; i++)
{
var p = positions[i];
var expected = FlowField.At(flow, new CultMath.float3(p.x, p.y, p.z), zoneScroll, rampGradient);
var e = new Vector3(expected.x, expected.y, expected.z);
if (e.magnitude > .1f * gatedScale) live++;
Compare($"{label}-flow-keywords", at, i, e, gatedOut[i], gatedScale);
}
if (gatedScale != 0f && live < positionCount / 4)
Fail($"{label}-flow-keywords", $"{at}: only {live} of {positionCount} zone flows are live; the check is vacuous");
var slopeScale = Math.Max(Math.Abs(flow.SlopeAmplitude), Math.Abs(flow.SwirlAmplitude));
for (var i = 0; i < gradientCount; i++)
{
var g = gradients[i];
var expected = FlowField.Slope(flow, new CultMath.float2(g.x, g.y));
Compare($"{label}-slope", at, i, new Vector3(expected.x, expected.y, expected.z), slopeOut[i], slopeScale);
}
}
}
finally
{
positionBuffer.Release(); gradientBuffer.Release(); globalBuffer.Release(); slopeBuffer.Release(); gatedBuffer.Release(); noiseBuffer?.Release(); UnityEngine.Object.DestroyImmediate(height);
}
}
// The nebula noise the flow advects evolves on the flow clock VolumeSampling lowers as _NebulaNoiseTime, never on
// _Time: with the speed non-zero, the noise changes when _NebulaNoiseTime does and not otherwise (a frame clock
// would not follow the global set here).
static void CheckNoiseClock(ComputeShader compute)
{
const int count = 64;
var kernel = compute.FindKernel("Evaluate");
var rng = new System.Random(4217);
var positions = new Vector3[count];
for (var i = 0; i < count; i++)
positions[i] = new Vector3((float) (rng.NextDouble() * 4000 - 2000), (float) (rng.NextDouble() * 100 - 50), (float) (rng.NextDouble() * 4000 - 2000));
var buffers = new[] { new ComputeBuffer(count, 12), new ComputeBuffer(count, 8), new ComputeBuffer(count, 12), new ComputeBuffer(count, 12), new ComputeBuffer(count, 12), new ComputeBuffer(count, 4) };
var height = new Texture2D(1, 1, TextureFormat.RFloat, false);
try
{
buffers[0].SetData(positions);
buffers[1].SetData(new Vector2[count]);
compute.SetBuffer(kernel, "positions", buffers[0]);
compute.SetBuffer(kernel, "gradients", buffers[1]);
compute.SetBuffer(kernel, "globalOut", buffers[2]);
compute.SetBuffer(kernel, "slopeOut", buffers[3]);
compute.SetBuffer(kernel, "gatedOut", buffers[4]);
compute.SetBuffer(kernel, "noiseOut", buffers[5]);
compute.SetTexture(kernel, "_NebulaSurfaceHeight", height);
compute.SetInt("count", count);
Shader.SetGlobalFloat("_NebulaNoiseSpeed", 1f);
float[] Noise(float noiseTime)
{
Shader.SetGlobalFloat("_NebulaNoiseTime", noiseTime);
compute.Dispatch(kernel, 1, 1, 1);
var result = new float[count];
buffers[5].GetData(result);
return result;
}
var a = Noise(0f);
var b = Noise(3f);
var again = Noise(3f);
int moved = 0, repeated = 0;
for (var i = 0; i < count; i++)
{
if (Math.Abs(a[i] - b[i]) > 1e-4f) moved++;
if (b[i] == again[i]) repeated++;
}
if (moved < count / 2) Fail("nebula-noise-clock", $"only {moved} of {count} noise samples follow _NebulaNoiseTime");
if (repeated != count) Fail("nebula-noise-clock", $"{count - repeated} of {count} noise samples changed with _NebulaNoiseTime held");
}
finally
{
foreach (var buffer in buffers) buffer.Release();
UnityEngine.Object.DestroyImmediate(height);
}
}
// Error is measured against the term's amplitude; a term with no amplitude must be exactly zero and never NaN.
static void Compare(string check, string at, int index, Vector3 expected, Vector3 actual, float amplitude)
{
var error = (expected - actual).magnitude;
if (float.IsNaN(error)) { Fail(check, $"{at} sample {index}: NaN (expected {expected}, shader {actual})"); return; }
if (amplitude != 0f) _maxError = Math.Max(_maxError, error / Math.Abs(amplitude));
var tolerance = RelativeTolerance * Math.Abs(amplitude);
if (error > tolerance)
Fail(check, $"{at} sample {index}: expected {expected}, shader {actual}, error {error:G4} > {tolerance:G4}");
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8fae18f5f32f10f43ba892a097f18caa

View file

@ -0,0 +1,392 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for the flow as the scene runs it (campaign aetheria-fauna, cut fauna-flow-field; target
/// invariants flow-one-owner and flow-shader-parity). FlowFieldParityVerify proves the HLSL against FlowField with
/// no scene loaded; this opens ARPG.unity, lets VolumeSampling and Stardust initialise as the game does, drives
/// their own Start and Update with a zone attached, and asserts what the presenters did:
/// - nothing threw and nothing logged an error (a type that cannot initialise in a scene, as VolumeSampling once
/// could when it created its keywords in a static field initializer, throws on its first use);
/// - FLOW_GLOBAL and FLOW_SLOPE are enabled, _FlowAmplitude is the zone's, and the nebula noise clock is the zone's;
/// - the stardust particle buffer changes with the flow and freezes when the zone pauses;
/// - CloudShader pass 0 carries the FLOW_* keywords.
/// The scene is opened before any Aetheria type is touched: run this method alone in its own Unity session, never
/// after FlowFieldParityVerify (which would initialise VolumeSampling outside a MonoBehaviour constructor).
/// Dispatches compute and renders, so it needs a graphics device: run WITHOUT -nographics.
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.FlowFieldSceneVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class FlowFieldSceneVerify
{
const string Tag = "[FlowFieldSceneVerify]";
static bool _ok = true;
static void OnLog(string message, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && !message.StartsWith(Tag))
Fail("logged-error", message.Split('\n')[0]);
}
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
Application.logMessageReceived += OnLog;
try
{
// Before anything else touches the project's types: the scene constructs its MonoBehaviours here.
EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single);
Check();
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
Application.logMessageReceived -= OnLog;
}
EditorApplication.Exit(_ok ? 0 : 1);
}
static void Check()
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
var agm = UnityEngine.Object.FindObjectsByType<ActionGameManager>(FindObjectsInactive.Include, FindObjectsSortMode.None).FirstOrDefault();
var volume = UnityEngine.Object.FindObjectsByType<VolumeSampling>(FindObjectsInactive.Include, FindObjectsSortMode.None).FirstOrDefault();
var dust = UnityEngine.Object.FindObjectsByType<Stardust>(FindObjectsInactive.Include, FindObjectsSortMode.None).FirstOrDefault();
if (agm == null || volume == null || dust == null)
{
Fail("scene-objects", $"ARPG.unity has ActionGameManager={agm != null}, VolumeSampling={volume != null}, Stardust={dust != null}");
return;
}
// Every flow term live, so FLOW_SLOPE is on; and the same flow with every amplitude zero.
var on = new FlowSettings
{
GlobalScale = 512f, GlobalAmplitude = 15f, GlobalScrollSpeed = .025f, Period = 8f, SlopeAmplitude = 3f, SwirlAmplitude = 5f
};
var off = new FlowSettings { GlobalScale = on.GlobalScale, GlobalScrollSpeed = on.GlobalScrollSpeed, Period = on.Period };
var work = Path.Combine(Path.GetTempPath(), "flow-scene-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(work);
try
{
var zone = FlowFieldParityVerify.BuildZone(settings, work, on, 86400.0 * 3 + 12.3);
typeof(ActionGameManager).GetProperty("Instance").GetSetMethod(true).Invoke(null, new object[] { agm });
typeof(ActionGameManager).GetProperty("Zone").GetSetMethod(true).Invoke(agm, new object[] { zone });
if (agm.Settings == null) agm.Settings = settings;
Call(volume, "Start");
Call(volume, "Update");
if (!Shader.IsKeywordEnabled("FLOW_GLOBAL")) Fail("scene-keywords", "FLOW_GLOBAL is not enabled after VolumeSampling.Update");
if (!Shader.IsKeywordEnabled("FLOW_SLOPE")) Fail("scene-keywords", "FLOW_SLOPE is not enabled after VolumeSampling.Update");
if (Shader.GetGlobalFloat("_FlowAmplitude") != on.GlobalAmplitude)
Fail("scene-amplitude", $"_FlowAmplitude is {Shader.GetGlobalFloat("_FlowAmplitude")}, the zone's flow has {on.GlobalAmplitude}");
var scroll = Shader.GetGlobalVector("_FlowScroll");
if (scroll.x != zone.FlowScroll.x || scroll.y != zone.FlowScroll.y)
Fail("scene-scroll", $"_FlowScroll ({scroll.x}, {scroll.y}) is not the zone's ({zone.FlowScroll.x}, {zone.FlowScroll.y})");
var noiseTime = Shader.GetGlobalFloat("_NebulaNoiseTime");
if (noiseTime != (float) zone.ExactTime)
Fail("scene-noise-clock", $"_NebulaNoiseTime is {noiseTime}, the zone's time is {(float) zone.ExactTime}");
CheckCloudKeywords();
// Stardust follows the flow through its own dispatch: the particle buffer read back each frame.
Call(dust, "Start");
var bufferField = typeof(Stardust).GetField("_particlesBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
float[] Frame()
{
Call(dust, "Update");
var buffer = (ComputeBuffer) bufferField.GetValue(dust);
var data = new float[buffer.count * 7];
buffer.GetData(data);
return data;
}
var flowing = Frame();
VolumeSampling.LowerFlow(off, VolumeSampling.FlowClock);
var still = Frame();
if (Differing(flowing, still) == 0) Fail("scene-stardust", "the particle buffer is the same with the zone's flow and with no flow");
// A paused zone freezes the particles and the nebula noise clock; a running one moves both.
Call(volume, "Update");
zone.Update(0f);
Call(volume, "Update");
if (Differing(flowing, Frame()) != 0) Fail("scene-stardust-pause", "the particle buffer moved while the zone was paused");
if (Shader.GetGlobalFloat("_NebulaNoiseTime") != noiseTime) Fail("scene-noise-clock", "_NebulaNoiseTime moved while the zone was paused");
zone.Update(.05f);
Call(volume, "Update");
if (Differing(flowing, Frame()) == 0) Fail("scene-stardust-run", "the particle buffer did not move while the zone ran");
if (Shader.GetGlobalFloat("_NebulaNoiseTime") == noiseTime) Fail("scene-noise-clock", "_NebulaNoiseTime did not move while the zone ran");
CheckStardustUncullable(dust, bufferField);
CheckStardustUnderFog(dust, bufferField);
}
finally
{
try { Directory.Delete(work, true); } catch { }
}
}
// The event Stardust itself attaches its draw at, read from the class so the verifier cannot agree with a copy of it.
static CameraEvent DrawEvent() =>
(CameraEvent) typeof(Stardust).GetField("DrawEvent", BindingFlags.NonPublic | BindingFlags.Static).GetRawConstantValue();
// The dust is a command buffer on the target camera, which no culling sees: with every particle 10000 below the
// camera (far past any box a hand could inflate round it) a render still shows dust, and shows none when the
// same particles have no size.
static void CheckStardustUncullable(Stardust dust, FieldInfo bufferField)
{
var camera = dust.TargetCamera;
if (camera == null) { Fail("scene-stardust-uncullable", "Stardust has no TargetCamera"); return; }
var drawEvent = DrawEvent();
var attached = camera.GetCommandBuffers(drawEvent).Count(buffer => buffer.name == "Stardust");
if (attached != 1) Fail("scene-stardust-uncullable", $"{attached} Stardust command buffers at {drawEvent} on the target camera, expected 1");
foreach (var other in Enum.GetValues(typeof(CameraEvent)).Cast<CameraEvent>().Where(other => other != drawEvent))
{
var stray = camera.GetCommandBuffers(other).Count(buffer => buffer.name == "Stardust");
if (stray != 0) Fail("scene-stardust-uncullable", $"{stray} Stardust command buffers at {other}, expected 0");
}
var particles = (ComputeBuffer) bufferField.GetValue(dust);
float[] Layout(float size, Vector3 centre, float below) => DustLayout(particles.count, size, centre, below);
var transform = camera.transform;
var (position, rotation) = (transform.position, transform.rotation);
var (far, flags, background, mask, target) = (camera.farClipPlane, camera.clearFlags, camera.backgroundColor, camera.cullingMask, camera.targetTexture);
var texture = RenderTexture.GetTemporary(64, 64, 24, RenderTextureFormat.ARGB32);
var readback = new Texture2D(64, 64, TextureFormat.RGBA32, false);
var previous = RenderTexture.active;
// Image effects on the camera would write their own frame over the dust; only the dust draw is under test.
var effects = camera.GetComponents<MonoBehaviour>().Where(behaviour => behaviour.enabled).ToArray();
Color32[] Render(float size, Vector3 centre, float below)
{
Call(dust, "Update"); // on a bounded draw this queues the draw for the camera; here it dispatches the compute
particles.SetData(Layout(size, centre, below));
camera.Render();
RenderTexture.active = texture;
readback.ReadPixels(new Rect(0, 0, 64, 64), 0, 0);
readback.Apply();
return readback.GetPixels32();
}
try
{
foreach (var effect in effects) effect.enabled = false;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.black;
camera.cullingMask = 1;
camera.targetTexture = texture;
// control: the camera where the scene put it, dust 100 below, inside any box a hand-set extent would give
transform.SetPositionAndRotation(position, Quaternion.Euler(90f, 0f, 0f));
camera.farClipPlane = 1000f;
var nearWith = Render(5f, position, 100f); var nearWithout = Render(0f, position, 100f);
var nearDiff = 0; for (var i = 0; i < nearWith.Length; i++) if (!nearWith[i].Equals(nearWithout[i])) nearDiff++;
Debug.Log($"{Tag} stardust near-control differing pixels={nearDiff}");
if (nearDiff == 0) Fail("scene-stardust-uncullable", "control: dust 100 below the camera drew no pixels");
transform.SetPositionAndRotation(new Vector3(0f, -40000f, 0f), Quaternion.Euler(90f, 0f, 0f));
camera.farClipPlane = 30000f;
var withDust = Render(400f, transform.position, 10000f); // the material scales a quad by distance^.33, so at this range it needs this size to cover pixels
var without = Render(0f, transform.position, 10000f);
var differing = 0;
for (var i = 0; i < withDust.Length; i++)
if (!withDust[i].Equals(without[i])) differing++;
if (differing == 0) Fail("scene-stardust-uncullable", "the dust 10000 below the camera drew no pixels");
}
finally
{
RenderTexture.active = previous;
foreach (var effect in effects) effect.enabled = true;
camera.targetTexture = target;
camera.cullingMask = mask;
camera.backgroundColor = background;
camera.clearFlags = flags;
camera.farClipPlane = far;
transform.SetPositionAndRotation(position, rotation);
RenderTexture.ReleaseTemporary(texture);
UnityEngine.Object.DestroyImmediate(readback);
}
}
// The nebula is an [ImageEffectOpaque] that fogs the whole ray to a depth the dust never writes (B49): dust drawn
// before it is attenuated by the fog, dust drawn after it sits on top at full strength. The dust's contribution to a
// pixel (render with dust minus render without) is read with the cloud renderer off and on, in an HDR target.
static void CheckStardustUnderFog(Stardust dust, FieldInfo bufferField)
{
const int Size = 128;
var camera = dust.TargetCamera;
var cloud = camera == null ? null : camera.GetComponent<VolumeCloudRenderer>();
if (cloud == null) { Fail("scene-stardust-under-fog", "the target camera has no VolumeCloudRenderer"); return; }
var particles = (ComputeBuffer) bufferField.GetValue(dust);
var transform = camera.transform;
var (position, rotation) = (transform.position, transform.rotation);
var (far, flags, background, mask, target, hdr) = (camera.farClipPlane, camera.clearFlags, camera.backgroundColor, camera.cullingMask, camera.targetTexture, camera.allowHDR);
var texture = RenderTexture.GetTemporary(Size, Size, 24, RenderTextureFormat.ARGBHalf);
var readback = new Texture2D(Size, Size, TextureFormat.RGBAHalf, false);
var previous = RenderTexture.active;
var effects = camera.GetComponents<MonoBehaviour>().Where(behaviour => behaviour.enabled).ToArray();
var fields = new System.Collections.Generic.List<Texture2D>();
GameObject floor = null;
float[] Render(bool fog, float size)
{
cloud.enabled = fog;
for (var frame = 0; frame < 2; frame++) // the cloud's first frame forces ULTRA and fills its history; the second is the settled one
{
Call(dust, "Update");
particles.SetData(DustLayout(particles.count, size, position, 100f));
camera.Render();
}
RenderTexture.active = texture;
readback.ReadPixels(new Rect(0, 0, Size, Size), 0, 0);
readback.Apply();
return readback.GetPixels().Select(pixel => pixel.r * .2126f + pixel.g * .7152f + pixel.b * .0722f).ToArray();
}
try
{
foreach (var effect in effects) effect.enabled = false;
camera.allowHDR = true;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.black;
camera.cullingMask = 1;
camera.targetTexture = texture;
camera.farClipPlane = 1000f;
transform.SetPositionAndRotation(position, Quaternion.Euler(90f, 0f, 0f));
// The fog only measures a partial density where depth is written: a pixel with no depth is fogged whole (CloudShader sets
// density 1 past the far plane). A floor under the dust gives the march a finite ray.
floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
floor.transform.position = position + Vector3.down * 200f;
floor.transform.localScale = Vector3.one * 100f;
UnityEngine.Object.DestroyImmediate(floor.GetComponent<Collider>());
// The scene's own nebula fields are textures the game renders; here a uniform fill of white fog stands in for them.
foreach (var (name, format) in new[] { ("_NebulaSurfaceHeight", TextureFormat.RFloat), ("_NebulaPatchHeight", TextureFormat.RHalf), ("_NebulaPatch", TextureFormat.RHalf) })
Shader.SetGlobalTexture(name, Uniform(format, Color.black, fields));
Shader.SetGlobalTexture("_NebulaTint", Uniform(TextureFormat.RGBA32, Color.white, fields));
Shader.DisableKeyword("NOISE_SLOPE");
Shader.SetGlobalFloat("_NebulaFillDensity", .01f);
Shader.SetGlobalFloat("_NebulaFillDistance", 120f);
Shader.SetGlobalFloat("_NebulaFillExponent", 0f);
Shader.SetGlobalFloat("_NebulaFillOffset", 0f);
Shader.SetGlobalFloat("_NebulaPatchDensity", 0f);
Shader.SetGlobalFloat("_NebulaLuminance", .01f); // a fog dimmer than the dust: dust drawn over it would otherwise read as a negative contribution
Shader.SetGlobalFloat("_ExtinctionCoefficient", .25f); // with the fill density, about 40% of the light to the floor is fogged away
Shader.SetGlobalFloat("_SafetyDistance", -1e6f); // below every sample: only the uniform fill, none of the zone's noise
Shader.SetGlobalFloat("_TintLodExponent", 0f);
var clearBare = Render(false, 0f);
var clearDust = Render(false, 5f);
var fogBare = Render(true, 0f);
var fogDust = Render(true, 5f);
var fogShown = 0f;
var (clearSum, fogSum, drawn) = (0f, 0f, 0);
for (var i = 0; i < clearBare.Length; i++)
{
fogShown += Mathf.Abs(fogBare[i] - clearBare[i]) / clearBare.Length;
if (clearDust[i] == clearBare[i]) continue;
drawn++; clearSum += clearDust[i] - clearBare[i]; fogSum += fogDust[i] - fogBare[i];
}
var (clearMean, fogMean) = (drawn == 0 ? 0f : clearSum / drawn, drawn == 0 ? 0f : fogSum / drawn);
Debug.Log($"{Tag} stardust under fog: fog control mean |difference|={fogShown}, dust pixels={drawn}, dust contribution cloud off={clearMean}, cloud on={fogMean}, ratio={(clearMean == 0f ? 0f : fogMean / clearMean)}");
if (drawn == 0 || clearMean <= 0f) Fail("scene-stardust-under-fog", "control: the dust drew no pixels with the cloud renderer off");
else if (fogShown < 1e-3f) Fail("scene-stardust-under-fog", "control: the cloud renderer changed no pixels, so no fog is in view");
else if (fogMean > .9f * clearMean) Fail("scene-stardust-under-fog", "the dust is not attenuated by the fog in front of it: it was drawn after the nebula composites");
else if (fogMean < .1f * clearMean) Fail("scene-stardust-under-fog", "the dust is erased, not dimmed, by a partial fog");
}
finally
{
RenderTexture.active = previous;
foreach (var effect in effects) effect.enabled = true;
camera.allowHDR = hdr;
camera.targetTexture = target;
camera.cullingMask = mask;
camera.backgroundColor = background;
camera.clearFlags = flags;
camera.farClipPlane = far;
transform.SetPositionAndRotation(position, rotation);
RenderTexture.ReleaseTemporary(texture);
UnityEngine.Object.DestroyImmediate(readback);
foreach (var field in fields) UnityEngine.Object.DestroyImmediate(field);
if (floor != null) UnityEngine.Object.DestroyImmediate(floor);
}
}
static Texture2D Uniform(TextureFormat format, Color colour, System.Collections.Generic.List<Texture2D> owner)
{
var texture = new Texture2D(1, 1, format, false) { wrapMode = TextureWrapMode.Clamp };
texture.SetPixel(0, 0, colour);
texture.Apply();
owner.Add(texture);
return texture;
}
// A square patch of particles 4 apart, `below` under `centre`.
static float[] DustLayout(int count, float size, Vector3 centre, float below)
{
var side = Mathf.RoundToInt(Mathf.Sqrt(count));
var data = new float[count * 7];
for (var i = 0; i < count; i++)
{
data[i * 7 + 0] = centre.x + ((i % side) - side / 2f) * 4f;
data[i * 7 + 1] = centre.y - below;
data[i * 7 + 2] = centre.z + ((i / side) - side / 2f) * 4f;
data[i * 7 + 3] = data[i * 7 + 4] = data[i * 7 + 5] = 1f;
data[i * 7 + 6] = size;
}
return data;
}
// CloudShader's pass 0 compiles with the flow keywords (it must #include_with_pragmas the shared include).
static void CheckCloudKeywords()
{
var shader = AssetDatabase.LoadAssetAtPath<Shader>("Assets/Shaders/Raymarching/CloudShader.shader");
if (shader == null) { Fail("scene-cloud-keywords", "No CloudShader.shader."); return; }
var keywords = ShaderUtil.GetPassKeywords(shader, new PassIdentifier(0, 0), UnityEditor.Rendering.ShaderType.Fragment)
.Select(keyword => keyword.name).ToArray();
foreach (var name in new[] { "FLOW_GLOBAL", "FLOW_SLOPE" })
if (!keywords.Contains(name)) Fail("scene-cloud-keywords", $"CloudShader pass 0 does not carry {name}");
}
static int Differing(float[] a, float[] b)
{
var count = 0;
for (var i = 0; i < a.Length; i++)
if (Math.Abs(a[i] - b[i]) > 1e-4f) count++;
return count;
}
// The presenters' own Start and Update, as the game calls them; an exception is a failure that names the type.
static void Call(object target, string method)
{
var info = target.GetType().GetMethod(method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (info == null) { Fail("scene-presenter-exception", $"{target.GetType().Name}.{method} not found"); return; }
try { info.Invoke(target, null); }
catch (TargetInvocationException e)
{
Fail("scene-presenter-exception", $"{target.GetType().Name}.{method} threw {e.InnerException?.GetType().Name}");
}
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 25fbd79fca1de49498c3bebf9f63243b

View file

@ -0,0 +1,367 @@
using System;
using System.IO;
using System.Linq;
using GameCult.Caching;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using CultMath;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for campaign aetheria-gravity, cut grid-lowering: what the Gravity Field pass draws is the sim's
/// height. It builds a zone from Settings.asset's PlanetSettings with three bodies, runs the real lowering
/// (GravityLowering.Lower and CreateField), renders the field through an orthographic camera that culls layer 9 into
/// a float target, and compares every texel with -Zone.GetHeight at the texel centre's world position. It then checks
/// that the texture's gradient points where Zone.GetForce does, and that ARPG.unity and the body prefabs are wired
/// the way the cut leaves them (the gravity cameras cull layer 9 alone, nothing but the run-time field sits on it).
///
/// Renders, so it needs a graphics device: run WITHOUT -nographics (as FlowFieldParityVerify).
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.GravityFieldParityVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class GravityFieldParityVerify
{
const string Tag = "[GravityFieldParityVerify]";
const int Size = 256;
// Measured on this tree (the "max error" line this run prints): the largest |texel + GetHeight| over the windows of the three
// frames and windows is 0.0065 u, in the last frame's planetoid window (float32 on both sides, the GPU's log against the CPU's, the
// quad's interpolated world position). The tolerance is 4.6x that. A 0.1% error in the tail constant (.5 -> .501)
// moves the drawn height by 0.053 u where all three tails reach (the planetoid and zone windows), 1.8x the
// tolerance; a reference of zero moves it by about 150 u.
const float Tolerance = 0.03f;
// The worst angle between the texture's central difference and GetForce (B28: 1.0 degrees median zone, 2.9 worst).
const float GradientDegrees = 3f;
static float _maxError, _maxAngle;
static bool _ok = true;
static void OnLog(string message, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && !message.StartsWith(Tag))
Fail("logged-error", message.Split('\n')[0]);
}
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
Application.logMessageReceived += OnLog;
var work = Path.Combine(Path.GetTempPath(), "gravity-parity-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(work);
ComputeBuffer wells = null;
GameObject field = null;
try
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
var material = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Brushes/Gravity Field.mat")
?? throw new InvalidOperationException("No Gravity Field.mat.");
var zone = BuildZone(settings, work, out var orbits);
GravityLowering.Lower(zone, 0f, ref wells);
field = GravityLowering.CreateField(material);
// Three frames through the one buffer, as ZoneRenderer.Update runs it: the bodies as built, then two moves
// (an orbit's Position is what Zone.GetHeight reads). A lowering that mirrors an axis or stops refreshing
// the upload agrees with the sim in the first frame only where it is symmetric, and not after a move.
CheckFrame("built", zone, orbits);
orbits[1].Position = new float2(-420f, 560f);
orbits[2].Position = new float2(900f, -700f);
GravityLowering.Lower(zone, 0f, ref wells);
CheckFrame("moved", zone, orbits);
orbits[0].Position = new float2(210f, -95f);
orbits[2].Position = new float2(-1800f, 1300f);
GravityLowering.Lower(zone, 0f, ref wells);
CheckFrame("moved-again", zone, orbits);
Debug.Log($"{Tag} max error {_maxError:G4} u (tolerance {Tolerance:G4}); max gradient angle {_maxAngle:F2} degrees (limit {GradientDegrees:F0})");
CheckWiring(settings);
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
Application.logMessageReceived -= OnLog;
if (field != null) UnityEngine.Object.DestroyImmediate(field);
wells?.Release();
try { Directory.Delete(work, true); } catch { }
}
EditorApplication.Exit(_ok ? 0 : 1);
}
static float Core(Zone zone, float mass) => zone.Settings.RocheLimit.Evaluate(mass);
static Vector2 At(Orbit orbit) => new Vector2(orbit.Position.x, orbit.Position.y);
// Orbits 0-2 are the sun, the planet and the planetoid, each window centred where the body is now; orbit 3 is the
// body of no strength. The zone window holds all four.
static void CheckFrame(string frame, Zone zone, Orbit[] orbits)
{
CheckTexels(frame + "-planetoid", zone, At(orbits[2]), 4f * Core(zone, 29.2f));
CheckTexels(frame + "-sun", zone, At(orbits[0]), 4f * Core(zone, 14152f));
CheckTexels(frame + "-zone", zone, Vector2.zero, 1.05f * zone.Pack.Radius);
CheckGradient(zone, orbits.Select(At).ToArray());
}
// A sun (14152 at (-130, 85)), a planet (273.9 at (610, -240)), a planetoid (29.2 at (670, -270)) and a body of
// mass 0, whose well has no strength (a legal body; its curves give c = 0 and R = 0), at (1700, 300): parentless,
// fixed, off both axes and asymmetric, so the zone's wells sit where the verify says before any Update and a
// mirrored or swapped axis cannot agree with the sim.
internal static Zone BuildZone(GameSettings settings, string work, out Orbit[] orbits, float radius = 4182f)
{
var cache = AetheriaStores.Open(Path.Combine(work, "catalog.cc"), Path.Combine(work, "run.cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), settings.GameplaySettings, _ => { });
var positions = new[] { new Vector2(-130f, 85f), new Vector2(610f, -240f), new Vector2(670f, -270f), new Vector2(1700f, 300f) };
var masses = new[] { 14152f, 273.9f, 29.2f, 0f };
var keys = new CultRecordKey[positions.Length];
var pack = new ZonePack { Radius = radius };
for (var i = 0; i < positions.Length; i++)
{
var orbit = keys[i] = cache.Upsert(new OrbitData { FixedPosition = new float2(positions[i].x, positions[i].y) }).Key;
var body = cache.Upsert(new PlanetData
{ Name = "Body " + i, Orbit = new CultRecordRef<OrbitData>(orbit), Mass = masses[i] }).Key;
pack.Orbits.Add(new CultRecordRef<OrbitData>(orbit));
pack.Planets.Add(new CultRecordRef<BodyData>(body));
}
var zone = new Zone(items, settings.PlanetSettings, pack, new GalaxyZone { Name = "Gravity Parity", Owner = null }, null);
orbits = keys.Select(k => zone.Orbits[k]).ToArray();
return zone;
}
// Renders the field through a downward orthographic camera that culls layer 9 only, centred on `centre` with
// half-size `half`, and returns the depth of every texel with the world xz of the texel's centre, which is asked
// of the camera rather than assumed.
static void Render(Vector2 centre, float half, out float[] depth, out Vector2[] world)
{
var rt = new RenderTexture(Size, Size, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point };
var cameraObject = new GameObject("Gravity Parity Camera");
var read = new Texture2D(Size, Size, TextureFormat.RFloat, false);
var previous = RenderTexture.active;
try
{
var camera = cameraObject.AddComponent<Camera>();
camera.orthographic = true;
camera.orthographicSize = half;
camera.aspect = 1f;
camera.nearClipPlane = .3f;
camera.farClipPlane = 1000f;
camera.cullingMask = 1 << GravityLowering.FieldLayer;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.black;
camera.allowHDR = false;
camera.allowMSAA = false;
camera.targetTexture = rt;
cameraObject.transform.SetPositionAndRotation(new Vector3(centre.x, 100f, centre.y), Quaternion.Euler(90f, 0f, 0f));
camera.Render();
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, Size, Size), 0, 0);
read.Apply();
depth = read.GetPixelData<float>(0).ToArray();
world = new Vector2[Size * Size];
for (var y = 0; y < Size; y++)
for (var x = 0; x < Size; x++)
{
var p = camera.ViewportToWorldPoint(new Vector3((x + .5f) / Size, (y + .5f) / Size, 100f));
world[y * Size + x] = new Vector2(p.x, p.z);
}
}
finally
{
RenderTexture.active = previous;
UnityEngine.Object.DestroyImmediate(cameraObject);
UnityEngine.Object.DestroyImmediate(read);
rt.Release();
UnityEngine.Object.DestroyImmediate(rt);
}
}
static void CheckTexels(string window, Zone zone, Vector2 centre, float half)
{
Render(centre, half, out var depth, out var world);
var worst = 0f;
var live = 0;
for (var i = 0; i < depth.Length; i++)
{
var expected = -zone.GetHeight(new float2(world[i].x, world[i].y));
if (float.IsNaN(depth[i])) { Fail($"{window}-texels", $"texel {i}: NaN"); return; }
var error = Math.Abs(depth[i] - expected);
worst = Math.Max(worst, error);
if (Math.Abs(expected) > 1f) live++;
if (error > Tolerance)
{
Fail($"{window}-texels", $"texel {i} at ({world[i].x:F2}, {world[i].y:F2}): expected {expected:G6}, drawn {depth[i]:G6}, error {error:G4} > {Tolerance:G4}");
return;
}
}
_maxError = Math.Max(_maxError, worst);
// A window that draws nothing agrees with a zone that is flat: the check must be live.
if (live < depth.Length / 2) Fail($"{window}-texels", $"only {live} of {depth.Length} texels are deeper than 1 u; the check is vacuous");
Debug.Log($"{Tag} {window}: {depth.Length} texels, max error {worst:G4} u");
}
// The texture's central difference (over two 4 u texels, mid-zone) points where GetForce does: depth = -h, so its
// gradient is the force over the exaggeration. This is what the slope readers (the shader's slopeFlow, the nebula
// surface normal, the drawn grid) take from the texture.
static void CheckGradient(Zone zone, Vector2[] bodies)
{
Render(new Vector2(1500f, 0f), 512f, out var depth, out var world);
var compared = 0;
for (var y = 1; y < Size - 1; y++)
for (var x = 1; x < Size - 1; x++)
{
var here = world[y * Size + x];
if (bodies.Any(b => (b - here).magnitude < 16f)) continue;
// The world step of each texel axis is read from the camera, so a flipped or rotated target is still measured.
var au = world[y * Size + x + 1] - world[y * Size + x - 1];
var av = world[(y + 1) * Size + x] - world[(y - 1) * Size + x];
var du = depth[y * Size + x + 1] - depth[y * Size + x - 1];
var dv = depth[(y + 1) * Size + x] - depth[(y - 1) * Size + x];
var det = au.x * av.y - au.y * av.x;
var g = new Vector2((du * av.y - dv * au.y) / det, (dv * au.x - du * av.x) / det);
var f = zone.GetForce(new float2(here.x, here.y));
var angle = Vector2.Angle(g, new Vector2(f.x, f.y));
if (float.IsNaN(angle) || angle > GradientDegrees)
{
Fail("gradient", $"at ({here.x:F1}, {here.y:F1}) the drawn slope points {angle:F2} degrees from the force (limit {GradientDegrees:F0})");
return;
}
_maxAngle = Math.Max(_maxAngle, angle);
compared++;
}
if (compared < Size * Size / 2) Fail("gradient", $"only {compared} texels were compared");
}
// Main Menu.unity has no ZoneRenderer, so no Gravity Field and no lowered potential: its gravity cameras draw the
// menu's own brush objects (Boundary on layer 9, the Waves on layer 10) and are presentation by spec (follow-up
// menu-grid-brushes), not a reader of the potential. This pins that: a ZoneRenderer in the menu would make its
// cameras readers of the field, and they would have to cull layer 9 alone like ARPG's.
static void CheckTestSceneWiring()
{
EditorSceneManager.OpenScene("Assets/Scenes/TestScene.unity", OpenSceneMode.Single);
try
{
if (CheckPatchCameras("TestScene.unity") < 1) Fail("wiring", "no Fog Patch Displacement camera in TestScene.unity");
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
}
static void CheckMenuWiring()
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/Main Menu.unity", OpenSceneMode.Single);
try
{
if (UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>(FindObjectsInactive.Include) != null)
Fail("wiring", "Main Menu.unity has a ZoneRenderer: its gravity cameras now read the Gravity Field and must cull layer 9 alone");
var seen = 0;
foreach (var camera in UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None))
{
if (camera.targetTexture == null || camera.targetTexture.name != "Fog Surface Displacement") continue;
seen++;
const int menuBrushLayers = (1 << 9) | (1 << 10);
if (camera.cullingMask != menuBrushLayers)
Fail("wiring", $"Main Menu camera {camera.name} culls mask {camera.cullingMask}, not the menu brush layers 9 and 10");
}
if (seen != 1) Fail("wiring", $"{seen} Fog Surface Displacement cameras in Main Menu.unity, expected 1");
if (CheckPatchCameras("Main Menu.unity") < 1) Fail("wiring", "no Fog Patch Displacement camera in Main Menu.unity");
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
}
// Every scene's Fog Patch Displacement camera: cloudDensity adds the R32 gravity height to the patch texture, so
// a patch camera that culls the gravity layer counts the field twice. Returns how many it found in the open scene.
static int CheckPatchCameras(string sceneName)
{
var found = 0;
foreach (var camera in UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None))
{
if (camera.targetTexture == null || camera.targetTexture.name != "Fog Patch Displacement") continue;
found++;
if ((camera.cullingMask & 1 << GravityLowering.FieldLayer) != 0)
Fail("wiring", $"camera {camera.name} (target Fog Patch Displacement) in {sceneName} culls layer {GravityLowering.FieldLayer}, the gravity layer");
}
return found;
}
static void CheckWiring(GameSettings settings)
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single);
try
{
var gravityTargets = new[] { "Fog Surface Displacement", "Slime Gravity", "MinimapGravity" };
var seen = 0;
foreach (var camera in UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None))
{
if (camera.targetTexture == null || !gravityTargets.Contains(camera.targetTexture.name)) continue;
seen++;
if (camera.cullingMask != 1 << GravityLowering.FieldLayer)
Fail("wiring", $"camera {camera.name} (target {camera.targetTexture.name}) culls mask {camera.cullingMask}, not layer {GravityLowering.FieldLayer} alone");
}
if (seen < gravityTargets.Length) Fail("wiring", $"only {seen} gravity cameras found in ARPG.unity");
// The patch texture is half-float: it holds the patch layers only, the nebula reads gravity from the R32 surface.
if (CheckPatchCameras("ARPG.unity") != 1) Fail("wiring", "ARPG.unity does not have exactly 1 Fog Patch Displacement camera");
// The map screen's gravity camera has no target until MapRenderer gives it one at run time.
var map = UnityEngine.Object.FindFirstObjectByType<MapRenderer>(FindObjectsInactive.Include);
if (map == null || map.GravityCamera == null) Fail("wiring", "no MapRenderer.GravityCamera in ARPG.unity");
else if (map.GravityCamera.cullingMask != 1 << GravityLowering.FieldLayer)
Fail("wiring", $"MapRenderer.GravityCamera culls mask {map.GravityCamera.cullingMask}, not layer {GravityLowering.FieldLayer} alone");
var renderer = UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>(FindObjectsInactive.Include);
if (renderer == null) Fail("wiring", "no ZoneRenderer in ARPG.unity");
else if (renderer.GravityField == null || renderer.GravityField.shader.name != "Brushes/Gravity Field")
Fail("wiring", "ZoneRenderer.GravityField is not a Brushes/Gravity Field material");
foreach (var r in UnityEngine.Object.FindObjectsByType<Renderer>(FindObjectsInactive.Include, FindObjectsSortMode.None))
if (r.gameObject.layer == GravityLowering.FieldLayer)
Fail("wiring", $"renderer {r.name} in ARPG.unity sits on layer {GravityLowering.FieldLayer}");
}
finally
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
}
CheckMenuWiring();
CheckTestSceneWiring();
foreach (var path in new[]
{
"Assets/Prefabs/RPG/Planets/Planet.prefab", "Assets/Prefabs/RPG/Planets/Gas Giant.prefab",
"Assets/Prefabs/RPG/Planets/Sun.prefab", "Assets/Prefabs/RPG/Wormhole 1.prefab"
})
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (prefab == null) { Fail("wiring", $"no prefab at {path}"); continue; }
foreach (var r in prefab.GetComponentsInChildren<Renderer>(true))
if (r.gameObject.layer == GravityLowering.FieldLayer)
Fail("wiring", $"renderer {r.name} in {path} sits on layer {GravityLowering.FieldLayer}");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ceb2bdab0804463b1998471d47e82fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -130,7 +130,7 @@ namespace Aetheria.EditorTools
static AbsorbEvent Absorb(Vector3 worldPos, Vector3 worldDir, float energy = 5f,
DamageType type = DamageType.Kinetic)
=> new AbsorbEvent(worldPos.ToCultMath(), worldDir.ToCultMath(), energy, type);
=> new AbsorbEvent(worldPos.ToCultMath(), worldDir.ToCultMath(), energy, type, AbsorbLayer.Shield);
// ==============================================================
// D17/D20: a panel struck in its own spawn frame must absorb that hit, not swallow it.

View file

@ -96,7 +96,7 @@ public static class ShipModPlaySmoke
}
Install(package.Visual.Id, Path.GetFullPath(packagePath));
var (hull, ship) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc"));
var (hull, ship, _) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc"));
ship.Id += ".broken";
hull.Name += " Broken";
hull.Visual = new CultRecordRef<ShipAuthoring>(ShipModCatalog.AuthoringKey(ship.Id));

View file

@ -140,12 +140,10 @@ public static class ShipPrefabAuthoring
if (values.Length != 7) throw new InvalidOperationException($"Invalid pivot name {name}");
var pivot = AddOrGet<ArticulationPoint>(node.gameObject);
pivot.Group = ParseInt(values[1], name);
pivot.YawMin = ParseInt(values[2], name);
pivot.YawMax = ParseInt(values[3], name);
pivot.PitchMin = ParseInt(values[4], name);
pivot.PitchMax = ParseInt(values[5], name);
pivot.Speed = ParseInt(values[6], name);
if (pivot.YawMin > pivot.YawMax || pivot.PitchMin > pivot.PitchMax || pivot.Speed <= 0)
if (pivot.PitchMin > pivot.PitchMax || pivot.Speed <= 0)
throw new InvalidOperationException($"Invalid articulation range or speed in {name}");
pivots.Add(pivot);
}

View file

@ -0,0 +1,75 @@
using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
// Strips the deleted integrator component from the pickup prefabs and points ZoneRenderer's four pickup fields in ARPG.unity at
// each prefab's ItemPickup, then saves the prefabs and the scene. Idempotent: a prefab with no missing script is left as
// it is, and the fields are set to the same values again.
//
// Unity -batchmode -projectPath <project> -executeMethod WireFloatingItems.Run -logFile <log>
//
// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure. The menu item runs the same wiring.
public static class WireFloatingItems
{
private const string ScenePath = "Assets/Scenes/ARPG.unity";
private const string PickupFolder = "Assets/Prefabs/RPG/Pickups/";
// The field each prefab filled before this cut (read from ARPG.unity at the cut's base). Icosahedron fills none.
private static readonly (string Field, string Prefab)[] Fields =
{
("SimpleCommodityPickup", "Tetrahedron"),
("CompoundCommodityPickup", "Hexahedron"),
("GearPickup", "Octahedron"),
("WeaponPickup", "Dodecahedron"),
};
private static readonly string[] Prefabs = { "Tetrahedron", "Hexahedron", "Octahedron", "Dodecahedron", "Icosahedron" };
[MenuItem("Aetheria/Wire Floating Items")]
public static void Menu() => Wire();
public static void Run()
{
try
{
Wire();
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void Wire()
{
foreach (var name in Prefabs)
{
var path = PickupFolder + name + ".prefab";
var contents = PrefabUtility.LoadPrefabContents(path);
try
{
var removed = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(contents);
if (contents.GetComponent<ItemPickup>() == null) throw new InvalidOperationException($"{path} has no ItemPickup.");
if (removed > 0) PrefabUtility.SaveAsPrefabAsset(contents, path);
Debug.Log($"WIRE_FLOATING_ITEMS {name} removed={removed}");
}
finally { PrefabUtility.UnloadPrefabContents(contents); }
}
var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
var renderer = UnityEngine.Object.FindFirstObjectByType<ZoneRenderer>();
if (renderer == null) throw new InvalidOperationException("ARPG.unity has no ZoneRenderer.");
var serialized = new SerializedObject(renderer);
foreach (var (field, prefab) in Fields)
{
var pickup = AssetDatabase.LoadAssetAtPath<GameObject>(PickupFolder + prefab + ".prefab").GetComponent<ItemPickup>();
var property = serialized.FindProperty(field) ?? throw new InvalidOperationException($"ZoneRenderer has no {field}.");
property.objectReferenceValue = pickup;
}
serialized.ApplyModifiedProperties();
EditorSceneManager.MarkSceneDirty(scene);
if (!EditorSceneManager.SaveScene(scene)) throw new InvalidOperationException("The scene did not save.");
Debug.Log("WIRE_FLOATING_ITEMS ok");
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9a56d7dc8471d224f9bed434b39f7c87

View file

@ -0,0 +1,61 @@
using System;
using Cinemachine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
// Adds the impact-feedback tuning object to ARPG.unity and the impulse listener to its follow camera, then saves the
// scene. Idempotent: a scene that already has them is left as it is.
//
// Unity -batchmode -projectPath <project> -executeMethod WireImpactFeedback.Run -logFile <log>
//
// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure. The menu item runs the same wiring.
public static class WireImpactFeedback
{
private const string ScenePath = "Assets/Scenes/ARPG.unity";
// The weapons' own hit effect (the nested prefab AC5's Projectile uses as HitEffect): no new art.
private const string HullEffectPath = "Assets/Prefabs/Fire & Explosion Effects/Prefabs/TinyExplosion.prefab";
[MenuItem("Aetheria/Wire Impact Feedback")]
public static void Menu() => Wire();
public static void Run()
{
try
{
Wire();
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void Wire()
{
var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
var manager = UnityEngine.Object.FindFirstObjectByType<ActionGameManager>();
if (manager == null || manager.FollowCamera == null) throw new InvalidOperationException("ARPG.unity has no ActionGameManager with a FollowCamera.");
if (manager.FollowCamera.GetComponent<CinemachineImpulseListener>() == null)
manager.FollowCamera.gameObject.AddComponent<CinemachineImpulseListener>();
if (UnityEngine.Object.FindFirstObjectByType<ImpactFeedback>() == null)
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(HullEffectPath);
if (prefab == null) throw new InvalidOperationException($"No prefab at {HullEffectPath}.");
var root = new GameObject("Impact Feedback");
var feedback = root.AddComponent<ImpactFeedback>();
var effect = (GameObject) PrefabUtility.InstantiatePrefab(prefab, root.transform);
feedback.HullEffect = effect.GetComponent<Prototype>();
if (feedback.HullEffect == null) throw new InvalidOperationException("The hull effect prefab has no Prototype.");
EditorUtility.SetDirty(feedback);
}
EditorSceneManager.MarkSceneDirty(scene);
if (!EditorSceneManager.SaveScene(scene)) throw new InvalidOperationException("The scene did not save.");
Debug.Log("WIRE_IMPACT_FEEDBACK ok");
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9083abd01a947a847847d2f6fc177153

View file

@ -113,8 +113,11 @@ public class ActionGameManager : MonoBehaviour
//public string StarterShipTemplate = "Longinus";
// The run's credits: seeded from the scenario stage on a new game and from SavedGame on Continue, written by SaveRun.
[NonSerialized] public int Credits;
public float TargetSpottedBlinkFrequency = 20;
public float TargetSpottedBlinkOffset = -.25f;
// Presentation scale: the player's own Visibility at which the target panel's VisibilityToTargetFill reads full.
public float OwnSignatureFullScale = 10;
// The music last asked for: Update decides it each frame from what the player's own instruments hold and calls
// PlayMusic only when it changes.
private MusicType? _music;
[Header("Postprocessing")]
public float DeathPostTransitionTime;
@ -157,6 +160,12 @@ public class ActionGameManager : MonoBehaviour
public Prototype FriendlyTargetIndicator;
public PlaceUIElementWorldspace ViewDot;
public Prototype LockIndicator;
// Presentation tuning: how far from the ship, toward the locker, the incoming-lock indicator sits.
public float IncomingLockIndicatorDistance = 30;
// Presentation tuning: how far from the ship, toward a remembered hostile's bearing, its marker sits; how long a
// sweep flash takes to fade.
public float BearingMarkerDistance = 40;
public float SearchFlashSeconds = .6f;
public PlaceUIElementWorldspace[] Crosshairs;
public GameObject HitMarker;
public float HitMarkerDuration;
@ -177,8 +186,6 @@ public class ActionGameManager : MonoBehaviour
public Sprite ShieldIcon;
public Sprite NoShieldIcon;
public float IntroDuration;
//public PlayerInput Input;
// private CinemachineFramingTransposer _transposer;
@ -196,9 +203,19 @@ public class ActionGameManager : MonoBehaviour
private readonly HelmInput _helm = new HelmInput();
private TextMeshProUGUI _faceAimMark;
private (HardpointData[] hardpoints, Transform[] barrels, PlaceUIElementWorldspace crosshair)[] _articulationGroups;
private (LockWeapon targetLock, PlaceUIElementWorldspace indicator, Rotate spin)[] _lockingIndicators;
// The outgoing progress indicators on the player's target: one per lock weapon (its Lock, shown only on a hostile target)
// and one per scanner (its scan Progress, shown on any target: a scan reads no stance).
private (Func<float> progress, bool hostileOnly, PlaceUIElementWorldspace indicator, Rotate spin)[] _progressIndicators;
private (PlaceUIElementWorldspace indicator, Rotate spin) _incomingLockIndicator;
private Dictionary<Entity, VisibleTargetIndicator> _visibleHostileIndicators = new Dictionary<Entity, VisibleTargetIndicator>();
private Dictionary<Entity, VisibleTargetIndicator> _visibleFriendlyIndicators = new Dictionary<Entity, VisibleTargetIndicator>();
// Display-only: a marker per remembered hostile (shares HostileTargetIndicator's pool), the Search warnings the last
// ticks delivered (bearing, zone time; a per-tick buffer), and the sweep flashes drawn from them.
private readonly Dictionary<Entity, VisibleTargetIndicator> _bearingMarkers = new Dictionary<Entity, VisibleTargetIndicator>();
private readonly List<(float2 bearing, float time)> _pendingSweeps = new List<(float2, float)>();
private readonly List<(PlaceUIElementWorldspace indicator, Image image, float2 bearing, float time)> _sweepFlashes =
new List<(PlaceUIElementWorldspace, Image, float2, float)>();
private readonly List<Entity> _markerScratch = new List<Entity>();
private List<IDisposable> _shipSubscriptions = new List<IDisposable>();
private List<IDisposable> _targetSubscriptions = new List<IDisposable>();
private readonly Dictionary<EquippedItem, ShotOutcome> _debugLastShots = new Dictionary<EquippedItem, ShotOutcome>();
@ -231,6 +248,8 @@ public class ActionGameManager : MonoBehaviour
public ItemManager ItemManager { get; private set; }
public Zone Zone { get; private set; }
public static SimClock Clock { get; } = new SimClock(1f / 60f);
private bool _zoneEntered;
private readonly (float2 direction, string name)[] _directions = {
(float2(0, 1), "Front"),
@ -317,7 +336,7 @@ public class ActionGameManager : MonoBehaviour
Input.Global.ZoneMap.performed += context =>
{
ToggleMenuTab(MenuTab.Map);
MenuMap.Position = CurrentEntity.Position.xz;
MenuMap.Position = DrawAhead.Position(CurrentEntity, Clock.Lead).xz;
};
Input.Global.Inventory.performed += context => ToggleMenuTab(MenuTab.Inventory);
@ -341,6 +360,19 @@ public class ActionGameManager : MonoBehaviour
foreach (var wormhole in ZoneRenderer.WormholeInstances.Keys)
{
if (!(length(wormhole.Position - CurrentEntity.Position.xz) < Settings.GameplaySettings.WormholeExitRadius)) continue;
if (wormhole.Exit)
{
// The exit gate leads nowhere: RunGoal decides whether it is open, and an open one ends the run.
if (RunGoal.ExitOpen(Zone)) Win();
else
{
Dialog.Clear();
Dialog.Title.text = $"The exit gate is sealed. {RunGoal.Boss(Zone)?.Name ?? "Its guardian"} holds it shut.";
Dialog.Show();
Dialog.MoveToCursor();
}
return;
}
EnterWormhole(wormhole);
}
Dock();
@ -409,22 +441,9 @@ public class ActionGameManager : MonoBehaviour
Input.Player.TargetNext.performed += context => CurrentEntity.TargetNext();
Input.Player.TargetPrevious.performed += context => CurrentEntity.TargetPrevious();
// Cut 2 (docs/fire-control-cut.md): cycles the aim point among the current target's revealed
// subsystems -- decides nothing itself, only calls the one writer (TrySelectTargetItem), same
// predicate (FireControl.IsRevealed) the AI path uses. Entity-only: a chunk has no subsystems.
Input.Player.CycleTargetItem.performed += context =>
{
var target = CurrentEntity.Target.Value.Entity;
if (target == null) return;
var revealed = target.Equipment.Where(x => FireControl.IsRevealed(CurrentEntity, x)).ToArray();
if (revealed.Length == 0)
{
CurrentEntity.TrySelectTargetItem(null);
return;
}
var currentItemIndex = Array.IndexOf(revealed, CurrentEntity.ResolvedTargetItem);
CurrentEntity.TrySelectTargetItem(revealed[(currentItemIndex + 1) % revealed.Length]);
};
// Cut 2 (docs/fire-control-cut.md): steps the aim through the target's schematic rows -- every mount this ship
// has located, empty or not, minus the ones it saw destroyed. Decides nothing: the entity owns the cycle.
Input.Player.CycleTargetItem.performed += context => CurrentEntity.CycleAim();
#endregion
@ -715,14 +734,16 @@ public class ActionGameManager : MonoBehaviour
galaxyZone.Contents = new Zone(ItemManager, Settings.PlanetSettings, galaxyZone.PackedContents, galaxyZone, CurrentGalaxy);
}
Zone = galaxyZone.Contents;
_zoneEntered = true; // the clock forgets its lead between frames, never inside a step
PlayMusic(MusicType.Overworld);
_music = MusicType.Overworld;
Zone.Log = s => Debug.Log($"Zone: {s}");
if (CurrentEntity != null)
{
CurrentEntity.Deactivate();
CurrentEntity.Zone.Entities.Remove(CurrentEntity);
CurrentEntity.Zone.Remove(CurrentEntity);
CurrentEntity.Zone = Zone;
Zone.Admit(CurrentEntity, piloted: false);
}
@ -805,7 +826,6 @@ public class ActionGameManager : MonoBehaviour
}
else
{
//StartCoroutine(IntroCutscene(targetEntity as Ship));
BindToEntity(targetEntity);
}
@ -853,35 +873,6 @@ public class ActionGameManager : MonoBehaviour
BindToEntity(staged.Player);
}
private IEnumerator IntroCutscene(Ship ship)
{
ZoneRenderer.PerspectiveEntity = ship;
var entityPosition = ship.Position.xz;
var followOrbit = Zone.Orbits.Keys.MinBy(o => lengthsq(Zone.GetOrbitPosition(o) - entityPosition));
var followPlanet = ZoneRenderer.Planets[Zone.Planets.FirstOrDefault(p => p.Value.Orbit.Key.Equals(followOrbit)).Key];
DockCamera.Follow = followPlanet.Body.transform;
var rootOrbit = followOrbit;
while (Zone.Orbits[rootOrbit].Data.Parent.IsSet())
rootOrbit = Zone.Orbits[rootOrbit].Data.Parent.Key;
var rootPlanet = ZoneRenderer.Planets[Zone.Planets.FirstOrDefault(p => p.Value.Orbit.Key.Equals(rootOrbit)).Key];
DockCamera.LookAt = rootPlanet.Body.transform;
var shipVelocity = ship.GetBehavior<VelocityLimit>().Limit;
var followOrbitPosition = Zone.GetOrbitPosition(followOrbit);
var shipDirection = normalize(Zone.GetOrbitPosition(rootOrbit) - followOrbitPosition);
ship.Position.xz = followOrbitPosition - shipDirection * shipVelocity * IntroDuration;
var startTime = Time.time;
while (Time.time - startTime < IntroDuration)
{
ship.Direction = shipDirection;
ship.Velocity = shipDirection * shipVelocity;
yield return null;
}
BindToEntity(ship);
}
public void Dock()
{
if (CurrentEntity.Parent != null) return;
@ -948,7 +939,7 @@ public class ActionGameManager : MonoBehaviour
Dialog.MoveToCursor();
// TODO: SFX: Fail
}
else if (CurrentEntity.GetBehavior<Thruster>() == null && CurrentEntity.GetBehavior<AetherDrive>() == null)
else if (CurrentEntity.GetBehavior<Thruster>() == null)
{
Dialog.Clear();
Dialog.Title.text = "Can't undock. Missing thruster component!";
@ -1012,9 +1003,17 @@ public class ActionGameManager : MonoBehaviour
foreach (var indicator in _visibleFriendlyIndicators) Destroy(indicator.Value.gameObject);
_visibleFriendlyIndicators.Clear();
foreach (var marker in _bearingMarkers.Values) RetireMarker(marker);
_bearingMarkers.Clear();
foreach (var flash in _sweepFlashes) RetireFlash(flash.indicator, flash.image);
_sweepFlashes.Clear();
_pendingSweeps.Clear();
if(_lockingIndicators!=null) foreach(var (_, indicator, _) in _lockingIndicators)
if(_progressIndicators!=null) foreach(var (_, _, indicator, _) in _progressIndicators)
indicator.GetComponent<Prototype>().ReturnToPool();
if(_incomingLockIndicator.indicator != null) _incomingLockIndicator.indicator.GetComponent<Prototype>().ReturnToPool();
_incomingLockIndicator = default;
DisablePlayerInput();
Cursor.lockState = CursorLockMode.None;
GameplayUI.gameObject.SetActive(false);
@ -1076,11 +1075,6 @@ public class ActionGameManager : MonoBehaviour
foreach (var group in _articulationGroups)
group.crosshair.gameObject.SetActive(true);
_shipSubscriptions.Add(CurrentEntity.TargetedByCount.Subscribe(count =>
{
PlayMusic(count > 0 ? MusicType.Combat : MusicType.Overworld);
}));
_shipSubscriptions.Add(CurrentEntity.Target.Subscribe(target =>
{
// Clear previous subscriptions related to currently targeted enemy
@ -1152,12 +1146,18 @@ public class ActionGameManager : MonoBehaviour
_shipSubscriptions.Add(CurrentEntity.Death.Subscribe(Die));
_lockingIndicators = CurrentEntity.GetBehaviors<LockWeapon>()
var progressSources = CurrentEntity.GetBehaviors<LockWeapon>().Select(x => ((Func<float>) (() => x.Lock), true))
.Concat(CurrentEntity.GetBehaviors<Scanner>().Select(x => ((Func<float>) (() => x.Progress), false)));
_progressIndicators = progressSources
.Select(x =>
{
var i = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
return (x, i, i.GetComponent<Rotate>());
return (x.Item1, x.Item2, i, i.GetComponent<Rotate>());
}).ToArray();
var incoming = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
incoming.gameObject.SetActive(false);
_incomingLockIndicator = (incoming, incoming.GetComponent<Rotate>());
}
private void UpdatePlayerPanel()
@ -1178,16 +1178,18 @@ public class ActionGameManager : MonoBehaviour
}
}
// A chunk's simulated position is planar (Zone.ChunkPose); the renderer draws it at the asteroid layer's height.
// A chunk's pose is planar (Zone.ChunkPose), read at the drawn time so the reticle sits on the drawn rock; the renderer
// draws it at the asteroid layer's height.
private float3 ChunkWorldPosition(ChunkId chunk)
{
var pose = CurrentEntity.Zone.ChunkPose(chunk.Field, chunk.Index);
var zone = CurrentEntity.Zone;
var pose = zone.ChunkPose(chunk.Field, chunk.Index, DrawAhead.Time(zone, Clock.Lead));
return float3(pose.x, Settings.PlanetSettings.AsteroidVerticalOffset, pose.y);
}
private void Die(CauseOfDeath cause)
// The one way a run ends, won or lost: the run is cleared and the main menu returns.
private void EndRun()
{
var deathTime = Time.time;
UnbindEntity();
CurrentEntity = null;
MainMenu.gameObject.SetActive(true);
@ -1195,6 +1197,21 @@ public class ActionGameManager : MonoBehaviour
CurrentGalaxy = null;
RunSave.Clear(CultCache);
SavePlayerSettings();
}
private void Win()
{
EndRun();
Dialog.Clear();
Dialog.Title.text = "You have escaped the Terminus. This was the demo; the whole of it is yet to come.";
Dialog.Show();
Dialog.MoveToCursor();
}
private void Die(CauseOfDeath cause)
{
var deathTime = Time.time;
EndRun();
Observable.EveryUpdate()
.Where(_ => Time.time - deathTime < DeathPostTransitionTime)
.Subscribe(_ =>
@ -1256,6 +1273,36 @@ public class ActionGameManager : MonoBehaviour
// TODO: SFX: Music
}
// What the player's own instruments say about combat, nothing a hostile knows: a hostile tracked, a paint on the
// player, or a remembered hostile the player still has a bearing on (a reveal younger than BearingMemory).
private void UpdateMusic()
{
var combat = CurrentEntity.VisibleEnemies.Count > 0 || CurrentEntity.IncomingPaints.Count > 0;
combat |= CurrentEntity.RememberedHostiles.Any();
var type = combat ? MusicType.Combat : MusicType.Overworld;
if (_music == type) return;
_music = type;
PlayMusic(type);
}
// An indicator's fill is how far the player's own sensors have resolved the ship from a track toward identifying
// it (ContactOf.Info over the detection-to-gear span): nothing of what the ship sees of the player.
private void PlaceFill(VisibleTargetIndicator indicator, Entity subject)
{
indicator.Fill.enabled = subject.Active;
if (!subject.Active) return;
var settings = Settings.GameplaySettings;
indicator.Fill.fillAmount = saturate(unlerp(settings.TargetDetectionInfoThreshold, settings.TargetGearInfoThreshold,
CurrentEntity.ContactOf(subject).Info));
}
// Whether an effect drawn at `subject`'s true position may be drawn: the player's own ship, or a ship its
// instruments track. The one seam for impact and hit effects (follow-up presentation-gated-on-tracked); a bearing
// alone (Detected without Tracked) places nothing there. No player ship, nothing to gate on.
public static bool DrawsAt(Entity subject) =>
Instance == null || Instance.CurrentEntity == null || subject == null || subject == Instance.CurrentEntity ||
Instance.CurrentEntity.ContactOf(subject).Tracked;
void Update()
{
if(!_paused)
@ -1269,30 +1316,14 @@ public class ActionGameManager : MonoBehaviour
foreach (var indicator in _visibleHostileIndicators)
{
indicator.Value.gameObject.SetActive(indicator.Key!=CurrentEntity.Target.Value.Entity);
indicator.Value.Place.Target = indicator.Key.Position.ToUnity();
if (!indicator.Key.Active)
indicator.Value.Fill.enabled = false;
else
{
indicator.Value.Fill.fillAmount =
saturate(indicator.Key.EntityInfoGathered[CurrentEntity] / Settings.GameplaySettings.TargetDetectionInfoThreshold);
indicator.Value.Fill.enabled =
!(indicator.Key.EntityInfoGathered[CurrentEntity] > Settings.GameplaySettings.TargetDetectionInfoThreshold) ||
sin(TargetSpottedBlinkFrequency * Time.time) + TargetSpottedBlinkOffset > 0;
}
indicator.Value.Place.Target = DrawAhead.Position(indicator.Key, Clock.Lead).ToUnity();
PlaceFill(indicator.Value, indicator.Key);
}
foreach (var indicator in _visibleFriendlyIndicators)
{
indicator.Value.gameObject.SetActive(indicator.Key!=CurrentEntity.Target.Value.Entity);
indicator.Value.Place.Target = indicator.Key.Position.ToUnity();
if (!indicator.Key.Active)
indicator.Value.Fill.enabled = false;
else
{
indicator.Value.Fill.enabled = true;
indicator.Value.Fill.fillAmount =
saturate(indicator.Key.EntityInfoGathered[CurrentEntity] / Settings.GameplaySettings.TargetDetectionInfoThreshold);
}
indicator.Value.Place.Target = DrawAhead.Position(indicator.Key, Clock.Lead).ToUnity();
PlaceFill(indicator.Value, indicator.Key);
}
var look = Input.Player.Look.ReadValue<Vector2>();
var sensitivity = PlayerSettings.InputSettings.Sensitivity;
@ -1313,23 +1344,36 @@ public class ActionGameManager : MonoBehaviour
ship.Turn = _helm.Demand(ship, _viewDirection.xz, Input.Player.Turn.ReadValue<float>());
}
UpdateMusic();
UpdateFireControlDebug(CurrentEntity.Target.Value);
var target = CurrentEntity.Target.Value.Entity;
if (target != null)
{
var threshold = Settings.GameplaySettings.TargetDetectionInfoThreshold;
TargetVisibilityFill.fillAmount = lerp(.25f, .75f, (CurrentEntity.EntityInfoGathered[target] - threshold)/(1-threshold));
VisibilityToTargetFill.fillAmount = lerp(.25f, .75f, target.EntityInfoGathered[CurrentEntity] / threshold);
TargetVisibilityFill.fillAmount = lerp(.25f, .75f, (CurrentEntity.ContactOf(target).Info - threshold)/(1-threshold));
VisibilityToTargetFill.fillAmount = lerp(.25f, .75f, saturate(CurrentEntity.Visibility / OwnSignatureFullScale));
TargetHitpointsFill.fillAmount = lerp(.25f, .75f, target.Hull.Durability / target.EquippedHull.Data.Durability);
TargetShieldsFill.fillAmount = target.Shield == null ? 0 : lerp(.25f, .75f, target.Shield.Progress);
}
var tractorPower = Input.Player.TractorBeam.ReadValue<float>();
CurrentEntity.TractorPower =
saturate(CurrentEntity.TractorPower + sign(tractorPower - CurrentEntity.TractorPower) * Time.deltaTime * 2);
CurrentEntity.TractorCommand = Input.Player.TractorBeam.ReadValue<float>();
}
Zone.Update(Time.deltaTime);
}
// One clock steps the zone, paused or not: a paused frame feeds it no real time.
// A zone entered inside a step (a wormhole) ends this frame's stepping: the rest of its steps are the old zone's.
void EnterNewZone() { if (_zoneEntered) { Clock.Reset(); _zoneEntered = false; } }
EnterNewZone();
var steppedZone = Zone;
Clock.Advance(_paused ? 0f : Time.deltaTime, delta =>
{
if (Zone != steppedZone) return;
steppedZone.Update(delta);
// A warning lives one tick, so sweeps are collected per tick, never read per frame.
if (CurrentEntity != null && CurrentEntity.Zone == steppedZone)
foreach (var warning in CurrentEntity.IncomingPaints)
if (warning.Mode == PaintMode.Search) _pendingSweeps.Add((warning.Bearing, steppedZone.Time));
});
EnterNewZone();
}
private static string ResultLabel(ShotResult result) => result switch
@ -1395,7 +1439,7 @@ public class ActionGameManager : MonoBehaviour
: $"base {d.PBase:P1}";
DebugInfoText.text =
$"FIRE CONTROL - {selectedItem.Data.Name}\n" +
$"FIRE CONTROL - {ItemManager.Title(selectedItem.EquippableItem)}\n" +
$"{gates}\n" +
$"range {d.Range:F0} [{d.MinRange:F0}..{d.MaxRange:F0}]\n" +
$"info {d.Info:F3}/{d.InfoDemandCeiling:F3} sensor {d.PSensor:F3}\n" +
@ -1416,13 +1460,15 @@ public class ActionGameManager : MonoBehaviour
{
if (CurrentEntity == null || CurrentEntity.Parent != null) return;
var lead = Clock.Lead;
var ownDrawn = DrawAhead.Position(CurrentEntity, lead);
ViewDot.Target = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint.position;
var target = CurrentEntity.Target.Value;
if (target.Chunk is ChunkId chunk)
TargetIndicator.Target = ChunkWorldPosition(chunk).ToUnity();
else if (target.Entity != null)
TargetIndicator.Target = target.Entity.Position.ToUnity();
var distance = length(ViewDot.Target.ToCultMath() - CurrentEntity.Position);
TargetIndicator.Target = DrawAhead.Position(target.Entity, lead).ToUnity();
var distance = length(ViewDot.Target.ToCultMath() - ownDrawn);
foreach (var (_, barrels, crosshair) in _articulationGroups)
{
var averagePosition = Vector3.zero;
@ -1432,18 +1478,112 @@ public class ActionGameManager : MonoBehaviour
crosshair.Target = averagePosition;
}
foreach (var (targetLock, indicator, spin) in _lockingIndicators)
foreach (var (progress, hostileOnly, indicator, spin) in _progressIndicators)
{
var showLockingIndicator = targetLock.Lock > .01f && CurrentEntity.Target.Value.Entity != null && CurrentEntity.IsHostileTo(CurrentEntity.Target.Value.Entity);
indicator.gameObject.SetActive(showLockingIndicator);
if(showLockingIndicator)
var value = progress();
var targetEntity = CurrentEntity.Target.Value.Entity;
var showIndicator = value > .01f && targetEntity != null && (!hostileOnly || CurrentEntity.IsHostileTo(targetEntity));
indicator.gameObject.SetActive(showIndicator);
if(showIndicator)
{
indicator.Target = CurrentEntity.Target.Value.Entity.Position.ToUnity();
indicator.NoiseAmplitude = Settings.GameplaySettings.LockIndicatorNoiseAmplitude * (1 - targetLock.Lock);
indicator.NoiseFrequency = Settings.GameplaySettings.LockIndicatorFrequency.Evaluate(targetLock.Lock);
spin.Speed = Settings.GameplaySettings.LockSpinSpeed.Evaluate(targetLock.Lock);
indicator.Target = DrawAhead.Position(targetEntity, lead).ToUnity();
ApplyLockProgress(indicator, spin, value);
}
}
// The strongest lock or scan on the player's ship, read only from IncomingPaints (never another ship's LockWeapon or
// Scanner). A Scan paint's Strength is the scan's progress (ruling scan-is-an-act). Search paints (ping sweeps) are
// this class's sweep flashes (UpdateSweepFlashes). Same curves as the outgoing indicator, driven by the warning's Strength.
var warnings = CurrentEntity.IncomingPaints;
var strongest = -1;
for (var w = 0; w < warnings.Count; w++)
if ((warnings[w].Mode is PaintMode.Track or PaintMode.Scan) && (strongest < 0 || warnings[w].Strength > warnings[strongest].Strength)) strongest = w;
var (incomingIndicator, incomingSpin) = _incomingLockIndicator;
incomingIndicator.gameObject.SetActive(strongest >= 0);
if (strongest >= 0)
{
var warning = warnings[strongest];
incomingIndicator.Target = DrawAhead.AtBearing(CurrentEntity, warning.Bearing, IncomingLockIndicatorDistance, lead).ToUnity();
ApplyLockProgress(incomingIndicator, incomingSpin, warning.Strength);
}
UpdateBearingMarkers();
UpdateSweepFlashes();
}
// One marker per remembered hostile (a contact held by a bearing only): at the bearing the book keeps, labelled with the
// classes it claimed. Never at the subject's position, never read from its gear.
private void UpdateBearingMarkers()
{
var remembered = CurrentEntity.RememberedHostiles.ToList();
_markerScratch.Clear();
foreach (var subject in _bearingMarkers.Keys)
if (!remembered.Contains(subject)) _markerScratch.Add(subject);
foreach (var subject in _markerScratch)
{
RetireMarker(_bearingMarkers[subject]);
_bearingMarkers.Remove(subject);
}
foreach (var subject in remembered)
{
if (!_bearingMarkers.TryGetValue(subject, out var marker))
{
marker = HostileTargetIndicator.Instantiate<VisibleTargetIndicator>();
marker.Fill.enabled = false;
_bearingMarkers.Add(subject, marker);
}
marker.gameObject.SetActive(true);
var bearing = CurrentEntity.ContactOf(subject).Bearing;
marker.Place.Target = DrawAhead.AtBearing(CurrentEntity, bearing, BearingMarkerDistance, Clock.Lead).ToUnity();
marker.ShowLabel(string.Join(", ", CurrentEntity.ClaimedClasses(subject).Select(c => c.Name)));
}
}
// A pooled indicator goes back as the next hostile indicator will want it: label hidden, fill restored.
private static void RetireMarker(VisibleTargetIndicator marker)
{
marker.ShowLabel(null);
marker.Fill.enabled = true;
marker.GetComponent<Prototype>().ReturnToPool();
}
private static void RetireFlash(PlaceUIElementWorldspace indicator, Image image)
{
if (image != null) image.color = new Color(image.color.r, image.color.g, image.color.b, 1);
indicator.GetComponent<Prototype>().ReturnToPool();
}
// A ping crossing the player draws one flash toward the pinger, fading over SearchFlashSeconds of zone time.
private void UpdateSweepFlashes()
{
foreach (var (bearing, time) in _pendingSweeps)
{
var indicator = LockIndicator.Instantiate<PlaceUIElementWorldspace>();
ApplyLockProgress(indicator, indicator.GetComponent<Rotate>(), 0); // a pooled lock indicator keeps its last tightening
_sweepFlashes.Add((indicator, indicator.GetComponentInChildren<Image>(), bearing, time));
}
_pendingSweeps.Clear();
for (var i = _sweepFlashes.Count - 1; i >= 0; i--)
{
var (indicator, image, bearing, time) = _sweepFlashes[i];
var age = Zone.Time - time;
if (age < 0 || age >= SearchFlashSeconds)
{
RetireFlash(indicator, image);
_sweepFlashes.RemoveAt(i);
continue;
}
indicator.Target = DrawAhead.AtBearing(CurrentEntity, bearing, IncomingLockIndicatorDistance, Clock.Lead).ToUnity();
if (image != null) image.color = new Color(image.color.r, image.color.g, image.color.b, 1 - age / SearchFlashSeconds);
}
}
// The one lock-indicator curve: outgoing (the player's own lock) and incoming (the warning's strength) both tighten through it.
private void ApplyLockProgress(PlaceUIElementWorldspace indicator, Rotate spin, float progress)
{
indicator.NoiseAmplitude = Settings.GameplaySettings.LockIndicatorNoiseAmplitude * (1 - progress);
indicator.NoiseFrequency = Settings.GameplaySettings.LockIndicatorFrequency.Evaluate(progress);
spin.Speed = Settings.GameplaySettings.LockSpinSpeed.Evaluate(progress);
}
}

View file

@ -4,15 +4,14 @@ using UnityEngine;
using CultMath;
using static CultMath.math;
// Presentation only: the barrel follows the point its group's solution places (EntityInstance), which FireControl has
// already clamped to the arc. This decides no arc; Speed and the pitch clamp are how the picture slews.
public class ArticulationPoint : MonoBehaviour
{
public Transform Target;
public int Group;
public float YawMin;
public float YawMax;
public float PitchMin;
public float PitchMax;
@ -30,7 +29,7 @@ public class ArticulationPoint : MonoBehaviour
var yaw = Vector2.SignedAngle(new Vector2(0, 1), new Vector2(targetLocal.x, targetLocal.z));
var pitch = Vector2.SignedAngle(new Vector2(1, 0), new Vector2(targetLocal.z, targetLocal.y));
var targetYaw = clamp(_yaw - yaw, YawMin, YawMax);
var targetYaw = _yaw - yaw;
var targetPitch = clamp(_pitch - pitch, PitchMin, PitchMax);
if (abs(targetYaw - _yaw) < Speed * Time.deltaTime)

View file

@ -8,27 +8,18 @@ using UnityEngine;
// playground-cut.md fork L: "presentation is chosen per item, independently of capability... one
// presentation... can visualize any subset of an item's capabilities"). This binder has no knowledge
// of FieldDriver or any other concrete presentation, and no knowledge of what publishes events --
// today the FieldShieldTest scene calls Bind() directly; a real capability owner will do the same
// later without this binder changing.
// EntityInstance binds every entity's events, and the FieldShieldTest scene binds its stand-in sim's the same way.
public class CapabilityPresentationBinder : MonoBehaviour
{
private readonly List<IDisposable> _subscriptions = new List<IDisposable>();
private Func<int, Transform> _grabTargetResolver;
private Func<int, Vector3> _grabInitialVelocityResolver;
// Subscribes every presenter interface implemented by components on this object or its children to
// the matching stream of `events`. `grabTargetResolver`/`grabInitialVelocityResolver` resolve a
// GrabEvent's plain target handle to the live Transform/velocity a grab presenter needs; the owner
// of `events` supplies them (the test scene today; the real pickup capability's caller later).
public void Bind(CapabilityEvents events, Func<int, Transform> grabTargetResolver = null,
Func<int, Vector3> grabInitialVelocityResolver = null)
// the matching stream of `events`.
public void Bind(CapabilityEvents events)
{
Unbind();
if (events == null) return;
_grabTargetResolver = grabTargetResolver;
_grabInitialVelocityResolver = grabInitialVelocityResolver;
foreach (var presenter in GetComponentsInChildren<IAbsorbPresenter>(true))
{
var p = presenter;
@ -38,12 +29,7 @@ public class CapabilityPresentationBinder : MonoBehaviour
foreach (var presenter in GetComponentsInChildren<IGrabPresenter>(true))
{
var p = presenter;
_subscriptions.Add(events.Grab.Subscribe(e =>
{
var target = _grabTargetResolver?.Invoke(e.TargetHandle);
var velocity = _grabInitialVelocityResolver?.Invoke(e.TargetHandle) ?? Vector3.zero;
p.Grab(e, target, velocity);
}));
_subscriptions.Add(events.Grab.Subscribe(e => p.Grab(e)));
}
foreach (var presenter in GetComponentsInChildren<IMeleePresenter>(true))
@ -63,8 +49,6 @@ public class CapabilityPresentationBinder : MonoBehaviour
{
foreach (var s in _subscriptions) s.Dispose();
_subscriptions.Clear();
_grabTargetResolver = null;
_grabInitialVelocityResolver = null;
}
private void OnDisable() => Unbind();

View file

@ -10,13 +10,10 @@ public interface IAbsorbPresenter
void Absorb(AbsorbEvent e);
}
// Grab needs a live Transform to animate, which the engine-free GrabEvent cannot carry (its
// TargetHandle is a plain identity, not a Unity reference). The binder resolves the handle through a
// delegate supplied by the event source's owner and hands the presenter the result, along with the
// initial velocity the target was already moving with (also owner-supplied, for the same reason).
// Presenters read the event and the simulated pose, never a Transform the sim does not own.
public interface IGrabPresenter
{
void Grab(GrabEvent e, Transform target, Vector3 initialVelocity);
void Grab(GrabEvent e);
}
public interface IMeleePresenter

View file

@ -64,6 +64,7 @@ public class EntityInstance : MonoBehaviour
public Dictionary<HardpointData, int> BarrelIndices { get; private set; }
public Dictionary<Radiator, MeshRenderer> RadiatorMeshes { get; private set; }
public Transform LookAtPoint { get; private set; }
private Dictionary<int, Transform> _groupAims;
public Entity Entity { get; private set; }
public ZoneRenderer ZoneRenderer { get; private set; }
public Transform LocalSpace { get; private set; }
@ -166,6 +167,13 @@ public class EntityInstance : MonoBehaviour
if(Shield)
Shield.Entity = entity;
// Landed impacts reach the screen through the entity's one binding: the shield ripple (ShieldManager) and the
// hull reaction and camera kick (ImpactPresenter) subscribe to the Absorb stream the simulation publishes.
var impacts = gameObject.GetComponent<ImpactPresenter>() ?? gameObject.AddComponent<ImpactPresenter>();
impacts.Entity = entity;
(gameObject.GetComponent<CapabilityPresentationBinder>() ?? gameObject.AddComponent<CapabilityPresentationBinder>())
.Bind(entity.Capabilities);
foreach (var hullCollider in HullColliders) hullCollider.Entity = entity;
foreach (var item in entity.Equipment)
@ -179,14 +187,15 @@ public class EntityInstance : MonoBehaviour
{
var pingInstance = Instantiate(PingPrefab);
var pingMesh = pingInstance.GetComponent<MeshRenderer>();
pingInstance.position = entity.Position.ToUnity();
pingInstance.position = DrawAhead.Position(entity, ActionGameManager.Clock.Lead).ToUnity();
_pingBrightness = pingMesh.material.GetFloat("_Depth");
_currentPing = (pingInstance, pingMesh);
};
sensor.OnPingEnd += OnSensorPingEnd;
}
if (behavior is InstantWeapon instantWeapon)
// A mine layer's presentation is the mine it lays (MineInstance, drawn by ZoneRenderer from Zone.Mines).
if (behavior is InstantWeapon instantWeapon && !FireControl.IsMineLayer(instantWeapon))
{
var data = (InstantWeaponData) instantWeapon.Data;
if (!_instantWeaponManagers.ContainsKey(data))
@ -276,39 +285,22 @@ public class EntityInstance : MonoBehaviour
// HullColliders no longer publish Hit or a blast event at all (R8).
LookAtPoint = new GameObject($"{entity.Name} Look Point").transform;
// One aim point per articulation group, placed each LateUpdate where the group's first weapon aims.
_groupAims = new Dictionary<int, Transform>();
foreach (var articulationPoint in ArticulationPoints)
{
articulationPoint.Target = LookAtPoint;
if (!_groupAims.TryGetValue(articulationPoint.Group, out var aim))
_groupAims[articulationPoint.Group] = aim = new GameObject($"{entity.Name} Aim {articulationPoint.Group}").transform;
articulationPoint.Target = aim;
}
_subscriptions.Add(Entity.HullDamage.Subscribe(_ =>
{
if (Entity.Hull.Durability < .01f)
if (Entity.Hull.IsDestroyed)
{
if (!this) return;
_destroyed = true;
foreach (var gear in Entity.Equipment)
{
if (gear != Entity.EquippedHull && Random.value < ZoneRenderer.Settings.LootDropProbability)
{
ZoneRenderer.DropItem(
Entity.Position.ToUnity(),
Random.onUnitSphere * ZoneRenderer.Settings.LootDropVelocity,
gear.EquippableItem);
}
}
foreach (var cargo in Entity.CargoBays)
{
foreach (var item in cargo.Cargo.Keys)
{
ZoneRenderer.DropItem(
Entity.Position.ToUnity(),
Random.onUnitSphere * ZoneRenderer.Settings.LootDropVelocity,
item);
}
}
if (DestroyEffect != null)
{
var t = Instantiate(DestroyEffect).transform;
@ -398,11 +390,23 @@ public class EntityInstance : MonoBehaviour
x.Value.material.SetFloat("_Emission", Entity.ItemManager.GameplaySettings.TemperatureEmissionCurve.Evaluate(x.Key.RadiatorTemperature));
}
LookAtPoint.position = transform.position + Entity.Aim.ToUnity() *
(!Entity.Target.Value.IsNone ? max(Entity.TargetRange,Entity.ItemManager.GameplaySettings.ConvergenceMinimumDistance) : 10000);
LocalSpace.localPosition = transform.position = Entity.Position.ToUnity();
// The drawn pose first: the camera's LookAt and the barrels read this frame's pose, not the last frame's.
var drawn = DrawAhead.Position(Entity, ActionGameManager.Clock.Lead);
LocalSpace.localPosition = transform.position = drawn.ToUnity();
var aimDistance = !Entity.Target.Value.IsNone
? max(Entity.TargetRange, Entity.ItemManager.GameplaySettings.ConvergenceMinimumDistance)
: 10000;
LookAtPoint.position = transform.position + Entity.Aim.ToUnity() * aimDistance;
foreach (var group in _groupAims)
{
var weapon = group.Key >= 0 && group.Key < Entity.WeaponGroups.Length ? Entity.WeaponGroups[group.Key].weapons.FirstOrDefault() : null;
if (weapon == null) { group.Value.position = LookAtPoint.position; continue; }
var barrel = Barrels.TryGetValue(weapon.Item.Hardpoint, out var barrels) ? barrels[0].position : transform.position;
var direction = FireControl.Solution(weapon, Entity, Entity.Target.Value).Direction;
group.Value.position = barrel + new Vector3(direction.x, 0, direction.y) * aimDistance;
}
if (_influenceInstance)
_influenceInstance.position = new Vector3(Entity.Position.x, 0, Entity.Position.z);
_influenceInstance.position = new Vector3(drawn.x, 0, drawn.z);
}
public virtual void OnDestroy()

View file

@ -63,11 +63,7 @@ public class FieldDriver : MonoBehaviour, IAbsorbPresenter, IGrabPresenter, IMel
// public float GrabScaleAnimationExponent = .5f;
[Inspectable]
public float GrabExtendTime;
[Inspectable]
public float GrabEnvelopTime;
[Inspectable]
public float GrabPullTime;
public float TendrilTipScale = 1;
[Inspectable]
public RectTransform.Axis RefractionAxis = RectTransform.Axis.Horizontal;
@ -81,29 +77,17 @@ public class FieldDriver : MonoBehaviour, IAbsorbPresenter, IGrabPresenter, IMel
private float _meleeTime;
private bool _meleeActive;
private MeshCollider _collider;
private Transform _grabObject;
private Vector3 _grabObjectStartPos;
private Vector3 _grabObjectStartTendrilBasePos;
private Vector3 _grabObjectEndPos;
private Vector3 _grabObjectVelocity;
private float _grabObjectScale;
private bool _grabbing;
private GrabPhase _grabPhase;
private float _grabTime;
private TendrilPhase _grabPhase;
private float _phaseDuration;
private Vector3 _grabStart;
private Vector3 _grabStartTendrilBase;
private Vector3 _tendrilBasePos;
private Vector3 _tendrilBendTarget;
private Vector3 _tendrilTargetPos;
private float _fadePoint;
// Named distinctly from the global GrabPhase (CapabilityEvents.cs): this is FieldDriver's own
// internal tendril-animation timing, still owned here until a real pickup capability exists to
// publish per-phase GrabEvent transitions (see Grab(GrabEvent, Transform, Vector3) below).
private enum TendrilPhase
{
Extend,
Envelop,
Pull
}
private struct FieldHit
{
public float3 Position;
@ -181,32 +165,41 @@ public class FieldDriver : MonoBehaviour, IAbsorbPresenter, IGrabPresenter, IMel
_meleeTime = 0;
}
public bool CanGrab => _grabObject == null;
public void GrabObject(Transform t, Vector3 v)
{
_grabPhase = TendrilPhase.Extend;
_grabObject = t;
_grabObjectStartPos = t.position;
_grabObjectVelocity = v;
_grabObjectScale = t.localScale.x;
_tendrilBasePos = _grabObjectStartTendrilBasePos = _collider.ClosestPoint(_grabObjectStartPos);
_fadePoint = .999f;
}
// IAbsorbPresenter: delegates straight to the existing hit-buffer mechanism. e.DamageType is not
// read -- the field shield has no per-damage-type visual today; it rides along in the event for
// presentations that do vary by type (the mask itself is absorb-capability data, out of scope here).
public void Absorb(AbsorbEvent e) => AddHit(e.Position, e.Direction, e.Magnitude);
// IGrabPresenter: only the Started phase does anything today. FieldDriver still times the
// extend/envelop/pull animation itself (TendrilPhase above, driven by GrabExtendTime/
// GrabEnvelopTime/GrabPullTime) because no capability yet publishes those phase transitions;
// once one does, this is where FieldDriver would react to Envelop/Pull/Completed/Cancelled too.
public void Grab(GrabEvent e, Transform target, Vector3 initialVelocity)
// IGrabPresenter: the simulation owns the grab; this draws the tendril from the events alone. Started records
// where the item is held and where the tendril leaves the field; Extend, Envelop and Pull set the phase and
// restart the real-time phase clock over the event's duration (it clamps at 1 until the next event, so a
// slowed simulation stretches the wait, not the animation); Completed and Cancelled end it.
public void Grab(GrabEvent e)
{
if (e.Phase == GrabPhase.Started && target != null)
GrabObject(target, initialVelocity);
switch (e.Phase)
{
case GrabPhase.Started:
_grabbing = true;
_grabPhase = GrabPhase.Started;
_grabStart = e.TargetPosition.ToUnity();
_tendrilBasePos = _grabStartTendrilBase = _collider.ClosestPoint(_grabStart);
_tendrilTargetPos = _grabStart;
_fadePoint = .999f;
break;
case GrabPhase.Extend:
case GrabPhase.Envelop:
case GrabPhase.Pull:
if (!_grabbing) break;
_grabPhase = e.Phase;
_grabTime = 0;
_phaseDuration = e.PhaseDuration;
break;
case GrabPhase.Completed:
case GrabPhase.Cancelled:
_grabbing = false;
_field.SetFloat("_TendrilInfluence", 0);
break;
}
}
// IMeleePresenter: the field shield's swing shape comes from its own authored curves
@ -277,74 +270,47 @@ public class FieldDriver : MonoBehaviour, IAbsorbPresenter, IGrabPresenter, IMel
}
if(_grabObject != null)
if (_grabbing && _grabPhase != GrabPhase.Started)
{
_grabTime += Time.deltaTime / _grabPhase switch
_grabTime = min(1, _grabTime + Time.deltaTime / max(_phaseDuration, 1e-4f));
_tendrilBasePos = damp(_tendrilBasePos.ToCultMath(), _tendrilTargetPos.ToCultMath(), TendrilBaseDamping, Time.deltaTime).ToUnity();
switch (_grabPhase)
{
TendrilPhase.Extend => GrabExtendTime,
TendrilPhase.Envelop => GrabEnvelopTime,
TendrilPhase.Pull => GrabPullTime,
_ => throw new ArgumentOutOfRangeException()
};
if (_grabTime > 1)
{
_grabTime = 0;
if (_grabPhase == TendrilPhase.Envelop)
{
_grabObjectEndPos = _grabObject.position;
}
if (_grabPhase == TendrilPhase.Pull)
{
Destroy(_grabObject.gameObject);
_grabObject = null;
_field.SetFloat("_TendrilInfluence", 0);
}
else _grabPhase++;
}
if (_grabObject != null)
{
_tendrilBasePos = damp(_tendrilBasePos.ToCultMath(), _grabObject.position.ToCultMath(), TendrilBaseDamping, Time.deltaTime).ToUnity();
switch (_grabPhase)
{
case TendrilPhase.Extend:
_tendrilBendTarget = _grabObjectStartPos;
_grabObject.position += _grabObjectVelocity * Time.deltaTime;
_tendrilTargetPos = lerp(
lerp(_grabObjectStartTendrilBasePos.ToCultMath(), _grabObjectStartPos.ToCultMath(), _grabTime),
lerp(_grabObjectStartPos.ToCultMath(), _grabObject.position.ToCultMath(), _grabTime),
pow(_grabTime, TendrilExtensionExponent)).ToUnity();
_field.SetFloat("_TendrilInfluence", pow(_grabTime, TendrilExtendBaseAnimationExponent));
_field.SetFloat("_TendrilSize", lerp(TendrilBaseRadius/2,TendrilBaseRadius,pow(_grabTime, TendrilExtendBaseAnimationExponent)));
_field.SetFloat("_TendrilRadius", _grabObjectScale * pow(_grabTime, TendrilTipRadiusAnimationExponent) * TendrilTipRadius);
break;
case TendrilPhase.Envelop:
_tendrilBendTarget = _grabObjectStartPos;
_tendrilTargetPos = _grabObject.position += _grabObjectVelocity * Time.deltaTime * (1-_grabTime);
_field.SetFloat("_TendrilInfluence", 1);
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", _grabObjectScale * TendrilTipRadius);
break;
case TendrilPhase.Pull:
_tendrilTargetPos = _grabObject.position = lerp(_grabObjectEndPos.ToCultMath(), transform.position.ToCultMath(), _grabTime*_grabTime).ToUnity();
_tendrilBendTarget = lerp(_grabObjectStartPos.ToCultMath(), _grabObjectEndPos.ToCultMath(), _grabTime*_grabTime).ToUnity();
if (_fadePoint > .99 && transform.InverseTransformPoint(_grabObject.position).sqrMagnitude < 1)
_fadePoint = _grabTime;
_field.SetFloat("_TendrilInfluence", pow(smoothstep(1, _fadePoint, _grabTime), TendrilFadeExponent));
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", _grabObjectScale * TendrilTipRadius);
break;
default:
throw new ArgumentOutOfRangeException();
}
var tendrilRadii = EnvelopeRadiiOrFallback();
_field.SetVector("_TendrilBase", Vector3.Scale(transform.InverseTransformPoint(_tendrilBasePos).normalized, tendrilRadii));
_field.SetVector("_TendrilBend", Vector3.Scale(transform.InverseTransformPoint(_tendrilBendTarget), tendrilRadii));
_field.SetVector("_TendrilTarget", Vector3.Scale(transform.InverseTransformPoint(_tendrilTargetPos), tendrilRadii));
case GrabPhase.Extend:
_tendrilBendTarget = _grabStart;
_tendrilTargetPos = lerp(
lerp(_grabStartTendrilBase.ToCultMath(), _grabStart.ToCultMath(), _grabTime),
_grabStart.ToCultMath(),
pow(_grabTime, TendrilExtensionExponent)).ToUnity();
_field.SetFloat("_TendrilInfluence", pow(_grabTime, TendrilExtendBaseAnimationExponent));
_field.SetFloat("_TendrilSize", lerp(TendrilBaseRadius/2,TendrilBaseRadius,pow(_grabTime, TendrilExtendBaseAnimationExponent)));
_field.SetFloat("_TendrilRadius", TendrilTipScale * pow(_grabTime, TendrilTipRadiusAnimationExponent) * TendrilTipRadius);
break;
case GrabPhase.Envelop:
_tendrilBendTarget = _grabStart;
_tendrilTargetPos = _grabStart;
_field.SetFloat("_TendrilInfluence", 1);
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", TendrilTipScale * TendrilTipRadius);
break;
case GrabPhase.Pull:
// The curve of Zone's held pose (Zone.HeldPull): the tip rides the item the simulation pulls in.
_tendrilTargetPos = lerp(_grabStart.ToCultMath(), transform.position.ToCultMath(), Zone.HeldPull(_grabTime)).ToUnity();
_tendrilBendTarget = _grabStart;
if (_fadePoint > .99 && transform.InverseTransformPoint(_tendrilTargetPos).sqrMagnitude < 1)
_fadePoint = _grabTime;
_field.SetFloat("_TendrilInfluence", pow(smoothstep(1, _fadePoint, _grabTime), TendrilFadeExponent));
_field.SetFloat("_TendrilSize", TendrilBaseRadius);
_field.SetFloat("_TendrilRadius", TendrilTipScale * TendrilTipRadius);
break;
}
var tendrilRadii = EnvelopeRadiiOrFallback();
_field.SetVector("_TendrilBase", Vector3.Scale(transform.InverseTransformPoint(_tendrilBasePos).normalized, tendrilRadii));
_field.SetVector("_TendrilBend", Vector3.Scale(transform.InverseTransformPoint(_tendrilBendTarget), tendrilRadii));
_field.SetVector("_TendrilTarget", Vector3.Scale(transform.InverseTransformPoint(_tendrilTargetPos), tendrilRadii));
}
}
private float almostIdentity( float x )
{
return x*x*(2.0f-x);
@ -358,7 +324,7 @@ public class FieldDriver : MonoBehaviour, IAbsorbPresenter, IGrabPresenter, IMel
private const int GIZMO_STEPS = 16;
private void OnDrawGizmosSelected()
{
if (_grabObject != null)
if (_grabbing)
{
Vector3 previous = _tendrilBasePos;
for (int i = 1; i <= GIZMO_STEPS; i++)

View file

@ -11,14 +11,10 @@ using UnityEngine;
public class GameSettings : ScriptableObject
{
public string StartingHullName = "Longinus";
public float PickupLifetime = 30;
public float LootDropProbability = .25f;
public float LootDropVelocity = 25;
public float HeatstrokePhasingFloor = 0;
public float HeatstrokePhasingFrequency = 5;
public float WormholeDistanceRatio;
public float DefaultViewDistance;
public float MinimapZoneGravityRange;
public float[] MinimapZoomLevels;
public int DefaultMinimapZoom;
public ExponentialCurve IconSize;

View file

@ -1,51 +0,0 @@
using System;
using CultMath;
using CultMath.UnityBridge;
using UnityEngine;
using static CultMath.math;
using Random = UnityEngine.Random;
public class GridObject : MonoBehaviour
{
public float RotationSpeed;
public float GridOffset;
public float GridAttraction;
public float Gravity;
public float Drag = .1f;
public float LaunchDrag;
private float2 _selfVelocity;
private float _timeOffset;
public Zone Zone { get; set; }
public Vector3 Velocity { get; set; }
private void Start()
{
_timeOffset = Random.value * 100;
}
void Update()
{
var t = transform;
t.localRotation = Quaternion.Euler(sin(Time.time - _timeOffset * RotationSpeed) * 90, 0, cos(Time.time - _timeOffset * RotationSpeed) * 90);
if (Zone == null) return;
var position = t.position;
var gridHeight = Zone.GetHeight(position.Flatland().ToCultMath()) + GridOffset;
Velocity += Vector3.up * (sign(gridHeight - position.y) * GridAttraction * Time.deltaTime);
Velocity *= max(0, 1 - LaunchDrag * Time.deltaTime);
var normal = Zone.GetNormal(position.Flatland().ToCultMath());
var force = new float2(normal.x, normal.z);
var forceMagnitude = lengthsq(force);
if (forceMagnitude > .001f)
{
var fa = 1 / (1 - forceMagnitude) - 1;
_selfVelocity += normalize(force) * Zone.Settings.GravityStrength * fa * Gravity;
}
_selfVelocity *= max(0, 1 - Drag * Time.deltaTime);
t.position = position + (Velocity + new Vector3(_selfVelocity.x, 0, _selfVelocity.y)) * Time.deltaTime;
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 737f47c158214f0995ba2835f040ed96
timeCreated: 1618441439

View file

@ -1,17 +1,12 @@
using UnityEngine;
using CultMath.UnityBridge;
// Cut 4 (docs/fire-control-cut.md): Hit, Splash, SendHit and SendSplash are deleted -- their last callers
// (ConstantLaser, ConstantLightning, ConstantParticleWeapon, HitscanEffect) are gone too (see those
// files and FireControl.Detonate, 12.4(b)'s renamed Splash). Nothing decides or applies damage through a Unity
// collider any more (R8):
// this component is now purely a physics surface for ship-on-ship collision impulse, not hit detection.
// collider any more (R8), and no collision callback writes an Entity (cut sim-contact): ship contact is
// Zone's, through Contacts.Step. This component holds the hull's collider for authoring, smokes and click
// picking, and writes nothing.
public class HullCollider : MonoBehaviour
{
public Entity Entity { get; set; }
private void OnCollisionEnter(Collision other)
{
Entity.Velocity += other.impulse.ToCultMath().xz / Time.deltaTime;
}
}

View file

@ -0,0 +1,39 @@
using Cinemachine;
using UnityEngine;
// Presentation tuning for landed impacts (ImpactPresenter reads it, nothing in the simulation does): the hull
// reaction's effect prefab and size, how strongly a hit's share of the hull reads (Feedback.Cue's intensityScale),
// and the camera impulse. A scene component, so the scene is where it is tuned; absent in menus and test scenes,
// where ImpactPresenter does nothing.
public class ImpactFeedback : MonoBehaviour
{
public static ImpactFeedback Instance { get; private set; }
// A scene instance of a pooled hit effect (Prototype); a hit spawns one under the struck EntityInstance.
public Prototype HullEffect;
// Multiplies a hit's share of the receiver's max durability before it saturates to 0..1 (Feedback.Cue).
public float IntensityScale = 10f;
// The effect's scale never drops below this, so the lightest hit still reads.
public float MinEffectScale = .3f;
public CinemachineImpulseDefinition Impulse = new CinemachineImpulseDefinition();
// Impulses raised since the scene loaded; the batchmode smoke reads it.
public int KicksRaised { get; private set; }
private void Awake() => Instance = this;
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
// Raises one camera impulse of the given force, travelling along `direction` from `position`.
public void Kick(Vector3 position, Vector3 direction, float force)
{
KicksRaised++;
Impulse.CreateEvent(position, direction.normalized * force);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bfdc38a81d00b0347bb55ad6469535ff

View file

@ -0,0 +1,48 @@
using System.Collections.Generic;
using CultMath.UnityBridge;
using UnityEngine;
// How one entity's landed impacts look and feel: the hull reaction at the drawn impact point, and the player's camera
// kick. The simulation publishes each impact once on the entity's Capabilities (FireControl); Feedback.Cue decides how
// hard it reads and whether the camera feels it, DrawAhead.Carried decides where it is drawn; this decides nothing.
// The hull effect is drawn only where the player's instruments place the ship (ActionGameManager.DrawsAt).
// The shield ripple is ShieldManager's. Everything here is display-only and runs in real time.
public class ImpactPresenter : MonoBehaviour, IAbsorbPresenter
{
public Entity Entity;
private readonly List<Prototype> _live = new List<Prototype>();
public void Absorb(AbsorbEvent e)
{
var feedback = ImpactFeedback.Instance;
if (feedback == null || Entity == null) return;
var manager = ActionGameManager.Instance;
var cue = Feedback.Cue(e, Entity.EquippedHull.Data.Durability,
manager != null && Entity == manager.CurrentEntity,
ActionGameManager.PlayerSettings.GraphicsSettings.ScreenShake, feedback.IntensityScale);
var point = DrawAhead.Carried(Entity, cue.Position, ActionGameManager.Clock.Lead).ToUnity();
if (e.Layer == AbsorbLayer.Hull && feedback.HullEffect != null && ActionGameManager.DrawsAt(Entity))
{
_live.RemoveAll(live => live == null || !live.gameObject.activeSelf);
var effect = feedback.HullEffect.Instantiate<Prototype>();
var size = Mathf.Max(feedback.MinEffectScale, cue.Intensity);
effect.transform.SetParent(transform, false);
effect.transform.position = point;
effect.transform.localScale = Vector3.one * (size / Mathf.Max(transform.lossyScale.x, 1e-3f));
_live.Add(effect);
}
if (cue.Shake > 0f)
feedback.Kick(point, new Vector3(cue.Direction.x, 0f, cue.Direction.z), cue.Shake);
}
// A live effect is a pooled child of this instance; hand it back before the instance takes it down with it.
private void OnDestroy()
{
foreach (var live in _live)
if (live != null && live.gameObject.activeSelf) live.ReturnToPool();
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 775c61f785344d54b9f41ad3328cecee

View file

@ -4,9 +4,14 @@ using CultMath;
using CultMath.UnityBridge;
using UnityEngine;
using static CultMath.math;
using Random = UnityEngine.Random;
// How one floating item looks. Zone owns the item's every fact (existence, position, expiry, pickup); once bound,
// this reads the latest sim body and draws, spun for show, and writes nothing back (rulings unity-presents-only-r3
// and sim-speed-presentation). An unbound pickup (FieldTester's test scene) leaves its transform alone.
public class ItemPickup : MonoBehaviour
{
public float RotationSpeed = 1f;
public float LabelFadeDuration = .5f;
public float LabelPersistDuration = 3;
public float LabelDisplayAngle = 15;
@ -15,28 +20,51 @@ public class ItemPickup : MonoBehaviour
public TextMeshPro ScanLabel;
public ItemInstance Item { get; set; }
public ZoneRenderer ZoneRenderer { get; set; }
public float3 ViewOrigin { get; set; }
public float3 ViewDirection { get; set; }
private float _displayTime;
private float _timeOffset;
private Zone _zone;
private GameplaySettings _settings;
private FloatingItem _floating;
public void Bind(Zone zone, FloatingItem floating, GameplaySettings settings)
{
_zone = zone;
_settings = settings;
_floating = floating;
Item = floating.Item;
_timeOffset = Random.value * 100;
Place();
}
private void Place()
{
var lead = ActionGameManager.Clock.Lead;
var p = DrawAhead.Position(_floating.Body, lead);
transform.position = new Vector3(p.x, DrawAhead.FloaterHeight(_zone, _settings, p, lead), p.y);
}
private void Update()
{
if (_floating != null)
{
Place();
transform.localRotation = Quaternion.Euler(
sin(Time.time - _timeOffset * RotationSpeed) * 90, 0, cos(Time.time - _timeOffset * RotationSpeed) * 90);
}
var diff = transform.position.ToCultMath() - ViewOrigin;
var toThis = normalize(diff);
var viewAngle = acos(dot(toThis, ViewDirection)) * Mathf.Rad2Deg;
if (length(diff) < LabelDisplayMaxDistance && viewAngle < LabelDisplayAngle)
_displayTime = Time.time;
if (_floating?.Holder != null) _displayTime = Time.time;
var targetAlpha = Time.time - _displayTime < LabelPersistDuration ? 1 : 0;
var c = ScanLabel.color;
c.a = c.a + sign(targetAlpha - c.a) * (Time.deltaTime / LabelFadeDuration);
ScanLabel.color = c;
ScanLabelContainer.rotation = Quaternion.LookRotation((-toThis).ToUnity());
}
private void OnDestroy()
{
ZoneRenderer?.DestroyLoot(this);
}
}
}

View file

@ -0,0 +1,76 @@
using CultMath;
using CultMath.UnityBridge;
using UnityEngine;
using static CultMath.math;
using Random = UnityEngine.Random;
// How one laid mine looks. Zone owns the mine's every fact (position, arming, trigger, end); this reads them and
// draws, and writes nothing back. The pose is the latest sim body, spun for show; the pulse runs in real time
// (rulings unity-presents-only-r3 and sim-speed-presentation).
public class MineInstance : MonoBehaviour
{
public MeshRenderer MeshRenderer;
public int EmissionSubmesh = 2;
public AnimationCurve EmissionCurve;
public float ActiveCycleDuration = 1f;
public float ArmedCycleDuration = .25f;
public float ActiveEmission = 100f;
public float ArmedEmission = 1000f;
public float RotationSpeed = 1f;
// The blast's particles; the effect prefab destroys itself when its particle system stops.
public GameObject HitEffect;
public float HitEffectScale = 10f;
private Zone _zone;
private GameplaySettings _settings;
private Mine _mine;
private Material _material;
private float _timeOffset;
private float _pulse;
private float _emission;
public void Bind(Zone zone, Mine mine, GameplaySettings settings)
{
_zone = zone;
_settings = settings;
_mine = mine;
_material = MeshRenderer.materials[EmissionSubmesh];
_timeOffset = Random.value * 100;
Place();
}
private void Update()
{
Place();
transform.localRotation = Quaternion.Euler(
sin(Time.time - _timeOffset * RotationSpeed) * 90, 0, cos(Time.time - _timeOffset * RotationSpeed) * 90);
// None before the mine arms, then slow while it waits and fast once its fuse is lit.
var armed = _mine.Armed(_zone.Time);
var counting = _mine.TriggeredAt != null;
var target = !armed ? 0f : counting ? ArmedEmission : ActiveEmission;
_emission = lerp(_emission, target, Time.deltaTime * 10);
_pulse = (_pulse + Time.deltaTime / (counting ? ArmedCycleDuration : ActiveCycleDuration)) % 1;
_material.SetFloat("_Emission", _emission * EmissionCurve.Evaluate(_pulse));
}
private void Place()
{
var lead = ActionGameManager.Clock.Lead;
var p = DrawAhead.Position(_mine.Body, lead);
transform.position = new Vector3(p.x, DrawAhead.FloaterHeight(_zone, _settings, p, lead), p.y);
}
// The mine left Zone.Mines, which only its blast does: show it where it was drawn last.
public void Blast()
{
var effect = Instantiate(HitEffect, transform.position, Quaternion.identity);
effect.transform.localScale = Vector3.one * HitEffectScale;
Destroy(gameObject);
}
private void OnDestroy()
{
if (_material) Destroy(_material);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 35c62f5e26769f645b1a1614a70422e1

View file

@ -5,14 +5,37 @@ using System.Linq;
using CultMath;
using CultMath.UnityBridge;
using static CultMath.math;
using UniRx;
using UnityEngine;
public class ShieldManager : MonoBehaviour
public class ShieldManager : MonoBehaviour, IAbsorbPresenter
{
public Prototype ShieldPrototype;
public float CollisionHitDuration = 3;
public Entity Entity { get; set; }
private Entity _entity;
private IDisposable _contacts;
// Ship-on-ship contact is Zone's (Contacts.Step); this shield only presents it.
public Entity Entity
{
get => _entity;
set
{
_contacts?.Dispose();
_entity = value;
_contacts = value?.Zone.Contacted.Subscribe(Present);
}
}
private void OnDestroy() => _contacts?.Dispose();
private void Present(ContactEvent contact)
{
if (contact.A != Entity && contact.B != Entity) return;
if (Entity.Shield != null && Entity.Shield.Item.Active.Value)
ShowHit(DrawAhead.Carried(Entity, float3(contact.Point.x, Entity.Position.y, contact.Point.y), ActionGameManager.Clock.Lead).ToUnity(), CollisionHitDuration);
}
private ShieldEnvelope _envelope;
private bool _loggedMissingEnvelope;
@ -29,55 +52,12 @@ public class ShieldManager : MonoBehaviour
Debug.LogWarning("ShieldManager has no ShieldEnvelope; falling back to its own transform for the hit direction.", this);
}
private void OnCollisionEnter(Collision other)
// A shot the shield took ripples it where the shot landed, drawn on the hull as it is drawn. The hull layer is
// ImpactPresenter's.
public void Absorb(AbsorbEvent e)
{
var otherShield = other.collider.GetComponent<ShieldManager>();
if (!otherShield)
{
var gridObject = other.collider.GetComponent<GridObject>();
if (gridObject)
{
var itemPickup = other.collider.GetComponent<ItemPickup>();
if (itemPickup)
{
if (Entity.CargoBays.Any(c => c.TryStore(itemPickup.Item)))
{
// TODO: Pickup notification!
Destroy(itemPickup.gameObject);
}
else
{
// TODO: Pickup failed notification!
var cp = other.GetContact(0);
gridObject.Velocity += cp.normal * 25;
Debug.Log("Attempted item pickup, but no space in cargo bay!");
}
}
else
{
Debug.Log("Shield collision occurred with grid object, but other collider isn't an item pickup!");
}
}
else
Debug.Log("Shield collision occurred, but other collider isn't a shield or a grid object!");
return;
}
var contact = other.GetContact(0);
var normal = normalize(float2(contact.normal.x, contact.normal.z));
var tangent = normal.Rotate(ItemRotation.CounterClockwise);
var v1n = dot(normal, Entity.Velocity);
var v1t = dot(tangent, Entity.Velocity);
var v2n = dot(normal, otherShield.Entity.Velocity);
//var v2t = dot(tangent, otherShield.Entity.Velocity);
var v1np = PostCollisionVelocity(v1n, Entity.Mass, v2n, otherShield.Entity.Mass);
Entity.Velocity = tangent * v1t + normal * v1np;
if(Entity.Shield != null && Entity.Shield.Item.Active.Value) ShowHit(contact.point, CollisionHitDuration);
}
private float PostCollisionVelocity(float v1, float m1, float v2, float m2)
{
return (v1 * (m1 - m2) + m2 * v2) / (m1 + m2);
if (e.Layer != AbsorbLayer.Shield || Entity == null || Entity.Shield == null || !Entity.Shield.Item.Active.Value || !ActionGameManager.DrawsAt(Entity)) return;
ShowHit(DrawAhead.Carried(Entity, e.Position, ActionGameManager.Clock.Lead).ToUnity(), CollisionHitDuration);
}
public void ShowHit(Vector3 point, float duration)

View file

@ -18,16 +18,7 @@ public class ShipInstance : EntityInstance
public int MaxParticleCount;
}
private class AetherDriveInstance
{
public AetherDrive Drive;
public ParticleSystem Particles;
public float BaseEmission;
public float BaseForce;
}
private ThrusterInstance[] _thrusters;
private AetherDriveInstance _aetherDrive;
public Ship Ship { get; private set; }
@ -47,20 +38,6 @@ public class ShipInstance : EntityInstance
return;
}
Ship = ship;
var drive = ship.GetBehavior<AetherDrive>();
if (drive != null)
{
var particles = Instantiate(EngineAssets.Load<ParticleSystem>(drive.DriveData.Particles), transform, false);
var main = particles.main;
main.customSimulationSpace = LocalSpace;
_aetherDrive = new AetherDriveInstance
{
Drive = drive,
BaseEmission = particles.emission.rateOverTimeMultiplier,
Particles = particles,
BaseForce = particles.forceOverLifetime.z.curveMultiplier
};
}
_thrusters = ship.GetBehaviors<Thruster>().Select(thruster =>
{
var effectData = (ThrusterData) thruster.Data;
@ -115,19 +92,6 @@ public class ShipInstance : EntityInstance
TractorBeam.Power = Entity.TractorPower;
TractorBeam.Direction = Entity.Aim.ToUnity();
if (_aetherDrive != null)
{
var thrust = length(_aetherDrive.Drive.ThrustDirection);
var forceOverLifetime = _aetherDrive.Particles.forceOverLifetime;
forceOverLifetime.xMultiplier = _aetherDrive.Drive.ThrustDirection.x * _aetherDrive.BaseForce;
forceOverLifetime.zMultiplier = _aetherDrive.Drive.ThrustDirection.y * _aetherDrive.BaseForce;
var emissionModule = _aetherDrive.Particles.emission;
// Cut 8 (operator ask 2026-09-19): intent (thrust) times condition -- presentation reads the
// simulation's own ratio rather than recomputing any part of it. AetherDrive.Condition is the
// equivalent of Thruster.Condition below (Torque in place of Thrust).
emissionModule.rateOverTimeMultiplier = _aetherDrive.BaseEmission * thrust * _aetherDrive.Drive.Condition;
}
foreach (var thrusterInstance in _thrusters)
{
var emissionModule = thrusterInstance.System.emission;
@ -138,6 +102,6 @@ public class ShipInstance : EntityInstance
emissionModule.rateOverTimeMultiplier = thrusterInstance.BaseEmission * thrusterInstance.Thruster.Axis * thrusterInstance.Thruster.Condition;
}
transform.rotation = Ship.Rotation.ToUnity();
transform.rotation = DrawAhead.Rotation(Ship, ActionGameManager.Clock.Lead).ToUnity();
}
}

View file

@ -1,19 +0,0 @@
using System;
using UnityEngine;
public class TimedDestroy : MonoBehaviour
{
public float Duration;
private float _startTime;
private void Start()
{
_startTime = Time.time;
}
public void Update()
{
if(Time.time - _startTime > Duration) Destroy(gameObject);
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 5d5539a23b814254b038a16f32f1d8a9
timeCreated: 1618453298

View file

@ -1,33 +1,51 @@
using System;
using UnityEngine;
using CultMath.UnityBridge;
public class TractorBeam : MonoBehaviour
// Presents the ship's grab: while the simulation holds an item, the beam looks along the ground-plane vector to the
// point the item was held from and emits at Power. Zone pulls the held item along the segment from the ship to that
// point (docs/aetheria-release-map.md L11), which is why GrabEvent.TargetPosition on Started is the exact aim and no
// pose lookup is needed. Idle, the beam turns with Direction and emits nothing. The simulation decides every grab fact.
public class TractorBeam : MonoBehaviour, IGrabPresenter
{
public ParticleSystem ParticleSystem;
public float Radius;
public float Traction;
public float Distance;
public float Power { get; set; }
public Vector3 Direction { get; set; }
private bool _grabbing;
private Vector3 _heldPoint;
private Vector3 _heldDirection;
// Cancelled can carry no position (a vanished item), so only Started is read for one.
public void Grab(GrabEvent e)
{
switch (e.Phase)
{
case GrabPhase.Started:
_grabbing = true;
_heldPoint = e.TargetPosition.ToUnity();
_heldDirection = Direction;
break;
case GrabPhase.Completed:
case GrabPhase.Cancelled:
_grabbing = false;
break;
}
}
public void Update()
{
transform.rotation = Quaternion.LookRotation(Direction);
var emission = ParticleSystem.emission;
if (Power > .01f)
var look = Direction;
if (_grabbing)
{
var objectFound = false;
foreach (var o in Physics.SphereCastAll(transform.position, Radius, Direction, Distance, 1 << 21))
{
var gridObject = o.collider.GetComponent<GridObject>();
if (gridObject == null) continue;
objectFound = true;
gridObject.Velocity += Vector3.Normalize(transform.position - gridObject.transform.position) * (Traction * Time.deltaTime);
}
emission.rateOverTimeMultiplier = objectFound ? Power : 0;
var toHeld = _heldPoint - transform.position;
toHeld.y = 0;
if (toHeld.sqrMagnitude > 1e-6f) _heldDirection = toHeld;
look = _heldDirection;
}
else emission.rateOverTimeMultiplier = 0;
transform.rotation = Quaternion.LookRotation(look);
var emission = ParticleSystem.emission;
emission.rateOverTimeMultiplier = _grabbing ? Power : 0;
}
}
}

View file

@ -87,7 +87,7 @@ public class GuidedProjectile : MonoBehaviour
// The resolution. A round that detonated (a hit, or a burst) bursts now, at the simulation's burst point when
// it has one; a round the simulation resolved without a detonation (a contact or delayed round that missed,
// one whose target is gone) just falls away, with no explosion to show.
public void Resolve(bool detonated, Vector3? point)
public void Resolve(bool detonated, Vector3? point, bool showHitEffect)
{
// A round that already faded out (overshot, out of flight) still shows the simulation's detonation: only a
// round that has been killed is done. The fade is stopped so it cannot Kill the round a second time.
@ -102,7 +102,7 @@ public class GuidedProjectile : MonoBehaviour
// short of it), and is skipped when the round never knew where its target was.
Vector3? effectAt = point ?? (TargetPosition != null ? TargetPosition() : Target ? Target.position : (Vector3?) null);
if (point.HasValue) transform.position = point.Value;
if (HitEffect != null && effectAt.HasValue)
if (HitEffect != null && showHitEffect && effectAt.HasValue)
{
var ht = HitEffect.Instantiate<Transform>();
ht.position = effectAt.Value;

View file

@ -17,7 +17,8 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
var bindings = new CompositeDisposable();
zone.ShotCommitted.Where(o => o.ShotId == shotId && o.HasBurstPoint).Subscribe(o => p.BurstAt(At(o))).AddTo(bindings);
zone.ShotResolved.Where(o => o.ShotId == shotId)
.Subscribe(o => p.Resolve(o.Result == ShotResult.Hit || o.Result == ShotResult.Burst, o.HasBurstPoint ? At(o) : (Vector3?) null))
.Subscribe(o => p.Resolve(o.Result == ShotResult.Hit || o.Result == ShotResult.Burst, o.HasBurstPoint ? At(o) : (Vector3?) null,
ActionGameManager.DrawsAt(o.Target)))
.AddTo(bindings);
// The binding outlives a fade-out until the shot's own arrival (the moment the simulation resolves it), plus a
// second of margin; a shot no longer pending has nothing left to resolve.
@ -44,7 +45,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.SourceEntity = source.Entity;
if (target != null) p.Target = target.transform;
else p.TargetPosition = () => burst;
p.Frequency = launcher.DodgeFrequency;
p.Frequency = item.Evaluate(MunitionParts.Of<MunitionControlData>(item).EvasionFrequency);
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.StartPosition = (p.transform.position = barrel.position).ToCultMath();
@ -53,8 +54,8 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.LiftCurve = launcher.LiftCurve.ToCurve();
p.ThrustCurve = launcher.ThrustCurve.ToCurve();
p.Velocity = barrel.forward * weapon.Velocity;
p.Thrust = item.Evaluate(launcher.Thrust);
p.TopSpeed = item.Evaluate(launcher.MissileVelocity);
p.Thrust = item.Evaluate(MunitionParts.Of<MunitionThrusterData>(item).Acceleration);
p.TopSpeed = item.Evaluate(MunitionParts.Of<MunitionThrusterData>(item).MaxSpeed);
Bind(p, source.Entity.Zone, shotId);
// A round with no target (a fused round fired at none) has no transform to hand a listener.
OnFireGuided.OnNext((source.Entity, target != null ? target.transform : null, p));
@ -65,7 +66,7 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.ShotId = shotId;
p.Source = source.transform;
p.SourceEntity = source.Entity;
p.Frequency = guidance.DodgeFrequency;
p.Frequency = item.Evaluate(MunitionParts.Of<MunitionControlData>(item).EvasionFrequency);
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
p.StartPosition = (p.transform.position = barrel.position).ToCultMath();
@ -74,9 +75,13 @@ public class GuidedProjectileManager : InstantWeaponEffectManager
p.LiftCurve = guidance.LiftCurve.ToCurve();
p.ThrustCurve = guidance.ThrustCurve.ToCurve();
p.Velocity = barrel.forward * weapon.Velocity;
p.Thrust = item.Evaluate(guidance.Thrust);
p.TopSpeed = item.Evaluate(guidance.MissileVelocity);
p.TargetPosition = () => (source.Entity.Position + length(source.LookAtPoint.position.ToCultMath() - source.Entity.Position) * source.Entity.Aim).ToUnity();
p.Thrust = item.Evaluate(MunitionParts.Of<MunitionThrusterData>(item).Acceleration);
p.TopSpeed = item.Evaluate(MunitionParts.Of<MunitionThrusterData>(item).MaxSpeed);
p.TargetPosition = () =>
{
var drawn = DrawAhead.Position(source.Entity, ActionGameManager.Clock.Lead);
return (drawn + length(source.LookAtPoint.position.ToCultMath() - drawn) * source.Entity.Aim).ToUnity();
};
Bind(p, source.Entity.Zone, shotId);
}
else Debug.LogError($"Weapon {item.Data.Name} linked to {name} effect, but is not a Launcher!");

View file

@ -1,59 +1,97 @@
using System.Collections;
using System;
using System.Collections;
using UniRx;
using UnityEngine;
using static CultMath.math;
// Cut 3 (docs/fire-control-cut.md): the raycast, shield branch and SendHit are deleted -- FireControl already
// decided this shot's fate before this object was ever spawned (R8). What is left is pure flight-path
// presentation: fly, and disappear at Range or ShotId's resolution, whichever comes first.
// Cut 6b, 6.2 (12.4(b): Apply's own switch on the frozen Fuse decides this now, not Step): the flak-round
// blast resolves in the simulation, through FireControl.Detonate -- a MonoBehaviour calling it would be
// exactly the authority Cut 3 spent itself deleting, so the blast-distance/blast-radius fields this object
// used to carry for that are gone. This object's job stays fly-and-disappear.
// A ballistic round, drawn by DrawAhead.Round from what the simulation publishes and deciding nothing. The simulation
// owns the round's facts (the PendingShot copy taken at spawn, replaced by the sim's record at ShotCommitted, and the
// outcome it publishes), so this object stores no motion state of its own and computes no position, time, range or
// impact point: each frame it asks DrawAhead.Round where the round is at sim time plus the clock's Lead (the same
// draw-ahead ships use). The round ends on the sim's word: ShotResolved ends one that hit or burst, and
// DrawAhead.RoundOver ends one the sim published as a miss. The barrel is only where the round is first seen: its
// offset from the drawn line decays to zero over BlendTime sim seconds. The trail's fade after the end stays real time
// (pure presentation, ruling sim-speed-presentation).
public class Projectile : MonoBehaviour
{
public TrailRenderer Trail;
public float Gravity;
public float Drag = .1f;
public Prototype HitEffect;
// Sim seconds over which the barrel's offset from the sim line decays to nothing.
public float BlendTime = .1f;
private PendingShot _shot;
private Zone _zone;
private CultMath.float3 _barrel;
private ShotOutcome _known;
private bool _alive;
private CompositeDisposable _binding;
// Cut 3: FireControl.Fire's ShotId -- this projectile's handle onto Zone.ShotCommitted/ShotResolved.
public int ShotId { get; set; }
public Zone Zone { get; set; }
public Vector3 StartPosition { get; set; }
public Vector3 Velocity { get; set; }
public Entity SourceEntity { get; set; }
public float Range { get; set; }
private void OnEnable()
// Takes the shot as the sim holds it, the zone whose sim time it is drawn at, and where the barrel is as this round is first seen.
public void Launch(Zone zone, PendingShot shot, Vector3 barrel)
{
_zone = zone;
_shot = shot;
_barrel = new CultMath.float3(barrel.x, barrel.y, barrel.z);
_known = null;
_binding?.Dispose();
_binding = new CompositeDisposable(
zone.ShotCommitted.Where(o => o.ShotId == shot.ShotId).Subscribe(Committed),
zone.ShotResolved.Where(o => o.ShotId == shot.ShotId).Subscribe(Resolve));
_alive = true;
transform.forward = new Vector3(shot.TravelDirection.x, 0, shot.TravelDirection.y);
Draw();
}
// Update is called once per frame
void Update()
{
if (SourceEntity == null) return;
if(_alive)
{
var t = transform;
Velocity -= Vector3.up * (Gravity * Time.deltaTime);
Velocity *= max(0, 1 - Drag * Time.deltaTime);
t.forward = Velocity.normalized;
transform.position += Velocity * Time.deltaTime;
var distanceTraveled = (transform.position - StartPosition).magnitude;
if(distanceTraveled > Range)
StartCoroutine(Kill());
}
if (_alive) Draw();
}
IEnumerator Kill()
private void Draw()
{
var lead = ActionGameManager.Clock.Lead;
var drawn = DrawAhead.Time(_zone, lead);
transform.position = V(DrawAhead.Round(_shot, _known, _barrel, BlendTime, drawn));
if (DrawAhead.RoundOver(_shot, _known, drawn)) Finish();
}
// The sim's commit: the record it holds now (a contact burst's arrival is shortened here) and what it decided.
private void Committed(ShotOutcome outcome)
{
if (_zone.TryGetShot(outcome.ShotId, out var record)) _shot = record;
_known = outcome;
}
// The simulation's verdict. A round that hit or burst is drawn at its end and stops; a miss keeps flying.
private void Resolve(ShotOutcome outcome)
{
if (!_alive) return;
_known = outcome;
if (outcome.Result == ShotResult.Miss) return;
Draw();
if (HitEffect != null && ActionGameManager.DrawsAt(outcome.Target)) HitEffect.Instantiate<Transform>().position = transform.position;
Finish();
}
private static Vector3 V(CultMath.float3 p) => new Vector3(p.x, p.y, p.z);
private void Finish()
{
_alive = false;
_binding?.Dispose();
_binding = null;
StartCoroutine(Fade());
}
void OnDisable()
{
_alive = false;
_binding?.Dispose();
_binding = null;
}
IEnumerator Fade()
{
var startTime = Time.time;
var lifetime = Trail.time;
while (Time.time - startTime < lifetime)

View file

@ -1,32 +1,17 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
using UnityEngine;
public class ProjectileManager : InstantWeaponEffectManager
{
public Prototype ProjectilePrototype;
public bool InheritVelocity;
// The round is drawn by DrawAhead from what the simulation publishes, so there is nothing to aim, jitter
// or inherit here: spread is priced by FireControl, and the sim's round inherits nothing from its shooter.
public override void Fire(InstantWeapon weapon, EquippedItem item, EntityInstance source, EntityInstance target, int shotId)
{
var zone = source.Entity.Zone;
if (!zone.TryGetShot(shotId, out var shot)) return;
var p = ProjectilePrototype.Instantiate<Projectile>();
var hp = item.Hardpoint;
var barrel = source.GetBarrel(hp);
var angle = weapon.Spread / 2;
p.ShotId = shotId;
p.SourceEntity = source.Entity;
p.Velocity = Quaternion.Euler(
Random.Range(-angle, angle),
Random.Range(-angle, angle),
Random.Range(-angle, angle)) *
barrel.forward *
weapon.Velocity;
p.StartPosition = p.transform.position = barrel.position + p.Velocity * (Random.value * Time.deltaTime);
if(InheritVelocity)
p.Velocity += new Vector3(source.Entity.Velocity.x, 0, source.Entity.Velocity.y);
p.Range = weapon.Range;
p.Zone = source.Entity.Zone;
p.Launch(zone, shot, source.GetBarrel(item.Hardpoint).position);
p.Trail.Clear();
}
}

View file

@ -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);
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 2022c838bbc64a0d86cfbd477e6a379c
timeCreated: 1618332827

View file

@ -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
{

View file

@ -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;
}
}

View file

@ -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

View file

@ -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;
}

View 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;
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: be58ee6eb8c74ea89518ee8200add0ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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)
{

View 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;
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5b0e1f6c2d7a4e39a8c4d1f27e6b3a90
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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);
}
}

View 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();
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6d4eac117ca042aaba71d1f6491b4617
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View 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));
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ac7678d240564331be7486588d28c5ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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()

View file

@ -94,8 +94,6 @@ public class Reactor : Behavior
Draw = 0;
}
Item.SetAudioParameter(SpecialAudioParameter.Intensity, max(.25f, 1 - 1 / CurrentLoadRatio));
AddHeat(heat);
return true;
}

View file

@ -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;
}

View 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;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bf9e034c7a31410ea1c516f46b43825c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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

View file

@ -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();

View file

@ -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]

View 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;
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 558ff9ad01ba4fd4987d5e6ba4f31e4d

View file

@ -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;

View file

@ -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

View 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;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 961a74683c574807a300eb26694f206d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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;
}
}

View file

@ -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);

View file

@ -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>();

View 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));
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7c1e5a3b9d4f4e2a8b6c0d1f2e3a4b5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View 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;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 007fe4255cd84c26a010151a399f45c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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;
}

View file

@ -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;

View file

@ -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,

View file

@ -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;

View 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);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 51efa531176e4871835ae88104c92c85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -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

View file

@ -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;
}

View 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);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8105a45840c4552459aaf44e6c0e19ce

Some files were not shown because too many files have changed in this diff Show more