Actuated assemblies in the hull record: AssemblyData, root anchor, judge

HullData key 34 Assemblies holds each assembly's region, pivot, yaw limits and
slew (rulings actuated-assemblies-are-their-own-kind, assembly-slew-hull-authored).
Membership is derived (Assemblies.Of), never stored. The judge refuses bad ids,
regions outside the hull or overlapping, straddling hardpoints, bad pivot, limits
or slew, and a missing or short assembly-root anchor. RigChains gains the
assembly-root actuator: a member's chain may pass its own root joint and no other
driven joint (ruling one-joint-one-driver). HullLike drops assemblies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 00:43:09 +01:00
commit f376a58d18
5 changed files with 425 additions and 25 deletions

View file

@ -561,10 +561,15 @@ public class HullData : EquippableItemData
// What a station hull is built to be (StationKinds): set on every Station hull and on no other. The hull names its kind
// and the kind names no hull, so a package can add a faction's model of a kind without editing any kind record.
// Key 33 is the next free key.
[Inspectable, JsonProperty("kind"), Key(33)]
public CultRecordRef<StationKindData> Kind;
// The hull's actuated assemblies (ruling actuated-assemblies-are-their-own-kind): each a region of cells with its
// hinge, yaw limits and slew, authored with the hull. A hardpoint's membership is derived (Assemblies.Of), never
// stored. Key 35 is the next free key.
[Inspectable, JsonProperty("assemblies"), Key(34)]
public List<AssemblyData> Assemblies = new List<AssemblyData>();
// The farthest corner of any occupied hull cell from the centre of mass the schematic frame uses, in world
// units: a true bound on how far the hull reaches from its position (the half-diagonal of the bounding box is not,
// as FireControl.Detonate's comment records). A cell at (x, y) spans x +/- .5 and y +/- .5.
@ -661,6 +666,29 @@ public class HardpointData
[Key(8)] [CultElementId] public string Id = "";
}
// An actuated assembly: a region of the hull's cells that turns about a hinge (ruling actuated-assemblies-are-their-own-kind).
// It is its own kind, not a field of HardpointData: the members' own mounts, arcs and gimbals are unchanged and compose
// on top of the assembly's pose. The slew is the hull's (ruling assembly-slew-hull-authored), never a gear stat. Which
// hardpoints are members is derived from the region (Assemblies.Of); the rig's assembly-root anchor only draws the joint.
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class AssemblyData
{
// The label: unique in the hull, and the Id of the assembly-root anchor that draws it.
[Inspectable, JsonProperty("id"), Key(0)] public string Id;
[Inspectable, JsonProperty("position"), Key(1)] public int2 Position;
[Inspectable, JsonProperty("shape"), Key(2)] public Shape Shape = new Shape();
// The hinge in cell space. The schematic and the model are separate spaces, so it is authored, never derived from the model.
[Inspectable, JsonProperty("pivot"), Key(3)] public float2 Pivot;
// Degrees of yaw from the authored layout: Min <= 0 <= Max, and the span is at most a turn.
[Inspectable, JsonProperty("min"), Key(4)] public float Min;
[Inspectable, JsonProperty("max"), Key(5)] public float Max;
// Degrees per second, above 0.
[Inspectable, JsonProperty("slew"), Key(6)] public float Slew;
// Element identity, derived from the assembly id so it never changes across rewrites.
[Key(7)] [CultElementId(nameof(Id))] public string ElementId = "";
}
// What a PerformanceStat reads to resolve one number: the lot it prices quality against, and the per-context
// factors that used to be three separate Evaluate bodies. EquippedItem, ConsumableItemEffect and the
// unequipped case (ItemManager's own private context) are the three implementations; each supplies only the

View file

@ -6,6 +6,7 @@ using System.Reflection;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using int2 = CultMath.int2;
// A mod ship's visual package: model, anchors, schematic lines. The hull semantics (cells, hardpoints, stats) live in
// the ship's own HullData record beside this one, and HullData.Visual is the only binding between the two.
@ -44,7 +45,7 @@ public sealed class ShipAnchor
// Stable semantic identity. HullData.Hardpoints[].Transform names this ID for mounts.
[Key(0)] public string Id;
// One of: map-icon, hull-collider, shield, tractor, thruster-emitter, weapon-mount,
// weapon-muzzle, or radiator-mesh.
// weapon-muzzle, radiator-mesh, or assembly-root.
[Key(1)] public string Role;
// Stable node ID in the compiled model, never a Blender display name.
[Key(2)] public string ModelNodeId;
@ -80,7 +81,7 @@ public static class ShipAuthoringStore
// ShipAnchor.Role's vocabulary.
private static readonly HashSet<string> Roles = new HashSet<string>(StringComparer.Ordinal)
{
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh"
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh", "assembly-root"
};
// The anchor role a visible hardpoint's mount plays, or null for an internal hardpoint, which has no anchor.
@ -120,9 +121,9 @@ public static class ShipAuthoringStore
cache.UpsertAsync(typeof(FactionProductData), product, ShipModCatalog.ProductKey(shipId, product.Manufacturer.Key)).GetAwaiter().GetResult();
// A new mod hull that flies like a shipped one. Every member of the reference is copied through the type's own
// MessagePack round trip, so a member added to HullData later is copied too; then the seven that are the shipped ship's
// own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Prefab, Schematic, Kind,
// and Visual, which names this mod's visual record.
// MessagePack round trip, so a member added to HullData later is copied too; then the eight that are the shipped ship's
// own body and layout are reset: Name, Shape (one occupied cell, so the record loads), Hardpoints, Assemblies, Prefab,
// Schematic, Kind, and Visual, which names this mod's visual record.
public static HullData HullLike(HullData reference, string name, string shipId)
{
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly);
@ -130,6 +131,7 @@ public static class ShipAuthoringStore
hull.Name = name;
hull.Shape = new Shape();
hull.Hardpoints = new List<HardpointData>();
hull.Assemblies = new List<AssemblyData>();
hull.Prefab = null;
hull.Schematic = null;
// A station's kind is its own fact, written by ship-authoring kind; a like hull's is never copied.
@ -362,13 +364,14 @@ public static class ShipAuthoringStore
if (!(lead.FiringArc > 0f))
throw new InvalidOperationException($"{ship.Id}: thruster row {row.Key} must state a gimbal FiringArc above 0.");
}
ValidateAssemblies(hull, ship, anchors);
foreach (var anchor in anchors)
{
if (!string.IsNullOrEmpty(anchor.ParentId) && !mounts.ContainsKey(anchor.ParentId))
throw new InvalidOperationException($"{ship.Id}: anchor {anchor.Id} has unknown hardpoint parent {anchor.ParentId}.");
// A mount-role anchor is the mount of a hardpoint of its type, never a loose node. The hardpoint loop above has
// already refused one whose id names a hardpoint of another type, so here it only has to name a hardpoint.
if ((RigChains.Actuates(anchor.Role) || anchor.Role == "radiator-mesh") && !mounts.ContainsKey(anchor.Id))
if ((RigChains.Actuates(anchor.Role) && anchor.Role != "assembly-root" || anchor.Role == "radiator-mesh") && !mounts.ContainsKey(anchor.Id))
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} must be the mount of a hardpoint of its type.");
if (anchor.Role == "weapon-muzzle" &&
(string.IsNullOrEmpty(anchor.ParentId) || !IsWeapon(mounts[anchor.ParentId].Type)))
@ -377,7 +380,7 @@ public static class ShipAuthoringStore
foreach (var hardpoint in mounts.Values.Where(hardpoint => IsWeapon(hardpoint.Type)))
if (!anchors.Any(anchor => anchor.Role == "weapon-muzzle" && anchor.ParentId == hardpoint.Transform))
throw new InvalidOperationException($"{ship.Id}: weapon hardpoint {hardpoint.Transform} needs at least one muzzle anchor.");
ValidateRig(ship, anchors, mounts, nodeIds);
ValidateRig(hull, ship, anchors, mounts, nodeIds);
foreach (var line in ship.SchematicLines ?? new List<ShipPolyline>())
{
@ -398,12 +401,58 @@ public static class ShipAuthoringStore
}
}
// The assembly rules (ruling actuated-assemblies-are-their-own-kind): the one judge of HullData.Assemblies. The rig side,
// that a root's joint reaches its arc and that members' chains pass only their own root joint, is ValidateRig's.
private static void ValidateAssemblies(HullData hull, ShipAuthoring ship, List<ShipAnchor> anchors)
{
var assemblies = hull.Assemblies ?? new List<AssemblyData>();
var owner = new Dictionary<(int x, int y), string>();
var ids = new HashSet<string>(StringComparer.Ordinal);
foreach (var assembly in assemblies)
{
if (assembly == null || string.IsNullOrWhiteSpace(assembly.Id) || !ids.Add(assembly.Id))
throw new InvalidOperationException($"{ship.Id}: assembly IDs must be present and unique.");
if (assembly.Shape?.Cells == null || !assembly.Shape.Cells.Cast<bool>().Any(occupied => occupied))
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} has no cells.");
foreach (var cell in Assemblies.Cells(assembly.Position, assembly.Shape))
{
if (cell.x < 0 || cell.y < 0 || cell.x >= hull.Shape.Width || cell.y >= hull.Shape.Height || !hull.Shape.Cells[cell.x, cell.y])
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} lies outside the hull schematic.");
if (owner.TryGetValue(cell, out var other))
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} overlaps assembly {other}.");
owner.Add(cell, assembly.Id);
}
if (!float.IsFinite(assembly.Pivot.x) || !float.IsFinite(assembly.Pivot.y))
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} pivot must be finite.");
if (!float.IsFinite(assembly.Min) || !float.IsFinite(assembly.Max) || assembly.Min > 0f || assembly.Max < 0f)
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} yaw limits must be finite with Min <= 0 <= Max.");
if (!(assembly.Max - assembly.Min > 0f) || assembly.Max - assembly.Min > 360f)
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} yaw span must be above 0 and at most 360 degrees.");
if (!float.IsFinite(assembly.Slew) || !(assembly.Slew > 0f))
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} slew must be finite and above 0.");
var root = anchors.FirstOrDefault(anchor => anchor.Role == "assembly-root" && anchor.Id == assembly.Id);
if (root == null)
throw new InvalidOperationException($"{ship.Id}: assembly {assembly.Id} needs an assembly-root anchor of that id.");
if (string.IsNullOrEmpty(root.Joint))
throw new InvalidOperationException($"{ship.Id}: assembly-root anchor {root.Id} must name a joint.");
}
foreach (var anchor in anchors.Where(anchor => anchor.Role == "assembly-root"))
if (!ids.Contains(anchor.Id))
throw new InvalidOperationException($"{ship.Id}: assembly-root anchor {anchor.Id} must be the root of an assembly of that id.");
foreach (var hardpoint in hull.Hardpoints ?? new List<HardpointData>())
{
var homes = Assemblies.Cells(hardpoint.Position, hardpoint.Shape).Select(cell => owner.TryGetValue(cell, out var id) ? id : null).Distinct().ToArray();
if (homes.Length > 1)
throw new InvalidOperationException($"{ship.Id}: hardpoint {hardpoint.Transform} straddles the edge of an assembly.");
}
}
// A degree of freedom counts as yaw when its axis lies within 5 degrees of Ship Root up (glTF +Y).
private static readonly float YawAxisCos = MathF.Cos(5f * MathF.PI / 180f);
// The joints, which anchors ride them, and whether each driven joint's chain can sweep the arc its guns state. The
// joints are presentation, so this judges only that the rig could point the gun where the hardpoint says it may fire.
private static void ValidateRig(ShipAuthoring ship, List<ShipAnchor> anchors, Dictionary<string, HardpointData> mounts, HashSet<string> nodeIds)
private static void ValidateRig(HullData hull, ShipAuthoring ship, List<ShipAnchor> anchors, Dictionary<string, HardpointData> mounts, HashSet<string> nodeIds)
{
var joints = ship.Joints ?? new List<ShipJoint>();
var byId = new Dictionary<string, ShipJoint>(StringComparer.Ordinal);
@ -450,29 +499,41 @@ public static class ShipAuthoringStore
if (anchor.Role == "radiator-mesh")
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} may not ride a joint.");
if (!RigChains.Actuates(anchor.Role))
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} may not name a joint; only a weapon mount or a thruster emitter rides one.");
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} may not name a joint; only a weapon mount, a thruster emitter or an assembly root rides one.");
if (!byId.ContainsKey(anchor.Joint))
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} names an unknown joint.");
}
// A joint has one actuator (ruling one-joint-one-actuator), and RigChains.Drives is the only place that says what drives a
// joint: a joint carrying two actuators, or whose reach passes through a joint another actuator drives, is refused here,
// whatever the two actuators are.
var drives = RigChains.Drives(ship).Select(drive => (drive.Joint, Hardpoint: mounts[drive.Anchor.Id])).ToArray();
foreach (var onJoint in drives.GroupBy(drive => drive.Joint, StringComparer.Ordinal))
// A joint has one driver (ruling one-joint-one-driver): a member's own mount, or the assembly whose root it is.
// RigChains.Drives is the only place that says what drives a joint: a joint carrying two actuators, or whose reach
// passes through a joint another actuator drives, is refused here, whatever the two actuators are. The one
// exception is a member whose chain passes through its own assembly's root joint, which the assembly drives.
var all = RigChains.Drives(ship).ToArray();
string ActuatorOf(ShipAnchor anchor) => anchor.Role == "assembly-root" ? RigChains.Actuator(anchor) : RigChains.Actuator(mounts[anchor.Id]);
foreach (var onJoint in all.GroupBy(drive => drive.Joint, StringComparer.Ordinal))
{
var lead = onJoint.First().Hardpoint;
var other = onJoint.Select(drive => drive.Hardpoint).FirstOrDefault(hardpoint => RigChains.Actuator(hardpoint) != RigChains.Actuator(lead));
var lead = onJoint.First().Anchor;
var other = onJoint.Select(drive => drive.Anchor).FirstOrDefault(anchor => ActuatorOf(anchor) != ActuatorOf(lead));
if (other != null)
throw new InvalidOperationException($"{ship.Id}: joint {onJoint.Key} carries more than one actuator ({lead.Transform} and {other.Transform}); a joint has one actuator.");
throw new InvalidOperationException($"{ship.Id}: joint {onJoint.Key} carries more than one actuator ({lead.Id} and {other.Id}); a joint has one actuator.");
}
var driven = RigChains.Driven(ship);
foreach (var joint in driven)
foreach (var (joint, anchor) in all)
{
var through = RigChains.Chain(ship, joint).SkipLast(1).FirstOrDefault(driven.Contains);
var own = anchor.Role == "assembly-root" ? null
: Assemblies.Of(hull, mounts[anchor.Id]) is { } home ? all.FirstOrDefault(drive => drive.Anchor.Role == "assembly-root" && drive.Anchor.Id == home.Id).Joint : null;
var through = RigChains.Chain(ship, joint).SkipLast(1).FirstOrDefault(step => driven.Contains(step) && step != own);
if (through != null)
throw new InvalidOperationException($"{ship.Id}: joint {joint} reaches through joint {through}, which another actuator drives; a joint has one actuator.");
}
foreach (var (joint, anchor) in all.Where(drive => drive.Anchor.Role == "assembly-root"))
{
var assembly = hull.Assemblies.Single(candidate => candidate.Id == anchor.Id);
var reach = YawReach(ship, joint);
if (reach < assembly.Max - assembly.Min)
throw new InvalidOperationException($"{ship.Id}: joint {joint} chain reaches {reach} degrees of yaw, short of the {assembly.Max - assembly.Min} degree arc of assembly {assembly.Id}.");
}
var drives = all.Where(drive => drive.Anchor.Role != "assembly-root").Select(drive => (drive.Joint, Hardpoint: mounts[drive.Anchor.Id])).ToArray();
var ridden = drives.Where(drive => IsWeapon(drive.Hardpoint.Type)).ToArray();
foreach (var (_, hardpoint) in ridden)
@ -522,12 +583,13 @@ public static class ShipAuthoringStore
}
}
// A rig's actuators and the joints they drive. An actuator is a weapon mount or a thruster emitter that names a joint; a gun
// group (every gun on a joint) or a thruster row is one actuator, and a joint has at most one (ruling one-joint-one-actuator).
// This is the only place that says which anchors are actuators, so the judge, the binder and the plan all follow it.
// A rig's actuators and the joints they drive. An actuator is a weapon mount, a thruster emitter or an assembly root that names
// a joint; a gun group (every gun on a joint) or a thruster row is one actuator, an assembly is its own, and a joint has one
// driver (ruling one-joint-one-driver). This is the only place that says which anchors are actuators, so the judge, the binder
// and the plan all follow it.
public static class RigChains
{
public static bool Actuates(string role) => role == "weapon-mount" || role == "thruster-emitter";
public static bool Actuates(string role) => role == "weapon-mount" || role == "thruster-emitter" || role == "assembly-root";
// Every actuator anchor that names a joint, with the joint it drives.
public static IEnumerable<(string Joint, ShipAnchor Anchor)> Drives(ShipAuthoring ship) =>
@ -540,6 +602,9 @@ public static class RigChains
public static string Actuator(HardpointData hardpoint) =>
ShipAuthoringStore.IsWeapon(hardpoint.Type) ? "weapon" : string.IsNullOrEmpty(hardpoint.Row) ? "thruster:" + hardpoint.Transform : "row:" + hardpoint.Row;
// An assembly drives its root joint: its own actuator, distinct from every member's (ruling actuated-assemblies-are-their-own-kind).
public static string Actuator(ShipAnchor assemblyRoot) => "assembly:" + assemblyRoot.Id;
// The joint and its ancestors, root-first. The judge refuses a driven joint whose ancestors another actuator drives,
// so for an accepted ship this is the whole chain the actuator's reach is summed over.
public static string[] Chain(ShipAuthoring ship, string jointId)
@ -552,3 +617,27 @@ public static class RigChains
return chain.ToArray();
}
}
// Which hardpoints belong to which assembly. Membership is derived, never stored (ruling actuated-assemblies-are-their-own-kind):
// a hardpoint belongs to the assembly whose region holds every one of its cells.
public static class Assemblies
{
// The hull cells a placed shape occupies.
public static IEnumerable<(int x, int y)> Cells(int2 position, Shape shape)
{
for (var x = 0; x < shape.Width; x++)
for (var y = 0; y < shape.Height; y++)
if (shape.Cells[x, y]) yield return (position.x + x, position.y + y);
}
// The assembly holding the whole hardpoint, or null for one outside every assembly (the judge refuses a straddling one).
public static AssemblyData Of(HullData hull, HardpointData hardpoint)
{
var cells = Cells(hardpoint.Position, hardpoint.Shape).ToArray();
return cells.Length == 0 ? null : (hull.Assemblies ?? new List<AssemblyData>()).FirstOrDefault(assembly =>
{
var region = new HashSet<(int x, int y)>(Cells(assembly.Position, assembly.Shape));
return cells.All(region.Contains);
});
}
}

View file

@ -485,7 +485,7 @@ public static class ShipModCatalog
if (string.Equals(above ?? "", anchor.Joint ?? "", StringComparison.Ordinal)) continue;
throw new InvalidOperationException(anchor.Role == "radiator-mesh"
? $"{ship.Id}: {anchor.Role} anchor {anchor.Id} sits under a joint in the model."
: $"{ship.Id}: {(anchor.Role == "weapon-mount" ? "weapon mount" : "thruster emitter")} {anchor.Id} must name the nearest joint above its model node as its Joint.");
: $"{ship.Id}: {(anchor.Role == "weapon-mount" ? "weapon mount" : anchor.Role == "assembly-root" ? "assembly root" : "thruster emitter")} {anchor.Id} must name the nearest joint above its model node as its Joint.");
}
}

View file

@ -0,0 +1,268 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CultMath;
using Xunit;
// Actuated assemblies in the hull record (rulings actuated-assemblies-are-their-own-kind, assembly-slew-hull-authored and
// one-joint-one-driver): HullData.Assemblies is their one home and ShipAuthoringStore.Validate their one judge. Each rule
// below has the mutant it refuses; the fixture with one assembly holding a gun on its own joint and a thruster row passes.
public sealed class AssemblyTests
{
private static readonly float[] Up = { 0f, 1f, 0f };
private static ShipJoint Joint(string id, string parent, float min, float max) =>
new ShipJoint { Id = id, Parent = parent, Axes = Up, Min = new[] { min }, Max = new[] { max } };
// A 3x1 hull. Assembly "A" holds cells 0 and 1: gun g0 (cell 0) on joint gj and thruster t0 (cell 1, a row of one) on joint
// tj, both children of A's root joint "root" (yaw -90..90, the assembly's arc is -60..60). Thruster t1 (cell 2) is no member
// and rides no joint.
private static ShipParts Fixture()
{
var ship = ShipAuthoringTests.Fixture();
ship.Hull.Shape = new Shape(3, 1);
for (var x = 0; x < 3; x++) ship.Hull.Shape.Cells[x, 0] = true;
ship.Hull.Hardpoints.Clear();
ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "thruster.port");
ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Energy, Position = new int2(0, 0), Shape = new Shape(), Transform = "g0", FiringArc = 90 });
ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Thruster, Position = new int2(1, 0), Shape = new Shape(), Transform = "t0", Row = "r", FiringArc = 90 });
ship.Hull.Hardpoints.Add(new HardpointData { Type = HardpointType.Thruster, Position = new int2(2, 0), Shape = new Shape(), Transform = "t1" });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "g0", Role = "weapon-mount", ModelNodeId = "g0", Joint = "gj" });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "g0.muzzle", Role = "weapon-muzzle", ModelNodeId = "g0-muzzle", ParentId = "g0" });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "t0", Role = "thruster-emitter", ModelNodeId = "t0", Joint = "tj" });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "t1", Role = "thruster-emitter", ModelNodeId = "t1" });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "A", Role = "assembly-root", ModelNodeId = "A-root", Joint = "root" });
ship.Visual.Joints.Add(Joint("root", null, -90f, 90f));
ship.Visual.Joints.Add(Joint("gj", "root", -45f, 45f));
ship.Visual.Joints.Add(Joint("tj", "root", -45f, 45f));
var region = new Shape(2, 1);
region.Cells[0, 0] = region.Cells[1, 0] = true;
ship.Hull.Assemblies.Add(new AssemblyData { Id = "A", Position = new int2(0, 0), Shape = region, Pivot = new float2(1f, .5f), Min = -60f, Max = 60f, Slew = 30f });
return ship;
}
private static AssemblyData Only(ShipParts ship) => ship.Hull.Assemblies.Single();
private static string Refusal(ShipParts ship) => Assert.Throws<InvalidOperationException>(ship.Validate).Message;
[Fact]
public void AnAssemblyHoldingAGunOnItsOwnJointAndAThrusterRowIsValid() => Fixture().Validate();
[Fact]
public void MembershipIsDerivedFromTheRegionAndStoredNowhere()
{
var ship = Fixture();
var of = ship.Hull.Hardpoints.ToDictionary(hardpoint => hardpoint.Transform, hardpoint => Assemblies.Of(ship.Hull, hardpoint)?.Id);
Assert.Equal(("A", "A", (string)null), (of["g0"], of["t0"], of["t1"]));
Assert.Null(Assemblies.Of(new HullData { Hardpoints = ship.Hull.Hardpoints }, ship.Hull.Hardpoints[0]));
}
[Fact]
public void AssemblyIdsArePresentAndUnique()
{
var ship = Fixture();
Only(ship).Id = " ";
Assert.Contains("assembly IDs must be present and unique", Refusal(ship));
ship = Fixture();
ship.Hull.Assemblies.Add(new AssemblyData { Id = "A", Position = new int2(2, 0), Shape = new Shape(), Min = -10f, Max = 10f, Slew = 10f });
Assert.Contains("assembly IDs must be present and unique", Refusal(ship));
}
[Fact]
public void ARegionHasCellsAndLiesInsideTheHull()
{
var ship = Fixture();
Only(ship).Shape = new Shape(2, 1);
Assert.Contains("assembly A has no cells", Refusal(ship));
ship = Fixture();
Only(ship).Position = new int2(2, 0);
Assert.Contains("assembly A lies outside the hull schematic", Refusal(ship));
// A hull cell the schematic leaves empty is outside it too.
ship = Fixture();
ship.Hull.Shape.Cells[1, 0] = false;
ship.Hull.Hardpoints.RemoveAll(hardpoint => hardpoint.Transform == "t0");
ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "t0");
Assert.Contains("assembly A lies outside the hull schematic", Refusal(ship));
}
[Fact]
public void RegionsDoNotOverlap()
{
var ship = Fixture();
ship.Hull.Assemblies.Add(new AssemblyData { Id = "B", Position = new int2(1, 0), Shape = new Shape(), Min = -10f, Max = 10f, Slew = 10f });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "B", Role = "assembly-root", ModelNodeId = "B-root", Joint = "root" });
Assert.Contains("assembly B overlaps assembly A", Refusal(ship));
}
[Fact]
public void NoHardpointStraddlesARegionEdge()
{
var ship = Fixture();
ship.Hull.Hardpoints.RemoveAll(hardpoint => hardpoint.Transform == "t0");
ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "t0");
var across = ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "t1");
across.Position = new int2(1, 0);
across.Shape = new Shape(2, 1);
across.Shape.Cells[0, 0] = across.Shape.Cells[1, 0] = true;
Assert.Contains("hardpoint t1 straddles the edge of an assembly", Refusal(ship));
// Wholly outside, and wholly inside, are both fine.
across.Position = new int2(2, 0);
across.Shape = new Shape();
ship.Validate();
}
[Fact]
public void PivotMustBeFinite()
{
foreach (var bad in new[] { float.NaN, float.PositiveInfinity })
{
var ship = Fixture();
Only(ship).Pivot = new float2(bad, 0f);
Assert.Contains("pivot must be finite", Refusal(ship));
ship = Fixture();
Only(ship).Pivot = new float2(0f, bad);
Assert.Contains("pivot must be finite", Refusal(ship));
}
}
[Fact]
public void YawLimitsBracketTheAuthoredLayoutAndSpanAtMostATurn()
{
foreach (var (min, max, reason) in new[]
{
(10f, 60f, "Min <= 0 <= Max"), (-60f, -10f, "Min <= 0 <= Max"), (float.NaN, 60f, "Min <= 0 <= Max"), (-60f, float.NaN, "Min <= 0 <= Max"),
(0f, 0f, "yaw span must be above 0"), (-181f, 180f, "at most 360"),
})
{
var ship = Fixture();
(Only(ship).Min, Only(ship).Max) = (min, max);
Assert.Contains(reason, Refusal(ship));
}
var turn = Fixture();
(Only(turn).Min, Only(turn).Max) = (-180f, 180f);
turn.Visual.Joints.Single(joint => joint.Id == "root").Min[0] = -180f;
turn.Visual.Joints.Single(joint => joint.Id == "root").Max[0] = 180f;
turn.Validate();
(Only(turn).Min, Only(turn).Max) = (0f, 60f);
turn.Validate();
}
[Fact]
public void SlewIsFiniteAndAboveZero()
{
foreach (var bad in new[] { 0f, -5f, float.NaN, float.PositiveInfinity })
{
var ship = Fixture();
Only(ship).Slew = bad;
Assert.Contains("slew must be finite and above 0", Refusal(ship));
}
}
[Fact]
public void EachAssemblyHasExactlyOneRootAnchorOfItsIdNamingAJoint()
{
var ship = Fixture();
ship.Visual.Anchors.RemoveAll(anchor => anchor.Role == "assembly-root");
Assert.Contains("assembly A needs an assembly-root anchor of that id", Refusal(ship));
ship = Fixture();
ship.Visual.Anchors.Single(anchor => anchor.Role == "assembly-root").Joint = null;
Assert.Contains("assembly-root anchor A must name a joint", Refusal(ship));
ship = Fixture();
ship.Visual.Anchors.Single(anchor => anchor.Role == "assembly-root").Joint = "ghost";
Assert.Contains("names an unknown joint", Refusal(ship));
ship = Fixture();
ship.Visual.Anchors.Add(new ShipAnchor { Id = "Z", Role = "assembly-root", ModelNodeId = "Z-root", Joint = "gj" });
Assert.Contains("assembly-root anchor Z must be the root of an assembly of that id", Refusal(ship));
}
[Fact]
public void TheRootJointMustReachTheAssembliesArc()
{
var ship = Fixture();
ship.Visual.Joints.Single(joint => joint.Id == "root").Min[0] = -60f;
ship.Visual.Joints.Single(joint => joint.Id == "root").Max[0] = 59f;
Assert.Contains("joint root chain reaches 119 degrees of yaw, short of the 120 degree arc of assembly A", Refusal(ship));
ship.Visual.Joints.Single(joint => joint.Id == "root").Max[0] = 60f;
ship.Validate();
}
[Fact]
public void AMembersChainMayPassItsOwnRootJointAndNoOtherDrivenJoint()
{
// The fixture itself: g0's chain is root, gj, and root is its own assembly's.
Fixture().Validate();
// Between the root and the gun sits a joint the member thruster drives: that one is another actuator's.
var ship = Fixture();
ship.Visual.Joints.Add(Joint("mid", "root", -45f, 45f));
ship.Visual.Joints.Single(joint => joint.Id == "gj").Parent = "mid";
ship.Visual.Anchors.Single(anchor => anchor.Id == "t0").Joint = "mid";
Assert.Contains("joint gj reaches through joint mid, which another actuator drives", Refusal(ship));
}
[Fact]
public void ANonMemberMayNotRideUnderAnAssembliesRootJoint()
{
var ship = Fixture();
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "t1").FiringArc = 90;
ship.Visual.Joints.Add(Joint("k", "root", -45f, 45f));
ship.Visual.Anchors.Single(anchor => anchor.Id == "t1").Joint = "k";
Assert.Contains("joint k reaches through joint root, which another actuator drives", Refusal(ship));
}
[Fact]
public void ARootJointOwnChainMayNotPassAnotherDrivenJoint()
{
var ship = Fixture();
ship.Visual.Joints.Single(joint => joint.Id == "root").Parent = "base";
ship.Visual.Joints.Add(Joint("base", null, -90f, 90f));
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "t1").FiringArc = 90;
ship.Visual.Anchors.Single(anchor => anchor.Id == "t1").Joint = "base";
Assert.Contains("reaches through joint base, which another actuator drives", Refusal(ship));
}
[Fact]
public void AJointHasOneDriverTheRootJointIncluded()
{
var ship = Fixture();
ship.Visual.Anchors.Single(anchor => anchor.Id == "g0").Joint = "root";
Assert.Contains("joint root carries more than one actuator (g0 and A)", Refusal(ship));
}
[Fact]
public void AssembliesRoundTripThroughTheShipFile()
{
using var directory = new TempDirectory();
var path = Path.Combine(directory.Path, "assembly.cc");
var ship = Fixture();
ship.Validate();
using (var cache = ShipAuthoringStore.Open(path, writable: true))
{
ShipAuthoringStore.Write(cache, ship.Hull, ship.Visual);
cache.FlushAsync().GetAwaiter().GetResult();
}
var (hull, visual, _) = ShipAuthoringStore.Read(path);
var read = Assert.Single(hull.Assemblies);
Assert.Equal(("A", new int2(0, 0), 2, new float2(1f, .5f), -60f, 60f, 30f),
(read.Id, read.Position, read.Shape.Width, read.Pivot, read.Min, read.Max, read.Slew));
ShipAuthoringStore.Validate(hull, visual);
}
[Fact]
public void ALikeHullCopiesNoAssemblies()
{
var reference = Fixture().Hull;
var hull = ShipAuthoringStore.HullLike(reference, "Gale", "mod.gale");
Assert.Empty(hull.Assemblies);
Assert.Single(reference.Assemblies);
}
}

View file

@ -34,6 +34,21 @@ public sealed class ShipSchemaPinTests
Assert.Equal(taken.Length, taken.Distinct().Count());
}
// HullData.Assemblies and AssemblyData's members are wire contract: a file written with them must decode on every later build.
[Fact]
public void AssembliesAreHullKey34AndAssemblyDataKeysZeroToSeven()
{
Assert.Equal(34, KeyOf(typeof(HullData), nameof(HullData.Assemblies)));
var keys = new[]
{
nameof(AssemblyData.Id), nameof(AssemblyData.Position), nameof(AssemblyData.Shape), nameof(AssemblyData.Pivot),
nameof(AssemblyData.Min), nameof(AssemblyData.Max), nameof(AssemblyData.Slew), nameof(AssemblyData.ElementId)
};
Assert.Equal(Enumerable.Range(0, keys.Length), keys.Select(member => KeyOf(typeof(AssemblyData), member)));
Assert.Equal(keys.Length, typeof(AssemblyData).GetMembers(BindingFlags.Public | BindingFlags.Instance)
.Count(member => member.GetCustomAttribute<KeyAttribute>() != null));
}
// New Ship refuses a bad ship ID before it touches anything, with ship_cc.valid_ship_id; these two constants are that
// rule's data, so the C# rule that create and Validate share must agree with them on every character and every stem.
[Fact]